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(cos): TUI agent resolution survives the /quit-vs-poll race (#480)
[._.]/ Adam Eivye1e1c844b2fb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3e7206a322..aa39ee01f5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -30,6 +30,8 @@## Fixed+- **Completed Claude TUI agents now show their final resolution again.** When a TUI agent wrote its `.agent-done` completion sentinel and then ran `/quit`, the process exited within milliseconds — long before the 2s sentinel poll fired — so the shell-exit path finalized the agent first and the poll bailed on `finalized`. The sentinel's markdown summary was therefore never appended to the agent's output, leaving the completed-agent details view blank. The sentinel read now happens inside `finish()` (the single chokepoint for every finalize path — `/quit`-exit, idle-timeout, and the poll), so the resolution is captured no matter which path wins the race. Extracted as an idempotent `ingestDoneSentinel()` helper; the poll watcher is now only an early-finalize trigger.+- **Background agent cleanup no longer removes an in-progress manual claim's workspace.** A long-running hands-on task could have its isolated workspace deleted out from under it by the periodic agent-cleanup sweep, which mistook the human-owned workspace for an abandoned agent one. The sweep now leaves manual-claim workspaces alone and only reaps truly abandoned agent workspaces, and it runs on the daily maintenance schedule instead of every 15 minutes.- **Federated media-collection sync reconciliation + resolution UX.** Follow-up to the federated-media-collections feature, fixing issues found running it across two machines. (1) **Universe/series-linked collections now reconcile across peers.** Each machine used to mint a random UUID for its "Universe: X" / "Series: Y" collection, so per-record sync (keyed on `id`) treated each machine's copy as distinct — integrity reported both sides "local only" and the merge created a *duplicate* on every peer. Linked collections now derive a deterministic id (`uc-<universeId>` / `sc-<seriesId>`); create paths reclaim the id when a tombstone holds it (re-creating a deleted collection). Migration 038 canonicalizes existing ids on each machine, merging (union of items) any same-owner duplicates and rewriting `mediaCollection` subscription recordIds — idempotent; both machines converge independently. (2) **New "Pull from peer" action** (`GET /api/peer-sync/record` + `POST /api/peer-sync/pull-record`) lets a machine that is *behind* on a record fetch it and background-pull its asset bytes via `applyIncomingPush`, instead of "Sync to peer" being push-only; the Sync Details drawer is now direction-aware (Pull for peer-only, Sync for local-only, both for diverged/assets-missing). (3) **The Sync Details drawer can no longer hang on "Loading…"** — the record fetch gets a 12s timeout + explicit error state. (4) **Removed the unbounded "Live-pushed records" per-record list** from the Instances page (the Sync Details drawer covers per-record status). `mediaCollections` sync remains opt-in per peer — enable the "Media Collections" category on the Instances page for collections to sync.diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex c980abe993..2c4f30d942 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -182,11 +182,20 @@ export async function spawnTuiAgent({// failure so it gets the full PTY stream regardless of run length.const rawFile = join(agentDir, 'raw.txt');const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : PATHS.root;+ // The agent writes `.agent-done` in its workspace to signal completion (see+ // the sentinel watcher below). Computed up front so both the watcher AND+ // finish() can read it — finish() ingests it directly to survive the+ // /quit-exit-vs-poll race (see ingestDoneSentinel).+ const doneSentinelPath = workspacePath ? join(workspacePath, DONE_SENTINEL_NAME) : null;const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);const commandName = tuiConfig.command.split('/').pop();let outputBuffer = '';let finalized = false;+ // Guards ingestDoneSentinel to a single read. finish() is its only caller and+ // is itself guarded by `finalized`, so this is defensive — it pins the+ // read-at-most-once invariant at the helper.+ let sentinelIngested = false;let hasStartedWorking = false;let promptSentAt = null;let firstOutputAt = null;@@ -333,6 +342,28 @@ export async function spawnTuiAgent({scheduleFlush();};+ // Read the `.agent-done` sentinel (if present) and append its markdown task+ // summary line-by-line into the agent's output so downstream consumers+ // (extractFinalSummary, persistSimplifySummaries, completion hooks, the agent+ // card, output.txt) get the resolution. Called only from finish() (the single+ // finalize chokepoint); idempotent via `sentinelIngested` so it reads at most+ // once. Capped at 4 KB so an agent that pasted the whole diff into the+ // sentinel can't blow up the record.+ const ingestDoneSentinel = async () => {+ if (sentinelIngested) return;+ if (!doneSentinelPath || !existsSync(doneSentinelPath)) return;+ sentinelIngested = true;+ const contents = await readFile(doneSentinelPath, 'utf8').catch(err => {+ console.error(`❌ ingestDoneSentinel readFile failed: ${err.message}`);+ return '';+ });+ const trimmed = contents.trim();+ if (!trimmed) return;+ appendLine(`✅ Agent signaled completion`);+ const truncated = trimmed.length > 4096 ? `${trimmed.slice(0, 4096)}\n…[truncated]` : trimmed;+ for (const line of truncated.split('\n')) appendLine(line);+ };+const finish = async ({ success, exitCode = 0, error = null, reason = 'completed' }) => {if (finalized) return;finalized = true;@@ -348,6 +379,15 @@ export async function spawnTuiAgent({// termination) the timer never gets a chance to run.postPasteBuffer = null;+ // Ingest the .agent-done sentinel BEFORE draining, so its markdown summary+ // lands in outputBuffer/output.txt regardless of WHICH path finalized the+ // agent. The completion workflow writes the sentinel and then runs /quit —+ // the process exits within milliseconds, so handleExit almost always wins+ // the race against the 2s doneSentinelTimer poll. Reading it here (not just+ // in the poll) is what makes the resolution show up in the completed-agent+ // details view. Idempotent via `sentinelIngested`.+ await ingestDoneSentinel();+// Drain pending parsed lines AND raw chunks before the final state// writes so completion events don't beat the last output batch to disk.if (flushing) await flushing.catch(() => {});@@ -622,40 +662,23 @@ export async function spawnTuiAgent({}, 5000);// Sentinel-file watcher. The agent's prompt instructs it to write- // .agent-done in the workspace after running /simplify + /do:pr; the file- // contains a markdown task summary that we ingest line-by-line into the- // agent's outputBuffer so downstream code (extractFinalSummary,- // persistSimplifySummaries, completion hooks, the agent card) gets the- // same `outputBuffer.tail = summary` shape it used to get from headless- // CLI runs. Idle-complete is just the fallback for an agent that didn't- // comply.- const doneSentinelPath = workspacePath ? join(workspacePath, DONE_SENTINEL_NAME) : null;+ // .agent-done in the workspace after running /simplify + /do:pr. This poll+ // exists only to finalize PROMPTLY when the agent signals done WITHOUT+ // exiting its TUI (e.g. it forgot /quit, or stays alive) — otherwise we'd+ // wait out the much longer idle timeout. The actual sentinel READ happens in+ // finish() (via ingestDoneSentinel) so the resolution is captured no matter+ // which path finalizes: the far more common case is the agent writing the+ // sentinel and then running /quit, whose process exit fires finish() long+ // before this 2s poll ticks. Idle-complete is the fallback for a+ // non-complying agent.const doneSentinelTimer = doneSentinelPath ? setInterval(() => {try {if (finalized) return;if (!existsSync(doneSentinelPath)) return;clearInterval(doneSentinelTimer);- readFile(doneSentinelPath, 'utf8')- .then(contents => {- const trimmed = contents.trim();- if (!trimmed) return;- appendLine(`✅ Agent signaled completion`);- // Cap at 4 KB so a runaway agent that pasted the entire diff into- // the sentinel doesn't blow up the agent record / downstream- // memory-extraction prompts.- const truncated = trimmed.length > 4096 ? `${trimmed.slice(0, 4096)}\n…[truncated]` : trimmed;- for (const line of truncated.split('\n')) appendLine(line);- })- .catch(err => console.error(`❌ doneSentinelTimer readFile failed: ${err.message}`))- .finally(() => {- try {- finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId} after sentinel: ${err.message}`, { agentId });- });- } catch (err) {- console.error(`❌ doneSentinelTimer finish call failed: ${err.message}`);- }- });+ finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' }).catch(err => {+ emitLog('error', `Failed to finalize TUI agent ${agentId} after sentinel: ${err.message}`, { agentId });+ });} catch (err) {console.error(`❌ doneSentinelTimer interval callback failed: ${err.message}`);}diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 23bc781b93..5c506a1fcc 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -68,6 +68,12 @@ vi.mock('./agentState.js', () => ({userTerminatedAgents: new Set()}));+vi.mock('fs', () => ({+ // Default: no .agent-done sentinel on disk. The completion-sentinel test+ // overrides this to true. Re-set in beforeEach so it can't leak between tests.+ existsSync: vi.fn().mockReturnValue(false),+}));+vi.mock('fs/promises', () => ({writeFile: vi.fn().mockResolvedValue(undefined),appendFile: vi.fn().mockResolvedValue(undefined),@@ -115,6 +121,8 @@ vi.mock('../lib/tuiHandshake.js', async (importOriginal) => {};});+import { existsSync } from 'fs';+import { readFile } from 'fs/promises';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';import * as shellService from './shell.js';import * as agentLifecycle from './agentLifecycle.js';@@ -294,6 +302,12 @@ describe('spawnTuiAgent runtime', () => {vi.mocked(shellService.getSessionProcess).mockReturnValue(null);vi.mocked(shellService.getSession).mockReturnValue({ id: SESSION_ID });++ // Reset sentinel state: no .agent-done on disk, empty read. The+ // completion-sentinel test overrides both. clearAllMocks keeps the factory+ // implementation, so re-set explicitly to prevent cross-test leakage.+ vi.mocked(existsSync).mockReturnValue(false);+ vi.mocked(readFile).mockResolvedValue('');});afterEach(() => {@@ -625,4 +639,49 @@ describe('spawnTuiAgent runtime', () => {);expect(openCalls).toHaveLength(0);});++ // ── 10. Completion-sentinel ingestion on the shell-exit (/quit) race ─────────+ // The completion workflow has the agent write `.agent-done` and then run+ // `/quit`, which exits the TUI process within milliseconds — long before the+ // 2s doneSentinelTimer poll fires. The shell-exit path therefore wins the+ // race and finalizes the agent. finish() MUST still ingest the sentinel so+ // its markdown resolution lands in outputBuffer / output.txt and shows up in+ // the completed-agent details view. Regression guard for the lost-resolution+ // bug where the summary only got ingested by the (slower) poll path.+ it('shell-exit after sentinel write: ingests .agent-done summary into the persisted output (process /quit beats the 2s poll)', async () => {+ const { appendFile } = await import('fs/promises');+ const sentinel = '## Summary\nImplemented the fix.\n\n## PR\nhttps://example.com/pr/42';+ vi.mocked(existsSync).mockReturnValue(true);+ vi.mocked(readFile).mockImplementation(async (p) =>+ typeof p === 'string' && p.endsWith('.agent-done') ? sentinel : ''+ );++ const spawnPromise = runSpawn({ workspacePath: '/tmp/ws' });+ await flushMicrotasks();++ // Simulate the TUI process exiting cleanly from /quit — NOT the poll.+ await capturedOnExit({ exitCode: 0, killed: false });+ await flushMicrotasks();++ await spawnPromise;++ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);++ // The completed-agent details view reads output.txt (getAgent) and the+ // in-state output stream (live view / fallback). Both must carry the+ // sentinel resolution — assert on the persistence paths, not outputBuffer,+ // since the test mocks OUTPUT_BUFFER_CAP down to 1 byte.+ const flushedLines = vi.mocked(cosAgents.appendAgentOutputLines).mock.calls+ .flatMap(([, lines]) => lines);+ expect(flushedLines).toContain('✅ Agent signaled completion');+ expect(flushedLines.some(l => l.includes('Implemented the fix.'))).toBe(true);+ expect(flushedLines.some(l => l.includes('https://example.com/pr/42'))).toBe(true);++ const outputTxtWrites = vi.mocked(appendFile).mock.calls+ .filter(([p]) => typeof p === 'string' && p.endsWith('output.txt'))+ .map(([, data]) => String(data))+ .join('');+ expect(outputTxtWrites).toContain('Implemented the fix.');+ expect(outputTxtWrites).toContain('https://example.com/pr/42');+ });});