Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(voice-input): 统一润色上下文预算并保留光标格式 (#3977)

Dash64a0136556fa
diff --git a/apps/desktop/src/main/voice-input/index.ts b/apps/desktop/src/main/voice-input/index.ts
index 319cb5816e..7a29e7a111 100644
--- a/apps/desktop/src/main/voice-input/index.ts
+++ b/apps/desktop/src/main/voice-input/index.ts
@@ -6,6 +6,9 @@ import {
DictationRefiner,
VoiceInputController,
VoiceTimelineLogger,
+ takeRefinementContextHead,
+ takeRefinementContextTail,
+ truncateRefinementReply,
getDictationDictionaryAdviceSkipReason,
type DictationDictionaryAdviceInput,
type DictationDictionaryAdviceResult,
@@ -596,9 +599,9 @@ function normalizeRefinementContext(
dictionaryAliasHints: normalizeDictionaryAliasHints(context?.dictionaryAliasHints),
voiceInputHistory: normalizeMultilineText(context?.voiceInputHistory ?? ''),
selectionBefore: takeTail(context?.selectionBefore ?? '', MAX_REFINEMENT_SIDE_CONTEXT_CHARS),
- selectedText: truncateText(context?.selectedText ?? '', MAX_REFINEMENT_SIDE_CONTEXT_CHARS),
+ selectedText: takeHead(context?.selectedText ?? '', MAX_REFINEMENT_SIDE_CONTEXT_CHARS),
selectionAfter: takeHead(context?.selectionAfter ?? '', MAX_REFINEMENT_SIDE_CONTEXT_CHARS),
- replyToMessage: truncateText(
+ replyToMessage: truncateRefinementReply(
context?.replyToMessage ?? '',
MAX_REFINEMENT_REPLY_TO_MESSAGE_CHARS,
),
@@ -641,7 +644,7 @@ function beginOverlayContextInjection(
// synchronous fields, so prompt sizing stays predictable regardless
// of whether overlay capture won the race.
targetContext.selectionBefore = takeTail(overlayContext.selectionBefore, MAX_REFINEMENT_SIDE_CONTEXT_CHARS);
- targetContext.selectedText = truncateText(overlayContext.selectedText, MAX_REFINEMENT_SIDE_CONTEXT_CHARS);
+ targetContext.selectedText = takeHead(overlayContext.selectedText, MAX_REFINEMENT_SIDE_CONTEXT_CHARS);
targetContext.selectionAfter = takeHead(overlayContext.selectionAfter, MAX_REFINEMENT_SIDE_CONTEXT_CHARS);
})
.catch((error: unknown) => {
@@ -733,13 +736,11 @@ function normalizeMultilineText(text: string): string {
}
function takeHead(text: string, maxChars: number): string {
- return truncateText(text, maxChars);
+ return takeRefinementContextHead(text, maxChars);
}
function takeTail(text: string, maxChars: number): string {
- const normalized = text.replace(/\s+/g, ' ').trim();
- if (normalized.length <= maxChars) return normalized;
- return normalized.slice(-maxChars).trim();
+ return takeRefinementContextTail(text, maxChars);
}
function readActiveVoiceInputModelSelection(reason: string): ReturnType<typeof getVoiceInputModelSelection> {
diff --git a/apps/desktop/src/renderer/voice-input/__tests__/refinementContext.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/refinementContext.test.ts
index 07df52ae66..1179b0a7f7 100644
--- a/apps/desktop/src/renderer/voice-input/__tests__/refinementContext.test.ts
+++ b/apps/desktop/src/renderer/voice-input/__tests__/refinementContext.test.ts
@@ -1,11 +1,23 @@
import { describe, expect, it } from 'vitest';
+import { Schema } from '@tiptap/pm/model';
+import { DictationRefiner } from '@cindy/voice-input-core';
import {
buildReplyToMessageFromChatMessages,
buildVoiceInputHistoryContext,
+ buildEditorSelectionContext,
} from '../refinementContext';
describe('buildReplyToMessageFromChatMessages', () => {
+ it('retains the opening subject and the closing question from a long reply', () => {
+ const reply = buildReplyToMessageFromChatMessages([
+ { role: 'assistant', content: `结论:可以修。\n${'详细解释'.repeat(200)}\n选择方案 A 还是 B?` },
+ ]);
+ expect(reply).toHaveLength(500);
+ expect(reply).toContain('结论:可以修。');
+ expect(reply).toContain('选择方案 A 还是 B?');
+ });
+
it('uses the latest completed assistant reply as the message being replied to', () => {
const replyToMessage = buildReplyToMessageFromChatMessages([
{ role: 'assistant', content: '旧回复。' },
@@ -20,6 +32,38 @@ describe('buildReplyToMessageFromChatMessages', () => {
});
});
+describe('editor cursor context delivered to refinement', () => {
+ const schema = new Schema({ nodes: {
+ doc: { content: 'paragraph+' }, paragraph: { content: 'inline*' }, text: { group: 'inline' },
+ hard_break: { inline: true, group: 'inline' },
+ } });
+ const doc = schema.node('doc', null, [
+ schema.node('paragraph', null, [schema.text('前文'), schema.node('hard_break'), schema.text(' 光标选中后文')]),
+ schema.node('paragraph', null, [schema.text(' 下一段')]),
+ ]);
+
+ it('reads both sides of a real ProseMirror selection and preserves structure through the refiner', async () => {
+ const context = buildEditorSelectionContext(doc, { from: 8, to: 10 });
+ expect(context).toEqual({ selectionBefore: '前文\n 光标', selectedText: '选中', selectionAfter: '后文\n 下一段' });
+ let sent: unknown;
+ const refiner = new DictationRefiner({
+ model: 'test', contextProvider: () => context,
+ client: { async requestJson<T>(input: { user: unknown }) { sent = input.user; return { text: '新的文字。' } as T; } },
+ });
+ await refiner.refine({ text: '新的文字', runId: 'test', segmentIds: ['segment'] });
+ expect(sent).toMatchObject({ context });
+ expect(refiner.buildWarmupRequest().user).toMatchObject({ context });
+ });
+
+ it('handles a collapsed cursor, an empty editor and long text on both sides', () => {
+ expect(buildEditorSelectionContext(doc, { from: 8, to: 8 })).toMatchObject({ selectedText: '', selectionAfter: '选中后文\n 下一段' });
+ const empty = schema.node('doc', null, [schema.node('paragraph')]);
+ expect(buildEditorSelectionContext(empty, { from: 1, to: 1 })).toEqual({ selectionBefore: '', selectedText: '', selectionAfter: '' });
+ const long = schema.node('doc', null, [schema.node('paragraph', null, [schema.text('前'.repeat(1500) + '后'.repeat(1500))])]);
+ expect(buildEditorSelectionContext(long, { from: 1501, to: 1501 })).toEqual({ selectionBefore: '前'.repeat(1200), selectedText: '', selectionAfter: '后'.repeat(1200) });
+ });
+});
+
describe('buildVoiceInputHistoryContext', () => {
it('builds one bounded voice-input history block oldest to newest', () => {
const context = buildVoiceInputHistoryContext([
diff --git a/apps/desktop/src/renderer/voice-input/refinementContext.ts b/apps/desktop/src/renderer/voice-input/refinementContext.ts
index ab7cf7b171..6558a1804f 100644
--- a/apps/desktop/src/renderer/voice-input/refinementContext.ts
+++ b/apps/desktop/src/renderer/voice-input/refinementContext.ts
@@ -1,20 +1,22 @@
import type { DictationRefinementContext } from '@cindy/voice-input-core';
+import type { Node as PMNode } from '@tiptap/pm/model';
import {
- MAX_REFINEMENT_HISTORY_ITEM_CHARS,
+ formatVoiceInputHistoryContext,
+ takeRefinementContextHead,
+ takeRefinementContextTail,
+ truncateRefinementReply,
+ MAX_REFINEMENT_REPLY_TO_MESSAGE_CHARS,
+} from '@cindy/voice-input-core';
+export {
+ MAX_REFINEMENT_SIDE_CONTEXT_CHARS,
+ MAX_REFINEMENT_REPLY_TO_MESSAGE_CHARS,
+ estimateVoiceInputHistoryContextChars,
VOICE_INPUT_HISTORY_COMPACT_CHARS,
VOICE_INPUT_HISTORY_COMPACT_KEEP_ENTRIES,
VOICE_INPUT_HISTORY_COMPACT_TARGET_CHARS,
- VOICE_INPUT_HISTORY_HEADER,
-} from '../../shared/voiceInputData';
+} from '@cindy/voice-input-core';
-export const MAX_REFINEMENT_SIDE_CONTEXT_CHARS = 1_200;
-export const MAX_REFINEMENT_REPLY_TO_MESSAGE_CHARS = 500;
export const VOICE_INPUT_REFINEMENT_CACHE_SCOPE = 'voice-input-refinement';
-export {
- VOICE_INPUT_HISTORY_COMPACT_CHARS,
- VOICE_INPUT_HISTORY_COMPACT_KEEP_ENTRIES,
- VOICE_INPUT_HISTORY_COMPACT_TARGET_CHARS,
-};
export type VoiceInputChatMessage = {
role: string;
@@ -22,10 +24,16 @@ export type VoiceInputChatMessage = {
isStreaming?: boolean;
};
+export function buildEditorSelectionContext(doc: PMNode, range: { from: number; to: number }) {
+ return {
+ selectionBefore: takeRefinementContextTail(doc.textBetween(0, range.from, '\n', '\n')),
+ selectedText: takeRefinementContextHead(doc.textBetween(range.from, range.to, '\n', '\n')),
+ selectionAfter: takeRefinementContextHead(doc.textBetween(range.to, doc.content.size, '\n', '\n')),
+ };
+}
+
export function truncateContextText(text: string, maxChars: number): string {
- const normalized = text.replace(/\s+/g, ' ').trim();
- if (normalized.length <= maxChars) return normalized;
- return normalized.slice(0, maxChars).trim();
+ return takeRefinementContextHead(text, maxChars);
}
export function buildReplyToMessageFromChatMessages(messages: VoiceInputChatMessage[] | undefined): string | undefined {
@@ -33,7 +41,7 @@ export function buildReplyToMessageFromChatMessages(messages: VoiceInputChatMess
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
if (!message || message.isStreaming || message.role !== 'assistant') continue;
- return truncateContextText(message.content, MAX_REFINEMENT_REPLY_TO_MESSAGE_CHARS) || undefined;
+ return truncateRefinementReply(message.content, MAX_REFINEMENT_REPLY_TO_MESSAGE_CHARS) || undefined;
}
return undefined;
}
@@ -48,31 +56,8 @@ export function buildReplyToMessageFromChatMessages(messages: VoiceInputChatMess
export function buildVoiceInputHistoryContext(
newestFirst: ReadonlyArray<{ text: string }>,
): Pick<DictationRefinementContext, 'voiceInputHistory'> {
- const oldestFirst = normalizeVoiceInputHistoryEntries(newestFirst);
- if (oldestFirst.length === 0) return {};
- return {
- voiceInputHistory: [
- VOICE_INPUT_HISTORY_HEADER,
- ...oldestFirst.map((entry) => `- ${entry}`),
- ].join('\n'),
- };
-}
-
-export function estimateVoiceInputHistoryContextChars(newestFirst: ReadonlyArray<{ text: string }>): number {
- const oldestFirst = normalizeVoiceInputHistoryEntries(newestFirst);
- if (oldestFirst.length === 0) return 0;
- return oldestFirst.reduce(
- (total, entry) => total + 3 + entry.length,
- VOICE_INPUT_HISTORY_HEADER.length,
- );
-}
-
-function normalizeVoiceInputHistoryEntries(newestFirst: ReadonlyArray<{ text: string }>): string[] {
- return newestFirst
- .slice()
- .reverse()
- .map((entry) => truncateContextText(entry.text, MAX_REFINEMENT_HISTORY_ITEM_CHARS))
- .filter(Boolean);
+ const voiceInputHistory = formatVoiceInputHistoryContext(newestFirst);
+ return voiceInputHistory ? { voiceInputHistory } : {};
}
export function takeContextHead(text: string, maxChars: number): string {
@@ -80,7 +65,5 @@ export function takeContextHead(text: string, maxChars: number): string {
}
export function takeContextTail(text: string, maxChars: number): string {
- const normalized = text.replace(/\s+/g, ' ').trim();
- if (normalized.length <= maxChars) return normalized;
- return normalized.slice(-maxChars).trim();
+ return takeRefinementContextTail(text, maxChars);
}
diff --git a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
index 4a7be6e209..564d714474 100644
--- a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
+++ b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
@@ -34,10 +34,7 @@ import {
import {
VOICE_INPUT_REFINEMENT_CACHE_SCOPE,
buildReplyToMessageFromChatMessages,
- MAX_REFINEMENT_SIDE_CONTEXT_CHARS,
- takeContextHead,
- takeContextTail,
- truncateContextText,
+ buildEditorSelectionContext,
type VoiceInputChatMessage,
} from './refinementContext';
import {
@@ -796,9 +793,7 @@ export function useVoiceInput(
...baseContext,
// DictationRefiner.getContext re-imposes cache-friendly ordering when
// serializing the request body.
- selectionBefore: takeContextTail(doc.textBetween(0, range.from, '\n', '\n'), MAX_REFINEMENT_SIDE_CONTEXT_CHARS),
- selectedText: truncateContextText(doc.textBetween(range.from, range.to, '\n', '\n'), MAX_REFINEMENT_SIDE_CONTEXT_CHARS),
- selectionAfter: takeContextHead(doc.textBetween(range.to, doc.content.size, '\n', '\n'), MAX_REFINEMENT_SIDE_CONTEXT_CHARS),
+ ...buildEditorSelectionContext(doc, range),
replyToMessage,
};
}, [
diff --git a/apps/desktop/src/shared/voiceInputData.ts b/apps/desktop/src/shared/voiceInputData.ts
index 577f5c24fd..dbdd67db28 100644
--- a/apps/desktop/src/shared/voiceInputData.ts
+++ b/apps/desktop/src/shared/voiceInputData.ts
@@ -6,6 +6,15 @@ import type {
DictationRefinementContext,
} from '@cindy/voice-input-core';
import type { CindyRegion } from '@cindy/maker-shared/brand-identity';
+export {
+ compactVoiceInputHistoryIfNeeded,
+ estimateVoiceInputHistoryContextChars,
+ MAX_REFINEMENT_HISTORY_ITEM_CHARS,
+ VOICE_INPUT_HISTORY_COMPACT_CHARS,
+ VOICE_INPUT_HISTORY_COMPACT_TARGET_CHARS,
+ VOICE_INPUT_HISTORY_COMPACT_KEEP_ENTRIES,
+ VOICE_INPUT_HISTORY_HEADER,
+} from '@cindy/voice-input-core';
import { CURRENT_CINDY_REGION } from './brandRegion';
import { SUPPORTED_LOCALES, type SupportedLocale } from './locale';
@@ -125,15 +134,6 @@ export const MAX_VOICE_INPUT_DICTIONARY_ENTRY_CHARS = 120;
export const MAX_VOICE_INPUT_DICTIONARY_ALIASES = 8;
export const MAX_VOICE_INPUT_DICTIONARY_CSV_BYTES = 5 * 1024 * 1024;
export const MAX_VISIBLE_VOICE_INPUT_HISTORY_ENTRIES = 5;
-// 历史块只作术语/口语风格参考,术语纠错主要由用户字典 + alias hints 承载。
-// 线上日志实测(2026-06-21 ~ 07-04,1050 次听写):历史从 33k 涨到 96k chars
-// 期间采纳率 / no_change 率 / 术语修正率均无变化,而它占 refine prompt 约八成
-// token(单次 42k+)。预算据此收紧到 ~12k chars(≈ 最近三四十条)。
-export const VOICE_INPUT_HISTORY_COMPACT_CHARS = 12_000;
-export const VOICE_INPUT_HISTORY_COMPACT_TARGET_CHARS = 8_000;
-export const VOICE_INPUT_HISTORY_COMPACT_KEEP_ENTRIES = 40;
-export const MAX_REFINEMENT_HISTORY_ITEM_CHARS = 360;
-export const VOICE_INPUT_HISTORY_HEADER = '语音输入历史(旧到新,仅作术语、别名和用词风格参考):';
export const VOICE_INPUT_MODIFIER_SHORTCUT_CODES: readonly VoiceInputModifierShortcutCode[] = [
'MetaLeft',
'MetaRight',
@@ -886,35 +886,6 @@ export function normalizeVoiceInputHistory(raw: unknown): VoiceInputHistoryEntry
.sort((a, b) => b.createdAt - a.createdAt);
}
-export function compactVoiceInputHistoryIfNeeded(entries: VoiceInputHistoryEntry[]): VoiceInputHistoryEntry[] {
- if (estimateVoiceInputHistoryContextChars(entries) <= VOICE_INPUT_HISTORY_COMPACT_CHARS) {
- return entries;
- }
- // This is intentionally a rare reset, not a sliding cap. The history prefix
- // grows append-only for prompt-cache reuse until it crosses the context
- // budget, then we rewrite it to a compact recent base with enough headroom
- // to accumulate a long new prefix. The lower target avoids re-compacting on
- // the next few dictations, which would repeatedly invalidate the cache.
- const recent = entries.slice(0, VOICE_INPUT_HISTORY_COMPACT_KEEP_ENTRIES);
- let keepCount = recent.length;
- while (
- keepCount > 1 &&
- estimateVoiceInputHistoryContextChars(recent.slice(0, keepCount)) > VOICE_INPUT_HISTORY_COMPACT_TARGET_CHARS
- ) {
- keepCount -= 1;
- }
- return recent.slice(0, keepCount);
-}
-
-export function estimateVoiceInputHistoryContextChars(newestFirst: ReadonlyArray<{ text: string }>): number {
- const oldestFirst = normalizeVoiceInputHistoryTextEntries(newestFirst);
- if (oldestFirst.length === 0) return 0;
- return oldestFirst.reduce(
- (total, entry) => total + 3 + entry.length,
- VOICE_INPUT_HISTORY_HEADER.length,
- );
-}
-
export function createVoiceInputHistoryEntry(text: string, timestamp = Date.now()): VoiceInputHistoryEntry | null {
const normalizedText = text.trim();
if (!normalizedText) return null;
@@ -1267,20 +1238,6 @@ function normalizeVoiceInputHistoryEntry(raw: unknown): VoiceInputHistoryEntry |
};
}
-function normalizeVoiceInputHistoryTextEntries(newestFirst: ReadonlyArray<{ text: string }>): string[] {
- return newestFirst
- .slice()
- .reverse()
- .map((entry) => truncateContextText(entry.text, MAX_REFINEMENT_HISTORY_ITEM_CHARS))
- .filter(Boolean);
-}
-
-function truncateContextText(text: string, maxChars: number): string {
- const normalized = text.replace(/\s+/g, ' ').trim();
- if (normalized.length <= maxChars) return normalized;
- return normalized.slice(0, maxChars).trim();
-}
-
function createId(prefix: string, timestamp = Date.now(), seed = ''): string {
if (typeof globalThis.crypto?.randomUUID === 'function') {
return globalThis.crypto.randomUUID();
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 7bbe80b656..8f33a3d720 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -1,4 +1,5 @@
import { isInFlightDeviceLinkError } from '@cindy/device-link';
+import { takeRefinementContextTail, truncateRefinementReply } from '@cindy/voice-input-core';
import {
ArrowDown,
Camera,
@@ -4723,9 +4724,10 @@ export default function SessionScreen() {
// 词典快照拉取不进 await:它只影响润色提示的丰富度,拉不到(桌面离线、老版本
// 被控端)就用上次缓存,绝不为它推迟开麦。本次拉到的内容供下一次润色使用。
void refreshMobileVoiceDictionary(deviceId, () => maker.getVoiceDictionary());
+ const prewarmedVoicePromise = takePrewarmedMobileVoiceAsr(deviceId) ?? Promise.resolve(null);
const [prewarmedVoice, localVoiceInputHistory] = await Promise.all([
- takePrewarmedMobileVoiceAsr(deviceId) ?? Promise.resolve(null),
- getMobileVoiceInputHistoryForHost(deviceId),
+ prewarmedVoicePromise,
+ prewarmedVoicePromise.then((voice) => getMobileVoiceInputHistoryForHost(deviceId, voice?.credential.settings?.voiceInputHistory)),
hydrateMobileVoiceDictionary(deviceId),
]);
claimedPrewarm = prewarmedVoice;
@@ -10730,7 +10732,7 @@ function buildMobileVoiceSessionRefinementContext(
draftText: string,
items: readonly MobileMessageRenderItem[],
) {
- const selectionBefore = truncateMobileVoiceContext(draftText, 1200);
+ const selectionBefore = takeRefinementContextTail(draftText);
const replyToMessage = findLastAssistantMessageText(items);
return {
selectionBefore: selectionBefore || undefined,
@@ -10743,7 +10745,7 @@ function findLastAssistantMessageText(items: readonly MobileMessageRenderItem[])
const item = items[index];
if (!item) continue;
if (item.type === 'message' && item.message.kind === 'assistant' && !item.message.isStreaming) {
- return truncateMobileVoiceContext(item.message.body, 500);
+ return truncateRefinementReply(item.message.body);
}
if (item.type === 'work_group') {
const nested = findLastAssistantMessageText(item.children);
@@ -10758,12 +10760,6 @@ function findLastAssistantMessageText(items: readonly MobileMessageRenderItem[])
return '';
}
-function truncateMobileVoiceContext(text: string, maxChars: number): string {
- const normalized = text.replace(/\s+/g, ' ').trim();
- if (normalized.length <= maxChars) return normalized;
- return normalized.slice(-maxChars).trim();
-}
-
interface RouteActionButtonProps {
accessibilityHint?: string;
accessibilityLabel: string;
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 9753fb86e8..2cfd56de45 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -1,4 +1,5 @@
import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';
+import { takeRefinementContextTail } from '@cindy/voice-input-core';
import { useLocalSearchParams, useRouter } from 'expo-router';
import Constants from 'expo-constants';
import { MOBILE_VISUAL_MOCK_ENABLED } from '@/config/env';
@@ -3127,9 +3128,10 @@ export default function NewRemoteSessionScreen() {
// 词典快照拉取不进 await:它只影响润色提示的丰富度,拉不到(桌面离线、老版本
// 被控端)就用上次缓存,绝不为它推迟开麦。
void refreshMobileVoiceDictionary(selectedDeviceId, () => maker.getVoiceDictionary());
+ const prewarmedVoicePromise = takePrewarmedMobileVoiceAsr(selectedDeviceId) ?? Promise.resolve(null);
const [prewarmedVoice, localVoiceInputHistory] = await Promise.all([
- takePrewarmedMobileVoiceAsr(selectedDeviceId) ?? Promise.resolve(null),
- getMobileVoiceInputHistoryForHost(selectedDeviceId),
+ prewarmedVoicePromise,
+ prewarmedVoicePromise.then((voice) => getMobileVoiceInputHistoryForHost(selectedDeviceId, voice?.credential.settings?.voiceInputHistory)),
hydrateMobileVoiceDictionary(selectedDeviceId),
]);
claimedPrewarm = prewarmedVoice;
@@ -3161,7 +3163,7 @@ export default function NewRemoteSessionScreen() {
}
return;
}
- const selectionBefore = currentDraft.trim() ? currentDraft.slice(-1200) : undefined;
+ const selectionBefore = takeRefinementContextTail(currentDraft) || undefined;
const controller = createMobileVoiceControllerSession({
credential,
...(prewarmedVoice ? { asr: prewarmedVoice.asr } : {}),
diff --git a/apps/mobile/src/__tests__/mobileVoiceHistoryStore.test.ts b/apps/mobile/src/__tests__/mobileVoiceHistoryStore.test.ts
index 734f9c60bb..f0beb15869 100644
--- a/apps/mobile/src/__tests__/mobileVoiceHistoryStore.test.ts
+++ b/apps/mobile/src/__tests__/mobileVoiceHistoryStore.test.ts
@@ -1,4 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { formatVoiceInputHistoryContext } from '@cindy/voice-input-core';
+import { setSecureItem } from '@/auth/secureStorage';
const secureItems = vi.hoisted(() => new Map<string, string>());
@@ -73,24 +75,36 @@ describe('mobileVoiceHistoryStore', () => {
expect(firstId).not.toBe(rawId);
});
- it('normalizes long entries and caps the retained history', async () => {
+ it('compacts at the shared character budget and persists a stable prefix after compaction', async () => {
const {
- MAX_MOBILE_VOICE_HISTORY_ENTRIES,
MAX_MOBILE_VOICE_HISTORY_ITEM_CHARS,
getMobileVoiceInputHistoryForHost,
recordMobileVoiceInputHistoryForHost,
} = await import('@/session/mobileVoiceHistoryStore');
- for (let index = 0; index < MAX_MOBILE_VOICE_HISTORY_ENTRIES + 5; index += 1) {
- await recordMobileVoiceInputHistoryForHost('host-a', `entry ${index}`);
+ for (let index = 0; index < 32; index += 1) {
+ await recordMobileVoiceInputHistoryForHost('host-a', `entry ${index}`.padEnd(360, 'x'));
}
await recordMobileVoiceInputHistoryForHost('host-a', ` ${'x'.repeat(MAX_MOBILE_VOICE_HISTORY_ITEM_CHARS + 20)} `);
const history = await getMobileVoiceInputHistoryForHost('host-a');
- expect(history).toHaveLength(MAX_MOBILE_VOICE_HISTORY_ENTRIES);
+ const before = formatVoiceInputHistoryContext(history.map((text) => ({ text })));
+ expect(before.length).toBeLessThanOrEqual(8000);
+ expect(history.length).toBeLessThanOrEqual(40);
expect(history[0]).toHaveLength(MAX_MOBILE_VOICE_HISTORY_ITEM_CHARS);
- expect(history[1]).toBe(`entry ${MAX_MOBILE_VOICE_HISTORY_ENTRIES + 4}`);
- expect(history).not.toContain('entry 5');
+ expect(history[1]).toBe('entry 31'.padEnd(360, 'x'));
+ expect(history).not.toContain('entry 0'.padEnd(360, 'x'));
+ await recordMobileVoiceInputHistoryForHost('host-a', '下一句');
+ const after = await getMobileVoiceInputHistoryForHost('host-a');
+ expect(formatVoiceInputHistoryContext(after.map((text) => ({ text })))).toBe(`${before}\n- 下一句`);
+ });
+
+ it('retains more than 100 short phrases without shifting the history prefix', async () => {
+ const { recordMobileVoiceInputHistoryForHost, getMobileVoiceInputHistoryForHost } = await import('@/session/mobileVoiceHistoryStore');
+ for (let i = 0; i < 105; i += 1) await recordMobileVoiceInputHistoryForHost('host-a', `entry ${i}`);
+ const history = await getMobileVoiceInputHistoryForHost('host-a');
+ expect(history).toHaveLength(105);
+ expect(history.at(-1)).toBe('entry 0');
});
it('clears all recorded host histories on logout', async () => {
@@ -109,4 +123,96 @@ describe('mobileVoiceHistoryStore', () => {
await expect(getMobileVoiceInputHistoryForHost('host-b')).resolves.toEqual([]);
expect(secureItems.has(__testing.storageIndexKey)).toBe(false);
});
+
+ it('preserves legacy entries and imports a desktop snapshot only once across reloads', async () => {
+ const { __testing, getMobileVoiceInputHistoryForHost, recordMobileVoiceInputHistoryForHost } = await import('@/session/mobileVoiceHistoryStore');
+ const legacy = Array.from({ length: 4 }, (_, i) => ({ id: `local-${i}`, text: `local ${i}`.padEnd(360, 'l'), createdAt: i + 1 }));
+ secureItems.set(__testing.storageKeyForHostDevice('host-a'), JSON.stringify(legacy));
+ const desktop = Array.from({ length: 30 }, (_, i) => `desktop ${i}`.padEnd(360, 'd'));
+ const first = await getMobileVoiceInputHistoryForHost('host-a', desktop);
+ const prefix = formatVoiceInputHistoryContext(first.map((text) => ({ text })));
+ expect(prefix.length).toBeLessThanOrEqual(8000);
+ expect(first.slice(0, 4)).toEqual(legacy.map((entry) => entry.text));
+ const persisted = JSON.parse(secureItems.get(__testing.storageKeyForHostDevice('host-a'))!);
+ expect(Array.isArray(persisted)).toBe(true);
+ expect(persisted[0].id).toBe('local-0');
+ await recordMobileVoiceInputHistoryForHost('host-a', '新手机语音');
+ vi.resetModules();
+ const reloaded = await import('@/session/mobileVoiceHistoryStore');
+ const second = await reloaded.getMobileVoiceInputHistoryForHost('host-a', desktop);
+ expect(formatVoiceInputHistoryContext(second.map((text) => ({ text })))).toBe(`${prefix}\n- 新手机语音`);
+ const changed = await reloaded.getMobileVoiceInputHistoryForHost('host-a', ['新的桌面术语', ...desktop]);
+ expect(changed).toContain('新的桌面术语');
+ await reloaded.clearAllMobileVoiceInputHistories();
+ expect(secureItems.has(__testing.storageKeyForHostDevice('host-a'))).toBe(false);
+ expect(secureItems.has(__testing.snapshotKeyForHostDevice('host-a'))).toBe(false);
+ });
+
+ it('retains imported history when an older bundle reads and appends to the v1 array', async () => {
+ const { __testing, getMobileVoiceInputHistoryForHost } = await import('@/session/mobileVoiceHistoryStore');
+ await getMobileVoiceInputHistoryForHost('host-a', ['desktop phrase']);
+ const key = __testing.storageKeyForHostDevice('host-a');
+ const parsed = JSON.parse(secureItems.get(key)!);
+ // Previous bundles reject any non-array value and overwrite it on recording.
+ const legacyEntries = Array.isArray(parsed) ? parsed : [];
+ expect(legacyEntries.map((entry) => entry.text)).toEqual(['desktop phrase']);
+ secureItems.set(key, JSON.stringify([
+ { id: 'voice-older-bundle', text: 'recorded after rollback', createdAt: 2 },
+ ...legacyEntries,
+ ]));
+ await expect(getMobileVoiceInputHistoryForHost('host-a', ['desktop phrase'])).resolves.toEqual([
+ 'recorded after rollback', 'desktop phrase',
+ ]);
+ });
+
+ it('recovers the development object format into a rollback-readable array on write', async () => {
+ const { __testing, getMobileVoiceInputHistoryForHost, recordMobileVoiceInputHistoryForHost } = await import('@/session/mobileVoiceHistoryStore');
+ const key = __testing.storageKeyForHostDevice('host-a');
+ const desktopSnapshot = JSON.stringify(['desktop phrase']);
+ secureItems.set(key, JSON.stringify({
+ entries: [{ id: 'desktop-0', text: 'desktop phrase', createdAt: 1 }], desktopSnapshot,
+ }));
+ await recordMobileVoiceInputHistoryForHost('host-a', 'new phrase');
+ expect(Array.isArray(JSON.parse(secureItems.get(key)!))).toBe(true);
+ expect(secureItems.get(__testing.snapshotKeyForHostDevice('host-a'))).toBe(desktopSnapshot);
+ await expect(getMobileVoiceInputHistoryForHost('host-a', ['desktop phrase'])).resolves.toEqual(['new phrase', 'desktop phrase']);
+ });
+
+ it('preserves history when the snapshot marker write fails and retries the import safely', async () => {
+ const { __testing, getMobileVoiceInputHistoryForHost } = await import('@/session/mobileVoiceHistoryStore');
+ vi.mocked(setSecureItem)
+ .mockImplementationOnce(async (key, value) => { secureItems.set(key, value); })
+ .mockImplementationOnce(async (key, value) => { secureItems.set(key, value); })
+ .mockRejectedValueOnce(new Error('marker write failed'));
+ await expect(getMobileVoiceInputHistoryForHost('host-a', ['desktop phrase'])).resolves.toEqual(['desktop phrase']);
+ expect(JSON.parse(secureItems.get(__testing.storageKeyForHostDevice('host-a'))!)[0].text).toBe('desktop phrase');
+ expect(secureItems.has(__testing.snapshotKeyForHostDevice('host-a'))).toBe(false);
+ await expect(getMobileVoiceInputHistoryForHost('host-a', ['desktop phrase'])).resolves.toEqual(['desktop phrase']);
+ expect(secureItems.get(__testing.snapshotKeyForHostDevice('host-a'))).toBe(JSON.stringify(['desktop phrase']));
+ });
+
+ it('ignores a stale or corrupt snapshot marker when importing history', async () => {
+ const { __testing, getMobileVoiceInputHistoryForHost, recordMobileVoiceInputHistoryForHost } = await import('@/session/mobileVoiceHistoryStore');
+ await recordMobileVoiceInputHistoryForHost('host-a', 'local phrase');
+ secureItems.set(__testing.snapshotKeyForHostDevice('host-a'), 'corrupt');
+ await expect(getMobileVoiceInputHistoryForHost('host-a', ['desktop phrase'])).resolves.toEqual(['local phrase', 'desktop phrase']);
+ });
+
+ it('keeps newly synced desktop phrases ahead of old ones when the merged history compacts', async () => {
+ const { getMobileVoiceInputHistoryForHost, recordMobileVoiceInputHistoryForHost } = await import('@/session/mobileVoiceHistoryStore');
+ const desktop = Array.from({ length: 29 }, (_, i) => `desktop ${i}`.padEnd(360, 'd'));
+ await getMobileVoiceInputHistoryForHost('host-a', desktop);
+ for (let i = 0; i < 3; i += 1) await recordMobileVoiceInputHistoryForHost('host-a', `local ${i}`.padEnd(360, 'l'));
+ const newest = 'NEW desktop'.padEnd(360, 'n');
+ const history = await getMobileVoiceInputHistoryForHost('host-a', [newest, ...desktop]);
+ expect(history[3]).toBe(newest);
+ expect(history[4]).toBe(desktop[0]);
+ expect(formatVoiceInputHistoryContext(history.map((text) => ({ text }))).length).toBeLessThanOrEqual(8000);
+ });
+
+ it('keeps recording available when persisting the imported snapshot fails', async () => {
+ const { getMobileVoiceInputHistoryForHost } = await import('@/session/mobileVoiceHistoryStore');
+ vi.mocked(setSecureItem).mockRejectedValueOnce(new Error('storage unavailable'));
+ await expect(getMobileVoiceInputHistoryForHost('host-a', ['桌面术语'])).resolves.toEqual(['桌面术语']);
+ });
});
diff --git a/apps/mobile/src/__tests__/mobileVoiceInput.test.ts b/apps/mobile/src/__tests__/mobileVoiceInput.test.ts
index ed43e6dc97..a6a7124281 100644
--- a/apps/mobile/src/__tests__/mobileVoiceInput.test.ts
+++ b/apps/mobile/src/__tests__/mobileVoiceInput.test.ts
@@ -122,7 +122,7 @@ describe('mobileVoiceInput', () => {
},
}), {
uiLanguage: 'zh-CN',
- localVoiceInputHistory: ['手机最新术语', '手机较早术语'],
+ localVoiceInputHistory: ['手机最新术语', '手机较早术语', '桌面较新的术语', '桌面较早的术语'],
refinementContext: {
selectionBefore: '当前输入框前文',
replyToMessage: '最近的助手回复',
@@ -151,6 +151,33 @@ describe('mobileVoiceInput', () => {
expect(history.indexOf('- 手机较早术语')).toBeLessThan(history.indexOf('- 手机最新术语'));
});
+ it('does not reintroduce desktop entries already removed from the persisted combined history', () => {
+ const context = buildMobileVoiceRefinementContext(storedCredential({
+ settings: {
+ language: 'zh-CN', refinementEnabled: true, playInteractionSound: true,
+ voiceInputHistory: Array.from({ length: 50 }, (_, i) => `desktop ${i}`.padEnd(360, 'x')),
+ },
+ }), {
+ localVoiceInputHistory: Array.from({ length: 20 }, (_, i) => `mobile ${i}`.padEnd(360, 'y')),
+ });
+ expect(context.voiceInputHistory!.length).toBeLessThanOrEqual(8_000);
+ expect(context.voiceInputHistory).toContain('mobile 0');
+ expect(context.voiceInputHistory).not.toContain('desktop 0');
+ expect(context.voiceInputHistory).not.toContain('desktop 49');
+ });
+
+ it('bounds the desktop history fallback when a caller has no persisted mobile history', () => {
+ const context = buildMobileVoiceRefinementContext(storedCredential({
+ settings: {
+ language: 'zh-CN', refinementEnabled: true, playInteractionSound: true,
+ voiceInputHistory: Array.from({ length: 50 }, (_, i) => `desktop ${i}`.padEnd(360, 'x')),
+ },
+ }));
+ expect(context.voiceInputHistory!.length).toBeLessThanOrEqual(8000);
+ expect(context.voiceInputHistory).toContain('desktop 0');
+ expect(context.voiceInputHistory).not.toContain('desktop 49');
+ });
+
it('uses the current UI language for refinement when ASR language is auto', () => {
const context = buildMobileVoiceRefinementContext(storedCredential({
settings: {
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index 2db83801fe..4963fb8621 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -1809,7 +1809,8 @@ describe('new session composer surface', () => {
expect(newSource).toContain('refreshAccessToken: () => auth.refreshAccessToken(),');
expect(newSource).toContain('apiFetch: auth.apiFetch,');
expect(newSource).toContain('const [prewarmedVoice, localVoiceInputHistory] = await Promise.all([');
- expect(newSource).toContain('takePrewarmedMobileVoiceAsr(selectedDeviceId) ?? Promise.resolve(null),');
+ expect(newSource).toContain('const prewarmedVoicePromise = takePrewarmedMobileVoiceAsr(selectedDeviceId) ?? Promise.resolve(null);');
+ expect(newSource).toContain('prewarmedVoicePromise.then((voice) => getMobileVoiceInputHistoryForHost(selectedDeviceId, voice?.credential.settings?.voiceInputHistory))');
expect(newSource).not.toContain('MobileVoiceServiceMode');
expect(newSource).not.toContain('LiteLlm');
expect(newSource).toContain('?? createMobileCindyVoiceCredential(selectedDeviceId);');
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index d958d5184c..0ad14919a8 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -636,7 +636,8 @@ describe('mobile session composer desktop-first surface', () => {
// falls back to building the managed credential itself otherwise. 手机语音
// 只保留 Cindy 官方托管路径:BYOK/穿透已删除。
expect(source).toContain('const [prewarmedVoice, localVoiceInputHistory] = await Promise.all([');
- expect(source).toContain('takePrewarmedMobileVoiceAsr(deviceId) ?? Promise.resolve(null),');
+ expect(source).toContain('const prewarmedVoicePromise = takePrewarmedMobileVoiceAsr(deviceId) ?? Promise.resolve(null);');
+ expect(source).toContain('prewarmedVoicePromise.then((voice) => getMobileVoiceInputHistoryForHost(deviceId, voice?.credential.settings?.voiceInputHistory))');
expect(source).not.toContain('MobileVoiceServiceMode');
expect(source).not.toContain('LiteLlm');
expect(source).toContain('?? createMobileCindyVoiceCredential(deviceId);');
@@ -649,7 +650,7 @@ describe('mobile session composer desktop-first surface', () => {
expect(source).toContain('connectionProvider: (providerId: string) => voiceContext.createAsrConnection(providerId),');
expect(source).toContain('voiceContext.createRefinerTarget(providerId, options),');
expect(source).toContain('voiceContext.warmRefiner(input),');
- expect(source).toContain('getMobileVoiceInputHistoryForHost(deviceId),');
+ expect(source).toContain('getMobileVoiceInputHistoryForHost(deviceId, voice?.credential.settings?.voiceInputHistory)');
// Device link is opened non-blocking (not awaited): dictation goes through the
// cloud ASR proxy and does not need the link, so it must not gate mic start.
expect(source).toContain('void openLink(deviceId).catch(() => undefined);');
diff --git a/apps/mobile/src/session/mobileVoiceHistoryStore.ts b/apps/mobile/src/session/mobileVoiceHistoryStore.ts
index ddbca70399..2c2014233c 100644
--- a/apps/mobile/src/session/mobileVoiceHistoryStore.ts
+++ b/apps/mobile/src/session/mobileVoiceHistoryStore.ts
@@ -1,9 +1,9 @@
import { deleteSecureItem, getSecureItem, setSecureItem } from '@/auth/secureStorage';
+import { compactVoiceInputHistoryIfNeeded, normalizeVoiceHistoryText } from '@cindy/voice-input-core';
+export { MAX_REFINEMENT_HISTORY_ITEM_CHARS as MAX_MOBILE_VOICE_HISTORY_ITEM_CHARS } from '@cindy/voice-input-core';
const STORAGE_KEY_PREFIX = 'xdt.mobileVoiceHistory.v1';
const STORAGE_INDEX_KEY = `${STORAGE_KEY_PREFIX}.hosts`;
-export const MAX_MOBILE_VOICE_HISTORY_ENTRIES = 100;
-export const MAX_MOBILE_VOICE_HISTORY_ITEM_CHARS = 360;
type StoredMobileVoiceHistoryEntry = {
id: string;
@@ -11,8 +11,33 @@ type StoredMobileVoiceHistoryEntry = {
createdAt: number;
};
-export async function getMobileVoiceInputHistoryForHost(hostDeviceId: string): Promise<string[]> {
- return (await readMobileVoiceHistoryEntries(hostDeviceId)).map((entry) => entry.text);
+type StoredMobileVoiceHistory = {
+ entries: StoredMobileVoiceHistoryEntry[];
+ desktopSnapshot?: string;
+};
+
+export async function getMobileVoiceInputHistoryForHost(
+ hostDeviceId: string,
+ syncedDesktopHistory?: readonly string[],
+): Promise<string[]> {
+ const state = await readMobileVoiceHistory(hostDeviceId);
+ if (syncedDesktopHistory?.length) {
+ const desktopEntries = normalizeHistoryEntries(syncedDesktopHistory.map((text, index) => ({
+ text, id: `desktop-${index}-${fnv1a(text)}`, createdAt: 1,
+ })));
+ const snapshot = JSON.stringify(desktopEntries.map((entry) => entry.text));
+ // Remember the imported snapshot separately from the legacy history array.
+ // Otherwise each dictation reimports entries removed by the last compaction.
+ if (state.desktopSnapshot !== snapshot) {
+ const localEntries = state.entries.filter((entry) => !entry.id.startsWith('desktop-'));
+ const priorDesktopEntries = state.entries.filter((entry) => entry.id.startsWith('desktop-'));
+ state.entries = normalizeHistoryEntries([...localEntries, ...desktopEntries, ...priorDesktopEntries]);
+ state.desktopSnapshot = snapshot;
+ // History is advisory; unavailable secure storage must not block recording.
+ await writeMobileVoiceHistory(hostDeviceId, state).catch(() => undefined);
+ }
+ }
+ return state.entries.map((entry) => entry.text);
}
export async function recordMobileVoiceInputHistoryForHost(
@@ -63,22 +88,41 @@ export async function updateMobileVoiceInputHistoryEntryForHost(
export async function clearAllMobileVoiceInputHistories(): Promise<void> {
const hosts = await readHistoryHostIndex();
await Promise.all(
- hosts.map((hostDeviceId) =>
+ hosts.flatMap((hostDeviceId) => [
deleteSecureItem(storageKeyForHostDevice(hostDeviceId)).catch(() => undefined),
- ),
+ deleteSecureItem(snapshotKeyForHostDevice(hostDeviceId)).catch(() => undefined),
+ ]),
);
await deleteSecureItem(STORAGE_INDEX_KEY).catch(() => undefined);
}
async function readMobileVoiceHistoryEntries(hostDeviceId: string): Promise<StoredMobileVoiceHistoryEntry[]> {
- const raw = await getSecureItem(storageKeyForHostDevice(normalizeHostDeviceId(hostDeviceId))).catch(() => null);
- if (!raw) return [];
+ return (await readMobileVoiceHistory(hostDeviceId)).entries;
+}
+
+async function readMobileVoiceHistory(hostDeviceId: string): Promise<StoredMobileVoiceHistory> {
+ const normalizedHost = normalizeHostDeviceId(hostDeviceId);
+ const [raw, snapshot] = await Promise.all([
+ getSecureItem(storageKeyForHostDevice(normalizedHost)).catch(() => null),
+ getSecureItem(snapshotKeyForHostDevice(normalizedHost)).catch(() => null),
+ ]);
+ if (!raw) return { entries: [] };
try {
const parsed = JSON.parse(raw) as unknown;
- if (!Array.isArray(parsed)) return [];
- return normalizeHistoryEntries(parsed);
+ if (Array.isArray(parsed)) return {
+ entries: normalizeHistoryEntries(parsed),
+ desktopSnapshot: snapshot ?? undefined,
+ };
+ // Recover development builds that wrote an object; the next write restores
+ // the array understood by installed bundles and OTA rollback versions.
+ if (!parsed || typeof parsed !== 'object') return { entries: [] };
+ const state = parsed as Partial<StoredMobileVoiceHistory>;
+ return {
+ entries: normalizeHistoryEntries(Array.isArray(state.entries) ? state.entries : []),
+ desktopSnapshot: typeof state.desktopSnapshot === 'string' ? state.desktopSnapshot : undefined,
+ };
} catch {
- return [];
+ return { entries: [] };
}
}
@@ -86,9 +130,20 @@ async function writeMobileVoiceHistoryEntries(
hostDeviceId: string,
entries: StoredMobileVoiceHistoryEntry[],
): Promise<void> {
+ const state = await readMobileVoiceHistory(hostDeviceId);
+ await writeMobileVoiceHistory(hostDeviceId, { ...state, entries });
+}
+
+async function writeMobileVoiceHistory(hostDeviceId: string, state: StoredMobileVoiceHistory): Promise<void> {
const normalizedHost = normalizeHostDeviceId(hostDeviceId);
- await setSecureItem(storageKeyForHostDevice(normalizedHost), JSON.stringify(normalizeHistoryEntries(entries)));
+ const entries = normalizeHistoryEntries(state.entries);
await addHostToHistoryIndex(normalizedHost);
+ // Always keep this v1 value readable by older bundles. Commit history before
+ // its advisory marker so a failed history write cannot suppress a later import.
+ await setSecureItem(storageKeyForHostDevice(normalizedHost), JSON.stringify(entries));
+ if (state.desktopSnapshot) {
+ await setSecureItem(snapshotKeyForHostDevice(normalizedHost), state.desktopSnapshot);
+ }
}
function normalizeHistoryEntries(input: unknown[]): StoredMobileVoiceHistoryEntry[] {
@@ -108,15 +163,13 @@ function normalizeHistoryEntries(input: unknown[]): StoredMobileVoiceHistoryEntr
text,
createdAt,
});
- if (entries.length >= MAX_MOBILE_VOICE_HISTORY_ENTRIES) break;
}
- return entries;
+ return compactVoiceInputHistoryIfNeeded(entries);
}
function normalizeHistoryText(value: unknown): string {
if (typeof value !== 'string') return '';
- const normalized = value.replace(/\s+/g, ' ').trim();
- return normalized.slice(0, MAX_MOBILE_VOICE_HISTORY_ITEM_CHARS).trim();
+ return normalizeVoiceHistoryText(value);
}
function normalizeHostDeviceId(hostDeviceId: string): string {
@@ -134,6 +187,10 @@ function createMobileVoiceHistoryId(text: string, timestamp: number): string {
return `voice-${timestamp.toString(36)}-${fnv1a(`${timestamp}:${text}`)}`;
}
+function snapshotKeyForHostDevice(hostDeviceId: string): string {
+ return `${storageKeyForHostDevice(hostDeviceId)}.desktopSnapshot`;
+}
+
async function addHostToHistoryIndex(hostDeviceId: string): Promise<void> {
const hosts = await readHistoryHostIndex();
if (hosts.includes(hostDeviceId)) return;
@@ -192,4 +249,5 @@ export const __testing = {
readHistoryHostIndex,
storageIndexKey: STORAGE_INDEX_KEY,
storageKeyForHostDevice,
+ snapshotKeyForHostDevice,
};
diff --git a/apps/mobile/src/session/mobileVoiceInput.ts b/apps/mobile/src/session/mobileVoiceInput.ts
index 308d853b6e..795929f76e 100644
--- a/apps/mobile/src/session/mobileVoiceInput.ts
+++ b/apps/mobile/src/session/mobileVoiceInput.ts
@@ -7,6 +7,8 @@ import {
} from '@/session/mobileVoiceLanguage';
import {
DictationRefiner,
+ formatVoiceInputHistoryContext,
+ normalizeVoiceHistoryText,
extractJsonStringFieldSnapshot,
type DictationRefinementContext,
type TextModelClient,
@@ -87,9 +89,6 @@ interface CloudVoiceDeps {
fetch?: typeof fetch;
}
-const MOBILE_VOICE_INPUT_HISTORY_HEADER = '语音输入历史(旧到新,仅作术语、别名和用词风格参考):';
-const MAX_MOBILE_VOICE_HISTORY_ENTRIES_FOR_REFINEMENT = 100;
-const MAX_MOBILE_VOICE_HISTORY_ITEM_CHARS = 360;
const MAX_REFINER_RESPONSE_CHARS = 64_000;
const MAX_ERROR_DETAIL_CHARS = 1_000;
@@ -247,6 +246,7 @@ export function buildMobileVoiceRefinementContext(
uiLanguage?: string;
sourceLanguage?: string;
refinementContext?: DictationRefinementContext;
+ /** Persisted per-host history, including the imported desktop snapshot. */
localVoiceInputHistory?: readonly string[];
/**
* 从被控桌面拉来的词典快照。托管路径的 credential 本身不带词典
@@ -258,7 +258,7 @@ export function buildMobileVoiceRefinementContext(
): DictationRefinementContext {
const settings = credential.settings;
const dictionaryEntries = options.dictionaryEntries ?? settings?.dictionaryEntries ?? [];
- const history = mergeMobileVoiceHistories(settings?.voiceInputHistory, options.localVoiceInputHistory);
+ const history = normalizeMobileVoiceHistoryNewestFirst(options.localVoiceInputHistory ?? settings?.voiceInputHistory ?? []);
const uiLanguage = options.refinementContext?.uiLanguage?.trim()
|| options.uiLanguage?.trim()
|| currentMobileVoiceUiLanguage();
@@ -669,35 +669,15 @@ function formatMobileVoiceDictionary(
}
function formatMobileVoiceHistory(history: readonly string[]): string {
- const entries = normalizeMobileVoiceHistoryNewestFirst(history).reverse();
- if (entries.length === 0) return '';
- return [
- MOBILE_VOICE_INPUT_HISTORY_HEADER,
- ...entries.map((entry) => `- ${entry}`),
- ].join('\n');
-}
-
-function mergeMobileVoiceHistories(
- syncedDesktopHistory: readonly string[] | undefined,
- localMobileHistory: readonly string[] | undefined,
-): string[] {
- return normalizeMobileVoiceHistoryNewestFirst([
- ...(localMobileHistory ?? []),
- ...(syncedDesktopHistory ?? []),
- ]);
+ return formatVoiceInputHistoryContext(history.map((text) => ({ text })));
}
function normalizeMobileVoiceHistoryNewestFirst(history: readonly string[]): string[] {
const entries: string[] = [];
for (const item of history) {
- const text = item
- .replace(/\s+/g, ' ')
- .trim()
- .slice(0, MAX_MOBILE_VOICE_HISTORY_ITEM_CHARS)
- .trim();
+ const text = normalizeVoiceHistoryText(item);
if (!text || entries.includes(text)) continue;
entries.push(text);
- if (entries.length >= MAX_MOBILE_VOICE_HISTORY_ENTRIES_FOR_REFINEMENT) break;
}
return entries;
}
diff --git a/packages/voice-input-core/src/DictationRefiner.ts b/packages/voice-input-core/src/DictationRefiner.ts
index 97abaa7751..ef28579477 100644
--- a/packages/voice-input-core/src/DictationRefiner.ts
+++ b/packages/voice-input-core/src/DictationRefiner.ts
@@ -1,4 +1,5 @@
import type { DictationRefinementContext, RefinementResult } from './types';
+import { takeRefinementContextHead, takeRefinementContextTail, truncateRefinementReply } from './refinementContext';
export type TextModelClient = {
requestJson<T>(input: {
@@ -304,13 +305,10 @@ export class DictationRefiner {
),
userDictionary: normalizeBoundedOptionalMultilineText(base.userDictionary, MAX_USER_DICTIONARY_CHARS),
voiceInputHistory,
- selectionBefore: normalizeBoundedOptionalTailText(base.selectionBefore, MAX_SELECTION_CONTEXT_CHARS),
- selectedText: normalizeBoundedOptionalText(base.selectedText, MAX_SELECTION_CONTEXT_CHARS),
- selectionAfter: normalizeBoundedOptionalText(base.selectionAfter, MAX_SELECTION_CONTEXT_CHARS),
- replyToMessage: normalizeBoundedOptionalText(
- base.replyToMessage,
- MAX_REPLY_TO_MESSAGE_CHARS,
- ),
+ selectionBefore: takeRefinementContextTail(base.selectionBefore ?? '', MAX_SELECTION_CONTEXT_CHARS) || undefined,
+ selectedText: takeRefinementContextHead(base.selectedText ?? '', MAX_SELECTION_CONTEXT_CHARS) || undefined,
+ selectionAfter: takeRefinementContextHead(base.selectionAfter ?? '', MAX_SELECTION_CONTEXT_CHARS) || undefined,
+ replyToMessage: truncateRefinementReply(base.replyToMessage ?? '', MAX_REPLY_TO_MESSAGE_CHARS) || undefined,
userDictionaryMatches: buildUserDictionaryMatches(dictationText, base.dictionaryAliasHints),
};
}
@@ -359,12 +357,6 @@ function normalizeBoundedOptionalText(text: unknown, maxChars: number): string |
return normalized.length > maxChars ? normalized.slice(0, maxChars).trim() : normalized;
}
-function normalizeBoundedOptionalTailText(text: unknown, maxChars: number): string | undefined {
- const normalized = normalizeOptionalText(text);
- if (!normalized) return undefined;
- return normalized.length > maxChars ? normalized.slice(-maxChars).trim() : normalized;
-}
-
function normalizeBoundedOptionalMultilineText(text: unknown, maxChars: number): string | undefined {
const normalized = normalizeOptionalMultilineText(text);
if (!normalized) return undefined;
diff --git a/packages/voice-input-core/src/__tests__/refinementContext.test.ts b/packages/voice-input-core/src/__tests__/refinementContext.test.ts
new file mode 100644
index 0000000000..43b3b9ea82
--- /dev/null
+++ b/packages/voice-input-core/src/__tests__/refinementContext.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import {
+ compactVoiceInputHistoryIfNeeded,
+ estimateVoiceInputHistoryContextChars,
+ formatVoiceInputHistoryContext,
+ takeRefinementContextHead,
+ takeRefinementContextTail,
+ truncateRefinementReply,
+} from '../refinementContext';
+
+describe('shared refinement context', () => {
+ it('keeps history append-only until 12k and leaves room after compaction', () => {
+ const entries = Array.from({ length: 32 }, (_, i) => ({ text: `${i}:`.padEnd(360, '字') }));
+ expect(estimateVoiceInputHistoryContextChars(entries)).toBeLessThanOrEqual(12_000);
+ expect(compactVoiceInputHistoryIfNeeded(entries)).toBe(entries);
+ const overflow = [{ text: '最新'.repeat(180) }, ...entries];
+ const compacted = compactVoiceInputHistoryIfNeeded(overflow);
+ expect(compacted.length).toBeLessThanOrEqual(40);
+ expect(estimateVoiceInputHistoryContextChars(compacted)).toBeLessThanOrEqual(8_000);
+ expect(compacted[0]).toBe(overflow[0]);
+ expect(overflow).toHaveLength(33);
+ const next = [{ text: '下一句' }, ...compacted];
+ expect(compactVoiceInputHistoryIfNeeded(next)).toBe(next);
+ expect(formatVoiceInputHistoryContext(next)).toBe(`${formatVoiceInputHistoryContext(compacted)}\n- 下一句`);
+ });
+
+ it('does not slide at 100 short phrases and limits each history entry to 360 chars', () => {
+ const entries = Array.from({ length: 105 }, (_, i) => ({ text: `entry ${i}` }));
+ expect(compactVoiceInputHistoryIfNeeded(entries)).toBe(entries);
+ expect(formatVoiceInputHistoryContext([{ text: 'x'.repeat(500) }])).toContain(`- ${'x'.repeat(360)}`);
+ expect(formatVoiceInputHistoryContext([{ text: ' ' }])).toBe('');
+ });
+
+ it('preserves line structure, indentation and whitespace at the cursor within the budget', () => {
+ const before = `old${'x'.repeat(1200)}\r\n - one\r\n\t`;
+ expect(takeRefinementContextTail(before)).toHaveLength(1200);
+ expect(takeRefinementContextTail(before).endsWith('\n - one\n\t')).toBe(true);
+ const after = `\r\n next\r\n${'x'.repeat(1300)}`;
+ expect(takeRefinementContextHead(after)).toHaveLength(1200);
+ expect(takeRefinementContextHead(after).startsWith('\n next\n')).toBe(true);
+ expect(takeRefinementContextHead(' ')).toBe(' ');
+ });
+
+ it('keeps both the reply subject and closing question within 500 chars, idempotently', () => {
+ const reply = `方案结论\n${'说明'.repeat(400)}\n你选 A 还是 B?`;
+ const result = truncateRefinementReply(reply);
+ expect(result).toHaveLength(500);
+ expect(result.startsWith('方案结论\n')).toBe(true);
+ expect(result.endsWith('\n你选 A 还是 B?')).toBe(true);
+ expect(result).toContain('\n…\n');
+ expect(truncateRefinementReply(result)).toBe(result);
+ expect(truncateRefinementReply('第一行\r\n 第二行')).toBe('第一行\n 第二行');
+ });
+});
diff --git a/packages/voice-input-core/src/index.ts b/packages/voice-input-core/src/index.ts
index 702d1468e7..44f879e700 100644
--- a/packages/voice-input-core/src/index.ts
+++ b/packages/voice-input-core/src/index.ts
@@ -7,3 +7,4 @@ export * from './DictationExternalEditInspector';
export * from './DictationDictionaryAdvisor';
export * from './dictionary-sync';
export * from './streamingJson';
+export * from './refinementContext';
diff --git a/packages/voice-input-core/src/refinementContext.ts b/packages/voice-input-core/src/refinementContext.ts
new file mode 100644
index 0000000000..c124b69eed
--- /dev/null
+++ b/packages/voice-input-core/src/refinementContext.ts
@@ -0,0 +1,59 @@
+// Keep one history budget across hosts. Append to the old-to-new prompt prefix
+// until the high watermark, then leave room for more dictations after compaction.
+// The desktop budget was reduced after its 2026-06-21–07-04 log audit: increasing
+// history from 33k to 96k chars did not improve acceptance or terminology fixes.
+export const VOICE_INPUT_HISTORY_COMPACT_CHARS = 12_000;
+export const VOICE_INPUT_HISTORY_COMPACT_TARGET_CHARS = 8_000;
+export const VOICE_INPUT_HISTORY_COMPACT_KEEP_ENTRIES = 40;
+export const MAX_REFINEMENT_HISTORY_ITEM_CHARS = 360;
+export const VOICE_INPUT_HISTORY_HEADER = '语音输入历史(旧到新,仅作术语、别名和用词风格参考):';
+export const MAX_REFINEMENT_SIDE_CONTEXT_CHARS = 1_200;
+export const MAX_REFINEMENT_REPLY_TO_MESSAGE_CHARS = 500;
+
+export function normalizeVoiceHistoryText(text: string): string {
+ return text.replace(/\s+/g, ' ').trim().slice(0, MAX_REFINEMENT_HISTORY_ITEM_CHARS).trim();
+}
+
+export function estimateVoiceInputHistoryContextChars(entries: ReadonlyArray<{ text: string }>): number {
+ const texts = entries.map((entry) => normalizeVoiceHistoryText(entry.text)).filter(Boolean);
+ return texts.length === 0 ? 0 : texts.reduce((total, text) => total + 3 + text.length, VOICE_INPUT_HISTORY_HEADER.length);
+}
+
+/** Entries are newest first. Preserve identity and ordering below the budget. */
+export function compactVoiceInputHistoryIfNeeded<T extends { text: string }>(entries: T[]): T[] {
+ if (estimateVoiceInputHistoryContextChars(entries) <= VOICE_INPUT_HISTORY_COMPACT_CHARS) return entries;
+ const recent = entries.slice(0, VOICE_INPUT_HISTORY_COMPACT_KEEP_ENTRIES);
+ while (recent.length > 1 && estimateVoiceInputHistoryContextChars(recent) > VOICE_INPUT_HISTORY_COMPACT_TARGET_CHARS) {
+ recent.pop();
+ }
+ return recent;
+}
+
+export function formatVoiceInputHistoryContext(entries: ReadonlyArray<{ text: string }>): string {
+ const texts = compactVoiceInputHistoryIfNeeded([...entries])
+ .map((entry) => normalizeVoiceHistoryText(entry.text))
+ .filter(Boolean)
+ .reverse();
+ return texts.length === 0 ? '' : [VOICE_INPUT_HISTORY_HEADER, ...texts.map((text) => `- ${text}`)].join('\n');
+}
+
+// Cursor-adjacent whitespace is meaningful: a trailing newline or indentation
+// describes the insertion point. Only normalize line endings, never trim it.
+export function takeRefinementContextHead(text: string, maxChars = MAX_REFINEMENT_SIDE_CONTEXT_CHARS): string {
+ return text.replace(/\r\n?/g, '\n').slice(0, maxChars);
+}
+
+export function takeRefinementContextTail(text: string, maxChars = MAX_REFINEMENT_SIDE_CONTEXT_CHARS): string {
+ return maxChars > 0 ? text.replace(/\r\n?/g, '\n').slice(-maxChars) : '';
+}
+
+/** Keep the opening subject and closing question, with an explicit omission. */
+export function truncateRefinementReply(text: string, maxChars = MAX_REFINEMENT_REPLY_TO_MESSAGE_CHARS): string {
+ const normalized = text.replace(/\r\n?/g, '\n').trim();
+ if (normalized.length <= maxChars) return normalized;
+ const separator = '\n…\n';
+ if (maxChars <= separator.length) return normalized.slice(0, Math.max(0, maxChars));
+ const headChars = Math.floor((maxChars - separator.length) / 2);
+ const tailChars = maxChars - separator.length - headChars;
+ return `${normalized.slice(0, headChars)}${separator}${normalized.slice(-tailChars)}`;
+}