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

share the thread rules between server and client and fetch only the working set (#7664)

[._.]/ Adam Eivy1cfe558fef21
diff --git a/client/src/components/brain/ThreadRefChip.jsx b/client/src/components/brain/ThreadRefChip.jsx
new file mode 100644
index 0000000000..d20edf1b8b
--- /dev/null
+++ b/client/src/components/brain/ThreadRefChip.jsx
@@ -0,0 +1,40 @@
+import { Link } from 'react-router';
+import { ExternalLink, X } from 'lucide-react';
+import Pill from '../ui/Pill';
+import { EXTERNAL_THREAD_REF_KINDS, threadRefLabel } from '../../lib/threadRefKinds.js';
+
+// One chip for a `(kind, id)` ref, wherever it is rendered — the Threads tab's
+// Links panel and the catalog ingredient's "Appears in" list. Follows the
+// shared registry (`lib/threadRefKinds.js`): an external kind links with a real
+// `<a>`, an internal kind with the router `<Link>`, and a ref this build can't
+// deep-link (`url` null) renders unlinked — the contract the catalog page
+// always had. `onRemove` adds the detach affordance the Links panel needs;
+// `showKind={false}` drops the kind prefix where a group heading already says it.
+export default function ThreadRefChip({ kind, id, label, url, resolved, reason, onRemove, showKind = true }) {
+ const text = label || 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">
+ {showKind && <span className="text-gray-500">{threadRefLabel(kind)}</span>}
+ <span className="max-w-[16rem] truncate" title={text}>{text}</span>
+ {url && <ExternalLink size={10} aria-hidden="true" />}
+ </span>
+ );
+ const external = EXTERNAL_THREAD_REF_KINDS.includes(kind);
+ return (
+ <span className="inline-flex items-center gap-1">
+ {url
+ ? (external
+ ? <a href={url} target="_blank" rel="noreferrer" className="hover:opacity-80">{body}</a>
+ : <Link to={url} className="hover:opacity-80">{body}</Link>)
+ : body}
+ {resolved === false && (
+ <Pill tone="warning" size="xs" title={reason}>{reason === 'unknown-kind' ? 'unknown kind' : 'missing'}</Pill>
+ )}
+ {onRemove && (
+ <button type="button" onClick={onRemove} className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center -my-3 rounded text-gray-500 hover:text-port-error" aria-label={`Remove ${text}`}>
+ <X size={12} />
+ </button>
+ )}
+ </span>
+ );
+}
diff --git a/client/src/components/brain/tabs/ThreadsTab.jsx b/client/src/components/brain/tabs/ThreadsTab.jsx
index 1261d616d4..55f46862bf 100644
--- a/client/src/components/brain/tabs/ThreadsTab.jsx
+++ b/client/src/components/brain/tabs/ThreadsTab.jsx
@@ -9,9 +9,8 @@
// 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 { useEffect, useMemo, useState } from 'react';
+import { Check, 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';
@@ -22,29 +21,27 @@ import TabPills from '../../ui/TabPills';
import { FormField } from '../../ui/FormField';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
import toast from '../../ui/Toast';
+import ThreadRefChip from '../ThreadRefChip';
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();
+import {
+ THREAD_STATUSES, THREAD_PRIORITIES, THREAD_ACTIVE_STATUSES,
+ isTerminalThreadStatus, isThreadOverdue, threadNextLine, compareThreads,
+} from '../../../lib/brainThreads.js';
+import { tagsToArray, tagsToInput } from '../../../lib/tribe.js';
+import { formatCount, formatDateShort, localDateKey } from '../../../utils/formatters';
// `?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_LABELS = { open: 'Open', waiting: 'Waiting', someday: 'Someday', done: 'Done', archived: 'Archived' };
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' },
+ ...THREAD_STATUSES.map((id) => ({ id, label: STATUS_LABELS[id] })),
];
const STATUS_IDS = STATUS_VIEWS.map((v) => v.id);
+const WORKING_SET = THREAD_ACTIVE_STATUSES.join(',');
const PRIORITY_TONE = { urgent: 'error', high: 'warning', low: 'note' };
-const PRIORITIES = ['low', 'normal', 'high', 'urgent'];
-const STATUSES = ['open', 'waiting', 'someday', 'done', 'archived'];
+const SEARCH_DEBOUNCE_MS = 300;
const DRAWER_TABS = [
{ id: 'details', label: 'Details', icon: Info },
@@ -58,27 +55,20 @@ const DRAWER_TAB_IDS = DRAWER_TABS.map((t) => t.id);
// 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' },
+ { id: 'overdue', label: 'Overdue', pick: (t) => isThreadOverdue(t) },
+ ...THREAD_ACTIVE_STATUSES.map((status) => ({ id: status, label: STATUS_LABELS[status], pick: (t) => t.status === status })),
];
+// Each thread lands in the FIRST group whose predicate matches.
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);
+ const items = Object.fromEntries(GROUPS.map((g) => [g.id, []]));
+ for (const thread of threads) items[GROUPS.find((g) => g.pick(thread))?.id]?.push(thread);
+ return GROUPS.map((g) => ({ ...g, items: items[g.id] })).filter((g) => g.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.
+// LOCAL calendar date (`localDateKey` ⇄ local midnight, so the form round-trips
+// east of UTC); tags are edited as one comma-separated line.
const toDraft = (thread) => ({
title: thread.title ?? '',
status: thread.status ?? 'open',
@@ -86,8 +76,8 @@ const toDraft = (thread) => ({
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(', ') : '',
+ dueAt: typeof thread.dueAt === 'string' ? localDateKey(new Date(thread.dueAt)) : '',
+ tags: tagsToInput(thread.tags),
notes: thread.notes ?? '',
});
@@ -100,50 +90,20 @@ const draftToPatch = (draft) => ({
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),
+ tags: tagsToArray(draft.tags),
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';
+const loadRecord = (id) => api.getThread(id, { silent: true });
-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>
- );
-}
+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 ThreadRow({ thread, onOpen, onDone, onTag }) {
- const overdue = isOverdue(thread);
+ const nextLine = threadNextLine(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) && (
+ {!isTerminalThreadStatus(thread.status) && (
<button
type="button"
onClick={() => onDone(thread)}
@@ -163,15 +123,11 @@ function ThreadRow({ thread, onOpen, onDone, onTag }) {
)}
{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>
- )}
+ {nextLine && <div className="text-xs text-gray-400 truncate">{nextLine}</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>
+ <Pill tone={isThreadOverdue(thread) ? '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) => (
@@ -199,26 +155,29 @@ export default function ThreadsTab() {
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.
+ // Two-stage search (the Catalog page's pattern): `searchInput` is what the
+ // user is typing; `q` (the URL) drives the fetch and only moves after a
+ // pause, so a keystroke never costs a directory walk on the server.
+ const [searchInput, setSearchInput] = useState(q);
+ useEffect(() => { setSearchInput(q); }, [q]);
+ useEffect(() => {
+ if (searchInput === q) return undefined;
+ const timer = setTimeout(() => updateParams({ q: searchInput }, { replace: true }), SEARCH_DEBOUNCE_MS);
+ return () => clearTimeout(timer);
+ }, [searchInput, q, updateParams]);
+
+ // The list — one request for exactly the statuses the view shows.
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);
- })
+ api.listThreads({ q, tag, status: statusView === 'all' ? WORKING_SET : statusView })
+ .then((res) => { if (active) setThreads(Array.isArray(res?.threads) ? res.threads : []); })
.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);
@@ -239,10 +198,12 @@ export default function ThreadsTab() {
updateParams({ thread: null, threadTab: null }, { replace: true });
});
return () => { active = false; };
- }, [selectedId, loadRecord, updateParams]);
+ }, [selectedId, updateParams]);
const groups = useMemo(
- () => (statusView === 'all' ? groupThreads(threads) : [{ id: statusView, label: STATUS_VIEWS.find((v) => v.id === statusView).label, items: threads }]),
+ () => (statusView === 'all'
+ ? groupThreads(threads)
+ : [{ id: statusView, label: STATUS_LABELS[statusView], items: threads }]),
[threads, statusView],
);
@@ -250,14 +211,18 @@ export default function ThreadsTab() {
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 });
+ // Swap an updated record into the list where the server's order would put
+ // it, or drop it when it no longer belongs to the current view.
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 visible = statusView === 'all' ? !isTerminalThreadStatus(thread.status) : thread.status === statusView;
+ const without = prev.filter((t) => t.id !== thread.id);
+ return visible ? [thread, ...without].sort(compareThreads) : without;
});
+ const adoptRecord = (full) => {
+ setRecord(full);
+ replaceRow(full);
+ };
const [create, creating] = useAsyncAction(async () => {
const title = newTitle.trim();
@@ -284,9 +249,10 @@ export default function ThreadsTab() {
return null;
}
const updated = await api.updateThread(record.id, draftToPatch(draft), { silent: true });
- setRecord((prev) => ({ ...prev, ...updated }));
- setDraft(toDraft(updated));
- replaceRow(updated);
+ // A PUT answers with the bare record; keep the hydrated refs we already hold.
+ const full = { ...record, ...updated };
+ adoptRecord(full);
+ setDraft(toDraft(full));
toast.success('Thread saved');
return updated;
}, { errorMessage: 'Failed to save thread' });
@@ -299,29 +265,28 @@ export default function ThreadsTab() {
return true;
}, { errorMessage: 'Failed to delete thread' });
- // Ref writes return the bare thread; re-read so `resolvedRefs` is hydrated.
+ // Both ref writes answer with the detail shape (hydrated `resolvedRefs`), so
+ // the open record is swapped in place — no second read.
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);
+ adoptRecord(await api.addThreadRef(record.id, ref, { silent: true }));
setNewRef({ kind: newRef.kind, id: '', label: '' });
- return full;
+ return true;
}, { 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;
+ adoptRecord(await api.removeThreadRef(record.id, item.kind, item.id, { silent: true }));
+ return true;
}, { errorMessage: 'Failed to remove link' });
const patchDraft = (patch) => setDraft((prev) => ({ ...prev, ...patch }));
- const dirty = record && draft && JSON.stringify(draft) !== JSON.stringify(toDraft(record));
+ const baseline = useMemo(() => (record ? toDraft(record) : null), [record]);
+ const dirty = useMemo(
+ () => Boolean(baseline && draft && Object.keys(baseline).some((k) => baseline[k] !== draft[k])),
+ [baseline, draft],
+ );
return (
<div className="flex flex-col h-full min-h-0">
@@ -361,8 +326,8 @@ export default function ThreadsTab() {
<label htmlFor="brain-threads-q" className="sr-only">Search threads</label>
<input
id="brain-threads-q"
- value={q}
- onChange={(e) => setQuery(e.target.value)}
+ value={searchInput}
+ onChange={(e) => setSearchInput(e.target.value)}
placeholder="Search"
className={`${inputClass} pl-7 py-1.5`}
/>
@@ -431,12 +396,12 @@ export default function ThreadsTab() {
<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>)}
+ {THREAD_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>)}
+ {THREAD_PRIORITIES.map((p) => <option key={p} value={p}>{p}</option>)}
</select>
</FormField>
<FormField label="Due">
@@ -485,7 +450,7 @@ export default function ThreadsTab() {
<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)} />
+ <ThreadRefChip key={`${item.kind}:${item.id}`} {...item} onRemove={() => removeRef(item)} />
))}
</div>
<form
@@ -526,16 +491,3 @@ export default function ThreadsTab() {
</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
index a68e4b6366..b3a478fb9d 100644
--- a/client/src/components/brain/tabs/ThreadsTab.test.jsx
+++ b/client/src/components/brain/tabs/ThreadsTab.test.jsx
@@ -27,8 +27,10 @@ const ROWS = [
{ 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: [] },
];
+const DONE_ROW = { id: 'done', title: 'Finished loop', status: 'done', refs: [], tags: [] };
+
+const RESOLVED = [{ kind: 'url', id: 'https://example.com', label: 'example', url: 'https://example.com', resolved: true }];
function Location() {
return <output data-testid="location">{useLocation().search}</output>;
@@ -41,25 +43,21 @@ 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 }],
- }));
+ api.getThread.mockImplementation(async (id) => ({ ...ROWS.find((r) => r.id === id), notes: 'body', resolvedRefs: RESOLVED }));
});
- it('groups the working set (pinned, overdue, open, waiting) and hides finished threads', async () => {
+ it('asks the server for the working set and groups it pinned / overdue / open / waiting', 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: '' });
+ // One request for exactly the non-terminal statuses — never the archive filtered here.
+ expect(api.listThreads).toHaveBeenCalledWith({ q: '', tag: '', status: 'open,waiting,someday' });
});
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 });
+ api.listThreads.mockResolvedValue({ threads: [DONE_ROW], 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' });
@@ -103,6 +101,35 @@ describe('ThreadsTab', () => {
expect(screen.getByTestId('location').textContent).toBe('?thread=new');
});
+ it('debounces the search box into the URL instead of fetching per keystroke', async () => {
+ vi.useFakeTimers();
+ try {
+ renderTab();
+ await act(async () => { await Promise.resolve(); });
+ fireEvent.change(screen.getByLabelText('Search threads'), { target: { value: 'r' } });
+ fireEvent.change(screen.getByLabelText('Search threads'), { target: { value: 're' } });
+ expect(api.listThreads).toHaveBeenCalledTimes(1);
+ await act(async () => { vi.advanceTimersByTime(300); });
+ expect(screen.getByTestId('location').textContent).toBe('?q=re');
+ expect(api.listThreads).toHaveBeenCalledTimes(2);
+ expect(api.listThreads).toHaveBeenLastCalledWith({ q: 're', tag: '', status: 'open,waiting,someday' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('swaps the hydrated record a ref write returns into the drawer without a second read', async () => {
+ api.addThreadRef.mockResolvedValue({ ...ROWS[2], notes: 'body', refs: [{ kind: 'url', id: 'https://example.com/x' }], resolvedRefs: [{ kind: 'url', id: 'https://example.com/x', label: 'added', url: 'https://example.com/x', resolved: true }] });
+ renderTab('/brain/threads?thread=op&threadTab=links');
+ await screen.findByRole('dialog');
+ await screen.findByText('example');
+ fireEvent.change(screen.getByLabelText('Id or URL'), { target: { value: 'https://example.com/x' } });
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'Add link' })); });
+ expect(api.addThreadRef).toHaveBeenCalledWith('op', { kind: 'url', id: 'https://example.com/x' }, { silent: true });
+ expect(await screen.findByText('added')).toBeTruthy();
+ expect(api.getThread).toHaveBeenCalledTimes(1);
+ });
+
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');
diff --git a/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx b/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx
index 5fdbd3760f..72e8f3138c 100644
--- a/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx
+++ b/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx
@@ -2,31 +2,32 @@ import { Link } from 'react-router';
import { ListTodo, Pin } from 'lucide-react';
import * as api from '../../../services/api';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch';
+import { isThreadOverdue, threadNextLine } from '../../../lib/brainThreads.js';
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.
+// The Brain bullet journal's open loops (#7664) 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 on the Threads tab.
//
+// Deliberately narrower than the tab's working set: `someday` is parked by
+// definition, so the widget asks the server for open + waiting only, and only
+// the first page — `total` carries the count without shipping the rest.
// 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.
+// nothing else on the dashboard needs the list.
const ROWS = 6;
-const WORKING = new Set(['open', 'waiting']);
-
-const isOverdue = (t) => typeof t.dueAt === 'string' && Date.parse(t.dueAt) < Date.now();
+const WIDGET_STATUSES = 'open,waiting';
export default function OpenThreadsWidget() {
const { data, loading } = useAutoRefetch(
- () => api.listThreads({}, { silent: true }),
+ () => api.listThreads({ status: WIDGET_STATUSES, limit: ROWS, offset: 0 }, { 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);
+ const rows = Array.isArray(data?.threads) ? data.threads : [];
+ const total = Number.isFinite(data?.total) ? data.total : rows.length;
return (
<div className="@container bg-port-card border border-port-border rounded-xl p-4 h-full">
@@ -35,7 +36,7 @@ export default function OpenThreadsWidget() {
<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>}
+ {total > 0 && <span className="text-xs text-gray-500">{formatCount(total)} open</span>}
</div>
{rows.length === 0 ? (
@@ -44,31 +45,30 @@ export default function OpenThreadsWidget() {
</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>
+ {rows.map((t) => {
+ const nextLine = threadNextLine(t);
+ return (
+ <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>
+ {nextLine && <span className="block truncate text-gray-500">{nextLine}</span>}
+ </span>
+ {t.dueAt && (
+ <span className={`shrink-0 ${isThreadOverdue(t) ? 'text-port-error' : 'text-gray-500'}`}>{formatDateShort(t.dueAt)}</span>
)}
- </span>
- {t.dueAt && (
- <span className={`shrink-0 ${isOverdue(t) ? 'text-port-error' : 'text-gray-500'}`}>{formatDateShort(t.dueAt)}</span>
- )}
- </Link>
- </li>
- ))}
+ </Link>
+ </li>
+ );
+ })}
</ul>
)}
- {open.length > rows.length && (
+ {total > 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
+ +{formatCount(total - 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
index a5179019bd..d6ddebd7c8 100644
--- a/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx
+++ b/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx
@@ -10,6 +10,7 @@ vi.mock('../../../hooks/useAutoRefetch', () => ({
}));
vi.mock('../../../services/api', () => ({ listThreads: vi.fn() }));
+import * as api from '../../../services/api';
import OpenThreadsWidget from './OpenThreadsWidget';
const renderWidget = () => render(<MemoryRouter><OpenThreadsWidget /></MemoryRouter>);
@@ -21,15 +22,22 @@ describe('OpenThreadsWidget', () => {
expect(container.innerHTML).toBe('');
});
- it('shows only the working set, with the next action, and deep-links each row to its drawer', () => {
+ it('asks the server for the first page of open + waiting threads only', () => {
+ mockUseAutoRefetch.mockReturnValue({ data: null, loading: true });
+ renderWidget();
+ const fetchFn = mockUseAutoRefetch.mock.calls.at(-1)[0];
+ fetchFn();
+ expect(api.listThreads).toHaveBeenCalledWith({ status: 'open,waiting', limit: 6, offset: 0 }, { silent: true });
+ });
+
+ it('shows the next action on each row and deep-links it to its drawer', () => {
mockUseAutoRefetch.mockReturnValue({
loading: false,
data: {
+ total: 2,
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' },
],
},
});
@@ -37,15 +45,13 @@ describe('OpenThreadsWidget', () => {
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', () => {
+ it('links the overflow the page did not ship to the tab', () => {
mockUseAutoRefetch.mockReturnValue({
loading: false,
- data: { threads: Array.from({ length: 8 }, (_, i) => ({ id: `t${i}`, title: `Loop ${i}`, status: 'open' })) },
+ data: { total: 8, threads: Array.from({ length: 6 }, (_, i) => ({ id: `t${i}`, title: `Loop ${i}`, status: 'open' })) },
});
renderWidget();
expect(screen.getAllByRole('listitem')).toHaveLength(6);
@@ -53,7 +59,7 @@ describe('OpenThreadsWidget', () => {
});
it('offers to track one when the list is empty', () => {
- mockUseAutoRefetch.mockReturnValue({ loading: false, data: { threads: [] } });
+ mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 0, threads: [] } });
renderWidget();
expect(screen.getByText('Track one').closest('a')).toHaveAttribute('href', '/brain/threads');
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index bc0c134212..37ef214514 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -244,7 +244,8 @@ 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 — `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. |
+| `brainThreads.js` | Re-export of `server/lib/brainThreads.js` — Brain THREAD statuses, `isTerminalThreadStatus` / `isThreadOverdue`, `threadNextLine` and the server's list comparator `compareThreads`, so the Threads tab and the Open Threads widget group, badge and order rows exactly as `GET /api/brain/threads` does (a *thread* is a tracked open loop, never a message thread). |
+| `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` / `EXTERNAL_THREAD_REF_KINDS` (what the Threads tab's ref picker enumerates and how `ThreadRefChip` picks `<a>` over `<Link>`). `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/brainThreads.js b/client/src/lib/brainThreads.js
new file mode 100644
index 0000000000..79abb10862
--- /dev/null
+++ b/client/src/lib/brainThreads.js
@@ -0,0 +1,21 @@
+/**
+ * Brain THREAD rules — statuses, the terminal/overdue predicates, the row's
+ * next-action line and the list comparator.
+ *
+ * Re-export of `server/lib/brainThreads.js` — the one definition of these
+ * rules, imported rather than copied so the Threads tab, the Open Threads
+ * dashboard widget and the server list order cannot drift (the "One pure
+ * module, one definition" convention in this directory's README).
+ *
+ * A Brain *thread* is a tracked topic or commitment, not a message thread.
+ */
+export {
+ THREAD_STATUSES,
+ THREAD_PRIORITIES,
+ THREAD_TERMINAL_STATUSES,
+ THREAD_ACTIVE_STATUSES,
+ isTerminalThreadStatus,
+ isThreadOverdue,
+ threadNextLine,
+ compareThreads,
+} from '../../../server/lib/brainThreads.js';
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 0f76028ab4..dc8f6a1f30 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -205,6 +205,7 @@ export * from './terminalScroll.js';
export * from './terminalTheme.js';
export * from './textUtils.js';
export * from './threadRefKinds.js';
+export * from './brainThreads.js';
export * from './threejsAnimation.js';
export * from './threejsEnvironment.js';
export * from './threejsExplode.js';
diff --git a/client/src/lib/threadRefKinds.js b/client/src/lib/threadRefKinds.js
index c543936ba7..a3b9102f1d 100644
--- a/client/src/lib/threadRefKinds.js
+++ b/client/src/lib/threadRefKinds.js
@@ -7,8 +7,9 @@
*
* A Brain *thread* is a tracked topic or commitment, not a message thread.
*
- * 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
+ * Named exports only: the two the client renders with, the kind id list the
+ * Threads tab's ref picker enumerates, and the external set the shared ref chip
+ * uses to pick `<a>` over `<Link>`. The server-side predicates stay out
* of the client barrel until something here needs them.
*/
-export { THREAD_REF_KIND_IDS, threadRefLabel, threadRefUrl } from '../../../server/lib/threadRefKinds.js';
+export { THREAD_REF_KIND_IDS, EXTERNAL_THREAD_REF_KINDS, threadRefLabel, threadRefUrl } from '../../../server/lib/threadRefKinds.js';
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index 90e7eae492..88dac5c741 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -36,6 +36,7 @@ import { useGalleryPage } from '../hooks/useGalleryPage';
import { generateImage } from '../services/apiSystem';
import { composeCanonStyledPrompt } from '../lib/composeStyledPrompt';
import { threadRefLabel, threadRefUrl } from '../lib/threadRefKinds.js';
+import ThreadRefChip from '../components/brain/ThreadRefChip';
import { getUniverse } from '../services/apiUniverseBuilder';
import useMounted from '../hooks/useMounted';
import MediaJobThumb from '../components/pipeline/MediaJobThumb';
@@ -53,9 +54,9 @@ import { timeAgo, formatDateTime } from '../utils/formatters';
// (`client/src/lib/catalogTypes.js`). Each editor entry is `[key, label, kind]`
// where `kind` is 'text' (single line) or 'textarea' (multi-line).
-// Ref chips deep-link through the SHARED kind→route registry
-// (`client/src/lib/threadRefKinds.js`, a re-export of the server leaf), not a
-// switch local to this page — one table, so a kind added for a Brain thread and
+// Ref chips are the SHARED `ThreadRefChip`, deep-linking through the shared
+// kind→route registry (`client/src/lib/threadRefKinds.js`, a re-export of the
+// server leaf), not a switch local to this page — one table, so a kind added for a Brain thread and
// a kind stored on a catalog ingredient can never disagree about where it goes
// (#7664). Same contract this page always had: `threadRefUrl` returns null for a
// kind we can't deep-link (the chip renders unlinked) and `threadRefLabel` falls
@@ -1491,25 +1492,16 @@ function RefsPanel({ refsByKind }) {
{threadRefLabel(kind)}
</div>
<div className="flex flex-wrap gap-1.5">
- {refsByKind[kind].map((r, i) => {
- const path = threadRefUrl(kind, r.refId);
- const label = r.refName || r.refId || '(unnamed)';
- const role = r.role ? ` · ${r.role}` : '';
- const chip = (
- // biome-ignore lint/correctness/useJsxKeyInIterable: `chip` is a child of the keyed <Link>/<span> returned below, not the list element itself.
- <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">
- {label}{role}
- {path && <ExternalLink size={10} aria-hidden="true" />}
- </span>
- );
- return path ? (
- <Link key={`${kind}-${r.refId}-${i}`} to={path} className="hover:opacity-80">
- {chip}
- </Link>
- ) : (
- <span key={`${kind}-${r.refId}-${i}`}>{chip}</span>
- );
- })}
+ {refsByKind[kind].map((r, i) => (
+ <ThreadRefChip
+ key={`${kind}-${r.refId}-${i}`}
+ kind={kind}
+ id={r.refId}
+ label={`${r.refName || r.refId || '(unnamed)'}${r.role ? ` · ${r.role}` : ''}`}
+ url={threadRefUrl(kind, r.refId)}
+ showKind={false}
+ />
+ ))}
</div>
</div>
))}
diff --git a/client/src/services/apiBeeper.js b/client/src/services/apiBeeper.js
index fec5a2cae7..e5724f1c4d 100644
--- a/client/src/services/apiBeeper.js
+++ b/client/src/services/apiBeeper.js
@@ -1,4 +1,4 @@
-import { API_BASE, request } from './apiCore.js';
+import { API_BASE, request, queryString } from './apiCore.js';
// Beeper Desktop bridge — status card (#30). Read-only connection status
// (token-configured flag, never the token; tri-state reachability; the
@@ -24,16 +24,6 @@ export const syncBeeperNow = (options = {}) => request('/beeper/sync', { method:
// costs one local query rather than an upstream fan-out.
// ---------------------------------------------------------------------------
-const queryString = (params) => {
- const qs = new URLSearchParams();
- for (const [key, value] of Object.entries(params)) {
- if (value === undefined || value === null || value === '') continue;
- qs.set(key, String(value));
- }
- const encoded = qs.toString();
- return encoded ? `?${encoded}` : '';
-};
-
// `unreadOnly` / `archived` / `lowPriority` are omitted when undefined and sent
// as the literal "true"/"false" otherwise: the server reads an absent filter as
// "do not filter", which is a different query from `false`.
diff --git a/client/src/services/apiBrainThreads.js b/client/src/services/apiBrainThreads.js
index 068131a8e5..131f0886a8 100644
--- a/client/src/services/apiBrainThreads.js
+++ b/client/src/services/apiBrainThreads.js
@@ -1,4 +1,4 @@
-import { request } from './apiCore.js';
+import { request, queryString } 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
@@ -15,20 +15,16 @@ import { request } from './apiCore.js';
// - 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.
+// same detail shape as getThread (with `resolvedRefs`), so the open record
+// can be swapped in place.
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);
-};
+// Filters: status (one, or a comma list for the working set), priority, tag,
+// pinned ('true'/'false'), refKind, q — plus `limit`/`offset` to paginate, which
+// switches the response to `{ threads, total, limit, offset }`.
+export const listThreads = (filters = {}, options) =>
+ request(`/brain/threads${queryString(filters)}`, options);
export const getThread = (id, options) => request(`/brain/threads/${enc(id)}`, options);
@@ -41,7 +37,7 @@ export const updateThread = (id, patch, options) =>
export const deleteThread = (id, options) =>
request(`/brain/threads/${enc(id)}`, { method: 'DELETE', ...options });
-// ref: { kind, id, label? } → the updated thread (201).
+// ref: { kind, id, label? } → the updated thread with `resolvedRefs` (201).
export const addThreadRef = (id, ref, options) =>
request(`/brain/threads/${enc(id)}/refs`, { method: 'POST', body: JSON.stringify(ref), ...options });
diff --git a/client/src/services/apiCore.js b/client/src/services/apiCore.js
index d5fff2453b..cd98a6ec7a 100644
--- a/client/src/services/apiCore.js
+++ b/client/src/services/apiCore.js
@@ -107,6 +107,18 @@ export async function request(endpoint, options = {}) {
}
// Search
+// Query string from a filter object, dropping absent/empty values so a cleared
+// filter never reaches the server as `?q=`. Returns '' when nothing is set.
+export const queryString = (params = {}) => {
+ const qs = new URLSearchParams();
+ for (const [key, value] of Object.entries(params)) {
+ if (value === undefined || value === null || value === '') continue;
+ qs.set(key, String(value));
+ }
+ const encoded = qs.toString();
+ return encoded ? `?${encoded}` : '';
+};
+
export const search = (q) => request(`/search?q=${encodeURIComponent(q)}`);
// Default export for simplified imports
diff --git a/server/lib/README.md b/server/lib/README.md
index 8f67e142d9..ba7ae18d23 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -126,6 +126,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `storyBuilderValidation.js` | Unified Story Builder session/step schemas. |
| `telegramValidation.js` | Telegram bot config + test schemas. |
| `terminalReplay.js` | `stripTerminalQueries(text)` — remove response-soliciting terminal sequences (DSR `ESC[6n`, DA, DECRQM, DECRQSS, OSC colour queries) from the re-attach replay buffer a PTY session hands a newly attached client. A TUI emits `ESC[6n` on nearly every render and the 50KB ring buffer stores PTY output verbatim, so replaying it makes the attaching xterm ANSWER every historical query as input — landing cursor-position reports (`56;3R56;3R…`) on the shell prompt the dead TUI left behind, which then echo back into the same buffer and re-flood on every later attach. Applied on the way out, over the joined buffer, so a sequence split across two stored chunks still matches; live output is untouched because a running TUI must still get its replies. Stateful sequences the replay needs (mouse tracking, bracketed paste, alternate screen, SGR) are deliberately preserved — this is NOT `ansiStrip.js`, which removes every sequence to recover plain text. `createTerminalModeTracker()` — `observe(chunk)` follows the same stream’s DEC private modes (alternate screen, mouse tracking and encoding, bracketed paste, DECCKM, cursor visibility) and `preamble()` re-asserts the ones still in force, prepended to the replay: a TUI declares them ONCE at startup, so a session that overflows the 50KB window would otherwise replay as a normal-buffer, mouse-less terminal and become unscrollable. **`createReplayBuffer({ maxBytes })` is the export callers want** — the ring buffer that owns the bytes and applies both corrections to them (`push(chunk)` records and evicts, `render()` returns what an attaching client is handed); `services/shell.js` holds one per PTY session. The two helpers above are its internals, exported for their own direct tests — reach for the buffer rather than re-composing them by hand. |
+| `brainThreads.js` | Brain THREAD rules (#7664) — the pure half of the bullet journal (a *thread* is a tracked open loop, never a message thread): `THREAD_STATUSES` / `THREAD_PRIORITIES` / `THREAD_TERMINAL_STATUSES` / `THREAD_ACTIVE_STATUSES`, `isTerminalThreadStatus`, `isThreadOverdue(thread, now)` (never true once finished), `threadNextLine` (the row's "Waiting on X" / next-action line) and the list comparator `compareThreads` (pinned, soonest-due, most recently touched, id — NaN-safe for two undated threads). `brainValidation.js` builds its enums from the arrays, `routes/brainThreads.js` sorts with the comparator, and `client/src/lib/brainThreads.js` re-exports the whole module so the tab, the widget and the server agree. |
| `threadRefKinds.js` | Brain THREAD ref vocabulary + route table (#7664) — the one `(kind, id)` → label/URL registry in the repo. A *thread* is a tracked topic or commitment (an open loop), never a message thread. `THREAD_REF_KINDS` is the frozen row-per-kind table (brain records, catalog scraps/ingredients, the five app-native creative kinds, goals/apps/messages/CoS tasks, and the external GitHub/GitLab/JIRA/URL kinds); `threadRefUrl(kind, id, context)` builds the deep link and `threadRefLabel(kind)` the chip text, both degrading to `null`/the raw kind for a kind this build does not know so a peer-sourced ref never throws. `isSafeExternalUrl` scheme-guards an external id before it can become an href. Pure (no zod, no db, no services) and re-exported by `client/src/lib/threadRefKinds.js`, which is how `pages/CatalogIngredient.jsx` renders its inbound-ref chips through the same table. Existence/title lookups live in `services/threadRefs.js`; a drift guard fails CI when a kind here has no resolver there. |
## Story & narrative
diff --git a/server/lib/brainThreads.js b/server/lib/brainThreads.js
new file mode 100644
index 0000000000..b2b5769b56
--- /dev/null
+++ b/server/lib/brainThreads.js
@@ -0,0 +1,72 @@
+/**
+ * Brain THREAD rules — the pure, dependency-free half of the bullet journal
+ * (#7664): status/priority vocabularies, the terminal-status test, the overdue
+ * predicate and the list comparator.
+ *
+ * A Brain *thread* is a tracked topic or commitment (an open loop), NOT a
+ * message thread — `messageSync.js` / `messageGmailSync.js` / `beeperSync.js`
+ * own that other sense of the word.
+ *
+ * Deliberately a leaf (no zod, no services, no db): `server/lib/brainValidation.js`
+ * builds its enums from these arrays, `server/routes/brainThreads.js` sorts with
+ * the comparator, and the client re-exports the whole module
+ * (`client/src/lib/brainThreads.js`) so the Threads tab, the dashboard widget
+ * and the server can never disagree about which statuses are "done", which
+ * threads are overdue, or what order a list comes in.
+ */
+
+export const THREAD_STATUSES = Object.freeze(['open', 'waiting', 'someday', 'done', 'archived']);
+export const THREAD_PRIORITIES = Object.freeze(['low', 'normal', 'high', 'urgent']);
+export const THREAD_TERMINAL_STATUSES = Object.freeze(['done', 'archived']);
+
+/** The statuses that make up the working set — everything not finished. */
+export const THREAD_ACTIVE_STATUSES = Object.freeze(
+ THREAD_STATUSES.filter((status) => !THREAD_TERMINAL_STATUSES.includes(status)),
+);
+
+export const isTerminalThreadStatus = (status) => THREAD_TERMINAL_STATUSES.includes(status);
+
+/**
+ * Past its due date and still open. A finished thread is never overdue, however
+ * old its date — the badge means "needs you", not "was late".
+ */
+export function isThreadOverdue(thread, now = Date.now()) {
+ if (isTerminalThreadStatus(thread?.status)) return false;
+ const due = Date.parse(thread?.dueAt ?? '');
+ return !Number.isNaN(due) && due < now;
+}
+
+/**
+ * The one line a list row shows under the title: who a waiting thread is
+ * blocked on, else the next concrete step. Empty when the thread has neither.
+ */
+export function threadNextLine(thread) {
+ if (thread?.status === 'waiting' && thread.waitingOn) return `Waiting on ${thread.waitingOn}`;
+ return thread?.nextAction || thread?.waitingOn || '';
+}
+
+// Sort key for the due date: a thread with no due date sorts AFTER every dated
+// one rather than poisoning the comparator with NaN.
+export const dueSortKey = (thread) => {
+ const t = Date.parse(thread?.dueAt ?? '');
+ return Number.isNaN(t) ? Infinity : t;
+};
+
+/**
+ * Pinned first, then soonest-due, then most recently touched, with the id as a
+ * deterministic tiebreak — a stable order matters because the list paginates,
+ * and an unstable one drops or duplicates rows at the slice boundary.
+ */
+export function compareThreads(a, b) {
+ if (Boolean(b.pinned) !== Boolean(a.pinned)) return Boolean(b.pinned) - Boolean(a.pinned);
+ // Compared, not subtracted: two UNDATED threads are both Infinity, and
+ // `Infinity - Infinity` is NaN — a comparator returning NaN skips the
+ // remaining tiebreaks and leaves the order engine-defined, which the
+ // pagination slice cannot tolerate.
+ const aDue = dueSortKey(a);
+ const bDue = dueSortKey(b);
+ if (aDue !== bDue) return aDue - bDue;
+ 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/server/lib/brainValidation.js b/server/lib/brainValidation.js
index 98d9d94856..1fab78b7fd 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -3,6 +3,7 @@ import { partialWithoutDefaults, optionalBooleanMap } from './zodCompat.js';
import { REPO_INTAKE_KEYS } from './repoIntakeActions.js';
import { EFFORT_LEVELS } from './providerModels.js';
import { canonicalThreadRefKind } from './threadRefKinds.js';
+import { THREAD_STATUSES, THREAD_PRIORITIES } from './brainThreads.js';
import { MAX_QUALITY } from './spacedRepetition.js';
// Destination enum. `links` is reachable only from the bare-URL capture
@@ -795,12 +796,10 @@ export const songAttachmentUploadSchema = z.object({
// from, `externalState` what the tracker last said, and `closedAt` is stamped by
// the route when the status enters a terminal state.
-export const threadStatusEnum = z.enum(['open', 'waiting', 'someday', 'done', 'archived']);
-export const threadPriorityEnum = z.enum(['low', 'normal', 'high', 'urgent']);
-
-// Statuses that mean the loop is shut. The route stamps/clears `closedAt` on
-// this set so "when did I finish it" is answerable without scanning history.
-export const THREAD_TERMINAL_STATUSES = Object.freeze(['done', 'archived']);
+// Vocabularies live in the pure leaf (`lib/brainThreads.js`) so the client
+// renders its pickers from the same arrays these enums validate against.
+export const threadStatusEnum = z.enum(THREAD_STATUSES);
+export const threadPriorityEnum = z.enum(THREAD_PRIORITIES);
// A ref's `kind` is validated as a SHAPE, not against THREAD_REF_KIND_IDS. A
// peer running newer code can sync a thread naming a kind this build has never
@@ -856,7 +855,13 @@ export const threadUpdateSchema = partialWithoutDefaults(threadInputSchema);
// `isPaginationRequested`/`paginateArray` read them straight off req.query, and
// coercing them here would make every request look paginated.
export const threadQuerySchema = z.object({
- status: threadStatusEnum.optional(),
+ // One status, or a comma list (`?status=open,waiting,someday`) so the working
+ // set is one request rather than the whole archive filtered client-side.
+ // Always an array after parsing.
+ status: z.preprocess(
+ (value) => (typeof value === 'string' ? value.split(',').map((s) => s.trim()).filter(Boolean) : value),
+ z.array(threadStatusEnum).min(1).max(THREAD_STATUSES.length),
+ ).optional(),
priority: threadPriorityEnum.optional(),
tag: z.string().trim().min(1).max(50).optional(),
refKind: threadRefKindValue.optional(),
diff --git a/server/lib/index.js b/server/lib/index.js
index c83f419876..df8bfdade0 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -28,6 +28,7 @@ export * as agentValidation from './agentValidation.js';
export * as agentContextValidation from './agentContextValidation.js';
export * as appleHealthValidation from './appleHealthValidation.js';
export * as brainValidation from './brainValidation.js';
+export * from './brainThreads.js';
export * as catalogValidation from './catalogValidation.js';
export * as characterAugmentValidation from './characterAugmentValidation.js';
export * as characterEvolutionValidation from './characterEvolutionValidation.js';
diff --git a/server/routes/brainThreads.js b/server/routes/brainThreads.js
index 76e11a7ef6..fa6576dcdd 100644
--- a/server/routes/brainThreads.js
+++ b/server/routes/brainThreads.js
@@ -32,8 +32,8 @@ import {
threadQuerySchema,
threadRefInputSchema,
threadAttachSchema,
- THREAD_TERMINAL_STATUSES,
} from '../lib/brainValidation.js';
+import { isTerminalThreadStatus as isTerminal, compareThreads } from '../lib/brainThreads.js';
import { canonicalThreadRefKind } from '../lib/threadRefKinds.js';
import * as brainStorage from '../services/brainStorage.js';
import { resolveThreadRefs } from '../services/threadRefs.js';
@@ -47,8 +47,6 @@ function requireThread(thread) {
return thread;
}
-const isTerminal = (status) => THREAD_TERMINAL_STATUSES.includes(status);
-
/**
* `closedAt` for a record whose status is MOVING to `nextStatus`.
*
@@ -105,30 +103,6 @@ function matchesQuery(thread, q) {
return haystack.some((v) => typeof v === 'string' && v.toLowerCase().includes(needle));
}
-// Sort key for the due date: a thread with no due date sorts AFTER every dated
-// one rather than poisoning the comparator with NaN.
-const dueSortKey = (thread) => {
- const t = Date.parse(thread?.dueAt ?? '');
- return Number.isNaN(t) ? Infinity : t;
-};
-
-// Pinned first, then soonest-due, then most recently touched, with the id as a
-// deterministic tiebreak — a stable order matters because the list paginates,
-// and an unstable one drops or duplicates rows at the slice boundary.
-function compareThreads(a, b) {
- if (Boolean(b.pinned) !== Boolean(a.pinned)) return Boolean(b.pinned) - Boolean(a.pinned);
- // Compared, not subtracted: two UNDATED threads are both Infinity, and
- // `Infinity - Infinity` is NaN — a comparator returning NaN skips the
- // remaining tiebreaks and leaves the order engine-defined, which the
- // pagination slice below cannot tolerate.
- const aDue = dueSortKey(a);
- const bDue = dueSortKey(b);
- if (aDue !== bDue) return aDue - bDue;
- 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));
-}
-
// =============================================================================
// ATTACH (before /:id routes so 'attach' is never treated as an id)
// =============================================================================
@@ -171,7 +145,7 @@ router.get('/', asyncHandler(async (req, res) => {
const all = await brainStorage.getAll('threads');
const matching = all.filter((thread) => {
- if (filters.status && thread.status !== filters.status) return false;
+ if (filters.status && !filters.status.includes(thread.status)) return false;
if (filters.priority && thread.priority !== filters.priority) return false;
// A bare `?pinned` arrives as '' and reads as true; 'false' filters to the
// unpinned set. Absent means "don't filter" (the tri-state in the schema).
@@ -194,11 +168,15 @@ router.get('/', asyncHandler(async (req, res) => {
return res.json({ threads: rows, total: rows.length });
}));
+// The detail shape: the record plus `resolvedRefs`, hydrated for display only —
+// the stored `refs` array is untouched, so a target this build can't resolve
+// still round-trips through a later write. The ref writes return this same
+// shape so a client can swap the open record in place instead of re-reading.
+const withResolvedRefs = async (thread) => ({ ...thread, resolvedRefs: await resolveThreadRefs(thread.refs) });
+
router.get('/:id', asyncHandler(async (req, res) => {
const thread = requireThread(await brainStorage.getById('threads', req.params.id));
- // Hydrated for display only — the stored `refs` array is untouched, so a
- // target this build can't resolve still round-trips through a later write.
- res.json({ ...thread, resolvedRefs: await resolveThreadRefs(thread.refs) });
+ res.json(await withResolvedRefs(thread));
}));
router.post('/', asyncHandler(async (req, res) => {
@@ -248,7 +226,7 @@ router.post('/:id/refs', asyncHandler(async (req, res) => {
const ref = validateRequest(threadRefInputSchema, req.body);
const thread = requireThread(await brainStorage.updateWith('threads', req.params.id,
(fresh) => ({ refs: mergeRef(fresh.refs, ref) })));
- res.status(201).json(thread);
+ res.status(201).json(await withResolvedRefs(thread));
}));
// DELETE /:id/refs/:kind/:refId — detach one ref. `:refId` is URL-encoded by the
@@ -258,7 +236,7 @@ router.delete('/:id/refs/:kind/:refId', asyncHandler(async (req, res) => {
const thread = requireThread(await brainStorage.updateWith('threads', req.params.id, (fresh) => ({
refs: (Array.isArray(fresh.refs) ? fresh.refs : []).filter((r) => refKey(r) !== target),
})));
- res.json(thread);
+ res.json(await withResolvedRefs(thread));
}));
export default router;
diff --git a/server/routes/brainThreads.test.js b/server/routes/brainThreads.test.js
index e77914f4c7..37dad1d099 100644
--- a/server/routes/brainThreads.test.js
+++ b/server/routes/brainThreads.test.js
@@ -207,6 +207,9 @@ describe('Brain Threads routes', () => {
const ids = async (qs) => (await request(app).get(`/api/brain/threads${qs}`)).body.threads.map((t) => t.id);
expect(await ids('?status=open')).toEqual(['a', 'c']);
+ // The working set is one request — a comma list, not the archive filtered client-side.
+ expect(await ids('?status=open,waiting')).toEqual(['a', 'b', 'c']);
+ expect((await request(app).get('/api/brain/threads?status=open,bogus')).status).toBe(400);
expect(await ids('?tag=ops')).toEqual(['a', 'b']);
expect(await ids('?pinned=true')).toEqual(['a']);
expect(await ids('?pinned=false')).toEqual(['b', 'c']);
@@ -279,6 +282,9 @@ describe('Brain Threads routes', () => {
{ kind: 'brain.idea', id: 'idea-1', label: '' },
{ kind: 'github.issue', id: 'https://github.com/o/r/issues/7', label: 'o/r#7' },
]);
+ // Same shape as GET /:id, so the client swaps the open record in place
+ // instead of paying a second read for the hydrated refs.
+ expect(Array.isArray(res.body.resolvedRefs)).toBe(true);
});
it('replaces a same-(kind,id) ref in place instead of duplicating it', async () => {