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([issue-709]): cross-domain Needs Attention queue on the Review Hub
[._.]/ Adam Eivyb4b80e65a34c
diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsxindex 697dfcb84c..911454402d 100644--- a/client/src/pages/Review.jsx+++ b/client/src/pages/Review.jsx@@ -1,4 +1,5 @@import { useState, useEffect, useCallback } from 'react';+import { useNavigate } from 'react-router-dom';import {ClipboardList,AlertTriangle,@@ -15,13 +16,37 @@ import {Minimize2,Eye,Clock3,- BellRing+ BellRing,+ Inbox,+ ArrowRight,+ Brain as BrainIcon,+ MessageCircle,+ Mail,+ Activity,+ DatabaseBackup} from 'lucide-react';import BrailleSpinner from '../components/BrailleSpinner';import MarkdownOutput from '../components/cos/MarkdownOutput';+import { timeAgo } from '../utils/formatters';import * as api from '../services/api';import socket from '../services/socket';+// Cross-domain queue source → icon + accent (M42 P5 inbox-zero aggregator).+const QUEUE_SOURCE_CONFIG = {+ brain: { icon: BrainIcon, color: 'text-purple-400' },+ ask: { icon: MessageCircle, color: 'text-port-accent' },+ cos: { icon: Crown, color: 'text-port-accent' },+ drafts: { icon: Mail, color: 'text-blue-400' },+ health: { icon: Activity, color: 'text-port-warning' },+ backup: { icon: DatabaseBackup, color: 'text-port-error' }+};++const QUEUE_SEVERITY_STYLE = {+ critical: 'border-port-error/40',+ high: 'border-port-warning/40',+ normal: 'border-port-border'+};+const TYPE_CONFIG = {alert: { label: 'Alerts', icon: AlertTriangle, color: 'text-port-warning' },cos: { label: 'CoS Actions', icon: Crown, color: 'text-port-accent' },@@ -40,6 +65,7 @@ function isActionableItem(item) {}export default function Review() {+ const navigate = useNavigate();const [items, setItems] = useState([]);const [briefing, setBriefing] = useState(null);const [loading, setLoading] = useState(true);@@ -48,6 +74,12 @@ export default function Review() {const [filter, setFilter] = useState('pending');const [briefingFullscreen, setBriefingFullscreen] = useState(false);+ // Cross-domain live queue (M42 P5). These rows are derived live from each+ // producer, not stored, so "dismiss" is a per-session client-side hide rather+ // than a server mutation — accept/promote actions are a follow-up.+ const [queue, setQueue] = useState(null);+ const [dismissedQueueIds, setDismissedQueueIds] = useState(() => new Set());+const fetchItems = useCallback(async () => {const params = filter === 'all' ? {} : { status: filter };const data = await api.getReviewItems(params).catch(() => []);@@ -60,10 +92,17 @@ export default function Review() {setBriefing(data);}, []);+ 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);+ setQueue(data);+ }, []);+useEffect(() => {fetchItems();fetchBriefing();- }, [fetchItems, fetchBriefing]);+ fetchQueue();+ }, [fetchItems, fetchBriefing, fetchQueue]);useEffect(() => {const handleCreated = (item) => {@@ -117,6 +156,19 @@ export default function Review() {const handleMarkAllRead = () => api.bulkUpdateReviewStatus({ status: 'dismissed' }).catch(() => null);const handleCompleteAll = () => api.bulkUpdateReviewStatus({ status: 'completed' }).catch(() => null);+ const handleQueueDismiss = (id) => {+ setDismissedQueueIds(prev => {+ const next = new Set(prev);+ next.add(id);+ return next;+ });+ };++ const handleQueueDrill = (item) => {+ handleQueueDismiss(item.id);+ if (item.drillTo) navigate(item.drillTo);+ };+const grouped = items.reduce((acc, item) => {if (!acc[item.type]) acc[item.type] = [];acc[item.type].push(item);@@ -131,6 +183,9 @@ export default function Review() {);}+ const queueItems = (queue?.items || []).filter(i => !dismissedQueueIds.has(i.id));+ const queueSourceErrors = Object.entries(queue?.sources || {}).filter(([, s]) => s.error);+const pendingItems = items.filter(i => i.status === 'pending');const pendingCount = pendingItems.length;const pendingAlerts = pendingItems.filter(i => i.type === 'alert');@@ -197,6 +252,32 @@ export default function Review() {<SummaryPill icon={ClipboardList} label="Todos" value={pendingTodos.length} tone="text-port-success" /></section>+ {/* Cross-domain "Needs Attention" queue (M42 P5) — live-pulled from+ Brain, Ask, CoS, Messages, Health, and Backups. */}+ {queueItems.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">+ <Inbox size={16} className="text-port-accent" />+ Needs Attention+ </h3>+ <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+ </span>+ </div>+ <div className="space-y-2">+ {queueItems.map(item => (+ <QueueRow key={item.id} item={item} onDrill={handleQueueDrill} onDismiss={handleQueueDismiss} />+ ))}+ </div>+ {queueSourceErrors.length > 0 && (+ <p className="text-xs text-gray-600">+ Couldn't load: {queueSourceErrors.map(([, s]) => s.label).join(', ')}.+ </p>+ )}+ </section>+ )}+{/* Quick Add */}<form onSubmit={handleCreateTodo} className="flex gap-2"><input@@ -327,6 +408,53 @@ export default function Review() {);}+function QueueRow({ item, onDrill, onDismiss }) {+ 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;++ return (+ <div className={`flex items-start gap-3 p-3 rounded-lg border bg-port-card ${borderTone}`}>+ <div className={`mt-0.5 shrink-0 ${config.color}`}>+ <Icon size={18} />+ </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>+ <span className={`text-[10px] uppercase tracking-wide px-2 py-0.5 rounded-full border border-current/20 ${config.color}`}>+ {item.sourceLabel}+ </span>+ </div>+ {item.summary && (+ <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{item.summary}</p>+ )}+ {item.timestamp && (+ <p className="text-xs text-gray-600 mt-1 flex items-center gap-1">+ <Clock3 size={12} />+ {timeAgo(item.timestamp)}+ </p>+ )}+ </div>+ <div className="flex items-center gap-1 shrink-0">+ <button+ onClick={() => onDrill(item)}+ className="p-1.5 text-gray-500 hover:text-port-accent transition-colors"+ title="Open"+ >+ <ArrowRight size={16} />+ </button>+ <button+ onClick={() => onDismiss(item.id)}+ className="p-1.5 text-gray-500 hover:text-port-warning transition-colors"+ title="Dismiss from queue (this session)"+ >+ <X size={16} />+ </button>+ </div>+ </div>+ );+}+function SummaryPill({ icon: Icon, label, value, tone = 'text-white', urgent = false }) {return (<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'}`}>diff --git a/client/src/services/apiReview.js b/client/src/services/apiReview.jsindex 77671e75f3..5f782b99b8 100644--- a/client/src/services/apiReview.js+++ b/client/src/services/apiReview.js@@ -10,6 +10,8 @@ export const getReviewItems = (params) => {};export const getReviewCounts = () => request('/review/counts');export const getReviewBriefing = () => request('/review/briefing');+// Cross-domain live queue (brain inbox, ask, CoS approvals, drafts, health, backups)+export const getReviewQueue = (options = {}) => request('/review/queue', options);export const createReviewTodo = (data) => request('/review/todo', {method: 'POST',body: JSON.stringify(data)diff --git a/server/routes/review.js b/server/routes/review.jsindex c70f4cbf28..8ce860ba8b 100644--- a/server/routes/review.js+++ b/server/routes/review.js@@ -3,6 +3,7 @@ import { z } from 'zod';import { asyncHandler } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as reviewService from '../services/review.js';+import { buildQueue } from '../services/reviewQueue.js';const router = express.Router();@@ -40,6 +41,13 @@ router.get('/briefing', asyncHandler(async (req, res) => {res.json(briefing);}));+// GET /api/review/queue — cross-domain live aggregator of items needing+// attention (brain inbox, ask answers, CoS approvals, drafts, health, backups)+router.get('/queue', asyncHandler(async (req, res) => {+ const queue = await buildQueue();+ res.json(queue);+}));+// POST /api/review/todo — create a user todorouter.post('/todo', asyncHandler(async (req, res) => {const data = validateRequest(createTodoSchema, req.body);diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.jsnew file mode 100644index 0000000000..030a612899--- /dev/null+++ b/server/services/reviewQueue.js@@ -0,0 +1,220 @@+/**+ * Cross-domain Review Queue (M42 P5) — the "inbox zero" aggregator.+ *+ * Where review.js manages *stored* review items (todos/alerts/briefing/cos that+ * producers push in via cosEvents), this module *live-pulls* the things across+ * PortOS that are currently waiting on the user and normalizes them into one+ * list. It reads each producer's existing service on demand — nothing is+ * persisted here — so the queue always reflects live state.+ *+ * Each producer is gathered independently and defensively: a single producer+ * throwing (or its data file being absent) degrades that one source to empty+ * rather than sinking the whole queue. Every row is normalized to:+ *+ * { id, source, sourceLabel, title, summary, timestamp, severity, drillTo }+ *+ * `drillTo` is a client route the UI deep-links to so "drill-down" works without+ * the queue needing to know how to render each domain. v1 is read + drill-down;+ * per-source accept/promote actions are a follow-up (see issue #709).+ */++import * as brain from './brain.js';+import * as askConversations from './askConversations.js';+import * as cosTaskStore from './cosTaskStore.js';+import * as messageDrafts from './messageDrafts.js';+import * as proactiveAlerts from './proactiveAlerts.js';+import * as backup from './backup.js';++// Per-source cap so one noisy producer can't flood the queue; the UI shows a+// "+N more in <domain>" affordance via the per-source `total` vs `items.length`.+const PER_SOURCE_LIMIT = 25;++/**+ * 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+ * filtered to "needs attention"); `map` normalizes a single raw item.+ */+const PRODUCERS = [+ {+ source: 'brain',+ label: 'Brain inbox',+ drillTo: '/brain/inbox',+ async gather() {+ // Inbox entries the auto-classifier couldn't place — they need a human+ // to pick a destination.+ return brain.getInboxLog({ status: 'needs_review', limit: PER_SOURCE_LIMIT * 2 });+ },+ map(entry) {+ const text = (entry.capturedText || '').trim();+ return {+ id: `brain:${entry.id}`,+ title: 'Inbox item needs classification',+ summary: text.slice(0, 200),+ timestamp: entry.capturedAt || entry.createdAt || null,+ severity: 'normal',+ drillTo: '/brain/inbox'+ };+ }+ },+ {+ source: 'ask',+ label: 'Ask answers',+ drillTo: '/ask',+ async gather() {+ // Conversations with content that haven't been promoted to brain/task/goal.+ const convs = await askConversations.listConversations({ limit: PER_SOURCE_LIMIT * 2 });+ return convs.filter(c => !c.promoted && (c.turnCount || 0) > 0);+ },+ map(conv) {+ return {+ id: `ask:${conv.id}`,+ title: 'Ask answer ready to promote',+ summary: conv.title || '(untitled conversation)',+ timestamp: conv.updatedAt || conv.createdAt || null,+ severity: 'normal',+ drillTo: `/ask/${conv.id}`+ };+ }+ },+ {+ source: 'cos',+ label: 'CoS approvals',+ drillTo: '/cos/tasks',+ async gather() {+ // Internal CoS tasks parked awaiting the user's approval before they run.+ const { awaitingApproval = [] } = await cosTaskStore.getCosTasks();+ return awaitingApproval;+ },+ map(task) {+ return {+ id: `cos:${task.id}`,+ title: 'CoS task pending approval',+ summary: (task.description || '').slice(0, 200),+ timestamp: task.createdAt || null,+ severity: task.priority === 'HIGH' ? 'high' : 'normal',+ drillTo: '/cos/tasks'+ };+ }+ },+ {+ source: 'drafts',+ label: 'Message drafts',+ drillTo: '/messages/drafts',+ async gather() {+ // Drafts the user (or an AI) prepared that haven't been sent yet —+ // both freeform drafts and ones explicitly awaiting review.+ const drafts = await messageDrafts.listDrafts();+ return drafts.filter(d => d.status === 'draft' || d.status === 'pending_review');+ },+ map(draft) {+ return {+ id: `draft:${draft.id}`,+ title: draft.status === 'pending_review' ? 'Draft awaiting review' : 'Unsent message draft',+ summary: draft.subject || (draft.body || '').slice(0, 120) || '(no subject)',+ timestamp: draft.updatedAt || draft.createdAt || null,+ severity: 'normal',+ drillTo: '/messages/drafts'+ };+ }+ },+ {+ source: 'health',+ label: 'Health anomalies',+ drillTo: '/system-health',+ async gather() {+ // System/health alerts; only surface the ones worth interrupting for.+ const { alerts = [] } = await proactiveAlerts.generateAlerts();+ return alerts.filter(a => a.severity === 'critical' || a.severity === 'high');+ },+ map(alert) {+ return {+ id: `health:${alert.id || alert.type}`,+ title: alert.title || `${alert.type || 'System'} alert`,+ summary: (alert.message || '').slice(0, 200),+ timestamp: alert.timestamp || null,+ severity: alert.severity === 'critical' ? 'critical' : 'high',+ drillTo: alert.actionUrl || '/system-health'+ };+ }+ },+ {+ source: 'backup',+ label: 'Failed backups',+ drillTo: '/settings/backup',+ async gather() {+ // A backup that failed or errored on its last run needs acknowledgement.+ const state = await backup.getState();+ const failed = state && (state.status === 'failed' || state.lastError);+ return failed ? [state] : [];+ },+ map(state) {+ return {+ id: 'backup:last-run',+ title: 'Backup failed',+ summary: (state.lastError || 'The most recent backup did not complete.').slice(0, 200),+ timestamp: state.lastRun || null,+ severity: 'high',+ drillTo: '/settings/backup'+ };+ }+ }+];++const SEVERITY_ORDER = { critical: 0, high: 1, normal: 2 };++/**+ * Gather one producer into normalized, capped rows. Never throws — a failing+ * producer degrades to `{ items: [], total: 0, error }` so the aggregate still+ * returns the healthy sources.+ */+async function gatherProducer(producer) {+ const raw = await producer.gather();+ const list = Array.isArray(raw) ? raw : [];+ const items = list.slice(0, PER_SOURCE_LIMIT).map(item => ({+ source: producer.source,+ sourceLabel: producer.label,+ ...producer.map(item)+ }));+ return { items, total: list.length };+}++/**+ * Build the cross-domain review queue. Returns the normalized item list (sorted+ * by severity then recency), aggregate `counts`, and a `sources` map with+ * per-source `total` (pre-cap) + `error` so the UI can show "+N more" and flag+ * a source that failed to load.+ */+export async function buildQueue() {+ const results = await Promise.all(PRODUCERS.map(async (producer) => {+ return gatherProducer(producer)+ .then(r => ({ source: producer.source, label: producer.label, ...r, error: null }))+ .catch(err => {+ console.error(`❌ Review queue: ${producer.source} source failed: ${err.message}`);+ return { source: producer.source, label: producer.label, items: [], total: 0, error: err.message };+ });+ }));++ const items = results.flatMap(r => r.items);++ items.sort((a, b) => {+ const sev = (SEVERITY_ORDER[a.severity] ?? 2) - (SEVERITY_ORDER[b.severity] ?? 2);+ if (sev !== 0) return sev;+ return new Date(b.timestamp || 0) - new Date(a.timestamp || 0);+ });++ const sources = {};+ for (const r of results) {+ sources[r.source] = { label: r.label, total: r.total, shown: r.items.length, error: r.error };+ }++ return {+ items,+ counts: {+ total: items.length,+ critical: items.filter(i => i.severity === 'critical').length,+ high: items.filter(i => i.severity === 'high').length+ },+ sources,+ generatedAt: new Date().toISOString()+ };+}diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.jsnew file mode 100644index 0000000000..964aefab34--- /dev/null+++ b/server/services/reviewQueue.test.js@@ -0,0 +1,124 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock every producer service the aggregator pulls from, so the test exercises+// only the normalization / sort / cap / degrade-on-failure logic.+const brain = { getInboxLog: vi.fn() };+const askConversations = { listConversations: vi.fn() };+const cosTaskStore = { getCosTasks: vi.fn() };+const messageDrafts = { listDrafts: vi.fn() };+const proactiveAlerts = { generateAlerts: vi.fn() };+const backup = { getState: vi.fn() };++vi.mock('./brain.js', () => brain);+vi.mock('./askConversations.js', () => askConversations);+vi.mock('./cosTaskStore.js', () => cosTaskStore);+vi.mock('./messageDrafts.js', () => messageDrafts);+vi.mock('./proactiveAlerts.js', () => proactiveAlerts);+vi.mock('./backup.js', () => backup);++const { buildQueue } = await import('./reviewQueue.js');++// Default: every producer returns "nothing needs attention".+function resetEmpty() {+ brain.getInboxLog.mockResolvedValue([]);+ askConversations.listConversations.mockResolvedValue([]);+ cosTaskStore.getCosTasks.mockResolvedValue({ awaitingApproval: [] });+ messageDrafts.listDrafts.mockResolvedValue([]);+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [] });+ backup.getState.mockResolvedValue({ status: 'success', lastError: null });+}++describe('reviewQueue.buildQueue', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetEmpty();+ });++ it('returns an empty queue when nothing needs attention', async () => {+ const queue = await buildQueue();+ expect(queue.items).toEqual([]);+ expect(queue.counts.total).toBe(0);+ expect(queue.sources.brain.total).toBe(0);+ });++ it('normalizes each producer into the common row shape', async () => {+ brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'classify me', capturedAt: '2026-06-03T10:00:00.000Z' }]);+ const queue = await buildQueue();+ const row = queue.items.find(i => i.source === 'brain');+ expect(row).toMatchObject({+ id: 'brain:b1',+ source: 'brain',+ sourceLabel: 'Brain inbox',+ title: 'Inbox item needs classification',+ summary: 'classify me',+ drillTo: '/brain/inbox'+ });+ });++ it('only surfaces unpromoted ask conversations with content', async () => {+ askConversations.listConversations.mockResolvedValue([+ { id: 'a1', title: 'has content', promoted: false, turnCount: 2, updatedAt: '2026-06-03T10:00:00.000Z' },+ { id: 'a2', title: 'already promoted', promoted: true, turnCount: 3 },+ { id: 'a3', title: 'no turns', promoted: false, turnCount: 0 }+ ]);+ const queue = await buildQueue();+ const askRows = queue.items.filter(i => i.source === 'ask');+ expect(askRows).toHaveLength(1);+ expect(askRows[0].id).toBe('ask:a1');+ expect(askRows[0].drillTo).toBe('/ask/a1');+ });++ it('surfaces drafts and CoS approvals from their producers', async () => {+ cosTaskStore.getCosTasks.mockResolvedValue({ awaitingApproval: [{ id: 'sys-1', description: 'approve me', priority: 'HIGH', createdAt: '2026-06-03T09:00:00.000Z' }] });+ messageDrafts.listDrafts.mockResolvedValue([+ { id: 'd1', status: 'draft', subject: 'unsent', updatedAt: '2026-06-03T08:00:00.000Z' },+ { id: 'd2', status: 'sent', subject: 'gone' }+ ]);+ const queue = await buildQueue();+ expect(queue.items.find(i => i.id === 'cos:sys-1')).toMatchObject({ severity: 'high', drillTo: '/cos/tasks' });+ const draftRows = queue.items.filter(i => i.source === 'drafts');+ expect(draftRows).toHaveLength(1);+ expect(draftRows[0].id).toBe('draft:d1');+ });++ it('only surfaces critical/high health alerts and a failed backup', async () => {+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [+ { id: 'al1', type: 'memory', severity: 'critical', message: 'OOM' },+ { id: 'al2', type: 'cpu', severity: 'low', message: 'meh' }+ ] });+ backup.getState.mockResolvedValue({ status: 'failed', lastError: 'disk full', lastRun: '2026-06-03T07:00:00.000Z' });+ const queue = await buildQueue();+ const healthRows = queue.items.filter(i => i.source === 'health');+ expect(healthRows).toHaveLength(1);+ expect(healthRows[0]).toMatchObject({ severity: 'critical' });+ expect(queue.items.find(i => i.source === 'backup')).toMatchObject({ title: 'Backup failed', summary: 'disk full' });+ });++ it('sorts by severity then recency', async () => {+ brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'normal', capturedAt: '2026-06-03T12:00:00.000Z' }]);+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ id: 'al1', type: 'disk', severity: 'critical', message: 'crit', timestamp: '2026-06-03T01:00:00.000Z' }] });+ const queue = await buildQueue();+ // critical alert sorts ahead of the (newer) normal brain item+ expect(queue.items[0].severity).toBe('critical');+ expect(queue.counts.critical).toBe(1);+ });++ it('degrades a failing producer to empty without sinking the queue', async () => {+ brain.getInboxLog.mockRejectedValue(new Error('inbox boom'));+ messageDrafts.listDrafts.mockResolvedValue([{ id: 'd1', status: 'draft', subject: 'still here' }]);+ const queue = await buildQueue();+ expect(queue.sources.brain.error).toBe('inbox boom');+ expect(queue.items.find(i => i.source === 'drafts')).toBeTruthy();+ });++ it('caps each source and reports the pre-cap total', async () => {+ brain.getInboxLog.mockResolvedValue(+ Array.from({ length: 40 }, (_, i) => ({ id: `b${i}`, capturedText: `t${i}`, capturedAt: '2026-06-03T10:00:00.000Z' }))+ );+ const queue = await buildQueue();+ const brainRows = queue.items.filter(i => i.source === 'brain');+ expect(brainRows).toHaveLength(25);+ expect(queue.sources.brain.total).toBe(40);+ expect(queue.sources.brain.shown).toBe(25);+ });+});