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

add the Brain Threads tab, Open Threads dashboard widget and thread search (#7664)

[._.]/ Adam Eivy898399146b18
diff --git a/client/src/components/brain/constants.js b/client/src/components/brain/constants.js
index d47904a466..2e0cd490f0 100644
--- a/client/src/components/brain/constants.js
+++ b/client/src/components/brain/constants.js
@@ -1,4 +1,4 @@
-import { MessageSquare, Database, Calendar, Rss, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2, BookOpen, Network, FileText, NotebookPen, Upload, Target, BookText, Music, Video } from 'lucide-react';
+import { MessageSquare, Database, Calendar, Rss, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2, BookOpen, Network, FileText, NotebookPen, Upload, Target, BookText, Music, Video, ListTodo } from 'lucide-react';
import { getPageNavTabs } from '../../../../server/lib/navManifest.js';
import { buildPageNavTabs } from '../../lib/pageNavTabs.js';
@@ -10,6 +10,7 @@ import { buildPageNavTabs } from '../../lib/pageNavTabs.js';
// drift between the manifest and this map.
const TAB_PRESENTATION = {
inbox: { icon: MessageSquare },
+ threads: { icon: ListTodo, fullBleed: true },
ideas: { icon: Lightbulb },
'daily-log': { icon: NotebookPen, fullBleed: true },
links: { icon: Link2 },
diff --git a/client/src/components/brain/constants.test.js b/client/src/components/brain/constants.test.js
index 0860ab9adf..36c5f2e060 100644
--- a/client/src/components/brain/constants.test.js
+++ b/client/src/components/brain/constants.test.js
@@ -16,7 +16,7 @@ describe('Brain navigation', () => {
describe('Brain TABS ↔ nav manifest', () => {
it('renders the brain tabGroup in page order with a presentation entry each', () => {
expectPageNavTabs(TABS, [
- 'inbox:Inbox', 'ideas:Ideas', 'daily-log:Daily Log', 'links:Links',
+ 'inbox:Inbox', 'threads:Threads', 'ideas:Ideas', 'daily-log:Daily Log', 'links:Links',
'memory:Memory', 'notes:Notes', 'graph:Graph', 'digest:Digest',
'feeds:Feeds', 'trust:Trust', 'import:Import', 'spotify:Spotify',
'youtube:YouTube', 'config:Config',
@@ -24,6 +24,6 @@ describe('Brain TABS ↔ nav manifest', () => {
});
it('keeps the full-bleed set derived from the presentation map', () => {
- expect([...FULL_BLEED_TAB_IDS].sort()).toEqual(['daily-log', 'graph', 'notes']);
+ expect([...FULL_BLEED_TAB_IDS].sort()).toEqual(['daily-log', 'graph', 'notes', 'threads']);
});
});
diff --git a/client/src/components/brain/tabs/ThreadsTab.jsx b/client/src/components/brain/tabs/ThreadsTab.jsx
new file mode 100644
index 0000000000..1261d616d4
--- /dev/null
+++ b/client/src/components/brain/tabs/ThreadsTab.jsx
@@ -0,0 +1,541 @@
+// Brain > Threads — the bullet journal's open loops (#7664).
+//
+// A *thread* is one tracked topic or commitment: a status, a next action, and
+// refs to the PortOS records and external items that belong to it. It is NOT a
+// message thread (messages/ owns that sense of the word).
+//
+// Everything selectable lives in the URL (client/src/AGENTS.md): the filters
+// (`?status=`, `?tag=`, `?q=`), the open record (`?thread=<id>`) and the
+// drawer's section (`?threadTab=`), so the dashboard widget, unified search and
+// a shared link all land on the same drawer. Full-bleed: this tab owns its own
+// scroll region like the Daily Log.
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { Link } from 'react-router';
+import { Check, ExternalLink, Info, Link2, ListTodo, Pin, Plus, Search, Trash2, X } from 'lucide-react';
+import useUrlParams from '../../../hooks/useUrlParams';
+import useDrawerTab from '../../../hooks/useDrawerTab';
+import useAsyncAction from '../../../hooks/useAsyncAction';
+import * as api from '../../../services/api';
+import Drawer from '../../Drawer';
+import Pill from '../../ui/Pill';
+import TabPills from '../../ui/TabPills';
+import { FormField } from '../../ui/FormField';
+import InlineConfirmRow from '../../ui/InlineConfirmRow';
+import toast from '../../ui/Toast';
+import { THREAD_REF_KIND_IDS, threadRefLabel } from '../../../lib/threadRefKinds.js';
+import { formatCount, formatDateShort } from '../../../utils/formatters';
+
+const TERMINAL = new Set(['done', 'archived']);
+const isTerminal = (status) => TERMINAL.has(status);
+const isOverdue = (thread) =>
+ !isTerminal(thread.status) && typeof thread.dueAt === 'string' && Date.parse(thread.dueAt) < Date.now();
+
+// `?status=` views. `all` is the working set — every non-terminal thread,
+// grouped — and the only view that groups; a single status is one flat list.
+const STATUS_VIEWS = [
+ { id: 'all', label: 'Open loops' },
+ { id: 'open', label: 'Open' },
+ { id: 'waiting', label: 'Waiting' },
+ { id: 'someday', label: 'Someday' },
+ { id: 'done', label: 'Done' },
+ { id: 'archived', label: 'Archived' },
+];
+const STATUS_IDS = STATUS_VIEWS.map((v) => v.id);
+
+const PRIORITY_TONE = { urgent: 'error', high: 'warning', low: 'note' };
+const PRIORITIES = ['low', 'normal', 'high', 'urgent'];
+const STATUSES = ['open', 'waiting', 'someday', 'done', 'archived'];
+
+const DRAWER_TABS = [
+ { id: 'details', label: 'Details', icon: Info },
+ { id: 'links', label: 'Links', icon: Link2 },
+ { id: 'notes', label: 'Notes', icon: ListTodo },
+];
+const DRAWER_TAB_IDS = DRAWER_TABS.map((t) => t.id);
+
+// Working-set grouping, in reading order. Pinned and overdue are pulled out of
+// their status so the list answers "what needs me first?" before "what is
+// there?". A pinned overdue thread counts as pinned (it is already at the top).
+const GROUPS = [
+ { id: 'pinned', label: 'Pinned', pick: (t) => t.pinned },
+ { id: 'overdue', label: 'Overdue', pick: (t) => isOverdue(t) },
+ { id: 'open', label: 'Open', pick: (t) => t.status === 'open' },
+ { id: 'waiting', label: 'Waiting', pick: (t) => t.status === 'waiting' },
+ { id: 'someday', label: 'Someday', pick: (t) => t.status === 'someday' },
+];
+
+function groupThreads(threads) {
+ const remaining = [...threads];
+ return GROUPS.map((group) => {
+ const items = remaining.filter(group.pick);
+ for (const item of items) remaining.splice(remaining.indexOf(item), 1);
+ return { ...group, items };
+ }).filter((group) => group.items.length > 0);
+}
+
+// The list projection omits `notes`; keep a saved full record's row in step
+// with it without leaking the body into the list state.
+const toRow = ({ notes, resolvedRefs, ...rest }) => rest;
+
+// Form draft ⇄ record. `dueAt` is stored as an ISO timestamp and edited as a
+// local calendar date; tags are edited as one comma-separated line.
+const toDraft = (thread) => ({
+ title: thread.title ?? '',
+ status: thread.status ?? 'open',
+ priority: thread.priority ?? 'normal',
+ pinned: Boolean(thread.pinned),
+ nextAction: thread.nextAction ?? '',
+ waitingOn: thread.waitingOn ?? '',
+ dueAt: typeof thread.dueAt === 'string' ? thread.dueAt.slice(0, 10) : '',
+ tags: Array.isArray(thread.tags) ? thread.tags.join(', ') : '',
+ notes: thread.notes ?? '',
+});
+
+const draftToPatch = (draft) => ({
+ title: draft.title.trim(),
+ status: draft.status,
+ priority: draft.priority,
+ pinned: draft.pinned,
+ nextAction: draft.nextAction,
+ waitingOn: draft.waitingOn,
+ // Explicit null clears a stored date (absent would preserve it).
+ dueAt: draft.dueAt ? new Date(`${draft.dueAt}T00:00:00`).toISOString() : null,
+ tags: draft.tags.split(',').map((t) => t.trim()).filter(Boolean),
+ notes: draft.notes,
+});
+
+const inputClass = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent';
+
+function RefChip({ item, onRemove }) {
+ const label = item.label || item.id;
+ const body = (
+ <span className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded border border-port-border bg-port-bg text-gray-200">
+ <span className="text-gray-500">{threadRefLabel(item.kind)}</span>
+ <span className="max-w-[16rem] truncate" title={label}>{label}</span>
+ {item.url && <ExternalLink size={10} aria-hidden="true" />}
+ </span>
+ );
+ const external = typeof item.url === 'string' && /^https?:/.test(item.url);
+ return (
+ <span className="inline-flex items-center gap-1">
+ {!item.url && body}
+ {item.url && external && <a href={item.url} target="_blank" rel="noreferrer" className="hover:text-white">{body}</a>}
+ {item.url && !external && <Link to={item.url} className="hover:text-white">{body}</Link>}
+ {item.resolved === false && (
+ <Pill tone="warning" size="xs" title={item.reason}>{item.reason === 'unknown-kind' ? 'unknown kind' : 'missing'}</Pill>
+ )}
+ {onRemove && (
+ <button
+ type="button"
+ onClick={onRemove}
+ className="p-0.5 text-gray-500 hover:text-port-error"
+ aria-label={`Remove ${label}`}
+ >
+ <X size={12} />
+ </button>
+ )}
+ </span>
+ );
+}
+
+function ThreadRow({ thread, onOpen, onDone, onTag }) {
+ const overdue = isOverdue(thread);
+ const refCount = Array.isArray(thread.refs) ? thread.refs.length : 0;
+ return (
+ <li className="flex items-start gap-2 px-3 py-2 rounded-lg border border-port-border bg-port-card hover:border-port-accent/50">
+ {!isTerminal(thread.status) && (
+ <button
+ type="button"
+ onClick={() => onDone(thread)}
+ className="mt-0.5 shrink-0 w-5 h-5 rounded border border-port-border text-transparent hover:text-port-success hover:border-port-success flex items-center justify-center"
+ aria-label={`Mark "${thread.title}" done`}
+ title="Mark done"
+ >
+ <Check size={12} />
+ </button>
+ )}
+ <button type="button" onClick={() => onOpen(thread)} className="flex-1 min-w-0 text-left">
+ <div className="flex items-center gap-2 min-w-0">
+ {thread.pinned && <Pin size={12} className="shrink-0 text-port-accent" aria-label="Pinned" />}
+ <span className="truncate text-sm text-white">{thread.title}</span>
+ {thread.priority && thread.priority !== 'normal' && (
+ <Pill tone={PRIORITY_TONE[thread.priority] || 'muted'} size="xs">{thread.priority}</Pill>
+ )}
+ {thread.externalState === 'closed' && <Pill tone="warning" size="xs">source closed</Pill>}
+ </div>
+ {(thread.nextAction || thread.waitingOn) && (
+ <div className="text-xs text-gray-400 truncate">
+ {thread.status === 'waiting' && thread.waitingOn ? `Waiting on ${thread.waitingOn}` : `→ ${thread.nextAction || thread.waitingOn}`}
+ </div>
+ )}
+ </button>
+ <div className="shrink-0 flex flex-wrap items-center justify-end gap-1 max-w-[40%]">
+ {thread.dueAt && (
+ <Pill tone={overdue ? 'error' : 'muted'} size="xs">{formatDateShort(thread.dueAt)}</Pill>
+ )}
+ {refCount > 0 && <Pill tone="muted" size="xs" icon={Link2}>{formatCount(refCount)}</Pill>}
+ {(thread.tags || []).slice(0, 3).map((tag) => (
+ <button key={tag} type="button" onClick={() => onTag(tag)} className="text-xs text-gray-500 hover:text-port-accent">#{tag}</button>
+ ))}
+ </div>
+ </li>
+ );
+}
+
+export default function ThreadsTab() {
+ const [searchParams, updateParams] = useUrlParams();
+ const statusParam = searchParams.get('status');
+ const statusView = STATUS_IDS.includes(statusParam) ? statusParam : 'all';
+ const tag = searchParams.get('tag') || '';
+ const q = searchParams.get('q') || '';
+ const selectedId = searchParams.get('thread');
+ const [drawerTab, setDrawerTab] = useDrawerTab('threadTab', 'details', DRAWER_TAB_IDS);
+
+ const [threads, setThreads] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [newTitle, setNewTitle] = useState('');
+ const [record, setRecord] = useState(null);
+ const [draft, setDraft] = useState(null);
+ const [confirmDelete, setConfirmDelete] = useState(false);
+ const [newRef, setNewRef] = useState({ kind: 'url', id: '', label: '' });
+
+ // List — refetched when a URL filter moves. The `all` view asks for every
+ // thread and drops the terminal ones here, so a done thread disappears the
+ // moment it is checked off instead of after the next fetch.
+ useEffect(() => {
+ let active = true;
+ setLoading(true);
+ const filters = { q, tag, ...(statusView === 'all' ? {} : { status: statusView }) };
+ api.listThreads(filters)
+ .then((res) => {
+ if (!active) return;
+ const rows = Array.isArray(res?.threads) ? res.threads : [];
+ setThreads(statusView === 'all' ? rows.filter((t) => !isTerminal(t.status)) : rows);
+ })
+ .catch(() => { if (active) setThreads([]); })
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ }, [q, tag, statusView]);
+
+ // Open record — keyed to the URL so a deep link and a row click share the path.
+ const loadRecord = useCallback((id) => api.getThread(id, { silent: true }), []);
+ useEffect(() => {
+ if (!selectedId) {
+ setRecord(null);
+ setDraft(null);
+ setConfirmDelete(false);
+ return undefined;
+ }
+ let active = true;
+ loadRecord(selectedId)
+ .then((full) => {
+ if (!active) return;
+ setRecord(full);
+ setDraft(toDraft(full));
+ })
+ .catch(() => {
+ if (!active) return;
+ toast.error('Thread not found');
+ updateParams({ thread: null, threadTab: null }, { replace: true });
+ });
+ return () => { active = false; };
+ }, [selectedId, loadRecord, updateParams]);
+
+ const groups = useMemo(
+ () => (statusView === 'all' ? groupThreads(threads) : [{ id: statusView, label: STATUS_VIEWS.find((v) => v.id === statusView).label, items: threads }]),
+ [threads, statusView],
+ );
+
+ const openThread = (thread) => updateParams({ thread: thread.id });
+ const closeDrawer = () => updateParams({ thread: null, threadTab: null }, { replace: true });
+ const setView = (id) => updateParams({ status: id === 'all' ? null : id }, { replace: true });
+ const setTag = (next) => updateParams({ tag: next === tag ? null : next }, { replace: true });
+ const setQuery = (next) => updateParams({ q: next }, { replace: true });
+
+ const replaceRow = (thread) => setThreads((prev) => {
+ const row = toRow(thread);
+ const visible = statusView === 'all' ? !isTerminal(row.status) : row.status === statusView;
+ const without = prev.filter((t) => t.id !== row.id);
+ return visible ? [row, ...without].sort(sortRows) : without;
+ });
+
+ const [create, creating] = useAsyncAction(async () => {
+ const title = newTitle.trim();
+ if (!title) return null;
+ const thread = await api.createThread({ title }, { silent: true });
+ setNewTitle('');
+ replaceRow(thread);
+ updateParams({ thread: thread.id });
+ return thread;
+ }, { errorMessage: 'Failed to create thread' });
+
+ const [markDone] = useAsyncAction(async (thread) => {
+ const updated = await api.updateThread(thread.id, { status: 'done' }, { silent: true });
+ replaceRow(updated);
+ toast.success(`Done: ${updated.title}`);
+ return updated;
+ }, { errorMessage: 'Failed to update thread' });
+
+ const [save, saving] = useAsyncAction(async () => {
+ if (!record || !draft) return null;
+ if (!draft.title.trim()) {
+ toast.error('A thread needs a title');
+ setDrawerTab('details');
+ return null;
+ }
+ const updated = await api.updateThread(record.id, draftToPatch(draft), { silent: true });
+ setRecord((prev) => ({ ...prev, ...updated }));
+ setDraft(toDraft(updated));
+ replaceRow(updated);
+ toast.success('Thread saved');
+ return updated;
+ }, { errorMessage: 'Failed to save thread' });
+
+ const [remove, removing] = useAsyncAction(async () => {
+ await api.deleteThread(record.id, { silent: true });
+ setThreads((prev) => prev.filter((t) => t.id !== record.id));
+ closeDrawer();
+ toast.success('Thread deleted');
+ return true;
+ }, { errorMessage: 'Failed to delete thread' });
+
+ // Ref writes return the bare thread; re-read so `resolvedRefs` is hydrated.
+ const [addRef, addingRef] = useAsyncAction(async () => {
+ const id = newRef.id.trim();
+ if (!id) return null;
+ const ref = { kind: newRef.kind, id, ...(newRef.label.trim() ? { label: newRef.label.trim() } : {}) };
+ await api.addThreadRef(record.id, ref, { silent: true });
+ const full = await loadRecord(record.id);
+ setRecord(full);
+ replaceRow(full);
+ setNewRef({ kind: newRef.kind, id: '', label: '' });
+ return full;
+ }, { errorMessage: 'Failed to add link' });
+
+ const [removeRef] = useAsyncAction(async (item) => {
+ await api.removeThreadRef(record.id, item.kind, item.id, { silent: true });
+ const full = await loadRecord(record.id);
+ setRecord(full);
+ replaceRow(full);
+ return full;
+ }, { errorMessage: 'Failed to remove link' });
+
+ const patchDraft = (patch) => setDraft((prev) => ({ ...prev, ...patch }));
+ const dirty = record && draft && JSON.stringify(draft) !== JSON.stringify(toDraft(record));
+
+ return (
+ <div className="flex flex-col h-full min-h-0">
+ <div className="shrink-0 px-4 pt-4 pb-2 space-y-3 border-b border-port-border">
+ <form
+ className="flex gap-2"
+ onSubmit={(e) => { e.preventDefault(); create(); }}
+ >
+ <label htmlFor="brain-threads-new" className="sr-only">New thread</label>
+ <input
+ id="brain-threads-new"
+ value={newTitle}
+ onChange={(e) => setNewTitle(e.target.value)}
+ placeholder="Track a new open loop…"
+ className={inputClass}
+ />
+ <button
+ type="submit"
+ disabled={creating || !newTitle.trim()}
+ className="shrink-0 inline-flex items-center gap-1 px-3 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-50"
+ >
+ <Plus size={14} /> Add
+ </button>
+ </form>
+ <div className="flex flex-wrap items-center gap-2">
+ <TabPills
+ tabs={STATUS_VIEWS}
+ activeTab={statusView}
+ onChange={setView}
+ variant="pills"
+ size="sm"
+ ariaLabel="Thread status"
+ controlsIdPrefix="brain-threads"
+ />
+ <div className="relative flex-1 min-w-[10rem]">
+ <Search size={14} className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-500" aria-hidden="true" />
+ <label htmlFor="brain-threads-q" className="sr-only">Search threads</label>
+ <input
+ id="brain-threads-q"
+ value={q}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search"
+ className={`${inputClass} pl-7 py-1.5`}
+ />
+ </div>
+ {tag && (
+ <button type="button" onClick={() => setTag(tag)} className="inline-flex items-center gap-1 text-xs text-port-accent">
+ #{tag} <X size={12} aria-label={`Clear tag ${tag}`} />
+ </button>
+ )}
+ </div>
+ </div>
+
+ <div id={`brain-threads-${statusView}`} role="tabpanel" aria-labelledby={`tab-${statusView}`} className="flex-1 min-h-0 overflow-y-auto p-4 space-y-5">
+ {loading && threads.length === 0 && <p className="text-sm text-gray-500">Loading threads…</p>}
+ {!loading && threads.length === 0 && (
+ <p className="text-sm text-gray-500">
+ {q || tag ? 'No threads match.' : 'Nothing tracked yet — add the first open loop above.'}
+ </p>
+ )}
+ {groups.map((group) => (
+ <section key={group.id} aria-label={group.label}>
+ <h3 className="text-xs uppercase tracking-wide text-gray-500 mb-2">
+ {group.label} <span className="text-gray-600">{formatCount(group.items.length)}</span>
+ </h3>
+ <ul className="space-y-1.5">
+ {group.items.map((thread) => (
+ <ThreadRow key={thread.id} thread={thread} onOpen={openThread} onDone={markDone} onTag={setTag} />
+ ))}
+ </ul>
+ </section>
+ ))}
+ </div>
+
+ <Drawer
+ open={Boolean(selectedId)}
+ onClose={closeDrawer}
+ title="Thread"
+ subtitle={record?.title}
+ size="lg"
+ tabs={DRAWER_TABS}
+ activeTab={drawerTab}
+ onTabChange={setDrawerTab}
+ closeLabel="Close thread"
+ closeOnEsc={!dirty}
+ closeOnBackdrop={!dirty}
+ >
+ {record && draft && (
+ <div className="space-y-4">
+ <div className="flex items-center justify-end gap-2">
+ {dirty && <span className="text-xs text-port-warning">Unsaved changes</span>}
+ <button
+ type="button"
+ onClick={save}
+ disabled={saving || !dirty}
+ className="px-3 py-1.5 rounded bg-port-accent text-white text-sm disabled:opacity-50"
+ >
+ {saving ? 'Saving…' : 'Save'}
+ </button>
+ </div>
+
+ {drawerTab === 'details' && (
+ <div className="space-y-3">
+ <FormField label="Title">
+ <input value={draft.title} onChange={(e) => patchDraft({ title: e.target.value })} className={inputClass} maxLength={200} />
+ </FormField>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
+ <FormField label="Status">
+ <select value={draft.status} onChange={(e) => patchDraft({ status: e.target.value })} className={inputClass}>
+ {STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
+ </select>
+ </FormField>
+ <FormField label="Priority">
+ <select value={draft.priority} onChange={(e) => patchDraft({ priority: e.target.value })} className={inputClass}>
+ {PRIORITIES.map((p) => <option key={p} value={p}>{p}</option>)}
+ </select>
+ </FormField>
+ <FormField label="Due">
+ <input type="date" value={draft.dueAt} onChange={(e) => patchDraft({ dueAt: e.target.value })} className={inputClass} />
+ </FormField>
+ </div>
+ <FormField label="Next action" hint="The one concrete next step.">
+ <input value={draft.nextAction} onChange={(e) => patchDraft({ nextAction: e.target.value })} className={inputClass} maxLength={500} />
+ </FormField>
+ <FormField label="Waiting on">
+ <input value={draft.waitingOn} onChange={(e) => patchDraft({ waitingOn: e.target.value })} className={inputClass} maxLength={200} />
+ </FormField>
+ <FormField label="Tags" hint="Comma-separated.">
+ <input value={draft.tags} onChange={(e) => patchDraft({ tags: e.target.value })} className={inputClass} />
+ </FormField>
+ <label className="inline-flex items-center gap-2 text-sm text-gray-300">
+ <input type="checkbox" checked={draft.pinned} onChange={(e) => patchDraft({ pinned: e.target.checked })} />
+ Pinned
+ </label>
+ {record.externalState === 'closed' && (
+ <p className="text-xs text-port-warning">The source this thread was discovered from is closed. Mark it done when you are.</p>
+ )}
+ <div className="pt-2 border-t border-port-border">
+ {confirmDelete ? (
+ <InlineConfirmRow
+ question="Delete this thread?"
+ onConfirm={remove}
+ onCancel={() => setConfirmDelete(false)}
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={() => setConfirmDelete(true)}
+ disabled={removing}
+ className="inline-flex items-center gap-1 text-xs text-gray-500 hover:text-port-error"
+ >
+ <Trash2 size={12} /> Delete thread
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+
+ {drawerTab === 'links' && (
+ <div className="space-y-4">
+ <div className="flex flex-wrap gap-2">
+ {(record.resolvedRefs || []).length === 0 && <p className="text-sm text-gray-500">No links yet.</p>}
+ {(record.resolvedRefs || []).map((item) => (
+ <RefChip key={`${item.kind}:${item.id}`} item={item} onRemove={() => removeRef(item)} />
+ ))}
+ </div>
+ <form
+ className="grid grid-cols-1 gap-2 sm:grid-cols-[10rem_1fr_1fr_auto] items-end"
+ onSubmit={(e) => { e.preventDefault(); addRef(); }}
+ >
+ <FormField label="Kind" compact>
+ <select value={newRef.kind} onChange={(e) => setNewRef((p) => ({ ...p, kind: e.target.value }))} className={inputClass}>
+ {THREAD_REF_KIND_IDS.map((kind) => <option key={kind} value={kind}>{threadRefLabel(kind)}</option>)}
+ </select>
+ </FormField>
+ <FormField label="Id or URL" compact>
+ <input value={newRef.id} onChange={(e) => setNewRef((p) => ({ ...p, id: e.target.value }))} className={inputClass} />
+ </FormField>
+ <FormField label="Label" compact>
+ <input value={newRef.label} onChange={(e) => setNewRef((p) => ({ ...p, label: e.target.value }))} className={inputClass} maxLength={300} />
+ </FormField>
+ <button type="submit" disabled={addingRef || !newRef.id.trim()} className="px-3 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-50">
+ Add link
+ </button>
+ </form>
+ </div>
+ )}
+
+ {drawerTab === 'notes' && (
+ <FormField label="Notes" hint="Markdown.">
+ <textarea
+ value={draft.notes}
+ onChange={(e) => patchDraft({ notes: e.target.value })}
+ className={`${inputClass} min-h-[16rem] font-mono`}
+ maxLength={20000}
+ />
+ </FormField>
+ )}
+ </div>
+ )}
+ </Drawer>
+ </div>
+ );
+}
+
+// Client mirror of the server's list order (pinned, soonest due, most
+// recently touched) so a row updated in place lands where a refetch would.
+const dueKey = (t) => { const v = Date.parse(t?.dueAt ?? ''); return Number.isNaN(v) ? Infinity : v; };
+function sortRows(a, b) {
+ if (Boolean(b.pinned) !== Boolean(a.pinned)) return Boolean(b.pinned) - Boolean(a.pinned);
+ const ad = dueKey(a);
+ const bd = dueKey(b);
+ if (ad !== bd) return ad - bd;
+ const touched = Date.parse(b?.updatedAt ?? '') - Date.parse(a?.updatedAt ?? '');
+ if (!Number.isNaN(touched) && touched !== 0) return touched;
+ return String(a.id).localeCompare(String(b.id));
+}
diff --git a/client/src/components/brain/tabs/ThreadsTab.test.jsx b/client/src/components/brain/tabs/ThreadsTab.test.jsx
new file mode 100644
index 0000000000..a68e4b6366
--- /dev/null
+++ b/client/src/components/brain/tabs/ThreadsTab.test.jsx
@@ -0,0 +1,112 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter, useLocation } from 'react-router';
+
+vi.mock('../../../services/api', () => ({
+ listThreads: vi.fn(),
+ getThread: vi.fn(),
+ createThread: vi.fn(),
+ updateThread: vi.fn(),
+ deleteThread: vi.fn(),
+ addThreadRef: vi.fn(),
+ removeThreadRef: vi.fn(),
+}));
+vi.mock('../../ui/Toast', () => ({ default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));
+
+import * as api from '../../../services/api';
+import ThreadsTab from './ThreadsTab';
+
+const FAR_FUTURE = '2999-01-01T00:00:00.000Z';
+const PAST = '2000-01-01T00:00:00.000Z';
+
+const ROWS = [
+ { id: 'pin', title: 'Pinned loop', status: 'open', pinned: true, refs: [], tags: [] },
+ { id: 'late', title: 'Overdue loop', status: 'open', dueAt: PAST, refs: [{ kind: 'url', id: 'https://example.com' }], tags: ['ops'] },
+ { id: 'op', title: 'Plain loop', status: 'open', nextAction: 'Call back', dueAt: FAR_FUTURE, refs: [], tags: [] },
+ { id: 'wait', title: 'Waiting loop', status: 'waiting', waitingOn: 'Acme Corp', refs: [], tags: [] },
+ { id: 'done', title: 'Finished loop', status: 'done', refs: [], tags: [] },
+];
+
+function Location() {
+ return <output data-testid="location">{useLocation().search}</output>;
+}
+
+const renderTab = (entry = '/brain/threads') =>
+ render(<MemoryRouter initialEntries={[entry]}><ThreadsTab /><Location /></MemoryRouter>);
+
+describe('ThreadsTab', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.listThreads.mockResolvedValue({ threads: ROWS, total: ROWS.length });
+ api.getThread.mockImplementation(async (id) => ({
+ ...ROWS.find((r) => r.id === id),
+ notes: 'body',
+ resolvedRefs: [{ kind: 'url', id: 'https://example.com', label: 'example', url: 'https://example.com', resolved: true }],
+ }));
+ });
+
+ it('groups the working set (pinned, overdue, open, waiting) and hides finished threads', async () => {
+ renderTab();
+ await screen.findByText('Pinned loop');
+ const groupTitles = screen.getAllByRole('heading', { level: 3 }).map((h) => h.textContent.trim());
+ expect(groupTitles).toEqual(['Pinned 1', 'Overdue 1', 'Open 1', 'Waiting 1']);
+ expect(screen.getByText('Waiting on Acme Corp')).toBeTruthy();
+ expect(screen.queryByText('Finished loop')).toBeNull();
+ expect(api.listThreads).toHaveBeenCalledWith({ q: '', tag: '' });
+ });
+
+ it('reads the status, tag and search filters from the URL and sends them to the server', async () => {
+ api.listThreads.mockResolvedValue({ threads: [ROWS[4]], total: 1 });
+ renderTab('/brain/threads?status=done&tag=ops&q=fin');
+ await screen.findByText('Finished loop');
+ expect(api.listThreads).toHaveBeenCalledWith({ q: 'fin', tag: 'ops', status: 'done' });
+ expect(screen.getAllByRole('heading', { level: 3 }).map((h) => h.textContent.trim())).toEqual(['Done 1']);
+ });
+
+ it('opens the drawer for the thread named in the URL on load', async () => {
+ renderTab('/brain/threads?thread=late&threadTab=links');
+ await screen.findByRole('dialog');
+ expect(api.getThread).toHaveBeenCalledWith('late', { silent: true });
+ // The Links tab renders the hydrated ref with its click-through.
+ const chip = await screen.findByText('example');
+ expect(chip.closest('a')).toHaveAttribute('href', 'https://example.com');
+ });
+
+ it('puts the selected thread in the URL when a row is clicked, not in local state', async () => {
+ renderTab();
+ fireEvent.click(await screen.findByText('Plain loop'));
+ expect(screen.getByTestId('location').textContent).toBe('?thread=op');
+ await screen.findByRole('dialog');
+ expect(screen.getByDisplayValue('Call back')).toBeTruthy();
+ });
+
+ it('checks a thread off in place without refetching the list', async () => {
+ api.updateThread.mockResolvedValue({ ...ROWS[2], status: 'done', closedAt: FAR_FUTURE });
+ renderTab();
+ await screen.findByText('Plain loop');
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Mark "Plain loop" done' })); });
+ expect(api.updateThread).toHaveBeenCalledWith('op', { status: 'done' }, { silent: true });
+ await waitFor(() => expect(screen.queryByText('Plain loop')).toBeNull());
+ expect(api.listThreads).toHaveBeenCalledTimes(1);
+ });
+
+ it('creates a thread from the capture box and opens it', async () => {
+ api.createThread.mockResolvedValue({ id: 'new', title: 'Chase invoice', status: 'open', refs: [], tags: [] });
+ renderTab();
+ await screen.findByText('Pinned loop');
+ fireEvent.change(screen.getByLabelText('New thread'), { target: { value: 'Chase invoice' } });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Add' })); });
+ expect(api.createThread).toHaveBeenCalledWith({ title: 'Chase invoice' }, { silent: true });
+ expect(screen.getByTestId('location').textContent).toBe('?thread=new');
+ });
+
+ it('is the component the Brain page renders for its threads tab', () => {
+ const clientSrc = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
+ const brainPage = readFileSync(join(clientSrc, 'pages', 'Brain.jsx'), 'utf8');
+ expect(brainPage).toContain("import('../components/brain/tabs/ThreadsTab')");
+ expect(brainPage).toMatch(/case 'threads':[\s\S]{0,120}<ThreadsTab\b/);
+ });
+});
diff --git a/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx b/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx
new file mode 100644
index 0000000000..5fdbd3760f
--- /dev/null
+++ b/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx
@@ -0,0 +1,76 @@
+import { Link } from 'react-router';
+import { ListTodo, Pin } from 'lucide-react';
+import * as api from '../../../services/api';
+import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
+import { formatCount, formatDateShort } from '../../../utils/formatters';
+
+// The Brain bullet journal's open loops (#7664) — the same working set the
+// Threads tab shows, with the next action on each, so what you are on the hook
+// for is one glance away. A *thread* here is a tracked topic, never a message
+// thread. Rows deep-link to `?thread=<id>`, which opens the record's drawer.
+//
+// Self-fetched (like UpcomingTasksWidget) rather than read off dashboardState:
+// nothing else on the dashboard needs the list, and the server already orders
+// it pinned-first / soonest-due.
+const ROWS = 6;
+const WORKING = new Set(['open', 'waiting']);
+
+const isOverdue = (t) => typeof t.dueAt === 'string' && Date.parse(t.dueAt) < Date.now();
+
+export default function OpenThreadsWidget() {
+ const { data, loading } = useAutoRefetch(
+ () => api.listThreads({}, { silent: true }),
+ 60_000,
+ );
+
+ if (loading && !data) return null;
+
+ const open = (Array.isArray(data?.threads) ? data.threads : []).filter((t) => WORKING.has(t.status));
+ const rows = open.slice(0, ROWS);
+
+ return (
+ <div className="@container bg-port-card border border-port-border rounded-xl p-4 h-full">
+ <div className="flex items-center justify-between gap-2 mb-3">
+ <Link to="/brain/threads" className="flex items-center gap-2 hover:text-port-accent">
+ <ListTodo size={16} className="text-gray-500" aria-hidden="true" />
+ <h3 className="text-sm font-semibold text-white">Open Threads</h3>
+ </Link>
+ {open.length > 0 && <span className="text-xs text-gray-500">{formatCount(open.length)} open</span>}
+ </div>
+
+ {rows.length === 0 ? (
+ <p className="text-xs text-gray-500">
+ No open loops. <Link to="/brain/threads" className="text-port-accent hover:underline">Track one</Link>
+ </p>
+ ) : (
+ <ul className="space-y-2">
+ {rows.map((t) => (
+ <li key={t.id}>
+ <Link to={`/brain/threads?thread=${encodeURIComponent(t.id)}`} className="group flex items-start gap-2 text-xs">
+ {t.pinned
+ ? <Pin size={12} className="shrink-0 mt-0.5 text-port-accent" aria-label="Pinned" />
+ : <span className="shrink-0 mt-1 w-2 h-2 rounded-full border border-port-border" aria-hidden="true" />}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-gray-300 group-hover:text-white" title={t.title}>{t.title}</span>
+ {(t.nextAction || t.waitingOn) && (
+ <span className="block truncate text-gray-500">
+ {t.status === 'waiting' && t.waitingOn ? `Waiting on ${t.waitingOn}` : t.nextAction || t.waitingOn}
+ </span>
+ )}
+ </span>
+ {t.dueAt && (
+ <span className={`shrink-0 ${isOverdue(t) ? 'text-port-error' : 'text-gray-500'}`}>{formatDateShort(t.dueAt)}</span>
+ )}
+ </Link>
+ </li>
+ ))}
+ </ul>
+ )}
+ {open.length > rows.length && (
+ <Link to="/brain/threads" className="block text-xs text-gray-500 hover:text-port-accent mt-2">
+ +{formatCount(open.length - rows.length)} more
+ </Link>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx b/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx
new file mode 100644
index 0000000000..a5179019bd
--- /dev/null
+++ b/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx
@@ -0,0 +1,60 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+
+// The widget owns only what to show from a fetched list; the polling belongs
+// to useAutoRefetch, which has its own suite.
+const mockUseAutoRefetch = vi.fn();
+vi.mock('../../../hooks/useAutoRefetch', () => ({
+ useAutoRefetch: (...args) => mockUseAutoRefetch(...args),
+}));
+vi.mock('../../../services/api', () => ({ listThreads: vi.fn() }));
+
+import OpenThreadsWidget from './OpenThreadsWidget';
+
+const renderWidget = () => render(<MemoryRouter><OpenThreadsWidget /></MemoryRouter>);
+
+describe('OpenThreadsWidget', () => {
+ it('renders nothing until the first list arrives', () => {
+ mockUseAutoRefetch.mockReturnValue({ data: null, loading: true });
+ const { container } = renderWidget();
+ expect(container.innerHTML).toBe('');
+ });
+
+ it('shows only the working set, with the next action, and deep-links each row to its drawer', () => {
+ mockUseAutoRefetch.mockReturnValue({
+ loading: false,
+ data: {
+ threads: [
+ { id: 'a b', title: 'Renew domain', status: 'open', nextAction: 'Log in to registrar', dueAt: '2000-01-01T00:00:00.000Z' },
+ { id: 't2', title: 'Vendor quote', status: 'waiting', waitingOn: 'Acme Corp' },
+ { id: 't3', title: 'Someday idea', status: 'someday', nextAction: 'x' },
+ { id: 't4', title: 'Finished', status: 'done' },
+ ],
+ },
+ });
+ renderWidget();
+ expect(screen.getByText('Renew domain').closest('a')).toHaveAttribute('href', '/brain/threads?thread=a%20b');
+ expect(screen.getByText('Log in to registrar')).toBeTruthy();
+ expect(screen.getByText('Waiting on Acme Corp')).toBeTruthy();
+ expect(screen.queryByText('Someday idea')).toBeNull();
+ expect(screen.queryByText('Finished')).toBeNull();
+ expect(screen.getByText('2 open')).toBeTruthy();
+ });
+
+ it('caps the list and links the overflow to the tab', () => {
+ mockUseAutoRefetch.mockReturnValue({
+ loading: false,
+ data: { threads: Array.from({ length: 8 }, (_, i) => ({ id: `t${i}`, title: `Loop ${i}`, status: 'open' })) },
+ });
+ renderWidget();
+ expect(screen.getAllByRole('listitem')).toHaveLength(6);
+ expect(screen.getByText('+2 more').closest('a')).toHaveAttribute('href', '/brain/threads');
+ });
+
+ it('offers to track one when the list is empty', () => {
+ mockUseAutoRefetch.mockReturnValue({ loading: false, data: { threads: [] } });
+ renderWidget();
+ expect(screen.getByText('Track one').closest('a')).toHaveAttribute('href', '/brain/threads');
+ });
+});
diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsx
index 9d18564061..634888810b 100644
--- a/client/src/components/dashboard/widgetRegistry.jsx
+++ b/client/src/components/dashboard/widgetRegistry.jsx
@@ -29,6 +29,7 @@ const AutoFixMetricsWidget = lazyWithReload(() => import('./builtins/AutoFixMet
const DailyDriverWidget = lazyWithReload(() => import('./builtins/DailyDriverWidget'));
const TodayAgendaWidget = lazyWithReload(() => import('./builtins/TodayAgendaWidget'));
const OnThisDayWidget = lazyWithReload(() => import('./builtins/OnThisDayWidget'));
+const OpenThreadsWidget = lazyWithReload(() => import('./builtins/OpenThreadsWidget'));
const ActiveProcessingWidget = lazyWithReload(() => import('./ActiveProcessingWidget'));
const DailyActionsWidget = lazyWithReload(() => import('../DailyActionsWidget'));
@@ -75,6 +76,7 @@ export const WIDGETS = [
{ id: 'meatspace-streak', label: 'Health Logging Streak', Component: MeatSpaceStreakWidget, width: 'third', defaultH: 4, gate: (s) => (s.meatspaceLogging?.totalLogged ?? 0) > 0 },
{ id: 'today-agenda', label: 'Today\'s Agenda', Component: TodayAgendaWidget, width: 'third', defaultH: 4, gate: (s) => (s.calendarAgenda?.accountCount ?? 0) > 0 },
{ id: 'on-this-day', label: 'On This Day', Component: OnThisDayWidget, width: 'third', defaultH: 4, gate: (s) => (s.brainOnThisDay?.total ?? 0) > 0 },
+ { id: 'open-threads', label: 'Open Threads', Component: OpenThreadsWidget, width: 'third', defaultH: 4 },
{ id: 'autofix-metrics', label: 'Auto-Fix Telemetry', Component: AutoFixMetricsWidget, width: 'quarter', defaultH: 5 },
{ id: 'active-processing', label: 'Active Processing', Component: ActiveProcessingWidget, width: 'half', defaultH: 5 },
];
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index a72e0d64cb..bc0c134212 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -244,7 +244,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `terminalScroll.js` | Scrolling the Shell terminal by touch, wheel, and page controls. xterm 6 binds **no touch handlers at all**, and a TUI’s ALTERNATE screen buffer has no terminal scrollback, so `scrollLines()` clamps to a no-op there. Normal shell scrollback uses `scrollLines()`; alternate-screen wheel gestures are captured before xterm’s mouse listener and translated to standard PageUp/PageDown input, which OpenCode supports for its message viewport, while apps that explicitly enable terminal mouse tracking keep xterm’s native wheel path. `attachTerminalTouchScroll(terminal)` (→ detach fn) reserves one-finger panning while preserving pinch zoom and adds bounded flick momentum to normal shell scrollback; mouse-aware apps receive row-granular wheel events at the touch coordinates, and only apps without wheel support fall back to page keys. `attachTerminalWheelScroll(terminal)` handles native wheel input, and `scrollTerminalPage(terminal, direction)` powers the `SCROLL_KEYS` buttons. `measureTerminalGeometry(terminal)` takes one layout read per gesture; `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession`. |
| `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. |
| `textUtils.js` | `escapeRegExp(value)`, `countWords(text)`, `isStr(v)` and `isNonBlankStr(v)` re-exported from `server/lib/textUtils.js` — the two members the bundle has callers for (the Writers Room editor and exercise panel and the autobiography tab count words with the same `\S+` rule the server stores). Named exports rather than `export *`, so the file stays the list of what the browser actually uses. Also `pluralize(count, singular, pluralForm?)` — the shared "N item/items" phrasing helper for singular/plural counts. |
-| `threadRefKinds.js` | Re-export of `server/lib/threadRefKinds.js` — the Brain THREAD ref vocabulary and `(kind, id)` → label/URL route table (a *thread* is a tracked topic or commitment, never a message thread). Named exports only — just `threadRefLabel`/`threadRefUrl`, the two the client renders with. `pages/CatalogIngredient.jsx` renders its inbound-ref chips through `threadRefUrl`/`threadRefLabel` here instead of its own local switch, so the repo has exactly one kind→route table. |
+| `threadRefKinds.js` | Re-export of `server/lib/threadRefKinds.js` — the Brain THREAD ref vocabulary and `(kind, id)` → label/URL route table (a *thread* is a tracked topic or commitment, never a message thread). Named exports only — `threadRefLabel`/`threadRefUrl` (what the client renders with) and `THREAD_REF_KIND_IDS` (what the Threads tab's ref picker enumerates). `pages/CatalogIngredient.jsx` renders its inbound-ref chips through `threadRefUrl`/`threadRefLabel` here instead of its own local switch, so the repo has exactly one kind→route table. |
| `threejsAnimation.js` | Pure pose evaluator for the declarative clip contract in `server/lib/threejsModel.js`, used by the Three.js Models preview transport. `evaluateThreejsClipPose(clip, timeSeconds)` → `{ timeSeconds, pose, activeSequenceIds, activePartIds }` where `pose` is a null-prototype partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }` map: each part+channel resolves from the one sequence that owns the instant (the window containing it, else the most recent behind it, else the next ahead), `visible` steps at the window's end rather than interpolating, and a part no sequence drives is absent so the spec renders as authored. `collectThreejsCues(clip, from, to)` returns the data-only sound cues a play loop crossed in the half-open `[from, to)` interval — a scrub calls it never, which is what makes scrubbing silent. `listThreejsClips` / `listThreejsCues` / `resolveThreejsClip` / `getThreejsClipDuration` read a spec that may have no `animation` key at all. |
| `threejsEnvironment.js` | Image-based lighting for the procedural sculpt spec, used by the Three.js Models preview. `spec.lights` are punctual — they light a surface but give it nothing to REFLECT, so `metalness`, `transmission`, `clearcoat` and `iridescence` read off an environment or read off nothing, and a plausible conductor renders near-black without one. `createSculptEnvironmentTarget(renderer, preset)` builds a preset locally from three's own primitives and prefilters it through `PMREMGenerator` — `neutral` is three's bundled `RoomEnvironment`, `studio` a dark shell with three emissive softbox panels plus a floor bounce — returning null for `none`; the caller owns the render TARGET and disposes it (disposing only `.texture` leaks the framebuffer behind it). `THREEJS_RENDER_PROFILE` mirrors the server's colour-space/tone-map/exposure contract so the preview renders at what the export stamps on the model. Deliberately NOT drei's `<Environment preset=…>`, which fetches an HDR from a CDN: rendering a local model makes no outbound request. `resolveSculptEnvironment(spec)` is the client mirror of `resolveThreejsEnvironment` in `server/lib/threejsModel.js`, reading a spec with no `environment` key as the `none` it was actually authored against. |
| `threejsExplode.js` | Disassembly + part-picking maths for the procedural sculpt spec, shared by the Three.js Models preview so explode and the picker agree on what "a part" is. `computeExplodeLayout(parts, amount)` → `{ offsets, meshOffsets, unitIds, growth }`: separation is a layout **scale about the model centre** (≈2× at full explode) plus a base clearance for parts sitting at the centre — never a uniform outward push, which slides the arrangement without opening gaps — where `offsets` add to a unit's own `position` and `meshOffsets` apply to a group around a container's own geometry (moving its group instead would drag its child units along), and `growth` measures how much the layout actually grew so the camera re-fits on real change. `buildPartSelectionIndex(parts)` → `{ owners, ancestry, names }` for click resolution, subtree highlight, and the selection label. All maps are null-prototype — part ids are provider-authored and `idSchema` accepts `toString`. `isReliefPart` / `isContainerPart` expose the shared part definition: a part flagged `explodeWithParent` is surface relief that rides its parent and resolves selection up to it (unless it has no parent to ride), every other geometry-bearing part is both a movable unit and a selectable component, a part whose descendants carry geometry is additionally descended through, and a part with no geometry in its subtree moves nothing. |
diff --git a/client/src/lib/navPresentation.js b/client/src/lib/navPresentation.js
index 2b7a47c4ed..8171422f5b 100644
--- a/client/src/lib/navPresentation.js
+++ b/client/src/lib/navPresentation.js
@@ -97,6 +97,7 @@ import {
Drama,
UserRound,
Video,
+ ListTodo,
Plug,
TerminalSquare,
} from 'lucide-react';
@@ -122,6 +123,7 @@ export const NAV_PRESENTATION = {
'/brain/memory': { icon: Database },
'/brain/notes': { icon: FileText },
'/brain/spotify': { icon: Music },
+ '/brain/threads': { icon: ListTodo },
'/brain/youtube': { icon: Video },
'/rapid-reader': { icon: Zap },
'/songbook': { icon: ListMusic },
diff --git a/client/src/lib/threadRefKinds.js b/client/src/lib/threadRefKinds.js
index 365cec2b62..c543936ba7 100644
--- a/client/src/lib/threadRefKinds.js
+++ b/client/src/lib/threadRefKinds.js
@@ -7,8 +7,8 @@
*
* A Brain *thread* is a tracked topic or commitment, not a message thread.
*
- * Named exports only, and only the two the client renders with — the registry
- * table and the server-side predicates stay out of the client barrel until
- * something here needs them.
+ * Named exports only: the two the client renders with plus the kind id list
+ * the Threads tab's ref picker enumerates. The server-side predicates stay out
+ * of the client barrel until something here needs them.
*/
-export { threadRefLabel, threadRefUrl } from '../../../server/lib/threadRefKinds.js';
+export { THREAD_REF_KIND_IDS, threadRefLabel, threadRefUrl } from '../../../server/lib/threadRefKinds.js';
diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsx
index d1e2fa1733..9bcb596763 100644
--- a/client/src/pages/Brain.jsx
+++ b/client/src/pages/Brain.jsx
@@ -27,6 +27,7 @@ const ImportTab = lazy(() => import('../components/brain/tabs/ImportTab'));
const BrainGraph = lazy(() => import('../components/brain/tabs/BrainGraph'));
const SpotifyTab = lazy(() => import('../components/brain/tabs/SpotifyTab'));
const YoutubeTab = lazy(() => import('../components/brain/tabs/YoutubeTab'));
+const ThreadsTab = lazy(() => import('../components/brain/tabs/ThreadsTab'));
export default function Brain() {
const { tab } = useParams();
@@ -62,6 +63,8 @@ export default function Brain() {
switch (activeTab) {
case 'inbox':
return <InboxTab onRefresh={refetch} settings={settings} />;
+ case 'threads':
+ return <ThreadsTab />;
case 'links':
return <LinksTab onRefresh={refetch} />;
case 'memory':
diff --git a/client/src/services/README.md b/client/src/services/README.md
index fec1e084a9..f6ceced13d 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -73,6 +73,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| File | Purpose |
|---|---|
+| `apiBrainThreads.js` | Brain threads — the bullet journal's open loops (`/brain/threads`, Brain `threads` entity; a *thread* is a tracked topic, never a message thread): filtered list (`listThreads({ status, priority, tag, pinned, refKind, q })`), full record with `resolvedRefs` (`getThread`), create / defaults-free PUT / tombstone delete, and per-ref attach/detach (`addThreadRef`, `removeThreadRef`). |
| `apiBrain.js` | Brain (second-brain) search + ingest + edit, plus the federation parity audit (`getBrainParityReports`, `runBrainParityCheck`). |
| `apiMemory.js` | Memory CRUD. |
| `apiNotes.js` | Notes vault. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 6254ac01ce..bcc4a0788a 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -47,6 +47,7 @@ export * from './apiMemory.js';
export * from './apiTribe.js';
export * from './apiTimeline.js';
export * from './apiBrain.js';
+export * from './apiBrainThreads.js';
export * from './apiNotes.js';
export * from './apiDigitalTwin.js';
export * from './apiModelPersonality.js';
diff --git a/client/src/services/apiBrainThreads.js b/client/src/services/apiBrainThreads.js
new file mode 100644
index 0000000000..068131a8e5
--- /dev/null
+++ b/client/src/services/apiBrainThreads.js
@@ -0,0 +1,49 @@
+import { request } from './apiCore.js';
+
+// Brain Threads API surface — the bullet journal's open loops at
+// /brain/threads (#7664). A *thread* here is one tracked topic or commitment
+// with a status, a next action and refs to the records that belong to it — NOT
+// a message thread (messages/ owns that sense of the word).
+//
+// Every helper takes an optional `options` arg so a caller with its own error
+// UI can pass `{ silent: true }` (project convention). Path params are
+// URL-encoded — an external ref's id is a full URL.
+//
+// Server contract notes (server/routes/brainThreads.js):
+// - The list projection omits `notes`; the full record (with `resolvedRefs`,
+// hydrated for display) comes from getThread.
+// - PUT is a defaults-free partial. `source`, `externalState` and `closedAt`
+// are server-managed and stripped from a client write — never send them.
+// - POST /:id/refs is idempotent by (kind, id); both ref writes return the
+// updated thread, usable directly for reactive state.
+
+const enc = encodeURIComponent;
+
+// Filters: status, priority, tag, pinned ('true'/'false'), refKind, q. Empty
+// values are dropped so a cleared filter never reaches the server as `?q=`.
+export const listThreads = (filters = {}, options) => {
+ const params = new URLSearchParams();
+ for (const [key, value] of Object.entries(filters)) {
+ if (value != null && value !== '') params.set(key, value);
+ }
+ const qs = params.toString();
+ return request(`/brain/threads${qs ? `?${qs}` : ''}`, options);
+};
+
+export const getThread = (id, options) => request(`/brain/threads/${enc(id)}`, options);
+
+export const createThread = (body = {}, options) =>
+ request('/brain/threads', { method: 'POST', body: JSON.stringify(body), ...options });
+
+export const updateThread = (id, patch, options) =>
+ request(`/brain/threads/${enc(id)}`, { method: 'PUT', body: JSON.stringify(patch), ...options });
+
+export const deleteThread = (id, options) =>
+ request(`/brain/threads/${enc(id)}`, { method: 'DELETE', ...options });
+
+// ref: { kind, id, label? } → the updated thread (201).
+export const addThreadRef = (id, ref, options) =>
+ request(`/brain/threads/${enc(id)}/refs`, { method: 'POST', body: JSON.stringify(ref), ...options });
+
+export const removeThreadRef = (id, kind, refId, options) =>
+ request(`/brain/threads/${enc(id)}/refs/${enc(kind)}/${enc(refId)}`, { method: 'DELETE', ...options });
diff --git a/scripts/migrations/396-seed-open-threads-widget.js b/scripts/migrations/396-seed-open-threads-widget.js
new file mode 100644
index 0000000000..878f87587a
--- /dev/null
+++ b/scripts/migrations/396-seed-open-threads-widget.js
@@ -0,0 +1,15 @@
+/**
+ * Seed the Open Threads brain widget (#7664) into the built-in Everything
+ * layout. It lists the open loops from the Brain bullet journal with the next
+ * action on each, so an existing install gets it where a fresh one does.
+ */
+
+import { makeWidgetSeedMigration } from './_lib.js';
+
+export default makeWidgetSeedMigration({
+ label: 'migration 396',
+ widgetId: 'open-threads',
+ layoutIds: ['default'],
+ cell: { w: 4, h: 4 },
+ logLine: '🧵 migration 396: seeded Open Threads widget in',
+});
diff --git a/scripts/migrations/396-seed-open-threads-widget.test.js b/scripts/migrations/396-seed-open-threads-widget.test.js
new file mode 100644
index 0000000000..f9e90e3787
--- /dev/null
+++ b/scripts/migrations/396-seed-open-threads-widget.test.js
@@ -0,0 +1,72 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './396-seed-open-threads-widget.js';
+
+const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));
+
+describe('migration 396 — seed Open Threads dashboard widget', () => {
+ let rootDir;
+ let layoutsPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-396-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ layoutsPath = join(rootDir, 'data', 'dashboard-layouts.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('does nothing on a fresh install with no persisted layouts', async () => {
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-state' });
+ });
+
+ it('appends the widget to the Everything layout only, in post-#269 grid shape', async () => {
+ writeJson(layoutsPath, {
+ activeLayoutId: 'default',
+ layouts: [
+ {
+ id: 'default', name: 'Everything', builtIn: true,
+ widgets: ['quick-brain', 'on-this-day'],
+ grid: [
+ { id: 'quick-brain', x: 0, w: 3, order: 0, h: 2 },
+ { id: 'on-this-day', x: 4, w: 4, order: 1, h: 4 },
+ ],
+ },
+ {
+ id: 'morning-review', name: 'Morning Review', builtIn: true,
+ widgets: ['review-hub'], grid: [{ id: 'review-hub', x: 0, w: 4, order: 0, h: 4 }],
+ },
+ {
+ id: 'custom', name: 'Mine', builtIn: false,
+ widgets: ['quick-brain'], grid: [{ id: 'quick-brain', x: 0, w: 12, order: 0, h: 2 }],
+ },
+ ],
+ });
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });
+ const after = readJson(layoutsPath);
+ const seeded = after.layouts.find((layout) => layout.id === 'default');
+ expect(seeded.widgets).toEqual(['quick-brain', 'on-this-day', 'open-threads']);
+ expect(seeded.grid.at(-1)).toEqual({ id: 'open-threads', x: 0, w: 4, order: 2, h: 4 });
+ expect(after.layouts.find((layout) => layout.id === 'morning-review').widgets).toEqual(['review-hub']);
+ expect(after.layouts.find((layout) => layout.id === 'custom').widgets).toEqual(['quick-brain']);
+ });
+
+ it('is idempotent once the widget is present', async () => {
+ writeJson(layoutsPath, {
+ activeLayoutId: 'default',
+ layouts: [
+ {
+ id: 'default', name: 'Everything', builtIn: true,
+ widgets: ['open-threads'],
+ grid: [{ id: 'open-threads', x: 0, w: 4, order: 0, h: 4 }],
+ },
+ ],
+ });
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
+ });
+});
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 2acb0cc268..a37aea8dde 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -101,6 +101,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.settings.fleet-llm', path: '/ai/fleet', label: 'Fleet LLM Setup', section: 'Settings', aliases: ['fleet-llm', 'gpu-host', 'remote-ai-provider'], keywords: ['3090', 'tailscale', 'vllm', 'qwen', 'coding model', 'dedicated host'] },
{ id: 'nav.brain.inbox', path: '/brain/inbox', label: 'Inbox', section: 'Brain', tabGroup: 'brain', tabId: 'inbox', aliases: ['brain', 'brain-inbox', 'inbox'] },
+ { id: 'nav.brain.threads', path: '/brain/threads', label: 'Threads', section: 'Brain', tabGroup: 'brain', tabId: 'threads', aliases: ['threads', 'brain-threads', 'bullet-journal', 'open-loops'], keywords: ['todo', 'tracking', 'next action', 'open loops', 'bullet journal'] },
{ id: 'nav.brain.ideas', path: '/brain/ideas', label: 'Ideas', section: 'Brain', tabGroup: 'brain', tabId: 'ideas', aliases: ['brain-ideas', 'ideas'], keywords: ['brainstorm', 'creative', 'thought', 'concept'] },
{ id: 'nav.brain.daily-log', path: '/brain/daily-log', label: 'Daily Log', section: 'Brain', tabGroup: 'brain', tabId: 'daily-log', aliases: ['daily-log', 'journal'] },
{ id: 'nav.brain.links', path: '/brain/links', label: 'Links', section: 'Brain', tabGroup: 'brain', tabId: 'links', aliases: ['brain-links'] },
diff --git a/server/services/brainSearchIndex.js b/server/services/brainSearchIndex.js
index 9721e29eee..603d56d725 100644
--- a/server/services/brainSearchIndex.js
+++ b/server/services/brainSearchIndex.js
@@ -11,7 +11,7 @@
* (`data/brain/<type>/<id>/index.json`) with NO whole-store cache — every
* `brainStorage.getAll(type)` lists the directory and `loadOne`s each record.
* That is the right trade for the write paths, but the ⌘K palette fans out to
- * seven of those stores on EVERY keystroke, so a brain of a few thousand
+ * eight of those stores on EVERY keystroke, so a brain of a few thousand
* records turns each character typed into thousands of stat+read+JSON.parse
* calls. This module reads each store at most once and then keeps the
* projection fresh from `brainEvents`.
@@ -45,7 +45,8 @@ import { safeDate } from '../lib/fileUtils.js';
* consumer reads:
* - `searchBrain` (server/services/search.js) matches on and renders snippets
* from `capturedText` / `name` / `context` / `title` / `oneLiner` / `notes`
- * / `nextAction` / `content` / `mood` / `url` / `description`.
+ * / `nextAction` / `content` / `mood` / `url` / `description` /
+ * `waitingOn`.
* - `getBrainGraphSearchIndex` (server/services/brainGraph.js) derives each
* node's label from `name || title` and drops archived records, while the
* edge-bearing graph views also need tags, status, and summary fields.
@@ -73,6 +74,10 @@ const PROJECTED_FIELDS = Object.freeze({
links: Object.freeze(['title', 'url', 'description']),
journals: Object.freeze(['date']),
songs: GRAPH_PROJECTION_FIELDS,
+ // A Brain *thread* is a tracked open loop (#7664), not a message thread.
+ // Search matches the fields a person would type to find one; `notes` is the
+ // markdown body (capped at 20k, the same order as an admin item's notes).
+ threads: Object.freeze(['title', 'nextAction', 'waitingOn', 'notes']),
});
/**
@@ -103,7 +108,7 @@ const DERIVED_FIELDS = Object.freeze({
* indexed here or its `getBrainProjections` call throws.
*/
export const BRAIN_SEARCH_TYPES = Object.freeze([
- 'inbox', 'people', 'projects', 'ideas', 'admin', 'memories', 'links',
+ 'inbox', 'people', 'projects', 'ideas', 'admin', 'memories', 'links', 'threads',
]);
/** Every brain entity type this index projects (search sources + graph-only). */
diff --git a/server/services/brainSearchIndex.test.js b/server/services/brainSearchIndex.test.js
index c2aef31d7f..f14bae558a 100644
--- a/server/services/brainSearchIndex.test.js
+++ b/server/services/brainSearchIndex.test.js
@@ -30,7 +30,7 @@ describe('brainSearchIndex', () => {
it('covers every brain type unified search reads', () => {
expect([...BRAIN_SEARCH_TYPES]).toEqual([
- 'inbox', 'people', 'projects', 'ideas', 'admin', 'memories', 'links'
+ 'inbox', 'people', 'projects', 'ideas', 'admin', 'memories', 'links', 'threads'
])
})
diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.js
index ab3e34b3d2..8764d71e9d 100644
--- a/server/services/dashboardLayouts.js
+++ b/server/services/dashboardLayouts.js
@@ -111,7 +111,7 @@ const DEFAULT_LAYOUTS = [
'apps',
'cos', 'goal-progress', 'upcoming-tasks',
'proactive-alerts', 'review-hub', 'while-away', 'system-health', 'active-processing', 'network-exposure', 'backup', 'death-clock', 'quick-stats', 'decision-log',
- 'hourly-activity', 'tribe-care', 'feeds', 'today-agenda', 'on-this-day',
+ 'hourly-activity', 'tribe-care', 'feeds', 'today-agenda', 'on-this-day', 'open-threads',
],
// Above-the-fold capture row stretches to h=5 so the Quick Task card
// can show its expanded options (worktree/PR/simplify/etc.) without
@@ -153,6 +153,9 @@ const DEFAULT_LAYOUTS = [
{ id: 'today-agenda', x: 0, w: 4, order: 21, h: 4 },
// Gated on having past-year Brain captures for today's date.
{ id: 'on-this-day', x: 4, w: 4, order: 22, h: 4 },
+ // Open loops from the Brain bullet journal (#7664) — the same list the
+ // Threads tab shows, so the next action on each is one glance away.
+ { id: 'open-threads', x: 8, w: 4, order: 23, h: 4 },
],
},
{
diff --git a/server/services/search.js b/server/services/search.js
index 687b46c66f..02fce9e45e 100644
--- a/server/services/search.js
+++ b/server/services/search.js
@@ -5,7 +5,7 @@
* Uses Promise.allSettled for fault isolation — a failing adapter never
* blocks results from the other sources.
*
- * Sources: Brain (inbox/people/projects/ideas/admin/memories/links, served from
+ * Sources: Brain (inbox/people/projects/ideas/admin/memories/links/threads, served from
* the in-memory projections in brainSearchIndex.js), CoS Memory
* (BM25/hybrid), Apps, History, Health metrics
*/
@@ -109,6 +109,16 @@ const BRAIN_SOURCES = Object.freeze([
title: (r) => r.title || r.url,
snippet: (r) => r.description || r.url,
url: () => '/brain/links'
+ },
+ {
+ // A tracked open loop (#7664), not a message thread. `?thread=` opens the
+ // record's drawer on the Threads tab — the same deep-link the widget uses.
+ type: 'threads',
+ resultType: 'thread',
+ match: ['title', 'nextAction', 'waitingOn', 'notes'],
+ title: (r) => r.title,
+ snippet: (r) => r.nextAction || r.waitingOn || r.notes,
+ url: (r) => `/brain/threads?thread=${encodeURIComponent(r.id)}`
}
]);
@@ -117,7 +127,7 @@ const BRAIN_SOURCES = Object.freeze([
*
* Reads field projections from `brainSearchIndex` rather than
* `brainStorage.getAll()`, so a keystroke costs an in-memory scan instead of a
- * full stat+read+parse of every record file across seven collection dirs
+ * full stat+read+parse of every record file across eight collection dirs
* (issue #3506). The index also removes the old `limit: 200` cap on inbox
* entries — that cap existed only to bound the per-query disk cost.
*/
diff --git a/server/services/search.test.js b/server/services/search.test.js
index 7812bf7b00..65dbe9471f 100644
--- a/server/services/search.test.js
+++ b/server/services/search.test.js
@@ -29,7 +29,7 @@ vi.mock('./history.js', () => ({
import { fanOutSearch } from './search.js'
import { getAll } from './brainStorage.js'
-import { __resetBrainSearchIndex } from './brainSearchIndex.js'
+import { __resetBrainSearchIndex, BRAIN_SEARCH_TYPES } from './brainSearchIndex.js'
import { searchBM25 } from './memoryBM25.js'
import { getMemories, ensureBackend, hybridSearchMemories } from './memoryBackend.js'
import { getAllApps } from './apps.js'
@@ -122,6 +122,22 @@ describe('search service', () => {
expect(linkResult.type).toBe('link')
})
+ it('should search across threads and deep-link the record drawer', async () => {
+ setBrainRecords('threads', [
+ { id: 'th1', title: 'Renew the domain', nextAction: 'Log into the registrar', notes: 'Expires soon' },
+ { id: 'th2', title: 'Unrelated', nextAction: 'Nothing here', notes: '' }
+ ])
+
+ const results = await fanOutSearch('registrar')
+ const brainSource = results.find(s => s.id === 'brain')
+ expect(brainSource.results.map(r => r.id)).toEqual(['th1'])
+ expect(brainSource.results[0]).toMatchObject({
+ type: 'thread',
+ title: 'Renew the domain',
+ url: '/brain/threads?thread=th1'
+ })
+ })
+
it('should search across admin items', async () => {
setBrainRecords('admin', [
{ id: 'ad1', title: 'Renew registration', notes: 'Due next month', nextAction: 'Book appointment' }
@@ -157,15 +173,15 @@ describe('search service', () => {
// One scan per brain source on the first query; every later keystroke is
// served from the in-memory projection (issue #3506).
- expect(afterFirst).toBe(7)
- expect(getAll).toHaveBeenCalledTimes(7)
+ expect(afterFirst).toBe(BRAIN_SEARCH_TYPES.length)
+ expect(getAll).toHaveBeenCalledTimes(BRAIN_SEARCH_TYPES.length)
})
it('should not re-scan a brain store that is legitimately empty', async () => {
await fanOutSearch('anything')
await fanOutSearch('anything else')
- expect(getAll).toHaveBeenCalledTimes(7)
+ expect(getAll).toHaveBeenCalledTimes(BRAIN_SEARCH_TYPES.length)
})
it('should search apps', async () => {