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: wait for OpenCode composer and skip startup update offers
[._.]/ Adam Eivy5cdfc2c815f6
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex 8c907e0423..6268c77524 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -30,11 +30,11 @@ export const PASTE_DEADLINE_MS = 10000;// Give Claude Code time to switch into /low-priority mode before retrying a// prompt rejected by its session limit. Shared by both TUI execution paths.export const CLAUDE_LOW_PRIORITY_RESUBMIT_DELAY_MS = 1500;-// How long to wait for claude's POSITIVE input-ready footer (createInputReadyTracker)+// How long to wait for a positive input-ready signal (createInputReadyTracker)// before giving up and surfacing a startup failure. Generous because a cold// claude start can spend many seconds on banner + MCP-server + model init// (well within the normal startup budget). Used only on the input-ready-gated-// path; the non-claude providers use PASTE_DEADLINE_MS.+// path (Claude, Antigravity, OpenCode); other providers use PASTE_DEADLINE_MS.export const TUI_INPUT_READY_DEADLINE_MS = 45000;// Claude Code emits `[Pasted text #N +M lines]`, Codex emits@@ -458,6 +458,13 @@ export const TUI_HOOK_REVIEW_PROMPT_PATTERN = /hooksneedreview/i;// it, same as claude's.)export const AGY_INPUT_READY_PATTERN = /\?forshortcuts/i;+// OpenCode emits terminal-capability queries and enables paste mode before its+// composer exists. Silence after those bytes is not input readiness.+export const OPENCODE_INPUT_READY_PATTERN = /askanything/i;+// The update offer overlays the composer and defaults to Confirm. Escape+// closes it without installing software or changing the operator's settings.+const OPENCODE_UPDATE_PROMPT_PATTERN = /updateavailable.*anewreleasev[\d.]+isavailable\.wouldyouliketoupdatenow\?/i;+// Handshake markers are matched against a rolling window of whitespace-stripped// output rather than a single chunk, so a marker split across two PTY reads// (`? for short` | `cuts`) still matches. Sized to a few screens of chrome.@@ -520,6 +527,8 @@ export function createInputReadyTracker({ readyTextPattern = null, launchShape =// from re-arming the dialog and blocking delivery forever.let needsHookReview = false;let hookReviewAnswered = false;+ let needsOpencodeUpdate = false;+ let opencodeUpdateAnswered = false;let tail = '';// node-pty can split `ESC[?2004h` across reads. Keep only the trailing// prefix of that exact toggle so the next chunk can complete it without@@ -538,7 +547,7 @@ export function createInputReadyTracker({ readyTextPattern = null, launchShape =// spawner has answered it.get ready() {return sawCommandRun && pasteModeOn && !needsTrust && !needsAutoModeChoice- && !needsExternalImportsChoice && !needsHookReview+ && !needsExternalImportsChoice && !needsHookReview && !needsOpencodeUpdate&& (!readyTextPattern || sawReadyText);},get needsTrust() { return needsTrust; },@@ -547,6 +556,7 @@ export function createInputReadyTracker({ readyTextPattern = null, launchShape =get needsAutoModeChoice() { return needsAutoModeChoice; },get needsExternalImportsChoice() { return needsExternalImportsChoice; },get needsHookReview() { return needsHookReview; },+ get needsOpencodeUpdate() { return needsOpencodeUpdate; },/** Spawner selected the affirmative trust choice. */ackTrustChoice() { needsTrust = false; trustAnswered = true; },/** Spawner reports the dismissal keystrokes went out; re-arms `ready`. */@@ -555,6 +565,7 @@ export function createInputReadyTracker({ readyTextPattern = null, launchShape =ackExternalImportsChoice() { needsExternalImportsChoice = false; externalImportsAnswered = true; },/** Spawner selected Codex's safe "Continue without trusting" option. */ackHookReview() { needsHookReview = false; hookReviewAnswered = true; },+ ackOpencodeUpdate() { needsOpencodeUpdate = false; opencodeUpdateAnswered = true; },// rawText: un-stripped chunk (paste-mode toggles live here);// strippedText: ANSI-stripped chunk (the trust-gate / composer text).observe(rawText, strippedText) {@@ -600,6 +611,7 @@ export function createInputReadyTracker({ readyTextPattern = null, launchShape =needsExternalImportsChoice = true;}if (!needsHookReview && !hookReviewAnswered && TUI_HOOK_REVIEW_PROMPT_PATTERN.test(tail)) needsHookReview = true;+ if (!needsOpencodeUpdate && !opencodeUpdateAnswered && OPENCODE_UPDATE_PROMPT_PATTERN.test(tail)) needsOpencodeUpdate = true;if (readyTextPattern && !sawReadyText && readyTextPattern.test(tail)) sawReadyText = true;}},@@ -630,6 +642,15 @@ export function createInputReadyTracker({ readyTextPattern = null, launchShape =// to highlight (which can be "No, exit", or rewriting the user's global// permission default).const STARTUP_DIALOGS = [+ {+ id: 'opencode-update',+ stage: 'before-composer',+ answered: 'opencodeUpdateSkipped',+ asks: (inputReady) => inputReady.needsOpencodeUpdate,+ keys: () => '\x1b',+ ack: (inputReady) => inputReady.ackOpencodeUpdate(),+ describe: (command) => `Skipped ${command} startup update offer`,+ },// Claude can discover PortOS's parent AGENTS.md (via CLAUDE.md) from a// managed-app worktree nested under data/cos/worktrees, then ask whether to// allow that file's external AGENTS.md import. Decline it: the parentdiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 21a351e6a2..2410ef955b 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -1213,7 +1213,7 @@ describe('spawnTuiAgent runtime', () => {tuiConfig: { ...defaultTuiConfig, command: 'opencode', spawnCommand: 'opencode', commandLine: 'opencode' },});await flushMicrotasks();- await capturedOnData(Buffer.from('OpenCode booting...\n'));+ await capturedOnData(Buffer.from('\x1b[?2004l\x1b[?2004hAsk anything…\n'));await flushMicrotasks();await vi.advanceTimersByTimeAsync(2000);await flushMicrotasks();@@ -1493,6 +1493,42 @@ describe('spawnTuiAgent runtime', () => {expect(pasteCount()).toBe(1);});+ it('waits through OpenCode terminal negotiation and skips its update modal before submitting once', async () => {+ const spawnPromise = runSpawn({+ provider: { ...defaultProvider, id: 'opencode-tui', name: 'OpenCode TUI' },+ tuiConfig: { ...defaultTuiConfig, command: '/opt/bin/opencode', spawnCommand: 'opencode', commandLine: 'opencode' },+ });+ await flushMicrotasks();+ // A quiet terminal-capability query used to trigger the idle paste, then+ // exhaust every retry before the composer and update offer even appeared.+ await capturedOnData(Buffer.from('\x1bP+q4d73\x1b\\'));+ await vi.advanceTimersByTimeAsync(15000);+ expect(pasteCount()).toBe(0);+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();++ await capturedOnData(Buffer.from('\x1b[?2004l\x1b[?2004hAsk anything…\n'));+ await vi.advanceTimersByTimeAsync(600);+ expect(pasteCount()).toBe(0);+ await capturedOnData(Buffer.from('Update\x1b[8;29H Available esc\nA new release v9.9.9 is avail'));+ await capturedOnData(Buffer.from('able. Would you like to update now?\nSkip Confirm\n'));+ await vi.advanceTimersByTimeAsync(400);+ expect(vi.mocked(shellService.writeToSession).mock.calls.map(([, data]) => data)).toEqual(['\x1b']);+ expect(pasteCount()).toBe(0);+ // Even beyond the old blind-paste deadline, require fresh output after Esc.+ await vi.advanceTimersByTimeAsync(2000);+ expect(pasteCount()).toBe(0);+ await capturedOnData(Buffer.from('Ask anything…\n'));+ await vi.advanceTimersByTimeAsync(1500);+ expect(pasteCount()).toBe(1);+ await capturedOnData(Buffer.from('[Pasted ~42 lines]'));+ await vi.advanceTimersByTimeAsync(8000);+ expect(vi.mocked(shellService.writeToSession).mock.calls.map(([, data]) => data)).toContain('\r');+ expect(pasteCount()).toBe(1);+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();+ await capturedOnExit({ exitCode: 0, killed: false });+ await spawnPromise;+ });+it('codex hook-review offer: continues without trusting hooks before pasting the prompt', async () => {runSpawn();await flushMicrotasks();diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.jsindex 28bf645788..4d09a75b79 100644--- a/server/services/agentTuiSpawning/sessionController.js+++ b/server/services/agentTuiSpawning/sessionController.js@@ -40,7 +40,7 @@ import { createStreamingAnsiStripper, stripAnsi } from '../../lib/ansiStrip.js';import { createContentRefusalDetector, createClaudeSessionLimitBannerDetector, createImmediateFallbackSignalDetector, createLocalRuntimeOomDetector, createTruncatedResponseDetector, createModelAtCapacityDetector } from '../../lib/aiToolkit/errorDetection.js';import { isAntigravityCommand } from '../../lib/antigravity.js';import { isCodexCommand } from '../../lib/codex.js';-import { isClaudeCommand } from '../../lib/providerModels.js';+import { isClaudeCommand, isOpencodeCommand } from '../../lib/providerModels.js';import { createCodexModelRejectionGate } from './codexModelRejection.js';import {READY_POLL_INTERVAL_MS,@@ -75,6 +75,7 @@ import {createStartupDialogAnswers,answerStartupDialogs,AGY_INPUT_READY_PATTERN,+ OPENCODE_INPUT_READY_PATTERN,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,PASTE_COMMIT_PATIENCE_MS,@@ -651,6 +652,7 @@ export function createTuiSessionController({// not `spawnCommand` — a credential-bootstrap wrap makes the latter the// bootstrap CLI.const isCodexSession = isCodexCommand(tuiConfig.command);+ const isOpencodeSession = isOpencodeCommand(tuiConfig.command);const codexModelRejectionGate = isCodexSession ? createCodexModelRejectionGate() : null;// Latches once codex's composer placeholder paints — the positive "the input// box exists" signal the idle heuristic lacks. See@@ -662,9 +664,12 @@ export function createTuiSessionController({// paste into a startup banner, a trust menu, or a returned shell prompt.// agy enables bracketed paste on alt-screen entry, before its composer (and// before its trust gate) exists, so it needs the extra composer-footer gate.+ // OpenCode also enables paste mode before the composer. Require its+ // placeholder and a settled repaint so terminal queries cannot trigger paste.// Runner/direct shapes pty.spawn the TUI itself (no launch shell), so the// tracker must not wait for a shell paste-mode OFF that will never come.const inputReady = createInputReadyTracker({+ ...(isOpencodeSession ? { readyTextPattern: OPENCODE_INPUT_READY_PATTERN } : {}),...(isAntigravityCommand(tuiConfig.command) ? { readyTextPattern: AGY_INPUT_READY_PATTERN } : {}),launchShape,});@@ -1692,7 +1697,7 @@ export function createTuiSessionController({// via TUI_TRUST_PROMPT_PATTERN. If agy ever fails to signal ready, the// requireInputReady path fails fast with a surfaced startup error instead of// silently failing at startup.- const requireInputReady = isClaudeCommand(tuiConfig.command) || isAntigravityCommand(tuiConfig.command);+ const requireInputReady = isClaudeCommand(tuiConfig.command) || isAntigravityCommand(tuiConfig.command) || isOpencodeSession;// 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())@@ -1716,7 +1721,7 @@ export function createTuiSessionController({// Answer whatever startup dialog the TUI is showing — one per tick, in the// order answerStartupDialogs declares (external imports, hook review,- // folder trust). These run for EVERY provider, not only the positive+ // folder trust, OpenCode updates). These run for EVERY provider, not only the positive// input-ready ones below, because codex takes the idle/deadline paste path// and a dialog is at its quietest right after it paints.//@@ -1776,7 +1781,8 @@ export function createTuiSessionController({appendLine(LIFECYCLE_LINES.startupDialogAnswered({ message: answeredAtComposer.message, session: sessionLabel }));return;}- if (inputReady.ready && elapsed >= tuiConfig.promptDelayMs) {+ if (inputReady.ready && elapsed >= tuiConfig.promptDelayMs+ && (!isOpencodeSession || (firstOutputAt !== null && now - lastOutputAt >= READY_IDLE_THRESHOLD_MS))) {safeSendPrompt('input-ready');clearInterval(promptTimer);promptTimer = null;diff --git a/server/services/tuiPromptRunner.js b/server/services/tuiPromptRunner.jsindex 4bb547f8fd..31b3c14095 100644--- a/server/services/tuiPromptRunner.js+++ b/server/services/tuiPromptRunner.js@@ -73,6 +73,7 @@ import {CLAUDE_LOW_PRIORITY_RESUBMIT_DELAY_MS,buildTuiInvocation,createInputReadyTracker,+ OPENCODE_INPUT_READY_PATTERN,detectMissingTuiBinary,createSelfClearingSignalGate,screenShowsInFlightChrome,@@ -80,7 +81,7 @@ import {} from '../lib/tuiHandshake.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { isCodexCommand } from '../lib/codex.js';-import { isClaudeCommand } from '../lib/providerModels.js';+import { isClaudeCommand, isOpencodeCommand } from '../lib/providerModels.js';import { applyCredentialBootstrap, needsProcessGroup, processGroupKillable } from '../lib/credentialBootstrap.js';import { killProcessTree } from '../lib/bufferedSpawn.js';@@ -440,10 +441,14 @@ ${prompt}`;const streamingStrip = createStreamingAnsiStripper();// This PTY spawns the TUI directly, so the TUI's first paste-mode ON is the- // positive ready signal. Claude gets that positive gate; other providers- // retain their existing idle/deadline behavior.- const inputReady = createInputReadyTracker({ launchShape: 'direct' });- const requiresInputReady = isClaudeCommand(command);+ // positive ready signal for Claude. OpenCode also requires its composer+ // placeholder and a settled repaint; terminal queries alone are not ready.+ const isOpencodeSession = isOpencodeCommand(command);+ const inputReady = createInputReadyTracker({+ launchShape: 'direct',+ ...(isOpencodeSession ? { readyTextPattern: OPENCODE_INPUT_READY_PATTERN } : {}),+ });+ const requiresInputReady = isClaudeCommand(command) || isOpencodeSession;// Keep local one-shot flags alongside the tracker's terminal acknowledgements// so a failed/delayed PTY write cannot cause repeated selector navigation.let trustAccepted = false;@@ -1027,6 +1032,13 @@ ${prompt}`;// keystroke makes delivery wait for what the dismissal reveals;// PASTE_DEADLINE_MS still backstops a dismissal the TUI ignores entirely.+ if (isOpencodeSession && inputReady.needsOpencodeUpdate) {+ if (dismissStartupDialog('\x1b', 'OpenCode update offer')) inputReady.ackOpencodeUpdate();+ lastOutputAt = now;+ firstOutputAt = null;+ return;+ }+// A managed-app worktree nested below PortOS can make Claude discover the// parent PortOS CLAUDE.md and offer to import its external AGENTS.md.// Decline option 1 rather than crossing that repository boundary. The@@ -1095,7 +1107,8 @@ ${prompt}`;}return;}- if (inputReady.ready && elapsed >= promptDelayMs) {+ if (inputReady.ready && elapsed >= promptDelayMs+ && (!isOpencodeSession || (firstOutputAt !== null && now - lastOutputAt >= READY_IDLE_THRESHOLD_MS))) {sendPrompt('input-ready');return;}diff --git a/server/services/tuiPromptRunner.test.js b/server/services/tuiPromptRunner.test.jsindex 22e9eacfb2..7b84c2fbe0 100644--- a/server/services/tuiPromptRunner.test.js+++ b/server/services/tuiPromptRunner.test.js@@ -837,7 +837,7 @@ describe('executeTuiRun', () => {vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],});- const provider = { id: 'opencode', type: 'tui', command: 'opencode', tuiPromptDelayMs: 50 };+ const provider = { id: 'grok', type: 'tui', command: 'grok', tuiPromptDelayMs: 50 };const promise = executeTuiRun({runId: 'run-non-claude-trust-text', provider, prompt: 'return one structured response',workspacePath: TEST_WORKSPACE, timeout: 60000,@@ -853,7 +853,7 @@ describe('executeTuiRun', () => {// from it — delivery still happens, via the blind PASTE_DEADLINE_MS// fallback that governs non-input-ready providers.expect(pty.write).not.toHaveBeenCalledWith(expect.stringContaining('\x1b[200~'));- pty.emitData('opencode ready\n');+ pty.emitData('grok ready\n');await vi.advanceTimersByTimeAsync(2000);expect(pty.write).toHaveBeenCalledWith(expect.stringContaining('\x1b[200~'));@@ -861,6 +861,34 @@ describe('executeTuiRun', () => {await promise;});+ it('waits for the OpenCode composer and dismisses its update offer without confirming it', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] });+ const provider = { id: 'opencode', type: 'tui', command: 'opencode', tuiPromptDelayMs: 50 };+ const promise = executeTuiRun({+ runId: 'run-opencode-update', provider, prompt: 'return one structured response',+ workspacePath: TEST_WORKSPACE, timeout: 60000,+ });+ await flushAsync();+ const pty = ptyInstances[0];+ pty.emitData('\x1bP+q4d73\x1b\\');+ await vi.advanceTimersByTimeAsync(15000);+ expect(pty.write).not.toHaveBeenCalled();+ pty.emitData('\x1b[?2004hAsk anything…\nUpdate Available esc\n'+ + 'A new release v9.9.9 is available. Would you like to update now?\nSkip Confirm\n');+ await vi.advanceTimersByTimeAsync(400);+ expect(pty.write.mock.calls.map(([data]) => data)).toEqual(['\x1b']);+ await vi.advanceTimersByTimeAsync(2000);+ expect(pty.write).toHaveBeenCalledTimes(1);+ pty.emitData('Ask anything…\n');+ await vi.advanceTimersByTimeAsync(1500);+ expect(pty.write).toHaveBeenCalledWith(expect.stringContaining('\x1b[200~'));+ pty.emitData('[Pasted ~42 lines]');+ await vi.advanceTimersByTimeAsync(1000);+ expect(pty.write).toHaveBeenCalledWith('\r');+ pty.emitExit({ exitCode: 0 });+ await promise;+ });+it('fails Claude startup after its input-readiness deadline instead of blind-pasting', async () => {vi.useFakeTimers({toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'],