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): read calendar isAllDay (cache field, not allDay), NaN-safe limit clamp helper, snapshot-correlated ui:read-response cache

Adam Eivyfcf8203e9495
diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.js
index 9868b8beba..174a457173 100644
--- a/server/services/voice/pipeline.js
+++ b/server/services/voice/pipeline.js
@@ -150,6 +150,12 @@ const requestUiText = (state, emit, signal, timeoutMs = UI_TEXT_READ_TIMEOUT_MS)
if (!state || typeof emit !== 'function') { resolve(null); return; }
if (!(state.uiTextWaiters instanceof Map)) state.uiTextWaiters = new Map();
const requestId = `uitext_${++uiTextRequestSeq}`;
+ // Capture the snapshot this read is FOR. state.ui is replaced wholesale on
+ // every voice:ui:index, so a reference change means the user navigated (or a
+ // new index arrived) between request and response — in that case we must NOT
+ // cache the now-stale text onto the current snapshot (a later same-turn
+ // ui_read would otherwise read the wrong page's text).
+ const snapshotAtRequest = state.ui;
let done = false;
const finish = (value) => {
if (done) return;
@@ -159,6 +165,10 @@ const requestUiText = (state, emit, signal, timeoutMs = UI_TEXT_READ_TIMEOUT_MS)
// 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);
+ // Cache onto the snapshot only when it's STILL the one we requested for, so
+ // a follow-up same-turn ui_read on the same page skips another round-trip
+ // without risking a stale-page overwrite.
+ if (value !== null && state.ui && state.ui === snapshotAtRequest) state.ui.text = value;
resolve(value);
};
const onAbort = () => finish(null);
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index 9b0155e9c5..a1bbdb7ed9 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -24,6 +24,16 @@ import { isDestructiveLabel, buildPending } from './confirmGate.js';
const DAILY_LOG_PATH = '/brain/daily-log';
+// Clamp an LLM-supplied `limit` to [1, hi]. Tool-call args can arrive as
+// strings ("10") or non-numeric junk; `Math.min(hi, "abc")` is NaN, which would
+// silently slice an empty result. Coerce with Number() and fall back to
+// `fallback` when the value isn't a finite positive number (preserving the old
+// `limit || fallback` behavior for 0 / blank).
+const clampLimit = (raw, fallback, hi) => {
+ const n = Number(raw);
+ return Math.max(1, Math.min(hi, Number.isFinite(n) && n > 0 ? n : fallback));
+};
+
// ----- Pipeline stage navigation helpers (used by pipeline_next_stage etc) -----
const PIPELINE_STAGE_LABELS = {
idea: 'Idea',
@@ -367,8 +377,10 @@ const findGoalByQuery = (goals, query) => {
// ----- Calendar helpers (calendar_today / calendar_next) -----
// The calendar cache stores ISO `startTime`/`endTime` (UTC or with offset) plus
-// `title`, `location`, and `allDay`. We format times in the user's TZ so a
-// spoken "10 AM" matches the wall clock, not the server's UTC.
+// `title`, `location`, and `isAllDay` (the cache field name — see
+// calendarGoogleSync.js / calendarApiSync.js; the tool's own output uses
+// `allDay`). We format times in the user's TZ so a spoken "10 AM" matches the
+// wall clock, not the server's UTC.
const formatEventTime = (iso, tz) => {
if (typeof iso !== 'string' || !iso) return null;
const d = new Date(iso);
@@ -377,7 +389,7 @@ const formatEventTime = (iso, tz) => {
};
const summarizeEvent = (e, tz) => {
const start = formatEventTime(e?.startTime, tz);
- const when = e?.allDay ? 'all day' : (start || 'time TBD');
+ const when = e?.isAllDay ? 'all day' : (start || 'time TBD');
const loc = e?.location ? ` at ${e.location}` : '';
return `${e?.title || 'Untitled event'} (${when})${loc}`;
};
@@ -473,7 +485,7 @@ const TOOLS = [
// `String.includes('')` matches everything, so an all-whitespace query
// would return unrelated entries — reject instead of surprising the user.
if (!q) throw new Error('query must not be empty');
- const max = Math.max(1, Math.min(10, limit || 5));
+ const max = clampLimit(limit, 5, 10);
// Load a reasonable window — the brain inbox is small enough that an
// in-memory filter is fine and avoids a second storage pass for ranking.
const records = await getInboxLog({ limit: 200 });
@@ -613,7 +625,7 @@ const TOOLS = [
},
},
execute: async ({ limit = 5 } = {}) => {
- const max = Math.max(1, Math.min(10, limit || 5));
+ const max = clampLimit(limit, 5, 10);
const records = await getInboxLog({ limit: max });
const items = records.map((r) => ({
date: (r.capturedAt || '').slice(0, 10),
@@ -676,7 +688,7 @@ const TOOLS = [
},
},
execute: async ({ limit = 10 } = {}) => {
- const max = Math.max(1, Math.min(20, limit || 10));
+ const max = clampLimit(limit, 10, 20);
const data = await getGoals();
const active = (data.goals || []).filter((g) => g.status === 'active' || !g.status);
active.sort((a, b) => (b.urgency ?? 0) - (a.urgency ?? 0));
@@ -840,7 +852,7 @@ const TOOLS = [
},
},
execute: async ({ limit = 5 } = {}) => {
- const max = Math.max(1, Math.min(10, limit || 5));
+ const max = clampLimit(limit, 5, 10);
const [items, feeds] = await Promise.all([getItems({ unreadOnly: true }), getFeeds()]);
const feedName = (id) => feeds.find((f) => f.id === id)?.title || 'feed';
const picks = items.slice(0, max).map((i) => ({
@@ -1503,7 +1515,7 @@ const TOOLS = [
},
},
execute: async ({ limit = 10 } = {}) => {
- const max = Math.max(1, Math.min(20, limit || 10));
+ const max = clampLimit(limit, 10, 20);
const tz = await getUserTimezone();
const today = todayInTimezone(tz); // YYYY-MM-DD in the user's TZ
// The server runs TZ=UTC and event startTimes carry an offset/Z, so the
@@ -1522,9 +1534,9 @@ const TOOLS = [
const items = events.map((e) => ({
title: e.title,
startTime: e.startTime,
- time: e.allDay ? 'all day' : formatEventTime(e.startTime, tz),
+ time: e.isAllDay ? 'all day' : formatEventTime(e.startTime, tz),
location: e.location || null,
- allDay: !!e.allDay,
+ allDay: !!e.isAllDay,
}));
return {
ok: true,
@@ -1570,7 +1582,7 @@ const TOOLS = [
}
const startDate = new Date(next.startTime);
const dayLabel = new Intl.DateTimeFormat('en-US', { timeZone: tz, weekday: 'long', month: 'long', day: 'numeric' }).format(startDate);
- const timeLabel = next.allDay ? 'all day' : (formatEventTime(next.startTime, tz) || 'time TBD');
+ const timeLabel = next.isAllDay ? 'all day' : (formatEventTime(next.startTime, tz) || 'time TBD');
const loc = next.location ? ` at ${next.location}` : '';
return {
ok: true,
@@ -1578,7 +1590,7 @@ const TOOLS = [
title: next.title,
startTime: next.startTime,
location: next.location || null,
- allDay: !!next.allDay,
+ allDay: !!next.isAllDay,
summary: `Next up: ${next.title || 'Untitled event'} — ${dayLabel}, ${timeLabel}${loc}.`,
};
},
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index c4300dca0d..4828ee05a8 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -922,8 +922,8 @@ describe('pipeline stage navigation tools', () => {
describe('calendar_today', () => {
it('summarizes today\'s events', async () => {
calendarEventsRef.value = [
- { title: 'Standup', startTime: '2026-04-17T17:00:00Z', location: 'Zoom', allDay: false },
- { title: 'All-hands', startTime: '2026-04-17T20:00:00Z', allDay: false },
+ { title: 'Standup', startTime: '2026-04-17T17:00:00Z', location: 'Zoom', isAllDay: false },
+ { title: 'All-hands', startTime: '2026-04-17T20:00:00Z', isAllDay: false },
];
const r = await dispatchTool('calendar_today', {});
expect(r.ok).toBe(true);
@@ -945,7 +945,7 @@ describe('calendar_today', () => {
describe('calendar_next', () => {
it('returns the soonest future event', async () => {
const soon = new Date(Date.now() + 3600_000).toISOString();
- calendarEventsRef.value = [{ title: 'Dentist', startTime: soon, allDay: false }];
+ calendarEventsRef.value = [{ title: 'Dentist', startTime: soon, isAllDay: false }];
const r = await dispatchTool('calendar_next', {});
expect(r.ok).toBe(true);
expect(r.found).toBe(true);
@@ -966,7 +966,7 @@ describe('calendar_next', () => {
// past but endTime is in the future, matching calendarSync's range.
const startedAgo = new Date(Date.now() - 1800_000).toISOString();
const endsSoon = new Date(Date.now() + 1800_000).toISOString();
- calendarEventsRef.value = [{ title: 'Standup (in progress)', startTime: startedAgo, endTime: endsSoon, allDay: false }];
+ calendarEventsRef.value = [{ title: 'Standup (in progress)', startTime: startedAgo, endTime: endsSoon, isAllDay: false }];
const r = await dispatchTool('calendar_next', {});
expect(r.found).toBe(true);
expect(r.title).toBe('Standup (in progress)');
@@ -977,7 +977,7 @@ describe('calendar_next', () => {
// endTime later today they must still surface as "next".
const pastMidnight = new Date(Date.now() - 8 * 3600_000).toISOString();
const endOfDay = new Date(Date.now() + 8 * 3600_000).toISOString();
- calendarEventsRef.value = [{ title: 'Conference Day', startTime: pastMidnight, endTime: endOfDay, allDay: true }];
+ calendarEventsRef.value = [{ title: 'Conference Day', startTime: pastMidnight, endTime: endOfDay, isAllDay: true }];
const r = await dispatchTool('calendar_next', {});
expect(r.found).toBe(true);
expect(r.title).toBe('Conference Day');
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index 236cde0771..9d61da78ad 100644
--- a/server/sockets/voice.js
+++ b/server/sockets/voice.js
@@ -302,12 +302,10 @@ export const registerVoiceHandlers = (socket) => {
const resolve = state.uiTextWaiters.get(requestId);
if (resolve) {
state.uiTextWaiters.delete(requestId);
- // Cache on the current ui snapshot too, so a follow-up read in the same
- // turn (same page) doesn't need another round-trip. Only cache for a
- // MATCHED response — a late/unmatched reply (after the read timed out or
- // the user navigated) must not overwrite the live snapshot with stale
- // text that a subsequent ui_read would then return.
- if (state.ui && capped !== null) state.ui.text = capped;
+ // Resolve only — caching onto state.ui.text happens inside requestUiText
+ // (pipeline.js), which captured the snapshot this read was issued for and
+ // caches only if it's still current. Caching here couldn't tell whether
+ // the snapshot changed (navigation) between request and response.
resolve(capped);
}
});