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: SSE abort, TZ-stable timestamps, client cleanup, id guards

Adam Eivycade7b861fd7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 363ec3f2f0..cf89c2812a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -8,7 +8,7 @@
**Slice (b) deferred**: voice integration, `ui_ask` tool, and one-click "Save as Brain note / Create CoS task / Attach to Goal" promotions will land in a follow-up.
- Files: `server/services/askService.js` (new — orchestration, retrieval, prompt assembly, streaming), `server/services/askConversations.js` (new — persistent storage with expiry + pin), `server/services/askService.test.js` (new — 11 tests), `server/services/askConversations.test.js` (new — 16 tests), `server/routes/ask.js` (new — SSE stream + list/get/delete/promote), `server/routes/ask.test.js` (new — 12 tests), `server/index.js` (mounts `/api/ask`), `server/lib/navManifest.js` (Ask entry), `client/src/services/apiAsk.js` (new — manual SSE reader since EventSource is GET-only), `client/src/services/api.js` (re-export), `client/src/pages/Ask.jsx` (new — chat transcript, source chips, mode switcher, conversation sidebar), `client/src/App.jsx` (routes), `client/src/components/Layout.jsx` (sidebar entry).
+ Files: `server/services/askService.js` (new — orchestration, retrieval, prompt assembly, streaming), `server/services/askConversations.js` (new — persistent storage with expiry + pin), `server/services/askService.test.js` (new — 11 tests), `server/services/askConversations.test.js` (new — 17 tests), `server/routes/ask.js` (new — SSE stream + list/get/delete/promote), `server/routes/ask.test.js` (new — 12 tests), `server/index.js` (mounts `/api/ask`), `server/lib/navManifest.js` (Ask entry), `client/src/services/apiAsk.js` (new — manual SSE reader since EventSource is GET-only), `client/src/services/api.js` (re-export), `client/src/pages/Ask.jsx` (new — chat transcript, source chips, mode switcher, conversation sidebar), `client/src/App.jsx` (routes), `client/src/components/Layout.jsx` (sidebar entry).
- **Global Command Palette (`⌘K`) with shared backbone for the voice agent** — the `CmdK` overlay has been upgraded from a content-search box into a true command palette. Typing fuzzy-matches across every navigable page (Dashboard, Brain, CoS sub-pages, MeatSpace tabs, Settings, etc.) and a curated set of voice-agent actions (Capture to Brain, PM2 status, Today's health summary, Current time, Feed digest, Recent Brain entries, etc.). Enter navigates or runs the action; arrow keys walk the list; Esc closes. The existing Brain/Memory/Apps/History/Health content search is preserved underneath as a second section so nothing regresses. Empty-query state shows a curated shortlist (Dashboard, Brain Inbox, Tasks, Goals, Review Hub, Capture to Brain, time, goal list, today's summary) so `⌘K` + Enter always does something useful.
diff --git a/PLAN.md b/PLAN.md
index efdea729f5..68418b329c 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.
>
-> 39 new tests (askService 11, askConversations 16, 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 2548/2548.
**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.jsx
index 0af2704dbc..81b0163c67 100644
--- a/client/src/pages/Ask.jsx
+++ b/client/src/pages/Ask.jsx
@@ -41,13 +41,14 @@ function SourceChip({ source, index }) {
);
}
-function Sidebar({ conversations, activeId, onPick, onNew, onDelete, loading }) {
+function Sidebar({ conversations, activeId, onPick, onNew, onDelete, loading, streaming }) {
return (
<aside className="w-full md:w-64 md:shrink-0 border-r border-port-border bg-port-card md:h-full md:overflow-y-auto">
<div className="p-3 border-b border-port-border flex items-center gap-2">
<button
onClick={onNew}
- className="flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-md bg-port-accent/15 text-port-accent hover:bg-port-accent/25 text-sm font-medium transition-colors"
+ disabled={streaming}
+ className="flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-md bg-port-accent/15 text-port-accent hover:bg-port-accent/25 text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
<MessageCircle size={14} /> New conversation
</button>
@@ -57,30 +58,38 @@ function Sidebar({ conversations, activeId, onPick, onNew, onDelete, loading })
{!loading && conversations.length === 0 && (
<div className="p-3 text-xs text-gray-500">No conversations yet. Ask yourself something.</div>
)}
- {conversations.map((c) => (
- <div
- key={c.id}
- className={`group flex items-center justify-between gap-2 px-3 py-2 cursor-pointer hover:bg-port-border/30 ${c.id === activeId ? 'bg-port-border/40' : ''}`}
- onClick={() => onPick(c.id)}
- >
- <div className="min-w-0 flex-1">
- <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>
- <span>·</span>
- <span>{c.turnCount} turns</span>
- {c.promoted && <Pin size={10} className="text-amber-400" />}
+ {conversations.map((c) => {
+ // Lock conversation switching while a stream is in flight on a
+ // different conversation — switching mid-stream would race the
+ // assistant turn into the wrong local state and URL.
+ const lockedSwitch = streaming && c.id !== activeId;
+ return (
+ <div
+ key={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); }}
+ >
+ <div className="min-w-0 flex-1">
+ <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>
+ <span>·</span>
+ <span>{c.turnCount} turns</span>
+ {c.promoted && <Pin size={10} className="text-amber-400" />}
+ </div>
</div>
+ <button
+ onClick={(e) => { e.stopPropagation(); onDelete(c.id); }}
+ className="opacity-0 group-hover:opacity-100 text-gray-500 hover:text-port-error transition-opacity"
+ title="Delete conversation"
+ >
+ <Trash2 size={14} />
+ </button>
</div>
- <button
- onClick={(e) => { e.stopPropagation(); onDelete(c.id); }}
- className="opacity-0 group-hover:opacity-100 text-gray-500 hover:text-port-error transition-opacity"
- title="Delete conversation"
- >
- <Trash2 size={14} />
- </button>
- </div>
- ))}
+ );
+ })}
</div>
</aside>
);
@@ -162,6 +171,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.
+ useEffect(() => () => {
+ abortRef.current?.abort();
+ abortRef.current = null;
+ }, []);
+
const startNew = useCallback(() => {
if (streaming) return;
navigate('/ask');
@@ -225,6 +244,9 @@ export default function Ask() {
{
signal: controller.signal,
onEvent: ({ event, data }) => {
+ // Drop events that arrive after the user navigated away / aborted —
+ // otherwise we'd write into a stale conversation's local state.
+ if (controller.signal.aborted) return;
if (event === 'open') {
serverConvId = data.conversationId;
if (!activeConv?.id || activeConv.id === 'pending') {
@@ -247,8 +269,13 @@ export default function Ask() {
if (err.name !== 'AbortError') toast.error(err.message || 'Ask failed');
});
+ const wasAborted = controller.signal.aborted;
setStreamingTurn(null);
- abortRef.current = null;
+ if (abortRef.current === controller) abortRef.current = null;
+
+ // Skip post-stream state writes if the user navigated/unmounted — those
+ // updates would land in a stale conversation.
+ if (wasAborted) return;
// Append the persisted assistant turn locally rather than refetching the
// whole conversation — server returned the canonical record in 'done'.
@@ -273,6 +300,7 @@ export default function Ask() {
onNew={startNew}
onDelete={handleDelete}
loading={loadingList}
+ streaming={streaming}
/>
<main className="flex-1 flex flex-col min-w-0">
diff --git a/server/routes/ask.js b/server/routes/ask.js
index 1503732892..e66ed25c9f 100644
--- a/server/routes/ask.js
+++ b/server/routes/ask.js
@@ -103,7 +103,20 @@ router.post('/', asyncHandler(async (req, res) => {
});
res.flushHeaders?.();
+ // Propagate client disconnects (browser nav, tab close, abort) into
+ // retrieval + provider streaming so we don't keep burning tokens/CPU on
+ // a stream nobody's reading. `aborted` short-circuits the post-loop
+ // persistence too.
+ const abortController = new AbortController();
+ let aborted = false;
+ const onClose = () => {
+ aborted = true;
+ abortController.abort();
+ };
+ req.on('close', onClose);
+
const send = (event, data) => {
+ if (aborted) return;
res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
@@ -129,7 +142,9 @@ router.post('/', asyncHandler(async (req, res) => {
maxSources: body.maxSources,
providerId: body.providerId,
model: body.model,
+ signal: abortController.signal,
})) {
+ if (aborted) break;
if (evt.type === 'sources') {
assistantSources = evt.sources;
send('sources', { sources: evt.sources });
@@ -147,6 +162,11 @@ router.post('/', asyncHandler(async (req, res) => {
}
}
+ req.off('close', onClose);
+
+ // If the client bailed mid-stream we still persist whatever assistant text
+ // we accumulated so the conversation isn't silently lossy on reconnect,
+ // but we don't try to write any more SSE frames to a dead socket.
let persistedAssistantTurn = null;
if (!streamErrored && assistantText) {
const result = await convs.appendTurn(conversation.id, {
@@ -159,10 +179,12 @@ router.post('/', asyncHandler(async (req, res) => {
persistedAssistantTurn = result.turn;
}
- // 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 (!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();
+ }
}));
export default router;
diff --git a/server/services/askConversations.js b/server/services/askConversations.js
index a056467fd8..acb7f61dfa 100644
--- a/server/services/askConversations.js
+++ b/server/services/askConversations.js
@@ -165,6 +165,7 @@ export async function deleteConversation(id) {
}
export async function setPromoted(id, promoted) {
+ if (!isValidId(id)) return null;
const conv = await readConversation(id);
if (!conv) return null;
conv.promoted = !!promoted;
diff --git a/server/services/askService.js b/server/services/askService.js
index 8428ad9e0f..ccae90828c 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -198,11 +198,15 @@ async function retrieveCalendar(question, queryTokens, timeWindow) {
const events = result?.events || [];
const ranked = events.map((e) => {
const text = `${e.title || ''} ${e.description || ''} ${e.location || ''}`.trim();
+ // Emit raw ISO startTime (or whatever the calendar gave us) — formatting
+ // via toLocaleString() would silently apply the *server* TZ/locale,
+ // baking inconsistent timestamps into prompts when the server and user
+ // disagree on timezone.
return {
kind: 'calendar',
id: `calendar:${e.id || `${e.startTime}-${e.title}`}`,
title: e.title || '(event)',
- snippet: [e.startTime ? new Date(e.startTime).toLocaleString() : '', e.location || '', (e.description || '').slice(0, 200)].filter(Boolean).join(' · '),
+ snippet: [e.startTime || '', e.location || '', (e.description || '').slice(0, 200)].filter(Boolean).join(' · '),
href: `/calendar/agenda?date=${encodeURIComponent(e.startTime || '')}`,
relevance: lexicalScore(text, queryTokens),
meta: { startTime: e.startTime, endTime: e.endTime, accountId: e.accountId },
@@ -334,11 +338,19 @@ async function pickProvider(providerId) {
/**
* Stream a completion from an API-style provider. Yields text chunks.
* Falls back to a single-shot call for non-streaming providers (CLI).
+ *
+ * `signal` (optional) is an external AbortSignal — when the caller aborts
+ * (e.g. SSE client disconnects), the provider fetch / child process is
+ * cancelled so we stop wasting tokens/CPU on a stream nobody's reading.
*/
-async function* streamCompletion(provider, model, prompt) {
+async function* streamCompletion(provider, model, prompt, signal) {
if (provider.type === 'api') {
const headers = { 'Content-Type': 'application/json' };
if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
+ // Combine the per-provider timeout with the caller's abort signal so
+ // either one tearing down propagates to the upstream fetch.
+ const timeoutSignal = AbortSignal.timeout(provider.timeout || 300000);
+ const fetchSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
const response = await fetch(`${provider.endpoint}/chat/completions`, {
method: 'POST',
headers,
@@ -348,7 +360,7 @@ async function* streamCompletion(provider, model, prompt) {
temperature: 0.4,
stream: true,
}),
- signal: AbortSignal.timeout(provider.timeout || 300000),
+ signal: fetchSignal,
});
if (!response.ok || !response.body) {
const text = await response.text().catch(() => '');
@@ -358,6 +370,10 @@ async function* streamCompletion(provider, model, prompt) {
const decoder = new TextDecoder();
let buffer = '';
while (true) {
+ if (signal?.aborted) {
+ await reader.cancel().catch(() => {});
+ return;
+ }
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
@@ -401,12 +417,18 @@ async function* streamCompletion(provider, model, prompt) {
child.stdout.on('data', (d) => { buf += d.toString(); });
child.stderr.on('data', (d) => { buf += d.toString(); });
const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error('CLI timed out')); }, provider.timeout || 300000);
+ const onAbort = () => { child.kill('SIGKILL'); reject(new Error('aborted')); };
+ if (signal) {
+ if (signal.aborted) { onAbort(); return; }
+ signal.addEventListener('abort', onAbort, { once: true });
+ }
child.on('close', (code) => {
clearTimeout(timer);
+ signal?.removeEventListener('abort', onAbort);
if (code === 0) resolve(buf);
else reject(new Error(`CLI exited ${code}: ${buf.slice(0, 500)}`));
});
- child.on('error', (err) => { clearTimeout(timer); reject(err); });
+ child.on('error', (err) => { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); reject(err); });
});
yield out;
}
@@ -426,6 +448,9 @@ async function* streamCompletion(provider, model, prompt) {
* @param {number} [opts.maxSources]
* @param {string} [opts.providerId]
* @param {string} [opts.model]
+ * @param {AbortSignal} [opts.signal] - Aborts retrieval/provider stream when
+ * the caller (e.g. SSE client) disconnects, so we don't keep generating
+ * tokens for a closed connection.
*/
export async function* runAsk({
question,
@@ -435,6 +460,7 @@ export async function* runAsk({
maxSources = 12,
providerId,
model,
+ signal,
}) {
if (!question || typeof question !== 'string' || !question.trim()) {
yield { type: 'error', error: 'question is required' };
@@ -453,6 +479,7 @@ export async function* runAsk({
return;
}
+ if (signal?.aborted) return;
yield { type: 'sources', sources };
let provider;
@@ -473,12 +500,14 @@ export async function* runAsk({
// stream has started, we can't change to a 5xx response any longer.
let answer = '';
try {
- for await (const chunk of streamCompletion(provider, effectiveModel, prompt)) {
+ for await (const chunk of streamCompletion(provider, effectiveModel, prompt, signal)) {
+ if (signal?.aborted) return;
if (!chunk) continue;
answer += chunk;
yield { type: 'delta', text: chunk };
}
} catch (err) {
+ if (signal?.aborted) return;
yield { type: 'error', error: `Provider stream failed: ${err.message}` };
return;
}