Skip to content

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

feat: per-app agent options, CoS scheduling fix, loops page, and MortalLoom export

Adam Eivy163dcd84251b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 30fe6793b4..07496873ca 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,6 +1,8 @@
# Unreleased Changes
## Added
+- Agent options (Worktree+PR, /simplify, Review Loop) configurable per-app on both the Automation tab and CoS Schedule per-app overrides
+- Review Loop agent option: runs PR review feedback loop after opening a PR until checks pass
- Nicotine tracking tab in MeatSpace with consumption logging, daily totals, rolling averages, custom product quick-add buttons, inline editing, and entry history
- Nicotine chart (7d/30d/90d bar chart) and nicotine vs heart rate correlation visualization
- Nicotine data integrated into health correlation endpoint (HR, resting HR alongside nicotine mg)
@@ -23,6 +25,8 @@
- Alcohol page summary compressed into a single compact stat bar row to maximize above-the-fold content
## Fixed
+- CoS scheduled improvement tasks (feature-ideas, etc.) never spawning: event listener mismatch (`tasks:user:added`/`tasks:cos:added` vs actual `tasks:changed` event), missing dequeue trigger after improvement check timer, and no improvement queuing after daemon restart until timer fires
+- App icons in CoS schedule per-app override list rendering at natural image size instead of respecting the `size` prop
- Calendar day view current-time red line now updates every 60 seconds instead of only on page load
- Stokes Pick default nicotine amount corrected from 3mg to 5mg
- UTC timezone shift showing tomorrow's date in alcohol/nicotine forms — replaced `toISOString()` with local `localDateStr()` utility
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 5146687f29..0c4cfddca8 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -22,6 +22,7 @@ import Instances from './pages/Instances';
import MeatSpace from './pages/MeatSpace';
import Post from './pages/Post';
import Review from './pages/Review';
+import Loops from './pages/Loops';
// Auto-reload on stale chunk errors (e.g., after a rebuild changes chunk hashes)
// Uses sessionStorage to prevent infinite reload loops (max 1 reload per session)
@@ -116,6 +117,7 @@ export default function App() {
<Route path="insights" element={<Navigate to="/insights/overview" replace />} />
<Route path="insights/:tab" element={<Insights />} />
<Route path="instances" element={<Instances />} />
+ <Route path="loops" element={<Loops />} />
<Route path="meatspace" element={<Navigate to="/meatspace/overview" replace />} />
<Route path="meatspace/:tab" element={<MeatSpace />} />
<Route path="post" element={<Navigate to="/post/launcher" replace />} />
diff --git a/client/src/components/AppIcon.jsx b/client/src/components/AppIcon.jsx
index bcd2ae3b8f..8a1de2340d 100644
--- a/client/src/components/AppIcon.jsx
+++ b/client/src/components/AppIcon.jsx
@@ -184,8 +184,8 @@ export default function AppIcon({ icon, appId, hasAppIcon, size = 24, className
const [imgError, setImgError] = useState(false);
// Show real app icon image if the app has one detected
- // Image fills its parent container completely (parent controls size)
if (hasAppIcon && appId && !imgError) {
+ const sizeStyle = { width: size, height: size, minWidth: size, minHeight: size };
const imgEl = (
<img
src={getAppIconUrl(appId)}
@@ -196,9 +196,9 @@ export default function AppIcon({ icon, appId, hasAppIcon, size = 24, className
);
if (ariaLabel) {
- return <span role="img" aria-label={ariaLabel}>{imgEl}</span>;
+ return <span role="img" aria-label={ariaLabel} className="inline-block" style={sizeStyle}>{imgEl}</span>;
}
- return <span aria-hidden="true">{imgEl}</span>;
+ return <span aria-hidden="true" className="inline-block" style={sizeStyle}>{imgEl}</span>;
}
// Fall back to SVG icon
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 41e01a23ef..80148d9c07 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -177,6 +177,7 @@ const navItems = [
{ to: '/goals/tree', label: 'Goals', icon: Target, single: true },
{ to: '/insights/overview', label: 'Insights', icon: Lightbulb, single: true },
{ to: '/instances', label: 'Instances', icon: Network, single: true },
+ { to: '/loops', label: 'Loops', icon: RefreshCw, single: true },
{
label: 'MeatSpace',
icon: Skull,
diff --git a/client/src/components/apps/tabs/AutomationTab.jsx b/client/src/components/apps/tabs/AutomationTab.jsx
index 23b05cc414..253a7f81cf 100644
--- a/client/src/components/apps/tabs/AutomationTab.jsx
+++ b/client/src/components/apps/tabs/AutomationTab.jsx
@@ -3,6 +3,7 @@ import { RefreshCw, Play } from 'lucide-react';
import toast from 'react-hot-toast';
import BrailleSpinner from '../../BrailleSpinner';
import * as api from '../../../services/api';
+import { AGENT_OPTIONS, toggleAppMetadataOverride } from '../../cos/constants';
const INTERVAL_OPTIONS = [
{ value: null, label: 'Inherit Global' },
@@ -57,6 +58,18 @@ export default function AutomationTab({ appId, appName }) {
}));
};
+ const handleMetaToggle = async (taskType, field, globalTaskMetadata) => {
+ const taskMetadata = toggleAppMetadataOverride(overrides[taskType]?.taskMetadata, globalTaskMetadata, field);
+ await api.updateAppTaskTypeOverride(appId, taskType, { taskMetadata }).catch(err => {
+ toast.error(err.message);
+ return null;
+ });
+ setOverrides(prev => ({
+ ...prev,
+ [taskType]: { ...prev[taskType], taskMetadata }
+ }));
+ };
+
const handleTrigger = async (taskType) => {
setTriggering(taskType);
const result = await api.triggerCosOnDemandTask(taskType, appId).catch(err => {
@@ -103,7 +116,7 @@ export default function AutomationTab({ appId, appName }) {
<th className="text-left px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium">Task Type</th>
<th className="text-center px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium">Enabled</th>
<th className="text-left px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium">Interval</th>
- <th className="text-left px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium">Global Interval</th>
+ <th className="text-center px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium cursor-help" title="Bright = app override on, Dim = inherited from global, Gray = app override off">Agent Options</th>
<th className="text-right px-4 py-3 text-xs text-gray-500 uppercase tracking-wide font-medium">Actions</th>
</tr>
</thead>
@@ -117,7 +130,10 @@ export default function AutomationTab({ appId, appName }) {
return (
<tr key={taskType} className="border-b border-port-border/50 hover:bg-white/5">
<td className="px-4 py-3">
- <span className="text-white font-mono text-xs">{taskType}</span>
+ <div>
+ <span className="text-white font-mono text-xs">{taskType}</span>
+ <div className="text-xs text-gray-500">{globalConfig.type || 'rotation'}{globalConfig.intervalMs ? ` (${Math.round(globalConfig.intervalMs / 3600000)}h)` : ''}</div>
+ </div>
</td>
<td className="px-4 py-3 text-center">
<button
@@ -143,10 +159,28 @@ export default function AutomationTab({ appId, appName }) {
</select>
</td>
<td className="px-4 py-3">
- <span className="text-xs text-gray-400">
- {globalConfig.type || 'rotation'}
- {globalConfig.intervalMs && ` (${Math.round(globalConfig.intervalMs / 3600000)}h)`}
- </span>
+ <div className="flex items-center justify-center gap-1">
+ {AGENT_OPTIONS.map(({ field, shortLabel, label }) => {
+ const effective = override.taskMetadata?.[field] ?? globalConfig.taskMetadata?.[field] ?? false;
+ const hasOverride = override.taskMetadata?.[field] !== undefined;
+ return (
+ <button
+ key={field}
+ onClick={() => handleMetaToggle(taskType, field, globalConfig.taskMetadata)}
+ aria-pressed={effective}
+ aria-label={`${label}: ${effective ? 'on' : 'off'}${hasOverride ? ' (app override)' : ' (inherited)'}`}
+ className={`text-xs px-1.5 py-0.5 rounded transition-colors ${
+ effective
+ ? hasOverride ? 'bg-port-accent/30 text-port-accent' : 'bg-port-accent/15 text-port-accent/60'
+ : hasOverride ? 'bg-gray-600/50 text-gray-400' : 'bg-gray-600/25 text-gray-500'
+ }`}
+ title={`${label}: ${effective ? 'on' : 'off'}${hasOverride ? ' (app override)' : ' (inherited)'}`}
+ >
+ {shortLabel}
+ </button>
+ );
+ })}
+ </div>
</td>
<td className="px-4 py-3 text-right">
<button
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index 4740c928ee..1f2e89dd22 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -49,6 +49,27 @@ export const STATE_MESSAGES = {
ideating: "Analyzing options...",
};
+// Agent option toggles for task metadata (useWorktree, simplify, reviewLoop)
+export const AGENT_OPTIONS = [
+ { field: 'useWorktree', label: 'Worktree + PR', shortLabel: 'WT', description: 'Work in an isolated git worktree on a feature branch, then open a PR. If unchecked, commits directly to the default branch.' },
+ { field: 'simplify', label: 'Run /simplify', shortLabel: '/s', description: 'Review code for reuse and quality before committing' },
+ { field: 'reviewLoop', label: 'Review Loop', shortLabel: 'RL', description: 'After opening a PR, run review feedback loop until checks pass and PR is approved' }
+];
+
+// Compute new taskMetadata after toggling a field in a per-app override.
+// Returns null when all overrides are cleared (inherit everything).
+export function toggleAppMetadataOverride(overrideMetadata, globalMetadata, field) {
+ const current = overrideMetadata || {};
+ const newMeta = { ...current };
+ if (newMeta[field] !== undefined) {
+ delete newMeta[field];
+ } else {
+ const effective = overrideMetadata?.[field] ?? globalMetadata?.[field] ?? false;
+ newMeta[field] = !effective;
+ }
+ return Object.keys(newMeta).length ? newMeta : null;
+}
+
export const MEMORY_TYPES = ['fact', 'learning', 'observation', 'decision', 'preference', 'context'];
export const MEMORY_TYPE_COLORS = {
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsx
index 95c002839e..a538b98cd3 100644
--- a/client/src/components/cos/tabs/ScheduleTab.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.jsx
@@ -3,6 +3,7 @@ import { Play, RotateCcw, ChevronDown, ChevronRight, AlertCircle, RefreshCw, Pac
import toast from 'react-hot-toast';
import * as api from '../../../services/api';
import AppIcon from '../../AppIcon';
+import { AGENT_OPTIONS, toggleAppMetadataOverride } from '../constants';
const INTERVAL_LABELS = {
rotation: 'Rotation',
@@ -29,10 +30,6 @@ function toggleMetadataField(metadata, field) {
return Object.keys(active).length ? active : null;
}
-const AGENT_OPTIONS = [
- { field: 'useWorktree', label: 'Worktree + PR', shortLabel: 'WT', description: 'Work in an isolated git worktree on a feature branch, then open a PR. If unchecked, commits directly to the default branch.' },
- { field: 'simplify', label: 'Run /simplify', shortLabel: '/s', description: 'Review code for reuse and quality before committing' }
-];
function IntervalBadge({ type }) {
return (
@@ -366,17 +363,8 @@ function AppOverrideRow({ app, taskType, globalIntervalType, globalTaskMetadata,
const handleMetaToggle = async (field) => {
setUpdating(true);
- const current = override?.taskMetadata || {};
- const newMeta = { ...current };
- if (newMeta[field] !== undefined) {
- // Already overridden — remove override to inherit global
- delete newMeta[field];
- } else {
- // Set override to opposite of effective value
- const effective = override?.taskMetadata?.[field] ?? globalTaskMetadata?.[field] ?? false;
- newMeta[field] = !effective;
- }
- await onUpdate(app.id, taskType, { taskMetadata: Object.keys(newMeta).length ? newMeta : null }).catch(() => {});
+ const taskMetadata = toggleAppMetadataOverride(override?.taskMetadata, globalTaskMetadata, field);
+ await onUpdate(app.id, taskType, { taskMetadata }).catch(() => {});
setUpdating(false);
};
diff --git a/client/src/pages/Loops.jsx b/client/src/pages/Loops.jsx
new file mode 100644
index 0000000000..067eabe775
--- /dev/null
+++ b/client/src/pages/Loops.jsx
@@ -0,0 +1,427 @@
+import { useState, useEffect, useRef, useCallback } from 'react';
+import {
+ RefreshCw, Play, Square, Trash2, Plus, Clock, Zap, ChevronDown, ChevronRight,
+ Bot, AlertCircle, CheckCircle, Loader2
+} from 'lucide-react';
+import * as api from '../services/api';
+import socket from '../services/socket';
+import toast from 'react-hot-toast';
+import { timeAgo } from '../components/feature-agents/constants';
+import { formatInterval } from '../components/cos/constants';
+
+const INTERVAL_PRESETS = [
+ { label: '30s', value: '30s' },
+ { label: '1m', value: '1m' },
+ { label: '5m', value: '5m' },
+ { label: '10m', value: '10m' },
+ { label: '30m', value: '30m' },
+ { label: '1h', value: '1h' },
+];
+
+function StatusBadge({ loop }) {
+ if (loop.isExecuting) return (
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-blue-500/20 text-blue-400">
+ <Loader2 size={12} className="animate-spin" /> Running
+ </span>
+ );
+ if (loop.isRunning) return (
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-green-500/20 text-green-400">
+ <Clock size={12} /> Active
+ </span>
+ );
+ return (
+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs bg-gray-500/20 text-gray-400">
+ <Square size={12} /> Stopped
+ </span>
+ );
+}
+
+function CreateLoopForm({ providers, onCreated }) {
+ const [prompt, setPrompt] = useState('');
+ const [interval, setInterval] = useState('10m');
+ const [customInterval, setCustomInterval] = useState('');
+ const [name, setName] = useState('');
+ const [providerId, setProviderId] = useState('');
+ const [cwd, setCwd] = useState('');
+ const [creating, setCreating] = useState(false);
+ const [expanded, setExpanded] = useState(false);
+
+ const handleSubmit = async (e) => {
+ e.preventDefault();
+ if (!prompt.trim()) return;
+ setCreating(true);
+ const data = {
+ prompt: prompt.trim(),
+ interval: customInterval || interval,
+ name: name.trim() || undefined,
+ cwd: cwd.trim() || undefined,
+ providerId: providerId || undefined,
+ };
+ api.createLoop(data)
+ .then(() => {
+ setPrompt('');
+ setName('');
+ setCwd('');
+ setCustomInterval('');
+ onCreated();
+ })
+ .catch(() => {})
+ .finally(() => setCreating(false));
+ };
+
+ return (
+ <form onSubmit={handleSubmit} className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <div className="flex items-center gap-2 mb-2">
+ <Plus size={16} className="text-port-accent" />
+ <h3 className="text-sm font-medium text-gray-200">New Loop</h3>
+ </div>
+
+ <textarea
+ value={prompt}
+ onChange={e => setPrompt(e.target.value)}
+ placeholder="What should this loop do? e.g., check if the deployment finished and report status"
+ className="w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-200 placeholder-gray-500 resize-y min-h-[60px]"
+ rows={2}
+ />
+
+ <div className="flex flex-wrap gap-3 items-end">
+ <div>
+ <label className="block text-xs text-gray-400 mb-1">Interval</label>
+ <div className="flex gap-1">
+ {INTERVAL_PRESETS.map(p => (
+ <button
+ key={p.value}
+ type="button"
+ onClick={() => { setInterval(p.value); setCustomInterval(''); }}
+ className={`px-2 py-1 text-xs rounded border ${
+ interval === p.value && !customInterval
+ ? 'border-port-accent bg-port-accent/20 text-port-accent'
+ : 'border-port-border text-gray-400 hover:border-gray-500'
+ }`}
+ >
+ {p.label}
+ </button>
+ ))}
+ <input
+ type="text"
+ value={customInterval}
+ onChange={e => setCustomInterval(e.target.value)}
+ placeholder="custom"
+ className="w-16 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-200 placeholder-gray-600"
+ />
+ </div>
+ </div>
+
+ <div className="flex-1 min-w-[150px]">
+ <label className="block text-xs text-gray-400 mb-1">AI Provider</label>
+ <select
+ value={providerId}
+ onChange={e => setProviderId(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-200"
+ >
+ <option value="">Active provider (default)</option>
+ {providers.map(p => (
+ <option key={p.id} value={p.id}>
+ {p.name} {p.isActive ? '(active)' : ''} — {p.defaultModel || p.type}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <button
+ type="button"
+ onClick={() => setExpanded(!expanded)}
+ className="text-xs text-gray-400 hover:text-gray-300 flex items-center gap-1"
+ >
+ {expanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />} Advanced
+ </button>
+ </div>
+
+ {expanded && (
+ <div className="flex flex-wrap gap-3">
+ <div className="flex-1 min-w-[200px]">
+ <label className="block text-xs text-gray-400 mb-1">Name (optional)</label>
+ <input
+ type="text"
+ value={name}
+ onChange={e => setName(e.target.value)}
+ placeholder="Loop name for display"
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-200 placeholder-gray-600"
+ />
+ </div>
+ <div className="flex-1 min-w-[200px]">
+ <label className="block text-xs text-gray-400 mb-1">Working Directory (optional)</label>
+ <input
+ type="text"
+ value={cwd}
+ onChange={e => setCwd(e.target.value)}
+ placeholder="/path/to/project"
+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-gray-200 placeholder-gray-600"
+ />
+ </div>
+ </div>
+ )}
+
+ <button
+ type="submit"
+ disabled={!prompt.trim() || creating}
+ className="px-4 py-1.5 bg-port-accent text-white rounded text-sm font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
+ >
+ {creating ? <Loader2 size={14} className="animate-spin" /> : <Play size={14} />}
+ Start Loop
+ </button>
+ </form>
+ );
+}
+
+function LoopCard({ loop, onAction, expandedId, onToggle }) {
+ const outputRef = useRef(null);
+ const [liveOutput, setLiveOutput] = useState([]);
+ const expanded = expandedId === loop.id;
+
+ useEffect(() => {
+ const appendOutput = (entry) => {
+ setLiveOutput(prev => {
+ const next = [...prev, entry];
+ return next.length > 200 ? next.slice(-200) : next;
+ });
+ };
+
+ const handleOutput = (data) => {
+ if (data.id !== loop.id) return;
+ appendOutput({ line: data.line, timestamp: data.timestamp });
+ };
+ const handleComplete = (data) => {
+ if (data.id !== loop.id) return;
+ appendOutput({ line: `--- Iteration ${data.iteration} complete (exit ${data.exitCode}) ---`, timestamp: data.timestamp, system: true });
+ };
+ const handleStart = (data) => {
+ if (data.id !== loop.id) return;
+ appendOutput({ line: `--- Iteration ${data.iteration} starting ---`, timestamp: data.timestamp, system: true });
+ };
+ const handleError = (data) => {
+ if (data.id !== loop.id) return;
+ appendOutput({ line: `--- Error: ${data.error} ---`, timestamp: data.timestamp, system: true, error: true });
+ };
+
+ socket.on('loop:output', handleOutput);
+ socket.on('loop:iteration:complete', handleComplete);
+ socket.on('loop:iteration:start', handleStart);
+ socket.on('loop:iteration:error', handleError);
+ return () => {
+ socket.off('loop:output', handleOutput);
+ socket.off('loop:iteration:complete', handleComplete);
+ socket.off('loop:iteration:start', handleStart);
+ socket.off('loop:iteration:error', handleError);
+ };
+ }, [loop.id]);
+
+ useEffect(() => {
+ if (outputRef.current && expanded) {
+ outputRef.current.scrollTop = outputRef.current.scrollHeight;
+ }
+ }, [liveOutput, expanded]);
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">
+ <div
+ className="flex items-center gap-3 px-4 py-3 cursor-pointer hover:bg-port-bg/50"
+ onClick={() => onToggle(loop.id)}
+ >
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-gray-200 truncate">{loop.name}</span>
+ <StatusBadge loop={loop} />
+ <span className="text-xs text-gray-500">every {formatInterval(loop.intervalMs)}</span>
+ </div>
+ <div className="flex items-center gap-3 mt-0.5 text-xs text-gray-500">
+ <span>#{loop.currentIteration || 0} iterations</span>
+ <span>last: {loop.lastRun ? timeAgo(new Date(loop.lastRun).toISOString()) : 'never'}</span>
+ {loop.providerId && <span className="flex items-center gap-1"><Bot size={10} /> {loop.providerId}</span>}
+ </div>
+ </div>
+
+ <div className="flex items-center gap-1">
+ {loop.isRunning ? (
+ <>
+ <button onClick={e => { e.stopPropagation(); onAction('trigger', loop.id); }} className="p-1.5 rounded hover:bg-port-border text-gray-400 hover:text-port-accent" title="Run now">
+ <Zap size={14} />
+ </button>
+ <button onClick={e => { e.stopPropagation(); onAction('stop', loop.id); }} className="p-1.5 rounded hover:bg-port-border text-gray-400 hover:text-port-warning" title="Stop">
+ <Square size={14} />
+ </button>
+ </>
+ ) : (
+ <button onClick={e => { e.stopPropagation(); onAction('resume', loop.id); }} className="p-1.5 rounded hover:bg-port-border text-gray-400 hover:text-port-success" title="Resume">
+ <Play size={14} />
+ </button>
+ )}
+ <button onClick={e => { e.stopPropagation(); onAction('delete', loop.id); }} className="p-1.5 rounded hover:bg-port-border text-gray-400 hover:text-port-error" title="Delete">
+ <Trash2 size={14} />
+ </button>
+ {expanded ? <ChevronDown size={14} className="text-gray-500" /> : <ChevronRight size={14} className="text-gray-500" />}
+ </div>
+ </div>
+
+ {expanded && (
+ <div className="border-t border-port-border">
+ <div className="px-4 py-2 bg-port-bg/30">
+ <div className="text-xs text-gray-500 mb-1">Prompt</div>
+ <pre className="text-xs text-gray-300 whitespace-pre-wrap font-mono">{loop.prompt}</pre>
+ </div>
+
+ {loop.history?.length > 0 && (
+ <div className="px-4 py-2 border-t border-port-border/50">
+ <div className="text-xs text-gray-500 mb-1">Recent Iterations</div>
+ <div className="space-y-1 max-h-32 overflow-y-auto">
+ {loop.history.slice(-5).reverse().map((h, i) => (
+ <div key={i} className="flex items-center gap-2 text-xs">
+ {h.success ? <CheckCircle size={10} className="text-port-success" /> : <AlertCircle size={10} className="text-port-error" />}
+ <span className="text-gray-400">#{h.iteration}</span>
+ <span className="text-gray-500">{h.duration ? `${(h.duration / 1000).toFixed(1)}s` : ''}</span>
+ <span className="text-gray-500">{h.provider}</span>
+ <span className="text-gray-600 truncate flex-1">{h.summary?.slice(0, 80)}</span>
+ <span className="text-gray-600">{timeAgo(new Date(h.timestamp).toISOString())}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ <div className="border-t border-port-border/50">
+ <div className="px-4 py-1 text-xs text-gray-500 flex items-center gap-2">
+ Live Output
+ {loop.isExecuting && <Loader2 size={10} className="animate-spin text-blue-400" />}
+ {liveOutput.length > 0 && (
+ <button onClick={() => setLiveOutput([])} className="ml-auto text-gray-600 hover:text-gray-400 text-xs">clear</button>
+ )}
+ </div>
+ <div
+ ref={outputRef}
+ className="px-4 py-2 max-h-64 overflow-y-auto bg-port-bg/50 font-mono text-xs leading-relaxed"
+ >
+ {liveOutput.length === 0 ? (
+ <div className="text-gray-600 italic">Waiting for output...</div>
+ ) : (
+ liveOutput.map((entry, i) => (
+ <div
+ key={i}
+ className={
+ entry.system
+ ? entry.error ? 'text-port-error' : 'text-gray-500 italic'
+ : 'text-gray-300'
+ }
+ >
+ {entry.line}
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+const ACTION_MAP = {
+ stop: { fn: api.stopLoop, msg: 'Loop stopped' },
+ resume: { fn: api.resumeLoop, msg: 'Loop resumed' },
+ trigger: { fn: api.triggerLoop, msg: 'Iteration triggered' },
+ delete: { fn: api.deleteLoop, msg: 'Loop deleted' },
+};
+
+export default function Loops() {
+ const [loops, setLoops] = useState([]);
+ const [providers, setProviders] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [expandedId, setExpandedId] = useState(null);
+
+ const fetchLoops = useCallback(async () => {
+ const data = await api.getLoops().catch(() => []);
+ setLoops(data);
+ setLoading(false);
+ }, []);
+
+ const fetchProviders = useCallback(async () => {
+ const data = await api.getLoopProviders().catch(() => ({ providers: [] }));
+ setProviders(data.providers || []);
+ }, []);
+
+ useEffect(() => {
+ fetchLoops();
+ fetchProviders();
+
+ // Subscribe to loop events
+ socket.emit('loops:subscribe');
+
+ const refreshEvents = ['loop:created', 'loop:stopped', 'loop:resumed', 'loop:deleted', 'loop:updated'];
+ const handleRefresh = () => fetchLoops();
+ refreshEvents.forEach(e => socket.on(e, handleRefresh));
+
+ // Fallback poll for iteration count updates (socket events cover state changes)
+ const poll = setInterval(fetchLoops, 60000);
+
+ return () => {
+ socket.emit('loops:unsubscribe');
+ refreshEvents.forEach(e => socket.off(e, handleRefresh));
+ clearInterval(poll);
+ };
+ }, [fetchLoops, fetchProviders]);
+
+ const handleAction = async (action, id) => {
+ const entry = ACTION_MAP[action];
+ if (!entry) return;
+ await entry.fn(id).catch(() => {});
+ toast.success(entry.msg);
+ };
+
+ const runningCount = loops.filter(l => l.isRunning).length;
+
+ return (
+ <div className="max-w-4xl mx-auto space-y-4">
+ <div className="flex items-center justify-between">
+ <div>
+ <h1 className="text-xl font-bold text-gray-100 flex items-center gap-2">
+ <RefreshCw size={20} className="text-port-accent" /> Loops
+ </h1>
+ <p className="text-xs text-gray-500 mt-0.5">
+ Recurring AI tasks — like Claude Code's /loop, for any AI provider
+ </p>
+ </div>
+ <div className="flex items-center gap-3 text-xs text-gray-400">
+ {runningCount > 0 && <span className="text-port-success">{runningCount} active</span>}
+ <span>{loops.length} total</span>
+ <button onClick={fetchLoops} className="p-1 rounded hover:bg-port-border" title="Refresh">
+ <RefreshCw size={14} />
+ </button>
+ </div>
+ </div>
+
+ <CreateLoopForm providers={providers} onCreated={fetchLoops} />
+
+ {loading ? (
+ <div className="flex items-center justify-center py-12 text-gray-500">
+ <Loader2 size={20} className="animate-spin mr-2" /> Loading loops...
+ </div>
+ ) : loops.length === 0 ? (
+ <div className="text-center py-12 text-gray-500">
+ <RefreshCw size={32} className="mx-auto mb-2 opacity-30" />
+ <p className="text-sm">No loops yet. Create one above to get started.</p>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {loops.map(loop => (
+ <LoopCard
+ key={loop.id}
+ loop={loop}
+ onAction={handleAction}
+ expandedId={expandedId}
+ onToggle={id => setExpandedId(prev => prev === id ? null : id)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 6f621a83c2..38ca8e7dd5 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1886,3 +1886,14 @@ export const destroyDatabase = (backend) => request('/database/destroy', {
method: 'POST',
body: JSON.stringify({ backend })
});
+
+// Loops
+export const getLoops = () => request('/loops');
+export const getLoop = (id) => request(`/loops/${id}`);
+export const getLoopProviders = () => request('/loops/providers');
+export const createLoop = (data) => request('/loops', { method: 'POST', body: JSON.stringify(data) });
+export const updateLoop = (id, data) => request(`/loops/${id}`, { method: 'PUT', body: JSON.stringify(data) });
+export const stopLoop = (id) => request(`/loops/${id}/stop`, { method: 'POST' });
+export const resumeLoop = (id) => request(`/loops/${id}/resume`, { method: 'POST' });
+export const triggerLoop = (id) => request(`/loops/${id}/trigger`, { method: 'POST' });
+export const deleteLoop = (id) => request(`/loops/${id}`, { method: 'DELETE' });
diff --git a/server/index.js b/server/index.js
index 740237a352..f7d0abcd69 100644
--- a/server/index.js
+++ b/server/index.js
@@ -60,6 +60,7 @@ import githubRoutes from './routes/github.js';
import settingsRoutes from './routes/settings.js';
import telegramRoutes from './routes/telegram.js';
import updateRoutes from './routes/update.js';
+import loopsRoutes from './routes/loops.js';
import { ensureSelf, startPolling } from './services/instances.js';
import { initSyncLog } from './services/brainSyncLog.js';
import { backfillOriginInstanceId } from './services/brainStorage.js';
@@ -78,6 +79,7 @@ import * as telegram from './services/telegram.js';
import * as telegramBridge from './services/telegramBridge.js';
import { getSettings as getInitSettings } from './services/settings.js';
import { startUpdateScheduler, recordUpdateResult, clearStaleUpdateInProgress, getCurrentVersion } from './services/updateChecker.js';
+import { restoreLoops } from './services/loops.js';
import { startBrainScheduler } from './services/brainScheduler.js';
import { recoverStuckClassifications } from './services/brain.js';
import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridge.js';
@@ -254,6 +256,7 @@ app.use('/api/github', githubRoutes);
app.use('/api/settings', settingsRoutes);
app.use('/api/telegram', telegramRoutes);
app.use('/api/update', updateRoutes);
+app.use('/api/loops', loopsRoutes);
// Initialize agent automation scheduler and action executor
automationScheduler.init().catch(err => console.error(`❌ Agent scheduler init failed: ${err.message}`));
@@ -322,6 +325,9 @@ clearStaleUpdateInProgress().catch(err => console.error(`❌ Stale update recove
// Start periodic update checker (checks GitHub releases every 30 min)
startUpdateScheduler();
+// Restore any active loops from previous session
+restoreLoops().catch(err => console.error(`❌ Loop restore failed: ${err.message}`));
+
// Serve built client UI (production mode — no Vite dev server needed)
const CLIENT_DIST = join(__dirname, '..', 'client', 'dist');
if (existsSync(CLIENT_DIST)) {
diff --git a/server/lib/validation.js b/server/lib/validation.js
index eb9fe1b413..bec21dad49 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -542,7 +542,7 @@ export function validateRequest(schema, data) {
// TASK METADATA SANITIZATION
// =============================================================================
-const ALLOWED_TASK_METADATA_KEYS = ['useWorktree', 'simplify'];
+const ALLOWED_TASK_METADATA_KEYS = ['useWorktree', 'simplify', 'reviewLoop'];
/**
* Sanitize taskMetadata to only allowed agent-option keys with boolean values.
diff --git a/server/routes/loops.js b/server/routes/loops.js
new file mode 100644
index 0000000000..5b952ce427
--- /dev/null
+++ b/server/routes/loops.js
@@ -0,0 +1,69 @@
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import * as loopsService from '../services/loops.js';
+
+const router = Router();
+
+// GET /api/loops
+router.get('/', asyncHandler(async (req, res) => {
+ const loops = await loopsService.getLoops();
+ res.json(loops);
+}));
+
+// GET /api/loops/providers
+router.get('/providers', asyncHandler(async (req, res) => {
+ const data = await loopsService.getAvailableProviders();
+ res.json(data);
+}));
+
+// GET /api/loops/:id
+router.get('/:id', asyncHandler(async (req, res) => {
+ const loop = await loopsService.getLoop(req.params.id);
+ if (!loop) throw new ServerError('Loop not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(loop);
+}));
+
+// POST /api/loops
+router.post('/', asyncHandler(async (req, res) => {
+ const { prompt, interval, name, cwd, providerId, timeout, runImmediately } = req.body;
+ if (!prompt) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
+ if (!interval) throw new ServerError('Interval is required', { status: 400, code: 'VALIDATION_ERROR' });
+
+ const loop = await loopsService.createLoop({
+ prompt, interval, name, cwd, providerId, timeout,
+ runImmediately: runImmediately !== false
+ });
+ res.status(201).json(loop);
+}));
+
+// PUT /api/loops/:id
+router.put('/:id', asyncHandler(async (req, res) => {
+ const loop = await loopsService.updateLoop(req.params.id, req.body);
+ res.json(loop);
+}));
+
+// POST /api/loops/:id/stop
+router.post('/:id/stop', asyncHandler(async (req, res) => {
+ await loopsService.stopLoop(req.params.id);
+ res.json({ status: 'stopped' });
+}));
+
+// POST /api/loops/:id/resume
+router.post('/:id/resume', asyncHandler(async (req, res) => {
+ const loop = await loopsService.resumeLoop(req.params.id);
+ res.json(loop);
+}));
+
+// POST /api/loops/:id/trigger
+router.post('/:id/trigger', asyncHandler(async (req, res) => {
+ const result = await loopsService.triggerLoop(req.params.id);
+ res.json(result);
+}));
+
+// DELETE /api/loops/:id
+router.delete('/:id', asyncHandler(async (req, res) => {
+ await loopsService.deleteLoop(req.params.id);
+ res.status(204).end();
+}));
+
+export default router;
diff --git a/server/routes/meatspace.js b/server/routes/meatspace.js
index 9d7b957bad..7dbd116bbd 100644
--- a/server/routes/meatspace.js
+++ b/server/routes/meatspace.js
@@ -1,6 +1,8 @@
import { Router } from 'express';
+import { join } from 'path';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
+import { PATHS, readJSONFile } from '../lib/fileUtils.js';
import {
configUpdateSchema,
lifestyleUpdateSchema,
@@ -843,4 +845,133 @@ router.delete('/life-events/:id', asyncHandler(async (req, res) => {
res.json(events);
}));
+/**
+ * GET /api/meatspace/export/mortalloom
+ * Export all health data in MortalLoom-compatible JSON format.
+ * Transforms PortOS daily-log + files into MortalLoom AppData schema.
+ */
+router.get('/export/mortalloom', asyncHandler(async (req, res) => {
+ const config = await meatspaceService.getConfig();
+ const bloodData = await healthService.getBloodTests();
+ const epiData = await healthService.getEpigeneticTests();
+ const eyeData = await healthService.getEyeExams();
+ const bodyHistory = await healthService.getBodyHistory();
+ const dailyLog = await readJSONFile(join(PATHS.meatspace, 'daily-log.json'), { entries: [] });
+
+ // Profile
+ const profile = {
+ birthDate: config.birthDate || null,
+ biologicalSex: config.sex || null,
+ lifestyle: {
+ smokingStatus: config.lifestyle?.smokingStatus ?? 'never',
+ exerciseMinutesPerWeek: config.lifestyle?.exerciseMinutesPerWeek ?? 150,
+ sleepHoursPerNight: config.lifestyle?.sleepHoursPerNight ?? 7.5,
+ dietQuality: config.lifestyle?.dietQuality ?? 'good',
+ stressLevel: config.lifestyle?.stressLevel ?? 'moderate',
+ bmi: config.lifestyle?.bmi ?? null,
+ },
+ };
+
+ // Alcohol drinks - flatten daily log entries into individual drinks
+ const alcoholDrinks = [];
+ for (const entry of (dailyLog?.entries || [])) {
+ if (!entry.alcohol?.drinks) continue;
+ for (const drink of entry.alcohol.drinks) {
+ alcoholDrinks.push({
+ id: crypto.randomUUID(),
+ name: drink.name,
+ oz: drink.oz,
+ abv: drink.abv,
+ count: drink.count || 1,
+ date: entry.date,
+ });
+ }
+ }
+
+ // Nicotine entries - flatten daily log
+ const nicotineEntries = [];
+ for (const entry of (dailyLog?.entries || [])) {
+ if (!entry.nicotine?.items) continue;
+ for (const item of entry.nicotine.items) {
+ nicotineEntries.push({
+ id: crypto.randomUUID(),
+ product: item.product,
+ mgPerUnit: item.mgPerUnit,
+ count: item.count || 1,
+ date: entry.date,
+ });
+ }
+ }
+
+ // Blood tests - PortOS stores markers flat on test object, MortalLoom nests under `markers`
+ const bloodTests = (bloodData?.tests || []).map(test => {
+ const { date, ...markers } = test;
+ return {
+ id: crypto.randomUUID(),
+ date,
+ markers,
+ };
+ });
+
+ // Body entries from daily log
+ const bodyEntries = bodyHistory.map(entry => ({
+ id: crypto.randomUUID(),
+ date: entry.date,
+ weightLbs: entry.weightLbs ?? null,
+ bodyFatPct: entry.fatPct ?? null,
+ }));
+
+ // Epigenetic tests
+ const epigeneticTests = (epiData?.tests || []).map(test => ({
+ id: crypto.randomUUID(),
+ date: test.date,
+ chronologicalAge: test.chronologicalAge,
+ biologicalAge: test.biologicalAge,
+ paceOfAging: test.paceOfAging ?? null,
+ organScores: test.organScores ?? null,
+ }));
+
+ // Eye exams
+ const eyeExams = (eyeData?.exams || []).map(exam => ({
+ id: crypto.randomUUID(),
+ date: exam.date,
+ leftSphere: exam.leftSphere ?? null,
+ leftCylinder: exam.leftCylinder ?? null,
+ leftAxis: exam.leftAxis ?? null,
+ rightSphere: exam.rightSphere ?? null,
+ rightCylinder: exam.rightCylinder ?? null,
+ rightAxis: exam.rightAxis ?? null,
+ }));
+
+ // Default alcohol presets (match MortalLoom defaults)
+ const alcoholPresets = [
+ { id: crypto.randomUUID(), name: 'Modelo Especial (12oz)', oz: 12, abv: 4.4 },
+ { id: crypto.randomUUID(), name: 'Nitro Guinness (14.9oz)', oz: 14.9, abv: 4.2 },
+ { id: crypto.randomUUID(), name: 'Old Fashioned (2oz)', oz: 2, abv: 40 },
+ { id: crypto.randomUUID(), name: 'Guinness 0 (14.9oz)', oz: 14.9, abv: 0.4 },
+ { id: crypto.randomUUID(), name: 'N/A Beer (12oz)', oz: 12, abv: 0.4 },
+ ];
+
+ // Nicotine presets
+ const nicotinePresets = [
+ { id: crypto.randomUUID(), name: 'Stokes Pick (5mg)', mgPerUnit: 5 },
+ ];
+
+ const exportData = {
+ profile,
+ alcoholDrinks,
+ alcoholPresets,
+ nicotineEntries,
+ nicotinePresets,
+ bloodTests,
+ eyeExams,
+ epigeneticTests,
+ bodyEntries,
+ };
+
+ res.setHeader('Content-Disposition', 'attachment; filename="MortalLoom-export.json"');
+ res.setHeader('Content-Type', 'application/json');
+ res.json(exportData);
+}));
+
export default router;
diff --git a/server/services/cos.js b/server/services/cos.js
index 309eaeb21a..5d294c2b25 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -628,6 +628,19 @@ export async function start() {
cosEvents.emit('status', { running: true });
emitLog('success', 'CoS daemon started successfully');
+
+ // Queue due improvement tasks shortly after startup (not during initial eval
+ // to avoid overwhelming fresh installs, but soon enough to not stall)
+ setTimeout(() => {
+ if (!daemonRunning) return;
+ loadState().then(async (state) => {
+ if (!state.config.idleReviewEnabled) return;
+ const cosTaskData = await getCosTasks();
+ await queueEligibleImprovementTasks(state, cosTaskData);
+ setImmediate(() => dequeueNextTask());
+ }).catch(err => emitLog('warn', `Post-startup improvement queuing failed: ${err.message}`));
+ }, 30000);
+
return { success: true };
}
@@ -3854,6 +3867,7 @@ async function scheduleNextImprovementCheck() {
if (state.config.idleReviewEnabled) {
const cosTaskData = await getCosTasks();
await queueEligibleImprovementTasks(state, cosTaskData);
+ setImmediate(() => dequeueNextTask());
}
await scheduleNextImprovementCheck();
@@ -3894,7 +3908,11 @@ async function init() {
);
});
- // Event-driven triggers: file watcher changes → dequeueNextTask
+ // Event-driven triggers: task/file changes → dequeueNextTask
+ cosEvents.on('tasks:changed', (data) => {
+ if (daemonRunning && data?.action === 'added') setImmediate(() => dequeueNextTask());
+ });
+
cosEvents.on('tasks:user:added', () => {
if (daemonRunning) setImmediate(() => dequeueNextTask());
});
diff --git a/server/services/loops.js b/server/services/loops.js
new file mode 100644
index 0000000000..0f9d57c88e
--- /dev/null
+++ b/server/services/loops.js
@@ -0,0 +1,372 @@
+/**
+ * Loops Service
+ *
+ * Manages recurring AI CLI loops — the web equivalent of Claude Code's `/loop`.
+ * Each loop spawns a headless AI run on a configurable interval via portos-ai-toolkit,
+ * so any configured provider (Claude, Gemini, Codex, etc.) can power loops.
+ * Output streams in real-time via EventEmitter → Socket.IO.
+ */
+
+import { EventEmitter } from 'events';
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { randomUUID } from 'crypto';
+import { createRun, executeCliRun } from './runner.js';
+import { getProviderById, getAllProviders, getActiveProvider } from './providers.js';
+
+export const loopEvents = new EventEmitter();
+
+const LOOPS_FILE = join(PATHS.data, 'loops.json');
+const LOOPS_OUTPUT_DIR = join(PATHS.data, 'loops');
+const DEFAULT_TIMEOUT_MS = 300_000;
+const MIN_INTERVAL_MS = 10_000;
+
+const activeLoops = new Map();
+
+function parseInterval(str) {
+ const match = String(str).match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|ms)?$/i);
+ if (!match) return null;
+ const val = parseFloat(match[1]);
+ const unit = (match[2] || 'm').toLowerCase();
+ const multipliers = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
+ return Math.round(val * (multipliers[unit] || 60_000));
+}
+
+function formatInterval(ms) {
+ if (ms >= 86_400_000) return `${ms / 86_400_000}d`;
+ if (ms >= 3_600_000) return `${ms / 3_600_000}h`;
+ if (ms >= 60_000) return `${ms / 60_000}m`;
+ return `${ms / 1000}s`;
+}
+
+async function loadLoops() {
+ const raw = await readFile(LOOPS_FILE, 'utf-8').catch(() => '[]');
+ return JSON.parse(raw);
+}
+
+async function saveLoops(loops) {
+ await writeFile(LOOPS_FILE, JSON.stringify(loops, null, 2));
+}
+
+async function executeIteration(loop) {
+ const id = loop.id;
+ const active = activeLoops.get(id);
+ if (!active || active.running) return;
+
+ active.running = true;
+ active.iterationCount++;
+ const iterationNum = active.iterationCount;
+
+ loopEvents.emit('iteration:start', { id, iteration: iterationNum, timestamp: Date.now() });
+
+ let provider;
+ if (loop.providerId) {
+ provider = await getProviderById(loop.providerId).catch(() => null);
+ }
+ if (!provider) {
+ provider = await getActiveProvider().catch(() => null);
+ }
+ if (!provider) {
+ const msg = 'No AI provider available';
+ loopEvents.emit('iteration:error', { id, iteration: iterationNum, error: msg, timestamp: Date.now() });
+ active.running = false;
+ console.error(`❌ Loop ${id}: ${msg}`);
+ return;
+ }
+
+ const outputLines = [];
+
+ const onData = (text) => {
+ const lines = text.split('\n').filter(l => l.trim());
+ for (const line of lines) {
+ outputLines.push(line);
+ loopEvents.emit('output', { id, iteration: iterationNum, line, timestamp: Date.now() });
+ }
+ };
+
+ const onComplete = async (metadata) => {
+ const result = outputLines.join('\n');
+ const iterResult = {
+ iteration: iterationNum,
+ exitCode: metadata.exitCode,
+ success: metadata.success,
+ output: result,
+ lineCount: outputLines.length,
+ duration: metadata.duration,
+ provider: provider.name,
+ model: provider.defaultModel,
+ timestamp: Date.now()
+ };
+
+ active.lastResult = iterResult;
+ active.history.push({
+ iteration: iterationNum,
+ exitCode: metadata.exitCode,
+ success: metadata.success,
+ summary: result.slice(0, 500),
+ duration: metadata.duration,
+ provider: provider.name,
+ timestamp: Date.now()
+ });
+ if (active.history.length > 50) active.history.shift();
+
+ active.running = false;
+ active.runId = null;
+
+ loopEvents.emit('iteration:complete', { id, ...iterResult });
+
+ const outputPath = join(LOOPS_OUTPUT_DIR, `${id}-${iterationNum}.txt`);
+ await writeFile(outputPath, result).catch(() => {});
+
+ await updatePersistedLoop(id, {
+ lastRun: Date.now(),
+ iterationCount: active.iterationCount,
+ lastExitCode: metadata.exitCode
+ });
+
+ console.log(`🔄 Loop ${id} iteration ${iterationNum} complete (${provider.name}, exit ${metadata.exitCode}, ${outputLines.length} lines)`);
+ };
+
+ const runResult = await createRun({
+ providerId: provider.id,
+ prompt: loop.prompt,
+ workspacePath: loop.cwd || PATHS.root,
+ source: 'loop',
+ sourceId: id,
+ label: `Loop: ${loop.name} #${iterationNum}`
+ }).catch(err => {
+ active.running = false;
+ loopEvents.emit('iteration:error', { id, iteration: iterationNum, error: err.message, timestamp: Date.now() });
+ console.error(`❌ Loop ${id} createRun failed: ${err.message}`);
+ return null;
+ });
+
+ if (!runResult) return;
+
+ active.runId = runResult.metadata.id;
+
+ executeCliRun(
+ runResult.metadata.id,
+ runResult.provider,
+ loop.prompt,
+ loop.cwd || PATHS.root,
+ onData,
+ onComplete,
+ loop.timeout || DEFAULT_TIMEOUT_MS
+ ).catch(err => {
+ active.running = false;
+ active.runId = null;
+ loopEvents.emit('iteration:error', { id, iteration: iterationNum, error: err.message, timestamp: Date.now() });
+ console.error(`❌ Loop ${id} executeCliRun failed: ${err.message}`);
+ });
+}
+
+async function updatePersistedLoop(id, updates) {
+ const loops = await loadLoops();
+ const idx = loops.findIndex(l => l.id === id);
+ if (idx >= 0) {
+ Object.assign(loops[idx], updates);
+ await saveLoops(loops);
+ }
+}
+
+export async function createLoop({ prompt, interval, name, cwd, providerId, timeout, runImmediately = true }) {
+ const intervalMs = typeof interval === 'number' ? interval : parseInterval(interval);
+ if (!intervalMs || intervalMs < MIN_INTERVAL_MS) {
+ throw new Error('Interval must be at least 10 seconds');
+ }
+ if (!prompt?.trim()) {
+ throw new Error('Prompt is required');
+ }
+
+ await ensureDir(LOOPS_OUTPUT_DIR);
+
+ const id = randomUUID().slice(0, 8);
+ const loop = {
+ id,
+ name: name || prompt.slice(0, 60),
+ prompt: prompt.trim(),
+ intervalMs,
+ cwd: cwd || null,
+ providerId: providerId || null,
+ timeout: timeout || null,
+ status: 'running',
+ createdAt: Date.now(),
+ lastRun: null,
+ iterationCount: 0,
+ lastExitCode: null
+ };
+
+ const loops = await loadLoops();
+ loops.push(loop);
+ await saveLoops(loops);
+
+ startLoopTimer(loop, runImmediately);
+
+ loopEvents.emit('created', { loop });
+ console.log(`🔄 Loop ${id} created: "${loop.name}" every ${formatInterval(intervalMs)}`);
+
+ return loop;
+}
+
+function startLoopTimer(loop, runImmediately = false) {
+ const timer = setInterval(() => executeIteration(loop), loop.intervalMs);
+ activeLoops.set(loop.id, {
+ timer,
+ runId: null,
+ running: false,
+ iterationCount: loop.iterationCount || 0,
+ lastResult: null,
+ history: []
+ });
+
+ if (runImmediately) {
+ setTimeout(() => executeIteration(loop), 100);
+ }
+}
+
+export async function stopLoop(id) {
+ const active = activeLoops.get(id);
+ if (!active) throw new Error(`Loop ${id} is not running`);
+
+ clearInterval(active.timer);
+ activeLoops.delete(id);
+
+ const loops = await loadLoops();
+ const idx = loops.findIndex(l => l.id === id);
+ if (idx >= 0) {
+ loops[idx].status = 'stopped';
+ loops[idx].stoppedAt = Date.now();
+ await saveLoops(loops);
+ }
+
+ loopEvents.emit('stopped', { id });
+ console.log(`⏹️ Loop ${id} stopped`);
+}
+
+export async function resumeLoop(id) {
+ if (activeLoops.has(id)) throw new Error(`Loop ${id} is already running`);
+
+ const loops = await loadLoops();
+ const loop = loops.find(l => l.id === id);
+ if (!loop) throw new Error(`Loop ${id} not found`);
+
+ loop.status = 'running';
+ loop.stoppedAt = null;
+ await saveLoops(loops);
+
+ await ensureDir(LOOPS_OUTPUT_DIR);
+ startLoopTimer(loop, true);
+
+ loopEvents.emit('resumed', { id });
+ console.log(`▶️ Loop ${id} resumed`);
+ return loop;
+}
+
+export async function deleteLoop(id) {
+ if (activeLoops.has(id)) {
+ const active = activeLoops.get(id);
+ clearInterval(active.timer);
+ activeLoops.delete(id);
+ }
+
+ const loops = await loadLoops();
+ const filtered = loops.filter(l => l.id !== id);
+ await saveLoops(filtered);
+
+ loopEvents.emit('deleted', { id });
+ console.log(`🗑️ Loop ${id} deleted`);
+}
+
+export async function getLoops() {
+ const loops = await loadLoops();
+ return loops.map(loop => {
+ const active = activeLoops.get(loop.id);
+ return {
+ ...loop,
+ isRunning: !!active,
+ isExecuting: active?.running || false,
+ currentIteration: active?.iterationCount || loop.iterationCount || 0,
+ lastResult: active?.lastResult || null,
+ history: active?.history || []
+ };
+ });
+}
+
+export async function getLoop(id) {
+ const loops = await getLoops();
+ return loops.find(l => l.id === id) || null;
+}
+
+export async function triggerLoop(id) {
+ const loops = await loadLoops();
+ const loop = loops.find(l => l.id === id);
+ if (!loop) throw new Error(`Loop ${id} not found`);
+ if (!activeLoops.has(id)) throw new Error(`Loop ${id} is not running`);
+
+ executeIteration(loop);
+ return { triggered: true };
+}
+
+export async function updateLoop(id, updates) {
+ const loops = await loadLoops();
+ const idx = loops.findIndex(l => l.id === id);
+ if (idx < 0) throw new Error(`Loop ${id} not found`);
+
+ const allowed = ['name', 'prompt', 'interval', 'cwd', 'providerId', 'timeout'];
+ for (const key of allowed) {
+ if (updates[key] !== undefined) {
+ if (key === 'interval') {
+ const ms = typeof updates[key] === 'number' ? updates[key] : parseInterval(updates[key]);
+ if (!ms || ms < MIN_INTERVAL_MS) throw new Error('Interval must be at least 10 seconds');
+ loops[idx].intervalMs = ms;
+ } else {
+ loops[idx][key] = updates[key];
+ }
+ }
+ }
+
+ await saveLoops(loops);
+
+ if (activeLoops.has(id) && updates.interval) {
+ const active = activeLoops.get(id);
+ clearInterval(active.timer);
+ active.timer = setInterval(() => executeIteration(loops[idx]), loops[idx].intervalMs);
+ }
+
+ loopEvents.emit('updated', { loop: loops[idx] });
+ return loops[idx];
+}
+
+export async function getAvailableProviders() {
+ const result = await getAllProviders();
+ const providers = Array.isArray(result) ? result : (result?.providers || []);
+ const active = await getActiveProvider().catch(() => null);
+ return {
+ providers: providers.map(p => ({
+ id: p.id,
+ name: p.name,
+ type: p.type,
+ command: p.command,
+ defaultModel: p.defaultModel,
+ isActive: active?.id === p.id
+ })),
+ activeProviderId: active?.id || null
+ };
+}
+
+export async function restoreLoops() {
+ await ensureDir(LOOPS_OUTPUT_DIR);
+ const loops = await loadLoops();
+ let restored = 0;
+ for (const loop of loops) {
+ if (loop.status === 'running') {
+ startLoopTimer(loop, false);
+ restored++;
+ }
+ }
+ if (restored > 0) {
+ console.log(`🔄 Restored ${restored} active loop(s)`);
+ }
+}
diff --git a/server/services/socket.js b/server/services/socket.js
index c25d0655fd..4a262d7a01 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -17,6 +17,7 @@ import { moltworldWsEvents } from './moltworldWs.js';
import { queueEvents } from './moltworldQueue.js';
import { instanceEvents } from './instanceEvents.js';
import { reviewEvents } from './review.js';
+import { loopEvents } from './loops.js';
import * as shellService from './shell.js';
import {
validateSocketData,
@@ -46,6 +47,8 @@ const notificationSubscribers = new Set();
const agentSubscribers = new Set();
// Store instance subscribers
const instanceSubscribers = new Set();
+// Store loop subscribers
+const loopSubscribers = new Set();
// Store io instance for broadcasting
let ioInstance = null;
@@ -257,6 +260,17 @@ export function initSocket(io) {
socket.emit('instances:unsubscribed');
});
+ // Loop subscriptions
+ socket.on('loops:subscribe', () => {
+ loopSubscribers.add(socket);
+ socket.emit('loops:subscribed');
+ });
+
+ socket.on('loops:unsubscribe', () => {
+ loopSubscribers.delete(socket);
+ socket.emit('loops:unsubscribed');
+ });
+
// Handle error recovery requests (can trigger auto-fix agents)
socket.on('error:recover', async (rawData) => {
const data = validateSocketData(errorRecoverSchema, rawData, socket, 'error:recover');
@@ -431,6 +445,7 @@ export function initSocket(io) {
notificationSubscribers.delete(socket);
agentSubscribers.delete(socket);
instanceSubscribers.delete(socket);
+ loopSubscribers.delete(socket);
const detached = shellService.detachSocketSessions(socket);
if (detached > 0) {
console.log(`🐚 Detached ${detached} shell session(s) (still running)`);
@@ -481,6 +496,9 @@ export function initSocket(io) {
// Set up update event forwarding
setupUpdateEventForwarding();
+
+ // Set up loop event forwarding
+ setupLoopEventForwarding();
}
function cleanupStream(socketId) {
@@ -713,3 +731,27 @@ function setupUpdateEventForwarding() {
}
});
}
+
+// Broadcast to loop subscribers only
+function broadcastToLoops(event, data) {
+ for (const socket of loopSubscribers) {
+ if (!socket.connected) { loopSubscribers.delete(socket); continue; }
+ socket.emit(event, data);
+ }
+}
+
+// Set up loop event forwarding (idempotent)
+let loopForwardingSetup = false;
+function setupLoopEventForwarding() {
+ if (loopForwardingSetup) return;
+ loopForwardingSetup = true;
+ loopEvents.on('created', (data) => broadcastToLoops('loop:created', data));
+ loopEvents.on('stopped', (data) => broadcastToLoops('loop:stopped', data));
+ loopEvents.on('resumed', (data) => broadcastToLoops('loop:resumed', data));
+ loopEvents.on('deleted', (data) => broadcastToLoops('loop:deleted', data));
+ loopEvents.on('updated', (data) => broadcastToLoops('loop:updated', data));
+ loopEvents.on('iteration:start', (data) => broadcastToLoops('loop:iteration:start', data));
+ loopEvents.on('iteration:complete', (data) => broadcastToLoops('loop:iteration:complete', data));
+ loopEvents.on('iteration:error', (data) => broadcastToLoops('loop:iteration:error', data));
+ loopEvents.on('output', (data) => broadcastToLoops('loop:output', data));
+}