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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (copilot): user-gesture-authorized vision capture stream for ui_describe_visually + don't cache unmatched ui:read-response text
Adam Eivy9588cf2ca910
diff --git a/PLAN.md b/PLAN.mdindex cb322c563b..19713ac551 100644--- a/PLAN.md+++ b/PLAN.md@@ -11,8 +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] **`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).+- [ ] [voice-tool-edge-hardening] **Edge-case hardening for the new voice tools (all low-severity, from the xhigh code-review 2026-05-25).** (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 (related: [voice-calendar-next-allday-edge] covers the all-day facet). (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). _(Fixed in the v2.9.0 release review: (a) the `calendar_today` DST-offset bug — `anchorLocalMidnightUtc` now samples the offset at the target midnight; and `resolveExcludeSet` is now deferred to the `getChecksum` cache-miss path.)_## Deferred Architecture (human-led planning)diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsxindex 95d12ee6f0..9dcee71b52 100644--- a/client/src/components/voice/VoiceWidget.jsx+++ b/client/src/components/voice/VoiceWidget.jsx@@ -1,11 +1,12 @@import { useState, useEffect, useLayoutEffect, useRef, useCallback } from 'react';import { useNavigate } from 'react-router-dom';-import { Mic, MicOff, Brain, Volume2, Square, Trash2, ChevronDown, ChevronUp, Send, Infinity as InfinityIcon, NotebookPen, X, EyeOff } from 'lucide-react';+import { Mic, MicOff, Brain, Volume2, Square, Trash2, ChevronDown, ChevronUp, Send, Infinity as InfinityIcon, NotebookPen, X, EyeOff, Monitor, MonitorOff } from 'lucide-react';import {startCapture, stopCapture, interrupt, resetConversation, sendText, onVoiceEvent, isCapturing,startContinuous, stopContinuous, isContinuous, whenPlaybackDrained, getVadLevel,webSpeechSupported, startWebSpeechCapture, stopWebSpeechCapture, isWebSpeechCapturing,onProactiveSpeech, captureScreenForVision, sendScreenshotResult,+ enableVisionCapture, disableVisionCapture, isVisionCaptureEnabled,} from '../../services/voiceClient';import { getVoiceConfig } from '../../services/apiVoice';import toast from '../ui/Toast';@@ -85,6 +86,10 @@ export default function VoiceWidget() {});const [hidden, setHidden] = useState(readVoiceHidden);const [level, setLevel] = useState(0);+ // Whether the user has authorized a screen-capture stream for+ // ui_describe_visually ("what's on this chart?"). Must be enabled from a click+ // (user gesture) — getDisplayMedia can't run from the server-initiated turn.+ const [visionEnabled, setVisionEnabled] = useState(false);const scrollRef = useRef(null);const useWebSpeech = sttEngine === 'web-speech' && webSpeechSupported;@@ -220,20 +225,35 @@ 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.+ // ui_describe_visually: server asks the client to grab a frame of the+ // authorized screen-capture stream. The stream must have been authorized+ // earlier via the monitor button (a user gesture) — getDisplayMedia can't+ // run from this server-initiated event. captureScreenForVision returns a+ // data URL, or null when no stream is authorized / a frame grab failed;+ // always reply so the server-side waiter resolves rather than timing out.onVoiceEvent('voice:screenshot:request', async (payload) => {const requestId = payload && typeof payload === 'object' ? payload.requestId : undefined;+ if (!isVisionCaptureEnabled()) {+ toast('Voice: click the screen button in the voice controls so I can see your screen.', { icon: '🖥️' });+ setVisionEnabled(false);+ sendScreenshotResult(requestId, null);+ return;+ }const dataUrl = await captureScreenForVision();- if (!dataUrl) toast('Voice: screen capture was blocked or unavailable.', { icon: '📷' });+ if (!dataUrl) {+ toast('Voice: screen capture was unavailable.', { icon: '📷' });+ setVisionEnabled(isVisionCaptureEnabled());+ }sendScreenshotResult(requestId, dataUrl);}),];return () => offs.forEach((off) => off());}, [enabled, navigate]);+ // Release the authorized screen-capture stream when the widget unmounts so a+ // forgotten "vision ON" doesn't keep the browser's sharing indicator lit.+ useEffect(() => () => disableVisionCapture(), []);+// Auto-scroll to bottom on new contentuseEffect(() => {if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;@@ -623,6 +643,26 @@ export default function VoiceWidget() {{handsFree ? 'hands-free' : 'push-to-talk'}</button>)}+ <button+ onClick={async () => {+ if (visionEnabled) { disableVisionCapture(); setVisionEnabled(false); return; }+ // getDisplayMedia must run inside this click (user gesture).+ const ok = await enableVisionCapture();+ setVisionEnabled(ok);+ if (!ok) toast('Voice: screen sharing was declined or is unavailable.', { icon: '🖥️' });+ }}+ aria-label={visionEnabled ? 'Disable screen vision for voice' : 'Enable screen vision for voice'}+ aria-pressed={visionEnabled}+ title={visionEnabled+ ? 'Screen vision ON — the assistant can describe what\'s on your screen ("what\'s on this chart?"). Click to stop sharing.'+ : 'Screen vision OFF — click to let the assistant see your screen for "what\'s on this chart?" (you pick the tab/window).'}+ className={`flex items-center gap-1 px-2 py-1 rounded-full text-[10px] font-medium ${visionEnabled+ ? 'text-port-accent bg-port-accent/10 hover:bg-port-accent/20'+ : 'text-gray-400 hover:text-white hover:bg-port-border/70'}`}+ >+ {visionEnabled ? <Monitor size={12} /> : <MonitorOff size={12} />}+ {visionEnabled ? 'vision' : 'no vision'}+ </button>{history.length > 0 && (<buttononClick={() => setCollapsed((c) => !c)}diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex 8b77cf7fff..e37d65df56 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -462,43 +462,70 @@ 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.+// Persistent, user-authorized screen-capture stream for the voice agent's+// ui_describe_visually tool. getDisplayMedia is the only browser-native way to+// grab WebGL/canvas content (CyberCity, charts) without a heavy DOM-to-canvas+// dependency — but browsers REQUIRE a transient user gesture to call it, and the+// screenshot request is server-initiated (mid voice turn), not a click. So the+// user authorizes a capture stream ONCE via a click (enableVisionCapture, which+// the VoiceWidget wires to a button), we keep that stream alive, and+// captureScreenForVision grabs a frame from it on demand without re-prompting.+let visionStream = null;++const clearVisionStream = () => {+ if (visionStream) visionStream.getTracks().forEach((t) => t.stop());+ visionStream = null;+};++// True when a live, user-authorized capture stream is available to grab frames.+export const isVisionCaptureEnabled = () => !!(visionStream && visionStream.active);++// Authorize a screen-capture stream. MUST be called from within a user gesture+// (a click handler) — getDisplayMedia rejects outside transient activation,+// which is exactly why the server-initiated screenshot path can't call it.+// Returns true once a live stream is authorized. The stream self-clears when the+// user stops sharing via the browser's own chrome (track 'ended') so the next+// enable re-prompts instead of grabbing a dead track.+export const enableVisionCapture = async () => {+ if (!navigator.mediaDevices?.getDisplayMedia) return false;+ if (isVisionCaptureEnabled()) return true;+ const stream = await navigator.mediaDevices.getDisplayMedia({+ video: { displaySurface: 'browser' },+ audio: false,+ }).catch(() => null);+ if (!stream) return false;+ visionStream = stream;+ stream.getVideoTracks().forEach((t) => t.addEventListener('ended', clearVisionStream, { once: true }));+ return true;+};++// Stop and release the authorized capture stream (widget teardown / user toggle-off).+export const disableVisionCapture = () => clearVisionStream();++// Grab one frame from the authorized vision stream as a JPEG data URL. Returns+// null when no stream is authorized yet (the caller prompts the user to enable+// it) or on any frame-grab failure, so ui_describe_visually degrades to a clear+// "I can't see your screen" rather than crashing.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());- }+ if (typeof document === 'undefined' || !isVisionCaptureEnabled()) return null;+ const video = document.createElement('video');+ video.srcObject = visionStream;+ video.muted = true;+ const playing = await video.play().then(() => true).catch(() => false);+ if (!playing) return null;+ // 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');+ video.pause();+ if (!cctx) return null;+ cctx.drawImage(video, 0, 0, w, h);+ // JPEG @ 0.8 keeps the payload well under the server's 16 MB cap even at 4K.+ return canvas.toDataURL('image/jpeg', 0.8);};// Reply to a server voice:screenshot:request. Always emits a result (data URLdiff --git a/server/sockets/voice.js b/server/sockets/voice.jsindex ba40aa0838..236cde0771 100644--- a/server/sockets/voice.js+++ b/server/sockets/voice.js@@ -299,12 +299,15 @@ export const registerVoiceHandlers = (socket) => {if (!payload || typeof payload !== 'object') return;const { requestId, text } = payload;const capped = typeof text === 'string' ? truncateOnWordBoundary(text, MAX_UI_TEXT_CHARS) : null;- // Cache on the current ui snapshot too, so a follow-up read in the same- // turn (same page) doesn't need another round-trip.- if (state.ui && capped !== null) state.ui.text = capped;const resolve = state.uiTextWaiters.get(requestId);if (resolve) {state.uiTextWaiters.delete(requestId);+ // 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(capped);}});