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

address review (copilot): screenshot requestId correlation, DST-safe calendar anchor, tighten 'ran' workout-intent regex

Adam Eivyb438a4516d5c
diff --git a/PLAN.md b/PLAN.md
index f1484ca8fd..cb322c563b 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -11,7 +11,7 @@ _Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-ag
- [ ] [peer-sync-per-category-version-gate] **Generalize the cross-install schema version gate from whole-payload to per-category.** Surfaced by code review during the batch-clear of `[peer-sync-video-collection-metadata-sync]` (2026-05-25). `compareSchemaVersions` (`server/lib/schemaVersions.js`) walks the UNION of category keys, and the three gate sites (`dataSync.js` `applyRemote`, `peerSync.js` push, `importer.js` import) reject the ENTIRE payload on any `ahead.length > 0`. So introducing a brand-new category key — or bumping one category — makes every not-yet-upgraded peer reject ALL categories (universe, pipeline, …), severing sync across a federation that upgrades on independent schedules. `videoHistory` sidestepped this by deliberately staying OUT of `PORTOS_SCHEMA_VERSIONS` (see the comment there), but `mediaCollections: 1` has the same latent property. Fix: scope the ahead-check to the category (for `applyRemote`/import) or the record's kind→category (for push) actually being transferred, so a newer sender's unknown/bumped category gates only THAT category's transfer, not unrelated ones. Keep the union-walk for diagnostics/UI. Needs new cross-key test coverage (today's tests only exercise same-category gaps).
- [ ] [voice-weather-settings-location] **Wire a real `settings.location { lat, lon }` field so `weather_now` can use a configured location.** Surfaced during the batch-clear review of `[voice-cos-tool-expansion]` (2026-05-25). The `weather_now` voice tool already reads `settings?.location?.{lat,lon}` (forward-compatible, guarded) but no Settings UI or Zod slice ever sets it, so with no `lat`/`lon` args it always falls back to the default location. Add a `location` settings field (Settings UI + a Zod slice in `server/lib/validation.js`), then the existing tool path lights up. Small.
- [ ] [mediacard-use-mediaimage-for-syncing-assets] **`MediaCard.jsx` grid thumbnails still use a raw `<img src={previewUrl}>`.** Same peer-sync placeholder/live-swap gap that `[peer-sync-medialightbox-use-mediaimage-for-syncing-assets]` fixed for the lightbox — `client/src/components/media/MediaCard.jsx` (~line 42) doesn't get the "Syncing" placeholder or the `peerSync:asset-arrived` atomic swap. Swap the raw `<img>` for `MediaImage`. Surfaced by that item's cross-check during the batch-clear (2026-05-25); was outside its stated scope.
-- [ ] [voice-ui-describe-visually-gesture-and-correlation] **`ui_describe_visually` likely can't capture under default browser policy + screenshot waiters lack request correlation.** From the xhigh code-review (2026-05-25). (1) `captureScreenForVision` (`client/src/services/voiceClient.js`) calls `getDisplayMedia` from a *server-initiated* socket event (`voice:screenshot:request`), not a transient user gesture — browsers (Chrome/FF/Safari) require user activation for screen capture, so the call typically rejects with `NotAllowedError` and the feature degrades to "I couldn't capture the screen." Rethink the trigger: a click-to-grant affordance in `VoiceWidget`, a one-time captured `MediaStream` the user pre-authorizes, or document the gesture requirement. (2) `screenshotWaiters` (`server/sockets/voice.js`) is a bare array bulk-resolved with no `requestId` correlation (unlike the `uiTextWaiters` Map) — a late result from a prior/interrupted turn can satisfy a new turn's waiter, describing a stale tab. Mirror the `uiTextWaiters` requestId-keyed pattern. Until (1) is solved the feature is effectively non-functional.
+- [ ] [voice-ui-describe-visually-gesture] **`ui_describe_visually` likely can't capture under default browser policy.** From the xhigh code-review (2026-05-25). `captureScreenForVision` (`client/src/services/voiceClient.js`) calls `getDisplayMedia` from a *server-initiated* socket event (`voice:screenshot:request`), not a transient user gesture — browsers (Chrome/FF/Safari) require user activation for screen capture, so the call typically rejects with `NotAllowedError` and the feature degrades to "I couldn't capture the screen." Rethink the trigger: a click-to-grant affordance in `VoiceWidget`, a one-time captured `MediaStream` the user pre-authorizes, or document the gesture requirement. Until this is solved the feature is effectively non-functional. (The sibling screenshot-waiter request-correlation gap was fixed in the v2.9.0 release review — `screenshotWaiters` is now a `requestId`-keyed Map mirroring `uiTextWaiters`.)
- [ ] [voice-tool-edge-hardening] **Edge-case hardening for the new voice tools (all low-severity, from the xhigh code-review 2026-05-25).** (a) `calendar_today` samples the TZ offset at "now" (`getUtcOffsetMs(new Date(), tz)`) then applies it to the target day's midnight → window drifts ~1h on DST-transition days; sample the offset at the target midnight instead. (b) `calendar_next`'s in-memory filter requires `start >= now` while the server-side `getEvents` keeps `endTime >= now`, so a currently-in-progress meeting is skipped from "what's next?" — decide intended semantics (current+next vs strictly-future) and align the two layers. (c) `timer_set` is a bare in-memory `setTimeout` with no persistence (lost silently on restart) and no dedup across tool-loop iterations (LLM re-issue → double notification). Also minor: `dataSync.js` per-`(category,forPeerId)` `checksumCache` keys are never evicted (unbounded for cycling peer ids; negligible for a home federation), and `resolveExcludeSet` runs on every `getChecksum` even on a cache hit (extra subs-file read on the 60s poll — hoist below the cache-hit check).
## Deferred Architecture (human-led planning)
@@ -112,7 +112,7 @@ Surfaced during code review of the federated-media-collection-sync feature and c
- [ ] [localllm-env-atomic-write] **`.env` backend marker write is non-atomic.** `writeBackend` in `server/services/localLlm.js` (~line 94) uses `writeFileSync` to rewrite `.env`; a crash mid-write could corrupt it. `atomicWrite` (temp+rename, passes strings through unchanged) would make it crash-safe — but `writeBackend` is currently sync and the write is tiny/rare. Surfaced during v2.8.0 release review (gemini, IMPROVEMENT). Deferred: requires a sync→async ripple for a microsecond-wide crash window.
- [ ] [meatspace-workouts-read-path] **`getWorkouts()` is a write-only feature today.** Voice (`meatspace_log_workout`) and the palette can *write* workouts via `addWorkout` (`server/services/meatspaceHealth.js:194`), and `getWorkouts()` (line 189) is exported, but it has zero consumers — no route, no UI, no test reads workouts back. Wire a `GET /api/meatspace/workouts` route + a MeatSpace tab section so logged workouts are visible. Surfaced during v2.9.0 release review (claude, NIT). Deferred: feature-completion follow-up; the write side works and is tested.
- [ ] [datasync-route-forpeer-test] **Route-level `forPeer` + `videoHistory` coverage gap.** `server/routes/dataSync.js` threads the `forPeer` query param (incl. the `typeof === 'string'` array-drop guard) and the new `videoHistory` category to `getSnapshot`/`getChecksum`, but coverage exists only at the service layer (`dataSync.pipelineUniverse.test.js`). Add a route test asserting `?forPeer=x` reaches the snapshot/checksum calls and that a repeated `?forPeer=a&forPeer=b` (array) drops to `undefined`. Surfaced during v2.9.0 release review (claude, NIT). Deferred: test-coverage gap only, no correctness defect.
-- [ ] [voice-calendar-dst-allday-edge] **Calendar voice tools have DST + all-day edge cases.** `calendar_today`/`calendar_next` (`server/services/voice/tools.js` ~1494-1525) anchor local-midnight using `getUtcOffsetMs(new Date(), tz)` (offset at *now*), so on a DST-transition day an event within ~1h of the day boundary can be dropped/double-counted; and `calendar_next` skips an all-day event occurring *today* because its start is at past local-midnight. Compute the offset at the local-midnight instant, and treat today-or-later all-day events as still "upcoming." Surfaced during v2.9.0 release review (claude, NIT). Deferred: negligible single-user edge, twice-a-year window.
+- [ ] [voice-calendar-next-allday-edge] **`calendar_next` skips an all-day event occurring today.** `calendar_next` (`server/services/voice/tools.js` ~1525) selects the soonest event with `start.getTime() >= Date.now()`, but an all-day event today has its `startTime` at past local-midnight, so "what's next?" silently skips it and reports the next *timed* event. Treat today-or-later all-day events as still "upcoming." Surfaced during v2.9.0 release review (claude, NIT). Deferred: minor edge. (The sibling `calendar_today` DST-anchor bug was fixed in the same review — `anchorLocalMidnightUtc` now evaluates the offset at the target day's midnight, not at `now`.)
- [ ] [voice-vision-pinned-text-model] **`ui_describe_visually` reuses the voice text model for vision.** `describeScreenshot` (`server/services/voice/pipeline.js:602`) + `ui_describe_visually` (`tools.js:1356`) send the screenshot to `cfg.llm.model` when the user has pinned a non-`'auto'` voice model. If that pinned model is text-only, the chart description is empty/garbage (degrades gracefully to a clean error, no crash; the `'auto'` default is fine). Route vision through a dedicated vision-provider config, or validate vision-capability and message accordingly. Surfaced during v2.9.0 release review (claude, NIT). Deferred: only bites a non-default pinned-model config.
- [ ] [ltx2-utils-constants-qualified] **LTX2 negative-prompt patch imports a generic top-level module.** `scripts/generate_ltx2.py:92` tries `("utils", "constants")` to override `DEFAULT_NEGATIVE_PROMPT`; `utils` is a very generic top-level package name in a shared venv and could be shadowed (the `hasattr(...)` guard makes a wrong-module *write* improbable, so this is defense-in-depth only). If the real module is namespaced under the ltx package, prefer the fully-qualified import path. Surfaced during v2.9.0 release review (claude, NIT). Deferred: guarded; cosmetic robustness.
diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsx
index 3966894d8e..95d12ee6f0 100644
--- a/client/src/components/voice/VoiceWidget.jsx
+++ b/client/src/components/voice/VoiceWidget.jsx
@@ -224,10 +224,11 @@ export default function VoiceWidget() {
// tab. captureScreenForVision prompts for screen-capture permission and
// returns a data URL (or null on denial/failure); always reply so the
// server-side waiter resolves rather than timing out.
- onVoiceEvent('voice:screenshot:request', async () => {
+ onVoiceEvent('voice:screenshot:request', async (payload) => {
+ const requestId = payload && typeof payload === 'object' ? payload.requestId : undefined;
const dataUrl = await captureScreenForVision();
if (!dataUrl) toast('Voice: screen capture was blocked or unavailable.', { icon: '📷' });
- sendScreenshotResult(dataUrl);
+ sendScreenshotResult(requestId, dataUrl);
}),
];
return () => offs.forEach((off) => off());
diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.js
index 68cb1add4a..8b77cf7fff 100644
--- a/client/src/services/voiceClient.js
+++ b/client/src/services/voiceClient.js
@@ -502,9 +502,11 @@ export const captureScreenForVision = async () => {
};
// Reply to a server voice:screenshot:request. Always emits a result (data URL
-// or null) so the server-side waiter resolves instead of timing out.
-export const sendScreenshotResult = (dataUrl) => {
- socket.emit('voice:screenshot:result', { dataUrl: dataUrl || null });
+// or null) so the server-side waiter resolves instead of timing out. Echo the
+// requestId so the server resolves the matching waiter and a late reply can't
+// satisfy a newer capture.
+export const sendScreenshotResult = (requestId, dataUrl) => {
+ socket.emit('voice:screenshot:result', { requestId, dataUrl: dataUrl || null });
};
export const playWav = (arrayBuffer) => enqueuePlay(arrayBuffer);
diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.js
index f34e9c9fc9..9868b8beba 100644
--- a/server/services/voice/pipeline.js
+++ b/server/services/voice/pipeline.js
@@ -96,27 +96,33 @@ const waitForUiRefresh = (state, timeoutMs, signal) => new Promise((resolve) =>
});
// Ask the client to screenshot the active tab and await the data URL. Mirrors
-// waitForUiRefresh's waiter pattern: emit voice:screenshot:request, then resolve
-// when the client posts voice:screenshot:result (handled in sockets/voice.js).
+// requestUiText's requestId-keyed waiter pattern: emit voice:screenshot:request
+// with a requestId, park a resolver keyed by that id, and resolve only when the
+// client echoes the same id back on voice:screenshot:result (handled in
+// sockets/voice.js). Keying by id means a late result from an earlier capture
+// can't satisfy a newer waiter and describe the wrong screen.
// Resolves with the data URL or null on timeout/abort/denied-capture.
+let screenshotRequestSeq = 0;
const requestScreenshot = (emit, state, timeoutMs, signal) => new Promise((resolve) => {
if (!state) { resolve(null); return; }
- if (!Array.isArray(state.screenshotWaiters)) state.screenshotWaiters = [];
+ if (!(state.screenshotWaiters instanceof Map)) state.screenshotWaiters = new Map();
+ const requestId = `shot_${++screenshotRequestSeq}`;
let done = false;
const finish = (value) => {
if (done) return;
done = true;
clearTimeout(timer);
signal?.removeEventListener?.('abort', onAbort);
- const i = state.screenshotWaiters.indexOf(finish);
- if (i !== -1) state.screenshotWaiters.splice(i, 1);
+ // Drop our own waiter so a late response (after timeout/abort) is a no-op
+ // rather than resolving a stale promise.
+ state.screenshotWaiters.delete(requestId);
resolve(value);
};
const onAbort = () => finish(null);
const timer = setTimeout(() => finish(null), timeoutMs);
signal?.addEventListener?.('abort', onAbort, { once: true });
- state.screenshotWaiters.push(finish);
- emit('voice:screenshot:request', {});
+ state.screenshotWaiters.set(requestId, finish);
+ emit('voice:screenshot:request', { requestId });
});
// Send a captured image (base64 data URL) to the voice LLM provider's vision
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index e29eed5ea2..62f852ecda 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -217,9 +217,13 @@ const GROUP_INTENT = {
// Bare `run`/`ran` were dropped — they collide with common command phrasing
// ("run the pipeline", "I ran the report") and would expose the workout tool
// on non-fitness turns. Genuine run-logging is recovered via the "went
- // for/on a … run" and "ran a/N/for/my …" phrasings below; the other activity
- // nouns (jog/yoga/cardio/gym/cycling/swim/…) rarely collide in voice commands.
- meatspace: /\b(drink|drank|beer|wine|whiskey|shot|cocktail|cigarette|vape|pouch|nicotine|weigh|pound|kilo|kg|smoke|smoking|workout|exercise|exercised|jog|yoga|lift(?:ed|ing)?|cardio|gym|cycling|cycled|swim|swam|how am I|summary today|log (?:a|my) (?:drink|weight|nicotine|workout|run|exercise))\b|\bwent (?:for|on) (?:a |an )?(?:\w+ ){0,2}(?:run|jog|swim|ride|walk|hike|workout)\b|\bran (?:a |an |\d|for |my )/i,
+ // for/on a … run" phrasing and the "ran …" branch below, which requires a
+ // fitness OBJECT — a distance/race ("ran a 5k", "ran 3 miles", "ran a
+ // marathon"), a route ("ran my usual route", "ran my loop"), or a duration
+ // ("ran for 30 minutes") — so "I ran a report", "ran an errand", and "ran my
+ // mouth" no longer match. The other activity nouns (jog/yoga/cardio/gym/…)
+ // rarely collide in voice commands.
+ meatspace: /\b(drink|drank|beer|wine|whiskey|shot|cocktail|cigarette|vape|pouch|nicotine|weigh|pound|kilo|kg|smoke|smoking|workout|exercise|exercised|jog|yoga|lift(?:ed|ing)?|cardio|gym|cycling|cycled|swim|swam|how am I|summary today|log (?:a|my) (?:drink|weight|nicotine|workout|run|exercise))\b|\bwent (?:for|on) (?:a |an )?(?:\w+ ){0,2}(?:run|jog|swim|ride|walk|hike|workout)\b|\bran (?:a |an |my )?(?:\w+ ){0,2}(?:\d+\s?k\b|\d+\s?km\b|miles?\b|marathons?\b|half[- ]?marathons?\b|5k\b|10k\b|loops?\b|routes?\b|trails?\b|laps?\b)|\bran for (?:about |around |roughly )?(?:\d|an? |half|the )/i,
// Calendar reads — "what's on my calendar", "what do I have today",
// "next meeting", "what's next", "upcoming", "any appointments". Tight-ish
// so plain "open calendar" still routes to ui_navigate, not calendar_today.
@@ -375,6 +379,20 @@ const summarizeEvent = (e, tz) => {
const loc = e?.location ? ` at ${e.location}` : '';
return `${e?.title || 'Untitled event'} (${when})${loc}`;
};
+// UTC timestamp (ms) of local midnight for the `YYYY-MM-DD` day string in `tz`.
+// The server runs TZ=UTC, so we subtract the TZ offset from the naive UTC parse
+// of the day string. Evaluate the offset AT the target day's midnight (not at
+// `now`) so a DST transition elsewhere in the day can't shift the result by an
+// hour. The naive parse lands within ~14h of local midnight — close enough that
+// re-evaluating the offset at that candidate instant converges to the correct
+// offset across a DST boundary.
+export const anchorLocalMidnightUtc = (dayStr, tz) => {
+ const naiveUtc = Date.parse(`${dayStr}T00:00:00Z`);
+ const firstOffset = getUtcOffsetMs(new Date(naiveUtc), tz);
+ const candidate = naiveUtc - firstOffset;
+ const refinedOffset = getUtcOffsetMs(new Date(candidate), tz);
+ return naiveUtc - refinedOffset;
+};
// ----- Weather helpers (weather_now) -----
// WMO weather interpretation codes → short spoken text. Open-Meteo returns the
@@ -1489,10 +1507,13 @@ const TOOLS = [
// The server runs TZ=UTC and event startTimes carry an offset/Z, so the
// [startDate, endDate] bounds must be the user's LOCAL day expressed in
// UTC — otherwise a late-evening PT event lands on the next UTC day and
- // gets dropped. Anchor midnight-local by subtracting the TZ offset from
- // the naive UTC parse of the local-day string.
- const offsetMs = getUtcOffsetMs(new Date(), tz);
- const localMidnightUtc = Date.parse(`${today}T00:00:00Z`) - offsetMs;
+ // gets dropped. Anchor midnight-local by subtracting the TZ offset, but
+ // evaluate that offset at the TARGET day's midnight (not at `now`): on a
+ // DST-transition day the offset at `now` can differ from the offset at
+ // midnight by an hour, shifting the window and dropping/duplicating
+ // boundary events. Two passes converge (the first guess lands within
+ // ~14h of local midnight; the second re-evaluates at that instant).
+ const localMidnightUtc = anchorLocalMidnightUtc(today, tz);
const startDate = new Date(localMidnightUtc).toISOString();
const endDate = new Date(localMidnightUtc + 86399999).toISOString();
const { events = [] } = await getCalendarEvents({ startDate, endDate, limit: max });
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index 4ae1705ed5..ec7313dfc2 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -121,7 +121,8 @@ vi.mock('../askService.js', () => ({
}),
}));
-const { dispatchTool, getToolSpecs, getToolSpecsForIntent, classifyIntent } = await import('./tools.js');
+const { dispatchTool, getToolSpecs, getToolSpecsForIntent, classifyIntent, anchorLocalMidnightUtc } = await import('./tools.js');
+const { getUtcOffsetMs: mockedGetUtcOffsetMs } = await import('../../lib/timezone.js');
describe('getToolSpecs', () => {
it('returns OpenAI-format function specs', () => {
@@ -961,6 +962,29 @@ describe('calendar_next', () => {
});
});
+describe('anchorLocalMidnightUtc (DST-safe local-midnight anchor)', () => {
+ it('subtracts the constant offset off the naive UTC parse', () => {
+ // Both passes see the mocked -7h (PDT) offset → local midnight is +7h of the
+ // naive UTC parse of the day string (PDT midnight = 07:00 UTC).
+ const naive = Date.parse('2026-04-17T00:00:00Z');
+ expect(anchorLocalMidnightUtc('2026-04-17', 'America/Los_Angeles'))
+ .toBe(naive + 7 * 3600 * 1000);
+ });
+
+ it('uses the offset evaluated AT the target midnight, not the first guess', () => {
+ // Simulate a DST boundary: the offset at the naive-parse instant differs
+ // from the offset at the refined candidate instant. The returned anchor must
+ // use the SECOND (refined) offset, proving the two-pass convergence.
+ const naive = Date.parse('2026-03-08T00:00:00Z');
+ mockedGetUtcOffsetMs
+ .mockImplementationOnce(() => -8 * 3600 * 1000) // first pass: PST
+ .mockImplementationOnce(() => -7 * 3600 * 1000); // refined: PDT
+ expect(anchorLocalMidnightUtc('2026-03-08', 'America/Los_Angeles'))
+ .toBe(naive + 7 * 3600 * 1000); // refined offset wins
+ mockedGetUtcOffsetMs.mockReturnValue(-7 * 3600 * 1000); // restore default
+ });
+});
+
describe('meatspace_log_workout', () => {
it('rejects missing type', async () => {
await expect(dispatchTool('meatspace_log_workout', {})).rejects.toThrow(/type is required/);
@@ -1088,13 +1112,23 @@ describe('new tool intent routing', () => {
expect(classifyIntent('I went for a run').has('meatspace')).toBe(true);
expect(classifyIntent('went for a 30 minute run').has('meatspace')).toBe(true);
expect(classifyIntent('I ran a 5k this morning').has('meatspace')).toBe(true);
+ expect(classifyIntent('ran 3 miles before work').has('meatspace')).toBe(true);
+ expect(classifyIntent('ran a marathon yesterday').has('meatspace')).toBe(true);
+ expect(classifyIntent('ran my usual route').has('meatspace')).toBe(true);
+ expect(classifyIntent('ran for 30 minutes').has('meatspace')).toBe(true);
expect(classifyIntent('did some cardio at the gym').has('meatspace')).toBe(true);
});
it('does NOT route command phrasings of run/ran to the meatspace group', () => {
// Bare run/ran collide with common commands — must not expose the workout tool.
+ // The "ran …" branch requires a fitness object (distance/route/duration), so
+ // these non-fitness "ran a/an/my X" phrasings must NOT match.
expect(classifyIntent('run the pipeline render').has('meatspace')).toBe(false);
expect(classifyIntent('I ran the report again').has('meatspace')).toBe(false);
expect(classifyIntent('run it one more time').has('meatspace')).toBe(false);
+ expect(classifyIntent('I ran a report').has('meatspace')).toBe(false);
+ expect(classifyIntent('ran an errand').has('meatspace')).toBe(false);
+ expect(classifyIntent('ran my mouth').has('meatspace')).toBe(false);
+ expect(classifyIntent('ran for office').has('meatspace')).toBe(false);
});
it('routes visual-description utterances to the vision group', () => {
expect(classifyIntent("what's on this chart?").has('vision')).toBe(true);
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index 83a6d83fd8..ba40aa0838 100644
--- a/server/sockets/voice.js
+++ b/server/sockets/voice.js
@@ -66,10 +66,12 @@ export const registerVoiceHandlers = (socket) => {
// 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: [],
- // Promises awaiting a voice:screenshot:result for an in-flight
- // ui_describe_visually capture. The server emits voice:screenshot:request,
- // the client captures the active tab and replies with a data URL.
- screenshotWaiters: [],
+ // Resolvers keyed by requestId, awaiting a voice:screenshot:result for an
+ // in-flight ui_describe_visually capture. The server emits
+ // voice:screenshot:request with a requestId, the client captures the active
+ // tab and replies with the same requestId + a data URL. Keying by id stops
+ // a late result from an earlier capture satisfying a newer waiter.
+ screenshotWaiters: new Map(),
// 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
@@ -270,19 +272,22 @@ export const registerVoiceHandlers = (socket) => {
});
// Client replies to a voice:screenshot:request with a base64 data URL of the
- // captured tab (or null if capture failed / the user denied permission).
+ // captured tab (or null if capture failed / the user denied permission). The
+ // requestId echoes the request so a late result can't resolve a newer waiter.
// Cap the payload to bound memory from a runaway/malicious client — a
// full-screen PNG data URL is typically a few MB, so 16 MB is generous.
const MAX_SCREENSHOT_BYTES = 16 * 1024 * 1024;
socket.on('voice:screenshot:result', (payload) => {
- if (!state.screenshotWaiters.length) return;
- const raw = payload && typeof payload === 'object' ? payload.dataUrl : null;
+ if (!payload || typeof payload !== 'object') return;
+ const { requestId, dataUrl: raw } = payload;
const dataUrl = (typeof raw === 'string' && raw.startsWith('data:image/') && raw.length <= MAX_SCREENSHOT_BYTES)
? raw
: null;
- const waiters = state.screenshotWaiters;
- state.screenshotWaiters = [];
- waiters.forEach((resolve) => resolve(dataUrl));
+ const resolve = state.screenshotWaiters.get(requestId);
+ if (resolve) {
+ state.screenshotWaiters.delete(requestId);
+ resolve(dataUrl);
+ }
});
// Lazy visible-text reply. The ui_read tool emitted voice:ui:read-request;
@@ -311,8 +316,8 @@ export const registerVoiceHandlers = (socket) => {
state.uiWaiters = [];
waiters.forEach((resolve) => resolve(null));
// Same for any pending screenshot capture.
- const shotWaiters = state.screenshotWaiters;
- state.screenshotWaiters = [];
+ const shotWaiters = Array.from(state.screenshotWaiters.values());
+ state.screenshotWaiters.clear();
shotWaiters.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.
diff --git a/server/sockets/voice.test.js b/server/sockets/voice.test.js
index 3e11727b73..bde2360652 100644
--- a/server/sockets/voice.test.js
+++ b/server/sockets/voice.test.js
@@ -105,3 +105,21 @@ describe('voice:ui lazy-text socket handlers', () => {
expect(() => socket.fire('voice:ui:read-response', { requestId: 'missing', text: 'hi' })).not.toThrow();
});
});
+
+describe('voice:screenshot:result socket handler', () => {
+ it('registers the screenshot-result handler', () => {
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ expect(socket.has('voice:screenshot:result')).toBe(true);
+ });
+
+ it('tolerates malformed / unmatched screenshot-result payloads', () => {
+ const socket = makeFakeSocket();
+ registerVoiceHandlers(socket);
+ expect(() => socket.fire('voice:screenshot:result', null)).not.toThrow();
+ expect(() => socket.fire('voice:screenshot:result', 'nope')).not.toThrow();
+ // Unmatched requestId — no waiter parked for it, must not throw (and must
+ // not resolve a stale waiter, which is the whole point of the id keying).
+ expect(() => socket.fire('voice:screenshot:result', { requestId: 'missing', dataUrl: 'data:image/png;base64,AAAA' })).not.toThrow();
+ });
+});