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: unify action previews and deduplicate reminder delivery
[._.]/ Adam Eivy6b3ec0dda026
diff --git a/client/src/components/ActionQueuePreview.jsx b/client/src/components/ActionQueuePreview.jsxnew file mode 100644index 0000000000..f63c1244e9--- /dev/null+++ b/client/src/components/ActionQueuePreview.jsx@@ -0,0 +1,46 @@+import { useId } from 'react';+import { Link } from 'react-router';+import { useActionQueue } from '../hooks/useActionQueue';+import { formatCount } from '../utils/formatters';++export const actionSelectionLink = (id) => `/review/${encodeURIComponent(id)}?view=today`;++/** The same canonical rows and failure contract in every compact surface. */+export default function ActionQueuePreview({ title = 'Actions', sources, queue, onSelect, compact = false }) {+ const live = useActionQueue();+ const { data, loading, error } = queue || live;+ const heading = useId();+ const items = (data?.items || []).filter((item) => !sources || sources.includes(item.source));+ const required = items.filter((item) => item.required === true);+ const optional = items.filter((item) => item.isRecommendation === true);+ const lowerBound = data?.partial || Boolean(error);+ const groups = [{ label: 'Required', items: required }, { label: 'Optional recommendations', items: optional }];+ return (+ <section className={compact ? '@container p-4' : '@container bg-port-card border border-port-border rounded-xl p-4'} aria-labelledby={heading}>+ <div className="flex flex-wrap items-center justify-between gap-2 mb-3">+ <h3 id={heading} className="text-sm font-semibold text-port-text">{title}</h3>+ {data && <span className="text-xs text-port-warning">{lowerBound ? 'At least ' : ''}{formatCount(required.length)} required</span>}+ </div>+ {loading && !data && <p role="status" className="text-sm text-port-text-muted">Loading actions…</p>}+ {error && <p role="alert" className="text-sm text-port-warning">{data ? 'Actions could not refresh. Showing the last known actions.' : 'Actions unavailable.'} <button type="button" onClick={live.refetch} className="underline min-h-[44px]">Retry</button></p>}+ {data?.partial && <p role="status" className="text-xs text-port-warning mb-2">Some sources are unavailable or truncated. Counts are lower bounds.</p>}+ {data && !error && !data.partial && items.length === 0 && <p className="text-sm text-port-text-muted">All caught up!</p>}+ {groups.map((group) => group.items.length > 0 && (+ <div key={group.label} className="mb-3">+ <h4 className="text-xs text-port-text-muted mb-1">{group.label}</h4>+ <ul aria-label={group.label} className="space-y-1">+ {group.items.slice(0, 5).map((item) => (+ <li key={item.id} data-action-id={item.id}>+ <Link to={actionSelectionLink(item.id)} onClick={onSelect} className="block min-h-[44px] p-2 rounded hover:bg-port-border/50 focus:outline-hidden focus:ring-2 focus:ring-port-accent">+ <span className="block text-sm text-port-text break-words">{item.title}</span>+ <span className="block text-xs text-port-text-muted line-clamp-2">{item.reason || item.summary}</span>+ </Link>+ </li>+ ))}+ </ul>+ </div>+ ))}+ <Link to="/review?view=today" onClick={onSelect} className="inline-flex items-center min-h-[44px] text-sm text-port-accent">Open Actions</Link>+ </section>+ );+}diff --git a/client/src/components/ActionQueuePreview.test.jsx b/client/src/components/ActionQueuePreview.test.jsxnew file mode 100644index 0000000000..7edf6c2443--- /dev/null+++ b/client/src/components/ActionQueuePreview.test.jsx@@ -0,0 +1,89 @@+import { useState } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import NotificationDropdown from './NotificationDropdown';+import ReviewHubCard from './ReviewHubCard';+import DailyActionsWidget from './DailyActionsWidget';+import ProactiveAlertsWidget from './ProactiveAlertsWidget';+import { __resetActionQueue } from '../hooks/useActionQueue';+import { ACTION_QUEUE_CHANGED } from '../constants/events';++const mock = vi.hoisted(() => ({ getReviewQueue: vi.fn(), on: vi.fn(), off: vi.fn() }));+vi.mock('../services/api', () => ({ getReviewQueue: mock.getReviewQueue }));+vi.mock('../services/socket', () => ({ default: { on: mock.on, off: mock.off } }));++const required = { id: 'health:disk', source: 'health', required: true, title: 'Disk needs attention', reason: 'Free space is low' };+const optional = { id: 'product:daily-post', source: 'product', required: false, isRecommendation: true, title: 'Daily POST', reason: 'Practice today' };+const envelope = (items = [required, optional], partial = false) => ({ items, partial, sources: {} });++function Surfaces() {+ const [history, setHistory] = useState([{ id: 'event-1', title: 'An event', read: false, timestamp: '2026-01-01' }]);+ return <>+ <NotificationDropdown notifications={history} unreadCount={history.filter(n => !n.read).length}+ onMarkAllAsRead={() => setHistory(history.map(n => ({ ...n, read: true })))}+ onClearAll={() => setHistory([])} onRemove={() => setHistory([])} onMarkAsRead={() => {}} />+ <ReviewHubCard /><DailyActionsWidget /><ProactiveAlertsWidget />+ </>;+}+const show = () => render(<MemoryRouter><Surfaces /></MemoryRouter>);++beforeEach(() => {+ vi.clearAllMocks();+ __resetActionQueue();+ mock.getReviewQueue.mockResolvedValue(envelope());+});+afterEach(cleanup);++describe('canonical action previews', () => {+ it('shares IDs and required counts across the bell and saved widgets; history controls cannot complete actions', async () => {+ show();+ const bell = await screen.findByRole('button', { name: 'Notifications (1 required actions)' });+ fireEvent.click(bell);+ const panel = screen.getByRole('region', { name: 'Notifications' });+ expect(mock.getReviewQueue).toHaveBeenCalledTimes(1);+ for (const link of screen.getAllByRole('link', { name: /Disk needs attention/ })) {+ expect(link).toHaveAttribute('href', '/review/health%3Adisk?view=today');+ expect(link.closest('li')).toHaveAttribute('data-action-id', 'health:disk');+ }+ expect(screen.getAllByRole('link', { name: /Disk needs attention/ })).toHaveLength(3);+ expect(screen.getAllByRole('link', { name: /Daily POST/ })).toHaveLength(4);+ fireEvent.click(within(panel).getByRole('button', { name: 'Mark all notifications as read' }));+ expect(bell).toHaveAccessibleName('Notifications (1 required actions)');+ fireEvent.click(within(panel).getByRole('button', { name: 'Clear all notifications' }));+ expect(within(panel).getByText('No notifications')).toBeInTheDocument();+ expect(within(panel).getByRole('link', { name: /Disk needs attention/ })).toBeInTheDocument();++ mock.getReviewQueue.mockResolvedValue(envelope([optional]));+ act(() => mock.on.mock.calls.find(([event]) => event === 'brain:threads:changed')[1]());+ await waitFor(() => expect(screen.queryByText('Disk needs attention')).not.toBeInTheDocument());+ expect(bell).toHaveAccessibleName('Notifications (0 required actions)');+ expect(screen.getAllByText('Optional recommendations')).toHaveLength(4);+ });++ it('reports loading, failure, and lower bounds without flashing a healthy empty state', async () => {+ let finish;+ mock.getReviewQueue.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ show();+ expect(screen.queryByText('All caught up!')).not.toBeInTheDocument();+ await act(async () => finish(envelope([required], true)));+ expect(screen.getByRole('button', { name: /at least 1 required actions/ })).toBeInTheDocument();+ expect(screen.getAllByText(/Counts are lower bounds/)).toHaveLength(3);+ mock.getReviewQueue.mockRejectedValue(new Error('offline'));+ act(() => window.dispatchEvent(new Event(ACTION_QUEUE_CHANGED)));+ await waitFor(() => expect(screen.getAllByRole('alert')).toHaveLength(3));+ expect(screen.getAllByText('Disk needs attention')).toHaveLength(2);+ expect(screen.queryByText('All caught up!')).not.toBeInTheDocument();+ });++ it('drops an older response when completion invalidates a pending read', async () => {+ let finish;+ mock.getReviewQueue.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ show();+ mock.getReviewQueue.mockResolvedValue(envelope([]));+ act(() => mock.on.mock.calls.find(([event]) => event === 'review:queue:changed')[1]());+ await act(async () => finish(envelope()));+ await waitFor(() => expect(screen.getAllByText('All caught up!')).toHaveLength(3));+ expect(screen.queryByText('Disk needs attention')).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/DailyActionsWidget.jsx b/client/src/components/DailyActionsWidget.jsxindex c0e72a352a..b77eaa3657 100644--- a/client/src/components/DailyActionsWidget.jsx+++ b/client/src/components/DailyActionsWidget.jsx@@ -1,64 +1,6 @@-import { memo } from 'react';-import { Link } from 'react-router';-import { ArrowRight, Brain, Sparkles } from 'lucide-react';+import ActionQueuePreview from './ActionQueuePreview';-const ACTION_ICONS = {- post_engagement: Brain,- commission_feedback: Sparkles,-};--const ACTION_TONES = {- high: 'border-port-warning/50 bg-port-warning/10',- medium: 'border-port-accent/40 bg-port-accent/10',-};--/**- * Landing-card projection of the same deterministic actions used by the- * proactive-alert and reminder-toast surfaces. It reads dashboardState rather- * than fetching inside a widget, so the dashboard has one refresh boundary.- */-const DailyActionsWidget = memo(function DailyActionsWidget({ dashboardState }) {- const actions = dashboardState?.dailyActions?.actions || [];- if (actions.length === 0) return null;-- return (- <section className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6" aria-labelledby="daily-actions-heading">- <div className="flex items-center justify-between gap-3 mb-3">- <div className="flex items-center gap-3 min-w-0">- <div className="shrink-0 p-2 rounded-lg bg-port-warning/10">- <ArrowRight className="w-5 h-5 text-port-warning" />- </div>- <div className="min-w-0">- <h3 id="daily-actions-heading" className="text-lg font-semibold text-port-text">Today's actions</h3>- <p className="text-sm text-port-text-muted truncate">Small actions that keep your feedback loops moving</p>- </div>- </div>- <span className="shrink-0 text-xs text-port-warning bg-port-warning/10 rounded-full px-2 py-1">- {actions.length} waiting- </span>- </div>-- <div className="space-y-2">- {actions.map((action) => {- const Icon = ACTION_ICONS[action.type] || ArrowRight;- return (- <Link- key={action.id}- to={action.link || '/'}- className={`flex items-start gap-3 p-3 rounded-lg border ${ACTION_TONES[action.severity] || ACTION_TONES.medium} hover:brightness-110 transition-all min-h-[64px] group`}- >- <Icon size={17} className="mt-0.5 shrink-0 text-port-accent" />- <span className="min-w-0 flex-1">- <span className="block text-sm font-medium text-port-text truncate">{action.title}</span>- <span className="block text-xs text-port-text-muted mt-0.5">{action.detail}</span>- </span>- <ArrowRight size={16} className="mt-0.5 shrink-0 text-port-text-subtle group-hover:text-port-accent transition-colors" />- </Link>- );- })}- </div>- </section>- );-});--export default DailyActionsWidget;+// Saved daily-actions layouts remain a filtered product recommendation view.+export default function DailyActionsWidget() {+ return <ActionQueuePreview title="Today's actions" sources={['product']} />;+}diff --git a/client/src/components/DailyActionsWidget.test.jsx b/client/src/components/DailyActionsWidget.test.jsxdeleted file mode 100644index c9d53c84c6..0000000000--- a/client/src/components/DailyActionsWidget.test.jsx+++ /dev/null@@ -1,31 +0,0 @@-import { describe, it, expect } from 'vitest';-import { render, screen } from '@testing-library/react';-import { MemoryRouter } from 'react-router';-import DailyActionsWidget from './DailyActionsWidget';--const renderWidget = (actions) => render(- <MemoryRouter>- <DailyActionsWidget dashboardState={{ dailyActions: { actions } }} />- </MemoryRouter>,-);--describe('DailyActionsWidget', () => {- it('renders deep-linked daily actions from dashboard state', () => {- renderWidget([{- id: 'daily-post',- type: 'post_engagement',- severity: 'high',- title: 'Daily POST is waiting',- detail: 'No POST activity today.',- link: '/post/launcher',- }]);-- expect(screen.getByRole('heading', { name: "Today's actions" })).toBeInTheDocument();- expect(screen.getByRole('link', { name: /daily post is waiting.*no post activity today/i })).toHaveAttribute('href', '/post/launcher');- });-- it('reserves no card when there are no actions', () => {- const { container } = renderWidget([]);- expect(container).toBeEmptyDOMElement();- });-});diff --git a/client/src/components/NotificationDropdown.jsx b/client/src/components/NotificationDropdown.jsxindex 22adfb90d5..a6d78b924f 100644--- a/client/src/components/NotificationDropdown.jsx+++ b/client/src/components/NotificationDropdown.jsx@@ -2,7 +2,9 @@ import { useState, useRef, useEffect } from 'react';import { createPortal } from 'react-dom';import { useNavigate } from 'react-router';import { Bell, X, CheckCheck, Trash2, Brain, ListTodo, AlertTriangle, Code, HelpCircle, BellRing, Sparkles } from 'lucide-react';-import { timeAgo } from '../utils/formatters';+import { timeAgo, formatCount } from '../utils/formatters';+import { useActionQueue } from '../hooks/useActionQueue';+import ActionQueuePreview from './ActionQueuePreview';import { isHttpUrl } from '../utils/urlNormalize';import useFocusTrap from '../hooks/useFocusTrap.js';import useClickOutside from '../hooks/useClickOutside.js';@@ -70,6 +72,12 @@ export default function NotificationDropdown({onClearAll,position = 'above' // 'above' prefers opening upward, 'below' downward}) {+ const actionQueue = useActionQueue();+ const requiredCount = actionQueue.data?.items.filter((item) => item.required === true).length;+ const partialCount = actionQueue.data?.partial || Boolean(actionQueue.error);+ const actionCountLabel = requiredCount == null+ ? (actionQueue.error ? 'actions unavailable' : 'loading actions')+ : `${partialCount ? 'at least ' : ''}${formatCount(requiredCount)} required actions`;const [isOpen, setIsOpen] = useState(false);const [showAll, setShowAll] = useState(false);const containerRef = useRef(null);@@ -149,13 +157,13 @@ export default function NotificationDropdown({}}className="relative inline-flex items-center justify-center min-w-[44px] min-h-[44px] lg:min-w-0 lg:min-h-0 lg:p-1.5 p-1.5 rounded-lg text-gray-500 hover:text-white transition-colors focus:outline-hidden focus:ring-2 focus:ring-port-accent"title="Notifications"- aria-label={`Notifications${unreadCount > 0 ? ` (${unreadCount} unread)` : ''}`}+ aria-label={`Notifications (${actionCountLabel})`}aria-expanded={isOpen}>- <Bell size={18} className={unreadCount > 0 ? 'text-yellow-400' : 'text-gray-500'} aria-hidden="true" />- {unreadCount > 0 && (+ <Bell size={18} className={requiredCount > 0 ? 'text-yellow-400' : 'text-gray-500'} aria-hidden="true" />+ {(requiredCount > 0 || partialCount) && (<span className="absolute -top-1 -right-1 min-w-[15px] h-[15px] flex items-center justify-center text-[9px] font-bold rounded-full bg-port-warning text-port-on-warning px-0.5" aria-hidden="true">- {unreadCount > 9 ? '9+' : unreadCount}+ {requiredCount == null ? '?' : `${formatCount(requiredCount)}${partialCount ? '+' : ''}`}</span>)}</button>@@ -215,6 +223,8 @@ export default function NotificationDropdown({{/* Notification list */}<div className="max-h-[60dvh] overflow-y-auto sm:max-h-96">+ <ActionQueuePreview compact queue={actionQueue} onSelect={() => setIsOpen(false)} />+ <h3 className="px-4 py-2 text-sm text-port-text-muted">Notification history</h3>{notifications.length === 0 ? (<div className="px-4 py-8 text-center text-gray-500">No notificationsdiff --git a/client/src/components/NotificationDropdown.test.jsx b/client/src/components/NotificationDropdown.test.jsxindex 504b467131..1978f85caf 100644--- a/client/src/components/NotificationDropdown.test.jsx+++ b/client/src/components/NotificationDropdown.test.jsx@@ -4,6 +4,9 @@ import { render, screen, fireEvent } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter, useLocation } from 'react-router';import NotificationDropdown from './NotificationDropdown';+vi.mock('../hooks/useActionQueue', () => ({+ useActionQueue: () => ({ data: { items: [], partial: false }, loading: false, error: null, refetch: vi.fn() }),+}));const makeNotifications = (count) =>Array.from({ length: count }, (_, i) => ({@@ -152,7 +155,7 @@ describe('NotificationDropdown', () => {const close = screen.getByRole('button', { name: 'Close notifications' });expect(close).toHaveFocus();await user.tab();- expect(close).toHaveFocus();+ expect(screen.getByRole('link', { name: 'Open Actions' })).toHaveFocus();await user.tab({ shift: true });expect(close).toHaveFocus();await user.keyboard('{Enter}');@@ -191,7 +194,7 @@ describe('NotificationDropdown', () => {await user.click(screen.getByRole('button', { name: 'Clear all notifications' }));expect(close).toHaveFocus();await user.tab();- expect(close).toHaveFocus();+ expect(screen.getByRole('link', { name: 'Open Actions' })).toHaveFocus();await user.tab({ shift: true });expect(close).toHaveFocus();});diff --git a/client/src/components/ProactiveAlertsWidget.jsx b/client/src/components/ProactiveAlertsWidget.jsxindex a079957c9c..06642a66f5 100644--- a/client/src/components/ProactiveAlertsWidget.jsx+++ b/client/src/components/ProactiveAlertsWidget.jsx@@ -1,173 +1,6 @@-import { memo } from 'react';-import { Link } from 'react-router';-import {- Bell,- ChevronRight,- AlertTriangle,- AlertOctagon,- Target,- TrendingDown,- TrendingUp,- Cpu,- BookOpen,- CheckCircle,- Users,- MessageSquareReply,- Brain,- Sparkles-} from 'lucide-react';-import * as api from '../services/api';-import { useAutoRefetch } from '../hooks/useAutoRefetch';-import { equalByKeys, equalListByKeys } from '../lib/compareHelpers';-import ProvenanceChip from './ui/ProvenanceChip';+import ActionQueuePreview from './ActionQueuePreview';-// Alerts are detected by the Chief of Staff from trends in your goals, task-// success rates, costs, and system metrics — inferred from your data, not-// thresholds you configured. The chip declares that the same way the insights-// and health surfaces do. Only rendered when there are alerts to attribute.-const ALERT_PROVENANCE = {- level: 'inferred',- explainer:- 'Detected by your Chief of Staff from trends in your goals, task success rates, costs, system health, and product engagement — inferred from your data, not thresholds you set by hand.',- whatWouldChange:- 'As the underlying trend reverses — a goal resumes progress, success rates recover, costs settle, or a daily action is completed — the alert clears on the next sweep.',-};--const SEVERITY_STYLES = {- critical: { bg: 'bg-port-error/10', text: 'text-port-error', border: 'border-port-error/30' },- high: { bg: 'bg-port-warning/10', text: 'text-port-warning', border: 'border-port-warning/30' },- medium: { bg: 'bg-port-accent/10', text: 'text-port-accent', border: 'border-port-accent/30' }-};--const TYPE_ICONS = {- goal_stall: Target,- success_drop: TrendingDown,- cost_spike: TrendingUp,- system_resource: Cpu,- process_error: AlertOctagon,- learning_health: BookOpen,- tribe_cadence: Users,- tribe_unanswered: MessageSquareReply,- post_engagement: Brain,- commission_feedback: Sparkles-};--const ProactiveAlertsWidget = memo(function ProactiveAlertsWidget() {- // Let errors throw — `useAutoRefetch` preserves the last-good alert- // snapshot on transient failures instead of dropping the widget.- const { data, loading } = useAutoRefetch(- () => api.getAlertsSummary({ silent: true }),- 120000, // Refresh every 2 minutes- {- // Skip the re-render when the summary counts and every rendered per-row- // field are unchanged. Each alert row renders title, detail, severity- // (style class), type (icon), and link (href), so all five participate- // in the comparison — keep this list in sync with the JSX below.- compare: (prev, next) =>- equalByKeys(prev.counts, next.counts, ['total', 'critical', 'high', 'medium'])- && equalListByKeys(prev.alerts, next.alerts, [- 'title', 'severity', 'detail', 'type', 'link',- ]),- },- );-- if (loading) return null;- if (!data) return null;-- const { alerts, counts } = data;- const hasAlerts = counts.total > 0;-- return (- <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">- {/* Header */}- <div className="flex items-center justify-between gap-2 mb-3">- <div className="flex items-center gap-3 min-w-0">- <div className={`shrink-0 p-2 rounded-lg ${hasAlerts ? 'bg-port-warning/10' : 'bg-port-success/10'}`}>- {hasAlerts ? (- <Bell className="w-5 h-5 text-port-warning" />- ) : (- <CheckCircle className="w-5 h-5 text-port-success" />- )}- </div>- <div className="min-w-0">- <h3 className="text-lg font-semibold text-white truncate">Proactive Alerts</h3>- <p className="text-sm text-gray-500 truncate">- {hasAlerts- ? `${counts.total} alert${counts.total !== 1 ? 's' : ''} detected`- : 'All systems nominal'}- </p>- </div>- </div>- <div className="flex items-center gap-2 shrink-0">- {hasAlerts && <ProvenanceChip {...ALERT_PROVENANCE} align="end" />}- {hasAlerts && counts.total > 5 && (- <Link- to="/cos"- className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors min-h-[40px] px-2"- >- <span className="hidden sm:inline">View All</span>- <ChevronRight size={16} />- </Link>- )}- </div>- </div>-- {/* Severity badges */}- {hasAlerts && (- <div className="flex gap-2 mb-3">- {counts.critical > 0 && (- <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-port-error/20 text-port-error">- <AlertOctagon size={10} />- {counts.critical} critical- </span>- )}- {counts.high > 0 && (- <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-port-warning/20 text-port-warning">- <AlertTriangle size={10} />- {counts.high} high- </span>- )}- {counts.medium > 0 && (- <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-port-accent/20 text-port-accent">- {counts.medium} medium- </span>- )}- </div>- )}-- {/* Alert list */}- {hasAlerts ? (- <div className="space-y-2">- {alerts.map((alert, idx) => {- const style = SEVERITY_STYLES[alert.severity] || SEVERITY_STYLES.medium;- const Icon = TYPE_ICONS[alert.type] || AlertTriangle;- return (- <Link- key={idx}- to={alert.link || '/cos'}- className={`flex items-start gap-3 p-2.5 rounded-lg border ${style.border} ${style.bg} hover:brightness-110 transition-all group`}- >- <Icon size={14} className={`mt-0.5 shrink-0 ${style.text}`} />- <div className="min-w-0 flex-1">- <div className={`text-sm font-medium ${style.text} truncate`}>- {alert.title}- </div>- <div className="text-xs text-gray-500 truncate">- {alert.detail}- </div>- </div>- <ChevronRight size={14} className="mt-0.5 shrink-0 text-gray-600 opacity-40 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity" />- </Link>- );- })}- </div>- ) : (- <div className="text-center py-4 text-gray-500 text-sm">- No issues detected — goals progressing, tasks succeeding, system healthy- </div>- )}- </div>- );-});--export default ProactiveAlertsWidget;+// Saved proactive-alerts layouts retain their health/product focus.+export default function ProactiveAlertsWidget() {+ return <ActionQueuePreview title="Proactive Alerts" sources={['health', 'backup', 'product']} />;+}diff --git a/client/src/components/ReviewHubCard.jsx b/client/src/components/ReviewHubCard.jsxindex 0efc7c8f83..3b5ae0717a 100644--- a/client/src/components/ReviewHubCard.jsx+++ b/client/src/components/ReviewHubCard.jsx@@ -1,69 +1,6 @@-import { useState, useEffect } from 'react';-import { Link } from 'react-router';-import { AlertTriangle, Crown, CheckCircle2 } from 'lucide-react';-import * as api from '../services/api';-import socket from '../services/socket';+import ActionQueuePreview from './ActionQueuePreview';+// Retain the saved review-hub widget id as an unfiltered Actions projection.export default function ReviewHubCard() {- const [counts, setCounts] = useState(null);-- useEffect(() => {- api.getReviewCounts().then(setCounts).catch(() => null);-- const refresh = () => api.getReviewCounts().then(setCounts).catch(() => null);- socket.on('review:item:created', refresh);- socket.on('review:item:updated', refresh);- socket.on('review:item:deleted', refresh);- socket.on('review:items:bulk-updated', refresh);-- return () => {- socket.off('review:item:created', refresh);- socket.off('review:item:updated', refresh);- socket.off('review:item:deleted', refresh);- socket.off('review:items:bulk-updated', refresh);- };- }, []);-- const total = counts?.total ?? 0;-- return (- <Link- to="/review"- className="bg-port-card border border-port-border rounded-xl p-4 hover:border-port-accent/50 transition-colors block"- >- <div className="flex items-center justify-between mb-3">- <h3 className="text-sm font-semibold text-white">Review Hub</h3>- {total > 0 && (- <span className="min-w-[22px] h-[22px] flex items-center justify-center text-xs font-bold rounded-full bg-port-warning text-black px-1.5">- {total > 99 ? '99+' : total}- </span>- )}- </div>-- {total === 0 ? (- <p className="text-sm text-gray-500">All caught up!</p>- ) : (- <div className="grid grid-cols-3 gap-2">- {counts?.alert > 0 && (- <div className="flex items-center gap-1.5 text-xs text-port-warning">- <AlertTriangle size={14} />- <span>{counts.alert} alert{counts.alert !== 1 ? 's' : ''}</span>- </div>- )}- {counts?.cos > 0 && (- <div className="flex items-center gap-1.5 text-xs text-port-accent">- <Crown size={14} />- <span>{counts.cos} CoS</span>- </div>- )}- {counts?.todo > 0 && (- <div className="flex items-center gap-1.5 text-xs text-port-success">- <CheckCircle2 size={14} />- <span>{counts.todo} todo{counts.todo !== 1 ? 's' : ''}</span>- </div>- )}- </div>- )}- </Link>- );+ return <ActionQueuePreview />;}diff --git a/client/src/components/ReviewHubCard.test.jsx b/client/src/components/ReviewHubCard.test.jsxdeleted file mode 100644index a2652ae745..0000000000--- a/client/src/components/ReviewHubCard.test.jsx+++ /dev/null@@ -1,97 +0,0 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { act, render, screen } from '@testing-library/react';--const api = vi.hoisted(() => ({- getReviewCounts: vi.fn()-}));--const socket = vi.hoisted(() => ({- on: vi.fn(),- off: vi.fn(),- emit: vi.fn()-}));--vi.mock('../services/api', () => api);-vi.mock('../services/socket', () => ({ default: socket }));-vi.mock('react-router', () => ({- Link: ({ children, to, ...props }) => <a href={to} {...props}>{children}</a>-}));--import ReviewHubCard from './ReviewHubCard';--// Invokes the handler the component registered for `event` via socket.on,-// the same pattern as client/src/hooks/useNotifications.test.jsx.-function deliver(event, payload) {- const handler = socket.on.mock.calls.find(([name]) => name === event)?.[1];- expect(handler).toBeTypeOf('function');- handler(payload);-}--const ZERO_COUNTS = { total: 0, alert: 0, todo: 0, briefing: 0, cos: 0 };--beforeEach(() => {- vi.clearAllMocks();- api.getReviewCounts.mockResolvedValue(ZERO_COUNTS);-});--afterEach(() => vi.restoreAllMocks());--describe('ReviewHubCard', () => {- it('subscribes to every review socket event, including the bulk-update event, on mount', async () => {- render(<ReviewHubCard />);- await act(async () => { await Promise.resolve(); });-- const events = socket.on.mock.calls.map(([name]) => name);- expect(events).toEqual(expect.arrayContaining([- 'review:item:created',- 'review:item:updated',- 'review:item:deleted',- 'review:items:bulk-updated'- ]));- });-- it('renders the all-caught-up state when there are no pending items', async () => {- render(<ReviewHubCard />);- expect(await screen.findByText('All caught up!')).toBeInTheDocument();- });-- it('renders the total badge and per-type breakdown once counts resolve', async () => {- api.getReviewCounts.mockResolvedValue({ total: 3, alert: 1, todo: 1, briefing: 0, cos: 1 });- render(<ReviewHubCard />);-- expect(await screen.findByText('3')).toBeInTheDocument();- expect(screen.getByText('1 alert')).toBeInTheDocument();- expect(screen.getByText('1 todo')).toBeInTheDocument();- expect(screen.getByText('1 CoS')).toBeInTheDocument();- });-- it('refetches counts exactly once when a review:items:bulk-updated event arrives', async () => {- render(<ReviewHubCard />);- await act(async () => { await Promise.resolve(); });- expect(api.getReviewCounts).toHaveBeenCalledTimes(1); // the initial mount fetch-- api.getReviewCounts.mockResolvedValue({ total: 5, alert: 0, todo: 5, briefing: 0, cos: 0 });- await act(async () => {- deliver('review:items:bulk-updated', { ids: ['a', 'b'], status: 'dismissed', updatedAt: new Date().toISOString() });- await Promise.resolve();- });-- expect(api.getReviewCounts).toHaveBeenCalledTimes(2);- expect(await screen.findByText('5')).toBeInTheDocument();- });-- it('unsubscribes every review event, including the bulk-update event, on unmount', async () => {- const { unmount } = render(<ReviewHubCard />);- await act(async () => { await Promise.resolve(); });-- unmount();-- const offEvents = socket.off.mock.calls.map(([name]) => name);- expect(offEvents).toEqual(expect.arrayContaining([- 'review:item:created',- 'review:item:updated',- 'review:item:deleted',- 'review:items:bulk-updated'- ]));- });-});diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsxindex 634888810b..d179d7cff3 100644--- a/client/src/components/dashboard/widgetRegistry.jsx+++ b/client/src/components/dashboard/widgetRegistry.jsx@@ -48,7 +48,8 @@ const postFeatureEnabled = (state) => state?.instanceFeatures?.features?.some(// dashboard cells measure their content and float up (see DashboardGrid), so// this only has to be in the right ballpark for the first paint.export const WIDGETS = [- { id: 'daily-actions', label: 'Today\'s Actions', Component: DailyActionsWidget, width: 'full', defaultH: 4, gate: (s) => (s.dailyActions?.actions?.length ?? 0) > 0 },+ { id: 'actions', label: 'Actions', Component: ReviewHubCard, width: 'full', defaultH: 4 },+ { id: 'daily-actions', label: 'Today\'s Actions', Component: DailyActionsWidget, width: 'full', defaultH: 4 },// Daily Driver self-hides once the day is handled — gated on the per-day// first-visit/handled state so a handled day reserves no grid cell (#2666).{ id: 'daily-driver', label: 'Daily Driver', Component: DailyDriverWidget, width: 'third', defaultH: 6, gate: (s) => !!s.dailyDriver && !s.dailyDriver.handledToday },diff --git a/client/src/constants/events.js b/client/src/constants/events.jsindex 4ce85d3ecd..bf09c8f041 100644--- a/client/src/constants/events.js+++ b/client/src/constants/events.js@@ -3,3 +3,4 @@export const DASHBOARD_LAYOUT_CHANGED = 'portos:dashboard-layout-changed';export const INSTANCE_FEATURES_CHANGED = 'portos:instance-features-changed';+export const ACTION_QUEUE_CHANGED = 'portos:action-queue-changed';diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 3f0df6bf34..56909e9ae4 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -19,13 +19,14 @@ grep -i "what you want to do" client/src/hooks/README.md| Hook | Purpose | Use when ||---|---|---|+| `useActionQueue` | Shared canonical Actions snapshot, socket invalidation, visible-tab polling and explicit stale/error state. | Bell, dashboard previews and Actions. || `useNotifications` | Generic toast dispatch + socket-subscribed notification list. | You need to read / dispatch the global notification stream. || `useErrorNotifications` | Subscribes to server error events and shows toasts. | Wire once high in the tree to surface server errors. || `useAIStatusNotifications` | Subscribes to AI operation status events. | Wire once to surface AI run lifecycle as toasts. || `useFableLoomAiRun` | Tracks one FableLoom AI operation, including the attachable shell handoff for TUI providers. | FableLoom series or episode AI actions. || `useAgentFeedbackToast` | Agent completion toast with thumbs-up/down UI. | Show actionable agent-run completion feedback. || `useOnDemandTaskToast` | Toasts when a user-triggered on-demand task run found no work (parked). | Wire once high in the tree so an explicit "Run" that parks isn't a silent no-op. |-| `useEngagementReminderToast` | Polls deterministic POST/creative-feedback actions and shows each reminder once per browser tab/day with a deep link. | Wire once high in the tree so daily actions remain visible outside the dashboard. |+| `useEngagementReminderToast` | Shows explicitly opted-in POST reminders only after a durable server delivery claim. | Wire once high in the tree; reloads and tabs share the same occurrence/generation marker. || `useSharingNotifications` | Subscriber for share-bucket notifications. | Wire once to surface federation/sync events. || `useHealthWarningDismiss` | Dismisses a system-health dashboard warning as resolved, with an Undo toast. | The dashboard widget and the Live health overview page both dismiss/undo warnings. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 792aeb7265..4acdf3e022 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -232,3 +232,4 @@ export * from './useVoiceUiSync.js';export { default as useEidoverseFrame } from './useEidoverseFrame.js';export * from './useGalleryPage.js';export * from './useAccountSyncStatus.js';+export * from './useActionQueue.js';diff --git a/client/src/hooks/useActionQueue.js b/client/src/hooks/useActionQueue.jsnew file mode 100644index 0000000000..8f6a7e1fdd--- /dev/null+++ b/client/src/hooks/useActionQueue.js@@ -0,0 +1,86 @@+import { useCallback, useSyncExternalStore } from 'react';+import * as api from '../services/api';+import socket from '../services/socket';+import { useAutoRefetch } from './useAutoRefetch';+import { ACTION_QUEUE_CHANGED, INSTANCE_FEATURES_CHANGED } from '../constants/events';++// Shared by the bell, dashboard previews, and Actions page. These events carry+// invalidations only; source records are always re-read from this install.+const EVENTS = [+ 'connect', 'brain:classified', 'brain:threads:changed',+ 'cos:tasks:user:changed', 'cos:tasks:cos:changed', 'cos:agent:completed',+ 'cos:memory:approved', 'cos:memory:rejected', 'cos:agent:feedback',+ 'messages:changed', 'messages:draft:created', 'messages:draft:sent',+ 'backup:started', 'backup:completed', 'backup:failed',+ 'review:item:created', 'review:item:updated', 'review:item:deleted',+ 'review:items:bulk-updated', 'review:queue:changed',+ 'notifications:added', 'notifications:removed', 'notifications:cleared',+];+const stores = new Map();++function queueStore(view) {+ if (stores.has(view)) return stores.get(view);+ let state = { data: null, loading: true, error: null };+ let inFlight = null;+ let generation = 0;+ let refreshedAt = 0;+ const listeners = new Set();+ const publish = (next) => {+ state = next;+ for (const notify of listeners) notify();+ };+ const refresh = (force = false) => {+ if (inFlight) return inFlight;+ if (!force && Date.now() - refreshedAt < 1000) return Promise.resolve();+ const started = generation;+ inFlight = api.getReviewQueue({ view, silent: true }).then((data) => {+ if (!Array.isArray(data?.items) || typeof data.partial !== 'boolean') {+ throw new Error('Invalid Actions response');+ }+ if (started === generation) {+ refreshedAt = Date.now();+ publish({ data, loading: false, error: null });+ }+ }).catch((error) => {+ if (started === generation) publish({ ...state, loading: false, error });+ }).finally(() => {+ inFlight = null;+ if (started !== generation && listeners.size) refresh(true);+ });+ return inFlight;+ };+ const invalidate = () => { generation++; refresh(true); };+ const subscribe = (notify) => {+ listeners.add(notify);+ if (listeners.size === 1) {+ for (const event of EVENTS) socket.on(event, invalidate);+ window.addEventListener(ACTION_QUEUE_CHANGED, invalidate);+ window.addEventListener(INSTANCE_FEATURES_CHANGED, invalidate);+ }+ return () => {+ listeners.delete(notify);+ if (!listeners.size) {+ generation++;+ for (const event of EVENTS) socket.off(event, invalidate);+ window.removeEventListener(ACTION_QUEUE_CHANGED, invalidate);+ window.removeEventListener(INSTANCE_FEATURES_CHANGED, invalidate);+ }+ };+ };+ const store = { subscribe, getSnapshot: () => state, refresh };+ stores.set(view, store);+ return store;+}++/** One snapshot per view, retained on errors; polls pause in background tabs. */+export function useActionQueue(view = 'today') {+ const store = queueStore(view);+ const state = useSyncExternalStore(store.subscribe, store.getSnapshot);+ const refresh = useCallback(() => store.refresh(), [store]);+ useAutoRefetch(refresh, 120000, { pollOnly: true });+ const refetch = useCallback(() => store.refresh(true), [store]);+ return { ...state, refetch };+}++/** Test seam: call only after unmounting all consumers. */+export function __resetActionQueue() { stores.clear(); }diff --git a/client/src/hooks/useEngagementReminderToast.jsx b/client/src/hooks/useEngagementReminderToast.jsxindex 9fae3f6aec..4bf1748716 100644--- a/client/src/hooks/useEngagementReminderToast.jsx+++ b/client/src/hooks/useEngagementReminderToast.jsx@@ -1,14 +1,11 @@-import { useCallback, useRef, useState } from 'react';+import { useEffect, useState } from 'react';import { Link } from 'react-router';import toast from '../components/ui/Toast';import * as api from '../services/api';-import { safeReadJsonSession, safeWriteJsonSession } from '../lib/safeStorage';-import { useAutoRefetch } from './useAutoRefetch';+import { useActionQueue } from './useActionQueue';+import { actionSelectionLink } from '../components/ActionQueuePreview';import { INSTANCE_FEATURES_CHANGED } from '../constants/events.js';-const SESSION_KEY = 'portos:engagement-reminders:v1';-const MAX_REMINDER_KEYS = 100;-function ReminderToast({ t, action }) {const [disabling, setDisabling] = useState(false);const canDisable = typeof action.featureId === 'string' && action.featureId.length > 0;@@ -37,10 +34,10 @@ function ReminderToast({ t, action }) {<span className="text-port-warning" aria-hidden="true">⚠️</span><span className="font-medium text-port-text text-sm flex-1">{action.title}</span></div>- <p className="text-xs text-port-text-muted">{action.detail}</p>+ <p className="text-xs text-port-text-muted">{action.reason || action.summary}</p><div className="flex items-center gap-2 pt-1 border-t border-port-border/30"><Link- to={action.link || '/'}+ to={actionSelectionLink(action.id)}onClick={() => toast.dismiss(t.id)}className="inline-flex items-center justify-center min-h-[44px] px-3 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 text-xs font-medium">@@ -68,40 +65,23 @@ function ReminderToast({ t, action }) {);}-/**- * Poll the deterministic daily-action projection and show each actionable- * reminder once per browser tab/day. The session guard keeps a route reload- * from repeatedly interrupting the user while still allowing a new day's POST- * prompt or the next unrated commission run to surface.- */+/** Delivery requires an explicit scheduled reminder and a durable server claim. */export function useEngagementReminderToast() {- const shownRef = useRef(null);- if (shownRef.current === null) {- const stored = safeReadJsonSession(SESSION_KEY, {});- shownRef.current = new Set(stored && typeof stored === 'object' ? Object.keys(stored) : []);- }-- const showReminder = useCallback((today, action) => {- if (!action?.id) return;- const key = `${today || 'unknown'}:${action.id}`;- if (shownRef.current.has(key)) return;- shownRef.current.add(key);- const recent = [...shownRef.current].slice(-MAX_REMINDER_KEYS);- shownRef.current = new Set(recent);- safeWriteJsonSession(SESSION_KEY, Object.fromEntries(recent.map((item) => [item, true])));- toast((t) => <ReminderToast t={t} action={action} />, {- id: `engagement-reminder-${key}`,- duration: 12000,- icon: null,- label: action.title,- });- }, []);-- const fetchActions = useCallback(async () => {- const data = await api.getDailyActions({ silent: true });- for (const action of data?.actions || []) showReminder(data.today, action);- return data;- }, [showReminder]);-- useAutoRefetch(fetchActions, 300000, { pollOnly: true });+ const { data, error } = useActionQueue();+ useEffect(() => {+ let active = true;+ if (!error && document.visibilityState !== 'hidden') {+ for (const action of data?.items || []) {+ if (action.id !== 'product:daily-post') continue;+ api.claimReviewQueueDelivery(action.id, { silent: true }).then((result) => {+ if (!active || !result.claimed) return;+ toast((t) => <ReminderToast t={t} action={action} />, {+ id: `engagement-reminder-${action.id}:${action.occurrence}:${result.generation}`,+ duration: 12000, icon: null, label: action.title,+ });+ }).catch(() => {});+ }+ }+ return () => { active = false; };+ }, [data, error]);}diff --git a/client/src/hooks/useEngagementReminderToast.test.jsx b/client/src/hooks/useEngagementReminderToast.test.jsxindex 02b1da3d77..293943df0f 100644--- a/client/src/hooks/useEngagementReminderToast.test.jsx+++ b/client/src/hooks/useEngagementReminderToast.test.jsx@@ -3,15 +3,18 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libraimport { MemoryRouter } from 'react-router';const mock = vi.hoisted(() => ({- getDailyActions: vi.fn(),+ getReviewQueue: vi.fn(),+ claimReviewQueueDelivery: vi.fn(),updateInstanceFeature: vi.fn(),}));vi.mock('../services/api', () => mock);+vi.mock('../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));import { toast, Toaster } from '../components/ui/Toast';import { INSTANCE_FEATURES_CHANGED } from '../constants/events.js';import { useEngagementReminderToast } from './useEngagementReminderToast';+import { __resetActionQueue } from './useActionQueue';function Harness() {useEngagementReminderToast();@@ -22,10 +25,14 @@ describe('useEngagementReminderToast', () => {beforeEach(() => {sessionStorage.clear();vi.clearAllMocks();- mock.getDailyActions.mockResolvedValue({- today: '2026-08-24',- actions: [{- id: 'daily-post',+ __resetActionQueue();+ mock.claimReviewQueueDelivery.mockResolvedValue({ claimed: true, generation: 0 });+ mock.getReviewQueue.mockResolvedValue({+ partial: false,+ items: [{+ id: 'product:daily-post',+ source: 'product',+ occurrence: '2026-08-24',type: 'post_engagement',title: 'Daily POST is waiting',detail: 'No POST activity today.',@@ -46,7 +53,7 @@ describe('useEngagementReminderToast', () => {render(<MemoryRouter><Harness /><Toaster /></MemoryRouter>);const link = await screen.findByRole('link', { name: 'Open action' });- expect(link).toHaveAttribute('href', '/post/launcher');+ expect(link).toHaveAttribute('href', '/review/product%3Adaily-post?view=today');expect(screen.getByRole('button', { name: 'Disable on this instance' })).toBeInTheDocument();});diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsxindex 6aaf38a8bb..1ed21d420c 100644--- a/client/src/pages/Review.jsx+++ b/client/src/pages/Review.jsx@@ -42,34 +42,10 @@ 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 { useActionQueue } from '../hooks/useActionQueue';import * as api from '../services/api';import socket from '../services/socket';-// 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-// (no socket emit) and proactive alerts are live-computed (no event).-const QUEUE_INVALIDATION_EVENTS = [- 'brain:classified', // inbox item classified / re-reviewed- 'cos:tasks:user:changed', // CoS user-task list changed- 'cos:tasks:cos:changed', // CoS internal-task list changed- 'cos:agent:completed', // a newly completed run may need feedback- 'messages:changed', // draft approved/deleted/status changed- 'messages:draft:created', // new draft awaiting review- '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)- '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).const QUEUE_SOURCE_CONFIG = {brain: { icon: BrainIcon, color: 'text-port-accent-2' },@@ -172,7 +148,7 @@ export default function Review() {// Cross-domain live queue (M42 P5). Source payloads remain live projections;// presentation decisions are durable server-side markers keyed by the row's// canonical action identity, occurrence, and revision.- const [queue, setQueue] = useState(null);+ const { data: queue, error: queueError, loading: queueLoading, refetch: fetchQueue } = useActionQueue(actionView);const [dismissedQueueIds, setDismissedQueueIds] = useState(() => new Set());// Rows with an inline accept/promote in flight — disables the button so a// double-tap can't double-resolve while the request is pending.@@ -197,18 +173,11 @@ 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({ view: actionView, silent: true }).catch(() => null);- setQueue(data);- }, [actionView]);-useEffect(() => {fetchItems();fetchCounts();fetchBriefing();- fetchQueue();- }, [fetchItems, fetchCounts, fetchBriefing, fetchQueue]);+ }, [fetchItems, fetchCounts, fetchBriefing]);useEffect(() => {const handleCreated = (item) => {@@ -249,20 +218,6 @@ export default function Review() {};}, [fetchCounts, fetchItems]);- // Live-invalidate the cross-domain queue. A burst of producer events (e.g.- // a draft sent fires both messages:draft:sent and messages:changed) coalesces- // into a single refetch on the trailing edge. dismissedQueueIds still filters- // the result, so a row the user dismissed this session won't pop back; a- // re-resolved item simply isn't returned by the server anymore.- useEffect(() => {- const refetch = coalesce(() => fetchQueue(), 400);- for (const evt of QUEUE_INVALIDATION_EVENTS) socket.on(evt, refetch);- return () => {- for (const evt of QUEUE_INVALIDATION_EVENTS) socket.off(evt, refetch);- refetch.cancel();- };- }, [fetchQueue]);-const handleCreateTodo = async (e) => {e.preventDefault();if (!newTodo.trim()) return;@@ -408,7 +363,7 @@ export default function Review() {// 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 showLegacyReviewSurface = queue && !queueError && queueItems.length === 0 && queueSourceErrors.length === 0 && !queue.partial;const pendingItems = useMemo(() => items.filter(i => i.status === 'pending'), [items]);const genericCompletableCount = pendingItems.filter(isGenericCompletableItem).length;@@ -497,11 +452,19 @@ export default function Review() {/>{/* Triage summary */}<section className="flex flex-wrap gap-2">- <SummaryPill icon={BellRing} label="Pending" value={counts?.total ?? 0} tone="text-white" />- <SummaryPill icon={AlertTriangle} label="Alerts" value={counts?.alert ?? 0} tone="text-port-warning" urgent={(counts?.alert ?? 0) > 0} />- <SummaryPill icon={Crown} label="CoS" value={counts?.cos ?? 0} tone="text-port-accent" />- <SummaryPill icon={ClipboardList} label="Todos" value={counts?.todo ?? 0} tone="text-port-success" />+ {queue && <span className="text-sm text-port-text">{queue.partial || queueError ? 'At least ' : ''}{formatCount(queueItems.filter(item => item.required === true).length)} required</span>}+ {queueLoading && !queue && <span role="status">Loading actions…</span>}+ {queueError && <span role="alert">Actions unavailable{queue ? ' — showing last known actions' : ''}. <button onClick={fetchQueue}>Retry</button></span>}</section>+ <details>+ <summary className="text-xs text-port-text-muted">Stored review history counts</summary>+ <section className="flex flex-wrap gap-2">+ <SummaryPill icon={BellRing} label="Pending" value={counts?.total ?? 0} tone="text-white" />+ <SummaryPill icon={AlertTriangle} label="Alerts" value={counts?.alert ?? 0} tone="text-port-warning" urgent={(counts?.alert ?? 0) > 0} />+ <SummaryPill icon={Crown} label="CoS" value={counts?.cos ?? 0} tone="text-port-accent" />+ <SummaryPill icon={ClipboardList} label="Todos" value={counts?.todo ?? 0} tone="text-port-success" />+ </section>+ </details>{/* Canonical Actions queue — live-pulled from Brain commitments, manualtodos, Ask, CoS, Messages, Health, and Backups. Shown whenever therediff --git a/client/src/pages/Review.test.jsx b/client/src/pages/Review.test.jsxindex b43b172e60..92fc65c2b3 100644--- a/client/src/pages/Review.test.jsx+++ b/client/src/pages/Review.test.jsx@@ -89,7 +89,7 @@ vi.mock('../services/api', () => ({getReviewItems: vi.fn(() => Promise.resolve([ITEM, SHORT_ITEM, COMPLETED_ITEM])),getReviewCounts: vi.fn(),getReviewBriefing: vi.fn(() => Promise.resolve(null)),- getReviewQueue: vi.fn(() => Promise.resolve({ items: [], sources: {} })),+ getReviewQueue: vi.fn(() => Promise.resolve({ items: [], sources: {}, partial: false })),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' })),@@ -124,6 +124,7 @@ vi.mock('react-router', () => ({import Review from './Review';import * as api from '../services/api';import socket from '../services/socket';+import { __resetActionQueue } from '../hooks/useActionQueue';const SUMMARY_COUNTS = { total: 8, alert: 3, todo: 1, briefing: 0, cos: 4 };@@ -141,6 +142,7 @@ const forceOverflow = () =>afterEach(() => vi.restoreAllMocks());beforeEach(() => {+ __resetActionQueue();vi.clearAllMocks();routerState.actionId = undefined;routerState.searchParams = new URLSearchParams();@@ -203,6 +205,7 @@ describe('Review Hub queue-card triage (#3282)', () => {it('forwards an explicit source operation for source-owned queue actions', async () => {api.getReviewQueue.mockResolvedValueOnce({+ partial: false,items: [{id: 'memory:memory-1',source: 'review',@@ -230,7 +233,7 @@ describe('Review Hub queue-card triage (#3282)', () => {});it('shows durable snooze and recommendation-dismiss controls', async () => {- api.getReviewQueue.mockResolvedValueOnce({ items: [TRIAGE_RECOMMENDATION], sources: {} });+ api.getReviewQueue.mockResolvedValueOnce({ items: [TRIAGE_RECOMMENDATION], sources: {}, partial: false });render(<Review />);const snooze = await screen.findByRole('combobox', { name: 'Snooze Optional answer ready' });@@ -245,7 +248,7 @@ describe('Review Hub queue-card triage (#3282)', () => {});it('persists dismissal only for an optional recommendation', async () => {- api.getReviewQueue.mockResolvedValueOnce({ items: [TRIAGE_RECOMMENDATION], sources: {} });+ api.getReviewQueue.mockResolvedValueOnce({ items: [TRIAGE_RECOMMENDATION], sources: {}, partial: false });render(<Review />);fireEvent.click(await screen.findByRole('button', { name: 'Dismiss this recommendation' }));@@ -257,7 +260,7 @@ describe('Review Hub queue-card triage (#3282)', () => {});it('requires a rating before sending the source-owned feedback action', async () => {- api.getReviewQueue.mockResolvedValueOnce({ items: [FEEDBACK_ITEM], sources: {} });+ api.getReviewQueue.mockResolvedValueOnce({ items: [FEEDBACK_ITEM], sources: {}, partial: false });render(<Review />);const rate = await screen.findByRole('button', { name: 'Rate' });@@ -354,7 +357,7 @@ describe('Review Hub bulk status updates (#6853)', () => {await waitFor(() => expect(actionQueueBody()).toBeTruthy());await waitFor(() => expect(document.getElementById(`review-item-body-action-queue-${SHORT_ITEM.id}`)).toBeTruthy());- const handler = socket.on.mock.calls.find(([name]) => name === 'review:items:bulk-updated')?.[1];+ const handler = socket.on.mock.calls.findLast(([name]) => name === 'review:items:bulk-updated')?.[1];expect(handler).toBeTypeOf('function');act(() => {@@ -388,7 +391,7 @@ describe('Review Hub status-filtered socket items (#6925)', () => {await waitFor(() => expect(screen.getAllByText(ITEM.title).length).toBeGreaterThan(0));const handler = socket.on.mock.calls- .find(([name]) => name === 'review:item:updated')?.[1];+ .findLast(([name]) => name === 'review:item:updated')?.[1];expect(handler).toBeTypeOf('function');act(() => {@@ -409,7 +412,7 @@ describe('Review Hub status-filtered socket items (#6925)', () => {await waitFor(() => expect(screen.getByText(COMPLETED_ITEM.title)).toBeInTheDocument());const handler = socket.on.mock.calls- .find(([name]) => name === 'review:item:created')?.[1];+ .findLast(([name]) => name === 'review:item:created')?.[1];expect(handler).toBeTypeOf('function');act(() => {@@ -449,7 +452,7 @@ describe('Review Hub triage summary (#6926)', () => {render(<Review />);await waitFor(() => expect(summaryValue('Pending')).toBe('8'));- const handler = socket.on.mock.calls.find(([name]) => name === 'review:item:updated')?.[1];+ const handler = socket.on.mock.calls.findLast(([name]) => name === 'review:item:updated')?.[1];expect(handler).toBeTypeOf('function');await act(async () => {@@ -473,7 +476,7 @@ describe('Review Hub triage summary (#6926)', () => {render(<Review />);await waitFor(() => expect(resolveInitial).toBeTypeOf('function'));- const handler = socket.on.mock.calls.find(([name]) => name === 'review:item:updated')?.[1];+ const handler = socket.on.mock.calls.findLast(([name]) => name === 'review:item:updated')?.[1];expect(handler).toBeTypeOf('function');act(() => handler({ ...ITEM, status: 'completed' }));await waitFor(() => expect(resolveRefresh).toBeTypeOf('function'));diff --git a/client/src/services/apiReview.js b/client/src/services/apiReview.jsindex 25f12a4570..547c29374c 100644--- a/client/src/services/apiReview.js+++ b/client/src/services/apiReview.js@@ -1,4 +1,13 @@import { request, queryString } from './apiCore.js';+import { ACTION_QUEUE_CHANGED } from '../constants/events.js';++const actionChanged = (result) => {+ window.dispatchEvent(new Event(ACTION_QUEUE_CHANGED));+ return result;+};+export const claimReviewQueueDelivery = (id, options = {}) => request('/review/queue/delivery', {+ method: 'POST', body: JSON.stringify({ id }), ...options,+});// Review Hubexport const getReviewItems = (params) => {@@ -30,7 +39,7 @@ export const resolveReviewQueueItem = (id, { operation, rating, comment, ...opti...(comment !== undefined ? { comment } : {}),}),...options-});+}).then(actionChanged);// Persist a presentation-only queue decision. The server re-reads the source// row, so the client supplies only the row id and the selected operation/time.export const triageReviewQueueItem = (id, { operation, snoozedUntil, ...options } = {}) => request('/review/queue/triage', {@@ -41,7 +50,7 @@ export const triageReviewQueueItem = (id, { operation, snoozedUntil, ...options...(snoozedUntil ? { snoozedUntil } : {}),}),...options-});+}).then(actionChanged);// Promote an Ask row's latest assistant answer into Brain, a CoS task, or a// Goal's progress in place (id is `ask:<conversationId>`, target is// 'brain' | 'task' | 'goal'; goalId is required for the 'goal' target).@@ -49,7 +58,7 @@ export const promoteAskReviewQueueItem = (id, target, { goalId, ...options } = {method: 'POST',body: JSON.stringify({ id, target, ...(goalId ? { goalId } : {}) }),...options-});+}).then(actionChanged);export const updateReviewItem = (id, data, options = {}) => request(`/review/items/${id}`, {method: 'PATCH',body: JSON.stringify(data),diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 9c91b68e46..9da8370ee1 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -37,7 +37,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `memories` / `memory_links` — long-term memory + pgvector similarity.- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).- `user_action_events` — the operator-action ledger (#5594, epic #5593): one row per action the HUMAN took in PortOS (queued a CoS task, edited/deleted/approved/force-spawned one, rated an agent run, hit Run Now on a scheduled task, saved settings; phase 3 / #5596 also records event-only creative/Brain pointers, instance-feature toggles, and CoS schedule updates that skip `PUT /api/settings`). The leftover-branch idle detector is a **consumer** of this ledger (plus live git state), not a store of its own. `db-primary` because the value is in querying it — by type, actor, target, and time window — which is exactly what a JSONL append log cannot do. Columns carry the queryable axes (`type`/`actor`/`happened_at`/`target`/`success`) with structured detail in `payload` JSONB and the hook site in `source` JSONB; a unique `(type, dedupe_key)` index plus `ON CONFLICT DO NOTHING` makes a retried request idempotent. Bounded inline after each insert by BOTH a 20,000-row cap and a 90-day age cap — no cron. Credential-shaped payload keys are dropped at write time and their paths listed under `payload.redactedKeys`. **Intentionally machine-local — never federated**: it records what one operator did on one machine, and this ledger has no cross-machine merge contract. This is a store-specific implementation boundary, not a ban on syncing personal records to the user's own machines (ADR [user-controlled federation](./decisions/2026-09-19-user-controlled-federation.md)); guarded in `server/services/sharing/peerSync.test.js`. Deliberately NOT in `auditedTables` — auditing an audit log doubles every row, same rationale as `post_runs`. Adapter: `server/services/userActions.js` (file backend only under the dev/test escape hatch).-- `review_queue_triage` — the Review Hub's machine-local presentation markers: canonical `action_key` plus `occurrence`/`revision`, `snoozed_until`, optional recommendation `dismissed`, and a delivery `generation` marker reserved for the delivery layer. It contains no queue title, summary, prompt, source payload, or notification-read state; the live producer remains authoritative and a new occurrence/revision gets a fresh presentation decision. **Intentionally machine-local — never federated**, including when the source row is a federated Brain record. PostgreSQL is authoritative and the normal `pg_dump` captures it; the JSON adapter exists only for the documented dev/test file escape hatch. Adapter: `server/services/reviewQueueTriageStore.js`.+- `review_queue_triage` — the Review Hub's machine-local presentation and delivery markers: canonical `action_key` plus `occurrence`/`revision`, `snoozed_until`, optional recommendation `dismissed`, and `delivery_generation`. Delivery-only keys use `delivery:<canonical-id>` plus occurrence (empty revision); the additive `delivery` JSONB holds severity and per-channel generations. It contains no queue title, summary, prompt, source payload, or notification-read state; the live producer remains authoritative. New occurrence/revision gets a fresh presentation decision, but a text revision does not reset delivery. **Intentionally machine-local — never federated**, including when the source row is a federated Brain record. PostgreSQL is authoritative and the normal `pg_dump` captures it; the JSON adapter exists only for the documented dev/test file escape hatch. Adapter: `server/services/reviewQueueTriageStore.js`.- `cos_pending_agent_feedback` — a bounded, machine-local index of completed manual CoS runs that still need a human rating. It stores only `agent_id` plus the archive date locator; the agent archive remains the source-owned record and the rating is removed from this index only after that archive carries the durable rating. PostgreSQL is authoritative in normal installs (with the documented file backend only for dev/test), the input-gated migration 008 derives existing refs from live state without a seed or provider call, and future completion events enroll new refs. **Intentionally machine-local — never federated**; the DB dump backs it up alongside the agent archive under the filesystem snapshot. Adapter: `server/services/cosAgentFeedbackStore.js`.- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.diff --git a/docs/features/review-queue.md b/docs/features/review-queue.mdindex 3518e07a22..f410df1d48 100644--- a/docs/features/review-queue.md+++ b/docs/features/review-queue.md@@ -111,3 +111,45 @@ compatibility projections. Optional Ask promotion is still available from Askand its API, but it is not required action admission. Routine task-ready/successattention generation is not a queue producer; execution history and privatereports remain separate.++## Bell, previews, and delivery++The bell, Actions card, and Actions page share the same per-view queue snapshot.+The bell badge counts only unsnoozed required rows, never unread history or+optional recommendations. Partial source reads show lower-bound counts; failed+refreshes retain explicitly stale rows with Retry, never an inbox-zero claim.+Optional recommendations remain separately visible. Preview links select the+canonical row at `/review/<encoded-id>?view=today`.++Fresh dashboard layouts use one `actions` card. Saved widget IDs and geometry+are unchanged: `review-hub` wraps the queue, `daily-actions` filters product+recommendations, and `proactive-alerts` filters health, backup, and product rows.++Notification read/clear APIs affect event history only. Clearing a proven+notification-backed obligation hides its history record without deleting the+source marker; domain completion removes it through `removeByMetadata`.+Uncorrelated legacy records remain ordinary history with their existing clear+behavior. Producers attach canonical `metadata.actionId` only when the adapter+proves the source reference; title matching is never correlation.++Delivery claims live in the existing machine-local triage store, under a+`delivery:<canonical-id>` key plus occurrence, independent of text revision.+One marker stores a severity high-water mark, generation, and last delivered+generation per channel (toast, Telegram, scheduled reminder). Escalation+advances the generation without creating another action. Read, clear, snooze,+dismiss, reload, and additional tabs never reset that marker. An unavailable+queue/store cannot grant a delivery claim.++`POST /api/review/queue/delivery` accepts only the canonical ID. The server+re-reads the current unsnoozed queue, checks POST reminder opt-in and a matching+scheduled occurrence, then durably claims the toast. Daily recommendations do+not interrupt by default. Existing scheduling, feature, forwarding-type,+autonomy, and daily-budget gates still apply. Both Telegram transports share+the canonical claim; uncorrelated legacy forwards retain their old behavior.+Claims precede delivery: a lost response or failed transport can suppress a+nudge, but retrying cannot duplicate an interruption for that generation.++Completion and triage emit payload-free `review:queue:changed` invalidations,+alongside existing domain events. All subscribed surfaces refetch locally and+discard stale in-flight responses. POST completion, creative feedback, and CoS+approval therefore update other tabs without federating source payloads.diff --git a/scripts/migrations/400-action-delivery-markers.js b/scripts/migrations/400-action-delivery-markers.jsnew file mode 100644index 0000000000..47cbc1ff68--- /dev/null+++ b/scripts/migrations/400-action-delivery-markers.js@@ -0,0 +1,29 @@+/**+ * Additive history visibility for notification-backed obligations. Source+ * records remain in the same local store; existing read state is preserved.+ * PostgreSQL's idempotent schema upgrade adds review_queue_triage.delivery.+ */+import { readFile } from 'node:fs/promises';+import { join } from 'node:path';+import { atomicWrite } from '../../server/lib/fileUtils.js';++export default {+ async up({ rootDir }) {+ const path = join(rootDir, 'data/notifications.json');+ const raw = await readFile(path, 'utf8').catch((error) => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (raw === null) return;+ const document = JSON.parse(raw);+ if (!Array.isArray(document.notifications)) throw new Error('Invalid notification history');+ let changed = false;+ for (const record of document.notifications) {+ if (record && typeof record === 'object' && record.historyHidden === undefined) {+ record.historyHidden = false;+ changed = true;+ }+ }+ if (changed) await atomicWrite(path, document);+ },+};diff --git a/scripts/migrations/400-action-delivery-markers.test.js b/scripts/migrations/400-action-delivery-markers.test.jsnew file mode 100644index 0000000000..eec5369ab1--- /dev/null+++ b/scripts/migrations/400-action-delivery-markers.test.js@@ -0,0 +1,25 @@+import { afterEach, expect, it } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import migration from './400-action-delivery-markers.js';++let rootDir;+afterEach(async () => { if (rootDir) await rm(rootDir, { recursive: true, force: true }); });++it('adds history visibility without resetting existing reads or hidden obligations, and is idempotent', async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'action-delivery-migration-'));+ await migration.up({ rootDir });+ await mkdir(join(rootDir, 'data'));+ const file = join(rootDir, 'data/notifications.json');+ await writeFile(file, JSON.stringify({ version: 1, notifications: [+ { id: 'legacy', read: true }, { id: 'hidden', read: false, historyHidden: true },+ ] }));+ await migration.up({ rootDir });+ const migrated = await readFile(file, 'utf8');+ expect(JSON.parse(migrated).notifications).toEqual([+ { id: 'legacy', read: true, historyHidden: false }, { id: 'hidden', read: false, historyHidden: true },+ ]);+ await migration.up({ rootDir });+ expect(await readFile(file, 'utf8')).toBe(migrated);+});diff --git a/server/lib/db/schema/reviewQueueTriage.js b/server/lib/db/schema/reviewQueueTriage.jsindex 28f48fe7a2..b6bb38aae2 100644--- a/server/lib/db/schema/reviewQueueTriage.js+++ b/server/lib/db/schema/reviewQueueTriage.js@@ -11,4 +11,5 @@ export const reviewQueueTriageDdl = [delivery_generation INTEGER NOT NULL DEFAULT 0 CHECK (delivery_generation >= 0),PRIMARY KEY (action_key, occurrence, revision))`,+ `ALTER TABLE review_queue_triage ADD COLUMN IF NOT EXISTS delivery JSONB`,];diff --git a/server/routes/creativeCommissions.js b/server/routes/creativeCommissions.jsindex 5b7f0ff44d..5d83a2ee37 100644--- a/server/routes/creativeCommissions.js+++ b/server/routes/creativeCommissions.js@@ -11,6 +11,7 @@*/import { Router } from 'express';+import { reviewEvents } from '../services/review.js';import { asyncHandler, createServiceErrorMapper } from '../lib/errorHandler.js';import {validateRequest,@@ -72,6 +73,7 @@ router.post('/:id/run', asyncHandler(async (req, res) => {router.post('/:id/feedback', asyncHandler(async (req, res) => {const body = validateRequest(commissionFeedbackSchema, req.body ?? {});const rec = await svc.submitCommissionFeedback(req.params.id, body).catch((err) => { throw mapServiceError(err); });+ reviewEvents.emit('queue:changed');res.status(201).json(rec);}));diff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex 625ed7eff4..1c8886fee8 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -29,6 +29,7 @@ import {postProgressQuerySchema,} from '../lib/postValidation.js';import * as postService from '../services/meatspacePost.js';+import { reviewEvents } from '../services/review.js';// Named at their declaring modules, not through a re-export off meatspacePost.js// (that convenience re-export closed a static import cycle — issue #5690).import { getPostStats } from '../services/meatspacePostStats.js';@@ -114,6 +115,7 @@ router.get('/post/sessions/:id', asyncHandler(async (req, res) => {router.post('/post/sessions', asyncHandler(async (req, res) => {const data = validateRequest(postSessionSubmitSchema, req.body);const session = await postService.submitPostSession(data);+ reviewEvents.emit('queue:changed');res.status(201).json(session);}));@@ -340,6 +342,7 @@ router.post('/post/drill-cache/fill', asyncHandler(async (req, res) => {router.post('/post/training', asyncHandler(async (req, res) => {const data = validateRequest(trainingEntrySchema, req.body);const entry = await trainingService.submitTrainingEntry(data);+ reviewEvents.emit('queue:changed');res.status(201).json(entry);}));@@ -350,6 +353,7 @@ router.post('/post/training', asyncHandler(async (req, res) => {router.post('/post/training/runs', asyncHandler(async (req, res) => {const data = validateRequest(trainingRunSubmitSchema, req.body);const run = await trainingService.submitTrainingRun(data);+ reviewEvents.emit('queue:changed');res.status(201).json(run);}));diff --git a/server/routes/review.js b/server/routes/review.jsindex 4d891927df..266217f61c 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 { reviewQueueQuerySchema, validateRequest } from '../lib/validation.js';import * as reviewService from '../services/review.js';+import { claimQueueDelivery } from '../services/reviewQueueDelivery.js';import { buildQueue, MAX_REVIEW_QUEUE_SNOOZE_MS, resolveQueueItem, triageQueueItem, promoteAskQueueItem } from '../services/reviewQueue.js';const router = express.Router();@@ -64,6 +65,12 @@ const resolveQueueSchema = z.object({}});+const deliverySchema = z.object({ id: z.string().min(1).max(500) });+router.post('/queue/delivery', asyncHandler(async (req, res) => {+ const { id } = validateRequest(deliverySchema, req.body);+ res.json(await claimQueueDelivery(id, 'toast'));+}));+// POST /api/review/queue/resolve — accept a single cross-domain queue row in// place. Source-owned approvals carry an explicit operation so the mutation// revalidates the owning domain instead of using generic Review completion.@@ -73,6 +80,7 @@ router.post('/queue/resolve', asyncHandler(async (req, res) => {const result = operation? (Object.keys(input).length ? await resolveQueueItem(id, operation, input) : await resolveQueueItem(id, operation)): await resolveQueueItem(id);+ reviewService.reviewEvents.emit('queue:changed');res.json(result);}));@@ -98,6 +106,7 @@ const triageQueueSchema = z.object({router.post('/queue/triage', asyncHandler(async (req, res) => {const { id, operation, snoozedUntil } = validateRequest(triageQueueSchema, req.body);const result = await triageQueueItem(id, operation, snoozedUntil ? { snoozedUntil } : {});+ reviewService.reviewEvents.emit('queue:changed');res.json(result);}));@@ -120,6 +129,7 @@ const promoteAskQueueSchema = z.object({router.post('/queue/promote-ask', asyncHandler(async (req, res) => {const { id, target, goalId } = validateRequest(promoteAskQueueSchema, req.body);const result = await promoteAskQueueItem(id, target, goalId);+ reviewService.reviewEvents.emit('queue:changed');res.json(result);}));diff --git a/server/routes/review.test.js b/server/routes/review.test.jsindex 9c0364d9f9..8ce6146660 100644--- a/server/routes/review.test.js+++ b/server/routes/review.test.js@@ -9,7 +9,7 @@ const triageQueueItem = vi.fn();const promoteAskQueueItem = vi.fn();const MAX_REVIEW_QUEUE_SNOOZE_MS = 30 * 24 * 60 * 60 * 1000;-vi.mock('../services/review.js', () => ({}));+vi.mock('../services/review.js', () => ({ reviewEvents: { emit: vi.fn() } }));vi.mock('../services/reviewQueue.js', () => ({buildQueue,MAX_REVIEW_QUEUE_SNOOZE_MS,diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 018ec0adce..2ca6965984 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -1111,6 +1111,9 @@ export async function approveTask(taskId, { now = Date.now() } = {}) {cosEvents.emit('tasks:changed', { type: taskType, action: 'approved', task: tasks[taskIndex] });+ const { removeByMetadata } = await import('./notifications.js');+ await removeByMetadata('taskId', taskId);+return tasks[taskIndex];});}diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 5f1653cd58..400b2ce2c2 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -13,6 +13,9 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { readFileSync as realReadFileSync } from 'node:fs';import { fileURLToPath } from 'url';import { dirname, join } from 'path';+import { removeByMetadata } from './notifications.js';++vi.mock('./notifications.js', () => ({ removeByMetadata: vi.fn().mockResolvedValue(1) }));const mock = vi.hoisted(() => ({files: new Map(),@@ -1739,6 +1742,7 @@ describe('cosTaskStore.approveTask', () => {await addTask({ description: 'need approve', id: 'sys-ap2', approvalRequired: true }, 'internal', { now: T0 });const approved = await approveTask('sys-ap2', { now: T1 });expect(approved.metadata.updatedAt).toBe(new Date(T1).toISOString());+ expect(removeByMetadata).toHaveBeenCalledWith('taskId', 'sys-ap2');});it('rejects a task that does not require approval', async () => {diff --git a/server/services/dailyReminderScheduler.js b/server/services/dailyReminderScheduler.jsindex 4fe2ae977a..000e5fa1b2 100644--- a/server/services/dailyReminderScheduler.js+++ b/server/services/dailyReminderScheduler.js@@ -119,7 +119,7 @@ export function createDailyReminderScheduler({return;}- await notify();+ await notify({ timezone, todayStr });}/**diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex 8764d71e9d..c7debd204a 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -222,7 +222,21 @@ const DEFAULT_LAYOUTS = [],},...INTENT_LAYOUTS.map((l) => ({ ...l, builtIn: true })),-].map(seedDailyActions);+].map(seedDailyActions).map((layout) => {+ // Only first-read defaults change. Saved ids, placement and custom layouts+ // continue to render through compatible filtered wrappers.+ const previews = new Set(['daily-actions', 'review-hub', 'proactive-alerts']);+ if (!layout.widgets.some((id) => previews.has(id))) return layout;+ return {+ ...layout,+ widgets: ['actions', ...layout.widgets.filter((id) => !previews.has(id))],+ grid: [+ { id: 'actions', x: 0, w: 12, order: 0, h: 4 },+ ...layout.grid.filter((item) => !previews.has(item.id))+ .map((item, index) => ({ ...item, order: index + 1 })),+ ],+ };+});const DEFAULT_STATE = {activeLayoutId: 'default',diff --git a/server/services/dashboardLayouts.test.js b/server/services/dashboardLayouts.test.jsindex 9d16d97b85..5bf4135bce 100644--- a/server/services/dashboardLayouts.test.js+++ b/server/services/dashboardLayouts.test.js@@ -36,6 +36,28 @@ describe('dashboardLayouts service', () => {afterEach(() => {});+ it('seeds one Actions preview while preserving saved legacy widget IDs and geometry', async () => {+ const fresh = await svc.getState();+ for (const layout of fresh.layouts) {+ expect(layout.widgets.some(id => ['daily-actions', 'review-hub', 'proactive-alerts'].includes(id))).toBe(false);+ expect(layout.widgets.filter(id => id === 'actions').length).toBeLessThanOrEqual(1);+ }+ expect(fresh.layouts.find(layout => layout.id === 'default').widgets).toContain('actions');+ const layout = {+ id: 'custom', name: 'My layout', builtIn: false,+ widgets: ['daily-actions', 'review-hub', 'proactive-alerts'],+ grid: [+ { id: 'review-hub', x: 0, w: 6, h: 2, order: 0 },+ { id: 'daily-actions', x: 6, w: 6, h: 3, order: 1 },+ { id: 'proactive-alerts', x: 0, w: 12, h: 4, order: 2 },+ ],+ };+ writeJson(STATE_FILE, { activeLayoutId: 'custom', layouts: [layout] });+ const saved = (await svc.getState()).layouts.find(item => item.id === 'custom');+ expect(saved.widgets).toEqual(layout.widgets);+ expect(saved.grid).toEqual(layout.grid);+ });+describe('saveLayout — activateWindow merge behavior', () => {const stateFile = () => STATE_FILE;diff --git a/server/services/meatspacePostReminder.js b/server/services/meatspacePostReminder.jsindex 93c3316fa8..5bfb51a3c9 100644--- a/server/services/meatspacePostReminder.js+++ b/server/services/meatspacePostReminder.js@@ -17,6 +17,7 @@ import { createDailyReminderScheduler } from './dailyReminderScheduler.js';import { isLocalDay } from '../lib/timezone.js';import { getPostConfig, getPostSessions, postConfigEvents } from './meatspacePost.js';import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';+import { claimQueueDelivery } from './reviewQueueDelivery.js';export const POST_REMINDER_EVENT_ID = 'post-daily-reminder';@@ -36,13 +37,16 @@ const scheduler = createDailyReminderScheduler({const sessions = await getPostSessions();return sessions.some(s => isLocalDay(s?.startedAt, timezone, todayStr));},- notify: async () => {+ notify: async ({ todayStr }) => {+ const delivery = await claimQueueDelivery('product:daily-post', 'scheduled', todayStr);+ if (!delivery.claimed) return;await addNotification({type: NOTIFICATION_TYPES.DAILY_POST_REMINDER,title: "Today's POST is still open",description: "You haven't completed a Power On Self Test session today — a quick one keeps your streak alive.",priority: PRIORITY_LEVELS.LOW,- link: '/post/launcher'+ link: '/post/launcher',+ metadata: { actionId: 'product:daily-post', occurrence: todayStr },});console.log(`🔔 POST reminder: nudge sent (today's session incomplete)`);},diff --git a/server/services/meatspacePostReminder.test.js b/server/services/meatspacePostReminder.test.jsindex 2db383822c..1ead2bb12f 100644--- a/server/services/meatspacePostReminder.test.js+++ b/server/services/meatspacePostReminder.test.js@@ -45,6 +45,7 @@ vi.mock('./notifications.js', () => ({PRIORITY_LEVELS: { LOW: 'low' }}));vi.mock('./settings.js', () => ({ settingsEvents: settingsEventEmitter }));+vi.mock('./reviewQueueDelivery.js', () => ({ claimQueueDelivery: vi.fn().mockResolvedValue({ claimed: true, generation: 0 }) }));const { schedule, cancel } = await import('./eventScheduler.js');const { getUserTimezone } = await import('./userTimezone.js');diff --git a/server/services/notifications.js b/server/services/notifications.jsindex c99ddd0b50..5b3a456692 100644--- a/server/services/notifications.js+++ b/server/services/notifications.js@@ -13,6 +13,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';import { EventEmitter } from 'events';import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';+import { adaptNotification } from './reviewActionAdapters.js';const withLock = createMutex();@@ -74,6 +75,7 @@ async function saveNotifications(data) {export async function getNotifications(options = {}) {const data = await loadNotifications();let notifications = [...data.notifications];+ if (!options.includeHidden) notifications = notifications.filter(n => n.historyHidden !== true);// Filter by typeif (options.type) {@@ -101,7 +103,7 @@ export async function getNotifications(options = {}) {*/export async function getUnreadCount() {const data = await loadNotifications();- return data.notifications.filter(n => !n.read).length;+ return data.notifications.filter(n => !n.read && n.historyHidden !== true).length;}/**@@ -116,6 +118,7 @@ export async function getCountsByType() {};for (const n of data.notifications) {+ if (n.historyHidden === true) continue;counts.total++;if (!n.read) counts.unread++;counts.byType[n.type] = (counts.byType[n.type] || 0) + 1;@@ -144,12 +147,20 @@ export async function addNotification(notification) {read: false,metadata: notification.metadata || {}};+ const action = adaptNotification(newNotification);+ if (action) newNotification.metadata = { ...newNotification.metadata, actionId: action.id };data.notifications.push(newNotification);- // Keep only the most recent 500 notifications+ // Bound event history without dropping an unresolved source obligation.if (data.notifications.length > 500) {- data.notifications = data.notifications.slice(-500);+ const recentIds = new Set(data.notifications.filter(n => !n.historyHidden).slice(-500).map(n => n.id));+ data.notifications = data.notifications.filter(n => {+ if (recentIds.has(n.id)) return true;+ if (!adaptNotification(n)) return false;+ n.historyHidden = true;+ return true;+ });}await saveNotifications(data);@@ -174,7 +185,9 @@ export async function removeNotification(id) {return { success: false, error: 'Notification not found' };}- const removed = data.notifications.splice(index, 1)[0];+ const removed = data.notifications[index];+ if (adaptNotification(removed)) removed.historyHidden = true;+ else data.notifications.splice(index, 1);await saveNotifications(data);console.log(`🔔 Notification removed: ${id}`);@@ -244,7 +257,7 @@ export async function markAllAsRead() {let updated = 0;for (const notification of data.notifications) {- if (!notification.read) {+ if (!notification.read && !notification.historyHidden) {notification.read = true;updated++;}@@ -265,9 +278,13 @@ export async function markAllAsRead() {export async function clearAll() {return withLock(async () => {const data = await loadNotifications();- const count = data.notifications.length;+ const count = data.notifications.filter(n => !n.historyHidden).length;- data.notifications = [];+ data.notifications = data.notifications.filter(n => {+ if (!adaptNotification(n)) return false;+ n.historyHidden = true;+ return true;+ });await saveNotifications(data);notificationEvents.emit('cleared');diff --git a/server/services/notifications.test.js b/server/services/notifications.test.jsindex e33e994bc4..2b2f15b347 100644--- a/server/services/notifications.test.js+++ b/server/services/notifications.test.js@@ -38,6 +38,7 @@ import {notificationEvents} from './notifications.js'import { readJSONFile } from '../lib/fileUtils.js'+import { adaptNotification } from './reviewActionAdapters.js'describe('notifications', () => {const baseNotifications = {@@ -85,6 +86,20 @@ describe('notifications', () => {readJSONFile.mockResolvedValue(JSON.parse(JSON.stringify(baseNotifications)))})+ it('keeps a canonical obligation through read and clear, but removes it on domain completion', async () => {+ expect(adaptNotification((await getNotifications()).find(n => n.id === 'n1')).id).toBe('memory:mem-1')+ await markAllAsRead()+ expect(await getUnreadCount()).toBe(0)+ expect(adaptNotification((await getNotifications()).find(n => n.id === 'n1')).id).toBe('memory:mem-1')+ await clearAll()+ expect(await getNotifications()).toEqual([])+ const retained = await getNotifications({ includeHidden: true })+ expect(retained.map(adaptNotification).filter(Boolean).map(item => item.id)).toEqual(['memory:mem-1', 'content:42'])+ expect(await exists(NOTIFICATION_TYPES.MEMORY_APPROVAL, { memoryId: 'mem-1' })).toBe(true)+ await removeByMetadata('memoryId', 'mem-1')+ expect((await getNotifications({ includeHidden: true })).map(n => n.id)).toEqual(['n2'])+ })+describe('NOTIFICATION_TYPES', () => {it('should define expected notification types', () => {expect(NOTIFICATION_TYPES.MEMORY_APPROVAL).toBe('memory_approval')diff --git a/server/services/reviewActionAdapters.js b/server/services/reviewActionAdapters.jsindex 0e46f29bd2..c74b379edc 100644--- a/server/services/reviewActionAdapters.js+++ b/server/services/reviewActionAdapters.js@@ -192,7 +192,8 @@ const notificationReference = (notification, policy) => {};export function adaptNotification(notification) {- if (!notification || notification.read === true) return null;+ // Read and clear apply to event history, never to the source obligation.+ if (!notification) return null;const policy = NOTIFICATION_ACTION_POLICY[notification.type];if (!policy) return null;diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.jsindex 2ddd5f598b..aee97e4769 100644--- a/server/services/reviewQueue.js+++ b/server/services/reviewQueue.js@@ -527,8 +527,8 @@ const PRODUCERS = [async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {// Filter before applying the queue cap. A busy history stream must not// hide a source-owned approval that happens to be older than it.- const unread = await notifications.getNotifications({ unreadOnly: true });- const items = (Array.isArray(unread) ? unread : [])+ const records = await notifications.getNotifications({ includeHidden: true });+ const items = (Array.isArray(records) ? records : []).map(adaptNotification).filter(Boolean);return {@@ -868,6 +868,9 @@ export function applyQueueTriage(items, entries = [], now = new Date(), { includreturn items.flatMap((item) => {const identity = queueActionIdentity(item);const state = byIdentity.get(reviewQueueTriageStore.triageIdentityKey(identity)) || emptyTriageState;+ const delivery = byIdentity.get(reviewQueueTriageStore.triageIdentityKey({+ actionKey: `delivery:${item.id}`, occurrence: item.occurrence, revision: '',+ }));const snoozedUntilMs = state.snoozedUntil ? Date.parse(state.snoozedUntil) : NaN;const snoozed = Number.isFinite(snoozedUntilMs) && snoozedUntilMs > currentTime;const dismissed = state.dismissed && item.isRecommendation === true;@@ -877,7 +880,7 @@ export function applyQueueTriage(items, entries = [], now = new Date(), { includtriage: {snoozedUntil: state.snoozedUntil,dismissed: state.dismissed,- deliveryGeneration: state.deliveryGeneration,+ deliveryGeneration: delivery?.deliveryGeneration ?? state.deliveryGeneration,},triageOperations: triageOperationsFor(item, { snoozed }),}];@@ -1308,7 +1311,7 @@ async function readQueueTriageForProjection({const expired = entry.snoozedUntil && Date.parse(entry.snoozedUntil) <= nowMs;const unused = expired && entry.dismissed !== true && entry.deliveryGeneration === 0;const actionKind = typeof entry.actionKey === 'string' ? entry.actionKey.split(':')[0] : null;- const orphaned = currentKeys && !currentKeys.has(key) && !preservedKinds.has(actionKind);+ const orphaned = currentKeys && !entry.delivery && !currentKeys.has(key) && !preservedKinds.has(actionKind);if (unused || orphaned) removableKeys.add(key);}for (const entry of entries) {diff --git a/server/services/reviewQueueDelivery.js b/server/services/reviewQueueDelivery.jsnew file mode 100644index 0000000000..a5147ee79c--- /dev/null+++ b/server/services/reviewQueueDelivery.js@@ -0,0 +1,55 @@+import { createMutex } from '../lib/asyncMutex.js';+import { listReviewQueueTriage, upsertReviewQueueTriage, triageIdentityKey } from './reviewQueueTriageStore.js';++const withDelivery = createMutex();+const SEVERITY = { low: 0, normal: 1, medium: 1, high: 2, critical: 3 };++// Read state and source text revisions are not new delivery occurrences.+const deliveryIdentity = (item) => ({+ actionKey: `delivery:${item.id}`,+ occurrence: item.occurrence ?? '',+ revision: '',+});++/** Claim before interrupting. A lost client response can suppress a nudge,+ * but a second tab/reload cannot interrupt twice for the same generation. */+export function claimActionDelivery(item, channel) {+ return withDelivery(async () => {+ const identity = deliveryIdentity(item);+ const key = triageIdentityKey(identity);+ const entries = await listReviewQueueTriage();+ const previous = entries.find((entry) => triageIdentityKey(entry) === key);+ const severity = SEVERITY[item.severity] ?? 1;+ const escalated = previous?.delivery && severity > previous.delivery.severity;+ const generation = (previous?.deliveryGeneration ?? 0) + (escalated ? 1 : 0);+ if (previous?.delivery?.channels?.[channel] === generation) return { claimed: false, generation };+ await upsertReviewQueueTriage({+ ...identity,+ deliveryGeneration: generation,+ delivery: {+ severity: Math.max(severity, previous?.delivery?.severity ?? 0),+ channels: { ...previous?.delivery?.channels, [channel]: generation },+ },+ });+ return { claimed: true, generation };+ });+}++/** Callers cannot grant themselves reminder consent or a new occurrence. */+export async function claimQueueDelivery(id, channel = 'toast', occurrence) {+ const { buildQueue } = await import('./reviewQueue.js');+ const queue = await buildQueue({ query: { view: 'today' } });+ const item = queue.items.find((candidate) => candidate.id === id);+ if (!item) return { claimed: false };+ if (occurrence !== undefined && item.occurrence !== occurrence) return { claimed: false };+ if (channel === 'toast') {+ const { getPostConfig } = await import('./meatspacePost.js');+ if (id !== 'product:daily-post' || !(await getPostConfig()).reminder?.enabled) return { claimed: false };+ const { getNotifications } = await import('./notifications.js');+ const notices = await getNotifications();+ if (item.source !== 'product' || !notices.some((notice) =>+ notice.metadata?.actionId === id && notice.metadata?.occurrence === item.occurrence+ && notice.type === 'daily_post_reminder')) return { claimed: false };+ }+ return claimActionDelivery(item, channel);+}diff --git a/server/services/reviewQueueDelivery.test.js b/server/services/reviewQueueDelivery.test.jsnew file mode 100644index 0000000000..1b3ccd1bcb--- /dev/null+++ b/server/services/reviewQueueDelivery.test.js@@ -0,0 +1,96 @@+import { rm } from 'node:fs/promises';+import { join } from 'node:path';+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';++const mock = vi.hoisted(() => ({ buildQueue: vi.fn(), getNotifications: vi.fn(), getPostConfig: vi.fn() }));+vi.mock('./meatspacePost.js', () => ({ getPostConfig: mock.getPostConfig }));+vi.mock('./cosState.js', () => ({ getDomainAutonomyMode: vi.fn().mockResolvedValue('execute') }));+vi.mock('./domainUsage.js', () => ({+ getDomainBudgetStatus: vi.fn().mockResolvedValue({ withinBudget: true }),+ recordDomainUsage: vi.fn().mockResolvedValue(),+}));+vi.mock('./memoryBackend.js', () => ({ peekMemory: vi.fn().mockResolvedValue(null) }));+vi.mock('./reviewQueue.js', () => ({ buildQueue: mock.buildQueue }));+vi.mock('./notifications.js', () => ({ getNotifications: mock.getNotifications }));+vi.mock('../lib/fileUtils.js', async (original) => makePathsProxy(await original(), {+ dataRoot: () => lazyTempDataRoot('action-delivery-'),+}));++import { claimActionDelivery, claimQueueDelivery } from './reviewQueueDelivery.js';+import { forwardNotification } from './telegramForward.js';+import { listReviewQueueTriage, resetReviewQueueTriageStore } from './reviewQueueTriageStore.js';++const action = { id: 'health:disk', occurrence: 'incident-1', revision: 'v1', severity: 'high' };+beforeEach(async () => {+ resetReviewQueueTriageStore();+ await rm(join(lazyTempDataRoot('action-delivery-'), 'review-queue-triage.json'), { force: true });+ mock.getNotifications.mockResolvedValue([]);+ mock.getPostConfig.mockResolvedValue({ reminder: { enabled: true } });+ mock.buildQueue.mockResolvedValue({ items: [] });+});+afterAll(cleanupTempDataRoots);++describe('durable action delivery', () => {+ it('deduplicates correlated forwards across transports/reloads without changing legacy forwarding or type gates', async () => {+ const sendMessage = vi.fn().mockResolvedValue({});+ const deps = { cachedForwardTypes: [], sendMessage };+ const notice = { type: 'memory_approval', title: 'Review memory', link: '/cos/memory', metadata: { memoryId: 'example-memory' } };+ mock.buildQueue.mockResolvedValue({ items: [{ id: 'memory:example-memory', occurrence: null, severity: 'high' }] });+ await forwardNotification(notice, { ...deps, cachedForwardTypes: ['briefing_ready'] });+ expect(await listReviewQueueTriage()).toEqual([]);+ await forwardNotification(notice, deps);+ resetReviewQueueTriageStore();+ await forwardNotification(notice, deps);+ expect(sendMessage).toHaveBeenCalledTimes(1);+ mock.buildQueue.mockResolvedValue({ items: [{ id: 'memory:example-memory', occurrence: null, severity: 'critical' }] });+ await forwardNotification(notice, deps);+ expect(sendMessage).toHaveBeenCalledTimes(2);+ const legacy = { type: 'agent_warning', title: 'Legacy context', metadata: {} };+ await forwardNotification(legacy, deps);+ await forwardNotification(legacy, deps);+ expect(sendMessage).toHaveBeenCalledTimes(4);+ });++ it('claims once across tabs and reloads, ignores text revisions, and advances one generation only on escalation', async () => {+ const claims = await Promise.all([claimActionDelivery(action, 'toast'), claimActionDelivery(action, 'toast')]);+ expect(claims.map(result => result.claimed)).toEqual([true, false]);+ resetReviewQueueTriageStore();+ expect(await claimActionDelivery({ ...action, revision: 'v2' }, 'toast')).toEqual({ claimed: false, generation: 0 });+ expect(await claimActionDelivery({ ...action, severity: 'critical' }, 'toast')).toEqual({ claimed: true, generation: 1 });+ expect(await claimActionDelivery(action, 'toast')).toEqual({ claimed: false, generation: 1 });+ expect(await claimActionDelivery({ ...action, severity: 'critical' }, 'telegram')).toEqual({ claimed: true, generation: 1 });+ const markers = await listReviewQueueTriage();+ expect(markers).toHaveLength(1);+ expect(markers[0]).toMatchObject({ deliveryGeneration: 1, delivery: { channels: { toast: 1, telegram: 1 } } });+ expect(markers[0]).not.toHaveProperty('title');+ expect(await claimActionDelivery({ ...action, occurrence: 'incident-2' }, 'toast')).toEqual({ claimed: true, generation: 0 });+ });++ it('allows product toasts only after an opted-in reminder for the same occurrence, and rechecks snooze/completion', async () => {+ const product = { id: 'product:daily-post', source: 'product', occurrence: '2026-09-20', severity: 'high' };+ mock.buildQueue.mockResolvedValue({ items: [product] });+ expect(await claimQueueDelivery(product.id)).toEqual({ claimed: false });+ mock.getNotifications.mockResolvedValue([{+ type: 'daily_post_reminder', metadata: { actionId: product.id, occurrence: '2026-09-19' },+ }]);+ expect(await claimQueueDelivery(product.id)).toEqual({ claimed: false });+ mock.getNotifications.mockResolvedValue([{+ type: 'daily_post_reminder', metadata: { actionId: product.id, occurrence: product.occurrence },+ }]);+ expect(await claimQueueDelivery(product.id)).toEqual({ claimed: true, generation: 0 });+ mock.getPostConfig.mockResolvedValue({ reminder: { enabled: false } });+ expect(await claimQueueDelivery(product.id)).toEqual({ claimed: false });+ mock.getPostConfig.mockResolvedValue({ reminder: { enabled: true } });+ resetReviewQueueTriageStore();+ expect(await claimQueueDelivery(product.id)).toEqual({ claimed: false, generation: 0 });+ mock.buildQueue.mockResolvedValue({ items: [] });+ expect(await claimQueueDelivery(product.id, 'telegram')).toEqual({ claimed: false });+ });++ it('does not claim delivery when the queue is unavailable', async () => {+ mock.buildQueue.mockRejectedValue(new Error('queue unavailable'));+ await expect(claimQueueDelivery(action.id)).rejects.toThrow('queue unavailable');+ expect(await listReviewQueueTriage()).toEqual([]);+ });+});diff --git a/server/services/reviewQueueTriageStore.js b/server/services/reviewQueueTriageStore.jsindex 8b6f7c63d3..d2b2a7d03b 100644--- a/server/services/reviewQueueTriageStore.js+++ b/server/services/reviewQueueTriageStore.js@@ -56,6 +56,14 @@ export function normalizeReviewQueueTriage(value = {}, { rejectInvalid = false }snoozedUntil,dismissed: value.dismissed === true,deliveryGeneration,+ ...(value.delivery && typeof value.delivery === 'object' ? {+ delivery: {+ severity: Number.isSafeInteger(value.delivery.severity) ? value.delivery.severity : 0,+ channels: Object.fromEntries(['toast', 'telegram', 'scheduled']+ .filter((channel) => Number.isSafeInteger(value.delivery.channels?.[channel]) && value.delivery.channels[channel] >= 0)+ .map((channel) => [channel, value.delivery.channels[channel]])),+ },+ } : {}),};}@@ -95,7 +103,7 @@ function makePgBackend(db) {name: 'postgres',async list() {const { rows } = await db.query(- `SELECT action_key, occurrence, revision, snoozed_until, dismissed, delivery_generation+ `SELECT action_key, occurrence, revision, snoozed_until, dismissed, delivery_generation, deliveryFROM review_queue_triageORDER BY action_key, occurrence, revision`,);@@ -106,18 +114,20 @@ function makePgBackend(db) {snoozedUntil: row.snoozed_until,dismissed: row.dismissed,deliveryGeneration: row.delivery_generation,+ delivery: row.delivery,})).filter(Boolean);},async upsert(value) {await db.query(`INSERT INTO review_queue_triage- (action_key, occurrence, revision, snoozed_until, dismissed, delivery_generation)- VALUES ($1, $2, $3, $4, $5, $6)+ (action_key, occurrence, revision, snoozed_until, dismissed, delivery_generation, delivery)+ VALUES ($1, $2, $3, $4, $5, $6, $7)ON CONFLICT (action_key, occurrence, revision) DO UPDATE SETsnoozed_until = EXCLUDED.snoozed_until,dismissed = EXCLUDED.dismissed,- delivery_generation = EXCLUDED.delivery_generation`,- [value.actionKey, value.occurrence, value.revision, value.snoozedUntil, value.dismissed, value.deliveryGeneration],+ delivery_generation = EXCLUDED.delivery_generation,+ delivery = EXCLUDED.delivery`,+ [value.actionKey, value.occurrence, value.revision, value.snoozedUntil, value.dismissed, value.deliveryGeneration, value.delivery || null],);},async remove(value) {diff --git a/server/services/socket.js b/server/services/socket.jsindex 9131b77b47..66619f003b 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -534,6 +534,16 @@ let reviewForwardingSetup = false;function setupReviewEventForwarding() {if (reviewForwardingSetup) return;reviewForwardingSetup = true;+ // Global invalidations reach the bell/dashboard even without a CoS room+ // subscription. They carry no record payload and are never peer-forwarded.+ for (const event of ['tasks:changed', 'tasks:user:changed', 'tasks:cos:changed', 'agent:completed', 'agent:feedback', 'memory:approved', 'memory:rejected']) {+ cosEvents.on(event, () => {+ if (ioInstance) ioInstance.emit('review:queue:changed');+ });+ }+ reviewEvents.on('queue:changed', () => {+ if (ioInstance) ioInstance.emit('review:queue:changed');+ });reviewEvents.on('item:created', (data) => {if (ioInstance) ioInstance.emit('review:item:created', data?.metadata?.privateSecurity ? { id: data.id, metadata: { privateSecurity: true } } : data);});diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 8047a43d55..4da1dffac4 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -84,6 +84,7 @@ import { spawnPm2 } from './pm2.js';import { getAppById, notifyAppsChanged, resolvePm2HomeForProcess } from './apps.js';import { logAction } from './history.js';import { cosEvents } from './cosEvents.js';+import { reviewEvents } from './review.js';import { beeperSocketEvents } from './beeperSocketEvents.js';import { mediaJobEvents } from './mediaJobQueue/index.js';import { audioGenEvents } from './audioGen/events.js';@@ -279,6 +280,16 @@ describe('socket.js — initSocket', () => {expect(socket.emitted).toContainEqual(['cos:tasks:changed', payload]);});+ it('invalidates Actions globally without exposing domain payloads or requiring a CoS subscription', () => {+ for (const [event, listener] of cosEvents.on.mock.calls) {+ if (event === 'tasks:changed') listener({ type: 'user', task: { id: 'example', description: 'Private source text' } });+ }+ expect(io.emitted).toContainEqual(['review:queue:changed']);+ io.emitted.length = 0;+ reviewEvents.on.mock.calls.find(([event]) => event === 'queue:changed')[1]({ private: 'not forwarded' });+ expect(io.emitted).toEqual([['review:queue:changed']]);+ });+// The three agent-record events leave through the same listing projection as// `GET /api/cos/agents`. Without it the socket refills the CoS agents list with// unprojected rows — transcript and whole pasted prompt — moments after thediff --git a/server/services/telegramForward.js b/server/services/telegramForward.jsindex b92c1e697f..8b69fc206e 100644--- a/server/services/telegramForward.js+++ b/server/services/telegramForward.js@@ -18,6 +18,7 @@ import { getDomainAutonomyMode } from './cosState.js';import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';import { peekMemory } from './memoryBackend.js';import { buildNotificationMessage, isMemoryApprovalNotification } from '../lib/telegramMessage.js';+import { adaptNotification } from './reviewActionAdapters.js';const DOMAIN = 'messages';@@ -72,6 +73,15 @@ async function shouldForward(notification, cachedForwardTypes) {*/export async function forwardNotification(notification, { cachedForwardTypes, sendMessage }) {if (!await shouldForward(notification, cachedForwardTypes)) return;+ // Only proven references participate. Legacy uncorrelated forwards retain+ // their existing type/autonomy/budget behavior.+ const action = adaptNotification(notification);+ const actionId = action?.id || (notification.type === 'daily_post_reminder'+ && notification.metadata?.actionId === 'product:daily-post' ? 'product:daily-post' : null);+ if (actionId) {+ const { claimQueueDelivery } = await import('./reviewQueueDelivery.js');+ if (!(await claimQueueDelivery(actionId, 'telegram', notification.metadata?.occurrence)).claimed) return;+ }// The approval body is the one piece of the message that needs I/O, so it is// resolved here and handed to the pure builder.