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

perf(voice): lazy voice:ui:index text payload via voice:ui:read-request

Adam Eivy81991502250b
diff --git a/client/src/hooks/useVoiceUiSync.js b/client/src/hooks/useVoiceUiSync.js
index 5adbf21315..c4751f4b19 100644
--- a/client/src/hooks/useVoiceUiSync.js
+++ b/client/src/hooks/useVoiceUiSync.js
@@ -7,6 +7,17 @@
// VoiceWidget to emit right after a click/fill so the pipeline's in-turn
// "wait for refresh" can chain the next action.
//
+// LAZY visible-text payload. The index ships the lightweight structure
+// (path/title/elements) but NOT the heavy visible-text blob — that runs
+// extractVisibleText over the whole page and is only needed by the `ui_read`
+// tool. Instead the index sets `textOnDemand: true`; when the server actually
+// needs the text it emits `voice:ui:read-request`, and we compute
+// extractVisibleText on the live DOM right then and reply with
+// `voice:ui:read-response`. A legacy server that never sends the read-request
+// still works because `ui_read` falls back to the eager-text path (an index
+// that already carries `text`); the read-request handler here is purely
+// additive.
+//
// State lives on refs owned by the mounted hook, so StrictMode double-
// invocation and HMR remounts don't leave stale timers or signature caches.
// An escape-hatch module-level ref gives the post-action helper a handle
@@ -15,7 +26,7 @@
import { useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import socket from '../services/socket.js';
-import { buildIndex, clearRefs } from '../services/domIndex.js';
+import { buildIndex, clearRefs, extractVisibleText } from '../services/domIndex.js';
const DEBOUNCE_MS = 500;
const INITIAL_DELAY_MS = 250;
@@ -75,6 +86,20 @@ export const useVoiceUiSync = (enabled) => {
activePush = schedule;
+ // Server-driven lazy text read. The server emits voice:ui:read-request
+ // when the ui_read tool needs the visible-text blob it deliberately
+ // didn't ship in the index. Compute it on the live DOM right now and
+ // reply. Echo back the request id (when present) so the server can
+ // correlate the response with the awaiting tool call. Guard against a
+ // hidden tab returning a stale snapshot — still reply (with whatever the
+ // DOM holds) so the server's waiter doesn't hang on a missing response.
+ const onReadRequest = (payload) => {
+ const requestId = payload && typeof payload === 'object' ? payload.requestId : undefined;
+ const text = extractVisibleText();
+ socket.emit('voice:ui:read-response', { requestId, text });
+ };
+ socket.on('voice:ui:read-request', onReadRequest);
+
// Reset sigs on route change so the first index for a new page always
// emits, even if it happens to hash identically to the previous.
quickSigRef.current = null;
@@ -97,6 +122,7 @@ export const useVoiceUiSync = (enabled) => {
return () => {
observer.disconnect();
+ socket.off('voice:ui:read-request', onReadRequest);
if (timerRef.current) { clearTimeout(timerRef.current); timerRef.current = null; }
if (activePush === schedule) activePush = null;
};
diff --git a/client/src/hooks/useVoiceUiSync.test.jsx b/client/src/hooks/useVoiceUiSync.test.jsx
new file mode 100644
index 0000000000..9c08738dca
--- /dev/null
+++ b/client/src/hooks/useVoiceUiSync.test.jsx
@@ -0,0 +1,90 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, cleanup } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+// Mock the socket module so we can capture emit() and drive on() handlers.
+const handlers = new Map();
+const emitted = [];
+vi.mock('../services/socket.js', () => ({
+ default: {
+ emit: (event, payload) => emitted.push({ event, payload }),
+ on: (event, fn) => { handlers.set(event, fn); },
+ off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },
+ },
+}));
+
+import { useVoiceUiSync } from './useVoiceUiSync.js';
+
+const Harness = ({ enabled }) => {
+ useVoiceUiSync(enabled);
+ return null;
+};
+
+const renderHook = (enabled) => render(
+ <MemoryRouter initialEntries={['/tasks']}>
+ <Harness enabled={enabled} />
+ </MemoryRouter>,
+);
+
+describe('useVoiceUiSync — lazy text protocol', () => {
+ beforeEach(() => {
+ handlers.clear();
+ emitted.length = 0;
+ document.body.innerHTML = '<main><h1>Tasks</h1><p>Hello page text.</p><button>Add</button></main>';
+ // jsdom geometry stubs so buildIndex() / extractVisibleText() see elements.
+ Object.defineProperty(HTMLElement.prototype, 'offsetParent', {
+ configurable: true,
+ get() { return this.parentNode; },
+ });
+ HTMLElement.prototype.getBoundingClientRect = function () {
+ return { width: 100, height: 20, top: 0, left: 0, right: 100, bottom: 20, x: 0, y: 0 };
+ };
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ });
+
+ it('subscribes to voice:ui:read-request when enabled', () => {
+ renderHook(true);
+ expect(handlers.has('voice:ui:read-request')).toBe(true);
+ });
+
+ it('does not subscribe when disabled', () => {
+ renderHook(false);
+ expect(handlers.has('voice:ui:read-request')).toBe(false);
+ });
+
+ it('replies to voice:ui:read-request with voice:ui:read-response carrying text + requestId', () => {
+ renderHook(true);
+ const onReadRequest = handlers.get('voice:ui:read-request');
+ expect(typeof onReadRequest).toBe('function');
+
+ emitted.length = 0; // ignore any scheduled index emits
+ onReadRequest({ requestId: 'uitext_1' });
+
+ const resp = emitted.find((e) => e.event === 'voice:ui:read-response');
+ expect(resp).toBeTruthy();
+ expect(resp.payload.requestId).toBe('uitext_1');
+ expect(resp.payload.text).toMatch(/Hello page text/);
+ });
+
+ it('emits a lazy index (no text, textOnDemand:true) on the initial flush', () => {
+ vi.useFakeTimers();
+ renderHook(true);
+ // INITIAL_DELAY_MS schedule fires the first index push.
+ vi.advanceTimersByTime(300);
+ const idx = emitted.find((e) => e.event === 'voice:ui:index');
+ expect(idx).toBeTruthy();
+ expect(idx.payload.text).toBeUndefined();
+ expect(idx.payload.textOnDemand).toBe(true);
+ });
+
+ it('unsubscribes the read-request handler on cleanup', () => {
+ const view = renderHook(true);
+ expect(handlers.has('voice:ui:read-request')).toBe(true);
+ view.unmount();
+ expect(handlers.has('voice:ui:read-request')).toBe(false);
+ });
+});
diff --git a/client/src/services/domIndex.js b/client/src/services/domIndex.js
index de6efc074c..eabb52726e 100644
--- a/client/src/services/domIndex.js
+++ b/client/src/services/domIndex.js
@@ -172,7 +172,7 @@ const extractText = (node) => {
return raw.replace(/\s+/g, ' ').trim();
};
-const extractVisibleText = () => {
+export const extractVisibleText = () => {
const blocks = [];
for (const sel of TEXT_BLOCK_SELECTORS) {
document.querySelectorAll(sel).forEach((node) => {
@@ -196,7 +196,16 @@ const extractVisibleText = () => {
return `${cut.slice(0, lastWs > 0 ? lastWs : MAX_TEXT_CHARS)}…`;
};
-export const buildIndex = () => {
+// Build the per-page index the voice server uses to drive ui_* tools.
+//
+// The visible-text blob (extractVisibleText) is the heaviest part of the
+// payload and is only needed by the `ui_read` tool. By default we OMIT it and
+// set `textOnDemand: true` so the server knows it can request the text lazily
+// via `voice:ui:read-request` (answered by the client recomputing
+// extractVisibleText on the live DOM). Pass `{ includeText: true }` to embed
+// the text eagerly — kept for the legacy/fallback path where the server never
+// sends a read-request.
+export const buildIndex = ({ includeText = false } = {}) => {
clearRefs();
const root = pickRoot();
const elements = [];
@@ -235,12 +244,19 @@ export const buildIndex = () => {
elements.push(entry);
}
- return {
+ const index = {
path: window.location.pathname + window.location.search,
title: findTitle(),
elements,
- text: extractVisibleText(),
};
+ if (includeText) {
+ // Legacy/fallback path: embed the text eagerly.
+ index.text = extractVisibleText();
+ } else {
+ // Lazy path: tell the server it can ask for the text on demand.
+ index.textOnDemand = true;
+ }
+ return index;
};
const normalize = (s) => (s || '')
diff --git a/client/src/services/domIndex.test.js b/client/src/services/domIndex.test.js
new file mode 100644
index 0000000000..40ed981010
--- /dev/null
+++ b/client/src/services/domIndex.test.js
@@ -0,0 +1,52 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { buildIndex, extractVisibleText } from './domIndex.js';
+
+// jsdom doesn't do layout, so isVisible()'s offsetParent / getBoundingClientRect
+// checks would drop every element. Stub the geometry so elements register as
+// visible for these structural tests.
+const makeVisible = () => {
+ Object.defineProperty(HTMLElement.prototype, 'offsetParent', {
+ configurable: true,
+ get() { return this.parentNode; },
+ });
+ HTMLElement.prototype.getBoundingClientRect = function getBoundingClientRect() {
+ return { width: 100, height: 20, top: 0, left: 0, right: 100, bottom: 20, x: 0, y: 0 };
+ };
+};
+
+describe('domIndex buildIndex — lazy vs eager text', () => {
+ beforeEach(() => {
+ document.body.innerHTML = `
+ <main>
+ <h1>Tasks</h1>
+ <p>Three tasks pending.</p>
+ <button>Add task</button>
+ </main>
+ `;
+ makeVisible();
+ });
+
+ it('omits the visible-text blob and sets textOnDemand by default (lazy)', () => {
+ const idx = buildIndex();
+ expect(idx.text).toBeUndefined();
+ expect(idx.textOnDemand).toBe(true);
+ // Lightweight structure still ships.
+ expect(idx.title).toBe('Tasks');
+ expect(Array.isArray(idx.elements)).toBe(true);
+ expect(idx.elements.some((e) => e.label === 'Add task')).toBe(true);
+ });
+
+ it('embeds the text eagerly when includeText:true (fallback path)', () => {
+ const idx = buildIndex({ includeText: true });
+ expect(typeof idx.text).toBe('string');
+ expect(idx.text).toMatch(/Three tasks pending/);
+ // Capability flag NOT set on the eager path — the two are mutually exclusive.
+ expect(idx.textOnDemand).toBeUndefined();
+ });
+
+ it('extractVisibleText is independently callable and returns the main text', () => {
+ const text = extractVisibleText();
+ expect(text).toMatch(/Tasks/);
+ expect(text).toMatch(/Three tasks pending/);
+ });
+});
diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.js
index fe871a9f28..4cad4c238d 100644
--- a/server/services/voice/pipeline.js
+++ b/server/services/voice/pipeline.js
@@ -94,7 +94,39 @@ const waitForUiRefresh = (state, timeoutMs, signal) => new Promise((resolve) =>
state.uiWaiters.push(finish);
});
-export { summarizeUi, shouldIncludeUi };
+// Lazily fetch the page's visible text from the client. The client ships the
+// UI index WITHOUT the heavy visible-text blob by default (textOnDemand:true);
+// when ui_read actually needs it we emit voice:ui:read-request and await a
+// voice:ui:read-response (the socket handler resolves the matching waiter).
+// Resolves with the text string, or null on timeout / abort / no-waiter-infra
+// (e.g. tests). Falls back gracefully: if the client never replies (legacy
+// client that doesn't understand read-request) the timeout fires and the
+// caller treats it as "no text available".
+const UI_TEXT_READ_TIMEOUT_MS = 1500;
+let uiTextRequestSeq = 0;
+const requestUiText = (state, emit, signal, timeoutMs = UI_TEXT_READ_TIMEOUT_MS) => new Promise((resolve) => {
+ if (!state || typeof emit !== 'function') { resolve(null); return; }
+ if (!(state.uiTextWaiters instanceof Map)) state.uiTextWaiters = new Map();
+ const requestId = `uitext_${++uiTextRequestSeq}`;
+ let done = false;
+ const finish = (value) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ signal?.removeEventListener?.('abort', onAbort);
+ // Drop our own waiter so a late response (after timeout/abort) is a no-op
+ // rather than resolving a stale promise.
+ state.uiTextWaiters.delete(requestId);
+ resolve(value);
+ };
+ const onAbort = () => finish(null);
+ const timer = setTimeout(() => finish(null), timeoutMs);
+ signal?.addEventListener?.('abort', onAbort, { once: true });
+ state.uiTextWaiters.set(requestId, finish);
+ emit('voice:ui:read-request', { requestId });
+});
+
+export { summarizeUi, shouldIncludeUi, requestUiText };
const buildSystemPrompt = (cfg) => {
if (!cfg.llm.usePersonality) return cfg.llm.systemPrompt;
@@ -514,7 +546,15 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
const t0 = Date.now();
let result;
let args = {};
- const ctx = { sideEffects: [], state, signal };
+ // 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: [],
+ state,
+ signal,
+ 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(' ') : '—';
diff --git a/server/services/voice/pipeline.test.js b/server/services/voice/pipeline.test.js
index 827baf0bec..32f1c63cbb 100644
--- a/server/services/voice/pipeline.test.js
+++ b/server/services/voice/pipeline.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { splitSentences, isNonSpeechMarker, detectNarrationWithoutCall } from './pipeline.js';
+import { splitSentences, isNonSpeechMarker, detectNarrationWithoutCall, requestUiText } from './pipeline.js';
describe('splitSentences', () => {
it('returns empty when no terminator is present', () => {
@@ -133,3 +133,62 @@ describe('detectNarrationWithoutCall', () => {
expect(detectNarrationWithoutCall({})).toBe(false);
});
});
+
+describe('requestUiText (lazy visible-text fetch)', () => {
+ it('emits voice:ui:read-request with a requestId and resolves on matching response', async () => {
+ const state = {};
+ const emitted = [];
+ const emit = (event, payload) => emitted.push({ event, payload });
+
+ const p = requestUiText(state, emit, undefined);
+
+ // The helper emitted the request and parked a waiter keyed by requestId.
+ expect(emitted).toHaveLength(1);
+ expect(emitted[0].event).toBe('voice:ui:read-request');
+ const { requestId } = emitted[0].payload;
+ expect(typeof requestId).toBe('string');
+ expect(state.uiTextWaiters.has(requestId)).toBe(true);
+
+ // Simulate the socket handler delivering the client's read-response.
+ state.uiTextWaiters.get(requestId)('the page body');
+
+ await expect(p).resolves.toBe('the page body');
+ // Waiter cleared after resolution — no stale entries.
+ expect(state.uiTextWaiters.has(requestId)).toBe(false);
+ });
+
+ it('resolves null on timeout (legacy client never replies)', async () => {
+ const state = {};
+ const emit = () => {};
+ // Tiny timeout so the test is fast.
+ const out = await requestUiText(state, emit, undefined, 5);
+ expect(out).toBeNull();
+ expect(state.uiTextWaiters.size).toBe(0);
+ });
+
+ it('resolves null and never emits when no state/emit available (test/abort safety)', async () => {
+ await expect(requestUiText(null, () => {}, undefined)).resolves.toBeNull();
+ await expect(requestUiText({}, null, undefined)).resolves.toBeNull();
+ });
+
+ it('aborts via signal — resolves null and drops the waiter', async () => {
+ const state = {};
+ const ac = new AbortController();
+ const emitted = [];
+ const p = requestUiText(state, (e, d) => emitted.push(d), ac.signal, 10000);
+ expect(state.uiTextWaiters.size).toBe(1);
+ ac.abort();
+ await expect(p).resolves.toBeNull();
+ expect(state.uiTextWaiters.size).toBe(0);
+ });
+
+ it('a late response after timeout is a no-op (waiter already dropped)', async () => {
+ const state = {};
+ const emitted = [];
+ const p = requestUiText(state, (e, d) => emitted.push(d), undefined, 5);
+ const { requestId } = emitted[0];
+ await expect(p).resolves.toBeNull();
+ // No resolver remains, so a late delivery just finds nothing.
+ expect(state.uiTextWaiters.get(requestId)).toBeUndefined();
+ });
+});
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index 67b0f1e5e6..27a9600a68 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -1056,7 +1056,19 @@ const TOOLS = [
},
execute: async ({ summarize = false } = {}, ctx = {}) => {
const ui = ctx?.state?.ui;
- if (!ui || typeof ui.text !== 'string' || !ui.text.trim()) {
+ // The client no longer ships the visible-text blob with every index —
+ // it sets `textOnDemand` and we fetch it lazily here, only when ui_read
+ // actually runs. Resolution order:
+ // 1. Eager/legacy text already on the snapshot (older client, or a
+ // prior ui_read in this turn cached it) → use it directly.
+ // 2. textOnDemand client → request it now via ctx.requestUiText().
+ // 3. Neither (very old / no widget) → "no text available".
+ let text = typeof ui?.text === 'string' && ui.text.trim() ? ui.text : null;
+ if (!text && ui?.textOnDemand && typeof ctx?.requestUiText === 'function') {
+ const fetched = await ctx.requestUiText();
+ if (typeof fetched === 'string' && fetched.trim()) text = fetched;
+ }
+ if (!text) {
return {
ok: false,
error: 'No page text available',
@@ -1065,14 +1077,14 @@ const TOOLS = [
}
return {
ok: true,
- path: ui.path,
- title: ui.title,
- content: ui.text,
- chars: ui.text.length,
+ path: ui?.path,
+ title: ui?.title,
+ content: text,
+ chars: text.length,
summarize: !!summarize,
// Keep `summary` short so the LLM message history isn't doubled — the
// full body lives in `content`.
- summary: `Read page "${ui.title || ui.path || 'current page'}" (${ui.text.length} chars).`,
+ summary: `Read page "${ui?.title || ui?.path || 'current page'}" (${text.length} chars).`,
};
},
},
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index 712405e134..07db22fac7 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -499,6 +499,51 @@ describe('ui_read', () => {
const names = specs.map((s) => s.function.name);
expect(names).toContain('ui_read');
});
+
+ // Lazy text path: the client no longer ships `text` on every index; it sets
+ // textOnDemand and ui_read pulls the blob via ctx.requestUiText().
+ it('lazily fetches text via ctx.requestUiText when index omits text', async () => {
+ const text = 'Lazily fetched page body.';
+ let requested = 0;
+ const ctx = {
+ state: { ui: { textOnDemand: true, path: '/tasks', title: 'Tasks' } },
+ requestUiText: async () => { requested += 1; return text; },
+ };
+ const r = await dispatchTool('ui_read', {}, ctx);
+ expect(requested).toBe(1);
+ expect(r.ok).toBe(true);
+ expect(r.content).toBe(text);
+ expect(r.title).toBe('Tasks');
+ expect(r.chars).toBe(text.length);
+ });
+
+ it('does not request lazily when text is already present (eager/legacy)', async () => {
+ let requested = 0;
+ const ctx = {
+ state: { ui: { text: 'already here', textOnDemand: true } },
+ requestUiText: async () => { requested += 1; return 'should-not-be-used'; },
+ };
+ const r = await dispatchTool('ui_read', {}, ctx);
+ expect(requested).toBe(0);
+ expect(r.content).toBe('already here');
+ });
+
+ it('returns ok:false when lazy fetch times out / returns null', async () => {
+ const ctx = {
+ state: { ui: { textOnDemand: true } },
+ requestUiText: async () => null,
+ };
+ const r = await dispatchTool('ui_read', {}, ctx);
+ expect(r.ok).toBe(false);
+ expect(r.summary).toMatch(/can't see/i);
+ });
+
+ it('returns ok:false when client neither ships text nor advertises textOnDemand', async () => {
+ // Very old client / no widget — no eager text, no lazy capability.
+ const ctx = { state: { ui: { path: '/tasks' } }, requestUiText: async () => 'x' };
+ const r = await dispatchTool('ui_read', {}, ctx);
+ expect(r.ok).toBe(false);
+ });
});
describe('ui_click — destructive confirmation gate', () => {
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index b2fd98c5df..eea0393d0f 100644
--- a/server/sockets/voice.js
+++ b/server/sockets/voice.js
@@ -1,9 +1,10 @@
// Per-socket voice handlers.
// Inbound: voice:turn | voice:text | voice:interrupt | voice:reset
-// | voice:dictation:set | voice:ui:index
+// | voice:dictation:set | voice:ui:index | voice:ui:read-response
// Outbound: voice:transcript | voice:llm:delta | voice:llm:done | voice:tts:audio
// | voice:tool | voice:dictation | voice:navigate
// | voice:ui:click | voice:ui:fill | voice:ui:select | voice:ui:check
+// | voice:ui:read-request
// | voice:dailyLog:appended | voice:error | voice:idle
import { runTurn } from '../services/voice/pipeline.js';
@@ -57,12 +58,17 @@ export const registerVoiceHandlers = (socket) => {
history: [],
ctrl: null,
dictation: { enabled: false, date: null },
- ui: null, // { path, title, elements:[{ ref, kind, label, ... }], updatedAt }
+ ui: null, // { path, title, elements:[{ ref, kind, label, ... }], text?, textOnDemand, updatedAt }
// Promises awaiting the NEXT voice:ui:index arrival — used by the
// pipeline to chain ui_* actions within one LLM turn: after firing a
// ui:click, wait for the client's fresh index before the next tool
// runs so the LLM can see the modal/new content it just opened.
uiWaiters: [],
+ // Resolvers keyed by requestId, awaiting a voice:ui:read-response. The
+ // ui_read tool emits voice:ui:read-request and parks a resolver here so
+ // the heavy visible-text blob is only computed by the client (and shipped
+ // over the wire) when actually needed — not eagerly on every index push.
+ uiTextWaiters: new Map(),
// Ring of recently-spoken TTS sentences (with cached trigrams). The
// pipeline uses this to detect the bot's own voice being echoed back
// through the user's mic when laptop speakers are in play. The buffer is
@@ -228,7 +234,7 @@ export const registerVoiceHandlers = (socket) => {
// (ui_click, ui_fill, ui_select, ui_check).
socket.on('voice:ui:index', (payload) => {
if (!payload || typeof payload !== 'object') return;
- const { path, title, elements, text } = payload;
+ const { path, title, elements, text, textOnDemand } = payload;
if (!Array.isArray(elements)) return;
// Cap elements at 200 to bound prompt size from a malicious or runaway
// client. (The visible-text `text` field has its own ~8 KB cap, enforced
@@ -242,7 +248,12 @@ export const registerVoiceHandlers = (socket) => {
path: typeof path === 'string' ? path.slice(0, 256) : null,
title: typeof title === 'string' ? title.slice(0, 120) : null,
elements: filtered,
+ // Eager-text legacy path: an index that ships `text` is used as-is by
+ // ui_read. Lazy path: `textOnDemand` tells the server it can fetch the
+ // visible text on demand via voice:ui:read-request. Exactly one of these
+ // is set by the client per the buildIndex() contract.
text: typeof text === 'string' ? truncateOnWordBoundary(text, MAX_UI_TEXT_CHARS) : null,
+ textOnDemand: textOnDemand === true,
updatedAt: Date.now(),
};
if (state.uiWaiters.length) {
@@ -252,12 +263,36 @@ export const registerVoiceHandlers = (socket) => {
}
});
+ // Lazy visible-text reply. The ui_read tool emitted voice:ui:read-request;
+ // the client recomputed extractVisibleText on the live DOM and sent it back
+ // here. Re-apply the same ~8 KB word-boundary cap server-side so a runaway
+ // client can't blow past it, then resolve the matching waiter. Echo of the
+ // requestId correlates the response with the awaiting ui_read call.
+ socket.on('voice:ui:read-response', (payload) => {
+ if (!payload || typeof payload !== 'object') return;
+ const { requestId, text } = payload;
+ const capped = typeof text === 'string' ? truncateOnWordBoundary(text, MAX_UI_TEXT_CHARS) : null;
+ // Cache on the current ui snapshot too, so a follow-up read in the same
+ // turn (same page) doesn't need another round-trip.
+ if (state.ui && capped !== null) state.ui.text = capped;
+ const resolve = state.uiTextWaiters.get(requestId);
+ if (resolve) {
+ state.uiTextWaiters.delete(requestId);
+ resolve(capped);
+ }
+ });
+
socket.on('disconnect', () => {
state.ctrl?.abort();
// Abort any pending UI refresh waiters so their turns don't hang.
const waiters = state.uiWaiters;
state.uiWaiters = [];
waiters.forEach((resolve) => resolve(null));
+ // Same for any pending lazy-text read waiters — resolve null so a
+ // ui_read awaiting a response that will never arrive doesn't hang.
+ const textWaiters = Array.from(state.uiTextWaiters.values());
+ state.uiTextWaiters.clear();
+ textWaiters.forEach((resolve) => resolve(null));
unregisterEchoBuffer(state.recentTts);
});
};
diff --git a/server/sockets/voice.test.js b/server/sockets/voice.test.js
index 70562e4de2..3e11727b73 100644
--- a/server/sockets/voice.test.js
+++ b/server/sockets/voice.test.js
@@ -1,5 +1,20 @@
import { describe, it, expect } from 'vitest';
-import { truncateOnWordBoundary } from './voice.js';
+import { truncateOnWordBoundary, registerVoiceHandlers } from './voice.js';
+
+// Minimal fake socket: records on() handlers so tests can fire inbound events,
+// and captures emit() calls. No real Socket.IO needed — the voice:ui:index /
+// voice:ui:read-response handlers are pure state mutations.
+const makeFakeSocket = () => {
+ const handlers = new Map();
+ const emitted = [];
+ return {
+ on: (event, fn) => { handlers.set(event, fn); },
+ emit: (event, payload) => { emitted.push({ event, payload }); },
+ fire: (event, payload) => handlers.get(event)?.(payload),
+ has: (event) => handlers.has(event),
+ emitted,
+ };
+};
describe('truncateOnWordBoundary', () => {
it('returns input untouched when shorter than the cap', () => {
@@ -59,3 +74,34 @@ describe('truncateOnWordBoundary', () => {
expect(out[out.length - 2]).toMatch(/[a]/);
});
});
+
+describe('voice:ui lazy-text socket handlers', () => {
+ it('registers the lazy read-response handler', () => {
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ expect(socket.has('voice:ui:index')).toBe(true);
+ expect(socket.has('voice:ui:read-response')).toBe(true);
+ });
+
+ it('accepts a lazy index (no text, textOnDemand:true) without throwing', () => {
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ expect(() => socket.fire('voice:ui:index', {
+ path: '/tasks',
+ title: 'Tasks',
+ elements: [{ ref: 0, kind: 'button', label: 'Add' }],
+ textOnDemand: true,
+ })).not.toThrow();
+ });
+
+ it('tolerates malformed / unmatched read-response payloads', () => {
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ // Establish a ui snapshot first.
+ socket.fire('voice:ui:index', { path: '/x', title: 'X', elements: [], textOnDemand: true });
+ expect(() => socket.fire('voice:ui:read-response', null)).not.toThrow();
+ expect(() => socket.fire('voice:ui:read-response', 'nope')).not.toThrow();
+ // Unmatched requestId — no waiter to resolve, must not throw.
+ expect(() => socket.fire('voice:ui:read-response', { requestId: 'missing', text: 'hi' })).not.toThrow();
+ });
+});