Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
start a resumed CoS task immediately instead of leaving it pending for a manual Run
[._.]/ Adam Eivyf5d9a575c0db
diff --git a/client/src/components/cos/tabs/AgentsTab.jsx b/client/src/components/cos/tabs/AgentsTab.jsxindex d03645e10f..25eb2782ea 100644--- a/client/src/components/cos/tabs/AgentsTab.jsx+++ b/client/src/components/cos/tabs/AgentsTab.jsx@@ -8,16 +8,22 @@ import ResumeAgentModal from './ResumeAgentModal';import RelaunchAgentModal from './RelaunchAgentModal';import BrailleSpinner from '../../BrailleSpinner';import InlineConfirmRow from '../../ui/InlineConfirmRow';+import { agentResumeMessage } from '../../../lib/agentResumeOutcome';// What each `resumeAgent` outcome actually did (server modes, agentManagement.js).// `already-active` and `superseded` deliberately queue NOTHING — the task is already-// in flight, or a later pause owns it — so an unmapped mode must NOT fall through to-// "created a resume task". The server's `created` flag decides that (see below); this-// map only supplies the specific wording.+// in flight, or a later pause owns it — so they carry no `running` wording, and an+// unmapped mode must NOT fall through to "created a resume task". The server's+// `created` flag decides that (see below); this map only supplies the specific+// wording. `requeued` has both variants because the server force-spawns the resumed+// task when a slot is free — see `agentResumeMessage` for that contract.const RESUME_MESSAGES = {- requeued: 'Resumed — the paused task is queued 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',+ requeued: {+ queued: 'Resumed — the paused task is queued on its preserved worktree',+ running: 'Resumed — the paused task is running again on its preserved worktree',+ },+ 'already-active': { queued: 'Its task is already queued or running — nothing new was created' },+ superseded: { queued: 'A later agent now holds this task paused — that pause was left intact' },};// Only agents from a manually-filled task form ask for a rating — scheduled/@@ -165,8 +171,8 @@ export default function AgentsTab({ agents, onRefresh, liveOutputs, providers, a// A resume that created nothing (`created: false`) never claims it did, even for// a mode this build has no wording for — the completed-agent branch above has no// `created` field at all and did queue a task, so it keeps the default.- toast.success(RESUME_MESSAGES[result.mode]- || (result.created === false ? 'Resumed — nothing new was queued' : `Created ${type === 'internal' ? 'system ' : ''}resume task`));+ toast.success(agentResumeMessage(result, RESUME_MESSAGES,+ result.created === false ? 'Resumed — nothing new was queued' : `Created ${type === 'internal' ? 'system ' : ''}resume task`));setResumingAgent(null);onRefresh();};diff --git a/client/src/components/cos/tabs/AgentsTab.test.jsx b/client/src/components/cos/tabs/AgentsTab.test.jsxindex ce4c6c6f2b..01a781332c 100644--- a/client/src/components/cos/tabs/AgentsTab.test.jsx+++ b/client/src/components/cos/tabs/AgentsTab.test.jsx@@ -191,6 +191,36 @@ describe('AgentsTab resume routing', () => {expect(toast.success).not.toHaveBeenCalledWith(expect.stringMatching(/resume task/i));});+ // The server force-spawns the resumed task when a slot is free, so "queued" is the+ // exception, not the rule — and a "queued" toast for a run that already started+ // reads as the Resume click not having taken.+ it('says the resumed task is running when the server started it', async () => {+ const user = userEvent.setup();+ api.resumeCosAgent.mockResolvedValue({ success: true, taskId: 'task-abc', mode: 'requeued', spawned: true });+ renderTab([pausedAgent]);+ await act(async () => {});++ await user.click(screen.getByRole('button', { name: 'Resume agent-paused' }));+ await user.click(screen.getByRole('button', { name: 'Submit resume' }));++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/running again/i)));+ });++ it('names why a resumed task stayed queued instead of leaving the user to hunt for it', async () => {+ const user = userEvent.setup();+ api.resumeCosAgent.mockResolvedValue({+ success: true, taskId: 'task-abc', mode: 'requeued',+ spawned: false, spawnHold: 'No available agent slots (3/3)',+ });+ renderTab([pausedAgent]);+ await act(async () => {});++ await user.click(screen.getByRole('button', { name: 'Resume agent-paused' }));+ await user.click(screen.getByRole('button', { name: 'Submit resume' }));++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/No available agent slots \(3\/3\)/)));+ });+// The default has to be safe by construction, not by keeping a copy of the server's// mode enum in sync — a future non-creating mode this build has no wording for must// not regress to announcing a task that was never queued.diff --git a/client/src/components/cos/tabs/RelaunchAgentModal.jsx b/client/src/components/cos/tabs/RelaunchAgentModal.jsxindex 44820877bd..1c9a1b4db1 100644--- a/client/src/components/cos/tabs/RelaunchAgentModal.jsx+++ b/client/src/components/cos/tabs/RelaunchAgentModal.jsx@@ -9,15 +9,25 @@ import { FormField } from '../../ui/FormField';import CollapsibleText from '../../ui/CollapsibleText';import { useAsyncAction } from '../../../hooks/useAsyncAction';import { effortAwareModelOptions, seedModelEffort } from '../../../utils/providers';+import { agentResumeMessage } from '../../../lib/agentResumeOutcome';// 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.+// modes (agentManagement.js): only `requeued` and `new-task` put work back on the+// queue — `already-active` and `superseded` deliberately queue NOTHING, so those+// carry no `running` wording and an unmapped mode falls through to the plain+// fallback rather than a message claiming the task was relaunched. See+// `agentResumeMessage` for the queued-vs-running contract.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',+ requeued: {+ queued: 'Relaunched — the task is queued again on its preserved worktree',+ running: 'Relaunched — the task is running again on its preserved worktree',+ },+ 'new-task': {+ queued: 'Relaunched — a replacement task is queued',+ running: 'Relaunched — a replacement task is running',+ },+ 'already-active': { queued: 'Its task is already queued or running — nothing new was created' },+ superseded: { queued: 'A later agent now holds this task paused — that pause was left intact' },};/**@@ -72,7 +82,7 @@ export default function RelaunchAgentModal({ agent, providers, apps, onDone, onCapp: formData.app || undefined,context: formData.note.trim() || undefined}, { silent: true });- toast.success(RELAUNCH_MESSAGES[result?.mode] || 'Relaunched');+ toast.success(agentResumeMessage(result, RELAUNCH_MESSAGES, 'Relaunched'));onDone?.(result);onClose();return result;@@ -120,8 +130,9 @@ export default function RelaunchAgentModal({ agent, providers, apps, onDone, onCexpandedClassName="max-h-48 overflow-y-auto whitespace-pre-wrap"/><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.+ This stops the running agent and restarts the same task on the worktree it leaves+ behind — no second agent, and nothing to clean up afterward. It starts right away+ when an agent slot is free, and stays queued until one is otherwise.</div></div>diff --git a/client/src/components/cos/tabs/RelaunchAgentModal.test.jsx b/client/src/components/cos/tabs/RelaunchAgentModal.test.jsxindex 1c3c314acf..ceb1a582bf 100644--- a/client/src/components/cos/tabs/RelaunchAgentModal.test.jsx+++ b/client/src/components/cos/tabs/RelaunchAgentModal.test.jsx@@ -123,6 +123,30 @@ describe('RelaunchAgentModal', () => {expect(screen.getByRole('button', { name: /show less/i })).toBeInTheDocument();});+ it('says the task is running when the server started it, not that it is queued', async () => {+ const user = userEvent.setup();+ api.relaunchCosAgent.mockResolvedValue({ success: true, taskId: 'task-abc', mode: 'requeued', spawned: true });+ renderModal();++ await user.click(screen.getByRole('button', { name: 'Relaunch Agent' }));++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/running again/i)));+ expect(toast.success).not.toHaveBeenCalledWith(expect.stringMatching(/queued/i));+ });++ it('names why a relaunched task stayed queued instead of leaving the user to hunt for it', async () => {+ const user = userEvent.setup();+ api.relaunchCosAgent.mockResolvedValue({+ success: true, taskId: 'task-abc', mode: 'requeued',+ spawned: false, spawnHold: 'No available agent slots (3/3)',+ });+ renderModal();++ await user.click(screen.getByRole('button', { name: 'Relaunch Agent' }));++ await waitFor(() => expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/No available agent slots \(3\/3\)/)));+ });+it('keeps the dialog open and surfaces the error when the relaunch fails', async () => {const user = userEvent.setup();const onClose = vi.fn();diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex bbea8b4bce..d7e1cd4fe3 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -99,6 +99,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|| `a11yKeyboard.js` | `clickableProps(handler, { role?, disabled? })` → `{ role, tabIndex, onKeyDown }` and `onActivateKeyDown(handler)` — make a non-`<button>` element with an `onClick` keyboard-accessible (Enter/Space activation, focusable, `role="button"`). Spread `clickableProps` next to the existing `onClick`. Use instead of hand-rolling `role`/`tabIndex`/`onKeyDown` on clickable `<div>`/`<span>`/`<li>`. Also the shared predicate every app-global key handler consults: `shouldIgnoreGlobalKey(event, { enabledInDialog?, ignoreRepeat?, allowChords? })` — the single "must this handler stand down?" answer (editable target, native Space button activation, ⌘/Ctrl/Alt chord, OS auto-repeat, open `aria-modal` dialog), used by `useKeyboardShortcuts`, `useKeyCapture` AND the voice widget's push-to-talk hotkey so their guard lists can't drift. Add a new guard there, not at one caller. Its parts are exported too: `isEditableTarget(el)`, `isButtonActivation(event)` (true when Space would natively activate the focused button) and `isPressKey(event)` (Enter or Space by either `key` or `code`). Plus `noPointerFocusSurfaceProps` — spread on the ROOT of a surface that owns a key globally (a Space-scored drill, the Morse keyer, RapidReader, the OpenWorld HUD); one capture-phase handler stops a mouse click anywhere inside from parking focus on a button and taking that key over via native activation, covering controls added later too. |+| `agentResumeOutcome.js` | `agentResumeMessage(result, messages, fallback)` — the toast wording for a CoS agent resume/relaunch result. The server answers with a `mode` (what it did to the task) plus `spawned`/`spawnHold` (whether it also STARTED it — a resumed task is force-spawned when a slot is free, and `spawnHold` names the refusal when it isn't). `messages` is keyed by mode as `{ queued, running? }`; a mode with no `running` variant is one that deliberately queues nothing, so it can never be reported as started. Shared by the Resume dialog (`cos/tabs/AgentsTab.jsx`) and `cos/tabs/RelaunchAgentModal.jsx` so neither can say "queued" for a run that already started, or omit the reason it didn't. || `appIdentity.js` | `PORTOS_APP_ID` — stable id of the baseline PortOS app (mirrors `server/lib/appIdentity.js`). Dependency-free so a module reachable from a node-env server test (e.g. `components/apps/constants.js`) can identify PortOS without importing `services/apiCore.js`, which pulls in React via `ui/Toast`. `apiCore.js` re-exports it, so `import { PORTOS_APP_ID } from '../services/api'` still works. || `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. || `assessmentTuningNotice.js` | `tuningNoticeChip(entry)` — the short form of how a measured local-model assessment says its launch configuration did NOT take effect. `tuningApplied === false` covers two opposite cases and `tuningKey` separates them: a TUNED run whose knobs never reached the daemon (`tuning not applied`), versus an UNTUNED run PortOS could not put back on backend defaults (`not at defaults`) — #4759. Shared by `ModelThroughputReport.jsx`'s table cell and `LocalModelAssessments.jsx`'s result toast; the long form is the server's exclusion reason in `getAssessmentReport`. |diff --git a/client/src/lib/agentResumeOutcome.js b/client/src/lib/agentResumeOutcome.jsnew file mode 100644index 0000000000..4184748fa7--- /dev/null+++ b/client/src/lib/agentResumeOutcome.js@@ -0,0 +1,25 @@+/**+ * Toast wording for a resume/relaunch result, shared by the two dialogs that+ * dispatch one — Resume (`cos/tabs/AgentsTab.jsx`) and Relaunch+ * (`cos/tabs/RelaunchAgentModal.jsx`).+ *+ * The server (`resumeAgent` in `server/services/agentManagement.js`) answers with a+ * `mode` naming what it did to the task, plus `spawned` / `spawnHold` saying+ * whether it also STARTED it: a resumed task is force-spawned when an agent slot is+ * free, so `requeued` usually means running, not waiting. Two ways to get that+ * wrong, and both surfaces can get them wrong identically — hence one helper:+ * saying "queued" for a run that already started reads as the click not having+ * taken, and saying "queued" with no reason sends the user hunting the task list+ * for why it didn't start.+ *+ * `messages` is keyed by mode, each entry `{ queued, running? }`. A mode with no+ * `running` variant is one that deliberately queues NOTHING (`already-active`,+ * `superseded`), so it can never be reported as started. `fallback` covers a mode+ * this build has no wording for — an unmapped mode must never fall through to a+ * message claiming work was queued.+ */+export function agentResumeMessage(result, messages, fallback) {+ const entry = messages[result?.mode];+ const base = (result?.spawned && entry?.running) || entry?.queued || fallback;+ return result?.spawnHold ? `${base} — ${result.spawnHold}` : base;+}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex d08cdcc4c1..a730dd9e5b 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -75,6 +75,7 @@ export * from './goalFeatureMap.js';// === Generic UI / collection utilities ===export * from './a11yKeyboard.js';+export * from './agentResumeOutcome.js';export * from './appIdentity.js';export * from './applyManuscriptEdits.js';export * from './assessmentTuningNotice.js';diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex f723987b47..9fbacde85c 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -15,7 +15,7 @@ import { emitLog } from './cosEvents.js';// that declares it; a barrel would be a third answer to "where does completeAgent// live", which is the thing this sequencing keeps removing.import { completeAgent, updateAgent, getAgents, getAgentRecord, AGENT_RECORD_UNREADABLE, isLiveAgentRecord, readAgentRecordOrUnreadable } from './cosAgentLifecycle.js';-import { updateTask, addTask, getTaskById, reviveBlockedTask, evaluateTasks } from './cos.js';+import { updateTask, addTask, getTaskById, reviveBlockedTask, evaluateTasks, forceSpawnTask } from './cos.js';import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, pauseMetadata, isAgentPausedTask, isResumablePausedTask, registerPauseReleaseAdapter } from '../lib/taskPauseHold.js';import { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAgentStatsFromRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';import { runnerEntryShieldsRunningRecord } from '../lib/runnerAgentLiveness.js';@@ -429,11 +429,64 @@ export async function resumeAgent(agentId, overrides = {}) {agentId, taskId: resumed.taskId, branchName: resumed.branchName, mode: resumed.mode});+ // Dispatched AFTER the retirement above, for the same reason that retirement is+ // last: the task has to be `pending` and pointed at its resume branch before+ // anything can spawn it.+ const dispatch = await dispatchResumedTask(resumed);+// `created` says whether anything was queued, so a caller doesn't have to keep its// own copy of the mode enum to know — a client that guesses would go on announcing// "created a resume task" for a future non-creating mode, which is the exact false// claim this change exists to delete.- return { success: true, agentId, created: mode === 'new-task', ...resumed };+ return { success: true, agentId, created: mode === 'new-task', ...resumed, ...dispatch };+}++/**+ * Start the resumed task NOW, when the agent pool has room for it.+ *+ * The requeue alone only makes the task ELIGIBLE. What actually spawns it is the+ * automatic dequeue `completeAgent` schedules, and that path admits pending USER+ * tasks plus auto-approved system tasks under CoS auto-run in `execute` mode — so+ * a resumed internal task on an install with auto-run off, or one still awaiting+ * approval, sat `pending` until the user opened the task list and pressed Run.+ * That turns the one-click Resume/Relaunch into a two-step, on the exact screen+ * the user just acted from.+ *+ * This sits in `resumeAgent` rather than in `relaunchAgent` because relaunch is+ * defined as a pause plus a resume — it inherits the dispatch through that+ * composition, so the rule has one address. It does NOT sit deeper, in+ * `reviveBlockedTask` or the `tasks:changed` unblock listener, because those are+ * shared with the autonomous revival paths (investigation retry, orphan cooldown,+ * completion cleanup), and force-spawning there would strip the auto-run gate that+ * deliberately withholds unattended spawns. Both doors into here are a human+ * clicking a button, which is what makes the explicit dispatch correct.+ *+ * It goes through `forceSpawnTask`, the same door "Run now" uses, and inherits its+ * refusals rather than restating them. Best-effort by design: a stopped/paused+ * daemon, an unreachable runner, a task needing approval, and a full agent pool all+ * mean "leave it queued", which is the pre-existing behavior. The refusal is+ * reported as `spawnHold` so the dialog can say which, instead of toasting a resume+ * that silently didn't start.+ */+async function dispatchResumedTask({ taskId, mode }) {+ // `already-active` and `superseded` queue nothing on purpose — the task is+ // either already in flight or owned by a later pause, and dispatching it here+ // is exactly the duplicate spawn `classifyResume` exists to prevent.+ if (!taskId || (mode !== 'requeued' && mode !== 'new-task')) return { spawned: false, spawnHold: null };++ const result = await forceSpawnTask(taskId).catch(err => ({ error: err?.message || String(err) }));+ if (result?.success) return { spawned: true, spawnHold: null };++ // The dequeue `completeAgent` schedules races this call, so a refusal can mean+ // "already claimed" rather than "held". Read the task back and treat only a+ // real claim (`in_progress`) as started — string-matching the refusal would+ // drift the moment forceSpawnTask reworded one of them.+ const task = await getTaskById(taskId).catch(() => null);+ if (task?.status === 'in_progress') return { spawned: true, spawnHold: null };++ const spawnHold = result?.error || 'Task could not be spawned';+ emitLog('info', `⏳ Resumed task ${taskId} stays queued — ${spawnHold}`, { taskId });+ return { spawned: false, spawnHold };}/**@@ -485,6 +538,10 @@ export async function relaunchAgent(agentId, overrides = {}) {emitLog('warn', `⚠️ Relaunch of ${agentId} proceeded before its process exited — its worktree may not survive`, { agentId });}+ // `resumeAgent` already force-spawned the requeued task where it could+ // (`dispatchResumedTask`), so `spawned`/`spawnHold` ride along in `resumed` —+ // relaunch inherits the immediate dispatch through the composition rather than+ // repeating it.const resumed = await resumeAgent(agentId, resumeOverrides);emitLog('info', `🔁 Relaunched agent ${agentId} — ${pauseReason}`, {agentId, taskId: resumed.taskId, mode: resumed.modediff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 9b5f0aa034..8fbc1a4f42 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -54,7 +54,8 @@ vi.mock('./cos.js', () => ({getTaskById: vi.fn(),getAllTasks: vi.fn(),reviveBlockedTask: vi.fn().mockResolvedValue(true),- evaluateTasks: vi.fn().mockResolvedValue(undefined)+ evaluateTasks: vi.fn().mockResolvedValue(undefined),+ forceSpawnTask: vi.fn().mockResolvedValue({ success: true })}));vi.mock('./cosEvents.js', () => ({@@ -122,7 +123,7 @@ import { getAgents, updateAgent, getAgentRecord, readAgentRecordOrUnreadable, AGimport { updateRun, getProject } from './creativeDirector/local.js';import { advanceAfterPlanStepSettled } from './creativeDirector/planAdvance.js';import { advanceAfterSceneSettled } from './creativeDirector/completionHook.js';-import { updateTask, addTask, getTaskById, getAllTasks, reviveBlockedTask } from './cos.js';+import { updateTask, addTask, getTaskById, getAllTasks, reviveBlockedTask, forceSpawnTask } from './cos.js';import { pauseAgentViaRunner, terminateAgentViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';@@ -922,6 +923,7 @@ describe('resumeAgent — requeues the paused agent\'s own task', () => {resumedFromAgentId: 'agent-paused-1',resumeWorktreePath: '/tmp/worktrees/agent-paused-1',});+ forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-abc' });});it('flips the SAME task back to pending — no new task', async () => {@@ -1129,6 +1131,49 @@ describe('resumeAgent — requeues the paused agent\'s own task', () => {getTaskById.mockResolvedValue(null);await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ mode: 'new-task' });});++ // The requeue only makes the task ELIGIBLE, and the automatic dequeue admits+ // system tasks only under CoS auto-run — so without an explicit dispatch a+ // resumed task sits `pending` until the user opens the task list and presses+ // Run, which is the two-step both Resume and Relaunch exist to avoid.+ it('force-spawns the requeued task instead of leaving it pending', async () => {+ const result = await resumeAgent('agent-paused-1');++ expect(forceSpawnTask).toHaveBeenCalledWith('task-abc');+ expect(result).toMatchObject({ spawned: true, spawnHold: null });+ });++ it('reports the refusal instead of claiming a resume that never started', async () => {+ // A full pool / paused daemon / unreachable runner all mean "stays queued".+ // Reporting `spawned: true` there is what would send the user to a task list+ // showing a pending task after a toast that said it was running.+ forceSpawnTask.mockResolvedValue({ error: 'No available agent slots (3/3)' });++ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({+ mode: 'requeued', spawned: false, spawnHold: 'No available agent slots (3/3)',+ });+ });++ it('treats a task the racing dequeue already claimed as started, not as held', async () => {+ // `completeAgent` schedules a dequeue that can claim the task first; the+ // force-spawn then refuses because it is no longer `pending`. That is the+ // resume working, so the result must not report a hold.+ forceSpawnTask.mockImplementation(async () => {+ getTaskById.mockResolvedValue({ ...PAUSED_TASK, status: 'in_progress' });+ return { error: 'Task is in_progress, not pending' };+ });++ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ spawned: true, spawnHold: null });+ });++ it('does not dispatch a mode that deliberately queued nothing', async () => {+ // `already-active` means some other path already put the work in flight —+ // force-spawning here is the duplicate agent classifyResume exists to prevent.+ getTaskById.mockResolvedValue({ ...PAUSED_TASK, status: 'in_progress', metadata: { context: 'original context' } });++ await expect(resumeAgent('agent-paused-1')).resolves.toMatchObject({ mode: 'already-active', spawned: false });+ expect(forceSpawnTask).not.toHaveBeenCalled();+ });});// ─── relaunchAgent ────────────────────────────────────────────────────────────@@ -1171,6 +1216,7 @@ describe('relaunchAgent — moves a running agent\'s task onto another provider'getAgentRecord.mockImplementation(async () => ({ ...LIVE_AGENT, status: paused ? 'paused' : 'running' }));getTaskById.mockResolvedValue(PAUSED_TASK);reviveBlockedTask.mockResolvedValue({ metadata: {} });+ forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-abc' });});it('requeues the SAME task with the new provider/model/effort — no second task', async () => {@@ -1247,6 +1293,21 @@ describe('relaunchAgent — moves a running agent\'s task onto another provider'expect(metadata.effort).toBe('max');});+ // Relaunch is a pause plus a resume, so the immediate dispatch is inherited from+ // `resumeAgent` rather than repeated here (its own refusal/race handling is+ // covered in the resume suite above). This locks the inheritance: a relaunch that+ // stopped passing the dispatch outcome through would silently go back to leaving+ // the task pending for a user to run by hand.+ it('starts the requeued task and passes the dispatch outcome through', 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' });++ expect(forceSpawnTask).toHaveBeenCalledWith('task-abc');+ expect(result).toMatchObject({ relaunched: true, spawned: true, spawnHold: null });+ });+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({