Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: complete source-closed Brain threads from drawer and dashboard (#7664)
[._.]/ Adam Eivy09f6418fe4b8
diff --git a/client/src/components/brain/ThreadSourceClosedAction.jsx b/client/src/components/brain/ThreadSourceClosedAction.jsxnew file mode 100644index 0000000000..6b2247a0cb--- /dev/null+++ b/client/src/components/brain/ThreadSourceClosedAction.jsx@@ -0,0 +1,38 @@+// A Brain thread is a tracked topic, distinct from a message thread.+// Source closure is a suggestion: only this explicit action completes the loop.+import { useRef } from 'react';+import useAsyncAction from '../../hooks/useAsyncAction';+import { isTerminalThreadStatus } from '../../lib/brainThreads.js';+import * as api from '../../services/api';++export default function ThreadSourceClosedAction({ thread, onCompleted, onPendingChange, disabled = false }) {+ const inFlight = useRef(false);+ const [complete, completing] = useAsyncAction(async () => {+ if (inFlight.current || disabled) return;+ inFlight.current = true;+ onPendingChange?.(true);+ const updated = await api.updateThread(thread.id, { status: 'done' }, { silent: true })+ .finally(() => {+ inFlight.current = false;+ onPendingChange?.(false);+ });+ onCompleted(updated);+ }, { errorMessage: 'Failed to complete thread' });++ if (thread.externalState !== 'closed' || isTerminalThreadStatus(thread.status)) return null;++ return (+ <div className="flex flex-wrap items-center gap-x-2 text-xs text-port-warning">+ <span>Source closed — mark done?</span>+ <button+ type="button"+ onClick={complete}+ disabled={disabled || completing}+ aria-label={`Mark "${thread.title}" done`}+ className="min-h-8 px-2 rounded border border-port-border hover:border-port-success hover:text-port-success disabled:opacity-50"+ >+ {completing ? 'Saving…' : 'Mark done'}+ </button>+ </div>+ );+}diff --git a/client/src/components/brain/tabs/ThreadsTab.jsx b/client/src/components/brain/tabs/ThreadsTab.jsxindex 55f46862bf..ef2840889c 100644--- a/client/src/components/brain/tabs/ThreadsTab.jsx+++ b/client/src/components/brain/tabs/ThreadsTab.jsx@@ -9,7 +9,7 @@// 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 { useEffect, useMemo, useState } from 'react';+import { useEffect, useMemo, useRef, 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';@@ -22,6 +22,7 @@ import { FormField } from '../../ui/FormField';import InlineConfirmRow from '../../ui/InlineConfirmRow';import toast from '../../ui/Toast';import ThreadRefChip from '../ThreadRefChip';+import ThreadSourceClosedAction from '../ThreadSourceClosedAction';import { THREAD_REF_KIND_IDS, threadRefLabel } from '../../../lib/threadRefKinds.js';import {THREAD_STATUSES, THREAD_PRIORITIES, THREAD_ACTIVE_STATUSES,@@ -145,6 +146,8 @@ export default function ThreadsTab() {const tag = searchParams.get('tag') || '';const q = searchParams.get('q') || '';const selectedId = searchParams.get('thread');+ const selectedIdRef = useRef(selectedId);+ selectedIdRef.current = selectedId;const [drawerTab, setDrawerTab] = useDrawerTab('threadTab', 'details', DRAWER_TAB_IDS);const [threads, setThreads] = useState([]);@@ -153,6 +156,7 @@ export default function ThreadsTab() {const [record, setRecord] = useState(null);const [draft, setDraft] = useState(null);const [confirmDelete, setConfirmDelete] = useState(false);+ const [completingSource, setCompletingSource] = useState(false);const [newRef, setNewRef] = useState({ kind: 'url', id: '', label: '' });// Two-stage search (the Catalog page's pattern): `searchInput` is what the@@ -224,6 +228,15 @@ export default function ThreadsTab() {replaceRow(full);};+ const completeFromSource = (updated) => {+ replaceRow(updated);+ // The user can navigate while a save is pending. Never replace another+ // drawer's record, or discard edits typed while the request was in flight.+ if (selectedIdRef.current !== updated.id) return;+ setRecord((prev) => ({ ...prev, ...updated }));+ setDraft((prev) => ({ ...prev, status: updated.status }));+ };+const [create, creating] = useAsyncAction(async () => {const title = newTitle.trim();if (!title) return null;@@ -375,7 +388,7 @@ export default function ThreadsTab() {closeOnBackdrop={!dirty}>{record && draft && (- <div className="space-y-4">+ <fieldset disabled={completingSource} className="space-y-4 min-w-0"><div className="flex items-center justify-end gap-2">{dirty && <span className="text-xs text-port-warning">Unsaved changes</span>}<button@@ -421,9 +434,13 @@ export default function ThreadsTab() {<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>- )}+ <ThreadSourceClosedAction+ key={record.id}+ thread={record}+ onCompleted={completeFromSource}+ onPendingChange={setCompletingSource}+ disabled={dirty || saving || removing}+ /><div className="pt-2 border-t border-port-border">{confirmDelete ? (<InlineConfirmRow@@ -485,7 +502,7 @@ export default function ThreadsTab() {/></FormField>)}- </div>+ </fieldset>)}</Drawer></div>diff --git a/client/src/components/brain/tabs/ThreadsTab.test.jsx b/client/src/components/brain/tabs/ThreadsTab.test.jsxindex b3a478fb9d..6dd3e5aded 100644--- a/client/src/components/brain/tabs/ThreadsTab.test.jsx+++ b/client/src/components/brain/tabs/ThreadsTab.test.jsx@@ -2,7 +2,7 @@ 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 { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { MemoryRouter, useLocation } from 'react-router';vi.mock('../../../services/api', () => ({@@ -91,6 +91,46 @@ describe('ThreadsTab', () => {expect(api.listThreads).toHaveBeenCalledTimes(1);});+ it('completes a source-closed thread explicitly from its drawer and preserves hydrated links', async () => {+ const thread = { ...ROWS[2], externalState: 'closed', notes: 'body', resolvedRefs: RESOLVED };+ api.getThread.mockResolvedValue(thread);+ let finish;+ api.updateThread.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ renderTab('/brain/threads?thread=op');+ const dialog = within(await screen.findByRole('dialog'));+ const complete = await dialog.findByRole('button', { name: 'Mark "Plain loop" done' });+ expect(api.updateThread).not.toHaveBeenCalled();+ fireEvent.change(dialog.getByLabelText('Title'), { target: { value: 'My title' } });+ expect(complete).toBeDisabled();+ fireEvent.change(dialog.getByLabelText('Title'), { target: { value: thread.title } });+ fireEvent.click(complete);+ expect(complete).toBeDisabled();+ expect(dialog.getByLabelText('Title')).toBeDisabled();+ expect(api.updateThread).toHaveBeenCalledWith('op', { status: 'done' }, { silent: true });+ await act(async () => { finish({ ...ROWS[2], notes: 'body', externalState: 'closed', status: 'done' }); });+ expect(dialog.getByLabelText('Status')).toHaveValue('done');+ expect(dialog.queryByText('Source closed — mark done?')).toBeNull();+ expect(screen.queryByRole('button', { name: 'Mark "Plain loop" done' })).toBeNull();+ fireEvent.click(dialog.getByRole('tab', { name: 'Links' }));+ expect(await dialog.findByText('example')).toBeTruthy();+ expect(api.listThreads).toHaveBeenCalledTimes(1);+ });++ it('does not replace a different drawer when completion finishes after navigation', async () => {+ api.getThread.mockImplementation(async (id) => ({ ...ROWS.find((r) => r.id === id), externalState: 'closed', notes: 'body', resolvedRefs: RESOLVED }));+ let finish;+ api.updateThread.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ renderTab('/brain/threads?thread=op');+ const dialog = within(await screen.findByRole('dialog'));+ fireEvent.click(await dialog.findByRole('button', { name: 'Mark "Plain loop" done' }));+ fireEvent.click(screen.getByRole('button', { name: 'Close thread' }));+ fireEvent.click(screen.getByText('Waiting loop'));+ await waitFor(() => expect(screen.getByLabelText('Title')).toHaveValue('Waiting loop'));+ await act(async () => { finish({ ...ROWS[2], status: 'done' }); });+ expect(screen.getByLabelText('Title')).toHaveValue('Waiting loop');+ expect(screen.getByLabelText('Status')).toHaveValue('waiting');+ });+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();diff --git a/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx b/client/src/components/dashboard/builtins/OpenThreadsWidget.jsxindex 72e8f3138c..77b61050db 100644--- a/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx+++ b/client/src/components/dashboard/builtins/OpenThreadsWidget.jsx@@ -1,9 +1,11 @@+import { useState } from 'react';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';+import ThreadSourceClosedAction from '../../brain/ThreadSourceClosedAction';// 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@@ -19,6 +21,7 @@ const ROWS = 6;const WIDGET_STATUSES = 'open,waiting';export default function OpenThreadsWidget() {+ const [completed, setCompleted] = useState({});const { data, loading } = useAutoRefetch(() => api.listThreads({ status: WIDGET_STATUSES, limit: ROWS, offset: 0 }, { silent: true }),60_000,@@ -26,8 +29,12 @@ export default function OpenThreadsWidget() {if (loading && !data) return null;- const rows = Array.isArray(data?.threads) ? data.threads : [];- const total = Number.isFinite(data?.total) ? data.total : rows.length;+ const fetchedRows = Array.isArray(data?.threads) ? data.threads : [];+ // Retain successful writes over a poll that started before completion.+ // A genuinely newer record (e.g. reopened in Brain) becomes visible again.+ const rows = fetchedRows.filter((t) => !completed[t.id] || t.updatedAt > completed[t.id]);+ const total = (Number.isFinite(data?.total) ? data.total : fetchedRows.length) - (fetchedRows.length - rows.length);+ const onCompleted = (thread) => setCompleted((prev) => ({ ...prev, [thread.id]: thread.updatedAt }));return (<div className="@container bg-port-card border border-port-border rounded-xl p-4 h-full">@@ -41,7 +48,9 @@ export default function OpenThreadsWidget() {{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>+ {total > 0+ ? 'More open loops are available in Brain.'+ : <>No open loops. <Link to="/brain/threads" className="text-port-accent hover:underline">Track one</Link></>}</p>) : (<ul className="space-y-2">@@ -61,6 +70,7 @@ export default function OpenThreadsWidget() {<span className={`shrink-0 ${isThreadOverdue(t) ? 'text-port-error' : 'text-gray-500'}`}>{formatDateShort(t.dueAt)}</span>)}</Link>+ <ThreadSourceClosedAction thread={t} onCompleted={onCompleted} /></li>);})}diff --git a/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx b/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsxindex d6ddebd7c8..ec3eb314a0 100644--- a/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx+++ b/client/src/components/dashboard/builtins/OpenThreadsWidget.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi } from 'vitest';-import { render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { MemoryRouter } from 'react-router';// The widget owns only what to show from a fetched list; the polling belongs@@ -8,9 +8,11 @@ const mockUseAutoRefetch = vi.fn();vi.mock('../../../hooks/useAutoRefetch', () => ({useAutoRefetch: (...args) => mockUseAutoRefetch(...args),}));-vi.mock('../../../services/api', () => ({ listThreads: vi.fn() }));+vi.mock('../../../services/api', () => ({ listThreads: vi.fn(), updateThread: vi.fn() }));+vi.mock('../../ui/Toast', () => ({ default: { error: vi.fn() } }));import * as api from '../../../services/api';+import toast from '../../ui/Toast';import OpenThreadsWidget from './OpenThreadsWidget';const renderWidget = () => render(<MemoryRouter><OpenThreadsWidget /></MemoryRouter>);@@ -58,6 +60,63 @@ describe('OpenThreadsWidget', () => {expect(screen.getByText('+2 more').closest('a')).toHaveAttribute('href', '/brain/threads');});+ it('offers completion only for an unfinished thread with a positively closed source', () => {+ mockUseAutoRefetch.mockReturnValue({ loading: false, data: { threads: [+ { id: 'open', title: 'Open source', status: 'open', externalState: 'open' },+ { id: 'unknown', title: 'Unknown source', status: 'waiting', externalState: 'unknown' },+ { id: 'manual', title: 'Manual loop', status: 'open' },+ { id: 'done', title: 'Done loop', status: 'done', externalState: 'closed' },+ { id: 'archived', title: 'Archived loop', status: 'archived', externalState: 'closed' },+ { id: 'closed', title: 'Closed source', status: 'waiting', externalState: 'closed' },+ ] } });+ renderWidget();+ expect(screen.getAllByText('Source closed — mark done?')).toHaveLength(1);+ expect(screen.getByRole('button', { name: 'Mark "Closed source" done' }).closest('a')).toBeNull();+ expect(api.updateThread).not.toHaveBeenCalled();+ });++ it('removes a completed row and updates the count without fetching, tolerating stale polls and later reopening', async () => {+ const thread = { id: 'closed', title: 'Closed source', status: 'waiting', externalState: 'closed', updatedAt: '2026-01-01T00:00:00.000Z' };+ mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 8, threads: [thread] } });+ let finish;+ api.updateThread.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ const view = renderWidget();+ const button = screen.getByRole('button', { name: 'Mark "Closed source" done' });+ fireEvent.click(button);+ fireEvent.click(button);+ expect(button).toBeDisabled();+ expect(api.updateThread).toHaveBeenCalledTimes(1);+ expect(api.updateThread).toHaveBeenCalledWith('closed', { status: 'done' }, { silent: true });+ await act(async () => { finish({ ...thread, status: 'done', updatedAt: '2026-01-02T00:00:00.000Z' }); });+ expect(screen.queryByText('Closed source')).toBeNull();+ expect(screen.getByText('7 open')).toBeTruthy();+ expect(screen.queryByText(/No open loops/)).toBeNull();+ expect(api.listThreads).not.toHaveBeenCalled();+ mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 8, threads: [{ ...thread }] } });+ view.rerender(<MemoryRouter><OpenThreadsWidget /></MemoryRouter>);+ expect(screen.queryByText('Closed source')).toBeNull();+ mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 8, threads: [{ ...thread, updatedAt: '2026-01-03T00:00:00.000Z' }] } });+ view.rerender(<MemoryRouter><OpenThreadsWidget /></MemoryRouter>);+ expect(screen.getByText('Closed source')).toBeTruthy();+ expect(screen.getByText('8 open')).toBeTruthy();+ });++ it('keeps the row after a failed completion, reports the error once and permits retry', async () => {+ const thread = { id: 'closed', title: 'Closed source', status: 'open', externalState: 'closed' };+ mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 1, threads: [thread] } });+ api.updateThread.mockRejectedValueOnce(new Error('Connection lost')).mockResolvedValueOnce({ ...thread, status: 'done', updatedAt: '2026-01-02T00:00:00.000Z' });+ renderWidget();+ const button = screen.getByRole('button', { name: 'Mark "Closed source" done' });+ fireEvent.click(button);+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Connection lost'));+ expect(toast.error).toHaveBeenCalledTimes(1);+ expect(screen.getByText('1 open')).toBeTruthy();+ expect(button).not.toBeDisabled();+ fireEvent.click(button);+ await waitFor(() => expect(screen.queryByText('Closed source')).toBeNull());+ expect(api.updateThread).toHaveBeenCalledTimes(2);+ });+it('offers to track one when the list is empty', () => {mockUseAutoRefetch.mockReturnValue({ loading: false, data: { total: 0, threads: [] } });renderWidget();