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
gate the feature-agent hand-back on a continuation actually being queued
[._.]/ Adam Eivydd4a1e51a073
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 8b20816a01..3050a72e71 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -977,9 +977,11 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,)}{/* Feedback section - shown for completed, manually-run, non-system local- agents. A handoff is excluded: there is no result to rate, and the- continuation run asks for the rating that covers this work. */}- {completed && !isSystemAgent && isManualUserAgent && !remote && !handoff && (+ agents. A handoff has no result to rate — the continuation run asks for+ the rating that covers this work — so it is excluded UNLESS a rating is+ already on the record: pre-upgrade handoffs were ratable, and hiding the+ block outright would swallow a verdict the user did give. */}+ {completed && !isSystemAgent && isManualUserAgent && !remote && (!handoff || !!feedbackState) && (<div className="mt-2 pt-1 border-t border-port-border/50"><div className="flex items-center gap-3 flex-wrap"><span className="text-xs text-gray-500">Was this helpful?</span>diff --git a/client/src/lib/agentOutcome.js b/client/src/lib/agentOutcome.jsindex 87770b33b0..9dc176d3c4 100644--- a/client/src/lib/agentOutcome.js+++ b/client/src/lib/agentOutcome.js@@ -27,13 +27,23 @@ export function isAgentHandoff(agent) {/*** The one line a handoff card should show: WHAT THE USER CHANGED.*- * `metadata.pauseReason` first, because on a Relaunch that is the sentence the- * user is looking for ("Relaunched by user on codex / gpt-5"), while- * `result.error` holds `resumeAgent`'s summary — which says where the TASK went,- * not why this run stopped. Client-only: nothing server-side renders it, and- * keeping it out of the mirrored half is what keeps the parity test a one-line- * contract.+ * When a continuation was actually queued (`resumedTaskId`), `metadata.pauseReason`+ * wins: on a Relaunch that is the sentence the user is looking for ("Relaunched by+ * user on codex / gpt-5"), while `result.error` holds `resumeAgent`'s summary,+ * which says where the TASK went rather than why this run stopped.+ *+ * With no continuation the order flips. `retireStrandedPausedAgents` also stamps+ * `resumed: true` — on a pause whose task was deleted or moved on — and there the+ * pause reason is the ORIGINAL one ("Paused by user"), which would read as a+ * deliberate provider swap for a run that was simply abandoned. `result.error`+ * ("Pause retired — its task … no longer exists") is the honest line.+ *+ * Client-only: nothing server-side renders it, and keeping it out of the mirrored+ * half is what keeps the parity test a one-line contract.*/export function agentHandoffReason(agent) {- return agent?.metadata?.pauseReason || agent?.result?.error || 'Handed off to a new run';+ const error = agent?.result?.error;+ const pauseReason = agent?.metadata?.pauseReason;+ const handedOn = !!agent?.result?.resumedTaskId;+ return (handedOn ? pauseReason || error : error || pauseReason) || 'Handed off to a new run';}diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex f228f118ab..00f91f611e 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -10,6 +10,7 @@ import * as api from '../services/api';import { isRiggedAvatarStyle, riggedRecordForStyle, useAvatarCapabilities } from '../hooks/useAvatarCapabilities';import { coalesce } from '../utils/coalesce';import { sameJsonShape } from '../lib/sameJsonShape';+import { isAgentHandoff } from '../lib/agentOutcome';import { WEBGL_AVATAR_STYLE_IDS } from '../lib/avatarStyles';import { Play, Pause, Square, Clock, CheckCircle, AlertCircle, Cpu, ChevronDown, ChevronUp, Brain, PanelLeftClose, PanelLeftOpen } from 'lucide-react';import toast from '../components/ui/Toast';@@ -451,8 +452,14 @@ export default function ChiefOfStaff() {const handleAgentCompleted = (data) => {setAgentState('reviewing');- const success = data?.result?.success;- setStatusMessage(success ? "Task completed successfully" : "Task failed - checking errors...");+ // Three outcomes, not two: a run retired by Resume/Relaunch never reached a+ // verdict, so announcing "Task failed" for it tells the user their own+ // provider swap broke something.+ setStatusMessage(+ isAgentHandoff(data) ? "Handed the task to a new run"+ : data?.result?.success ? "Task completed successfully"+ : "Task failed - checking errors..."+ );setSpeaking(true);setTimeout(() => setSpeaking(false), SPEAKING_MS);// Clear active agent metadata so avatar reverts to defaultdiff --git a/server/lib/agentOutcome.parity.test.js b/server/lib/agentOutcome.parity.test.jsindex 37ecf59646..9c79ef00e7 100644--- a/server/lib/agentOutcome.parity.test.js+++ b/server/lib/agentOutcome.parity.test.js@@ -54,18 +54,28 @@ describe.each(IMPLEMENTATIONS)('isAgentHandoff (%s)', (_side, isAgentHandoff) =>});describe('agentHandoffReason (client-only)', () => {- it('prefers the pause reason, which names what the USER changed', () => {- // `result.error` is `resumeAgent`'s summary — "task … requeued on <branch>" —- // which answers a question nobody asked while looking at the run they just- // relaunched.+ it('prefers the pause reason when a continuation was actually queued', () => {+ // `result.error` there is `resumeAgent`'s summary — "task … requeued on+ // <branch>" — which answers a question nobody asked while looking at the run+ // they just relaunched.expect(agentHandoffReason({metadata: { pauseReason: 'Relaunched by user on codex / gpt-5' },- result: { error: 'Resumed agent agent-1 — task task-1 requeued on cos/task-1/agent-1' },+ result: { resumed: true, resumedTaskId: 'task-1', error: 'Resumed agent agent-1 — task task-1 requeued on cos/task-1/agent-1' },})).toBe('Relaunched by user on codex / gpt-5');});- it('falls back to the resume summary, then to a generic line', () => {- expect(agentHandoffReason({ result: { error: 'Resumed agent agent-1' } })).toBe('Resumed agent agent-1');+ it('prefers the retirement reason when NOTHING was queued', () => {+ // `retireStrandedPausedAgents` stamps `resumed: true` with no `resumedTaskId`+ // on a pause whose task is gone. Its `pauseReason` is the ORIGINAL one, so+ // preferring it would caption an abandoned run as a deliberate provider swap.+ expect(agentHandoffReason({+ metadata: { pauseReason: 'Paused by user' },+ result: { resumed: true, error: 'Pause retired — its task task-9 no longer exists' },+ })).toBe('Pause retired — its task task-9 no longer exists');+ });++ it('falls back through to a generic line', () => {+ expect(agentHandoffReason({ result: { resumed: true, resumedTaskId: 't1' }, metadata: {} })).toBe('Handed off to a new run');expect(agentHandoffReason({ result: { resumed: true } })).toBe('Handed off to a new run');});});diff --git a/server/services/featureAgents.js b/server/services/featureAgents.jsindex 084db1c3f9..74859ee095 100644--- a/server/services/featureAgents.js+++ b/server/services/featureAgents.js@@ -566,6 +566,20 @@ export async function setCurrentAgent(id, taskId) {});}+// Move a feature agent's pointer from the run that just handed off to the task its+// continuation will spawn from — but ONLY while it still names that retired run.+// See the `agent:completed` handler for the race this guards.+async function handOffCurrentAgent(id, retiredAgentId, continuationTaskId) {+ return withLock(async () => {+ const data = await readData();+ const idx = data.agents.findIndex(a => a.id === id);+ if (idx === -1 || data.agents[idx].currentAgentId !== retiredAgentId) return;+ data.agents[idx].currentAgentId = continuationTaskId;+ data.agents[idx].updatedAt = new Date().toISOString();+ await writeData(data);+ });+}+async function clearPendingAgentTask(id, taskId) {return withLock(async () => {const data = await readData();@@ -602,22 +616,34 @@ cosEvents.on('agent:completed', async (agentData) => {// A relaunch retires this record and requeues the SAME task on a new provider,// so the run is still in flight. Recording it would flip the feature agent to// `error`, bump its run count, and write a run-history entry reading- // "Relaunched by user" — for work that has not finished.+ // "Relaunched by user" — for work that has not finished. Instead, follow the+ // task: `currentAgentId` holds the RETIRED agent's id, and the `agent:spawned`+ // listener above re-binds only a feature agent still pointing at the TASK, so+ // without this hand-back the pointer stays on a dead agent and the+ // continuation's output never reaches the feature-agent view.//- // Instead, follow the task. `currentAgentId` holds the retired agent's id,- // and the `agent:spawned` listener above re-binds it only for a feature agent- // still pointing at the TASK — so without this hand-back the pointer stays on a- // dead agent and the continuation's output never reaches the feature-agent view.- if (isAgentHandoff(agentData)) {- // `resumedTaskId` — not `taskId` — because a resume that could not reuse the- // paused task queues a REPLACEMENT (which inherits this feature agent's- // metadata), and pointing at the retired task id would never re-bind.- const continuationTaskId = agentData.result?.resumedTaskId || agentData.taskId;- if (continuationTaskId) {- await setCurrentAgent(featureAgentId, continuationTaskId).catch(err => {- console.log(`⚠️ Failed to hand feature agent ${featureAgentId} back to its relaunched task: ${err.message}`);- });- }+ // Gated on `resumedTaskId`, which is what proves a continuation was actually+ // QUEUED. `resumed: true` alone does not: `retireStrandedPausedAgents` stamps+ // it on a pause whose task is gone or has moved on, with no `resumedTaskId` and+ // nothing requeued. Handing back there — to `agentData.taskId`, a task that no+ // longer exists — parks a pointer no `agent:spawned` can ever clear, and both+ // `triggerFeatureAgent` and `getDueFeatureAgents` refuse to run a feature agent+ // that holds one. The agent would never run again, by schedule or by hand,+ // recoverable only by Stop and re-activate. Those retirements fall through to+ // `recordRunCompletion` below, which clears the pointer as it always did.+ const continuationTaskId = isAgentHandoff(agentData) ? agentData.result?.resumedTaskId : null;+ if (continuationTaskId) {+ // Compare-and-set against the retired agent's id, because this races the+ // spawn of the very continuation it points at: `requeuePausedTask` runs+ // BEFORE `completeAgent`, and the `tasks:changed` it emits schedules the+ // dequeue on a `setImmediate` while `completeAgent` is still writing state and+ // archiving. If that spawn won and `agent:spawned` already bound the live+ // agent, overwriting it with the task id would blank the output view for the+ // whole run; losing the race merely leaves the pointer on the task until the+ // continuation completes and clears it.+ await handOffCurrentAgent(featureAgentId, agentData.id, continuationTaskId).catch(err => {+ console.log(`⚠️ Failed to hand feature agent ${featureAgentId} back to its relaunched task: ${err.message}`);+ });return;}const success = agentData.result?.success === true;diff --git a/server/services/featureAgents.trigger.test.js b/server/services/featureAgents.trigger.test.jsindex da753ea060..461929b939 100644--- a/server/services/featureAgents.trigger.test.js+++ b/server/services/featureAgents.trigger.test.js@@ -22,7 +22,7 @@ vi.mock('./apps.js', () => ({import { addTask, forceSpawnTask } from './cos.js';import { getAppById } from './apps.js';-const { generateTaskFromFeatureAgent, triggerFeatureAgent } = await import('./featureAgents.js');+const { generateTaskFromFeatureAgent, triggerFeatureAgent, stopFeatureAgent, updateFeatureAgent } = await import('./featureAgents.js');import { cosEvents } from './cosEvents.js';const agent = {@@ -121,6 +121,70 @@ describe('triggerFeatureAgent', () => {});});+ it('does NOT hand back a stranded pause, which would wedge the agent forever', async () => {+ // `retireStrandedPausedAgents` stamps `resumed: true` on a pause whose task is+ // gone, with no `resumedTaskId` and nothing requeued. Handing back to the dead+ // `taskId` parks a pointer no `agent:spawned` can clear, and both+ // `triggerFeatureAgent` and `getDueFeatureAgents` refuse to run a feature agent+ // holding one — so the agent never runs again by schedule or by hand.+ const result = await triggerFeatureAgent(agent.id);+ cosEvents.emit('agent:spawned', { taskId: result.taskId, id: 'agent-first' });+ await vi.waitFor(async () => {+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].currentAgentId).toBe('agent-first');+ });++ cosEvents.emit('agent:completed', {+ id: 'agent-first',+ taskId: result.taskId,+ metadata: { featureAgentId: agent.id, featureAgentRun: true },+ result: { success: false, resumed: true, error: 'Pause retired — its task no longer exists' },+ });++ await vi.waitFor(async () => {+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].currentAgentId).toBeNull();+ });+ // And it is runnable again, which is the whole point.+ expect((await triggerFeatureAgent(agent.id)).triggered).toBe(true);+ });++ it('does not resurrect the pointer when the agent was stopped mid-relaunch', async () => {+ // The hand-back is a compare-and-set against the RETIRED agent's id, not a+ // blind write: `agent:completed` is delivered asynchronously, so anything that+ // legitimately moved the pointer in between must win. Stop is the reachable+ // one — it sets `currentAgentId = null` and `status: 'draft'`, and a hand-back+ // that wrote the task id over that leaves a STOPPED feature agent holding a+ // pointer, which `triggerFeatureAgent` and `getDueFeatureAgents` both read as+ // "a run is already in flight" — so Stop would quietly disable the agent.+ const result = await triggerFeatureAgent(agent.id);+ cosEvents.emit('agent:spawned', { taskId: result.taskId, id: 'agent-first' });+ await vi.waitFor(async () => {+ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].currentAgentId).toBe('agent-first');+ });++ await stopFeatureAgent(agent.id);++ cosEvents.emit('agent:completed', {+ id: 'agent-first',+ taskId: result.taskId,+ metadata: { featureAgentId: agent.id, featureAgentRun: true },+ result: { success: false, resumed: true, resumedTaskId: result.taskId, error: 'Relaunched by user' },+ });++ // Deterministic settle, not a sleep: the listener reaches `withLock` before+ // `emit()` returns (nothing awaits ahead of it), so anything queued onto that+ // same mutex afterwards resolves strictly after the hand-back would have+ // written. `updateFeatureAgent` takes the lock and never touches+ // `currentAgentId`, so it orders the assertion without destroying the evidence.+ await updateFeatureAgent(agent.id, { description: 'settle' });++ const saved = JSON.parse(await readFile(dataPath(), 'utf8'));+ expect(saved.agents[0].currentAgentId).toBeNull();+ expect(saved.agents[0].status).toBe('draft');+ });+it('points at the REPLACEMENT task when a resume could not reuse the paused one', async () => {// `resumeAgent`'s new-task mode queues a fresh task (inheriting this feature// agent's metadata) and reports it as `resumedTaskId`. Handing back thediff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.jsindex 8c8357789f..2068100d62 100644--- a/server/services/maintenanceRun.test.js+++ b/server/services/maintenanceRun.test.js@@ -147,6 +147,27 @@ describe('manual maintenance run', () => {expect((await getMaintenanceRun(run.id)).active.stepId).toBe(run.steps[0].id);});+ it('a relaunched step neither completes nor settles the run', async () => {+ // Relaunch retires the step's agent with `success: false` and requeues the+ // SAME task on another provider, so the step is still in flight. Evaluating+ // here would report it as a hold the user must retry or dismiss, for work that+ // is already on its way back out. The continuation's own completion advances+ // the run; `retryMaintenanceRuns` is the backstop if it never lands.+ const { run } = await start();+ const relaunched = {+ ...agentFor(run, 0, false),+ result: { success: false, resumed: true, resumedTaskId: 'task-0', error: 'Relaunched by user on codex' },+ };++ expect(await __onMaintenanceAgentCompleted(relaunched)).toBeNull();++ const after = await getMaintenanceRun(run.id);+ expect(after.completed).toEqual({});+ expect(after.active.stepId).toBe(run.steps[0].id);+ // Nothing new dispatched — only the step that was already running.+ expect(state.invoked).toHaveLength(1);+ });+it('stops without recalling work, resumes from its ledger, and refuses a second run for the same app', async () => {const { run } = await start();await expect(start()).rejects.toMatchObject({ status: 409, code: 'MAINTENANCE_RUN_ACTIVE' });diff --git a/server/services/productivity.test.js b/server/services/productivity.test.jsindex 8d77441b7a..f1f34a50d8 100644--- a/server/services/productivity.test.js+++ b/server/services/productivity.test.js@@ -59,6 +59,14 @@ const agentOn = (id, { month = 3, day, hour = 10, minute = 0, success = true, duresult: { success, duration },});+// What Relaunch leaves behind: `success: false` with `resumed: true`, requeued on+// a new provider. It reached no verdict, so it must not score a failure against+// the hour and weekday the user happened to press the button.+const handoffOn = (id, opts) => {+ const base = agentOn(id, { ...opts, success: false });+ return { ...base, result: { ...base.result, resumed: true, resumedTaskId: `task-${id}`, error: 'Relaunched by user on codex' } };+};+const seed = (data) => {mkdirSync(COS_DIR, { recursive: true });writeFileSync(PRODUCTIVITY_FILE, JSON.stringify(data));@@ -107,6 +115,18 @@ describe('recalculateProductivity — activity totals', () => {expect(result.totals).toMatchObject({ totalTasks: 3, activeDays: 3, activeWeeks: 1 });});+ it('ignores a relaunched run, which reached no verdict', async () => {+ mock.agents = [+ agentOn('good', { day: 18, hour: 9 }),+ handoffOn('swapped', { day: 18, hour: 9 }),+ ];++ const result = await productivity.recalculateProductivity();++ expect(result.totals).toMatchObject({ totalTasks: 1, successfulTasks: 1, successRate: 100 });+ expect(result.hourlyPatterns[9]).toMatchObject({ tasks: 1, successes: 1, failures: 0 });+ });+it('ignores agents that are not completed or carry no completion stamp', async () => {mock.agents = [agentOn('good', { day: 18 }),@@ -200,6 +220,19 @@ describe('onTaskCompleted — incremental productivity updates', () => {cosEvents.off('productivity:updated', listener);});+ it('banks nothing for a relaunched run, keeping the incremental path in step with the rebuild', async () => {+ // The two paths must agree: if the rebuild drops handoffs but the+ // incremental update banks them, the store drifts until the next recalc+ // silently "loses" tasks the user watched it count.+ seed({ hourlyPatterns: {}, dailyPatterns: {}, dailyHistory: {}, milestones: [] });++ await productivity.onTaskCompleted(handoffOn('swapped', { day: 18, hour: 9 }));++ const stored = readStore();+ expect(stored.dailyHistory['2026-03-18']).toBeUndefined();+ expect(stored.hourlyPatterns[9]).toBeUndefined();+ });+it('prunes daily history older than 90 days', async () => {seed({hourlyPatterns: {}, dailyPatterns: {},diff --git a/server/services/weeklyDigest.test.js b/server/services/weeklyDigest.test.jsindex 0397189ecf..fcbc5ef453 100644--- a/server/services/weeklyDigest.test.js+++ b/server/services/weeklyDigest.test.js@@ -150,6 +150,29 @@ describe('generateWeeklyDigest — summary assembly', () => {expect(digest.generatedAt).toBe(NOW.toISOString());});+ it('leaves a relaunched run out of every week stat, including the error patterns', async () => {+ // A run retired by Resume/Relaunch carries `success: false` with the resume+ // summary in `result.error`, so before the handoff exclusion it dented the+ // success rate AND — because recurring issues are grouped by `result.error` —+ // a week with three provider swaps reported its top recurring issue as+ // "Relaunched by user on codex".+ const swap = (id, day) => ({+ ...agent(id, { day, success: false, duration: 600000, taskType: 'review' }),+ result: { success: false, duration: 600000, resumed: true, resumedTaskId: `task-${id}`, error: 'Relaunched by user on codex' },+ });+ onDates([+ agent('ok', { day: 16, duration: 3600000, taskType: 'review' }),+ swap('s1', 17), swap('s2', 17), swap('s3', 18),+ ]);++ const digest = await digestService.generateWeeklyDigest();++ expect(digest.summary).toMatchObject({ totalTasks: 1, succeededTasks: 1, failedTasks: 0, successRate: 100 });+ // `issues` is the digest's recurring-issue list, grouped by `result.error`.+ expect(digest.issues).toEqual([]);+ expect(digest.accomplishments.map(a => a.id)).toEqual(['ok']);+ });+it('ranks task types by volume with per-type success rates', async () => {onDates([agent('a1', { day: 16, taskType: 'review' }),