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

feat([voice-tool-edge-hardening]): persist + dedup voice timers

Adam Eivy3d794e5f1e60
diff --git a/server/index.js b/server/index.js
index 030bcac31e..8fedce32ea 100644
--- a/server/index.js
+++ b/server/index.js
@@ -58,6 +58,7 @@ import lmstudioRoutes from './routes/lmstudio.js';
import voiceRoutes from './routes/voice.js';
import { getVoiceConfig } from './services/voice/config.js';
import { reconcile as reconcileVoice } from './services/voice/bootstrap.js';
+import { initVoiceTimers } from './services/voice/timers.js';
import browserRoutes from './routes/browser.js';
import moltworldToolsRoutes from './routes/moltworldTools.js';
import moltworldWsRoutes from './routes/moltworldWs.js';
@@ -502,6 +503,9 @@ getInitSettings().then(s => {
}).catch(err => console.error(`❌ Telegram settings read failed: ${err.message}`));
// Reconcile voice stack (start portos-whisper if voice.enabled)
getVoiceConfig().then(reconcileVoice).catch(err => console.error(`❌ Voice reconcile failed: ${err.message}`));
+// Re-arm any voice timers that survived a restart (independent of voice.enabled —
+// a pending reminder should still fire even if voice is currently off).
+initVoiceTimers().catch(err => console.error(`❌ Voice timer init failed: ${err.message}`));
// Check for update completion marker from a previous update cycle
const updateMarkerPath = join(PATHS.data, 'update-complete.json');
const removeMarker = () => unlink(updateMarkerPath).catch(e => {
diff --git a/server/services/voice/timers.js b/server/services/voice/timers.js
new file mode 100644
index 0000000000..9f4d25b4ac
--- /dev/null
+++ b/server/services/voice/timers.js
@@ -0,0 +1,151 @@
+// Persistent, dedup-aware one-shot timers for the voice CoS `timer_set` tool.
+//
+// A bare in-memory `setTimeout` has two edge-case failures (xhigh review,
+// 2026-05-25): it's lost silently when the server restarts before the timer
+// fires, and an LLM re-issuing the same `timer_set` call inside one reasoning
+// loop arms a second identical timer → the user hears the reminder twice.
+//
+// This module fixes both: pending timers are snapshotted to disk (re-armed at
+// boot, firing any that came due while the process was down), and a near-
+// identical `(label, fireAt)` request is collapsed onto the existing timer.
+
+import { randomUUID } from 'crypto';
+import { join } from 'path';
+import { PATHS, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
+import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from '../notifications.js';
+
+const STORE_PATH = join(PATHS.data, 'voice-timers.json');
+const MAX_DURATION_MS = 24 * 60 * 60 * 1000; // mirror the tool's 24h cap
+
+// Two `timer_set` calls with the same label whose fire times land within this
+// window are treated as one. An LLM re-issuing the tool inside a single
+// reasoning loop produces `fireAt` values milliseconds apart, so a few seconds
+// of tolerance collapses the duplicate without merging two genuinely distinct
+// reminders a user set seconds apart (harmless either way — the worst case is
+// one notification instead of two).
+const DEDUP_WINDOW_MS = 10_000;
+
+// id -> { id, label, fireAt, createdAt, handle }. Authoritative in-memory
+// state; the JSON file is just a snapshot of it, so a read-modify-write race
+// between a fire (remove) and a schedule (add) can't drop a timer.
+const active = new Map();
+
+// Serialize snapshot writes onto a single tail so a fire and a schedule can't
+// clobber each other's atomicWrite.
+let writeTail = Promise.resolve();
+function persist() {
+ const timers = [...active.values()].map(({ handle, ...rec }) => rec);
+ writeTail = writeTail.then(() =>
+ atomicWrite(STORE_PATH, { version: 1, timers }).catch((err) =>
+ console.error(`❌ voice-timer persist failed: ${err.message}`)
+ )
+ );
+ return writeTail;
+}
+
+// Raise the reminder. Runs outside the request lifecycle, so the write is
+// guarded (per CLAUDE.md) — a thrown notification write can't crash the process.
+function notify(timer, { overdue = false } = {}) {
+ return addNotification({
+ type: NOTIFICATION_TYPES.AGENT_WARNING,
+ title: `⏰ ${timer.label}`,
+ description: overdue
+ ? 'Timer you set went off while PortOS was restarting.'
+ : 'Timer you set is up.',
+ priority: PRIORITY_LEVELS.HIGH,
+ metadata: { source: 'voice-timer', timerId: timer.id },
+ }).catch((err) => {
+ console.error(`❌ voice-timer notification failed: ${err.message}`);
+ });
+}
+
+// Fire a timer: drop it from state first (so any concurrent persist reflects the
+// removal), then notify.
+async function fire(timer) {
+ active.delete(timer.id);
+ await persist();
+ await notify(timer);
+}
+
+// Arm a Node timer for a still-pending record. Durations are capped at 24h, well
+// within setTimeout's max delay. `unref` so a lone pending timer never keeps the
+// process (or a test runner) alive on its own.
+function arm(timer) {
+ const delay = Math.max(0, timer.fireAt - Date.now());
+ timer.handle = setTimeout(() => {
+ fire(timer).catch((err) => console.error(`❌ voice-timer fire failed: ${err.message}`));
+ }, delay);
+ timer.handle.unref?.();
+ active.set(timer.id, timer);
+}
+
+// Find an already-armed timer that a new (label, fireAt) request duplicates.
+function findDuplicate(label, fireAt) {
+ for (const t of active.values()) {
+ if (t.label === label && Math.abs(t.fireAt - fireAt) <= DEDUP_WINDOW_MS) return t;
+ }
+ return null;
+}
+
+/**
+ * Schedule a one-shot timer. Returns `{ id, fireAt, deduped }` — `deduped: true`
+ * means an equivalent timer was already armed and this call was a no-op.
+ * Returns `null` for an out-of-range duration (callers validate first; this is
+ * a defensive guard so a bad value never arms a runaway/zero timer).
+ */
+export function scheduleTimer({ totalMs, label } = {}) {
+ if (!Number.isFinite(totalMs) || totalMs < 1000 || totalMs > MAX_DURATION_MS) return null;
+ const fireAt = Date.now() + totalMs;
+ const dup = findDuplicate(label, fireAt);
+ if (dup) return { id: dup.id, fireAt: dup.fireAt, deduped: true };
+ const timer = { id: randomUUID(), label, fireAt, createdAt: Date.now() };
+ arm(timer);
+ persist();
+ return { id: timer.id, fireAt, deduped: false };
+}
+
+// Idempotency guard so a double-call (re-init, tests) can't double-arm.
+let initialized = false;
+
+/**
+ * Re-arm persisted timers at boot. Any that came due while the process was down
+ * fire immediately (once); the rest re-arm for their remaining delay. The store
+ * is then rewritten with only the still-pending timers.
+ */
+export async function initVoiceTimers({ force = false } = {}) {
+ if (initialized && !force) return { skipped: true };
+ initialized = true;
+ const stored = await readJSONFile(STORE_PATH, { version: 1, timers: [] });
+ const list = Array.isArray(stored?.timers) ? stored.timers : [];
+ const now = Date.now();
+ let armed = 0;
+ let fired = 0;
+ for (const rec of list) {
+ if (!rec || typeof rec.fireAt !== 'number' || typeof rec.label !== 'string') continue;
+ const timer = {
+ id: typeof rec.id === 'string' && rec.id ? rec.id : randomUUID(),
+ label: rec.label,
+ fireAt: rec.fireAt,
+ createdAt: typeof rec.createdAt === 'number' ? rec.createdAt : now,
+ };
+ if (timer.fireAt <= now) {
+ // Overdue — notify once. Not added to `active`, so the post-loop persist
+ // drops it from the store.
+ await notify(timer, { overdue: true });
+ fired += 1;
+ } else {
+ arm(timer);
+ armed += 1;
+ }
+ }
+ await persist();
+ if (armed || fired) console.log(`⏰ voice-timers: re-armed ${armed}, fired ${fired} overdue`);
+ return { armed, fired };
+}
+
+// Test helper — clear all in-memory timers + handles and reset the init guard.
+export function __resetVoiceTimers() {
+ for (const t of active.values()) clearTimeout(t.handle);
+ active.clear();
+ initialized = false;
+}
diff --git a/server/services/voice/timers.test.js b/server/services/voice/timers.test.js
new file mode 100644
index 0000000000..71dfe71736
--- /dev/null
+++ b/server/services/voice/timers.test.js
@@ -0,0 +1,129 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// In-memory stand-ins for the disk store + notification sink so the module's
+// persistence/fire paths run without touching the filesystem.
+const { atomicWriteMock, readJSONFileMock, storeRef } = vi.hoisted(() => {
+ const storeRef = { value: { version: 1, timers: [] } };
+ return {
+ storeRef,
+ atomicWriteMock: vi.fn(async (_path, data) => { storeRef.value = data; }),
+ readJSONFileMock: vi.fn(async () => storeRef.value),
+ };
+});
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { data: '/tmp/portos-voice-timers-test' },
+ atomicWrite: (...a) => atomicWriteMock(...a),
+ readJSONFile: (...a) => readJSONFileMock(...a),
+}));
+const addNotificationMock = vi.hoisted(() => vi.fn(async () => ({ id: 'notif-1' })));
+vi.mock('../notifications.js', () => ({
+ addNotification: (...a) => addNotificationMock(...a),
+ NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },
+ PRIORITY_LEVELS: { HIGH: 'high' },
+}));
+
+const { scheduleTimer, initVoiceTimers, __resetVoiceTimers } = await import('./timers.js');
+
+const tick = () => Promise.resolve(); // flush a microtask (persist chain)
+
+beforeEach(() => {
+ __resetVoiceTimers();
+ storeRef.value = { version: 1, timers: [] };
+ atomicWriteMock.mockClear();
+ readJSONFileMock.mockClear();
+ addNotificationMock.mockClear();
+});
+
+describe('scheduleTimer', () => {
+ it('arms a timer that raises a notification when it elapses', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-05-26T12:00:00Z'));
+ const res = scheduleTimer({ totalMs: 600000, label: 'call mom' });
+ expect(res.deduped).toBe(false);
+ expect(typeof res.id).toBe('string');
+ await vi.advanceTimersByTimeAsync(600000);
+ expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({
+ title: '⏰ call mom',
+ priority: 'high',
+ metadata: expect.objectContaining({ source: 'voice-timer' }),
+ }));
+ vi.useRealTimers();
+ });
+
+ it('persists a pending timer (handle stripped) and clears it after firing', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-05-26T12:00:00Z'));
+ scheduleTimer({ totalMs: 600000, label: 'tea' });
+ await tick(); // let the schedule's persist() write run
+ const afterSchedule = atomicWriteMock.mock.calls.at(-1)[1];
+ expect(afterSchedule.timers).toHaveLength(1);
+ expect(afterSchedule.timers[0]).toMatchObject({ label: 'tea' });
+ expect(afterSchedule.timers[0].handle).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(600000);
+ const afterFire = atomicWriteMock.mock.calls.at(-1)[1];
+ expect(afterFire.timers).toHaveLength(0);
+ vi.useRealTimers();
+ });
+
+ it('rejects an out-of-range duration without arming anything', () => {
+ vi.useFakeTimers();
+ expect(scheduleTimer({ totalMs: 500, label: 'too short' })).toBeNull();
+ expect(scheduleTimer({ totalMs: 25 * 60 * 60 * 1000, label: 'too long' })).toBeNull();
+ expect(scheduleTimer({ totalMs: NaN, label: 'nan' })).toBeNull();
+ vi.useRealTimers();
+ });
+
+ it('dedups a re-issued identical timer but keeps a distinct label / out-of-window one', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-05-26T12:00:00Z'));
+ const a = scheduleTimer({ totalMs: 600000, label: 'tea' });
+ const b = scheduleTimer({ totalMs: 600000, label: 'tea' });
+ expect(b.deduped).toBe(true);
+ expect(b.id).toBe(a.id);
+
+ // Different label → not a duplicate.
+ expect(scheduleTimer({ totalMs: 600000, label: 'eggs' }).deduped).toBe(false);
+
+ // Same label but fireAt now 20s past the original → outside the dedup
+ // window → a genuinely new timer.
+ vi.advanceTimersByTime(20000);
+ expect(scheduleTimer({ totalMs: 600000, label: 'tea' }).deduped).toBe(false);
+ vi.useRealTimers();
+ });
+});
+
+describe('initVoiceTimers', () => {
+ it('fires overdue timers once and re-arms future ones', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-05-26T12:00:00Z'));
+ const now = Date.now();
+ storeRef.value = {
+ version: 1,
+ timers: [
+ { id: 'past', label: 'overdue', fireAt: now - 1000, createdAt: now - 600000 },
+ { id: 'future', label: 'soon', fireAt: now + 300000, createdAt: now },
+ { id: 'bad', label: 42, fireAt: now + 1000 }, // malformed label → skipped
+ ],
+ };
+ const res = await initVoiceTimers({ force: true });
+ expect(res).toEqual({ armed: 1, fired: 1 });
+ expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({ title: '⏰ overdue' }));
+
+ // Store rewritten with only the still-pending future timer.
+ const persisted = atomicWriteMock.mock.calls.at(-1)[1];
+ expect(persisted.timers.map((t) => t.id)).toEqual(['future']);
+
+ // The future timer fires when its time comes.
+ addNotificationMock.mockClear();
+ await vi.advanceTimersByTimeAsync(300000);
+ expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({ title: '⏰ soon' }));
+ vi.useRealTimers();
+ });
+
+ it('is idempotent unless forced', async () => {
+ const first = await initVoiceTimers();
+ expect(first).toEqual({ armed: 0, fired: 0 });
+ const second = await initVoiceTimers();
+ expect(second).toEqual({ skipped: true });
+ });
+});
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index 3a55883f54..817c7ce224 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -11,8 +11,8 @@ import { getGoals, updateGoalProgress, addProgressEntry } from '../identity.js';
import { listProcesses, restartApp } from '../pm2.js';
import { getItems, getFeeds, markItemRead, markAllRead } from '../feeds.js';
import { getEvents as getCalendarEvents } from '../calendarSync.js';
-import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from '../notifications.js';
import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
+import { scheduleTimer } from './timers.js';
import { getUserTimezone, todayInTimezone, getLocalParts, getUtcOffsetMs } from '../../lib/timezone.js';
import * as journal from '../brainJournal.js';
import { resolveNavCommand, normalizeLabel } from '../../lib/navManifest.js';
@@ -1721,23 +1721,15 @@ const TOOLS = [
return { ok: false, summary: 'Timers are capped at 24 hours. For longer reminders, add a calendar event.' };
}
const trimmedLabel = typeof label === 'string' && label.trim() ? label.trim().slice(0, 200) : 'Timer';
- // setTimeout runs OUTSIDE the request lifecycle — guard the async body so
- // a thrown notification write can't crash the process (per CLAUDE.md).
- setTimeout(() => {
- addNotification({
- type: NOTIFICATION_TYPES.AGENT_WARNING,
- title: `⏰ ${trimmedLabel}`,
- description: `Timer you set is up.`,
- priority: PRIORITY_LEVELS.HIGH,
- }).catch((err) => {
- console.error(`❌ timer_set notification failed: ${err.message}`);
- });
- }, totalMs);
+ // Delegate to the persistent scheduler — it survives a restart (re-armed
+ // at boot, overdue ones fired once) and dedups an LLM re-issuing the same
+ // timer inside one reasoning loop.
+ const scheduled = scheduleTimer({ totalMs, label: trimmedLabel });
const totalSecs = Math.round(totalMs / 1000);
const human = totalSecs >= 60
? `${Math.round(totalSecs / 60)} minute${Math.round(totalSecs / 60) === 1 ? '' : 's'}`
: `${totalSecs} second${totalSecs === 1 ? '' : 's'}`;
- console.log(`⏰ Timer set for ${human}: "${trimmedLabel}"`);
+ console.log(`⏰ Timer set for ${human}: "${trimmedLabel}"${scheduled?.deduped ? ' (deduped — already armed)' : ''}`);
return {
ok: true,
durationMs: totalMs,
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index ea3bdc9abe..f264a49e9e 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -36,6 +36,13 @@ vi.mock('../notifications.js', () => ({
NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },
PRIORITY_LEVELS: { HIGH: 'high' },
}));
+// timer_set delegates scheduling/persistence to ./timers.js — stub it so this
+// unit test stays pure dispatch/validation (timers.test.js covers firing,
+// persistence, and dedup).
+const scheduleTimerMock = vi.fn(() => ({ id: 'timer-1', fireAt: Date.now() + 600000, deduped: false }));
+vi.mock('./timers.js', () => ({
+ scheduleTimer: (...args) => scheduleTimerMock(...args),
+}));
// Open-Meteo fetch — controllable per-test via weatherFetchRef.
const weatherFetchRef = { value: { ok: true, json: async () => ({ current: { temperature_2m: 64, weather_code: 3 } }) } };
vi.mock('../../lib/fetchWithTimeout.js', () => ({
@@ -1097,16 +1104,13 @@ describe('timer_set', () => {
expect(r.ok).toBe(false);
expect(r.summary).toMatch(/capped at 24 hours/);
});
- it('sets a timer and schedules a notification', async () => {
- vi.useFakeTimers();
- addNotificationMock.mockClear();
+ it('delegates a valid timer to the persistent scheduler', async () => {
+ scheduleTimerMock.mockClear();
const r = await dispatchTool('timer_set', { minutes: 10, label: 'call mom' });
expect(r.ok).toBe(true);
expect(r.durationMs).toBe(600000);
expect(r.summary).toMatch(/Timer set for 10 minutes/);
- await vi.advanceTimersByTimeAsync(600000);
- expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({ title: expect.stringMatching(/call mom/) }));
- vi.useRealTimers();
+ expect(scheduleTimerMock).toHaveBeenCalledWith({ totalMs: 600000, label: 'call mom' });
});
});