Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: isolate voice dictation and tool execution

Adam Eivyaf6e830aa79b
diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.js
index 9a3701b2ee..b17572b616 100644
--- a/server/services/voice/pipeline.js
+++ b/server/services/voice/pipeline.js
@@ -388,6 +388,147 @@ const shortId = () => Math.random().toString(36).slice(2, 7);
// of that conversation and a runaway caller would blow the model's window.
const MAX_SYSTEM_CONTEXT_CHARS = 4000;
+// Journal dictation bypasses the model and emits only the newly appended segment.
+const runDictationTurn = async ({ userText, state, signal, emit }) => {
+ const trimmed = userText.trim();
+ // STT can return whitespace-only transcripts (Whisper on silent audio,
+ // trailing partials). Don't fire a bogus append event with { entry: null };
+ // just go idle and wait for the next utterance.
+ if (!trimmed) {
+ emit('voice:idle', { reason: 'empty-transcript' });
+ return { transcript: userText, reply: '' };
+ }
+ if (STOP_DICTATION_RE.test(trimmed)) {
+ state.dictation = { enabled: false, date: null };
+ emit('voice:dictation', { enabled: false });
+ const reply = 'Dictation off.';
+ const { wav, latencyMs } = await synthesize(reply, { signal });
+ // Report the real synth latency so the client's TTS timing stats
+ // reflect actual work, not a hardcoded zero.
+ if (!signal?.aborted) emit('voice:tts:audio', { sentence: reply, wav, latencyMs });
+ emit('voice:llm:delta', { delta: reply });
+ emit('voice:llm:done', { text: reply });
+ emit('voice:idle', { reason: 'turn-complete' });
+ return { transcript: userText, reply };
+ }
+ // Defensive: dictation can be enabled without a date (e.g. UI toggle
+ // without a date, or tool side-effect missing one). Default to today so
+ // we never throw here and kill the user's dictation turn.
+ let date = state.dictation.date;
+ if (!date) {
+ date = await getToday();
+ state.dictation.date = date;
+ console.warn(`🎙️ dictation missing date; defaulting to ${date}`);
+ emit('voice:dictation', { enabled: true, date });
+ }
+ const entry = await appendJournal(date, trimmed, { source: 'voice' });
+ // Ship only the delta (new segment + metadata) rather than the full
+ // entry. `entry.content` and `entry.segments` grow over the day, so
+ // emitting the whole record per utterance would push socket payload
+ // size and serialization cost toward O(n²) during long dictation
+ // sessions. The client patches local state from these fields.
+ const segments = Array.isArray(entry?.segments) ? entry.segments : [];
+ const segment = segments.length ? segments[segments.length - 1] : null;
+ emit('voice:dailyLog:appended', {
+ date,
+ text: trimmed,
+ segment,
+ segmentCount: segments.length,
+ updatedAt: entry?.updatedAt,
+ });
+ console.log(`🎙️ dictation → journal[${date}] +${trimmed.length} chars`);
+ emit('voice:idle', { reason: 'dictation-appended' });
+ return { transcript: userText, reply: '' };
+};
+
+// Execute one tool completely before the coordinator advances to its next call.
+// Host authority is passed through for dispatch-time revalidation; UI refresh
+// settles before the result is added to the next model iteration.
+const executeTurnToolCall = async ({ tc, cfg, emit, state, signal, hasHostControl, tlog, toolRuns }) => {
+ const t0 = Date.now();
+ let result;
+ let args = {};
+ // ctx.requestUiText lets ui_read pull the visible-text blob on demand
+ // (the client omits it from the index now). Bind state/emit/signal here
+ // so the tool just calls ctx.requestUiText() with no plumbing.
+ const ctx = {
+ sideEffects: [],
+ hasHostControl,
+ state,
+ signal,
+ // ui_describe_visually: capture the active tab (client round-trip) and
+ // describe it via the voice provider's vision endpoint. Provided here
+ // so tools.js stays free of socket/vision coupling.
+ captureScreenshot: () => requestScreenshot(emit, state, 15000, signal),
+ describeImage: (dataUrl, prompt) => describeScreenshot(dataUrl, prompt, cfg),
+ requestUiText: () => requestUiText(state, emit, signal),
+ };
+ try {
+ args = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
+ const argSummary = Object.keys(args).length ? Object.entries(args).map(([k, v]) => `${k}=${JSON.stringify(v).slice(0, 40)}`).join(' ') : '—';
+ tlog(`tool.start ${tc.function.name} ${argSummary}`);
+ result = await dispatchTool(tc.function.name, args, ctx);
+ const ms = Date.now() - t0;
+ toolRuns.push({ name: tc.function.name, ok: true, ms });
+ tlog(`tool.done ${tc.function.name} ok ${ms}ms`);
+ } catch (err) {
+ const ms = Date.now() - t0;
+ result = { ok: false, error: err.message };
+ if (err.code === 'HOST_CONTROL_FORBIDDEN') {
+ emit('voice:error', { stage: 'tool', code: err.code, message: err.message });
+ }
+ toolRuns.push({ name: tc.function.name, ok: false, ms, error: err.message });
+ tlog(`tool.fail ${tc.function.name} ${ms}ms err="${err.message}"`);
+ }
+ // Apply server-side side-effects (dictation state) and forward
+ // client-facing side-effects (navigation) over the socket.
+ for (const fx of ctx.sideEffects) {
+ if (fx.type === 'dictation' && state) {
+ // When disabling dictation, clear the date so it can't leak to the
+ // UI or be picked up by the next enable. A stale date is worse than
+ // null — it can cause surprising "jumped back to April 17" behavior.
+ const enabled = !!fx.enabled;
+ state.dictation = {
+ enabled,
+ date: enabled ? (fx.date || state.dictation?.date || null) : null,
+ };
+ emit('voice:dictation', { enabled: state.dictation.enabled, date: state.dictation.date });
+ } else if (fx.type === 'navigate') {
+ emit('voice:navigate', { path: fx.path });
+ } else if (fx.type === 'ui:click') {
+ emit('voice:ui:click', { target: fx.target });
+ } else if (fx.type === 'ui:fill') {
+ emit('voice:ui:fill', { target: fx.target, value: fx.value });
+ } else if (fx.type === 'ui:select') {
+ emit('voice:ui:select', { target: fx.target, option: fx.option });
+ } else if (fx.type === 'ui:check') {
+ emit('voice:ui:check', { target: fx.target, checked: fx.checked });
+ }
+ }
+ // If the tool mutated the UI (including client-side navigation), pause
+ // for the client's follow-up index push and attach the fresh summary to
+ // the tool result so the next LLM iteration can chain the next action
+ // against the new page state (e.g. click New Task → see the modal →
+ // fill Name → click Save, all in one turn; or ui_navigate → see the
+ // tasks page → click Add Task). Navigation involves a full React route
+ // change and a 250ms INITIAL_DELAY_MS before the client flushes its
+ // index, so give it a longer timeout than the ~120ms post-click push.
+ const hasUiEffect = ctx.sideEffects.some((fx) => typeof fx.type === 'string' && fx.type.startsWith('ui:'));
+ const hasNavigate = ctx.sideEffects.some((fx) => fx.type === 'navigate');
+ if ((hasUiEffect || hasNavigate) && !signal?.aborted) {
+ const tRefresh = Date.now();
+ const timeoutMs = hasNavigate ? 1500 : 800;
+ const refreshed = await waitForUiRefresh(state, timeoutMs, signal);
+ tlog(`tool.refresh ${tc.function.name} ${refreshed ? 'ok' : 'timeout'} ${Date.now() - tRefresh}ms`);
+ if (refreshed) {
+ const summary = summarizeUi(refreshed);
+ if (summary) result = { ...result, ui: summary };
+ }
+ }
+ emit('voice:tool', { name: tc.function.name, args, result });
+ return result;
+};
+
export const runTurn = async ({ audio, text, mimeType, source, history = [], emit, signal, state, systemContext = null, hasHostControl }) => {
const cfg = await getVoiceConfig();
if (signal?.aborted) return { transcript: '', reply: '' };
@@ -447,9 +588,8 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
}
}
- // Dictation mode short-circuits the LLM: the user's speech goes straight
- // into the daily-log entry unless they say the stop phrase, which ends
- // dictation and falls through to a normal confirmation turn.
+ // Dictation mode bypasses the LLM: speech goes into the daily log, and
+ // the stop phrase ends dictation with a canonical spoken reply.
//
// Only applies to spoken input. Typed input (the "Read back" button,
// assistant-issued sendText, manual typing) bypasses dictation so the
@@ -458,55 +598,7 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
// that hint in addition to the no-text case.
const isSpokenInput = !text || source === 'voice';
if (isSpokenInput && state?.dictation?.enabled) {
- const trimmed = userText.trim();
- // STT can return whitespace-only transcripts (Whisper on silent audio,
- // trailing partials). Don't fire a bogus append event with { entry: null };
- // just go idle and wait for the next utterance.
- if (!trimmed) {
- emit('voice:idle', { reason: 'empty-transcript' });
- return { transcript: userText, reply: '' };
- }
- if (STOP_DICTATION_RE.test(trimmed)) {
- state.dictation = { enabled: false, date: null };
- emit('voice:dictation', { enabled: false });
- const reply = 'Dictation off.';
- const { wav, latencyMs } = await synthesize(reply, { signal });
- // Report the real synth latency so the client's TTS timing stats
- // reflect actual work, not a hardcoded zero.
- if (!signal?.aborted) emit('voice:tts:audio', { sentence: reply, wav, latencyMs });
- emit('voice:llm:delta', { delta: reply });
- emit('voice:llm:done', { text: reply });
- emit('voice:idle', { reason: 'turn-complete' });
- return { transcript: userText, reply };
- }
- // Defensive: dictation can be enabled without a date (e.g. UI toggle
- // without a date, or tool side-effect missing one). Default to today so
- // we never throw here and kill the user's dictation turn.
- let date = state.dictation.date;
- if (!date) {
- date = await getToday();
- state.dictation.date = date;
- console.warn(`🎙️ dictation missing date; defaulting to ${date}`);
- emit('voice:dictation', { enabled: true, date });
- }
- const entry = await appendJournal(date, trimmed, { source: 'voice' });
- // Ship only the delta (new segment + metadata) rather than the full
- // entry. `entry.content` and `entry.segments` grow over the day, so
- // emitting the whole record per utterance would push socket payload
- // size and serialization cost toward O(n²) during long dictation
- // sessions. The client patches local state from these fields.
- const segments = Array.isArray(entry?.segments) ? entry.segments : [];
- const segment = segments.length ? segments[segments.length - 1] : null;
- emit('voice:dailyLog:appended', {
- date,
- text: trimmed,
- segment,
- segmentCount: segments.length,
- updatedAt: entry?.updatedAt,
- });
- console.log(`🎙️ dictation → journal[${date}] +${trimmed.length} chars`);
- emit('voice:idle', { reason: 'dictation-appended' });
- return { transcript: userText, reply: '' };
+ return runDictationTurn({ userText, state, signal, emit });
}
// Short, hand-crafted assistant reply that bypasses the LLM. Used by the
@@ -729,87 +821,7 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
for (const tc of callsWithIds) {
if (signal?.aborted) break;
- const t0 = Date.now();
- let result;
- let args = {};
- // ctx.requestUiText lets ui_read pull the visible-text blob on demand
- // (the client omits it from the index now). Bind state/emit/signal here
- // so the tool just calls ctx.requestUiText() with no plumbing.
- const ctx = {
- sideEffects: [],
- hasHostControl,
- state,
- signal,
- // ui_describe_visually: capture the active tab (client round-trip) and
- // describe it via the voice provider's vision endpoint. Provided here
- // so tools.js stays free of socket/vision coupling.
- captureScreenshot: () => requestScreenshot(emit, state, 15000, signal),
- describeImage: (dataUrl, prompt) => describeScreenshot(dataUrl, prompt, cfg),
- requestUiText: () => requestUiText(state, emit, signal),
- };
- try {
- args = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
- const argSummary = Object.keys(args).length ? Object.entries(args).map(([k, v]) => `${k}=${JSON.stringify(v).slice(0, 40)}`).join(' ') : '—';
- tlog(`tool.start ${tc.function.name} ${argSummary}`);
- result = await dispatchTool(tc.function.name, args, ctx);
- const ms = Date.now() - t0;
- toolRuns.push({ name: tc.function.name, ok: true, ms });
- tlog(`tool.done ${tc.function.name} ok ${ms}ms`);
- } catch (err) {
- const ms = Date.now() - t0;
- result = { ok: false, error: err.message };
- if (err.code === 'HOST_CONTROL_FORBIDDEN') {
- emit('voice:error', { stage: 'tool', code: err.code, message: err.message });
- }
- toolRuns.push({ name: tc.function.name, ok: false, ms, error: err.message });
- tlog(`tool.fail ${tc.function.name} ${ms}ms err="${err.message}"`);
- }
- // Apply server-side side-effects (dictation state) and forward
- // client-facing side-effects (navigation) over the socket.
- for (const fx of ctx.sideEffects) {
- if (fx.type === 'dictation' && state) {
- // When disabling dictation, clear the date so it can't leak to the
- // UI or be picked up by the next enable. A stale date is worse than
- // null — it can cause surprising "jumped back to April 17" behavior.
- const enabled = !!fx.enabled;
- state.dictation = {
- enabled,
- date: enabled ? (fx.date || state.dictation?.date || null) : null,
- };
- emit('voice:dictation', { enabled: state.dictation.enabled, date: state.dictation.date });
- } else if (fx.type === 'navigate') {
- emit('voice:navigate', { path: fx.path });
- } else if (fx.type === 'ui:click') {
- emit('voice:ui:click', { target: fx.target });
- } else if (fx.type === 'ui:fill') {
- emit('voice:ui:fill', { target: fx.target, value: fx.value });
- } else if (fx.type === 'ui:select') {
- emit('voice:ui:select', { target: fx.target, option: fx.option });
- } else if (fx.type === 'ui:check') {
- emit('voice:ui:check', { target: fx.target, checked: fx.checked });
- }
- }
- // If the tool mutated the UI (including client-side navigation), pause
- // for the client's follow-up index push and attach the fresh summary to
- // the tool result so the next LLM iteration can chain the next action
- // against the new page state (e.g. click New Task → see the modal →
- // fill Name → click Save, all in one turn; or ui_navigate → see the
- // tasks page → click Add Task). Navigation involves a full React route
- // change and a 250ms INITIAL_DELAY_MS before the client flushes its
- // index, so give it a longer timeout than the ~120ms post-click push.
- const hasUiEffect = ctx.sideEffects.some((fx) => typeof fx.type === 'string' && fx.type.startsWith('ui:'));
- const hasNavigate = ctx.sideEffects.some((fx) => fx.type === 'navigate');
- if ((hasUiEffect || hasNavigate) && !signal?.aborted) {
- const tRefresh = Date.now();
- const timeoutMs = hasNavigate ? 1500 : 800;
- const refreshed = await waitForUiRefresh(state, timeoutMs, signal);
- tlog(`tool.refresh ${tc.function.name} ${refreshed ? 'ok' : 'timeout'} ${Date.now() - tRefresh}ms`);
- if (refreshed) {
- const summary = summarizeUi(refreshed);
- if (summary) result = { ...result, ui: summary };
- }
- }
- emit('voice:tool', { name: tc.function.name, args, result });
+ const result = await executeTurnToolCall({ tc, cfg, emit, state, signal, hasHostControl, tlog, toolRuns });
messages.push({
role: 'tool',
tool_call_id: tc.resolvedId,
diff --git a/server/services/voice/pipelineTurnPhases.test.js b/server/services/voice/pipelineTurnPhases.test.js
new file mode 100644
index 0000000000..9c74bd862e
--- /dev/null
+++ b/server/services/voice/pipelineTurnPhases.test.js
@@ -0,0 +1,201 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ getVoiceConfig: vi.fn(),
+ streamChat: vi.fn(),
+ dispatchTool: vi.fn(),
+ transcribe: vi.fn(),
+ synthesize: vi.fn(),
+ appendJournal: vi.fn(),
+ getToday: vi.fn(),
+}));
+
+vi.mock('./config.js', () => ({ getVoiceConfig: mocks.getVoiceConfig }));
+vi.mock('./llm.js', () => ({ streamChat: mocks.streamChat }));
+vi.mock('./stt.js', () => ({ transcribe: mocks.transcribe }));
+vi.mock('./tts.js', () => ({ synthesize: mocks.synthesize }));
+vi.mock('../brainJournal.js', () => ({ appendJournal: mocks.appendJournal, getToday: mocks.getToday }));
+vi.mock('./echo.js', () => ({ isEchoOfRecentTts: () => false, rememberTtsSentence: vi.fn() }));
+vi.mock('./tools.js', () => ({
+ dispatchTool: mocks.dispatchTool,
+ getToolSpecsForIntent: () => ({ specs: [], activeGroups: new Set(['ui']) }),
+ classifyIntent: () => new Set(),
+ getAllToolNames: () => [],
+ UI_KINDS: ['tab', 'button', 'link', 'input', 'textarea', 'select', 'checkbox', 'radio'],
+}));
+
+const { runTurn } = await import('./pipeline.js');
+
+const toolCall = (name, args, extra = {}) => ({
+ type: 'function', function: { name, arguments: args }, ...extra,
+});
+const completion = (text, toolCalls = []) => ({
+ text, toolCalls, model: 'test-model', ttfbMs: 1, totalMs: 2, finishReason: 'stop',
+});
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.useFakeTimers();
+ mocks.getVoiceConfig.mockResolvedValue({
+ llm: { model: 'test-model', systemPrompt: 'sys', usePersonality: false, tools: { enabled: true, maxIterations: 3 } },
+ });
+ mocks.synthesize.mockResolvedValue({ wav: Buffer.alloc(8), latencyMs: 7 });
+ mocks.getToday.mockResolvedValue('2026-01-02');
+ mocks.streamChat.mockResolvedValue(completion('Ready.'));
+});
+
+afterEach(() => vi.useRealTimers());
+
+describe('runTurn tool execution', () => {
+ it('refreshes UI before continuing, pairs missing call IDs, and applies dictation effects in order', async () => {
+ const seenMessages = [];
+ mocks.streamChat.mockImplementation(async (messages, { onDelta }) => {
+ seenMessages.push(structuredClone(messages));
+ if (seenMessages.length === 1) {
+ onDelta('Opening. ');
+ return completion('Opening.', [
+ toolCall('ui_navigate', '{"path":"/example"}', { index: 4 }),
+ toolCall('daily_log_stop_dictation', '{}'),
+ ]);
+ }
+ return completion('Ready.');
+ });
+ mocks.dispatchTool.mockImplementation(async (name, _args, ctx) => {
+ if (name === 'ui_navigate') ctx.sideEffects.push({ type: 'navigate', path: '/example' });
+ else ctx.sideEffects.push({ type: 'dictation', enabled: false });
+ return { ok: true };
+ });
+ const state = { dictation: { enabled: true, date: '2026-01-01' } };
+ const signal = new AbortController().signal;
+ const hasHostControl = () => true;
+ const events = [];
+ const turn = runTurn({ text: 'open the example', state, signal, hasHostControl,
+ emit: (event, payload) => events.push({ event, payload }) });
+
+ await vi.waitFor(() => expect(state.uiWaiters).toHaveLength(1));
+ expect(mocks.dispatchTool).toHaveBeenCalledTimes(1);
+ expect(events).toContainEqual({ event: 'voice:navigate', payload: { path: '/example' } });
+ const refreshed = { title: 'Example page', elements: [{ kind: 'button', label: 'Save example' }] };
+ state.ui = refreshed;
+ for (const waiter of [...state.uiWaiters]) waiter(refreshed);
+
+ await expect(turn).resolves.toEqual({ transcript: 'open the example', reply: 'Opening. Ready.' });
+ const assistant = seenMessages[1].find(message => message.role === 'assistant');
+ expect(assistant.tool_calls.map(call => call.id)).toEqual(['call_0_4', 'call_0_1']);
+ const results = seenMessages[1].filter(message => message.role === 'tool');
+ expect(results.map(message => message.tool_call_id)).toEqual(['call_0_4', 'call_0_1']);
+ expect(JSON.parse(results[0].content)).toEqual({ ok: true, ui: 'Page: Example page. Buttons: Save example.' });
+ expect(JSON.parse(results[1].content)).toEqual({ ok: true });
+ expect(state.dictation).toEqual({ enabled: false, date: null });
+ expect(state.uiWaiters).toEqual([]);
+ expect(mocks.dispatchTool.mock.calls.every(([, , ctx]) => ctx.hasHostControl === hasHostControl && ctx.signal === signal && ctx.state === state)).toBe(true);
+ expect(events.filter(({ event }) => ['voice:navigate', 'voice:dictation', 'voice:tool'].includes(event)).map(({ event }) => event))
+ .toEqual(['voice:navigate', 'voice:tool', 'voice:dictation', 'voice:tool']);
+ });
+
+ it('returns argument and host-authority failures to the model and continues with the next tool', async () => {
+ const seenMessages = [];
+ mocks.streamChat.mockImplementation(async messages => {
+ seenMessages.push(structuredClone(messages));
+ return seenMessages.length === 1 ? completion('', [
+ toolCall('invalid_arguments', '{', { id: 'invalid' }),
+ toolCall('pm2_restart', '{"name":"example-app"}', { id: 'denied' }),
+ toolCall('time_now', '', { id: 'allowed' }),
+ ]) : completion('Reported.');
+ });
+ mocks.dispatchTool.mockImplementation(async name => {
+ if (name === 'pm2_restart') throw Object.assign(new Error('Operator authority required'), { code: 'HOST_CONTROL_FORBIDDEN' });
+ return { ok: true, time: '12:00' };
+ });
+ const events = [];
+ await runTurn({ text: 'restart the example', state: {}, hasHostControl: () => false,
+ emit: (event, payload) => events.push({ event, payload }) });
+
+ expect(mocks.dispatchTool.mock.calls.map(([name]) => name)).toEqual(['pm2_restart', 'time_now']);
+ const results = seenMessages[1].filter(message => message.role === 'tool').map(message => JSON.parse(message.content));
+ expect(results).toEqual([
+ { ok: false, error: expect.any(String) },
+ { ok: false, error: 'Operator authority required' },
+ { ok: true, time: '12:00' },
+ ]);
+ expect(events).toContainEqual({ event: 'voice:error', payload: {
+ stage: 'tool', code: 'HOST_CONTROL_FORBIDDEN', message: 'Operator authority required',
+ } });
+ expect(events.filter(({ event }) => event === 'voice:tool')).toHaveLength(3);
+ });
+
+ it('skips UI refresh, sibling tools and further model calls when dispatch aborts the turn', async () => {
+ const controller = new AbortController();
+ mocks.streamChat.mockResolvedValue(completion('', [
+ toolCall('ui_navigate', '{}', { id: 'first' }), toolCall('time_now', '{}', { id: 'second' }),
+ ]));
+ mocks.dispatchTool.mockImplementation(async (_name, _args, ctx) => {
+ ctx.sideEffects.push({ type: 'navigate', path: '/example' });
+ controller.abort();
+ return { ok: true };
+ });
+ const state = {};
+ await runTurn({ text: 'open the example', state, signal: controller.signal, emit: vi.fn() });
+ expect(mocks.dispatchTool).toHaveBeenCalledTimes(1);
+ expect(mocks.streamChat).toHaveBeenCalledTimes(1);
+ expect(state.uiWaiters).toBeUndefined();
+ });
+});
+
+describe('runTurn dictation routing', () => {
+ it('defaults the journal date and emits only the appended segment without calling the model', async () => {
+ const segment = { text: 'Example journal entry', source: 'voice' };
+ mocks.appendJournal.mockResolvedValue({ content: 'Earlier entry\nExample journal entry',
+ segments: [{ text: 'Earlier entry' }, segment], updatedAt: '2026-01-02T12:00:00Z' });
+ const state = { dictation: { enabled: true, date: null } };
+ const events = [];
+ const result = await runTurn({ text: ' Example journal entry ', source: 'voice', state,
+ emit: (event, payload) => events.push({ event, payload }) });
+
+ expect(result).toEqual({ transcript: ' Example journal entry ', reply: '' });
+ expect(mocks.appendJournal).toHaveBeenCalledWith('2026-01-02', 'Example journal entry', { source: 'voice' });
+ expect(state.dictation.date).toBe('2026-01-02');
+ expect(events).toContainEqual({ event: 'voice:dictation', payload: { enabled: true, date: '2026-01-02' } });
+ expect(events).toContainEqual({ event: 'voice:dailyLog:appended', payload: {
+ date: '2026-01-02', text: 'Example journal entry', segment, segmentCount: 2, updatedAt: '2026-01-02T12:00:00Z',
+ } });
+ expect(events.at(-1)).toEqual({ event: 'voice:idle', payload: { reason: 'dictation-appended' } });
+ expect(mocks.streamChat).not.toHaveBeenCalled();
+ expect(mocks.synthesize).not.toHaveBeenCalled();
+ });
+
+ it('stops spoken dictation and speaks its canonical reply without appending or calling the model', async () => {
+ mocks.transcribe.mockResolvedValue({ text: 'stop dictation', latencyMs: 3 });
+ const state = { dictation: { enabled: true, date: '2026-01-01' } };
+ const events = [];
+ await expect(runTurn({ audio: Buffer.alloc(8), mimeType: 'audio/wav', state,
+ emit: (event, payload) => events.push({ event, payload }) }))
+ .resolves.toEqual({ transcript: 'stop dictation', reply: 'Dictation off.' });
+ expect(state.dictation).toEqual({ enabled: false, date: null });
+ expect(events.map(({ event }) => event)).toEqual([
+ 'voice:transcript', 'voice:dictation', 'voice:tts:audio', 'voice:llm:delta', 'voice:llm:done', 'voice:idle',
+ ]);
+ expect(events[2].payload).toEqual({ sentence: 'Dictation off.', wav: Buffer.alloc(8), latencyMs: 7 });
+ expect(mocks.appendJournal).not.toHaveBeenCalled();
+ expect(mocks.streamChat).not.toHaveBeenCalled();
+ });
+
+ it('keeps typed requests on the conversational path while dictation is enabled', async () => {
+ const state = { dictation: { enabled: true, date: '2026-01-01' } };
+ await expect(runTurn({ text: 'stop dictation', source: 'text', state, emit: vi.fn() }))
+ .resolves.toEqual({ transcript: 'stop dictation', reply: 'Ready.' });
+ expect(state.dictation).toEqual({ enabled: true, date: '2026-01-01' });
+ expect(mocks.appendJournal).not.toHaveBeenCalled();
+ expect(mocks.streamChat).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves blank spoken dictation idle without writing a journal segment', async () => {
+ const events = [];
+ await runTurn({ text: ' ', source: 'voice', state: { dictation: { enabled: true } },
+ emit: (event, payload) => events.push({ event, payload }) });
+ expect(events.at(-1)).toEqual({ event: 'voice:idle', payload: { reason: 'empty-transcript' } });
+ expect(mocks.appendJournal).not.toHaveBeenCalled();
+ expect(mocks.getToday).not.toHaveBeenCalled();
+ expect(mocks.streamChat).not.toHaveBeenCalled();
+ });
+});