Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix(cos): name skipped tasks in health alert and add resolution controls in learning tab

[._.]/ Adam Eivy597c1261995a
diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsx
index 6483cc7cc1..b6d931bd73 100644
--- a/client/src/components/cos/tabs/LearningTab.jsx
+++ b/client/src/components/cos/tabs/LearningTab.jsx
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
+import { Link } from 'react-router';
import {
Brain,
RefreshCw,
@@ -6,6 +7,7 @@ import {
TrendingDown,
Clock,
AlertTriangle,
+ Check,
CheckCircle,
XCircle,
SkipForward,
@@ -185,16 +187,38 @@ export default function LearningTab() {
setBackfilling(false);
}, [loadData]);
+ const [resettingAll, setResettingAll] = useState(false);
+
const handleResetTaskType = useCallback(async (taskType) => {
setResettingType(taskType);
const result = await api.resetCosTaskTypeLearning(taskType).catch(() => null);
if (result?.reset) {
- toast.success(`Reset learning data for ${taskType}`);
+ toast.success(`Reset learning data for ${taskType} — auto-approval re-enabled`);
await loadData();
+ } else {
+ toast.error(`Failed to reset learning data for ${taskType}`);
}
setResettingType(null);
}, [loadData]);
+ const handleResetAllLowConfidence = useCallback(async () => {
+ const lowItems = confidence?.levels?.low || [];
+ if (lowItems.length === 0) return;
+ setResettingAll(true);
+ let successCount = 0;
+ for (const item of lowItems) {
+ const result = await api.resetCosTaskTypeLearning(item.taskType).catch(() => null);
+ if (result?.reset) successCount++;
+ }
+ if (successCount > 0) {
+ toast.success(`Marked ${successCount} task type${successCount > 1 ? 's' : ''} resolved — auto-approval re-enabled`);
+ await loadData();
+ } else {
+ toast.error('Failed to reset task types');
+ }
+ setResettingAll(false);
+ }, [confidence, loadData]);
+
const toggleSection = useCallback((section) => {
setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
}, []);
@@ -469,16 +493,36 @@ export default function LearningTab() {
</div>
{[
- { items: confidence.levels.low, borderClass: 'border-port-warning/30', bgClass: 'bg-port-warning/10', textClass: 'text-port-warning', Icon: ShieldAlert, title: 'Requires Approval', desc: 'These task types have low success rates and will require human approval before spawning' },
+ { items: confidence.levels.low, borderClass: 'border-port-warning/30', bgClass: 'bg-port-warning/10', textClass: 'text-port-warning', Icon: ShieldAlert, title: 'Requires Approval', desc: 'These task types have low success rates and will require human approval before spawning. Reset metrics to mark resolved and re-enable auto-approval.' },
{ items: confidence.levels.high, borderClass: 'border-port-success/30', bgClass: 'bg-port-success/10', textClass: 'text-port-success', Icon: ShieldCheck, title: 'High Confidence', desc: 'Consistently successful — auto-approved without hesitation' }
].filter(g => g.items?.length > 0).map(({ items, borderClass, bgClass, textClass, Icon, title, desc }) => (
<div key={title} className={`bg-port-card border ${borderClass} rounded-lg overflow-hidden`}>
- <div className={`px-4 py-2 ${bgClass} border-b border-port-border`}>
- <span className={`text-sm font-medium ${textClass} flex items-center gap-2`}>
- <Icon size={14} />
- {title} ({items.length})
- </span>
- <p className="text-xs text-gray-500 mt-0.5">{desc}</p>
+ <div className={`px-4 py-2 ${bgClass} border-b border-port-border flex flex-col sm:flex-row sm:items-center justify-between gap-2`}>
+ <div>
+ <span className={`text-sm font-medium ${textClass} flex items-center gap-2`}>
+ <Icon size={14} />
+ {title} ({items.length})
+ </span>
+ <p className="text-xs text-gray-500 mt-0.5">
+ {desc}
+ {title === 'Requires Approval' && (
+ <> &middot; Review pending tasks on the <Link to="/cos/tasks" className="text-port-accent hover:underline">Tasks tab</Link>.</>
+ )}
+ </p>
+ </div>
+ {title === 'Requires Approval' && items.length > 1 && (
+ <button
+ type="button"
+ onClick={handleResetAllLowConfidence}
+ disabled={resettingAll || !!resettingType}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1 text-xs bg-port-success/10 hover:bg-port-success/20 text-port-success border border-port-success/30 rounded transition-colors disabled:opacity-50 shrink-0 self-start sm:self-auto min-h-[32px]"
+ title="Mark all resolved — reset learning data to re-enable auto-approval"
+ aria-label="Mark all resolved"
+ >
+ <Check size={12} className={resettingAll ? 'animate-spin' : ''} />
+ {resettingAll ? 'Resolving all…' : 'Mark all resolved'}
+ </button>
+ )}
</div>
<div className="divide-y divide-port-border">
{items.map((t) => (
@@ -487,6 +531,19 @@ export default function LearningTab() {
<div className="flex items-center gap-3">
<span className="text-xs text-gray-500">{runsLabel(t)}</span>
<span className={`text-sm ${textClass} font-medium`}>{t.successRate}%</span>
+ {title === 'Requires Approval' && (
+ <button
+ type="button"
+ onClick={() => handleResetTaskType(t.taskType)}
+ disabled={resettingType === t.taskType || resettingAll}
+ className="inline-flex items-center gap-1 px-2.5 py-1 text-xs bg-port-success/10 hover:bg-port-success/20 text-port-success border border-port-success/30 rounded transition-colors disabled:opacity-50 min-h-[32px]"
+ title={`Mark ${t.taskType} resolved — reset learning metrics to restore auto-approval`}
+ aria-label={`Mark ${t.taskType} resolved`}
+ >
+ <Check size={12} className={resettingType === t.taskType ? 'animate-spin' : ''} />
+ {resettingType === t.taskType ? 'Resolving…' : 'Mark resolved'}
+ </button>
+ )}
</div>
</div>
))}
@@ -576,6 +633,17 @@ export default function LearningTab() {
<span className="text-sm font-mono text-port-error w-12 text-right">
{item.successRate}%
</span>
+ <button
+ type="button"
+ onClick={() => handleResetTaskType(item.taskType)}
+ disabled={resettingType === item.taskType}
+ className="inline-flex items-center gap-1 px-2 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded transition-colors disabled:opacity-50 min-h-[32px]"
+ title="Reset learning data to re-enable this task type"
+ aria-label={`Reset ${item.taskType}`}
+ >
+ <RotateCcw size={12} className={resettingType === item.taskType ? 'animate-spin' : ''} />
+ Reset
+ </button>
</div>
</div>
))}
diff --git a/client/src/components/cos/tabs/LearningTab.requiresApproval.test.jsx b/client/src/components/cos/tabs/LearningTab.requiresApproval.test.jsx
new file mode 100644
index 0000000000..36b5564579
--- /dev/null
+++ b/client/src/components/cos/tabs/LearningTab.requiresApproval.test.jsx
@@ -0,0 +1,97 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router';
+import LearningTab from './LearningTab';
+
+const api = vi.hoisted(() => ({
+ getCosLearning: vi.fn(),
+ getCosLearningPerformance: vi.fn(),
+ getCosLearningSkipped: vi.fn(),
+ getCosLearningDurations: vi.fn(),
+ getCosLearningRouting: vi.fn(),
+ getCosLearningConfidence: vi.fn(),
+ getCosFeedbackStats: vi.fn(),
+ getDismissedCosRecommendations: vi.fn(),
+ resetCosTaskTypeLearning: vi.fn(),
+}));
+
+const toast = vi.hoisted(() => ({
+ success: vi.fn(),
+ error: vi.fn(),
+}));
+
+vi.mock('../../../services/api', () => api);
+vi.mock('../../ui/Toast', () => ({ default: toast }));
+
+const renderTab = () => render(
+ <MemoryRouter>
+ <LearningTab />
+ </MemoryRouter>
+);
+
+describe('LearningTab — Requires Approval controls', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getCosLearning.mockResolvedValue({
+ totals: { completed: 60, succeeded: 5, avgDurationMs: 60000 },
+ recommendations: []
+ });
+ api.getCosLearningPerformance.mockResolvedValue({
+ topPerformers: [],
+ needsAttention: [{ taskType: 'internal-task', successRate: 10, completed: 30, avgDurationMin: 5 }],
+ skipped: []
+ });
+ api.getCosLearningSkipped.mockResolvedValue({ skippedCount: 0, skippedTypes: [] });
+ api.getCosLearningDurations.mockResolvedValue({});
+ api.getCosLearningRouting.mockResolvedValue({ byModelTier: {} });
+ api.getCosFeedbackStats.mockResolvedValue({ total: 0 });
+ api.getDismissedCosRecommendations.mockResolvedValue({ dismissed: [] });
+ api.resetCosTaskTypeLearning.mockResolvedValue({ reset: true });
+ api.getCosLearningConfidence.mockResolvedValue({
+ levels: {
+ high: [],
+ medium: [],
+ low: [
+ { taskType: 'internal-task', successRate: 10, completed: 30, rateSource: 'windowed', windowedCompleted: 30 },
+ { taskType: 'self-improve:claim-issue', successRate: 3, completed: 30, rateSource: 'windowed', windowedCompleted: 30 },
+ ],
+ new: []
+ },
+ thresholds: { highThreshold: 80, lowThreshold: 50, minSamples: 5 },
+ summary: { high: 0, medium: 0, low: 2, new: 0, total: 2, requireApproval: 2 }
+ });
+ });
+
+ it('renders Requires Approval table with Mark resolved on each row and link to Tasks tab', async () => {
+ const user = userEvent.setup();
+ renderTab();
+
+ expect(await screen.findByText('Requires Approval (2)')).toBeInTheDocument();
+ expect(screen.getAllByText('internal-task').length).toBeGreaterThanOrEqual(1);
+ expect(screen.getByText('self-improve:claim-issue')).toBeInTheDocument();
+
+ const tasksLink = screen.getByRole('link', { name: 'Tasks tab' });
+ expect(tasksLink).toBeInTheDocument();
+ expect(tasksLink).toHaveAttribute('href', '/cos/tasks');
+
+ const markInternalTaskBtn = screen.getByRole('button', { name: 'Mark internal-task resolved' });
+ expect(markInternalTaskBtn).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Mark self-improve:claim-issue resolved' })).toBeInTheDocument();
+
+ await user.click(markInternalTaskBtn);
+ expect(api.resetCosTaskTypeLearning).toHaveBeenCalledWith('internal-task');
+ });
+
+ it('provides Mark all resolved button when multiple items require approval', async () => {
+ const user = userEvent.setup();
+ renderTab();
+
+ const markAllButton = await screen.findByRole('button', { name: 'Mark all resolved' });
+ expect(markAllButton).toBeInTheDocument();
+
+ await user.click(markAllButton);
+ expect(api.resetCosTaskTypeLearning).toHaveBeenCalledWith('internal-task');
+ expect(api.resetCosTaskTypeLearning).toHaveBeenCalledWith('self-improve:claim-issue');
+ });
+});
diff --git a/client/src/pages/Review.jsx b/client/src/pages/Review.jsx
index 8187878815..2f54c340c7 100644
--- a/client/src/pages/Review.jsx
+++ b/client/src/pages/Review.jsx
@@ -1277,37 +1277,56 @@ function ActionDetail({ item, onClose, onResolve, onTriage, triagePending = fals
)}
<QueueInvestigation item={item} />
- {item.source === 'health' && <p className="text-sm text-gray-400">Mark resolved after correcting the issue. Earlier runs will no longer count toward run-based alerts; new evidence can raise another alert.</p>}
+ {item.source === 'health' && (
+ <div className="bg-port-card border border-port-border/60 rounded-lg p-3 text-xs text-gray-400 leading-relaxed">
+ Mark resolved after correcting the issue. Earlier runs will no longer count toward run-based alerts; new evidence can raise another alert.
+ </div>
+ )}
{item.source === 'feedback' && item.available !== false && item.availability !== 'unavailable' && (
<AgentFeedbackReview key={item.sourceRef} item={item} onSaved={async () => {
await onSaved?.();
onClose();
}} />
)}
- {item.source !== 'feedback' && operations.length > 0 && (
- <section className="flex flex-wrap gap-2">
- {operations.map((operation) => (
- <button key={operation.id} type="button" onClick={() => resolve(operation.id)} className="inline-flex items-center gap-2 rounded bg-port-success/10 border border-port-success/30 px-3 py-2 text-sm text-port-success hover:bg-port-success/20">
- <Check size={14} /> {operation.label}
- </button>
- ))}
- </section>
- )}
+ {item.source !== 'feedback' && (operations.length > 0 || item.drillTo || item.triageOperations?.length > 0) && (
+ <footer className="pt-4 border-t border-port-border space-y-3">
+ {operations.length > 0 && (
+ <section className="flex flex-wrap gap-2">
+ {operations.map((operation) => (
+ <button
+ key={operation.id}
+ type="button"
+ onClick={() => resolve(operation.id)}
+ className="inline-flex items-center gap-2 rounded bg-port-success/10 border border-port-success/30 px-3.5 py-2 text-sm font-medium text-port-success hover:bg-port-success/20 transition-colors"
+ >
+ <Check size={14} /> {operation.label}
+ </button>
+ ))}
+ </section>
+ )}
- <QueueTriageControls
- item={item}
- onTriage={async (...args) => {
- const ok = await onTriage?.(...args);
- if (ok) onClose();
- return ok;
- }}
- disabled={triagePending}
- />
+ <div className="flex flex-wrap items-center justify-between gap-3 pt-1">
+ <QueueTriageControls
+ item={item}
+ onTriage={async (...args) => {
+ const ok = await onTriage?.(...args);
+ if (ok) onClose();
+ return ok;
+ }}
+ disabled={triagePending}
+ />
- {item.drillTo && (
- <button type="button" onClick={() => { onClose(); onDrill(item); }} className="inline-flex items-center gap-2 text-sm text-port-accent hover:underline">
- <ExternalLink size={14} /> Open source editor
- </button>
+ {item.drillTo && (
+ <button
+ type="button"
+ onClick={() => { onClose(); onDrill(item); }}
+ className="inline-flex items-center gap-1.5 text-xs font-medium text-port-accent hover:text-port-accent/80 hover:underline py-1.5 px-2.5 rounded border border-port-accent/30 hover:bg-port-accent/10 transition-colors"
+ >
+ <ExternalLink size={13} /> {item.drillLabel || (item.source === 'health' ? (item.drillTo?.startsWith('/cos/learning') ? 'Open Learning' : 'View details') : 'Open source')}
+ </button>
+ )}
+ </div>
+ </footer>
)}
</div>
</Drawer>
diff --git a/server/routes/cosLearningRoutes.js b/server/routes/cosLearningRoutes.js
index 02ef558036..4d50ac49fe 100644
--- a/server/routes/cosLearningRoutes.js
+++ b/server/routes/cosLearningRoutes.js
@@ -57,6 +57,7 @@ router.post('/learning/reset/:taskType', asyncHandler(async (req, res) => {
if (!result.reset) {
throw new ServerError(`Task type "${taskType}" not found in learning data`, { status: 404, code: 'NOT_FOUND' });
}
+ import('../services/reviewQueue.js').then(m => m.__resetAlertsCache?.()).catch(() => {});
res.json(result);
}));
diff --git a/server/services/proactiveAlertSources.js b/server/services/proactiveAlertSources.js
index ae79796bb3..ca400eef6b 100644
--- a/server/services/proactiveAlertSources.js
+++ b/server/services/proactiveAlertSources.js
@@ -145,29 +145,45 @@ async function checkLearningHealth(perf) {
const alerts = [];
const recentAttention = (perf.needsAttention || []).filter(hasCurrentPerformanceEvidence);
- const skipped = (perf.skipped || []).filter(hasCurrentPerformanceEvidence).length;
- const critical = recentAttention.filter(item => item.successRate < 40).length;
+ const skippedList = (perf.skipped || []).filter(hasCurrentPerformanceEvidence);
+ const skipped = skippedList.length;
+ const criticalList = recentAttention.filter(item => item.successRate < 40);
+ const critical = criticalList.length;
const warning = recentAttention.length - critical;
if (skipped > 0) {
+ const names = skippedList.map(item => item.taskType).filter(Boolean);
+ const namesFormatted = names.slice(0, 3).join(', ') + (names.length > 3 ? `, +${names.length - 3} more` : '');
alerts.push({
id: alertId('learning_skipped', 'all'),
type: 'learning_health',
severity: 'high',
- title: `${skipped} task type${skipped > 1 ? 's' : ''} being skipped`,
- detail: 'Very low success rates caused automatic skip — review task configuration',
+ title: namesFormatted
+ ? `${skipped} task type${skipped > 1 ? 's' : ''} being skipped: ${namesFormatted}`
+ : `${skipped} task type${skipped > 1 ? 's' : ''} being skipped`,
+ detail: namesFormatted
+ ? `Very low success rates caused automatic skip (${namesFormatted}) — review task configuration`
+ : 'Very low success rates caused automatic skip — review task configuration',
link: '/cos/learning',
- metadata: { skipped, critical },
+ metadata: { skipped, critical, ...(names.length > 0 ? { taskTypes: names } : {}) },
+ evidence: { skipped, taskTypes: [...names].sort() },
});
} else if (critical > 0) {
+ const names = criticalList.map(item => item.taskType).filter(Boolean);
+ const namesFormatted = names.slice(0, 3).join(', ') + (names.length > 3 ? `, +${names.length - 3} more` : '');
alerts.push({
id: alertId('learning_critical', 'all'),
type: 'learning_health',
severity: 'medium',
- title: `${critical} task type${critical > 1 ? 's' : ''} need attention`,
- detail: `Success rates below ${SUCCESS_RATE_WARNING}% — may need provider or prompt adjustments`,
+ title: namesFormatted
+ ? `${critical} task type${critical > 1 ? 's' : ''} need attention: ${namesFormatted}`
+ : `${critical} task type${critical > 1 ? 's' : ''} need attention`,
+ detail: namesFormatted
+ ? `Success rates below ${SUCCESS_RATE_WARNING}% (${namesFormatted}) — may need provider or prompt adjustments`
+ : `Success rates below ${SUCCESS_RATE_WARNING}% — may need provider or prompt adjustments`,
link: '/cos/learning',
- metadata: { critical, warning },
+ metadata: { critical, warning, ...(names.length > 0 ? { taskTypes: names } : {}) },
+ evidence: { critical, taskTypes: [...names].sort() },
});
}
diff --git a/server/services/proactiveAlerts.test.js b/server/services/proactiveAlerts.test.js
index ab9cc5f057..91f46a5803 100644
--- a/server/services/proactiveAlerts.test.js
+++ b/server/services/proactiveAlerts.test.js
@@ -175,7 +175,34 @@ describe('proactiveAlerts — current task performance', () => {
detail: '20% success across the last 5 runs'
});
expect(alerts.find(a => a.type === 'learning_health')).toMatchObject({
- metadata: { skipped: 1, critical: 1 }
+ title: '1 task type being skipped: self-improve:example',
+ detail: 'Very low success rates caused automatic skip (self-improve:example) — review task configuration',
+ metadata: { skipped: 1, critical: 1, taskTypes: ['self-improve:example'] }
+ });
+ });
+
+ it('names multiple skipped task types in title and detail', async () => {
+ const task1 = {
+ taskType: 'internal-task',
+ successRate: 10,
+ completed: 30,
+ rateSource: 'windowed',
+ windowedCompleted: 30
+ };
+ const task2 = {
+ taskType: 'self-improve:claim-issue',
+ successRate: 3,
+ completed: 30,
+ rateSource: 'windowed',
+ windowedCompleted: 30
+ };
+ mock.performance = { needsAttention: [task1, task2], skipped: [task1, task2] };
+
+ const { alerts } = await generateAlerts();
+ expect(alerts.find(a => a.type === 'learning_health')).toMatchObject({
+ title: '2 task types being skipped: internal-task, self-improve:claim-issue',
+ detail: 'Very low success rates caused automatic skip (internal-task, self-improve:claim-issue) — review task configuration',
+ metadata: { skipped: 2, critical: 2, taskTypes: ['internal-task', 'self-improve:claim-issue'] }
});
});
});
diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.js
index b18066e69b..67ca9e5f19 100644
--- a/server/services/reviewQueue.js
+++ b/server/services/reviewQueue.js
@@ -680,6 +680,9 @@ const PRODUCERS = [
const alertType = typeof alert.type === 'string' && alert.type.trim()
? alert.type.trim()
: null;
+ const drillTo = alert.type === 'system_resource'
+ ? '/system-resources/overview'
+ : alert.link || '/system-resources/overview';
return {
id: `health:${alert.id}`,
...(alert.investigation ? { investigation: alert.investigation } : {}),
@@ -690,9 +693,12 @@ const PRODUCERS = [
summary: (alert.detail || alert.message || '').slice(0, 200),
timestamp: alert.timestamp || null,
severity: alert.severity === 'critical' ? 'critical' : 'high',
- drillTo: alert.type === 'system_resource'
- ? '/system-resources/overview'
- : alert.link || '/system-resources/overview',
+ drillTo,
+ drillLabel: drillTo.startsWith('/cos/learning')
+ ? 'Open Learning'
+ : drillTo.startsWith('/system-resources/overview')
+ ? 'Open system resources'
+ : 'View details',
...(alertType ? { meta: { alertType } } : {})
};
}
diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.js
index 9efb94fbcb..09eadfe5ba 100644
--- a/server/services/reviewQueue.test.js
+++ b/server/services/reviewQueue.test.js
@@ -592,10 +592,22 @@ describe('reviewQueue.buildQueue', () => {
const queue = await buildQueue();
const healthRows = queue.items.filter(i => i.source === 'health');
expect(healthRows).toHaveLength(1);
- expect(healthRows[0]).toMatchObject({ severity: 'critical', summary: '95% used', drillTo: '/system-resources/overview' });
+ expect(healthRows[0]).toMatchObject({ severity: 'critical', summary: '95% used', drillTo: '/system-resources/overview', drillLabel: 'Open system resources' });
expect(queue.items.find(i => i.source === 'backup')).toMatchObject({ title: 'Backup failed', summary: 'disk full' });
});
+ it('supplies drillLabel Open Learning when health alert links to /cos/learning', async () => {
+ proactiveAlerts.generateNonProductAlerts.mockResolvedValue([
+ { id: 'learning_skipped:all', type: 'learning_health', severity: 'high', title: '1 task type being skipped: internal-task', detail: 'Very low success rates', link: '/cos/learning' }
+ ]);
+ const queue = await buildQueue();
+ const row = queue.items.find(i => i.id === 'health:learning_skipped:all');
+ expect(row).toMatchObject({
+ drillTo: '/cos/learning',
+ drillLabel: 'Open Learning',
+ });
+ });
+
it('offers a process investigation in the registered owning app with full evidence', async () => {
apps.getAllApps.mockResolvedValue([{ id: 'example-app', name: 'Example App', repoPath: '/repos/example', pm2ProcessNames: ['example-worker'] }]);
proactiveAlerts.generateNonProductAlerts.mockResolvedValue([{