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

voice: add calendar/weather/timer/workout tools + ui_describe_visually vision fallback

Adam Eivyac9f5647505d
diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsx
index 5f804ae288..3966894d8e 100644
--- a/client/src/components/voice/VoiceWidget.jsx
+++ b/client/src/components/voice/VoiceWidget.jsx
@@ -5,7 +5,7 @@ import {
startCapture, stopCapture, interrupt, resetConversation, sendText, onVoiceEvent, isCapturing,
startContinuous, stopContinuous, isContinuous, whenPlaybackDrained, getVadLevel,
webSpeechSupported, startWebSpeechCapture, stopWebSpeechCapture, isWebSpeechCapturing,
- onProactiveSpeech,
+ onProactiveSpeech, captureScreenForVision, sendScreenshotResult,
} from '../../services/voiceClient';
import { getVoiceConfig } from '../../services/apiVoice';
import toast from '../ui/Toast';
@@ -220,6 +220,15 @@ export default function VoiceWidget() {
if (!res.ok) toast.error(`Voice: couldn't toggle "${d?.target?.label}"`);
else pushUiIndexAfterAction();
}),
+ // ui_describe_visually: server asks the client to screenshot the active
+ // 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 () => {
+ const dataUrl = await captureScreenForVision();
+ if (!dataUrl) toast('Voice: screen capture was blocked or unavailable.', { icon: '📷' });
+ sendScreenshotResult(dataUrl);
+ }),
];
return () => offs.forEach((off) => off());
}, [enabled, navigate]);
diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.js
index 725efc5bb4..68cb1add4a 100644
--- a/client/src/services/voiceClient.js
+++ b/client/src/services/voiceClient.js
@@ -462,6 +462,51 @@ export const onVoiceEvent = (event, handler) => {
return () => socket.off(event, handler);
};
+// Capture the current screen/tab as a JPEG data URL for the voice agent's
+// ui_describe_visually tool. Uses getDisplayMedia — the only browser-native way
+// to grab WebGL/canvas content (CyberCity, charts) without a heavy DOM-to-canvas
+// dependency. The browser prompts for screen-capture permission; the user picks
+// the tab/window. Returns null on denial or any failure so the caller can
+// gracefully tell the user it couldn't see the screen.
+export const captureScreenForVision = async () => {
+ if (!navigator.mediaDevices?.getDisplayMedia || typeof document === 'undefined') return null;
+ let mediaStream = null;
+ try {
+ mediaStream = await navigator.mediaDevices.getDisplayMedia({
+ video: { displaySurface: 'browser' },
+ audio: false,
+ });
+ const video = document.createElement('video');
+ video.srcObject = mediaStream;
+ video.muted = true;
+ await video.play();
+ // One frame is enough; give the decoder a tick to paint dimensions.
+ await new Promise((resolve) => setTimeout(resolve, 120));
+ const w = video.videoWidth || 1280;
+ const h = video.videoHeight || 720;
+ const canvas = document.createElement('canvas');
+ canvas.width = w;
+ canvas.height = h;
+ const cctx = canvas.getContext('2d');
+ if (!cctx) return null;
+ cctx.drawImage(video, 0, 0, w, h);
+ video.pause();
+ // JPEG @ 0.8 keeps the payload well under the server's 16 MB cap even at 4K.
+ return canvas.toDataURL('image/jpeg', 0.8);
+ } catch {
+ // User denied the prompt, or capture isn't available in this context.
+ return null;
+ } finally {
+ if (mediaStream) mediaStream.getTracks().forEach((t) => t.stop());
+ }
+};
+
+// 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 });
+};
+
export const playWav = (arrayBuffer) => enqueuePlay(arrayBuffer);
// Resolves once every currently-queued TTS chunk has finished playing locally.
diff --git a/server/routes/palette.js b/server/routes/palette.js
index b24f073cfd..a334ec5c8b 100644
--- a/server/routes/palette.js
+++ b/server/routes/palette.js
@@ -22,8 +22,10 @@ const router = Router();
// Palette-safe subset of voice tools. Excluded: DOM-driving ui_* tools
// (ui_click/ui_fill/ui_navigate need a live voice DOM context), dictation
// toggles (voice-widget state), daily_log_open (pushes a sideEffect HTTP
-// callers can't consume). ui_ask is the explicit exception — it has no DOM
-// dependency and runs the same askService pipeline a non-voice caller wants.
+// callers can't consume), and ui_describe_visually (needs the live voice
+// widget's screenshot round-trip — the palette has no screen-capture path).
+// ui_ask is the explicit exception — it has no DOM dependency and runs the
+// same askService pipeline a non-voice caller wants.
// pm2_restart is flagged destructive so the client can confirm.
const PALETTE_ACTIONS = [
{ id: 'brain_capture', label: 'Capture to Brain', section: 'Brain' },
@@ -35,7 +37,12 @@ const PALETTE_ACTIONS = [
{ id: 'meatspace_log_drink', label: 'Log a drink', section: 'Health' },
{ id: 'meatspace_log_nicotine', label: 'Log nicotine', section: 'Health' },
{ id: 'meatspace_log_weight', label: 'Log weight', section: 'Health' },
+ { id: 'meatspace_log_workout', label: 'Log a workout', section: 'Health' },
{ id: 'meatspace_summary_today', label: "Today's health summary", section: 'Health' },
+ { id: 'calendar_today', label: "Today's calendar", section: 'Calendar' },
+ { id: 'calendar_next', label: 'Next calendar event', section: 'Calendar' },
+ { id: 'weather_now', label: 'Current weather', section: 'System' },
+ { id: 'timer_set', label: 'Set a timer', section: 'System' },
{ id: 'feeds_digest', label: 'Feed digest', section: 'Feeds' },
{ id: 'pm2_status', label: 'PM2 status', section: 'System' },
{ id: 'pm2_restart', label: 'Restart a PM2 process', section: 'System', destructive: true },
diff --git a/server/routes/palette.test.js b/server/routes/palette.test.js
index 1ba4263662..07fee18b02 100644
--- a/server/routes/palette.test.js
+++ b/server/routes/palette.test.js
@@ -90,6 +90,22 @@ describe('GET /api/palette/manifest', () => {
expect(ids).toContain('ui_ask');
});
+ it('exposes the new user-invocable actions (calendar/weather/timer/workout)', async () => {
+ const res = await request(makeApp()).get('/api/palette/manifest');
+ const ids = res.body.actions.map((a) => a.id);
+ expect(ids).toContain('calendar_today');
+ expect(ids).toContain('calendar_next');
+ expect(ids).toContain('weather_now');
+ expect(ids).toContain('timer_set');
+ expect(ids).toContain('meatspace_log_workout');
+ });
+
+ it('keeps ui_describe_visually OFF the palette (no screenshot context)', async () => {
+ const res = await request(makeApp()).get('/api/palette/manifest');
+ const ids = res.body.actions.map((a) => a.id);
+ expect(ids).not.toContain('ui_describe_visually');
+ });
+
it('exposes ui_ask in the manifest with description hydrated from voice tools', async () => {
const res = await request(makeApp()).get('/api/palette/manifest');
const askAction = res.body.actions.find((a) => a.id === 'ui_ask');
diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.js
index cfc4508593..a6d8fb99a0 100644
--- a/server/services/meatspaceHealth.js
+++ b/server/services/meatspaceHealth.js
@@ -24,6 +24,7 @@ const BLOOD_TESTS_FILE = join(MEATSPACE_DIR, 'blood-tests.json');
const EPIGENETIC_TESTS_FILE = join(MEATSPACE_DIR, 'epigenetic-tests.json');
const EYES_FILE = join(MEATSPACE_DIR, 'eyes.json');
const HEALTH_METRICS_FILE = join(MEATSPACE_DIR, 'health-metrics.json');
+const WORKOUTS_FILE = join(MEATSPACE_DIR, 'workouts.json');
const byDate = (a, b) => (a.date || '').localeCompare(b.date || '');
@@ -180,6 +181,36 @@ export async function removeEyeExam(index) {
return removed;
}
+// === Workouts ===
+// Local PortOS store (not mirrored to MortalLoom — the iCloud store has no
+// `workouts` array key, and adding one would need a coordinated MortalLoom
+// schema change). Voice/CoS log workouts here via addWorkout().
+
+export async function getWorkouts() {
+ const data = await readJSONFile(WORKOUTS_FILE, { workouts: [] });
+ return (data.workouts || []).slice().sort(byDate);
+}
+
+export async function addWorkout({ date, type, durationMinutes, intensity, notes } = {}) {
+ const targetDate = date || new Date().toISOString().split('T')[0];
+ const trimmedType = typeof type === 'string' ? type.trim() : '';
+ if (!trimmedType) throw new Error('workout type is required');
+ const entry = {
+ date: targetDate,
+ type: trimmedType,
+ durationMinutes: Number.isFinite(durationMinutes) ? durationMinutes : null,
+ intensity: typeof intensity === 'string' && intensity.trim() ? intensity.trim() : null,
+ notes: typeof notes === 'string' && notes.trim() ? notes.trim() : null,
+ };
+ const data = await readJSONFile(WORKOUTS_FILE, { workouts: [] });
+ if (!Array.isArray(data.workouts)) data.workouts = [];
+ data.workouts.push(entry);
+ data.workouts.sort(byDate);
+ await writeLocal(WORKOUTS_FILE, data);
+ console.log(`🏋️ Workout logged: ${trimmedType}${entry.durationMinutes ? ` (${entry.durationMinutes}min)` : ''} for ${targetDate}`);
+ return entry;
+}
+
// === Blood Pressure ===
// Matches MortalLoom's HealthMetricEntry.bloodPressureSystolic/Diastolic (mmHg),
// upserted by date so multiple readings on the same day (e.g. from Apple Health
diff --git a/server/services/visionTest.js b/server/services/visionTest.js
index 31a627eb5a..168e8c5350 100644
--- a/server/services/visionTest.js
+++ b/server/services/visionTest.js
@@ -204,6 +204,40 @@ export async function testVision({ imagePath, prompt, expectedContent, providerI
};
}
+/**
+ * Describe an in-memory image (base64 data URL) using a provider's vision
+ * endpoint and return the model's text. Used by the voice agent's
+ * ui_describe_visually tool, which captures a screenshot client-side rather
+ * than reading one off disk. Throws on provider/transport errors so the caller
+ * can surface them.
+ * @param {Object} options
+ * @param {string} options.dataUrl - base64 image data URL (data:image/...;base64,...)
+ * @param {string} options.prompt - What to ask about the image
+ * @param {string} [options.providerId='lmstudio'] - Vision-capable API provider
+ * @param {string} [options.model] - Model override (defaults to provider default)
+ * @returns {Promise<string>} - The model's description text
+ */
+export async function describeImageDataUrl({ dataUrl, prompt, providerId = 'lmstudio', model }) {
+ if (typeof dataUrl !== 'string' || !dataUrl.startsWith('data:image/')) {
+ throw new Error('dataUrl must be a base64 image data URL');
+ }
+ const provider = await getProviderById(providerId);
+ if (!provider) throw new Error(`Provider '${providerId}' not found`);
+ if (provider.type !== 'api') throw new Error(`Provider '${providerId}' is not an API provider (type: ${provider.type})`);
+ const visionModel = model || provider.defaultModel;
+ if (!visionModel) throw new Error('No model specified and provider has no default model');
+
+ const apiResponse = await callVisionAPI({
+ endpoint: provider.endpoint,
+ apiKey: provider.apiKey,
+ model: visionModel,
+ imageDataUrl: dataUrl,
+ prompt: prompt || 'Describe what you see in this image.',
+ timeout: provider.timeout || DEFAULT_VISION_TIMEOUT_MS,
+ });
+ return apiResponse.choices?.[0]?.message?.content || '';
+}
+
/**
* Run a comprehensive vision test suite
* @param {string} [providerId='lmstudio'] - Provider to test
diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.js
index fe871a9f28..fd6e0ca85f 100644
--- a/server/services/voice/pipeline.js
+++ b/server/services/voice/pipeline.js
@@ -94,6 +94,41 @@ const waitForUiRefresh = (state, timeoutMs, signal) => new Promise((resolve) =>
state.uiWaiters.push(finish);
});
+// 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).
+// Resolves with the data URL or null on timeout/abort/denied-capture.
+const requestScreenshot = (emit, state, timeoutMs, signal) => new Promise((resolve) => {
+ if (!state) { resolve(null); return; }
+ if (!Array.isArray(state.screenshotWaiters)) state.screenshotWaiters = [];
+ 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);
+ 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', {});
+});
+
+// Send a captured image (base64 data URL) to the voice LLM provider's vision
+// endpoint and return the description text. Reuses visionTest's provider-aware
+// OpenAI-compatible /chat/completions call so we don't reimplement the request
+// shape. Lazy import keeps tools.js / the pipeline free of a hard vision dep.
+const describeScreenshot = async (dataUrl, prompt, cfg) => {
+ const { describeImageDataUrl } = await import('../visionTest.js');
+ const providerId = cfg?.llm?.provider || 'lmstudio';
+ const model = cfg?.llm?.model && cfg.llm.model !== 'auto' ? cfg.llm.model : undefined;
+ return describeImageDataUrl({ dataUrl, prompt, providerId, model });
+};
+
export { summarizeUi, shouldIncludeUi };
const buildSystemPrompt = (cfg) => {
@@ -514,7 +549,16 @@ export const runTurn = async ({ audio, text, mimeType, source, history = [], emi
const t0 = Date.now();
let result;
let args = {};
- const ctx = { sideEffects: [], state, signal };
+ const ctx = {
+ sideEffects: [],
+ 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),
+ };
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/tools.js b/server/services/voice/tools.js
index 67b0f1e5e6..045d62c9ab 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -6,11 +6,14 @@ import { captureThought, getInboxLog } from '../brain.js';
import { NAVIGABLE_STAGE_IDS as PIPELINE_STAGE_IDS } from '../pipeline/issues.js';
import { logDrink, getAlcoholSummary } from '../meatspaceAlcohol.js';
import { logNicotine, getNicotineSummary } from '../meatspaceNicotine.js';
-import { addBodyEntry } from '../meatspaceHealth.js';
+import { addBodyEntry, addWorkout } from '../meatspaceHealth.js';
import { getGoals, updateGoalProgress, addProgressEntry } from '../identity.js';
import { listProcesses, restartApp } from '../pm2.js';
import { getItems, getFeeds, markItemRead, markAllRead } from '../feeds.js';
-import { getUserTimezone, todayInTimezone, getLocalParts } from '../../lib/timezone.js';
+import { getEvents as getCalendarEvents } from '../calendarSync.js';
+import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from '../notifications.js';
+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
+import { getUserTimezone, todayInTimezone, getLocalParts, getUtcOffsetMs } from '../../lib/timezone.js';
import * as journal from '../brainJournal.js';
import { resolveNavCommand, normalizeLabel } from '../../lib/navManifest.js';
import { runAsk, VALID_MODES as ASK_VALID_MODES } from '../askService.js';
@@ -160,6 +163,12 @@ const TOOL_GROUPS = {
meatspace_log_nicotine: 'meatspace',
meatspace_summary_today: 'meatspace',
meatspace_log_weight: 'meatspace',
+ meatspace_log_workout: 'meatspace',
+ calendar_today: 'calendar',
+ calendar_next: 'calendar',
+ weather_now: 'weather',
+ timer_set: 'timer',
+ ui_describe_visually: 'vision',
goal_list: 'goals',
goal_update_progress: 'goals',
goal_log_note: 'goals',
@@ -205,7 +214,21 @@ const GROUP_INTENT = {
// "jot", "file" — without which moving brain_capture out of the always-on
// set would break "remember to buy milk" style turns.
brain: /\b(search|find|look ?up|recall|what did I (?:say|write|note)|brain|inbox|capture|remember|remind me|jot|note (?:that|to|down)|save (?:this|that)|file (?:this|that|it)|add (?:this|that|it) to (?:my )?(?:brain|inbox|notes?))\b/i,
- meatspace: /\b(drink|drank|beer|wine|whiskey|shot|cocktail|cigarette|vape|pouch|nicotine|weigh|pound|kilo|kg|smoke|smoking|how am I|summary today|log (?:a|my) (?:drink|weight|nicotine))\b/i,
+ meatspace: /\b(drink|drank|beer|wine|whiskey|shot|cocktail|cigarette|vape|pouch|nicotine|weigh|pound|kilo|kg|smoke|smoking|workout|exercise|exercised|run|ran|jog|yoga|lift(?:ed|ing)?|cardio|gym|cycling|cycled|swim|swam|how am I|summary today|log (?:a|my) (?:drink|weight|nicotine|workout))\b/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.
+ calendar: /\b(calendar|agenda|meeting|appointment|event)s?\b|\bwhat(?:'s| is| do i have)?\b[^.!?\n]{0,30}\b(today|next|coming up|upcoming|scheduled|on my (?:plate|schedule|calendar))\b|\bwhat'?s next\b/i,
+ // Weather — "what's the weather", "is it raining", "how hot/cold",
+ // "temperature outside", "forecast".
+ weather: /\b(weather|forecast|temperature|raining|snowing|sunny|cloudy|how (?:hot|cold|warm)|degrees? (?:out|outside))\b/i,
+ // Timers / reminders — "set a timer", "remind me in N minutes", "ping me in".
+ timer: /\b(set a timer|start a timer|timer for|remind me (?:in|to)|ping me in|alarm|countdown|wake me)\b/i,
+ // Visual description — needs a vision model on a screenshot. "what's on this
+ // chart/graph", "describe this", "what am I looking at", "what does this
+ // look like". Kept distinct from `ui` (text read) so the LLM can choose
+ // ui_read vs ui_describe_visually.
+ vision: /\b(chart|graph|diagram|cyber ?city|3d|render(?:ing)?|visualization|picture|image|screenshot)\b|\b(?:what(?:'s| does| am i)?|describe)\b[^.!?\n]{0,30}\b(?:look(?:ing|s)? like|on (?:this|the) (?:chart|graph|screen|map)|visual(?:ly)?)\b/i,
goals: /\b(goals?|progress|objective)\b/i,
system: /\b(restart|crash(?:ed)?|pm2|process|service|is.*(?:running|down|up)|status)\b/i,
// "mark.*read" / "mark.*unread" pairs feeds_mark_read with feeds_digest:
@@ -331,6 +354,46 @@ const findGoalByQuery = (goals, query) => {
return { match: scored[0].goal, candidates: scored.slice(0, 4).map((s) => s.goal) };
};
+// ----- 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.
+const formatEventTime = (iso, tz) => {
+ if (typeof iso !== 'string' || !iso) return null;
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return null;
+ return new Intl.DateTimeFormat('en-US', { timeZone: tz, hour: 'numeric', minute: '2-digit' }).format(d);
+};
+const summarizeEvent = (e, tz) => {
+ const start = formatEventTime(e?.startTime, tz);
+ const when = e?.allDay ? 'all day' : (start || 'time TBD');
+ const loc = e?.location ? ` at ${e.location}` : '';
+ return `${e?.title || 'Untitled event'} (${when})${loc}`;
+};
+
+// ----- Weather helpers (weather_now) -----
+// WMO weather interpretation codes → short spoken text. Open-Meteo returns the
+// integer `weather_code`; this small table avoids pulling in a weather lib.
+const WEATHER_CODES = {
+ 0: 'clear sky',
+ 1: 'mainly clear', 2: 'partly cloudy', 3: 'overcast',
+ 45: 'fog', 48: 'depositing rime fog',
+ 51: 'light drizzle', 53: 'moderate drizzle', 55: 'dense drizzle',
+ 56: 'light freezing drizzle', 57: 'dense freezing drizzle',
+ 61: 'slight rain', 63: 'moderate rain', 65: 'heavy rain',
+ 66: 'light freezing rain', 67: 'heavy freezing rain',
+ 71: 'slight snow', 73: 'moderate snow', 75: 'heavy snow', 77: 'snow grains',
+ 80: 'slight rain showers', 81: 'moderate rain showers', 82: 'violent rain showers',
+ 85: 'slight snow showers', 86: 'heavy snow showers',
+ 95: 'thunderstorm', 96: 'thunderstorm with slight hail', 99: 'thunderstorm with heavy hail',
+};
+const describeWeatherCode = (code) => WEATHER_CODES[code] ?? 'unknown conditions';
+// Fallback location when the user hasn't set one and didn't pass lat/lon.
+// San Francisco — a sensible documented default; the tool description tells
+// the LLM to pass lat/lon when the user names a place.
+const DEFAULT_LAT = 37.7749;
+const DEFAULT_LON = -122.4194;
+
const TOOLS = [
{
name: 'brain_capture',
@@ -1391,6 +1454,289 @@ const TOOLS = [
};
},
},
+
+ {
+ name: 'calendar_today',
+ description:
+ "Report today's calendar events. Use when the user asks \"what's on my calendar today?\", \"what do I have today?\", \"any meetings today?\". Reads from the user's synced calendar accounts (Google etc.). Returns up to 10 events with title, time, and location.",
+ parameters: {
+ type: 'object',
+ properties: {
+ limit: { type: 'integer', description: 'Max events to return (default 10, max 20).' },
+ },
+ },
+ execute: async ({ limit = 10 } = {}) => {
+ const max = Math.max(1, Math.min(20, limit || 10));
+ 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
+ // [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;
+ const startDate = new Date(localMidnightUtc).toISOString();
+ const endDate = new Date(localMidnightUtc + 86399999).toISOString();
+ const { events = [] } = await getCalendarEvents({ startDate, endDate, limit: max });
+ const items = events.map((e) => ({
+ title: e.title,
+ startTime: e.startTime,
+ time: e.allDay ? 'all day' : formatEventTime(e.startTime, tz),
+ location: e.location || null,
+ allDay: !!e.allDay,
+ }));
+ return {
+ ok: true,
+ date: today,
+ count: items.length,
+ events: items,
+ summary: items.length
+ ? `${items.length} event${items.length === 1 ? '' : 's'} today: ${events.slice(0, max).map((e) => summarizeEvent(e, tz)).join('; ')}.`
+ : 'Nothing on your calendar today.',
+ };
+ },
+ },
+
+ {
+ name: 'calendar_next',
+ description:
+ 'Report the next upcoming calendar event. Use when the user asks "what\'s next?", "what\'s my next meeting?", "when\'s my next appointment?". Reads from the user\'s synced calendar accounts and returns the soonest event starting from now.',
+ parameters: { type: 'object', properties: {} },
+ execute: async () => {
+ const tz = await getUserTimezone();
+ const nowIso = new Date().toISOString();
+ // Look ahead 30 days; getEvents returns events sorted ascending by
+ // startTime, so the first one at/after now is "next". Pull a small
+ // window and filter in-memory rather than relying on exact boundary.
+ const horizon = new Date(Date.now() + 30 * 86400000).toISOString();
+ const { events = [] } = await getCalendarEvents({
+ startDate: nowIso,
+ endDate: horizon,
+ limit: 50,
+ });
+ const next = events.find((e) => {
+ const start = new Date(e?.startTime);
+ return !Number.isNaN(start.getTime()) && start.getTime() >= Date.now();
+ });
+ if (!next) {
+ return { ok: true, found: false, summary: 'Nothing coming up on your calendar in the next 30 days.' };
+ }
+ 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 loc = next.location ? ` at ${next.location}` : '';
+ return {
+ ok: true,
+ found: true,
+ title: next.title,
+ startTime: next.startTime,
+ location: next.location || null,
+ allDay: !!next.allDay,
+ summary: `Next up: ${next.title || 'Untitled event'} — ${dayLabel}, ${timeLabel}${loc}.`,
+ };
+ },
+ },
+
+ {
+ name: 'meatspace_log_workout',
+ description:
+ 'Log a workout / exercise session to MortalLoom / Meatspace tracking. Use when the user says "log a workout", "I went for a 30 minute run", "did an hour of yoga", "lifted weights for 45 minutes". The `type` is free-form (run, yoga, lifting, cycling, swim, etc.). Duration and intensity are optional.',
+ parameters: {
+ type: 'object',
+ properties: {
+ type: { type: 'string', description: 'Workout type (e.g. "run", "yoga", "weightlifting", "cycling").' },
+ durationMinutes: { type: 'number', description: 'How long, in minutes. Omit if unknown.' },
+ intensity: { type: 'string', enum: ['light', 'moderate', 'vigorous'], description: 'Optional perceived intensity.' },
+ notes: { type: 'string', description: 'Optional free-form notes about the session.' },
+ date: { type: 'string', description: 'ISO date (YYYY-MM-DD). Omit for today.' },
+ },
+ required: ['type'],
+ },
+ execute: async ({ type, durationMinutes, intensity, notes, date } = {}) => {
+ if (typeof type !== 'string' || !type.trim()) throw new Error('type is required');
+ let resolvedDuration;
+ if (durationMinutes !== undefined && durationMinutes !== null && durationMinutes !== '') {
+ const parsed = Number(durationMinutes);
+ if (!Number.isFinite(parsed) || parsed <= 0 || parsed > 1440) {
+ throw new Error('durationMinutes must be a positive number (≤1440)');
+ }
+ resolvedDuration = parsed;
+ }
+ if (intensity !== undefined && intensity !== null && !['light', 'moderate', 'vigorous'].includes(intensity)) {
+ throw new Error('intensity must be light, moderate, or vigorous');
+ }
+ const entry = await addWorkout({
+ date,
+ type: type.trim(),
+ durationMinutes: resolvedDuration,
+ intensity,
+ notes,
+ });
+ const durPart = entry.durationMinutes ? ` (${entry.durationMinutes} min)` : '';
+ return {
+ ok: true,
+ date: entry.date,
+ type: entry.type,
+ summary: `Logged ${entry.type}${durPart} on ${entry.date}.`,
+ };
+ },
+ },
+
+ {
+ name: 'weather_now',
+ description:
+ 'Report the current weather (temperature + conditions) for a location. Use when the user asks "what\'s the weather?", "is it raining?", "how hot is it outside?". Defaults to the user\'s configured location (if set in Settings); otherwise pass `lat`/`lon` for a specific place. Uses the free Open-Meteo service (no API key).',
+ parameters: {
+ type: 'object',
+ properties: {
+ lat: { type: 'number', description: 'Latitude (-90 to 90). Omit to use the configured/default location.' },
+ lon: { type: 'number', description: 'Longitude (-180 to 180). Omit to use the configured/default location.' },
+ },
+ },
+ execute: async ({ lat, lon } = {}) => {
+ // Resolve location: explicit params > settings.location > default.
+ const settings = await getSettings().catch(() => ({}));
+ const cfgLat = Number(settings?.location?.lat);
+ const cfgLon = Number(settings?.location?.lon);
+ const numOrNull = (v) => {
+ if (v === undefined || v === null || v === '') return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+ };
+ const resolvedLat = numOrNull(lat) ?? (Number.isFinite(cfgLat) ? cfgLat : null) ?? DEFAULT_LAT;
+ const resolvedLon = numOrNull(lon) ?? (Number.isFinite(cfgLon) ? cfgLon : null) ?? DEFAULT_LON;
+ if (resolvedLat < -90 || resolvedLat > 90 || resolvedLon < -180 || resolvedLon > 180) {
+ return { ok: false, summary: 'Latitude must be -90..90 and longitude -180..180.' };
+ }
+ const url = `https://api.open-meteo.com/v1/forecast?latitude=${resolvedLat}&longitude=${resolvedLon}`
+ + '&current=temperature_2m,weather_code&temperature_unit=fahrenheit';
+ const res = await fetchWithTimeout(url, {}, 10000).catch((err) => ({ ok: false, error: err?.message }));
+ if (!res || !res.ok) {
+ return { ok: false, summary: `Couldn't reach the weather service${res?.error ? ` (${res.error})` : ''}.` };
+ }
+ const data = await res.json().catch(() => null);
+ const current = data?.current;
+ if (!current || typeof current.temperature_2m !== 'number') {
+ return { ok: false, summary: 'The weather service returned no current conditions.' };
+ }
+ const temp = Math.round(current.temperature_2m);
+ const conditions = describeWeatherCode(current.weather_code);
+ return {
+ ok: true,
+ lat: resolvedLat,
+ lon: resolvedLon,
+ temperatureF: temp,
+ weatherCode: current.weather_code,
+ conditions,
+ summary: `It's ${temp}°F and ${conditions} right now.`,
+ };
+ },
+ },
+
+ {
+ name: 'timer_set',
+ description:
+ 'Set a one-shot timer or reminder. Use when the user says "set a timer for 10 minutes", "remind me in 30 minutes to call mom", "ping me in an hour". When the timer fires, PortOS raises a notification with the label. Specify the duration in minutes (or seconds for short timers).',
+ parameters: {
+ type: 'object',
+ properties: {
+ minutes: { type: 'number', description: 'Timer duration in minutes. Use this for most timers.' },
+ seconds: { type: 'number', description: 'Timer duration in seconds. Use for short timers; added to minutes if both given.' },
+ label: { type: 'string', description: 'What to remind the user about (e.g. "tea is ready", "call mom").' },
+ },
+ },
+ execute: async ({ minutes, seconds, label } = {}) => {
+ const mins = Number.isFinite(Number(minutes)) ? Number(minutes) : 0;
+ const secs = Number.isFinite(Number(seconds)) ? Number(seconds) : 0;
+ const totalMs = Math.round((mins * 60 + secs) * 1000);
+ // Bound: at least 1s, at most 24h. An LLM-supplied NaN/negative or an
+ // absurd duration shouldn't schedule a runaway timer.
+ if (!Number.isFinite(totalMs) || totalMs < 1000) {
+ return { ok: false, summary: 'Tell me how long — e.g. "set a timer for 10 minutes".' };
+ }
+ if (totalMs > 24 * 60 * 60 * 1000) {
+ 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);
+ 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}"`);
+ return {
+ ok: true,
+ durationMs: totalMs,
+ label: trimmedLabel,
+ summary: `Timer set for ${human}${trimmedLabel !== 'Timer' ? ` — I'll remind you to ${trimmedLabel}` : ''}.`,
+ };
+ },
+ },
+
+ {
+ name: 'ui_describe_visually',
+ description:
+ "Take a screenshot of what the user is currently looking at and describe it using a vision model. Use when the user asks about VISUAL content the text-based ui_read can't capture — \"what's on this chart?\", \"describe this graph\", \"what does the CyberCity look like right now?\", \"what am I looking at?\". For plain text content prefer ui_read; only reach for this when the answer requires SEEING pixels (charts, 3D/WebGL views, images, diagrams). The screenshot is captured client-side (the browser may prompt for screen-capture permission the first time).",
+ parameters: {
+ type: 'object',
+ properties: {
+ question: {
+ type: 'string',
+ description: 'What the user wants to know about the screen (e.g. "what does this chart show?"). Defaults to a general description.',
+ },
+ },
+ },
+ execute: async ({ question } = {}, ctx = {}) => {
+ if (typeof ctx.captureScreenshot !== 'function') {
+ return {
+ ok: false,
+ error: 'No screenshot channel',
+ summary: "I can't capture the screen right now — this only works through the live voice widget.",
+ };
+ }
+ const prompt = (typeof question === 'string' && question.trim())
+ ? `${question.trim()}\n\nAnswer concisely based only on what is visible in this screenshot.`
+ : 'Describe what is visible in this screenshot of an app screen, concisely.';
+ // Ask the client to capture the active tab. Returns a data URL (base64
+ // PNG/JPEG) or null if the user denied / capture failed.
+ const dataUrl = await ctx.captureScreenshot().catch(() => null);
+ if (!dataUrl || typeof dataUrl !== 'string') {
+ return {
+ ok: false,
+ error: 'Screenshot capture failed',
+ summary: "I couldn't capture the screen — the browser may have blocked screen capture. Try again and allow it.",
+ };
+ }
+ const description = await ctx.describeImage(dataUrl, prompt).catch((err) => ({ __error: err?.message || String(err) }));
+ if (description?.__error) {
+ return { ok: false, error: description.__error, summary: `I captured the screen but the vision model failed: ${description.__error}` };
+ }
+ const text = typeof description === 'string' ? description.trim() : '';
+ if (!text) {
+ return { ok: false, summary: 'I captured the screen but the vision model returned nothing.' };
+ }
+ return {
+ ok: true,
+ content: text,
+ path: ctx.state?.ui?.path || null,
+ // Keep summary short — the full description is in `content` for the LLM
+ // to speak verbatim (mirrors ui_read / ui_ask).
+ summary: `Described the current screen (${text.length} chars).`,
+ };
+ },
+ },
];
const toSpec = (t) => ({
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index 712405e134..1dd32fb7a7 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -14,8 +14,40 @@ vi.mock('../meatspaceNicotine.js', () => ({
logNicotine: vi.fn(async () => ({ totalMg: 1, dayTotal: 1 })),
getNicotineSummary: vi.fn(async () => ({ today: 0 })),
}));
+const addWorkoutMock = vi.fn(async ({ date, type, durationMinutes, intensity, notes }) => ({
+ date: date || '2026-04-17',
+ type,
+ durationMinutes: durationMinutes ?? null,
+ intensity: intensity ?? null,
+ notes: notes ?? null,
+}));
vi.mock('../meatspaceHealth.js', () => ({
addBodyEntry: vi.fn(async () => ({ date: '2026-04-17' })),
+ addWorkout: (...args) => addWorkoutMock(...args),
+}));
+// Calendar events — controllable per-test via calendarEventsRef.
+const calendarEventsRef = { value: [] };
+vi.mock('../calendarSync.js', () => ({
+ getEvents: vi.fn(async () => ({ events: calendarEventsRef.value, total: calendarEventsRef.value.length })),
+}));
+const addNotificationMock = vi.fn(async () => ({ id: 'notif-1' }));
+vi.mock('../notifications.js', () => ({
+ addNotification: (...args) => addNotificationMock(...args),
+ NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },
+ PRIORITY_LEVELS: { HIGH: 'high' },
+}));
+// 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', () => ({
+ fetchWithTimeout: vi.fn(async () => weatherFetchRef.value),
+}));
+// Timezone — pin to deterministic values so calendar/time tests don't depend
+// on the host TZ or settings file.
+vi.mock('../../lib/timezone.js', () => ({
+ getUserTimezone: vi.fn(async () => 'America/Los_Angeles'),
+ todayInTimezone: vi.fn(() => '2026-04-17'),
+ getLocalParts: vi.fn(() => ({ year: 2026, month: 4, day: 17 })),
+ getUtcOffsetMs: vi.fn(() => -7 * 3600 * 1000), // PDT
}));
vi.mock('../identity.js', () => ({
getGoals: vi.fn(async () => ({ goals: [] })),
@@ -840,3 +872,178 @@ 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 },
+ ];
+ const r = await dispatchTool('calendar_today', {});
+ expect(r.ok).toBe(true);
+ expect(r.count).toBe(2);
+ expect(r.date).toBe('2026-04-17');
+ expect(r.events[0].title).toBe('Standup');
+ expect(r.summary).toMatch(/2 events today/);
+ });
+
+ it('reports an empty day cleanly', async () => {
+ calendarEventsRef.value = [];
+ const r = await dispatchTool('calendar_today', {});
+ expect(r.ok).toBe(true);
+ expect(r.count).toBe(0);
+ expect(r.summary).toMatch(/Nothing on your 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 }];
+ const r = await dispatchTool('calendar_next', {});
+ expect(r.ok).toBe(true);
+ expect(r.found).toBe(true);
+ expect(r.title).toBe('Dentist');
+ expect(r.summary).toMatch(/Next up: Dentist/);
+ });
+
+ it('reports nothing upcoming when the list is empty', async () => {
+ calendarEventsRef.value = [];
+ const r = await dispatchTool('calendar_next', {});
+ expect(r.ok).toBe(true);
+ expect(r.found).toBe(false);
+ expect(r.summary).toMatch(/Nothing coming up/);
+ });
+});
+
+describe('meatspace_log_workout', () => {
+ it('rejects missing type', async () => {
+ await expect(dispatchTool('meatspace_log_workout', {})).rejects.toThrow(/type is required/);
+ });
+ it('rejects absurd duration', async () => {
+ await expect(dispatchTool('meatspace_log_workout', { type: 'run', durationMinutes: 5000 }))
+ .rejects.toThrow(/durationMinutes must be a positive number/);
+ });
+ it('rejects invalid intensity', async () => {
+ await expect(dispatchTool('meatspace_log_workout', { type: 'run', intensity: 'extreme' }))
+ .rejects.toThrow(/intensity must be/);
+ });
+ it('logs a workout via addWorkout', async () => {
+ addWorkoutMock.mockClear();
+ const r = await dispatchTool('meatspace_log_workout', { type: 'yoga', durationMinutes: 30, intensity: 'moderate' });
+ expect(r.ok).toBe(true);
+ expect(r.type).toBe('yoga');
+ expect(addWorkoutMock).toHaveBeenCalledWith(expect.objectContaining({ type: 'yoga', durationMinutes: 30, intensity: 'moderate' }));
+ expect(r.summary).toMatch(/Logged yoga \(30 min\)/);
+ });
+});
+
+describe('weather_now', () => {
+ it('returns temperature + mapped conditions', async () => {
+ weatherFetchRef.value = { ok: true, json: async () => ({ current: { temperature_2m: 71.4, weather_code: 3 } }) };
+ const r = await dispatchTool('weather_now', { lat: 40, lon: -74 });
+ expect(r.ok).toBe(true);
+ expect(r.temperatureF).toBe(71);
+ expect(r.conditions).toBe('overcast');
+ expect(r.summary).toMatch(/71°F and overcast/);
+ });
+ it('rejects out-of-range coordinates', async () => {
+ const r = await dispatchTool('weather_now', { lat: 200, lon: 0 });
+ expect(r.ok).toBe(false);
+ expect(r.summary).toMatch(/Latitude must be/);
+ });
+ it('handles an unreachable weather service', async () => {
+ weatherFetchRef.value = { ok: false };
+ const r = await dispatchTool('weather_now', { lat: 1, lon: 1 });
+ expect(r.ok).toBe(false);
+ expect(r.summary).toMatch(/Couldn't reach the weather service/);
+ });
+});
+
+describe('timer_set', () => {
+ it('rejects a missing/zero duration', async () => {
+ const r = await dispatchTool('timer_set', { label: 'tea' });
+ expect(r.ok).toBe(false);
+ expect(r.summary).toMatch(/Tell me how long/);
+ });
+ it('rejects durations over 24 hours', async () => {
+ const r = await dispatchTool('timer_set', { minutes: 2000 });
+ 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();
+ 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();
+ });
+});
+
+describe('ui_describe_visually', () => {
+ it('fails gracefully without a screenshot channel', async () => {
+ const r = await dispatchTool('ui_describe_visually', { question: 'what is this?' }, { sideEffects: [] });
+ expect(r.ok).toBe(false);
+ expect(r.summary).toMatch(/can't capture the screen/);
+ });
+ it('returns null-capture as a friendly failure', async () => {
+ const ctx = { sideEffects: [], captureScreenshot: async () => null, describeImage: async () => 'x' };
+ const r = await dispatchTool('ui_describe_visually', {}, ctx);
+ expect(r.ok).toBe(false);
+ expect(r.summary).toMatch(/couldn't capture the screen/i);
+ });
+ it('captures + describes the screen and returns the description', async () => {
+ const ctx = {
+ sideEffects: [],
+ state: { ui: { path: '/cybercity' } },
+ captureScreenshot: async () => 'data:image/jpeg;base64,abc',
+ describeImage: async (dataUrl, prompt) => {
+ expect(dataUrl).toBe('data:image/jpeg;base64,abc');
+ expect(prompt).toMatch(/chart/i);
+ return 'A neon skyline with three towers.';
+ },
+ };
+ const r = await dispatchTool('ui_describe_visually', { question: 'what is on this chart?' }, ctx);
+ expect(r.ok).toBe(true);
+ expect(r.content).toBe('A neon skyline with three towers.');
+ expect(r.path).toBe('/cybercity');
+ });
+ it('surfaces a vision-model error', async () => {
+ const ctx = {
+ sideEffects: [],
+ captureScreenshot: async () => 'data:image/jpeg;base64,abc',
+ describeImage: async () => { throw new Error('model offline'); },
+ };
+ const r = await dispatchTool('ui_describe_visually', {}, ctx);
+ expect(r.ok).toBe(false);
+ expect(r.summary).toMatch(/model offline/);
+ });
+});
+
+describe('new tool intent routing', () => {
+ it('routes calendar utterances to the calendar group', () => {
+ expect(classifyIntent("what's on my calendar today?").has('calendar')).toBe(true);
+ expect(classifyIntent("what's my next meeting?").has('calendar')).toBe(true);
+ expect(classifyIntent('any appointments today').has('calendar')).toBe(true);
+ });
+ it('routes weather utterances to the weather group', () => {
+ expect(classifyIntent("what's the weather?").has('weather')).toBe(true);
+ expect(classifyIntent('is it raining outside').has('weather')).toBe(true);
+ });
+ it('routes timer utterances to the timer group', () => {
+ expect(classifyIntent('set a timer for 10 minutes').has('timer')).toBe(true);
+ expect(classifyIntent('remind me in 30 minutes to call mom').has('timer')).toBe(true);
+ });
+ it('routes workout utterances to the meatspace group', () => {
+ expect(classifyIntent('log a workout').has('meatspace')).toBe(true);
+ expect(classifyIntent('I went for a run').has('meatspace')).toBe(true);
+ });
+ it('routes visual-description utterances to the vision group', () => {
+ expect(classifyIntent("what's on this chart?").has('vision')).toBe(true);
+ expect(classifyIntent('describe the cybercity').has('vision')).toBe(true);
+ });
+});
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index b2fd98c5df..a4b646dc7e 100644
--- a/server/sockets/voice.js
+++ b/server/sockets/voice.js
@@ -1,10 +1,11 @@
// 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:screenshot:result
// 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:dailyLog:appended | voice:error | voice:idle
+// | voice:screenshot:request
import { runTurn } from '../services/voice/pipeline.js';
import { getVoiceConfig } from '../services/voice/config.js';
@@ -63,6 +64,10 @@ 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: [],
// 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
@@ -252,12 +257,32 @@ 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).
+ // 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;
+ 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));
+ });
+
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 screenshot capture.
+ const shotWaiters = state.screenshotWaiters;
+ state.screenshotWaiters = [];
+ shotWaiters.forEach((resolve) => resolve(null));
unregisterEchoBuffer(state.recentTts);
});
};