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

Add pause support for CoS agents

Adam Eivy24ca55a3aa51
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index f19bae8b80..37d5156eb5 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -9,6 +9,7 @@ import {
RotateCcw,
Loader2,
Skull,
+ Pause,
Activity,
Clock,
Brain,
@@ -99,7 +100,7 @@ function TaskDescription({ text }) {
);
}
-export default function AgentCard({ agent, onKill, onDelete, onResume, completed, liveOutput, durations, onFeedbackChange, remote, peerName }) {
+export default function AgentCard({ agent, onPause, onKill, onDelete, onResume, completed, paused = false, liveOutput, durations, onFeedbackChange, remote, peerName }) {
const [expanded, setExpanded] = useState(false);
const [now, setNow] = useState(Date.now());
const [fullOutput, setFullOutput] = useState(null);
@@ -109,6 +110,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
const [stageOutputs, setStageOutputs] = useState({});
const [loadingStageId, setLoadingStageId] = useState(null);
const [processStats, setProcessStats] = useState(null);
+ const [pausing, setPausing] = useState(false);
const [killing, setKilling] = useState(false);
const [feedbackState, setFeedbackState] = useState(agent.feedback?.rating || null);
const [btwInput, setBtwInput] = useState('');
@@ -134,6 +136,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
// Determine if this is a system agent (health check, etc.)
const isSystemAgent = agent.taskId?.startsWith('sys-') || agent.id?.startsWith('sys-');
+ const inactive = completed || paused;
// Handle feedback submission
const submitFeedback = useCallback(async (rating) => {
@@ -200,10 +203,10 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
// Update duration display for running agents
useEffect(() => {
- if (completed) return;
+ if (inactive) return;
const interval = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(interval);
- }, [completed]);
+ }, [inactive]);
// Fetch process stats for running agents (skip for remote peers).
// Only overwrite prior stats on a successful response so a transient
@@ -217,7 +220,14 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
}
}, [agent.id]);
- useAutoRefetch(fetchStats, 5000, { enabled: !completed && !remote, pollOnly: true });
+ useAutoRefetch(fetchStats, 5000, { enabled: !inactive && !remote, pollOnly: true });
+
+ const handlePause = async () => {
+ if (!onPause) return;
+ setPausing(true);
+ await onPause(agent.id);
+ setPausing(false);
+ };
const handleKill = async () => {
if (!onKill) return;
@@ -228,7 +238,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
// Fetch full output when expanded for completed agents (skip for remote)
useEffect(() => {
- if (expanded && completed && !fullOutput && !loadingOutput && !remote) {
+ if (expanded && inactive && !fullOutput && !loadingOutput && !remote) {
setLoadingOutput(true);
api.getCosAgent(agent.id)
.then(data => {
@@ -240,7 +250,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
})
.finally(() => setLoadingOutput(false));
}
- }, [expanded, completed, agent.id, fullOutput, loadingOutput, remote, agent.output]);
+ }, [expanded, inactive, agent.id, fullOutput, loadingOutput, remote, agent.output]);
const duration = agent.completedAt
? new Date(agent.completedAt) - new Date(agent.startedAt)
@@ -256,7 +266,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
// Calculate duration estimate for running agents
// Uses P80 (80th percentile approximation) for progress bars to prevent premature 100%
const durationEstimate = useMemo(() => {
- if (completed || !durations) return null;
+ if (inactive || !durations) return null;
const taskType = extractTaskType(agent.metadata?.taskDescription);
const typeData = durations[taskType];
@@ -283,7 +293,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
}
return null;
- }, [completed, durations, agent.metadata?.taskDescription]);
+ }, [inactive, durations, agent.metadata?.taskDescription]);
// Calculate progress percentage using P80-based estimate
// Cap at 99% for active tasks — only completion can land on 100%
@@ -295,23 +305,23 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
// Calculate remaining time (ETA) based on P80 estimate
const remainingTime = useMemo(() => {
- if (!durationEstimate || completed) return null;
+ if (!durationEstimate || inactive) return null;
const remaining = durationEstimate.estimatedMs - duration;
if (remaining <= 0) return { remaining: 0, overBy: Math.abs(remaining), isOvertime: true };
return { remaining, overBy: 0, isOvertime: false };
- }, [duration, durationEstimate, completed]);
+ }, [duration, durationEstimate, inactive]);
// For running agents, use live output; for completed, use fetched full output or stored
const output = useMemo(() => (
- completed
+ inactive
? (fullOutput || agent.output || [])
: (liveOutput || agent.output || [])
- ), [completed, fullOutput, liveOutput, agent.output]);
+ ), [inactive, fullOutput, liveOutput, agent.output]);
const lastOutput = output.length > 0 ? output[output.length - 1]?.line : null;
// Extract recent tool activity (last few tool lines) for live display
const recentActivity = useMemo(() => {
- if (completed || output.length === 0) return [];
+ if (inactive || output.length === 0) return [];
const recent = [];
// Walk backwards to find the last 3 tool actions (🔧 lines with their → details)
for (let i = output.length - 1; i >= 0 && recent.length < 6; i--) {
@@ -321,7 +331,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
}
}
return recent;
- }, [completed, output]);
+ }, [inactive, output]);
// Count total tool invocations
const toolCount = useMemo(() => {
@@ -374,7 +384,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
return (
<div className={`bg-port-card border rounded-lg overflow-hidden ${
- completed
+ inactive
? isSystemAgent ? 'border-port-border opacity-50' : 'border-port-border opacity-75'
: 'border-port-accent/50'
}`}>
@@ -382,7 +392,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
{/* Top row: Agent ID, badges, and actions */}
<div className="flex items-start justify-between gap-2 mb-2">
<div className="flex items-center gap-2 flex-wrap min-w-0 flex-1">
- <Cpu size={16} aria-hidden="true" className={`shrink-0 ${completed ? 'text-gray-500' : 'text-port-accent animate-pulse'}`} />
+ <Cpu size={16} aria-hidden="true" className={`shrink-0 ${inactive ? 'text-gray-500' : 'text-port-accent animate-pulse'}`} />
<span className="font-mono text-sm text-gray-400 truncate">{agent.id}</span>
{remote && peerName && (
<span className="px-1.5 py-0.5 text-xs bg-port-accent/20 text-port-accent rounded shrink-0" title={`Remote agent on ${peerName}`}>
@@ -411,7 +421,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
{agent.metadata.model.replace('claude-', '').replace(/-\d+$/, '')}
</span>
)}
- {!completed && (
+ {!inactive && (
<span className={`px-2 py-0.5 text-xs rounded animate-pulse shrink-0 ${
agent.metadata?.phase === 'initializing' ? 'bg-yellow-500/20 text-yellow-400' :
'bg-port-accent/20 text-port-accent'
@@ -419,6 +429,11 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
{agent.metadata?.phase === 'initializing' ? 'Initializing' : 'Working'}
</span>
)}
+ {paused && (
+ <span className="px-2 py-0.5 text-xs rounded bg-yellow-500/20 text-yellow-400 shrink-0">
+ Paused
+ </span>
+ )}
{agent.metadata?.executionMode === 'tui' && (
<span className="px-2 py-0.5 text-xs rounded bg-emerald-500/20 text-emerald-400 shrink-0">
TUI
@@ -427,7 +442,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
</div>
{/* Actions - right side */}
<div className="flex items-center gap-2 shrink-0">
- {(output.length > 0 || completed) && (
+ {(output.length > 0 || inactive) && (
<button
onClick={() => setExpanded(!expanded)}
className="text-gray-500 hover:text-white transition-colors text-xs whitespace-nowrap"
@@ -436,8 +451,19 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
{expanded ? 'Hide' : 'Show'}
</button>
)}
+ {!inactive && onPause && (
+ <button
+ onClick={handlePause}
+ disabled={pausing}
+ className="flex items-center gap-1.5 px-2 py-1 text-xs rounded bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors disabled:opacity-50"
+ aria-label="Pause agent and preserve worktree"
+ >
+ {pausing ? <Loader2 size={12} aria-hidden="true" className="animate-spin" /> : <Pause size={12} aria-hidden="true" />}
+ <span className="hidden sm:inline">Pause</span>
+ </button>
+ )}
{/* Kill button (force SIGKILL) */}
- {!completed && onKill && (
+ {!inactive && onKill && (
<button
onClick={handleKill}
disabled={killing}
@@ -448,7 +474,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
<span className="hidden sm:inline">Kill</span>
</button>
)}
- {completed && onResume && (
+ {(completed || paused) && onResume && (
<button
onClick={() => onResume(agent)}
className="flex items-center gap-1 text-xs px-2 py-1 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors"
@@ -458,7 +484,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
<span className="hidden sm:inline">Resume</span>
</button>
)}
- {completed && onDelete && (
+ {(completed || paused) && onDelete && (
<button
onClick={() => onDelete(agent.id)}
className="p-1 text-gray-500 hover:text-port-error transition-colors"
@@ -473,7 +499,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
{/* Second row: Runtime, ETA, and process stats - compact inline display */}
<div className="flex items-center gap-2 flex-wrap text-xs mb-2">
{/* Duration with ETA for running agents */}
- {!completed && durationEstimate ? (
+ {!inactive && durationEstimate ? (
<span
className="flex items-center gap-1.5 text-gray-500 whitespace-nowrap"
title={`Based on ${durationEstimate.basedOn} completed ${durationEstimate.taskType} tasks (avg: ${formatDuration(durationEstimate.avgMs)}, est: ${formatDuration(durationEstimate.estimatedMs)})`}
@@ -510,7 +536,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
</>
)}
{/* Process stats for running agents - inline */}
- {!completed && processStats?.active && (
+ {!inactive && processStats?.active && (
<span className="flex items-center gap-1 px-2 py-0.5 rounded bg-port-success/20 text-port-success whitespace-nowrap"
title={`PID: ${processStats.pid} | State: ${processStats.state}`}>
<Activity size={10} aria-hidden="true" className="shrink-0" />
@@ -521,7 +547,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
<span className="font-mono">{processStats.memoryMb}MB</span>
</span>
)}
- {!completed && agent.metadata?.tuiSessionId && (
+ {!inactive && agent.metadata?.tuiSessionId && (
<Link
to={`/shell?session=${encodeURIComponent(agent.metadata.tuiSessionId)}`}
className="flex items-center gap-1 px-2 py-0.5 rounded bg-emerald-500/15 text-emerald-400 hover:bg-emerald-500/25 whitespace-nowrap"
@@ -542,7 +568,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
</button>
)}
{/* Show zombie warning if PID exists but process is dead */}
- {!completed && agent.pid && processStats && !processStats.active && (
+ {!inactive && agent.pid && processStats && !processStats.active && (
<span className="flex items-center gap-1 px-2 py-0.5 rounded bg-port-error/20 text-port-error whitespace-nowrap"
title="Process is not running - zombie agent">
<Skull size={10} aria-hidden="true" className="shrink-0" />
@@ -624,7 +650,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
)}
{/* Live activity feed for running agents */}
- {!completed && recentActivity.length > 0 && (
+ {!inactive && recentActivity.length > 0 && (
<div className="text-xs font-mono bg-port-bg/50 px-2 py-1.5 rounded space-y-0.5">
{recentActivity.map((o, i) => {
const line = o.line || '';
@@ -641,7 +667,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
)}
</div>
)}
- {!completed && recentActivity.length === 0 && lastOutput && (
+ {!inactive && recentActivity.length === 0 && lastOutput && (
<div className="text-xs text-gray-500 font-mono truncate bg-port-bg/50 px-2 py-1 rounded">
{lastOutput.substring(0, 100)}
</div>
@@ -663,7 +689,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
</div>
)}
- {!completed && !remote && agent.metadata?.executionMode === 'tui' && agent.metadata?.tuiKind === 'claude' && (
+ {!inactive && !remote && agent.metadata?.executionMode === 'tui' && agent.metadata?.tuiKind === 'claude' && (
<div className="mt-2 flex gap-2">
<input
type="text"
@@ -688,7 +714,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
)}
{/* Progress bar and ETA for running agents with estimates */}
- {!completed && durationEstimate && progress !== null && (
+ {!inactive && durationEstimate && progress !== null && (
<div className="mt-2">
<div className="h-1.5 bg-port-border rounded-full overflow-hidden">
<div
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index c1e775080b..0bdb65dce7 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -61,6 +61,13 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
onRefresh();
};
+ const handlePause = async (agentId) => {
+ const result = await api.pauseCosAgent(agentId, 'Paused from CoS agent list').catch(err => { toast.error(err.message); return null; });
+ if (!result) return;
+ toast.success('Agent paused');
+ onRefresh();
+ };
+
const handleDelete = useCallback(async (agentId) => {
const result = await api.deleteCosAgent(agentId).catch(err => { toast.error(err.message); return null; });
if (!result) return;
@@ -113,6 +120,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
// Running agents come from props (real-time via parent socket updates)
const runningAgents = agents.filter(a => a.status === 'running');
+ const pausedAgents = agents.filter(a => a.status === 'paused');
// Completed agents still in state (recently completed, not yet archived)
const recentCompleted = agents.filter(a => a.status === 'completed');
// Merge recent completed (from state) with loaded (from disk), deduplicate
@@ -178,6 +186,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
<AgentCard
key={agent.id}
agent={agent}
+ onPause={handlePause}
onKill={handleKill}
liveOutput={liveOutputs[agent.id]}
durations={durations}
@@ -187,6 +196,28 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
)}
</div>
+ {/* Paused Agents */}
+ {pausedAgents.length > 0 && (
+ <div>
+ <div className="flex items-center justify-between mb-3">
+ <h3 className="text-lg font-semibold text-white">Paused Agents</h3>
+ <span className="text-sm text-yellow-400">{pausedAgents.length} paused</span>
+ </div>
+ <div className="space-y-2">
+ {pausedAgents.map(agent => (
+ <AgentCard
+ key={agent.id}
+ agent={agent}
+ paused
+ onDelete={handleDelete}
+ onResume={handleResumeClick}
+ onFeedbackChange={onRefresh}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+
{/* Completed Agents */}
{(totalCount > 0 || recentCompleted.length > 0) && (
<div>
diff --git a/client/src/components/cos/tabs/ResumeAgentModal.jsx b/client/src/components/cos/tabs/ResumeAgentModal.jsx
index 665a07cc63..146f009399 100644
--- a/client/src/components/cos/tabs/ResumeAgentModal.jsx
+++ b/client/src/components/cos/tabs/ResumeAgentModal.jsx
@@ -13,12 +13,22 @@ export default function ResumeAgentModal({ agent, taskType = 'user', providers,
const resultInfo = agent.result
? (agent.result.success ? 'Previous run: Completed successfully' : `Previous run: Failed - ${agent.result.error || 'Unknown error'}`)
: '';
+ const pauseInfo = agent.status === 'paused'
+ ? `Previous run: Paused${agent.metadata?.pauseReason ? ` - ${agent.metadata.pauseReason}` : ''}`
+ : '';
+ const resumeWorkspace = agent.metadata?.resumeWorkspacePath || agent.metadata?.workspacePath;
+ const worktreeInfo = [
+ resumeWorkspace ? `Resume Workspace: ${resumeWorkspace}` : '',
+ agent.metadata?.worktreeBranch ? `Worktree Branch: ${agent.metadata.worktreeBranch}` : '',
+ agent.metadata?.isWorktree ? 'The previous worktree and any uncommitted changes were intentionally preserved. Continue from that workspace instead of starting over.' : ''
+ ].filter(Boolean).join('\n');
const initialContext = [
'## Previous Agent Context',
`Agent ID: ${agent.id}`,
`Original Task: ${taskDescription}`,
- resultInfo,
+ pauseInfo || resultInfo,
+ worktreeInfo ? `\n## Preserved Workspace\n${worktreeInfo}` : '',
outputSummary ? `\n## Last Output:\n\`\`\`\n${outputSummary}\n\`\`\`` : ''
].filter(Boolean).join('\n');
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 0ee97d0ac8..97c0ef3406 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -81,6 +81,10 @@ export const getCosAgentDates = () => request('/cos/agents/history');
export const getCosAgentsByDate = (date) => request(`/cos/agents/history/${date}`);
export const getCosAgent = (id) => request(`/cos/agents/${id}`);
export const terminateCosAgent = (id) => request(`/cos/agents/${id}/terminate`, { method: 'POST' });
+export const pauseCosAgent = (id, reason) => request(`/cos/agents/${id}/pause`, {
+ method: 'POST',
+ body: JSON.stringify({ reason })
+});
export const killCosAgent = (id) => request(`/cos/agents/${id}/kill`, { method: 'POST' });
export const getCosAgentStats = (id, options) => request(`/cos/agents/${id}/stats`, options);
export const getCosAgentPrompt = (id) => request(`/cos/agents/${id}/prompt`);
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index 09bdb712ac..478b9ac901 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -568,8 +568,9 @@ app.post('/spawn', async (req, res) => {
}
const output = agent?.outputBuffer || '';
+ const paused = agent?.paused === true;
- console.log(`${code === 0 ? '✅' : '❌'} Agent ${agentId} exited with code ${code}`);
+ console.log(`${paused ? '⏸️' : code === 0 ? '✅' : '❌'} Agent ${agentId} exited with code ${code}${paused ? ' after pause' : ''}`);
// Save output to agent directory
const agentDir = join(AGENTS_DIR, agentId);
@@ -578,6 +579,11 @@ app.post('/spawn', async (req, res) => {
}
await writeFile(join(agentDir, 'output.txt'), output).catch(() => {});
+ if (paused) {
+ activeAgents.delete(agentId);
+ return;
+ }
+
// Persist completion status to disk BEFORE emitting event
// This ensures recovery is possible even if the socket event is lost
const metadataPath = join(agentDir, 'metadata.json');
@@ -683,6 +689,37 @@ app.post('/kill/:agentId', async (req, res) => {
res.json({ success: true, agentId, pid: agent.pid, signal: 'SIGKILL' });
});
+/**
+ * Pause an agent: stop the child process without reporting normal completion.
+ * PortOS server persists the paused agent/task state and preserves the
+ * worktree; the runner just ensures the process stops spending tokens.
+ */
+app.post('/pause/:agentId', async (req, res) => {
+ const { agentId } = req.params;
+ const { reason = null } = req.body || {};
+ const agent = activeAgents.get(agentId);
+
+ if (!agent) {
+ return res.status(404).json({ error: 'Agent not found or not running' });
+ }
+
+ const pausedAt = new Date().toISOString();
+ console.log(`⏸️ Pausing agent ${agentId} (PID: ${agent.pid})${reason ? `: ${reason}` : ''}`);
+
+ agent.paused = true;
+ agent.pausedAt = pausedAt;
+ agent.pauseReason = reason;
+
+ agent.process.kill('SIGTERM');
+ setTimeout(() => {
+ const current = activeAgents.get(agentId);
+ if (current?.paused) current.process.kill('SIGKILL');
+ }, 5000);
+
+ emitToServer('agent:paused', { agentId, taskId: agent.taskId, pid: agent.pid, pausedAt, reason });
+ res.json({ success: true, agentId, pid: agent.pid, pausedAt });
+});
+
/**
* Kill all agents
*/
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index 839766dfbe..03044a30ca 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -29,6 +29,7 @@ vi.mock('../services/cos.js', () => ({
getAgentsByDate: vi.fn(),
getAgent: vi.fn(),
terminateAgent: vi.fn(),
+ pauseAgent: vi.fn(),
killAgent: vi.fn(),
getAgentProcessStats: vi.fn(),
deleteAgent: vi.fn(),
@@ -473,6 +474,27 @@ describe('CoS Routes', () => {
});
});
+ describe('POST /api/cos/agents/:id/pause', () => {
+ it('should pause agent with reason', async () => {
+ cos.pauseAgent.mockResolvedValue({ success: true, agentId: 'agent-001', pausedAt: '2026-05-25T12:00:00.000Z' });
+
+ const response = await request(app)
+ .post('/api/cos/agents/agent-001/pause')
+ .send({ reason: 'billing window' });
+
+ expect(response.status).toBe(200);
+ expect(cos.pauseAgent).toHaveBeenCalledWith('agent-001', 'billing window');
+ });
+
+ it('should return 404 if agent not found', async () => {
+ cos.pauseAgent.mockResolvedValue({ error: 'Agent not found or not running' });
+
+ const response = await request(app).post('/api/cos/agents/agent-999/pause');
+
+ expect(response.status).toBe(404);
+ });
+ });
+
describe('POST /api/cos/agents/:id/kill', () => {
it('should force kill agent', async () => {
cos.killAgent.mockResolvedValue({ success: true, agentId: 'agent-001', signal: 'SIGKILL' });
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index 471215ec33..e1c26da738 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -68,6 +68,15 @@ router.post('/agents/:id/terminate', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/cos/agents/:id/pause - Stop process, preserve task/worktree for later resume
+router.post('/agents/:id/pause', asyncHandler(async (req, res) => {
+ const result = await cos.pauseAgent(req.params.id, req.body?.reason || null);
+ if (result?.error) {
+ throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(result);
+}));
+
// POST /api/cos/agents/:id/kill - Force kill agent (immediate SIGKILL)
router.post('/agents/:id/kill', asyncHandler(async (req, res) => {
const result = await cos.killAgent(req.params.id);
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 196d27c9bf..7cde7b5e64 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -18,7 +18,7 @@ import { completeExecution, errorExecution } from './toolStateMachine.js';
import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { completeAgentRun } from './agentRunTracking.js';
import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';
-import { activeAgents, userTerminatedAgents } from './agentState.js';
+import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';
import { normalizeReviewers } from '../lib/validation.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
@@ -578,6 +578,13 @@ export async function spawnDirectly({
await writeFile(outputFile, outputBuffer).catch(() => {});
+ if (pausedAgents.has(agentId)) {
+ pausedAgents.delete(agentId);
+ if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);
+ activeAgents.delete(agentId);
+ return;
+ }
+
// Use raw stream buffer for error analysis (contains full JSON with error details)
const analysisBuffer = rawStreamBuffer || outputBuffer;
const errorAnalysis = finalSuccess ? null : (immediateFallbackAnalysis || analyzeAgentFailure(analysisBuffer, task, model));
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 61da8d401d..ae89b0174e 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -7,16 +7,19 @@
import { join } from 'path';
import { emitLog } from './cosEvents.js';
-import { completeAgent } from './cosAgents.js';
+import { completeAgent, updateAgent } from './cosAgents.js';
import { updateTask, addTask, getTaskById } from './cos.js';
-import { terminateAgentViaRunner, killAgentViaRunner, getAgentStatsFromRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
+import { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAgentStatsFromRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import { unregisterSpawnedAgent } from './agents.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-import { activeAgents, runnerAgents, userTerminatedAgents, useRunner } from './agentState.js';
+import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunner } from './agentState.js';
import { cleanupAgentWorktree, syncRunnerAgents } from './agentLifecycle.js';
import { checkForTaskCommit } from './agentRunTracking.js';
import { PATHS } from '../lib/fileUtils.js';
+import { release } from './executionLanes.js';
+import { completeExecution, errorExecution } from './toolStateMachine.js';
+import * as shellService from './shell.js';
const ROOT_DIR = PATHS.root;
@@ -52,6 +55,95 @@ async function terminateRunnerAgent(agentId, runnerFn, errorMessage, blockedReas
return result;
}
+async function markPausedTask(agentInfo, agentId, pausedAt, reason) {
+ const task = agentInfo?.task || (agentInfo?.taskId ? await getTaskById(agentInfo.taskId).catch(() => null) : null);
+ if (!task) return;
+ const metadata = {
+ ...task.metadata,
+ blockedReason: reason ? `Paused by user: ${reason}` : 'Paused by user',
+ blockedCategory: 'agent-paused',
+ blockedAt: pausedAt,
+ pausedAt,
+ pausedAgentId: agentId
+ };
+ if (agentInfo?.workspacePath) metadata.resumeWorkspacePath = agentInfo.workspacePath;
+ if (agentInfo?.runId) metadata.resumeRunId = agentInfo.runId;
+ await updateTask(task.id, {
+ status: 'blocked',
+ metadata
+ }, task.taskType || 'user');
+}
+
+async function markAgentPaused(agentId, agentInfo, pausedAt, reason) {
+ await updateAgent(agentId, {
+ status: 'paused',
+ pausedAt,
+ metadata: {
+ phase: 'paused',
+ pauseReason: reason || null,
+ pausedAt,
+ resumeWorkspacePath: agentInfo?.workspacePath || null
+ }
+ });
+ await markPausedTask(agentInfo, agentId, pausedAt, reason);
+ release(agentId);
+ if (agentInfo?.executionId) {
+ errorExecution(agentInfo.executionId, { message: reason ? `Agent paused by user: ${reason}` : 'Agent paused by user', code: 'agent-paused' });
+ completeExecution(agentInfo.executionId, { success: false, paused: true });
+ }
+}
+
+/**
+ * Pause an agent without finalizing its task or cleaning up its worktree.
+ * The underlying process is stopped, but the persisted agent remains paused
+ * so a later resume task can use the same workspace/change context.
+ */
+export async function pauseAgent(agentId, reason = null) {
+ const pausedAt = new Date().toISOString();
+
+ if (runnerAgents.has(agentId)) {
+ const agentInfo = runnerAgents.get(agentId);
+ if (agentInfo?.initializationTimeout) clearTimeout(agentInfo.initializationTimeout);
+ pausedAgents.set(agentId, { pausedAt, reason });
+ const result = await pauseAgentViaRunner(agentId, reason).catch(err => ({ success: false, error: err.message }));
+ if (!result.success) {
+ pausedAgents.delete(agentId);
+ return result;
+ }
+ await markAgentPaused(agentId, agentInfo, pausedAt, reason);
+ runnerAgents.delete(agentId);
+ emitLog('info', `⏸️ Paused runner agent ${agentId}${reason ? `: ${reason}` : ''}`, { agentId, reason });
+ return { success: true, agentId, pausedAt, mode: 'runner' };
+ }
+
+ const agent = activeAgents.get(agentId);
+ if (!agent) {
+ return { success: false, error: 'Agent not found or not running' };
+ }
+
+ pausedAgents.set(agentId, { pausedAt, reason });
+ await markAgentPaused(agentId, agent, pausedAt, reason);
+
+ if (agent.tuiSessionId) {
+ shellService.writeToSession(agent.tuiSessionId, '\x1b');
+ setTimeout(() => {
+ if (activeAgents.has(agentId)) shellService.killSession(agent.tuiSessionId);
+ }, 250);
+ } else {
+ agent.process.kill('SIGTERM');
+ const killTimer = setTimeout(() => {
+ if (activeAgents.has(agentId)) {
+ agent.process.kill('SIGKILL');
+ }
+ }, 5000);
+ const agentEntry = activeAgents.get(agentId);
+ if (agentEntry) agentEntry.killTimer = killTimer;
+ }
+
+ emitLog('info', `⏸️ Paused agent ${agentId}${reason ? `: ${reason}` : ''}`, { agentId, reason });
+ return { success: true, agentId, pausedAt, mode: agent.tuiSessionId ? 'tui' : 'direct' };
+}
+
/**
* Terminate an agent (graceful SIGTERM with SIGKILL fallback).
*/
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 97db0ee496..6b5b54abe2 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -44,26 +44,34 @@ vi.mock('./agentRunTracking.js', () => ({
}));
// Stub other transitive imports we don't exercise in handleOrphanedTask.
-vi.mock('./cosAgents.js', () => ({ completeAgent: vi.fn() }));
+vi.mock('./cosAgents.js', () => ({ completeAgent: vi.fn(), updateAgent: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./cosRunnerClient.js', () => ({
terminateAgentViaRunner: vi.fn(),
killAgentViaRunner: vi.fn(),
+ pauseAgentViaRunner: vi.fn(),
getAgentStatsFromRunner: vi.fn(),
getActiveAgentsFromRunner: vi.fn().mockResolvedValue([])
}));
vi.mock('./agents.js', () => ({ unregisterSpawnedAgent: vi.fn() }));
+vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));
+vi.mock('./toolStateMachine.js', () => ({ completeExecution: vi.fn(), errorExecution: vi.fn() }));
+vi.mock('./shell.js', () => ({ writeToSession: vi.fn(), killSession: vi.fn() }));
vi.mock('./agentLifecycle.js', () => ({
cleanupAgentWorktree: vi.fn(),
syncRunnerAgents: vi.fn().mockResolvedValue(0)
}));
vi.mock('./worktreeManager.js', () => ({ cleanupOrphanedWorktrees: vi.fn() }));
-import { handleOrphanedTask } from './agentManagement.js';
-import { updateTask, addTask } from './cos.js';
+import { handleOrphanedTask, pauseAgent } from './agentManagement.js';
+import { updateTask, addTask, getTaskById } from './cos.js';
+import { updateAgent } from './cosAgents.js';
+import { activeAgents, pausedAgents } from './agentState.js';
describe('handleOrphanedTask — duplicate-investigation guard', () => {
beforeEach(() => {
vi.clearAllMocks();
+ activeAgents.clear();
+ pausedAgents.clear();
});
it('skips tasks already blocked with blockedCategory=max-retries (no new investigation task)', async () => {
@@ -151,6 +159,53 @@ describe('handleOrphanedTask — duplicate-investigation guard', () => {
});
});
+describe('pauseAgent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ activeAgents.clear();
+ pausedAgents.clear();
+ });
+
+ it('marks a direct agent paused, blocks the task as agent-paused, and signals SIGTERM', async () => {
+ const kill = vi.fn();
+ activeAgents.set('agent-1', {
+ process: { kill },
+ taskId: 'task-1',
+ runId: 'run-1',
+ pid: 123,
+ workspacePath: '/repo/worktree',
+ executionId: 'exec-1',
+ laneName: 'standard'
+ });
+ getTaskById.mockResolvedValue({
+ id: 'task-1',
+ taskType: 'user',
+ description: 'Do work',
+ metadata: { openPR: true }
+ });
+
+ const result = await pauseAgent('agent-1', 'billing window');
+
+ expect(result).toMatchObject({ success: true, agentId: 'agent-1', mode: 'direct' });
+ expect(updateAgent).toHaveBeenCalledWith('agent-1', expect.objectContaining({
+ status: 'paused',
+ metadata: expect.objectContaining({ phase: 'paused', pauseReason: 'billing window' })
+ }));
+ expect(updateTask).toHaveBeenCalledWith('task-1', expect.objectContaining({
+ status: 'blocked',
+ metadata: expect.objectContaining({
+ blockedCategory: 'agent-paused',
+ pausedAgentId: 'agent-1',
+ resumeWorkspacePath: '/repo/worktree',
+ resumeRunId: 'run-1'
+ })
+ }), 'user');
+ expect(kill).toHaveBeenCalledWith('SIGTERM');
+ expect(pausedAgents.has('agent-1')).toBe(true);
+ clearTimeout(activeAgents.get('agent-1')?.killTimer);
+ });
+});
+
// ─── Inline replica of parseTasklistCsvRow ───────────────────────────────────
// Keep in sync with the implementation in agentManagement.js.
diff --git a/server/services/agentState.js b/server/services/agentState.js
index 2787f3a249..555bf218eb 100644
--- a/server/services/agentState.js
+++ b/server/services/agentState.js
@@ -12,6 +12,10 @@ export const runnerAgents = new Map();
// userTerminatedAgents: agents the user explicitly killed (Set<agentId>)
export const userTerminatedAgents = new Set();
+// pausedAgents: agents whose process is being stopped without finalizing the
+// task or cleaning up the worktree (Map<agentId, { pausedAt, reason }>)
+export const pausedAgents = new Map();
+
// spawningTasks: tasks currently being spawned (Set<taskId>) — deduplication guard
export const spawningTasks = new Set();
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 4674ce84fa..6b1ff672dc 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -15,7 +15,7 @@ import { appendAgentOutputLines, updateAgent } from './cosAgents.js';
import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';
import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';
-import { activeAgents, userTerminatedAgents } from './agentState.js';
+import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { resolveCliModel } from '../lib/providerModels.js';
import { createStreamingAnsiStripper } from '../lib/ansiStrip.js';
@@ -400,6 +400,14 @@ export async function spawnTuiAgent({
if (rawFlushing) await rawFlushing.catch(() => {});
await flushPendingRawChunks();
+ if (pausedAgents.has(agentId)) {
+ pausedAgents.delete(agentId);
+ const pausedAgentData = activeAgents.get(agentId);
+ if (pausedAgentData?.pid) unregisterSpawnedAgent(pausedAgentData.pid);
+ activeAgents.delete(agentId);
+ return;
+ }
+
const duration = Date.now() - (agentData?.startedAt || Date.now());
const terminatedByUser = userTerminatedAgents.has(agentId);
if (terminatedByUser) userTerminatedAgents.delete(agentId);
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 6e493ae938..af47e27895 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -65,7 +65,8 @@ vi.mock('./agentLifecycle.js', () => ({
vi.mock('./agentState.js', () => ({
activeAgents: new Map(),
- userTerminatedAgents: new Set()
+ userTerminatedAgents: new Set(),
+ pausedAgents: new Map()
}));
vi.mock('fs', () => ({
diff --git a/server/services/cos.js b/server/services/cos.js
index f042770a77..a2c161d49d 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -53,7 +53,7 @@ import { cosEvents, emitLog } from './cosEvents.js';
export { cosEvents, emitLog };
// Agent lifecycle (re-export for backward compat with `import * as cos`)
-export { registerAgent, updateAgent, completeAgent, appendAgentOutput, getAgents, getAgentDates, getAgentsByDate, getAgent, getAgentPrompt, terminateAgent, killAgent, sendBtwToAgent, getAgentProcessStats, cleanupZombieAgents, deleteAgent, submitAgentFeedback, getFeedbackStats, extractTaskType, archiveStaleAgents, clearCompletedAgents, pruneOldAgentArchives } from './cosAgents.js';
+export { registerAgent, updateAgent, completeAgent, appendAgentOutput, getAgents, getAgentDates, getAgentsByDate, getAgent, getAgentPrompt, terminateAgent, pauseAgent, killAgent, sendBtwToAgent, getAgentProcessStats, cleanupZombieAgents, deleteAgent, submitAgentFeedback, getFeedbackStats, extractTaskType, archiveStaleAgents, clearCompletedAgents, pruneOldAgentArchives } from './cosAgents.js';
// Reports and activity (re-export for backward compat with `import * as cos`)
export { generateReport, getReport, getTodayReport, listReports, listBriefings, getBriefing, getLatestBriefing, getTodayActivity, getRecentTasks, formatRelativeTime } from './cosReports.js';
@@ -201,6 +201,7 @@ export async function getStatus() {
// Count active agents from state
const activeAgents = Object.values(state.agents).filter(a => a.status === 'running').length;
+ const pausedAgents = Object.values(state.agents).filter(a => a.status === 'paused').length;
// Derive tasksCompleted from union of index (disk) + state completed agents,
// since state.stats.tasksCompleted can drift after state resets
@@ -216,6 +217,7 @@ export async function getStatus() {
config: state.config,
stats: { ...state.stats, tasksCompleted },
activeAgents,
+ pausedAgents,
provider: provider ? { id: provider.id, name: provider.name } : null
};
}
@@ -3297,4 +3299,3 @@ export async function init() {
await start();
}
}
-
diff --git a/server/services/cosAgents.js b/server/services/cosAgents.js
index 928c8d4d2c..b6e6527b99 100644
--- a/server/services/cosAgents.js
+++ b/server/services/cosAgents.js
@@ -466,9 +466,10 @@ export async function getAgent(agentId) {
}
if (!agent) return null;
- // For completed agents, read full output from file
- if (agent.status === 'completed') {
- const dateStr = agent.completedAt?.slice(0, 10);
+ // Completed agents live in date buckets; paused agents remain in the flat
+ // agent dir but should still expose their preserved full transcript.
+ if (agent.status === 'completed' || agent.status === 'paused') {
+ const dateStr = agent.status === 'completed' ? agent.completedAt?.slice(0, 10) : null;
const agentDir = dateStr ? getAgentDir(agentId, dateStr) : getAgentDir(agentId);
const repaired = await repairCodexTaskSummary(agentDir, agent);
if (repaired) agent = { ...agent, metadata: { ...agent.metadata, taskSummary: repaired } };
@@ -476,9 +477,10 @@ export async function getAgent(agentId) {
if (existsSync(outputFile)) {
const fullOutput = await readFile(outputFile, 'utf-8');
const lines = fullOutput.split('\n').filter(line => line.trim());
+ const timestamp = agent.completedAt || agent.pausedAt;
return {
...agent,
- output: lines.map(line => ({ line, timestamp: agent.completedAt }))
+ output: lines.map(line => ({ line, timestamp }))
};
}
}
@@ -508,6 +510,12 @@ export async function terminateAgent(agentId) {
return { success: true, agentId };
}
+// Pause an agent without completing its task or cleaning up its worktree.
+export async function pauseAgent(agentId, reason = null) {
+ const { pauseAgent: pauseAgentFromSpawner } = await import('./subAgentSpawner.js');
+ return pauseAgentFromSpawner(agentId, reason);
+}
+
// Force kill an agent with SIGKILL (immediate, no graceful shutdown)
export async function killAgent(agentId) {
const { killAgent: killAgentFromSpawner } = await import('./subAgentSpawner.js');
diff --git a/server/services/cosAgents.test.js b/server/services/cosAgents.test.js
new file mode 100644
index 0000000000..8d39108e90
--- /dev/null
+++ b/server/services/cosAgents.test.js
@@ -0,0 +1,51 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdir, rm, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const mockCosState = vi.hoisted(() => ({
+ agentsDir: `/private/tmp/portos-cos-agents-test-${process.pid}`,
+ state: null
+}));
+
+vi.mock('./cosState.js', () => ({
+ AGENTS_DIR: mockCosState.agentsDir,
+ loadState: vi.fn(async () => mockCosState.state),
+ saveState: vi.fn(),
+ withStateLock: async (fn) => fn()
+}));
+
+import { getAgent } from './cosAgents.js';
+
+describe('cosAgents', () => {
+ beforeEach(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ await mkdir(mockCosState.agentsDir, { recursive: true });
+ mockCosState.state = { agents: {} };
+ });
+
+ afterEach(async () => {
+ await rm(mockCosState.agentsDir, { recursive: true, force: true });
+ });
+
+ it('hydrates paused agents with full preserved output from output.txt', async () => {
+ const agentId = 'agent-paused';
+ const pausedAt = '2026-05-25T12:00:00.000Z';
+ mockCosState.state.agents[agentId] = {
+ id: agentId,
+ status: 'paused',
+ pausedAt,
+ output: [{ line: 'state tail only', timestamp: pausedAt }]
+ };
+
+ await mkdir(join(mockCosState.agentsDir, agentId), { recursive: true });
+ await writeFile(join(mockCosState.agentsDir, agentId, 'output.txt'), 'full line one\nfull line two\n');
+
+ const agent = await getAgent(agentId);
+
+ expect(agent.status).toBe('paused');
+ expect(agent.output).toEqual([
+ { line: 'full line one', timestamp: pausedAt },
+ { line: 'full line two', timestamp: pausedAt }
+ ]);
+ });
+});
diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.js
index c7e97e3e8d..5bbac495a2 100644
--- a/server/services/cosRunnerClient.js
+++ b/server/services/cosRunnerClient.js
@@ -183,6 +183,22 @@ export async function killAgentViaRunner(agentId) {
return response.json();
}
+/**
+ * Pause an agent via the runner without emitting normal completion cleanup.
+ */
+export async function pauseAgentViaRunner(agentId, reason = null) {
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/pause/${agentId}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ reason })
+ }, 30000);
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error || 'Failed to pause agent');
+ }
+ return response.json();
+}
+
/**
* Get process stats for an agent
*/
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index e3fb8d60ad..84011168dd 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -26,7 +26,7 @@ export { ERROR_PATTERNS, analyzeAgentFailure, createInvestigationTask, API_ACCES
export { buildAgentPrompt, getAppWorkspace, getAppDataForTask, generateJiraTitle, createJiraTicketForTask, getClaudeMdContext, buildCompactionSection, detectSkillTemplate, loadSkillTemplate } from './agentPromptBuilder.js';
export { spawnDirectly, createStreamJsonParser, summarizeToolInput, safeParse, buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv } from './agentCliSpawning.js';
export { syncRunnerAgents, spawnAgentForTask, waitForRunnerStability, spawnViaRunner, extractFinalSummary, extractPipelineOutputSummary, handlePipelineProgression, handleAgentCompletion, cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp } from './agentLifecycle.js';
-export { terminateAgent, getActiveAgents, killAgent, getAgentProcessStats, killAllAgents, isPidAlive, cleanupOrphanedAgents, handleOrphanedTask } from './agentManagement.js';
+export { terminateAgent, pauseAgent, getActiveAgents, killAgent, getAgentProcessStats, killAllAgents, isPidAlive, cleanupOrphanedAgents, handleOrphanedTask } from './agentManagement.js';
export { processAgentCompletion } from './agentCompletion.js';
const ROOT_DIR = PATHS.root;