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

Relaunch a stalled CoS agent onto a different provider/model in one click

[._.]/ Adam Eivy485767cf5b3f
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 9f85cd1d05..ea19094de9 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -104,7 +104,7 @@ function TranscriptTruncationNotice({ transcript }) {
);
}
-export default function AgentCard({ agent, onPause, onKill, onDelete, onResume, completed, paused = false, liveOutput, durations, onFeedbackChange, remote, peerName }) {
+export default function AgentCard({ agent, onPause, onKill, onDelete, onResume, onRelaunch, completed, paused = false, liveOutput, durations, onFeedbackChange, remote, peerName }) {
const [expanded, setExpanded] = useState(false);
const [now, setNow] = useState(Date.now());
const [fullOutput, setFullOutput] = useState(null);
@@ -474,6 +474,16 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,
{expanded ? 'Hide' : 'Show'}
</button>
)}
+ {!inactive && onRelaunch && (
+ <button
+ onClick={() => onRelaunch(agent)}
+ className="flex items-center gap-1.5 px-2 py-1 text-xs rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors"
+ aria-label="Relaunch this agent's task on a different provider or model"
+ >
+ <RefreshCw size={12} aria-hidden="true" />
+ <span className="hidden sm:inline">Relaunch</span>
+ </button>
+ )}
{!inactive && onPause && (
<button
onClick={handlePause}
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsx
index 91e452b2aa..d03645e10f 100644
--- a/client/src/components/cos/tabs/AgentsTab.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.jsx
@@ -5,6 +5,7 @@ import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import AgentCard from './AgentCard';
import ResumeAgentModal from './ResumeAgentModal';
+import RelaunchAgentModal from './RelaunchAgentModal';
import BrailleSpinner from '../../BrailleSpinner';
import InlineConfirmRow from '../../ui/InlineConfirmRow';
@@ -31,6 +32,7 @@ const needsAgentFeedback = (agent) => {
export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, apps }) {
const [searchParams, setSearchParams] = useSearchParams();
const [resumingAgent, setResumingAgent] = useState(null);
+ const [relaunchingAgent, setRelaunchingAgent] = useState(null);
const [durations, setDurations] = useState(null);
const [searchQuery, setSearchQuery] = useState('');
const [feedbackUpdates, setFeedbackUpdates] = useState({});
@@ -125,6 +127,11 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
setResumingAgent(agent);
};
+ // A stalled RUNNING agent (a CLI parked on a provider usage limit) moves to a
+ // different provider/model in one step. The dialog owns the call and the
+ // outcome message — see RelaunchAgentModal.
+ const handleRelaunchClick = useCallback((agent) => setRelaunchingAgent(agent), []);
+
const handleFeedbackChange = useCallback((updatedAgent) => {
if (updatedAgent?.id && updatedAgent.feedback) {
setFeedbackUpdates(prev => ({ ...prev, [updatedAgent.id]: updatedAgent.feedback }));
@@ -253,6 +260,7 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
agent={agent}
onPause={handlePause}
onKill={handleKill}
+ onRelaunch={handleRelaunchClick}
liveOutput={liveOutputs[agent.id]}
durations={durations}
/>
@@ -412,6 +420,17 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a
</div>
)}
+ {/* Relaunch Modal */}
+ {relaunchingAgent && (
+ <RelaunchAgentModal
+ agent={relaunchingAgent}
+ providers={providers}
+ apps={apps}
+ onDone={onRefresh}
+ onClose={() => setRelaunchingAgent(null)}
+ />
+ )}
+
{/* Resume Modal */}
{resumingAgent && (
<ResumeAgentModal
diff --git a/client/src/components/cos/tabs/AgentsTab.test.jsx b/client/src/components/cos/tabs/AgentsTab.test.jsx
index e324840c6d..ce4c6c6f2b 100644
--- a/client/src/components/cos/tabs/AgentsTab.test.jsx
+++ b/client/src/components/cos/tabs/AgentsTab.test.jsx
@@ -10,6 +10,7 @@ vi.mock('../../../services/api', () => ({
getCosAgentsByDate: vi.fn(),
clearCompletedCosAgents: vi.fn(),
resumeCosAgent: vi.fn(),
+ relaunchCosAgent: vi.fn(),
addCosTask: vi.fn(),
}));
@@ -18,12 +19,15 @@ vi.mock('../../ui/Toast', () => ({
}));
vi.mock('./AgentCard', () => ({
- default: ({ agent, onFeedbackChange, onResume }) => (
+ default: ({ agent, onFeedbackChange, onResume, onRelaunch }) => (
<div data-testid={`agent-${agent.id}`}>
<span>{agent.metadata?.taskDescription}</span>
{onResume && (
<button type="button" onClick={() => onResume(agent)}>Resume {agent.id}</button>
)}
+ {onRelaunch && (
+ <button type="button" onClick={() => onRelaunch(agent)}>Relaunch {agent.id}</button>
+ )}
{!agent.feedback?.rating && (
<button
type="button"
@@ -59,6 +63,15 @@ vi.mock('./ResumeAgentModal', () => ({
</button>
),
}));
+// The dialog owns the relaunch call and its outcome message; the tab's job is to
+// mount it against the right agent and refresh when it is done.
+vi.mock('./RelaunchAgentModal', () => ({
+ default: ({ agent, onDone }) => (
+ <button type="button" onClick={() => onDone?.({ mode: 'requeued' })}>
+ Relaunch dialog for {agent.id}
+ </button>
+ ),
+}));
vi.mock('../../ui/InlineConfirmRow', () => ({ default: () => null }));
import * as api from '../../../services/api';
@@ -94,6 +107,45 @@ beforeEach(() => {
api.getCosAgentsByDate.mockResolvedValue([]);
});
+// A relaunch is offered only on a RUNNING agent — it is the recovery for a run
+// that is alive but stalled (a CLI parked on a provider usage limit), where the
+// existing Pause/Kill/Resume trio either loses the worktree or parks the task.
+describe('AgentsTab relaunch routing', () => {
+ const runningAgent = {
+ id: 'agent-live',
+ taskId: 'task-abc',
+ status: 'running',
+ startedAt: '2026-07-13T09:00:00.000Z',
+ metadata: { taskDescription: 'Stalled on a usage limit' },
+ };
+
+ it('opens the relaunch dialog on the running agent and refreshes when it finishes', async () => {
+ const user = userEvent.setup();
+ const onRefresh = vi.fn();
+ renderTab([runningAgent], onRefresh);
+ await act(async () => {});
+
+ await user.click(screen.getByRole('button', { name: 'Relaunch agent-live' }));
+ await user.click(screen.getByRole('button', { name: 'Relaunch dialog for agent-live' }));
+
+ await waitFor(() => expect(onRefresh).toHaveBeenCalled());
+ // A relaunch moves the EXISTING task, so neither resume door may fire — a
+ // second task would spawn a second agent.
+ expect(api.addCosTask).not.toHaveBeenCalled();
+ expect(api.resumeCosAgent).not.toHaveBeenCalled();
+ });
+
+ it('offers no relaunch on a settled agent, which has no live run to move', async () => {
+ renderTab([completedAgent('agent-done', 'Finished work')]);
+ await act(async () => {});
+
+ // The card renders (its Resume door is offered), so the missing Relaunch is a
+ // real absence rather than a row that never mounted.
+ expect(screen.getByRole('button', { name: 'Resume agent-done' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Relaunch agent-done' })).toBeNull();
+ });
+});
+
describe('AgentsTab resume routing', () => {
const pausedAgent = {
id: 'agent-paused',
diff --git a/client/src/components/cos/tabs/RelaunchAgentModal.jsx b/client/src/components/cos/tabs/RelaunchAgentModal.jsx
new file mode 100644
index 0000000000..842834b40b
--- /dev/null
+++ b/client/src/components/cos/tabs/RelaunchAgentModal.jsx
@@ -0,0 +1,173 @@
+import { useMemo, useState } from 'react';
+import { RefreshCw, Loader2, X } from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from '../../ui/Toast';
+import Modal from '../../ui/Modal';
+import AppContextPicker from '../../AppContextPicker';
+import ProviderModelSelector from '../../ProviderModelSelector';
+import { FormField } from '../../ui/FormField';
+import { useAsyncAction } from '../../../hooks/useAsyncAction';
+import { effortAwareModelOptions, seedModelEffort } from '../../../utils/providers';
+
+// What each relaunch outcome actually did. The server reuses `resumeAgent`'s
+// modes (agentManagement.js): only `requeued` restarts the work — `already-active`
+// and `superseded` deliberately queue NOTHING, so an unmapped mode must not fall
+// through to a message claiming the task was relaunched.
+const RELAUNCH_MESSAGES = {
+ requeued: 'Relaunched — the task is queued again on its preserved worktree',
+ 'already-active': 'Its task is already queued or running — nothing new was created',
+ superseded: 'A later agent now holds this task paused — that pause was left intact',
+};
+
+/**
+ * Move a RUNNING agent's task onto a different provider/model/effort.
+ *
+ * The case this exists for: a run that is alive but going nowhere because its CLI
+ * is parked on a provider usage limit. The server pauses the agent (worktree
+ * preserved) and requeues its OWN task with these overrides — so the dialog only
+ * edits what the next run should use, not what the task is.
+ *
+ * It owns the call and the outcome message rather than handing a payload back,
+ * because it is mounted from two places (the agent card and the in-progress task
+ * card) and the server's mode enum should have exactly one client reader.
+ */
+export default function RelaunchAgentModal({ agent, providers, apps, onDone, onClose }) {
+ const currentProvider = agent?.metadata?.providerId || agent?.metadata?.provider || '';
+ const taskDescription = agent?.metadata?.taskDescription || agent?.taskId || 'Current task';
+
+ const [formData, setFormData] = useState(() => {
+ // Seeded from the stalled run so the dialog opens on what it was using —
+ // and, for a pre-split Antigravity id, on the two halves the selects list.
+ const seeded = seedModelEffort(
+ providers?.find(p => p.id === currentProvider),
+ agent?.metadata?.model,
+ agent?.metadata?.effort,
+ );
+ return {
+ provider: currentProvider,
+ model: seeded.model,
+ effort: seeded.effort,
+ app: agent?.metadata?.taskApp || agent?.metadata?.app || '',
+ note: ''
+ };
+ });
+
+ const selectedProvider = useMemo(
+ () => providers?.find(p => p.id === formData.provider),
+ [providers, formData.provider]
+ );
+ const availableModels = useMemo(
+ () => effortAwareModelOptions(selectedProvider, formData.model),
+ [selectedProvider, formData.model]
+ );
+
+ const [submit, submitting] = useAsyncAction(async () => {
+ // Blank means "keep what the stalled run had" (AGENTS.md's absent-vs-empty
+ // rule) — the server treats a falsy override as unchanged.
+ const result = await api.relaunchCosAgent(agent.id, {
+ provider: formData.provider || undefined,
+ model: formData.model || undefined,
+ effort: formData.effort || undefined,
+ app: formData.app || undefined,
+ context: formData.note.trim() || undefined
+ }, { silent: true });
+ toast.success(RELAUNCH_MESSAGES[result?.mode] || 'Relaunched');
+ onDone?.(result);
+ onClose();
+ return result;
+ }, { errorMessage: 'Failed to relaunch agent' });
+
+ return (
+ <Modal
+ open
+ onClose={onClose}
+ closeOnBackdrop={false}
+ size="lg"
+ align="none"
+ backdropClassName="bg-black/50"
+ panelClassName="bg-port-card border border-port-border rounded-xl p-6"
+ ariaLabelledBy="relaunch-agent-title"
+ >
+ <div className="flex items-center justify-between mb-4">
+ <h2 id="relaunch-agent-title" className="text-xl font-bold text-white">
+ Relaunch on a different model
+ </h2>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close relaunch agent modal"
+ className="text-gray-500 hover:text-white transition-colors min-h-[44px] min-w-[44px] flex items-center justify-center"
+ >
+ <X size={20} aria-hidden="true" />
+ </button>
+ </div>
+
+ <div className="mb-4 p-3 bg-port-bg border border-port-border rounded-lg">
+ <div className="text-sm text-gray-400 mb-1">Current task</div>
+ <div className="text-white">{taskDescription}</div>
+ <div className="text-sm text-gray-400 mt-2">
+ This stops the running agent and requeues the same task on the worktree it leaves
+ behind — no second agent, and nothing to clean up afterward.
+ </div>
+ </div>
+
+ <form
+ onSubmit={e => { e.preventDefault(); submit(); }}
+ className="space-y-4"
+ >
+ <FormField label="Target App">
+ <AppContextPicker
+ apps={apps}
+ value={formData.app}
+ onChange={app => setFormData(d => ({ ...d, app }))}
+ showRepoPath={false}
+ ariaLabel="Target app"
+ />
+ </FormField>
+
+ <ProviderModelSelector
+ providers={providers || []}
+ selectedProviderId={formData.provider}
+ selectedModel={formData.model}
+ availableModels={availableModels}
+ onProviderChange={provider => setFormData(d => ({ ...d, provider, model: '', effort: '' }))}
+ onModelChange={model => setFormData(d => ({ ...d, model }))}
+ effort={formData.effort}
+ onEffortChange={effort => setFormData(d => ({ ...d, effort }))}
+ emptyProviderOption="Auto (default)"
+ emptyModelOption="Default model"
+ alwaysShowModel
+ highlightToolUse
+ />
+
+ <FormField label="Additional Instructions (optional)">
+ <textarea
+ value={formData.note}
+ onChange={e => setFormData(d => ({ ...d, note: e.target.value }))}
+ placeholder="Anything the relaunched run should know..."
+ rows={3}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden resize-none"
+ />
+ </FormField>
+
+ <div className="flex justify-end gap-2 pt-2">
+ <button
+ type="button"
+ onClick={onClose}
+ className="px-4 py-2 text-sm text-gray-400 hover:text-white transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={submitting}
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {submitting ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
+ {submitting ? 'Relaunching...' : 'Relaunch Agent'}
+ </button>
+ </div>
+ </form>
+ </Modal>
+ );
+}
diff --git a/client/src/components/cos/tabs/RelaunchAgentModal.test.jsx b/client/src/components/cos/tabs/RelaunchAgentModal.test.jsx
new file mode 100644
index 0000000000..67c6466100
--- /dev/null
+++ b/client/src/components/cos/tabs/RelaunchAgentModal.test.jsx
@@ -0,0 +1,106 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../../services/api', () => ({
+ relaunchCosAgent: vi.fn(),
+}));
+vi.mock('../../ui/Toast', () => ({
+ default: { success: vi.fn(), error: vi.fn() },
+}));
+
+import * as api from '../../../services/api';
+import toast from '../../ui/Toast';
+import RelaunchAgentModal from './RelaunchAgentModal';
+
+const PROVIDERS = [
+ { id: 'claude', name: 'Claude', enabled: true, models: ['claude-opus-5', 'claude-sonnet-5'] },
+ { id: 'codex', name: 'Codex', enabled: true, models: ['gpt-5'] },
+];
+
+// A run stalled on a usage limit: still `running`, pinned to the provider that
+// stopped answering.
+const STALLED_AGENT = {
+ id: 'agent-live',
+ taskId: 'task-abc',
+ status: 'running',
+ metadata: { taskDescription: 'Ship the thing', provider: 'claude', model: 'claude-opus-5' },
+};
+
+const renderModal = (props = {}) => render(
+ <RelaunchAgentModal
+ agent={STALLED_AGENT}
+ providers={PROVIDERS}
+ apps={[]}
+ onDone={vi.fn()}
+ onClose={vi.fn()}
+ {...props}
+ />
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.relaunchCosAgent.mockResolvedValue({ success: true, taskId: 'task-abc', mode: 'requeued' });
+});
+
+describe('RelaunchAgentModal', () => {
+ it('submits the stalled run\'s own settings when the user changes nothing', async () => {
+ const user = userEvent.setup();
+ renderModal();
+
+ await user.click(screen.getByRole('button', { name: 'Relaunch Agent' }));
+
+ await waitFor(() => expect(api.relaunchCosAgent).toHaveBeenCalledWith(
+ 'agent-live',
+ expect.objectContaining({ provider: 'claude', model: 'claude-opus-5' }),
+ { silent: true },
+ ));
+ });
+
+ it('sends the newly picked provider and drops the model pinned to the old one', async () => {
+ const user = userEvent.setup();
+ const onDone = vi.fn();
+ const onClose = vi.fn();
+ renderModal({ onDone, onClose });
+
+ await user.selectOptions(screen.getByRole('combobox', { name: /provider/i }), 'codex');
+ await user.click(screen.getByRole('button', { name: 'Relaunch Agent' }));
+
+ await waitFor(() => expect(api.relaunchCosAgent).toHaveBeenCalled());
+ const [, overrides] = api.relaunchCosAgent.mock.calls[0];
+ expect(overrides.provider).toBe('codex');
+ // A model from the provider the user just left would be unrunnable; blank is
+ // "server default", which is what clearing it means.
+ expect(overrides.model).toBeUndefined();
+ expect(onDone).toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ // `already-active` and `superseded` deliberately queue NOTHING server-side, so
+ // a relaunch must not claim it restarted the work.
+ it.each([
+ ['already-active', /already queued or running/i],
+ ['superseded', /later agent/i],
+ ])('reports the %s outcome without claiming the task was relaunched', async (mode, pattern) => {
+ const user = userEvent.setup();
+ api.relaunchCosAgent.mockResolvedValue({ success: true, taskId: 'task-abc', mode });
+ renderModal();
+
+ await user.click(screen.getByRole('button', { name: 'Relaunch Agent' }));
+
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(pattern)));
+ expect(toast.success).not.toHaveBeenCalledWith(expect.stringMatching(/queued again/i));
+ });
+
+ it('keeps the dialog open and surfaces the error when the relaunch fails', async () => {
+ const user = userEvent.setup();
+ const onClose = vi.fn();
+ api.relaunchCosAgent.mockRejectedValue(new Error('Agent agent-live is completed, not running'));
+ renderModal({ onClose });
+
+ await user.click(screen.getByRole('button', { name: 'Relaunch Agent' }));
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/not running/i)));
+ expect(onClose).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsx
index 025326c899..5d377e4daa 100644
--- a/client/src/components/cos/tabs/TaskItem.jsx
+++ b/client/src/components/cos/tabs/TaskItem.jsx
@@ -18,7 +18,8 @@ import {
Play,
Scale,
Unlock,
- Server
+ Server,
+ RefreshCw
} from 'lucide-react';
import toast from '../../ui/Toast';
import AutoSizeTextarea from '../../ui/AutoSizeTextarea';
@@ -32,6 +33,7 @@ import CollapsibleText from '../../ui/CollapsibleText';
import { extractCosTaskType } from '../../../lib/cosTaskType';
import InstancePicker from '../InstancePicker';
import EffortSelect from '../EffortSelect';
+import RelaunchAgentModal from './RelaunchAgentModal';
const statusIcons = {
pending: <Clock size={16} aria-hidden="true" className="text-yellow-500" />,
@@ -139,7 +141,7 @@ function getSuccessRateStyle(rate) {
return { bg: 'bg-port-error/15', text: 'text-port-error', label: 'low' };
}
-export default function TaskItem({ task, isSystem, spawning = false, selected = false, onRefresh, onTaskUnblocked, providers, durations, dragHandleProps, apps, instances = null, onEditingChange }) {
+export default function TaskItem({ task, agent = null, isSystem, spawning = false, selected = false, onRefresh, onTaskUnblocked, providers, durations, dragHandleProps, apps, instances = null, onEditingChange }) {
// System tasks are persisted in COS-TASKS.md. Every task
// mutation must name that source; otherwise the API's user-queue default
// searches TASKS.md and reports the system task as missing.
@@ -192,6 +194,7 @@ export default function TaskItem({ task, isSystem, spawning = false, selected =
const savedEditData = getTaskEditData(task, providers);
const [editData, setEditData] = useState(() => savedEditData);
const [showBlockedModal, setShowBlockedModal] = useState(false);
+ const [relaunching, setRelaunching] = useState(false);
const [blockedReason, setBlockedReason] = useState('');
const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();
// Independent armed-state from the delete confirm above — a second instance
@@ -748,6 +751,19 @@ export default function TaskItem({ task, isSystem, spawning = false, selected =
row's only recovery affordance away with it. forceSpawnTask
refuses a task a live agent already holds, so a click during a
real spawn gets an honest error rather than a duplicate run. */}
+ {/* Only when a live agent holds this task — relaunching pauses that
+ agent (see relaunchAgent in agentManagement.js). */}
+ {agent && (
+ <button
+ type="button"
+ onClick={() => setRelaunching(true)}
+ className="p-1 text-gray-500 hover:text-port-accent transition-colors"
+ title="Relaunch on a different provider or model"
+ aria-label={`Relaunch task ${task.id} on a different provider or model`}
+ >
+ <RefreshCw size={14} aria-hidden="true" />
+ </button>
+ )}
{task.status === 'pending' && !task.approvalRequired && (
<button
onClick={async () => {
@@ -811,6 +827,16 @@ export default function TaskItem({ task, isSystem, spawning = false, selected =
</div>
</div>
+ {relaunching && agent && (
+ <RelaunchAgentModal
+ agent={agent}
+ providers={providers}
+ apps={apps}
+ onDone={onRefresh}
+ onClose={() => setRelaunching(false)}
+ />
+ )}
+
{/* Blocked Reason Modal */}
<Modal
open={showBlockedModal}
diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsx
index a052f6ab7f..2e7f8e4171 100644
--- a/client/src/components/cos/tabs/TasksTab.jsx
+++ b/client/src/components/cos/tabs/TasksTab.jsx
@@ -79,12 +79,16 @@ export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, o
// store's task events so the flip lands in ~400ms instead of a 30s poll. This
// settles the render from whichever of the two signals arrived first, so the
// split is right even when an event is delayed or dropped.
- const spawningTaskIds = useMemo(() => new Set(
- agents.filter(a => a.status === 'running' && a.taskId).map(a => a.taskId)
+ // Keyed by task rather than reduced to a Set of ids: an Active row also uses the
+ // agent itself, to offer a relaunch onto a different provider/model without
+ // fetching the agent list of its own.
+ const runningAgentByTaskId = useMemo(() => new Map(
+ agents.filter(a => a.status === 'running' && a.taskId).map(a => [a.taskId, a])
), [agents]);
+
const isSpawning = useCallback(
- (task) => task.status === 'pending' && spawningTaskIds.has(task.id),
- [spawningTaskIds]
+ (task) => task.status === 'pending' && runningAgentByTaskId.has(task.id),
+ [runningAgentByTaskId]
);
// Split tasks by status for system tasks
@@ -279,7 +283,7 @@ export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, o
</div>
<div className="p-2 space-y-1.5">
{activeUserTasksLocal.map(task => (
- <TaskItem key={task.id} task={task} spawning={isSpawning(task)} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
+ <TaskItem key={task.id} task={task} agent={runningAgentByTaskId.get(task.id)} spawning={isSpawning(task)} selected={isTaskSelected(task, 'user')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
))}
</div>
</div>
@@ -369,7 +373,7 @@ export default function TasksTab({ tasks, agents = [], onRefresh, onTaskAdded, o
</div>
<div className="p-2 space-y-1.5">
{activeSystemTasks.map(task => (
- <TaskItem key={task.id} task={task} isSystem spawning={isSpawning(task)} selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
+ <TaskItem key={task.id} task={task} isSystem agent={runningAgentByTaskId.get(task.id)} spawning={isSpawning(task)} selected={isTaskSelected(task, 'internal')} onRefresh={onRefresh} onTaskUnblocked={onTaskUnblocked} providers={providers} durations={durations} apps={apps} instances={assignableInstances} />
))}
</div>
</div>
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 5897ee5596..fdd0f329a9 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -183,6 +183,14 @@ export const resumeCosAgent = (id, overrides = {}, options = {}) => request(`/co
body: JSON.stringify(overrides),
...options
});
+// Relaunch a RUNNING agent: the server pauses it (process stopped, worktree kept)
+// and requeues its own task with the overrides. Omit a field to keep the stalled
+// run's value. Returns the same mode enum as resumeCosAgent.
+export const relaunchCosAgent = (id, overrides = {}, options = {}) => request(`/cos/agents/${id}/relaunch`, {
+ method: 'POST',
+ body: JSON.stringify(overrides),
+ ...options
+});
export const killCosAgent = (id, options = {}) => request(`/cos/agents/${id}/kill`, { method: 'POST', ...options });
export const getCosAgentStats = (id, options) => request(`/cos/agents/${id}/stats`, options);
export const getCosAgentPrompt = (id) => request(`/cos/agents/${id}/prompt`);
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index a45eafe863..3175eb41a1 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -3614,6 +3614,14 @@
"server/routes/cosAgentRoutes.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/cos/agents/:id/relaunch",
+ "mountPath": "/api/cos",
+ "sources": [
+ "server/routes/cosAgentRoutes.js"
+ ]
+ },
{
"method": "POST",
"path": "/api/cos/agents/:id/resume",
@@ -17425,8 +17433,8 @@
],
"stats": {
"mounts": 147,
- "operations": 2158,
- "declarations": 2162,
+ "operations": 2159,
+ "declarations": 2163,
"sourceFiles": 229
}
}
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index d8e4c52852..dbe7ddaafa 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -1880,6 +1880,16 @@ export const resumeCosAgentSchema = createCosTaskSchema
.pick({ description: true, context: true, model: true, provider: true, effort: true, app: true, screenshots: true })
.partial();
+// A relaunch is a resume aimed at a RUNNING agent: the point is swapping the
+// provider/model/effort out from under a stalled run (a CLI parked on a usage
+// limit), so it takes no `description` — the task it requeues is the one the
+// agent is already working. `reason` is the pause note recorded against it.
+// Derived from the resume schema, not re-picked from the task schema, so a field
+// added to one resume door reaches the other instead of silently diverging.
+export const relaunchCosAgentSchema = resumeCosAgentSchema
+ .omit({ description: true, screenshots: true })
+ .extend({ reason: z.string().trim().max(500).optional() });
+
/**
* Sanitize taskMetadata to an allow-list of agent-option keys. Boolean flags
* (`useWorktree`/`openPR`/`simplify`/`reviewLoop`/`readOnly`/`claimFlow`/
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index ce161b1e50..a2d33d4184 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -8,7 +8,7 @@ import * as cos from '../services/cos.js';
// Lifecycle transitions go through the facade (#3450), not the `cos.js` barrel.
import * as agentOrchestrator from '../services/agentOrchestrator.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { validateRequest, resumeCosAgentSchema } from '../lib/validation.js';
+import { validateRequest, resumeCosAgentSchema, relaunchCosAgentSchema } from '../lib/validation.js';
const router = Router();
@@ -111,6 +111,16 @@ router.post('/agents/:id/resume', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/cos/agents/:id/relaunch - Stop a RUNNING agent and requeue its own
+// task on a different provider/model/effort (see relaunchAgent for why).
+// relaunchAgent throws a ServerError — 404 when the agent is missing, 409 when
+// it isn't running, 500 when the pause or requeue write fails.
+router.post('/agents/:id/relaunch', asyncHandler(async (req, res) => {
+ const overrides = validateRequest(relaunchCosAgentSchema, req.body ?? {});
+ const result = await agentOrchestrator.relaunchAgent(req.params.id, overrides);
+ res.json(result);
+}));
+
// POST /api/cos/agents/:id/kill - Force kill agent (immediate SIGKILL)
// killAgent throws a ServerError — 404 when the agent is missing, 500 when the
// runner termination fails — so no result-shape string-matching here.
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 5fe0670639..827fa2140d 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -21,7 +21,7 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { completeAgentRun } from './agentRunTracking.js';
import { appendRunEvent } from './agentRunEventLog.js';
import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';
-import { activeAgents, userTerminatedAgents, pausedAgents, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
+import { activeAgents, userTerminatedAgents, pausedAgents, consumePausedAgentExit, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
import { normalizeReviewers } from '../lib/validation.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
@@ -768,7 +768,7 @@ export async function spawnDirectly({
// it on the same executionId logs a spurious "Invalid state transition".
// Mirrors the TUI path's pause-check-before-releaseAgentLane ordering.
if (pausedAgents.has(agentId)) {
- pausedAgents.delete(agentId);
+ consumePausedAgentExit(agentId);
if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);
activeAgents.delete(agentId);
return;
@@ -919,7 +919,7 @@ export async function spawnDirectly({
// (mirrors the normal pause path) — finalizing it as failed here would
// overwrite the paused state and break later resume.
if (pausedAgents.has(agentId)) {
- pausedAgents.delete(agentId);
+ consumePausedAgentExit(agentId);
unregisterSpawnedAgent(claudeProcess.pid);
activeAgents.delete(agentId);
} else {
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 44ffed8729..d26ac2a6cf 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -70,7 +70,7 @@ import { releaseAppReviewMarker } from './appActivity.js';
import { ensureInstanceId } from './instances.js';
import { isClaimableBy, buildClaim, buildRelease, getClaimOwner, getTargetInstance, isTargetedElsewhere } from './cosTaskClaim.js';
import { resolveForgeTokenEnv } from './git.js';
-import { runnerAgents, pausedAgents, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';
+import { runnerAgents, pausedAgents, consumePausedAgentExit, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';
import { withSpawnDedupGuard, withMapEntryCleanup, withUpdateInProgressGuard, SPAWN_DEDUP_SKIP, SPAWN_UPDATE_SKIP } from './agentGuards.js';
import { isUpdateInProgress } from './updateChecker.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
@@ -1285,7 +1285,7 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
// completion event can't clean the worktree / complete the task out from
// under a later resume. Mirrors the CLI/TUI close-handler pause guards.
if (pausedAgents.has(agentId)) {
- pausedAgents.delete(agentId);
+ consumePausedAgentExit(agentId);
runnerAgents.delete(agentId);
return;
}
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 7ccf30a388..87cd3c0a80 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -21,7 +21,7 @@ import { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAg
import { runnerEntryShieldsRunningRecord } from '../lib/runnerAgentLiveness.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
import { isInternalTaskId } from '../lib/taskParser.js';
-import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunner, unregisterSpawnedAgent } from './agentState.js';
+import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, whenPausedAgentExits, useRunner, unregisterSpawnedAgent } from './agentState.js';
// Both were extracted out of agentLifecycle.js (issue #2837) so this module no
// longer depends on the lifecycle orchestrator — which depends on THIS module
// for handleOrphanedTask. Importing them from their own leaf modules is what
@@ -436,6 +436,68 @@ export async function resumeAgent(agentId, overrides = {}) {
return { success: true, agentId, created: mode === 'new-task', ...resumed };
}
+/**
+ * How long a relaunch waits for a LOCAL paused run's process to actually exit.
+ * The pause path escalates SIGTERM → SIGKILL after 5s, so the close handler has
+ * landed well inside this window in every observed case; the cap only exists so
+ * a wedged child can't hold the request open forever.
+ */
+const RELAUNCH_EXIT_TIMEOUT_MS = 15000;
+
+/**
+ * Relaunch a RUNNING agent's task on a different provider/model/effort.
+ *
+ * The motivating case is a run that is alive but going nowhere — a CLI sitting on
+ * a provider usage limit. Pausing and resuming already does exactly the right
+ * thing (stop the process, keep the worktree, requeue the same task with new
+ * provider/model/effort overrides), but as two clicks it is neither discoverable
+ * nor safe to do quickly. This composes the two so one click switches providers.
+ *
+ * Composition, not a third code path: `pauseAgent` owns stopping the process and
+ * preserving the worktree, `resumeAgent` owns the requeue and the four resume
+ * modes. The only thing between them is waiting for the stopped process to be
+ * gone — a human clicking Pause then Resume takes seconds, but collapsing the two
+ * into one request does not, and resuming first is what loses the worktree
+ * (`whenPausedAgentExits` in agentState.js has the mechanism).
+ *
+ * @param {string} agentId
+ * @param {{context?: string, provider?: string, model?: string, effort?: string, app?: string, reason?: string}} overrides
+ */
+export async function relaunchAgent(agentId, overrides = {}) {
+ const agent = await getAgentRecord(agentId);
+ if (!agent) {
+ throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ if (agent.status !== 'running') {
+ throw new ServerError(`Agent ${agentId} is ${agent.status}, not running`, {
+ status: 409, code: 'AGENT_NOT_RUNNING'
+ });
+ }
+
+ const { reason, ...resumeOverrides } = overrides;
+ const pauseReason = reason || relaunchReason(resumeOverrides);
+ const paused = await pauseAgent(agentId, pauseReason);
+
+ if (!await whenPausedAgentExits(agentId, RELAUNCH_EXIT_TIMEOUT_MS)) {
+ // Proceed anyway: the task is already parked as paused, so refusing here
+ // would leave the user with a stopped agent and no relaunch. Say so in the
+ // log, since this is the window where a late exit can clean the worktree.
+ emitLog('warn', `⚠️ Relaunch of ${agentId} proceeded before its process exited — its worktree may not survive`, { agentId });
+ }
+
+ const resumed = await resumeAgent(agentId, resumeOverrides);
+ emitLog('info', `🔁 Relaunched agent ${agentId} — ${pauseReason}`, {
+ agentId, taskId: resumed.taskId, mode: resumed.mode
+ });
+ return { ...resumed, relaunched: true, pausedAt: paused.pausedAt };
+}
+
+/** The pause reason a relaunch records, naming what the user actually changed. */
+function relaunchReason({ provider, model, effort }) {
+ const target = [provider, model, effort].filter(Boolean).join(' / ');
+ return `Relaunched by user${target ? ` on ${target}` : ''}`;
+}
+
/** One line naming what the resume actually did — used for the log and the record. */
function resumeSummary(agentId, { taskId, mode, branchName }) {
switch (mode) {
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index 354f1a8793..11d773fa21 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -116,7 +116,7 @@ vi.mock('./creativeDirector/local.js', () => ({
vi.mock('./creativeDirector/planAdvance.js', () => ({ advanceAfterPlanStepSettled: vi.fn().mockResolvedValue(undefined) }));
vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettled: vi.fn().mockResolvedValue(undefined) }));
-import { handleOrphanedTask, pauseAgent, resumeAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents, terminateAgent, killAgent } from './agentManagement.js';
+import { handleOrphanedTask, pauseAgent, resumeAgent, relaunchAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents, terminateAgent, killAgent } from './agentManagement.js';
import { cleanupAgentWorktree, resolveTaskResumePatch } from './agentWorktreeCleanup.js';
import { getAgents, updateAgent, getAgentRecord, readAgentRecordOrUnreadable, AGENT_RECORD_UNREADABLE, completeAgent as markAgentComplete } from './cosAgentLifecycle.js';
import { updateRun, getProject } from './creativeDirector/local.js';
@@ -128,7 +128,7 @@ import * as shellService from './shell.js';
import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';
import { completeAgentRun } from './agentRunTracking.js';
import { committedDuringRun } from '../lib/gitCommitProbe.js';
-import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';
+import { activeAgents, runnerAgents, pausedAgents, consumePausedAgentExit } from './agentState.js';
/**
* A direct-mode agent's spawned handle. Its prototype is ChildProcess so it
@@ -1131,6 +1131,99 @@ describe('resumeAgent — requeues the paused agent\'s own task', () => {
});
});
+// ─── relaunchAgent ────────────────────────────────────────────────────────────
+//
+// The stall this exists for: a RUNNING agent whose CLI is parked on a provider
+// usage limit. Kill loses the worktree, Pause leaves the task parked — the
+// recovery is "same task, different provider", which is a pause and a resume
+// glued together. These lock the two things the gluing can get wrong: dropping
+// the overrides, and resuming before the stopped process is actually gone.
+
+describe('relaunchAgent — moves a running agent\'s task onto another provider', () => {
+ const LIVE_AGENT = {
+ id: 'agent-live-1',
+ taskId: 'task-abc',
+ metadata: { taskType: 'user', provider: 'claude', model: 'claude-opus-5' },
+ };
+ const PAUSED_TASK = {
+ id: 'task-abc',
+ taskType: 'user',
+ description: 'Do the thing',
+ status: 'blocked',
+ metadata: {
+ blockedCategory: 'agent-paused',
+ pausedAgentId: 'agent-live-1',
+ pausedAt: '2026-08-10T00:00:00.000Z',
+ context: 'original context',
+ },
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ activeAgents.clear();
+ runnerAgents.clear();
+ pausedAgents.clear();
+ // The record flips through the same write production makes: markAgentPaused's
+ // `updateAgent`. Hard-coding `paused` from the first read would let a relaunch
+ // that never actually paused still pass.
+ let paused = false;
+ updateAgent.mockImplementation(async (_id, patch) => { if (patch?.status === 'paused') paused = true; });
+ getAgentRecord.mockImplementation(async () => ({ ...LIVE_AGENT, status: paused ? 'paused' : 'running' }));
+ getTaskById.mockResolvedValue(PAUSED_TASK);
+ reviveBlockedTask.mockResolvedValue({ metadata: {} });
+ });
+
+ it('requeues the SAME task with the new provider/model/effort — no second task', async () => {
+ runnerAgents.set('agent-live-1', { taskId: 'task-abc', runId: 'run-1' });
+ pauseAgentViaRunner.mockResolvedValue({ success: true });
+
+ const result = await relaunchAgent('agent-live-1', {
+ provider: 'codex', model: 'gpt-5', effort: 'high',
+ });
+
+ expect(result).toMatchObject({ success: true, taskId: 'task-abc', mode: 'requeued', relaunched: true });
+ expect(addTask).not.toHaveBeenCalled();
+ expect(reviveBlockedTask.mock.calls[0][1].metadata).toMatchObject({
+ provider: 'codex', model: 'gpt-5', effort: 'high',
+ });
+ });
+
+ it('waits for the stopped process to leave activeAgents before requeueing', async () => {
+ // The close handler consumes the `pausedAgents` flag and drops the
+ // `activeAgents` entry together. resumeAgent deletes that flag, so requeueing
+ // before the exit lands leaves the close handler treating the exit as a
+ // completion — which cleans up the worktree the relaunched task points at.
+ activeAgents.set('agent-live-1', { process: fakeChildProcess(), taskId: 'task-abc' });
+ let stillLiveAtRequeue = null;
+ reviveBlockedTask.mockImplementation(async () => {
+ stillLiveAtRequeue = activeAgents.has('agent-live-1');
+ return { metadata: {} };
+ });
+ setTimeout(() => {
+ // Through the real close-handler door, not a hand-rolled map delete: that
+ // consumer is what releases the waiter, so a test that deleted the entries
+ // itself would pass against a relaunch that never waited at all.
+ consumePausedAgentExit('agent-live-1');
+ activeAgents.delete('agent-live-1');
+ }, 150);
+
+ await relaunchAgent('agent-live-1', { provider: 'codex' });
+
+ expect(stillLiveAtRequeue).toBe(false);
+ });
+
+ it('refuses an agent that is not running, and one that does not exist', async () => {
+ getAgentRecord.mockResolvedValue({ ...LIVE_AGENT, status: 'completed' });
+ await expect(relaunchAgent('agent-live-1')).rejects.toMatchObject({
+ status: 409, code: 'AGENT_NOT_RUNNING',
+ });
+ expect(reviveBlockedTask).not.toHaveBeenCalled();
+
+ getAgentRecord.mockResolvedValue(null);
+ await expect(relaunchAgent('nope')).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });
+ });
+});
+
// ─── Pause-release adapter (#3730) ────────────────────────────────────────────
//
// The agent-addressed half `cosTaskStore.updateTask` calls through, registered at
diff --git a/server/services/agentOrchestrator.js b/server/services/agentOrchestrator.js
index 6e3ace3084..01d8e7946f 100644
--- a/server/services/agentOrchestrator.js
+++ b/server/services/agentOrchestrator.js
@@ -133,6 +133,7 @@
export {
pauseAgent, // running → paused (process stopped, worktree preserved)
resumeAgent, // paused → completed, task requeued on the preserved branch
+ relaunchAgent, // running → paused → completed, task requeued on a new provider/model
killAgent, // running → completed (immediate SIGKILL)
terminateAgent, // running → completed (SIGTERM, SIGKILL fallback)
getAgentProcessStats, // read, not a transition — but it needs the process layer
diff --git a/server/services/agentOrchestrator.test.js b/server/services/agentOrchestrator.test.js
index f9f23ad935..88f04e6d56 100644
--- a/server/services/agentOrchestrator.test.js
+++ b/server/services/agentOrchestrator.test.js
@@ -15,6 +15,7 @@ import { describe, it, expect, vi } from 'vitest';
vi.mock('./agentManagement.js', () => ({
pauseAgent: () => {},
resumeAgent: () => {},
+ relaunchAgent: () => {},
killAgent: () => {},
terminateAgent: () => {},
getAgentProcessStats: () => {}
@@ -38,6 +39,7 @@ import * as agentLifecycle from './agentLifecycle.js';
const WIRING = [
['pauseAgent', agentManagement, 'pauseAgent'],
['resumeAgent', agentManagement, 'resumeAgent'],
+ ['relaunchAgent', agentManagement, 'relaunchAgent'],
['killAgent', agentManagement, 'killAgent'],
['terminateAgent', agentManagement, 'terminateAgent'],
['getAgentProcessStats', agentManagement, 'getAgentProcessStats'],
diff --git a/server/services/agentState.js b/server/services/agentState.js
index a7c3f3dfbb..75173c68d8 100644
--- a/server/services/agentState.js
+++ b/server/services/agentState.js
@@ -20,6 +20,60 @@ export const userTerminatedAgents = new Set();
// task or cleaning up the worktree (Map<agentId, { pausedAt, reason }>)
export const pausedAgents = new Map();
+// Waiters for a paused agent's process to ACTUALLY exit, keyed by agentId
+// (Map<agentId, Array<(exited: boolean) => void>>). See whenPausedAgentExits.
+const pausedExitWaiters = new Map();
+
+/**
+ * Consume the pause flag on the way out of a close handler.
+ *
+ * The spawner close handlers (agentCliSpawning / agentTuiSpawning) and the
+ * runner completion handler (agentLifecycle) all skip finalization for a paused
+ * agent and drop the flag as they go. Deleting through here also releases anyone
+ * waiting on the exit, so `whenPausedAgentExits` is an event rather than a poll —
+ * and the two can't drift, because the delete IS the notification.
+ */
+export const consumePausedAgentExit = (agentId) => {
+ pausedAgents.delete(agentId);
+ const waiters = pausedExitWaiters.get(agentId);
+ if (!waiters) return;
+ pausedExitWaiters.delete(agentId);
+ for (const settle of waiters) settle(true);
+};
+
+/**
+ * Resolve once a paused agent's process is gone — `true` if the exit was
+ * observed, `false` if the window closed first.
+ *
+ * Pausing STOPS a local process without waiting for it: `pauseAgent` returns
+ * after the signal, and the close handler lands milliseconds later. A caller
+ * that acts on the paused agent immediately (relaunch, which requeues the task
+ * and retires the record) has to let that handler run first — once the record is
+ * retired the handler no longer recognizes the exit as a pause and finalizes the
+ * run, cleaning up the worktree the requeued task points at.
+ *
+ * An agent that is not in `activeAgents` has nothing left to wait for: either
+ * the handler already ran, or the run is runner-backed and its stop was
+ * confirmed by an awaited RPC.
+ */
+export const whenPausedAgentExits = (agentId, timeoutMs) => {
+ if (!activeAgents.has(agentId)) return Promise.resolve(true);
+ return new Promise(resolve => {
+ const settle = (exited) => {
+ clearTimeout(timer);
+ const waiters = pausedExitWaiters.get(agentId);
+ if (waiters) {
+ const rest = waiters.filter(w => w !== settle);
+ if (rest.length) pausedExitWaiters.set(agentId, rest);
+ else pausedExitWaiters.delete(agentId);
+ }
+ resolve(exited);
+ };
+ const timer = setTimeout(() => settle(false), timeoutMs);
+ pausedExitWaiters.set(agentId, [...(pausedExitWaiters.get(agentId) || []), settle]);
+ });
+};
+
// 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 b37d655d42..2ea67daa8c 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -15,7 +15,7 @@ import { updateAgent } from './cosAgentLifecycle.js';
import { createOutputSpooler } from './agentTuiSpawning/outputSpooler.js';
import { resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';
import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';
-import { activeAgents, userTerminatedAgents, pausedAgents, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
+import { activeAgents, userTerminatedAgents, pausedAgents, consumePausedAgentExit, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
import { PATHS, watchForFile } from '../lib/fileUtils.js';
import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';
@@ -806,7 +806,7 @@ export async function spawnTuiAgent({
await drainRaw();
if (pausedAgents.has(agentId)) {
- pausedAgents.delete(agentId);
+ consumePausedAgentExit(agentId);
const pausedAgentData = activeAgents.get(agentId);
if (pausedAgentData?.pid) unregisterSpawnedAgent(pausedAgentData.pid);
activeAgents.delete(agentId);