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

feat: build Actions commitments workspace (#7739)

[._.]/ Adam Eivy9cd8d1ee73bd
diff --git a/client/src/App.jsx b/client/src/App.jsx
index dd42c11963..1fdf471807 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -432,6 +432,7 @@ export default function App() {
satisfy with their :mode subtab (issue #3249). */}
<Route path="post/:tab/:subtab/:mode" element={<Post />} />
<Route path="review" element={<Review />} />
+ <Route path="review/:actionId" element={<Review />} />
<Route path="messages" element={<Navigate to="/messages/inbox" replace />} />
{/* :chatKey is only used by the imessage tab; other tabs strip a stray second segment. */}
<Route path="messages/:tab/:chatKey" element={<Messages />} />
diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsx
index 08addb3b56..6f10cdb806 100644
--- a/client/src/pages/Review.jsx
+++ b/client/src/pages/Review.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
-import { useNavigate } from 'react-router';
+import { useNavigate, useParams } from 'react-router';
import {
ClipboardList,
AlertTriangle,
@@ -23,20 +23,31 @@ import {
MessageCircle,
Mail,
Activity,
- DatabaseBackup
+ DatabaseBackup,
+ CalendarDays,
+ ListTodo,
+ Hourglass,
+ Sparkles,
+ History as HistoryIcon,
+ ExternalLink,
+ Save
} from 'lucide-react';
import PageHeader from '../components/PageHeader';
import PageSkeleton from '../components/ui/PageSkeleton';
import CollapsibleText from '../components/ui/CollapsibleText';
import MarkdownOutput from '../components/cos/MarkdownOutput';
-import { timeAgo, formatDateTime } from '../utils/formatters';
+import Drawer from '../components/Drawer';
+import TabPills from '../components/ui/TabPills';
+import useUrlParams from '../hooks/useUrlParams';
+import useAsyncAction from '../hooks/useAsyncAction';
+import { timeAgo, formatDateTime, formatCount, localDateKey } from '../utils/formatters';
import { markdownToPlainText, dropsMarkupWhenFlattened } from '../utils/markdownText';
import { coalesce } from '../utils/coalesce';
import * as api from '../services/api';
import socket from '../services/socket';
-// Producer-domain socket events that change what the cross-domain "Needs
-// Attention" queue (GET /api/review/queue) would return. The queue is derived
+// Producer-domain socket events that change what the unified Actions queue
+// (GET /api/review/queue) would return. The queue is derived
// live from each producer, so when any of these fire — a draft sent, an inbox
// item classified, a CoS task resolved, a backup finishing — we re-pull the
// queue (debounced) instead of waiting for a manual reload. Ask is omitted
@@ -50,7 +61,12 @@ const QUEUE_INVALIDATION_EVENTS = [
'messages:draft:sent', // draft sent (resolves a drafts row)
'backup:started', // backup state transitioning
'backup:completed', // backup succeeded (clears a failed-backup row)
- 'backup:failed' // backup errored (surfaces a failed-backup row)
+ 'backup:failed', // backup errored (surfaces a failed-backup row)
+ 'brain:threads:changed', // Brain commitment created/edited/completed
+ 'review:item:created', // legacy manual todo created
+ 'review:item:updated', // legacy manual todo status/title changed
+ 'review:item:deleted', // legacy manual todo removed
+ 'review:items:bulk-updated'
];
// Cross-domain queue source → icon + accent (M42 P5 inbox-zero aggregator).
@@ -60,7 +76,10 @@ const QUEUE_SOURCE_CONFIG = {
cos: { icon: Crown, color: 'text-port-accent' },
drafts: { icon: Mail, color: 'text-port-accent' },
health: { icon: Activity, color: 'text-port-warning' },
- backup: { icon: DatabaseBackup, color: 'text-port-error' }
+ backup: { icon: DatabaseBackup, color: 'text-port-error' },
+ threads: { icon: BrainIcon, color: 'text-port-accent-2' },
+ todo: { icon: ListTodo, color: 'text-port-success' },
+ history: { icon: HistoryIcon, color: 'text-gray-400' },
};
const QUEUE_SEVERITY_STYLE = {
@@ -78,6 +97,15 @@ const TYPE_CONFIG = {
const TYPE_PRIORITY = { alert: 0, cos: 1, todo: 2, briefing: 3 };
+const ACTION_VIEWS = [
+ { id: 'today', label: 'Today', icon: CalendarDays },
+ { id: 'all', label: 'All', icon: ListTodo },
+ { id: 'waiting', label: 'Waiting', icon: Hourglass },
+ { id: 'someday', label: 'Someday', icon: Sparkles },
+ { id: 'history', label: 'History', icon: HistoryIcon },
+];
+const ACTION_VIEW_IDS = new Set(ACTION_VIEWS.map(({ id }) => id));
+
const SOURCE_OWNED_REVIEW_CATEGORIES = new Set([
'content-review',
'goal-fidelity',
@@ -111,6 +139,10 @@ function isActionableItem(item) {
export default function Review() {
const navigate = useNavigate();
+ const { actionId } = useParams();
+ const [searchParams, updateParams] = useUrlParams();
+ const requestedActionView = searchParams.get('view');
+ const actionView = ACTION_VIEW_IDS.has(requestedActionView) ? requestedActionView : 'today';
const [items, setItems] = useState([]);
const [briefing, setBriefing] = useState(null);
const [loading, setLoading] = useState(true);
@@ -152,9 +184,9 @@ export default function Review() {
const fetchQueue = useCallback(async () => {
// Owns its own fallback, so silence the helper's default error toast.
- const data = await api.getReviewQueue({ silent: true }).catch(() => null);
+ const data = await api.getReviewQueue({ view: actionView, silent: true }).catch(() => null);
setQueue(data);
- }, []);
+ }, [actionView]);
useEffect(() => {
fetchItems();
@@ -219,8 +251,12 @@ export default function Review() {
const handleCreateTodo = async (e) => {
e.preventDefault();
if (!newTodo.trim()) return;
- await api.createReviewTodo({ title: newTodo.trim() }).catch(() => null);
+ const thread = await api.createThread({ title: newTodo.trim() }, { silent: true }).catch(() => null);
setNewTodo('');
+ await fetchQueue();
+ if (thread?.id) {
+ navigate(`/review/${encodeURIComponent(`threads:${thread.id}`)}?view=${actionView}`);
+ }
};
const handleComplete = async (id) => {
@@ -252,10 +288,13 @@ export default function Review() {
};
const handleQueueDrill = (item) => {
- handleQueueDismiss(item.id);
if (item.drillTo) navigate(item.drillTo);
};
+ const handleQueueSelect = (item) => {
+ navigate(`/review/${encodeURIComponent(item.id)}?view=${actionView}`);
+ };
+
const handleQueueResolve = async (item, operation) => {
if (resolvingQueueIds.has(item.id)) return;
setResolvingQueueIds(prev => new Set(prev).add(item.id));
@@ -269,8 +308,15 @@ export default function Review() {
next.delete(item.id);
return next;
});
- // Reactive removal — drop the resolved row in place rather than refetching.
- if (ok) handleQueueDismiss(item.id);
+ // Keep the visible row responsive, then re-read the canonical source. This
+ // matters for status views: a completed commitment must disappear from
+ // Today but remain reachable in History.
+ if (ok) {
+ handleQueueDismiss(item.id);
+ await fetchQueue();
+ if (actionId === item.id) navigate(`/review?view=${actionView}`, { replace: true });
+ }
+ return ok;
};
const handleQueuePromoteAsk = async (item, target, goalId) => {
@@ -283,8 +329,17 @@ export default function Review() {
next.delete(item.id);
return next;
});
- // Reactive removal — drop the promoted row in place rather than refetching.
- if (ok) handleQueueDismiss(item.id);
+ // Reactive removal — drop the promoted row in place, then refresh the
+ // source-backed queue so counts and partial-source metadata stay truthful.
+ if (ok) {
+ handleQueueDismiss(item.id);
+ await fetchQueue();
+ }
+ };
+
+ const setActionView = (view) => {
+ setDismissedQueueIds(new Set());
+ updateParams({ view });
};
// Derived review state. Memoized because this page subscribes to
@@ -311,6 +366,13 @@ export default function Review() {
const queueSourceErrors = useMemo(
() => Object.entries(queue?.sources || {}).filter(([, s]) => s.error),
[queue]);
+ const selectedAction = useMemo(
+ () => (queue?.items || []).find((item) => item.id === actionId) || null,
+ [queue, actionId]);
+ // Keep old stored Review records rendered only as a compatibility fallback
+ // while the live Actions projection is empty. Once a canonical row exists,
+ // rendering the old lists as well would show the same obligation twice.
+ const showLegacyReviewSurface = queueItems.length === 0 && queueSourceErrors.length === 0 && !queue?.partial;
const pendingItems = useMemo(() => items.filter(i => i.status === 'pending'), [items]);
const genericCompletableCount = pendingItems.filter(isGenericCompletableItem).length;
@@ -325,7 +387,7 @@ export default function Review() {
if (loading) {
return <PageSkeleton
- label="Loading review hub"
+ label="Loading Actions"
header="bar"
padded
fullHeight
@@ -350,7 +412,7 @@ export default function Review() {
<PageHeader
icon={ClipboardList}
iconColor="text-white"
- title="Review Hub"
+ title="Actions"
actions={(
<>
<select
@@ -388,6 +450,15 @@ export default function Review() {
)}
/>
<div className="flex-1 min-h-0 overflow-auto p-4 md:p-6 space-y-3">
+ <TabPills
+ tabs={ACTION_VIEWS}
+ activeTab={actionView}
+ onChange={setActionView}
+ ariaLabel="Actions views"
+ mobileCompact
+ mobileSelectId="actions-view-select"
+ controlsIdPrefix="actions-view"
+ />
{/* Triage summary */}
<section className="flex flex-wrap gap-2">
<SummaryPill icon={BellRing} label="Pending" value={counts?.total ?? 0} tone="text-white" />
@@ -396,20 +467,20 @@ export default function Review() {
<SummaryPill icon={ClipboardList} label="Todos" value={counts?.todo ?? 0} tone="text-port-success" />
</section>
- {/* Cross-domain "Needs Attention" queue (M42 P5) — live-pulled from
- Brain, Ask, CoS, Messages, Health, and Backups. Shown whenever there
+ {/* Canonical Actions queue — live-pulled from Brain commitments, manual
+ todos, Ask, CoS, Messages, Health, and Backups. Shown whenever there
are items OR a source failed to load (so the degraded-source notice
isn't hidden behind an otherwise-empty queue). */}
- {(queueItems.length > 0 || queueSourceErrors.length > 0) && (
+ {(queueItems.length > 0 || queueSourceErrors.length > 0 || queue?.partial) && (
<section className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<h3 className="text-sm font-semibold text-white flex items-center gap-2">
<Inbox size={16} className="text-port-accent" />
- Needs Attention
+ Actions
</h3>
{queueItems.length > 0 && (
<span className="text-xs rounded-full px-2 py-0.5 bg-port-accent/10 text-port-accent border border-port-accent/20">
- {queueItems.length} across domains
+ {formatCount(queueItems.length)} across domains
</span>
)}
</div>
@@ -419,6 +490,7 @@ export default function Review() {
<QueueRow
key={item.id}
item={item}
+ onSelect={handleQueueSelect}
onDrill={handleQueueDrill}
onDismiss={handleQueueDismiss}
onResolve={handleQueueResolve}
@@ -433,6 +505,11 @@ export default function Review() {
Couldn&apos;t load: {queueSourceErrors.map(([, s]) => s.label).join(', ')}.
</p>
)}
+ {queue?.partial && (
+ <p role="status" className="text-xs text-gray-500">
+ This bounded view may omit additional actions; open a source to see its complete list.
+ </p>
+ )}
</section>
)}
@@ -442,8 +519,8 @@ export default function Review() {
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
- aria-label="Quick add todo"
- placeholder="Quick add todo..."
+ aria-label="Quick add action"
+ placeholder="Quick add action..."
className="flex-1 bg-port-card border border-port-border rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent"
/>
<button
@@ -456,8 +533,10 @@ export default function Review() {
</button>
</form>
- {/* Action queue — only shown when there are actionable items */}
- {topActionItems.length > 0 && (
+ {/* Legacy Review list — only shown when the canonical projection is
+ empty, so old stored records remain usable without duplicating the
+ Actions rows. */}
+ {showLegacyReviewSurface && topActionItems.length > 0 && (
<section className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">
<div className="flex items-center justify-between gap-3">
<h3 className="text-sm font-semibold text-white flex items-center gap-2">
@@ -465,7 +544,7 @@ export default function Review() {
Action Queue
</h3>
<span className="text-xs rounded-full px-2 py-0.5 bg-port-warning/10 text-port-warning border border-port-warning/20">
- {actionableItems.length} actionable
+ {formatCount(actionableItems.length)} actionable
</span>
</div>
<div className="space-y-2">
@@ -488,14 +567,14 @@ export default function Review() {
</div>
{remainingActionCount > 0 && (
<p className="text-xs text-gray-500">
- {remainingActionCount} more actionable item{remainingActionCount !== 1 ? 's' : ''} below.
+ {formatCount(remainingActionCount)} more actionable item{remainingActionCount !== 1 ? 's' : ''} below.
</p>
)}
</section>
)}
- {/* Daily Briefing */}
- {briefing && briefing.source !== 'none' && (
+ {/* Daily Briefing remains available as compatibility/history context. */}
+ {showLegacyReviewSurface && briefing && briefing.source !== 'none' && (
<section className={`bg-port-card border border-port-border rounded-xl p-4 ${briefingFullscreen ? 'fixed inset-0 z-50 overflow-y-auto m-0 rounded-none' : ''}`}>
<div className="flex items-center justify-between gap-2 mb-2">
<h3 className="text-sm font-semibold text-white flex items-center gap-2">
@@ -523,7 +602,7 @@ export default function Review() {
{/* Detailed sections — tiled two-up on wide screens so the per-type
queues use the full width instead of stacking in one column. */}
- <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 items-start">
+ {showLegacyReviewSurface && <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 items-start">
{['alert', 'cos', 'todo', 'briefing'].map(type => {
const typeItems = grouped[type];
if (!typeItems?.length) return null;
@@ -535,7 +614,7 @@ export default function Review() {
<h3 className={`text-sm font-semibold uppercase tracking-wide ${config.color} flex items-center gap-2`}>
<TypeIcon size={16} />
{config.label}
- <span className="text-gray-600">({typeItems.length})</span>
+ <span className="text-gray-600">({formatCount(typeItems.length)})</span>
</h3>
<div className="space-y-1">
{typeItems.map(item => (
@@ -558,9 +637,9 @@ export default function Review() {
</section>
);
})}
- </div>
+ </div>}
- {visibleItems.length === 0 && (
+ {showLegacyReviewSurface && visibleItems.length === 0 && (
<div className="text-center py-12 text-gray-500">
<ClipboardList size={48} className="mx-auto mb-3 opacity-30" />
<p className="text-lg">No review items in this view</p>
@@ -568,6 +647,13 @@ export default function Review() {
</div>
)}
</div>
+ <ActionDetail
+ item={selectedAction}
+ onClose={() => navigate(`/review?view=${actionView}`, { replace: true })}
+ onResolve={handleQueueResolve}
+ onSaved={fetchQueue}
+ onDrill={handleQueueDrill}
+ />
</div>
);
}
@@ -595,7 +681,7 @@ function QueueMetaChips({ meta }) {
if (typeof meta.turnCount === 'number') {
chips.push(
<span key="turns" className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-400">
- {meta.turnCount} turn{meta.turnCount === 1 ? '' : 's'}
+ {formatCount(meta.turnCount)} turn{meta.turnCount === 1 ? '' : 's'}
</span>
);
}
@@ -627,6 +713,20 @@ function QueueMetaChips({ meta }) {
</span>
);
}
+ if (meta.localStatus) {
+ chips.push(
+ <span key="local-status" className="text-[10px] px-1.5 py-0.5 rounded border border-port-accent/30 text-port-accent">
+ local: {meta.localStatus}
+ </span>
+ );
+ }
+ if (meta.externalState) {
+ chips.push(
+ <span key="external-state" className="text-[10px] px-1.5 py-0.5 rounded border border-port-border text-gray-400">
+ external: {meta.externalState}
+ </span>
+ );
+ }
if (!chips.length) return null;
return <div className="flex items-center gap-1.5 flex-wrap mt-1">{chips}</div>;
}
@@ -634,7 +734,7 @@ function QueueMetaChips({ meta }) {
// Promote-target label for the Ask picker buttons.
const PROMOTE_TARGET_LABEL = { brain: 'Brain', task: 'Task', goal: 'Goal' };
-function QueueRow({ item, onDrill, onDismiss, onResolve, onPromoteAsk, resolving = false }) {
+function QueueRow({ item, onSelect, onDrill, onDismiss, onResolve, onPromoteAsk, resolving = false }) {
const config = QUEUE_SOURCE_CONFIG[item.source] || { icon: Inbox, color: 'text-gray-400' };
const Icon = config.icon;
const borderTone = QUEUE_SEVERITY_STYLE[item.severity] || QUEUE_SEVERITY_STYLE.normal;
@@ -658,7 +758,14 @@ function QueueRow({ item, onDrill, onDismiss, onResolve, onPromoteAsk, resolving
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
- <p className="text-sm font-medium text-white">{item.title}</p>
+ <button
+ type="button"
+ onClick={() => onSelect?.(item)}
+ className="text-sm font-medium text-white text-left hover:text-port-accent focus:outline-none focus-visible:ring-2 focus-visible:ring-port-accent rounded"
+ aria-label={`Open action ${item.title}`}
+ >
+ {item.title}
+ </button>
<span className={`text-[10px] uppercase tracking-wide px-2 py-0.5 rounded-full border border-current/20 ${config.color}`}>
{item.sourceLabel}
</span>
@@ -745,7 +852,7 @@ function SummaryPill({ icon: Icon, label, value, tone = 'text-white', urgent = f
<div className={`inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 bg-port-card ${urgent ? 'border-port-warning/40' : 'border-port-border'}`}>
<Icon size={14} className={urgent ? 'text-port-warning' : tone} />
<span className="text-xs text-gray-500">{label}</span>
- <span className={`text-sm font-bold ${tone}`}>{value}</span>
+ <span className={`text-sm font-bold ${tone}`}>{formatCount(value, { fallback: '0' })}</span>
</div>
);
}
@@ -917,3 +1024,176 @@ function ReviewItem({ item, config, idScope, isEditing, onComplete, onDismiss, o
</div>
);
}
+
+const threadDraft = (record) => ({
+ title: record?.title || '',
+ status: record?.status || 'open',
+ priority: record?.priority || 'normal',
+ nextAction: record?.nextAction || '',
+ dueAt: typeof record?.dueAt === 'string' ? localDateKey(new Date(record.dueAt)) : '',
+ notes: record?.notes || '',
+});
+
+function ActionDetail({ item, onClose, onResolve, onSaved, onDrill }) {
+ const isThread = item?.source === 'threads';
+ const isTodo = item?.source === 'todo';
+ const [record, setRecord] = useState(item);
+ const [draft, setDraft] = useState(() => (isThread ? threadDraft(item) : {
+ title: item?.title || '',
+ description: item?.summary || '',
+ }));
+
+ useEffect(() => {
+ if (!item) return;
+ setRecord(item);
+ setDraft(isThread ? threadDraft(item) : {
+ title: item.title || '',
+ description: item.summary || '',
+ });
+ if (isThread && item.sourceRef) {
+ api.getThread(item.sourceRef, { silent: true })
+ .then((full) => {
+ setRecord(full);
+ setDraft(threadDraft(full));
+ })
+ .catch(() => null);
+ }
+ }, [item?.id, item?.sourceRef, isThread]);
+
+ const [save, saving] = useAsyncAction(async () => {
+ if (!item || !draft || (!isThread && !isTodo)) return null;
+ const updated = isThread
+ ? await api.updateThread(item.sourceRef, {
+ title: draft.title.trim(),
+ status: draft.status,
+ priority: draft.priority,
+ nextAction: draft.nextAction.trim(),
+ dueAt: draft.dueAt ? new Date(`${draft.dueAt}T00:00:00`).toISOString() : null,
+ notes: draft.notes,
+ }, { silent: true })
+ : await api.updateReviewItem(item.sourceRef, {
+ title: draft.title.trim(),
+ description: draft.description.trim(),
+ }, { silent: true });
+ setRecord((previous) => ({ ...previous, ...updated }));
+ setDraft(isThread ? threadDraft({ ...record, ...updated }) : {
+ title: updated.title || '',
+ description: updated.description || '',
+ });
+ await onSaved?.(updated);
+ return updated;
+ }, { errorMessage: 'Failed to save action' });
+
+ if (!item) return null;
+
+ const operations = Array.isArray(item.operations)
+ ? item.operations.filter((operation) => operation?.available !== false)
+ : [];
+ const localStatus = item.meta?.localStatus || record?.status || item.meta?.status;
+ const externalState = item.meta?.externalState;
+ const updateDraft = (patch) => setDraft((previous) => ({ ...previous, ...patch }));
+ const resolve = async (operation) => {
+ const ok = await onResolve(item, operation);
+ if (ok) onClose();
+ };
+
+ return (
+ <Drawer
+ open
+ onClose={onClose}
+ title={item.title}
+ subtitle={item.sourceLabel}
+ size="md"
+ closeLabel="Close action"
+ >
+ <div className="space-y-5">
+ <div className="space-y-2">
+ <p className="text-sm text-gray-300">{item.summary || 'No additional context.'}</p>
+ <div className="flex flex-wrap gap-2 text-xs">
+ {localStatus && <span className="rounded border border-port-accent/30 px-2 py-1 text-port-accent">Local: {localStatus}</span>}
+ {externalState && <span className="rounded border border-port-border px-2 py-1 text-gray-400">External: {externalState}</span>}
+ {item.meta?.externalSource && <span className="rounded border border-port-border px-2 py-1 text-gray-400">Source: {item.meta.externalSource}</span>}
+ </div>
+ </div>
+
+ {(isThread || isTodo) && (
+ <section className="space-y-3">
+ <h3 className="text-sm font-semibold text-white">Edit commitment</h3>
+ <label className="block text-xs text-gray-400" htmlFor="action-detail-title">
+ Title
+ <input
+ id="action-detail-title"
+ value={draft?.title || ''}
+ onChange={(e) => updateDraft({ title: e.target.value })}
+ className="mt-1 w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white"
+ />
+ </label>
+ {isThread ? (
+ <>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <label className="block text-xs text-gray-400" htmlFor="action-detail-status">
+ Local status
+ <select id="action-detail-status" value={draft.status} onChange={(e) => updateDraft({ status: e.target.value })} className="mt-1 w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white">
+ <option value="open">Open</option>
+ <option value="waiting">Waiting</option>
+ <option value="someday">Someday</option>
+ <option value="done">Done</option>
+ <option value="archived">Archived</option>
+ </select>
+ </label>
+ <label className="block text-xs text-gray-400" htmlFor="action-detail-priority">
+ Priority
+ <select id="action-detail-priority" value={draft.priority} onChange={(e) => updateDraft({ priority: e.target.value })} className="mt-1 w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white">
+ <option value="urgent">Urgent</option>
+ <option value="high">High</option>
+ <option value="normal">Normal</option>
+ <option value="low">Low</option>
+ </select>
+ </label>
+ </div>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <label className="block text-xs text-gray-400" htmlFor="action-detail-next-action">
+ Next action
+ <input id="action-detail-next-action" value={draft.nextAction} onChange={(e) => updateDraft({ nextAction: e.target.value })} className="mt-1 w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white" />
+ </label>
+ <label className="block text-xs text-gray-400" htmlFor="action-detail-due">
+ Due date
+ <input id="action-detail-due" type="date" value={draft.dueAt} onChange={(e) => updateDraft({ dueAt: e.target.value })} className="mt-1 w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white" />
+ </label>
+ </div>
+ <label className="block text-xs text-gray-400" htmlFor="action-detail-notes">
+ Notes
+ <textarea id="action-detail-notes" rows={5} value={draft.notes} onChange={(e) => updateDraft({ notes: e.target.value })} className="mt-1 w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white resize-y" />
+ </label>
+ </>
+ ) : (
+ <label className="block text-xs text-gray-400" htmlFor="action-detail-description">
+ Notes
+ <textarea id="action-detail-description" rows={5} value={draft.description} onChange={(e) => updateDraft({ description: e.target.value })} className="mt-1 w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white resize-y" />
+ </label>
+ )}
+ <button type="button" onClick={save} disabled={saving || !draft?.title?.trim()} className="inline-flex items-center gap-2 rounded border border-port-accent/40 px-3 py-2 text-sm text-port-accent hover:bg-port-accent/10 disabled:opacity-50">
+ <Save size={14} /> {saving ? 'Saving…' : 'Save changes'}
+ </button>
+ </section>
+ )}
+
+ {operations.length > 0 && (
+ <section className="flex flex-wrap gap-2">
+ {operations.map((operation) => (
+ <button key={operation.id} type="button" onClick={() => resolve(operation.id)} className="inline-flex items-center gap-2 rounded bg-port-success/10 border border-port-success/30 px-3 py-2 text-sm text-port-success hover:bg-port-success/20">
+ <Check size={14} /> {operation.label}
+ </button>
+ ))}
+ </section>
+ )}
+
+ {item.drillTo && (
+ <button type="button" onClick={() => { onClose(); onDrill(item); }} className="inline-flex items-center gap-2 text-sm text-port-accent hover:underline">
+ <ExternalLink size={14} /> Open source editor
+ </button>
+ )}
+ </div>
+ </Drawer>
+ );
+}
diff --git a/client/src/pages/Review.test.jsx b/client/src/pages/Review.test.jsx
index f9938115e3..a92b992774 100644
--- a/client/src/pages/Review.test.jsx
+++ b/client/src/pages/Review.test.jsx
@@ -62,6 +62,9 @@ vi.mock('../services/api', () => ({
getReviewCounts: vi.fn(),
getReviewBriefing: vi.fn(() => Promise.resolve(null)),
getReviewQueue: vi.fn(() => Promise.resolve({ items: [], sources: {} })),
+ createThread: vi.fn(() => Promise.resolve({ id: 'thread-1', title: 'New action' })),
+ getThread: vi.fn(() => Promise.resolve({ id: 'thread-1', title: 'New action', status: 'open' })),
+ updateThread: vi.fn(() => Promise.resolve({ id: 'thread-1', title: 'Updated action', status: 'open' })),
createReviewTodo: vi.fn(() => Promise.resolve({})),
completeReviewItem: vi.fn(() => Promise.resolve({})),
dismissReviewItem: vi.fn(() => Promise.resolve({})),
@@ -78,7 +81,9 @@ vi.mock('../services/socket', () => ({
}));
vi.mock('react-router', () => ({
- useNavigate: () => vi.fn()
+ useNavigate: () => vi.fn(),
+ useParams: () => ({}),
+ useSearchParams: () => [new URLSearchParams(), vi.fn()]
}));
import Review from './Review';
@@ -236,6 +241,21 @@ describe('Review Hub queue-card triage (#3282)', () => {
});
});
+describe('Actions commitments workspace (#7739)', () => {
+ it('uses Brain threads for quick-add instead of the legacy todo endpoint', async () => {
+ render(<Review />);
+ const input = await screen.findByLabelText('Quick add action');
+ fireEvent.change(input, { target: { value: 'Track the example follow-up' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add' }));
+
+ await waitFor(() => expect(api.createThread).toHaveBeenCalledWith(
+ { title: 'Track the example follow-up' },
+ { silent: true },
+ ));
+ expect(api.createReviewTodo).not.toHaveBeenCalled();
+ });
+});
+
describe('Review Hub bulk status updates (#6853)', () => {
it('applies a review:items:bulk-updated event to every affected item in one update', async () => {
render(<Review />);
diff --git a/client/src/services/apiReview.js b/client/src/services/apiReview.js
index 3eb84dd06a..ccf5bd0713 100644
--- a/client/src/services/apiReview.js
+++ b/client/src/services/apiReview.js
@@ -13,8 +13,8 @@ export const getReviewBriefing = () => request('/review/briefing');
// Cross-domain live queue (source-owned obligations plus domain projections).
// Keep transport options (silent, headers, abort signal) separate from the
// pagination query so callers can continue using the old options-only shape.
-export const getReviewQueue = ({ limit, cursor, ...options } = {}) => {
- const query = queryString({ limit, cursor });
+export const getReviewQueue = ({ view, limit, cursor, ...options } = {}) => {
+ const query = queryString({ view, limit, cursor });
return request(`/review/queue${query}`, options);
};
// Resolve a single queue row in place (id is `<source>:<rawId>`). Source-owned
@@ -37,9 +37,10 @@ export const createReviewTodo = (data) => request('/review/todo', {
method: 'POST',
body: JSON.stringify(data)
});
-export const updateReviewItem = (id, data) => request(`/review/items/${id}`, {
+export const updateReviewItem = (id, data, options = {}) => request(`/review/items/${id}`, {
method: 'PATCH',
- body: JSON.stringify(data)
+ body: JSON.stringify(data),
+ ...options
});
export const completeReviewItem = (id) => request(`/review/items/${id}/complete`, { method: 'POST' });
export const dismissReviewItem = (id) => request(`/review/items/${id}/dismiss`, { method: 'POST' });
diff --git a/client/src/services/apiReview.test.js b/client/src/services/apiReview.test.js
index 2a3164a856..f37a5ec250 100644
--- a/client/src/services/apiReview.test.js
+++ b/client/src/services/apiReview.test.js
@@ -24,6 +24,14 @@ beforeEach(async () => {
});
describe('getReviewQueue', () => {
+ it('encodes the Actions view with pagination while preserving request options', async () => {
+ request.mockResolvedValue({ items: [] });
+
+ await getReviewQueue({ view: 'today', limit: 25, cursor: 'snapshot/page', silent: true });
+
+ expect(request).toHaveBeenCalledWith('/review/queue?view=today&limit=25&cursor=snapshot%2Fpage', { silent: true });
+ });
+
it('encodes pagination in the query while preserving request options', async () => {
request.mockResolvedValue({ items: [] });
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 3e2bf84892..e9ef47d74b 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1777,6 +1777,7 @@ export const agentActivityCleanupSchema = z.object({
export const reviewQueueQuerySchema = z.object({
limit: z.preprocess(emptyToUndefined, z.coerce.number().int().min(1).max(100).optional()),
cursor: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(4096).optional()),
+ view: z.preprocess(emptyToUndefined, z.enum(['today', 'all', 'waiting', 'someday', 'history']).optional()),
}).strict();
// =============================================================================
diff --git a/server/routes/review.js b/server/routes/review.js
index 9e545c0213..925dedbdc1 100644
--- a/server/routes/review.js
+++ b/server/routes/review.js
@@ -45,14 +45,14 @@ router.get('/briefing', asyncHandler(async (req, res) => {
// attention, including source-owned review obligations and actionable
// notifications.
router.get('/queue', asyncHandler(async (req, res) => {
- const { limit, cursor } = validateRequest(reviewQueueQuerySchema, req.query);
- const queue = await buildQueue({ limit, cursor, query: {} });
+ const { limit, cursor, view } = validateRequest(reviewQueueQuerySchema, req.query);
+ const queue = await buildQueue({ limit, cursor, query: { ...(view ? { view } : {}) } });
res.json(queue);
}));
const resolveQueueSchema = z.object({
id: z.string().min(1).max(500),
- operation: z.enum(['resolve', 'approve', 'reject']).optional(),
+ operation: z.enum(['resolve', 'approve', 'reject', 'complete', 'reopen']).optional(),
});
// POST /api/review/queue/resolve — accept a single cross-domain queue row in
@@ -86,7 +86,8 @@ router.post('/queue/promote-ask', asyncHandler(async (req, res) => {
res.json(result);
}));
-// POST /api/review/todo — create a user todo
+// POST /api/review/todo — legacy compatibility endpoint. New Actions quick-add
+// writes Brain threads; existing clients keep this endpoint and store shape.
router.post('/todo', asyncHandler(async (req, res) => {
const data = validateRequest(createTodoSchema, req.body);
const item = await reviewService.createItem({
diff --git a/server/services/review.js b/server/services/review.js
index afc54a9e48..5decc4d9a3 100644
--- a/server/services/review.js
+++ b/server/services/review.js
@@ -323,6 +323,34 @@ export async function completeItem(id) {
return updateItemStatus(id, 'completed');
}
+/**
+ * Reopen a completed or dismissed personal item. Archived items are moved back
+ * into the live collection before the archive entry is removed so pending work
+ * never remains stranded in cold storage.
+ */
+export async function reopenItem(id) {
+ const liveItems = await loadItems();
+ if (liveItems.some((item) => item.id === id)) {
+ return updateItemStatus(id, 'pending');
+ }
+
+ const archive = await loadArchive();
+ const index = archive.findIndex((item) => item.id === id);
+ if (index === -1) {
+ const err = new Error(`Review item not found: ${id}`);
+ err.status = 404;
+ throw err;
+ }
+
+ const [item] = archive.splice(index, 1);
+ const reopened = { ...item, status: 'pending', updatedAt: new Date().toISOString() };
+ await saveItems([...liveItems, reopened]);
+ await atomicWrite(ARCHIVE_FILE, archive);
+ console.log(`📋 Review item reopened: ${reopened.type} — ${reopened.title}`);
+ reviewEvents.emit('item:updated', reopened);
+ return reopened;
+}
+
/**
* Dismiss an item
*/
diff --git a/server/services/review.test.js b/server/services/review.test.js
index b8fdaa4069..0f8b75e62f 100644
--- a/server/services/review.test.js
+++ b/server/services/review.test.js
@@ -39,6 +39,7 @@ const {
getItems,
getPendingCounts,
completeItem,
+ reopenItem,
dismissItem,
updateItem,
deleteItem,
@@ -154,6 +155,15 @@ describe('review service', () => {
expect(updated.status).toBe('dismissed');
});
+ it('reopens a completed personal item', async () => {
+ const items = [{ id: '1', type: 'todo', title: 'Test', status: 'completed', createdAt: '', updatedAt: '' }];
+ readFile.mockResolvedValue(JSON.stringify(items));
+
+ const updated = await reopenItem('1');
+ expect(updated.status).toBe('pending');
+ expect(atomicWrite).toHaveBeenCalled();
+ });
+
it('rejects generic completion for source-owned obligations', async () => {
const items = [{
id: 'memory-review',
diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.js
index 340177e2f0..628cdb9546 100644
--- a/server/services/reviewQueue.js
+++ b/server/services/reviewQueue.js
@@ -28,6 +28,7 @@
import { randomUUID } from 'node:crypto';
import * as brain from './brain.js';
+import * as brainStorage from './brainStorage.js';
import * as askConversations from './askConversations.js';
import * as cosTaskStore from './cosTaskStore.js';
import * as messageDrafts from './messageDrafts.js';
@@ -42,6 +43,9 @@ import { promoteLatestAssistantTurn } from './askPromote.js';
import { adaptNotification, adaptStoredReviewItem } from './reviewActionAdapters.js';
import { ServerError } from '../lib/errorHandler.js';
import { safeJSONParse } from '../lib/fileUtils.js';
+import { getUserTimezone } from './userTimezone.js';
+import { todayInTimezone } from '../lib/timezone.js';
+import { isTerminalThreadStatus, threadNextLine } from '../lib/brainThreads.js';
// Producers are read with a bounded upper limit. The queue reports a lower
// bound, rather than pretending that a full count is known, when a producer
@@ -65,6 +69,9 @@ const ACTION_KINDS = Object.freeze({
backup: 'backup.retry',
review: 'review.triage',
notifications: 'notification.action',
+ threads: 'brain.thread',
+ todo: 'review.todo',
+ history: 'review.history',
});
const OPERATION_LABELS = Object.freeze({
@@ -78,6 +85,9 @@ const OPERATION_LABELS = Object.freeze({
backup: 'Retry',
review: 'Review',
notifications: 'Review',
+ threads: 'Complete',
+ todo: 'Complete',
+ history: 'History',
});
const PRIORITY_ORDER = { HIGH: 0, MEDIUM: 1, LOW: 2 };
@@ -121,6 +131,51 @@ async function getActiveGoalOptions() {
.map((g) => ({ id: g.id, title: typeof g.title === 'string' && g.title ? g.title : '(untitled goal)' }));
}
+const COMMITMENT_VIEWS = new Set(['today', 'all', 'waiting', 'someday', 'history']);
+const ACTIVE_THREAD_STATUSES = new Set(['open', 'waiting', 'someday']);
+
+function isDueByLocalToday(thread, timezone, now = new Date()) {
+ if (!thread.dueAt) return thread.status === 'open';
+ const dueAt = Date.parse(thread.dueAt);
+ if (!Number.isFinite(dueAt)) return false;
+ const today = todayInTimezone(timezone, now);
+ const dueDay = todayInTimezone(timezone, new Date(dueAt));
+ return dueDay <= today;
+}
+
+function threadBelongsToView(thread, view, timezone, now = new Date()) {
+ if (!thread || typeof thread.id !== 'string' || !thread.id) return false;
+ if (!view) return ACTIVE_THREAD_STATUSES.has(thread.status);
+ if (!COMMITMENT_VIEWS.has(view)) return ACTIVE_THREAD_STATUSES.has(thread.status);
+ if (view === 'all') return ACTIVE_THREAD_STATUSES.has(thread.status);
+ if (view === 'history') return isTerminalThreadStatus(thread.status);
+ if (view === 'waiting' || view === 'someday') return thread.status === view;
+ return ACTIVE_THREAD_STATUSES.has(thread.status) && isDueByLocalToday(thread, timezone, now);
+}
+
+const visibleInLiveViews = (producer, view) => {
+ if (!view) return producer.source !== 'history';
+ if (Array.isArray(producer.views)) return producer.views.includes(view);
+ return view === 'today' || view === 'all';
+};
+
+const threadAction = (thread) => {
+ const terminal = isTerminalThreadStatus(thread.status);
+ return terminal
+ ? [{ id: 'reopen', label: 'Reopen', available: true }]
+ : [{ id: 'complete', label: 'Complete', available: true }];
+};
+
+const threadMeta = (thread) => ({
+ localStatus: thread.status,
+ externalState: typeof thread.externalState === 'string' && thread.externalState
+ ? thread.externalState
+ : 'unknown',
+ ...(typeof thread.source === 'string' && thread.source.trim()
+ ? { externalSource: thread.source.trim() }
+ : {}),
+});
+
/**
* Producer registry. Each entry knows how to gather its raw items and map one
* into the normalized queue shape. `gather` returns the raw list (already
@@ -160,6 +215,37 @@ const PRODUCERS = [
};
}
},
+ {
+ source: 'threads',
+ label: 'Brain commitments',
+ drillTo: '/brain/threads',
+ views: ['today', 'all', 'waiting', 'someday', 'history'],
+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT, ctx = {}) {
+ const timezone = ctx.timezone || 'UTC';
+ const now = ctx.now || new Date();
+ const threads = await brainStorage.getThreads();
+ const matching = (Array.isArray(threads) ? threads : [])
+ .filter((thread) => threadBelongsToView(thread, ctx.view, timezone, now));
+ return { items: matching, truncated: matching.length > limit };
+ },
+ map(thread) {
+ const nextAction = threadNextLine(thread);
+ const summary = nextAction || (thread.waitingOn ? `Waiting on ${thread.waitingOn}` : 'No next action set');
+ return {
+ id: `threads:${thread.id}`,
+ title: thread.title || 'Untitled commitment',
+ summary,
+ timestamp: thread.updatedAt || thread.createdAt || null,
+ severity: thread.priority === 'urgent' ? 'high' : 'normal',
+ required: true,
+ isRecommendation: false,
+ dueAt: thread.dueAt || null,
+ drillTo: `/brain/threads?thread=${encodeURIComponent(thread.id)}`,
+ operations: threadAction(thread),
+ meta: threadMeta(thread),
+ };
+ },
+ },
{
source: 'ask',
label: 'Ask answers',
@@ -311,6 +397,68 @@ const PRODUCERS = [
return item;
},
},
+ {
+ source: 'todo',
+ label: 'Manual commitments',
+ drillTo: '/review?view=history',
+ views: ['today', 'all', 'history'],
+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT, ctx = {}) {
+ const history = ctx.view === 'history';
+ const items = await reviewService.getItems({
+ type: 'todo',
+ ...(history ? {} : { status: 'pending' }),
+ });
+ const matching = (Array.isArray(items) ? items : [])
+ .filter((item) => item.type === 'todo')
+ .filter((item) => history ? item.status !== 'pending' : item.status === 'pending');
+ return { items: matching, truncated: matching.length > limit };
+ },
+ map(item) {
+ const completed = item.status !== 'pending';
+ return {
+ id: `todo:${item.id}`,
+ title: item.title || 'Untitled commitment',
+ summary: item.description || item.title || '',
+ timestamp: item.updatedAt || item.createdAt || null,
+ dueAt: item.metadata?.dueAt || null,
+ required: !completed,
+ isRecommendation: false,
+ drillTo: `/review/${encodeURIComponent(`todo:${item.id}`)}?view=${completed ? 'history' : 'today'}`,
+ operations: completed
+ ? [{ id: 'reopen', label: 'Reopen', available: true }]
+ : [{ id: 'complete', label: 'Complete', available: true }],
+ meta: { status: item.status, reviewItemId: item.id },
+ };
+ },
+ },
+ {
+ source: 'history',
+ label: 'Review history',
+ drillTo: '/review?view=history',
+ views: ['history'],
+ async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {
+ const items = await reviewService.getItems();
+ const matching = (Array.isArray(items) ? items : [])
+ .filter((item) => item.status !== 'pending' && item.type !== 'todo');
+ return {
+ items: matching,
+ truncated: matching.length > limit,
+ };
+ },
+ map(item) {
+ return {
+ id: `history:${item.id}`,
+ title: item.title || 'Review history item',
+ summary: item.description || item.title || '',
+ timestamp: item.updatedAt || item.createdAt || null,
+ required: false,
+ isRecommendation: false,
+ operations: [],
+ drillTo: item.metadata?.link || '/review?view=history',
+ meta: { status: item.status, type: item.type, reviewItemId: item.id },
+ };
+ },
+ },
{
source: 'notifications',
label: 'Actionable notifications',
@@ -452,8 +600,15 @@ const SEVERITY_ORDER = { critical: 0, high: 1, normal: 2 };
* `goal` only when goals exist), so the map result is spread AFTER the
* producer-level default.
*/
-const canonicalPriority = (value) =>
- typeof value === 'string' && Object.hasOwn(PRIORITY_ORDER, value) ? value : null;
+const canonicalPriority = (value) => {
+ if (typeof value !== 'string') return null;
+ if (Object.hasOwn(PRIORITY_ORDER, value)) return value;
+ const normalized = value.toLowerCase();
+ if (normalized === 'urgent' || normalized === 'high') return 'HIGH';
+ if (normalized === 'normal' || normalized === 'medium') return 'MEDIUM';
+ if (normalized === 'low') return 'LOW';
+ return null;
+};
const firstText = (...values) => values.find((value) => typeof value === 'string' && value.trim())?.trim() || null;
@@ -494,15 +649,15 @@ function normalizeQueueItem(producer, raw, mapped) {
raw?.id == null ? null : String(raw.id),
typeof mapped.id === 'string' && mapped.id.startsWith(prefix) ? mapped.id.slice(prefix.length) : null,
);
- const priority = canonicalPriority(raw?.priority);
+ const priority = canonicalPriority(raw?.priority ?? mapped.priority);
const required = typeof mapped.required === 'boolean'
? mapped.required
: typeof raw?.required === 'boolean'
? raw.required
: !(raw?.recommendation === true || raw?.isRecommendation === true || raw?.optional === true);
- const dueAt = firstText(raw?.dueAt, raw?.due, raw?.deadline, raw?.scheduledFor);
- const revision = firstScalar(raw?.revision, raw?.version, raw?.updatedAt, raw?.updated_at, raw?.capturedAt, raw?.createdAt);
- const occurrence = firstScalar(raw?.occurrence, raw?.occurrenceId);
+ const dueAt = firstText(raw?.dueAt, raw?.due, raw?.deadline, raw?.scheduledFor, mapped.dueAt);
+ const revision = firstScalar(raw?.revision, raw?.version, raw?.updatedAt, raw?.updated_at, raw?.capturedAt, raw?.createdAt, mapped.revision);
+ const occurrence = firstScalar(raw?.occurrence, raw?.occurrenceId, mapped.occurrence);
const operations = semanticOperations(producer, mapped, raw);
const availableOperation = operations.find((entry) => entry.available)?.label;
@@ -538,7 +693,7 @@ function normalizeQueueItem(producer, raw, mapped) {
* are a lower bound, not evidence that the source is exhausted.
*/
async function gatherProducer(producer, ctx = {}) {
- const gathered = await producer.gather(REVIEW_QUEUE_SOURCE_PROBE_LIMIT);
+ const gathered = await producer.gather(REVIEW_QUEUE_SOURCE_PROBE_LIMIT, ctx);
const descriptor = Array.isArray(gathered) ? { items: gathered } : gathered;
const rawItems = Array.isArray(descriptor?.items) ? descriptor.items : [];
const truncated = descriptor?.truncated === true || rawItems.length > REVIEW_QUEUE_SOURCE_READ_LIMIT;
@@ -644,6 +799,23 @@ async function resolveCosApproval(id) {
return result;
}
+async function resolveThreadAction(id, status) {
+ const result = await brainStorage.updateWith('threads', id, (fresh) => {
+ const terminal = isTerminalThreadStatus(status);
+ return {
+ status,
+ // Keep Brain's closedAt contract when an Actions button changes only the
+ // local thread state. Refs and externalState are deliberately untouched.
+ closedAt: terminal
+ ? (isTerminalThreadStatus(fresh.status) && fresh.closedAt
+ ? fresh.closedAt
+ : new Date().toISOString())
+ : null,
+ };
+ });
+ return result;
+}
+
const SOURCE_ACTIONS = Object.freeze({
memory: Object.freeze({
approve: (id) => resolveMemoryAction(id, 'approve'),
@@ -652,6 +824,14 @@ const SOURCE_ACTIONS = Object.freeze({
cos: Object.freeze({
approve: resolveCosApproval,
}),
+ threads: Object.freeze({
+ complete: (id) => resolveThreadAction(id, 'done'),
+ reopen: (id) => resolveThreadAction(id, 'open'),
+ }),
+ todo: Object.freeze({
+ complete: (id) => reviewService.completeItem(id),
+ reopen: (id) => reviewService.reopenItem(id),
+ }),
});
export async function resolveQueueItem(queueItemId, operation = 'resolve') {
@@ -772,13 +952,21 @@ function sourceShownCounts(items) {
return shown;
}
-async function gatherFullQueue() {
+async function gatherFullQueue(query = {}) {
// Fetch active goals once (not per Ask row) so the goal picker on Ask rows
// has targets. A failure here degrades to no goal targets, not a sunk queue.
const goalOptions = await getActiveGoalOptions();
- const ctx = { goalOptions };
+ const view = typeof query.view === 'string' && query.view ? query.view : null;
+ const timezone = view === 'today'
+ ? await getUserTimezone().catch((err) => {
+ console.error(`⚠️ Review queue: timezone read failed: ${err.message}`);
+ return 'UTC';
+ })
+ : 'UTC';
+ const ctx = { goalOptions, view, timezone, now: new Date() };
+ const visibleProducers = PRODUCERS.filter((producer) => visibleInLiveViews(producer, view));
- const results = await Promise.all(PRODUCERS.map(async (producer) => {
+ const results = await Promise.all(visibleProducers.map(async (producer) => {
return gatherProducer(producer, ctx)
.then((result) => ({ source: producer.source, label: producer.label, ...result, error: null }))
.catch((err) => {
@@ -920,7 +1108,7 @@ export async function buildQueue({ limit, cursor, query = {} } = {}) {
return pageFromSnapshot(snapshot, payload.offset);
}
- const queue = await gatherFullQueue();
+ const queue = await gatherFullQueue(query);
if (requestedLimit === null) return queue;
const snapshot = saveQueueSnapshot(queue, queryKey, requestedLimit);
diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.js
index 302dac2d3b..3455e04ef2 100644
--- a/server/services/reviewQueue.test.js
+++ b/server/services/reviewQueue.test.js
@@ -3,12 +3,13 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Mock every producer service the aggregator pulls from, so the test exercises
// only the normalization / sort / bounded-read / snapshot / degrade-on-failure logic.
const brain = { getInboxLog: vi.fn(), markInboxDone: vi.fn() };
+const brainStorage = { getThreads: vi.fn(), getThreadById: vi.fn(), updateWith: vi.fn() };
const askConversations = { listConversations: vi.fn() };
const cosTaskStore = { getCosTasks: vi.fn(), approveTask: vi.fn() };
const messageDrafts = { listDrafts: vi.fn(), approveDraft: vi.fn() };
const proactiveAlerts = { generateAlerts: vi.fn() };
const backup = { getState: vi.fn() };
-const reviewService = { getItems: vi.fn(), dismissByReferenceId: vi.fn() };
+const reviewService = { getItems: vi.fn(), dismissByReferenceId: vi.fn(), completeItem: vi.fn(), reopenItem: vi.fn() };
const notifications = { getNotifications: vi.fn() };
// Mocked so the meta-field / buildQueue cases don't pull the brain/cos/identity
// stack in transitively (askPromote imports all three). The promoteAskQueueItem
@@ -19,8 +20,10 @@ const askPromote = { promoteLatestAssistantTurn: vi.fn() };
const identity = { getGoals: vi.fn() };
const stackerNews = { listPendingReviewActions: vi.fn() };
const x = { listPendingReviewActions: vi.fn() };
+const userTimezone = { getUserTimezone: vi.fn() };
vi.mock('./brain.js', () => brain);
+vi.mock('./brainStorage.js', () => brainStorage);
vi.mock('./askConversations.js', () => askConversations);
vi.mock('./cosTaskStore.js', () => cosTaskStore);
vi.mock('./messageDrafts.js', () => messageDrafts);
@@ -32,6 +35,7 @@ vi.mock('./identity.js', () => identity);
vi.mock('./askPromote.js', () => askPromote);
vi.mock('./stackerNews.js', () => stackerNews);
vi.mock('./x.js', () => x);
+vi.mock('./userTimezone.js', () => userTimezone);
const {
buildQueue,
@@ -45,6 +49,9 @@ const {
// Default: every producer returns "nothing needs attention".
function resetEmpty() {
brain.getInboxLog.mockResolvedValue([]);
+ brainStorage.getThreads.mockResolvedValue([]);
+ brainStorage.getThreadById.mockResolvedValue(null);
+ brainStorage.updateWith.mockResolvedValue(null);
askConversations.listConversations.mockResolvedValue([]);
cosTaskStore.getCosTasks.mockResolvedValue({ awaitingApproval: [] });
messageDrafts.listDrafts.mockResolvedValue([]);
@@ -52,10 +59,13 @@ function resetEmpty() {
backup.getState.mockResolvedValue({ status: 'ok', error: null });
reviewService.getItems.mockResolvedValue([]);
reviewService.dismissByReferenceId.mockResolvedValue(undefined);
+ reviewService.completeItem.mockResolvedValue({ id: 'todo-1', status: 'completed' });
+ reviewService.reopenItem.mockResolvedValue({ id: 'todo-1', status: 'pending' });
notifications.getNotifications.mockResolvedValue([]);
identity.getGoals.mockResolvedValue({ goals: [] });
stackerNews.listPendingReviewActions.mockResolvedValue([]);
x.listPendingReviewActions.mockResolvedValue([]);
+ userTimezone.getUserTimezone.mockResolvedValue('UTC');
}
describe('reviewQueue.buildQueue', () => {
@@ -107,6 +117,82 @@ describe('reviewQueue.buildQueue', () => {
});
});
+ it('projects active Brain commitments and manual todos into the all view', async () => {
+ brainStorage.getThreads.mockResolvedValue([
+ {
+ id: 'thread-1',
+ title: 'Ship the example follow-up',
+ status: 'open',
+ priority: 'high',
+ nextAction: 'Write the acceptance test',
+ externalState: 'open',
+ source: 'github',
+ updatedAt: '2026-09-20T10:00:00.000Z',
+ },
+ { id: 'thread-done', title: 'Finished loop', status: 'done' },
+ ]);
+ reviewService.getItems.mockResolvedValue([
+ { id: 'todo-1', type: 'todo', title: 'Call the example office', status: 'pending', createdAt: '2026-09-20T09:00:00.000Z' },
+ ]);
+
+ const queue = await buildQueue({ query: { view: 'all' } });
+
+ expect(queue.items.find((item) => item.id === 'threads:thread-1')).toMatchObject({
+ source: 'threads',
+ actionKind: 'brain.thread',
+ priority: 'HIGH',
+ summary: 'Write the acceptance test',
+ operations: [{ id: 'complete', label: 'Complete', available: true }],
+ meta: { localStatus: 'open', externalState: 'open', externalSource: 'github' },
+ });
+ expect(queue.items.find((item) => item.id === 'todo:todo-1')).toMatchObject({
+ source: 'todo',
+ actionKind: 'review.todo',
+ operations: [{ id: 'complete', label: 'Complete', available: true }],
+ });
+ expect(queue.items.some((item) => item.id === 'threads:thread-done')).toBe(false);
+ });
+
+ it('keeps waiting and someday commitments out of Today unless their follow-up is due', async () => {
+ userTimezone.getUserTimezone.mockResolvedValue('America/Los_Angeles');
+ brainStorage.getThreads.mockResolvedValue([
+ { id: 'waiting-future', title: 'Waiting future', status: 'waiting', dueAt: '2026-09-22T12:00:00.000Z' },
+ { id: 'waiting-due', title: 'Waiting due', status: 'waiting', dueAt: '2026-09-20T12:00:00.000Z' },
+ { id: 'someday-undated', title: 'Someday undated', status: 'someday' },
+ { id: 'open-undated', title: 'Open undated', status: 'open' },
+ ]);
+
+ vi.useFakeTimers({ now: new Date('2026-09-20T20:00:00.000Z') });
+ const today = await buildQueue({ query: { view: 'today' } });
+ expect(today.items.map((item) => item.id)).toEqual([
+ 'threads:waiting-due',
+ 'threads:open-undated',
+ ]);
+
+ const waiting = await buildQueue({ query: { view: 'waiting' } });
+ expect(waiting.items.map((item) => item.id)).toEqual(['threads:waiting-due', 'threads:waiting-future']);
+ });
+
+ it('keeps terminal Brain commitments and completed manual todos in History', async () => {
+ brainStorage.getThreads.mockResolvedValue([
+ { id: 'thread-done', title: 'Finished loop', status: 'done', updatedAt: '2026-09-20T10:00:00.000Z' },
+ { id: 'thread-open', title: 'Open loop', status: 'open' },
+ ]);
+ reviewService.getItems.mockResolvedValue([
+ { id: 'todo-done', type: 'todo', title: 'Completed personal item', status: 'completed', updatedAt: '2026-09-20T09:00:00.000Z' },
+ { id: 'alert-done', type: 'alert', title: 'Past alert', status: 'dismissed', updatedAt: '2026-09-20T08:00:00.000Z' },
+ ]);
+
+ const history = await buildQueue({ query: { view: 'history' } });
+ expect(history.items.map((item) => item.id).sort()).toEqual([
+ 'history:alert-done',
+ 'threads:thread-done',
+ 'todo:todo-done',
+ ]);
+ expect(history.items.find((item) => item.id === 'todo:todo-done').operations)
+ .toEqual([{ id: 'reopen', label: 'Reopen', available: true }]);
+ });
+
it('surfaces pending Stacker News approvals with an account-specific drill-down', async () => {
stackerNews.listPendingReviewActions.mockResolvedValue([{ id: 's1', accountId: 'a1', accountLabel: 'Example account', kind: 'publish_comment', payload: { body: 'Thoughtful reply' }, createdAt: '2026-06-03T10:00:00.000Z' }]);
const queue = await buildQueue();
@@ -592,6 +678,33 @@ describe('reviewQueue.resolveQueueItem', () => {
expect(messageDrafts.approveDraft).toHaveBeenCalledWith('d1');
});
+ it('completes and reopens Brain commitments through the locked Brain store', async () => {
+ brainStorage.updateWith.mockImplementation(async (type, id, mutate) => {
+ expect(type).toBe('threads');
+ expect(id).toBe('thread-1');
+ return { id, ...(await mutate({ id, status: 'open', externalState: 'open' })) };
+ });
+
+ await expect(resolveQueueItem('threads:thread-1', 'complete')).resolves.toMatchObject({
+ source: 'threads', operation: 'complete', resolved: true,
+ });
+ await expect(resolveQueueItem('threads:thread-1', 'reopen')).resolves.toMatchObject({
+ source: 'threads', operation: 'reopen', resolved: true,
+ });
+ expect(brainStorage.updateWith).toHaveBeenCalledTimes(2);
+ });
+
+ it('completes and reopens manual todo rows without using generic Review completion', async () => {
+ await expect(resolveQueueItem('todo:todo-1', 'complete')).resolves.toMatchObject({
+ source: 'todo', operation: 'complete', resolved: true,
+ });
+ await expect(resolveQueueItem('todo:todo-1', 'reopen')).resolves.toMatchObject({
+ source: 'todo', operation: 'reopen', resolved: true,
+ });
+ expect(reviewService.completeItem).toHaveBeenCalledWith('todo-1');
+ expect(reviewService.reopenItem).toHaveBeenCalledWith('todo-1');
+ });
+
it('dispatches explicit source operations through the owning service', async () => {
cosTaskStore.approveTask.mockResolvedValue({ id: 'sys-1', approvalRequired: false });
const result = await resolveQueueItem('cos:sys-1', 'approve');
diff --git a/server/services/socket.js b/server/services/socket.js
index 678aa94b56..9131b77b47 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -472,6 +472,12 @@ function setupBrainEventForwarding() {
ioInstance.emit('brain:classified', data);
}
});
+ brainEvents.on('threads:upserted', (data) => {
+ if (ioInstance) ioInstance.emit('brain:threads:changed', data);
+ });
+ brainEvents.on('threads:deleted', (data) => {
+ if (ioInstance) ioInstance.emit('brain:threads:changed', data);
+ });
}
// Set up Moltworld WebSocket event forwarding to agent subscribers