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
fix([issue-2705]): deliver antigravity TUI prompts + settle orphaned CD runs
Adam Eivydcfdb7be9570
diff --git a/client/src/components/creative-director/RunsTab.jsx b/client/src/components/creative-director/RunsTab.jsxindex b6988798c5..fd444bf8b5 100644--- a/client/src/components/creative-director/RunsTab.jsx+++ b/client/src/components/creative-director/RunsTab.jsx@@ -38,6 +38,13 @@ export default function RunsTab({ project }) {</div>)}{r.error && <div className="text-xs text-port-error mt-1">{r.error}</div>}+ {/* failureReason is what recovery + orphan-settle write (e.g. "interrupted+ by restart", "agent process terminated unexpectedly (orphaned)") — a+ failed run with no `error` used to render blank, so surface it too so a+ failed run always says WHY (issue #2705). */}+ {r.failureReason && r.failureReason !== r.error && (+ <div className="text-xs text-port-error mt-1">{r.failureReason}</div>+ )}</div>))}</div>diff --git a/client/src/components/creative-director/RunsTab.test.jsx b/client/src/components/creative-director/RunsTab.test.jsxnew file mode 100644index 0000000000..69688e6c60--- /dev/null+++ b/client/src/components/creative-director/RunsTab.test.jsx@@ -0,0 +1,63 @@+/**+ * RunsTab — surfaces a failed run's failureReason so a failed run always says+ * WHY (issue #2705). Recovery + orphan-settle write `failureReason` (not `error`),+ * and the tab previously rendered only `error`, so those runs showed blank.+ */+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';++import RunsTab from './RunsTab.jsx';++const renderTab = (project) =>+ render(+ <MemoryRouter>+ <RunsTab project={project} />+ </MemoryRouter>,+ );++describe('RunsTab — run failure reasons', () => {+ it('renders a failed run\'s failureReason', () => {+ renderTab({+ runs: [+ {+ runId: 'r1', kind: 'plan', status: 'failed',+ startedAt: '2026-07-16T23:52:34.206Z',+ failureReason: 'interrupted by restart',+ },+ ],+ });+ expect(screen.getByText('interrupted by restart')).toBeInTheDocument();+ });++ it('surfaces the orphan-settle reason (the case that used to render blank)', () => {+ renderTab({+ runs: [+ {+ runId: 'r2', kind: 'plan', status: 'failed',+ startedAt: '2026-07-16T23:59:30.600Z',+ failureReason: 'agent process terminated unexpectedly (orphaned)',+ },+ ],+ });+ expect(screen.getByText(/orphaned/)).toBeInTheDocument();+ });++ it('does not duplicate the message when error and failureReason are identical', () => {+ renderTab({+ runs: [+ {+ runId: 'r3', kind: 'treatment', status: 'failed',+ startedAt: '2026-07-16T23:59:30.600Z',+ error: 'same message', failureReason: 'same message',+ },+ ],+ });+ expect(screen.getAllByText('same message')).toHaveLength(1);+ });++ it('shows an empty-state message when there are no runs', () => {+ renderTab({ runs: [] });+ expect(screen.getByText(/No runs yet/)).toBeInTheDocument();+ });+});diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 99689c5db9..f48692e284 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -478,6 +478,34 @@ export async function isPidAlive(pid) {* - Creates investigation task after max retries exceeded* - Triggers evaluation to spawn new agents*/++/**+ * Settle a Creative Director run tied to an orphaned/reaped agent (issue #2705).+ *+ * A CD plan/treatment agent that dies without issuing its completion PATCH leaves+ * its `runs[]` row stuck `running`. `maybeEnqueuePlan`'s guard then treats that+ * non-terminal run as "a worker is already on it" and refuses to re-dispatch — so+ * the project wedges in `planning` until the NEXT server restart runs boot+ * recovery (`recoverInFlightProjects`). Reaping the run here — mirroring recovery's+ * reap — lets the project advance without a restart (the orphan-task retry then+ * re-dispatches the plan). No-op for non-CD tasks; the `creativeDirector/local.js`+ * import is deferred so non-CD orphans pay nothing. Exported for unit testing.+ *+ * @param {object|null} task - the orphaned agent's task record.+ * @returns {Promise<boolean>} true if a CD run was settled, false for a non-CD task.+ */+export async function settleOrphanedCreativeDirectorRun(task) {+ const cd = task?.metadata?.creativeDirector;+ if (!cd?.projectId || !cd?.runId) return false;+ const { updateRun } = await import('./creativeDirector/local.js');+ await updateRun(cd.projectId, cd.runId, {+ status: 'failed',+ completedAt: new Date().toISOString(),+ failureReason: 'agent process terminated unexpectedly (orphaned)',+ }).catch((err) => console.log(`⚠️ CD orphan settle: run ${cd.runId?.slice(0, 8)} of ${cd.projectId} failed: ${err.message}`));+ return true;+}+export async function cleanupOrphanedAgents() {const { getAgents, completeAgent: markComplete, evaluateTasks, getTaskById: getTask } = await import('./cos.js');const agents = await getAgents();@@ -545,6 +573,13 @@ export async function cleanupOrphanedAgents() {await cleanupAgentWorktree(agentId, false);}+ // Settle any Creative Director run tied to an orphaned agent (issue #2705)+ // BEFORE the retry below, so the project can advance without a server restart.+ for (const { taskId } of orphanedTaskIds) {+ const task = await getTask(taskId).catch(() => null);+ await settleOrphanedCreativeDirectorRun(task);+ }+// Handle orphaned tasks - reset for retry or create investigation taskfor (const { taskId, agentId } of orphanedTaskIds) {await handleOrphanedTask(taskId, agentId, getTask);diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 6b3628dec6..f685948435 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -74,14 +74,42 @@ vi.mock('./agentLifecycle.js', () => ({syncRunnerAgents: vi.fn().mockResolvedValue(0)}));vi.mock('./worktreeManager.js', () => ({ cleanupOrphanedWorktrees: vi.fn() }));+vi.mock('./creativeDirector/local.js', () => ({ updateRun: vi.fn().mockResolvedValue(undefined) }));-import { handleOrphanedTask, pauseAgent } from './agentManagement.js';+import { handleOrphanedTask, pauseAgent, settleOrphanedCreativeDirectorRun } from './agentManagement.js';+import { updateRun } from './creativeDirector/local.js';import { updateTask, addTask, getTaskById } from './cos.js';import { updateAgent } from './cosAgents.js';import { pauseAgentViaRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';+describe('settleOrphanedCreativeDirectorRun — reap a dead CD agent run (#2705)', () => {+ beforeEach(() => vi.clearAllMocks());++ it('marks the orphaned CD plan agent run failed with an orphan reason', async () => {+ const task = {+ id: 'cd-cd-p1-plan-abc',+ metadata: { creativeDirector: { projectId: 'cd-p1', runId: 'run-abc', kind: 'plan', sceneId: null } },+ };+ const settled = await settleOrphanedCreativeDirectorRun(task);+ expect(settled).toBe(true);+ expect(updateRun).toHaveBeenCalledWith(+ 'cd-p1',+ 'run-abc',+ expect.objectContaining({ status: 'failed', failureReason: expect.stringContaining('orphaned') }),+ );+ });++ it('is a no-op (no updateRun) for a non-CD task or a CD task missing projectId/runId', async () => {+ expect(await settleOrphanedCreativeDirectorRun({ id: 't', metadata: {} })).toBe(false);+ expect(await settleOrphanedCreativeDirectorRun(null)).toBe(false);+ // metadata present but incomplete — must not settle a run it can't identify.+ expect(await settleOrphanedCreativeDirectorRun({ metadata: { creativeDirector: { projectId: 'cd-p1' } } })).toBe(false);+ expect(updateRun).not.toHaveBeenCalled();+ });+});+describe('handleOrphanedTask — duplicate-investigation guard', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 9ba435d77f..23b2c14979 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -1123,7 +1123,17 @@ export async function spawnTuiAgent({// POSITIVE input-ready footer (see createInputReadyTracker), auto-confirm the// trust gate, and NEVER blind-paste: if the prompt never appears we surface a// failure. Other TUI providers keep the original idle heuristic + deadline.- const requireInputReady = commandName === 'claude';+ //+ // Antigravity (agy) gets the SAME positive gate (issue #2705). agy's TUI also+ // enables bracketed-paste mode (`ESC[?2004h`) exactly when its input box is+ // live — the identical signal createInputReadyTracker keys on — but the old+ // blind-paste path fired into agy's still-initializing banner, so the prompt+ // never landed and the agent sat idle at an empty prompt until it was reaped+ // having done nothing. agy has no folder-trust gate (`needsTrust` stays false,+ // so the auto-confirm branch below is inert for it); and if agy ever fails to+ // signal ready, the requireInputReady path fails fast with a surfaced startup+ // error instead of silently idle-reaping.+ const requireInputReady = isClaudeCommand(tuiConfig.command) || isAntigravityCommand(tuiConfig.command);// sendPrompt / finishStartupFailure are async and dispatched fire-and-forget// from the interval below. A setInterval callback can't await, and an// unhandled rejection there (e.g. a finalizeAgent throw inside finish())diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex d66550fa06..c08b838cd5 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -825,6 +825,8 @@ describe('spawnTuiAgent runtime', () => {// ── 1c. claude waits for bracketed-paste mode (input ready) before pasting ───const claudeTuiConfig = { command: 'claude', args: [], commandLine: 'claude', promptDelayMs: 100, idleTimeoutMs: 50 };+ // Antigravity (agy) gets the SAME positive input-ready gate as claude (#2705).+ const agyTuiConfig = { command: 'agy', args: [], commandLine: 'agy', promptDelayMs: 100, idleTimeoutMs: 50 };const pasteCount = () => vi.mocked(shellService.writeToSession).mock.calls.filter(([, d]) => typeof d === 'string' && d.includes('\x1b[200~')).length;// The launch shell turns bracketed-paste OFF to run the command, then claude@@ -912,6 +914,53 @@ describe('spawnTuiAgent runtime', () => {);});+ // ── 1c-bis. Antigravity (agy) uses the SAME positive input-ready gate (#2705) ─+ // agy's TUI emits the bracketed-paste-mode toggle exactly like claude, so it+ // must gate the paste on paste-mode-re-enabled rather than blind-pasting on the+ // idle heuristic (which fired into agy's still-initializing banner and left the+ // agent sitting at an empty prompt until it was reaped). Without the fix agy+ // took the idle-heuristic path and WOULD have pasted after ~2s of banner idle;+ // asserting pasteCount()===0 there is what discriminates the fix.+ it('agy input-ready: does NOT paste on the startup banner, only once paste mode is re-enabled', async () => {+ runSpawn({ tuiConfig: agyTuiConfig });+ await flushMicrotasks();++ // Startup banner (and the shell turning paste mode OFF to run the command).+ await capturedOnData(Buffer.from(`${PASTE_OFF}Antigravity CLI 1.1.3\nGemini 3.5 Flash (Medium)\n`));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();+ expect(pasteCount()).toBe(0); // banner / paste-mode-off is not "input ready"++ // agy re-enables bracketed-paste mode → input box live, safe to paste.+ await capturedOnData(Buffer.from(PASTE_ON));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(400);+ await flushMicrotasks();+ expect(pasteCount()).toBe(1);+ });++ it('agy tui-not-ready: an agy TUI that never signals input-ready fails fast instead of idle-reaping', async () => {+ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ runSpawn({ tuiConfig: agyTuiConfig });+ await flushMicrotasks();+ await capturedOnData(Buffer.from('some agy startup noise but no input box ever appears\n'));+ await flushMicrotasks();++ // Advance past TUI_INPUT_READY_DEADLINE_MS (45s).+ await vi.advanceTimersByTimeAsync(46000);+ vi.useRealTimers();+ await completeDone;++ expect(pasteCount()).toBe(0);+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', success: false, completionReason: 'tui-not-ready' })+ );+ });+// ── 1a-bis. Non-counter TUI provider keeps the permissive idle-complete ──────// The work-counter signal only exists on Claude Code / Codex. On a provider// that never renders it (Antigravity/Gemini), absence proves nothing — so a