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 (round 2): SSE backpressure, error/done split, CRLF parsing, a11y rows
Adam Eivy6eb7e2a77915
diff --git a/PLAN.md b/PLAN.mdindex 68418b329c..8298775d35 100644--- a/PLAN.md+++ b/PLAN.md@@ -87,7 +87,7 @@ Three high-value work items drawn from an inventory of the current app surface (> **Slice (a) — text chat + sources — shipped.** `/ask` and `/ask/:conversationId` are live. `server/services/askService.js` orchestrates parallel retrieval across memory (hybrid), brain notes, autobiography, goals, and calendar with kind-weighted reranking. Persona preamble is sourced from `character.json`. Three modes (`ask` / `advise` / `draft`) swap directives. API providers stream SSE; CLI providers single-shot. Conversations persist to `data/ask-conversations/<id>.json` with 30-day auto-expiry unless pinned. Source chips deep-link back to origin. Registered in the nav manifest so `⌘K` and voice (`ui_navigate`) resolve "ask" automatically. **Slice (b) (voice + promotion actions) still pending** — see backlog item below.>-> 40 new tests (askService 11, askConversations 17, ask routes 12); full server suite stays green at 2548/2548.+> 40 new tests (askService 11, askConversations 17, ask routes 12); full server suite stays green at 2549/2549.**Problem.** PortOS has spent many milestones building a rich model of the user: Brain (thoughts, daily log, notes, links), Memory (pgvector + BM25 hybrid retrieval), Digital Twin (identity, autobiography, personality, behavioral feedback), Goals, Calendar, MeatSpace biomarkers. These live on separate pages with separate inputs. There is still no single conversational surface where the user can ask their own system a question like *"What did I decide about my exercise routine in March?"*, *"What's on my plate this afternoon given how I slept?"*, or *"Draft a status update to my team as me."* Without this, the twin is a library nobody borrows from.diff --git a/client/src/pages/Ask.jsx b/client/src/pages/Ask.jsxindex 81b0163c67..b2f1a774a9 100644--- a/client/src/pages/Ask.jsx+++ b/client/src/pages/Ask.jsx@@ -66,12 +66,16 @@ function Sidebar({ conversations, activeId, onPick, onNew, onDelete, loading, streturn (<divkey={c.id}- aria-disabled={lockedSwitch || undefined}- title={lockedSwitch ? 'Wait for the current answer to finish' : undefined}- className={`group flex items-center justify-between gap-2 px-3 py-2 hover:bg-port-border/30 ${c.id === activeId ? 'bg-port-border/40' : ''} ${lockedSwitch ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}- onClick={() => { if (!lockedSwitch) onPick(c.id); }}+ className={`group relative flex items-center justify-between gap-2 ${c.id === activeId ? 'bg-port-border/40' : ''}`}>- <div className="min-w-0 flex-1">+ <button+ type="button"+ disabled={lockedSwitch}+ aria-current={c.id === activeId ? 'page' : undefined}+ onClick={() => onPick(c.id)}+ title={lockedSwitch ? 'Wait for the current answer to finish' : c.title}+ className={`flex-1 min-w-0 text-left px-3 py-2 hover:bg-port-border/30 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent focus:outline-none focus-visible:ring-1 focus-visible:ring-port-accent`}+ ><div className="text-sm truncate">{c.title}</div><div className="text-xs text-gray-500 flex items-center gap-1.5"><span>{c.mode}</span>@@ -79,10 +83,11 @@ function Sidebar({ conversations, activeId, onPick, onNew, onDelete, loading, st<span>{c.turnCount} turns</span>{c.promoted && <Pin size={10} className="text-amber-400" />}</div>- </div>+ </button><button- onClick={(e) => { e.stopPropagation(); onDelete(c.id); }}- className="opacity-0 group-hover:opacity-100 text-gray-500 hover:text-port-error transition-opacity"+ type="button"+ onClick={() => onDelete(c.id)}+ className="absolute right-2 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 text-gray-500 hover:text-port-error transition-opacity"title="Delete conversation"><Trash2 size={14} />@@ -171,15 +176,16 @@ export default function Ask() {}}, [activeConv?.turns?.length, streamingTurn?.content]);- // Abort any in-flight stream on unmount so we don't leave a dangling fetch- // pumping deltas + toasts into a component that's no longer mounted. The- // handleSend closure is keyed off `activeConv?.id` so a deliberate- // conversation switch unmounts the old subtree's stream by re-running this- // effect — anything still streaming dies cleanly.+ // Abort any in-flight stream when the user navigates to a different+ // conversation OR when the page unmounts — React Router reuses the same+ // `Ask` instance across `/ask/:conversationId` transitions, so an+ // unmount-only effect would leak a stream from conversation A while the+ // user reads conversation B. Tying the cleanup to `conversationId`+ // guarantees stale events can't land in the wrong local state.useEffect(() => () => {abortRef.current?.abort();abortRef.current = null;- }, []);+ }, [conversationId]);const startNew = useCallback(() => {if (streaming) return;diff --git a/server/routes/ask.js b/server/routes/ask.jsindex e66ed25c9f..20bcbe7116 100644--- a/server/routes/ask.js+++ b/server/routes/ask.js@@ -4,7 +4,8 @@* GET /api/ask → list conversations (summaries)* GET /api/ask/:id → full conversation* POST /api/ask → SSE-stream a new turn (creates a- * conversation if no `id` in body)+ * conversation if no `conversationId`+ * in body)* DELETE /api/ask/:id → delete a conversation* POST /api/ask/:id/promote → mark conversation exempt from* 30-day auto-expiry@@ -115,15 +116,25 @@ router.post('/', asyncHandler(async (req, res) => {};req.on('close', onClose);- const send = (event, data) => {+ // Honour socket backpressure — for long answers with many delta frames,+ // a slow reader could otherwise force Node to buffer unbounded SSE data+ // in memory. If `res.write` returns false, await the next `drain` (or+ // `close`) before queuing more frames.+ const send = async (event, data) => {if (aborted) return;- res.write(`event: ${event}\n`);- res.write(`data: ${JSON.stringify(data)}\n\n`);+ const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;+ if (!res.write(frame)) {+ await new Promise((resolve) => {+ const onDrain = () => { res.off('close', onDrain); resolve(); };+ res.once('drain', onDrain);+ res.once('close', onDrain);+ });+ }};// Tell the client the conversation id up-front so it can deep-link the URL// before the answer finishes streaming.- send('open', { conversationId: conversation.id, mode: body.mode });+ await send('open', { conversationId: conversation.id, mode: body.mode });// Drop the just-appended user turn (we're about to answer it) plus take// the last PROMPT_HISTORY_TURNS prior turns as multi-turn context.@@ -147,10 +158,10 @@ router.post('/', asyncHandler(async (req, res) => {if (aborted) break;if (evt.type === 'sources') {assistantSources = evt.sources;- send('sources', { sources: evt.sources });+ await send('sources', { sources: evt.sources });} else if (evt.type === 'delta') {assistantText += evt.text;- send('delta', { text: evt.text });+ await send('delta', { text: evt.text });} else if (evt.type === 'done') {providerInfo = { providerId: evt.providerId, model: evt.model };// Streaming providers accumulate via delta events; one-shot CLI@@ -158,7 +169,7 @@ router.post('/', asyncHandler(async (req, res) => {if (!assistantText && evt.answer) assistantText = evt.answer;} else if (evt.type === 'error') {streamErrored = true;- send('error', { error: evt.error });+ await send('error', { error: evt.error });}}@@ -180,10 +191,17 @@ router.post('/', asyncHandler(async (req, res) => {}if (!aborted) {- // Hand back the persisted turn so the client can append to local state- // instead of round-tripping a full conversation refetch.- send('done', { conversationId: conversation.id, turn: persistedAssistantTurn });- res.end();+ if (streamErrored) {+ // Error event already flushed inside the loop — close the stream+ // without a `done` frame so clients can cleanly distinguish failure+ // (terminal `error`) from success (terminal `done`).+ res.end();+ } else {+ // Hand back the persisted turn so the client can append to local+ // state instead of round-tripping a full conversation refetch.+ await send('done', { conversationId: conversation.id, turn: persistedAssistantTurn });+ res.end();+ }}}));diff --git a/server/services/askService.js b/server/services/askService.jsindex ccae90828c..092dd288e7 100644--- a/server/services/askService.js+++ b/server/services/askService.js@@ -376,7 +376,10 @@ async function* streamCompletion(provider, model, prompt, signal) {}const { value, done } = await reader.read();if (done) break;- buffer += decoder.decode(value, { stream: true });+ // Some SSE producers emit CRLF line terminators (`\r\n\r\n` between+ // frames); normalise to LF so the `\n\n` frame split below works+ // regardless of upstream.+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n');let idx;while ((idx = buffer.indexOf('\n\n')) !== -1) {const frame = buffer.slice(0, idx).trim();@@ -384,7 +387,16 @@ async function* streamCompletion(provider, model, prompt, signal) {if (!frame.startsWith('data:')) continue;const payload = frame.slice(5).trim();if (payload === '[DONE]') return;- const parsed = JSON.parse(payload);+ // A single malformed/partial frame from the upstream provider must+ // not kill the whole stream — log and skip so subsequent good+ // frames still flow.+ let parsed;+ try {+ parsed = JSON.parse(payload);+ } catch {+ console.warn(`⚠️ Ask: skipping malformed SSE frame from ${provider.id}`);+ continue;+ }const delta = parsed?.choices?.[0]?.delta?.content;if (delta) yield delta;}