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
move the four TUI startup-dialog arms into one answerStartupDialogs table (#6872)
[._.]/ Adam Eivy2e9f8338ac8e
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex 4874843b30..d3fb4c80af 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -495,6 +495,135 @@ export function createInputReadyTracker({ readyTextPattern = null, directLaunch}+// ─── Startup-dialog answers ───────────────────────────────────────────────++// One row per modal a TUI can paint before (or just after) its composer+// exists, in the exact order the spawner's poll must try them. Adding a+// provider's next dialog is a row here plus the `needs…`/`ack…` pair on+// createInputReadyTracker — not another boolean in the spawner's closure and+// another arm hundreds of lines away from it.+//+// `stage` says WHEN the dialog paints, which is also which providers see it:+// 'before-composer' — runs for every TUI. Codex takes the idle/deadline+// paste path and these dialogs go quiet the instant they paint, so the+// idle heuristic reads that silence as "ready" and pastes the task into+// the menu, which swallows it and all three paste retries (2026-08-21,+// `paste-not-rendered`). Answering first is what lets the composer appear.+// 'after-composer' — claude's auto-mode offer paints once the composer is+// already live, so it only concerns the positive-input-ready providers.+//+// `keys` is the answer written to the PTY. `\x1b[B` is arrow-down, so+// `'\x1b[B\r'` picks option 2 and `'\x1b[B\x1b[B\r'` option 3; a bare Enter is+// deliberately never sent, because it would accept whatever the TUI happened+// to highlight (which can be "No, exit", or rewriting the user's global+// permission default).+const STARTUP_DIALOGS = [+ // 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 parent+ // repository's instructions must not leak into the target app, and option 2+ // leaves the target's own instruction files intact.+ {+ id: 'external-imports',+ stage: 'before-composer',+ answered: 'externalImportsDeclined',+ asks: (inputReady) => inputReady.needsExternalImportsChoice,+ keys: () => '\x1b[B\r',+ ack: (inputReady) => inputReady.ackExternalImportsChoice(),+ describe: (command) => `Declined ${command} external instruction imports`,+ },+ // Codex can present a hook-review selector before its composer exists. Do+ // not trust hooks from an unattended run: option 3 keeps them disabled for+ // this session and lets the agent continue without executing code outside+ // its sandbox.+ {+ id: 'hook-review',+ stage: 'before-composer',+ answered: 'hookReviewDeclined',+ asks: (inputReady) => inputReady.needsHookReview,+ keys: () => '\x1b[B\x1b[B\r',+ ack: (inputReady) => inputReady.ackHookReview(),+ describe: (command) => `Continued ${command} without trusting startup hooks`,+ },+ // Auto-confirm the first-run "trust this folder?" gate so agents can run in+ // fresh worktrees. Waits for the choices themselves to paint: Claude Code+ // releases disagree about their ordering and newer builds can highlight+ // "No, exit" by default, so `trustSelectionKey` — derived from the painted+ // options — is what moves to the affirmative one before submitting.+ {+ id: 'folder-trust',+ stage: 'before-composer',+ answered: 'trustAccepted',+ asks: (inputReady) => inputReady.needsTrust && inputReady.trustChoiceReady,+ keys: (inputReady) => `${inputReady.trustSelectionKey}${SUBMIT_KEY}`,+ ack: (inputReady) => inputReady.ackTrustChoice(),+ describe: (command) => `Auto-confirmed ${command} folder-trust prompt`,+ },+ // Decline claude's "make auto mode your default permission mode?" offer+ // (v2.1.233+). Unlike the trust gate this one paints AFTER the composer is+ // live, so it swallows the paste and every retry unless it is cleared first+ // — see TUI_AUTO_MODE_PROMPT_PATTERN. Arrow-down + Enter rather than the+ // digit `2`: it lands on "No, keep don't ask" under both of Ink's selection+ // models (digit-immediate-select and navigate-then-confirm).+ {+ id: 'auto-mode',+ stage: 'after-composer',+ answered: 'autoModeDeclined',+ asks: (inputReady) => inputReady.needsAutoModeChoice,+ keys: () => '\x1b[B\r',+ ack: (inputReady) => inputReady.ackAutoModeChoice(),+ describe: (command) => `Declined ${command} auto-mode default offer`,+ },+];++/**+ * A fresh "which startup dialogs has this session already answered?" record —+ * one value per STARTUP_DIALOGS row, so a new row needs no caller edit.+ *+ * The tracker's own `needs…` getters go false on ack, so they already stop a+ * second answer on their own. These latches are the second guard the spawner+ * carried as four sibling booleans, kept rather than reasoned away in a change+ * whose contract is that nothing behaves differently.+ */+export const createStartupDialogAnswers = () =>+ Object.fromEntries(STARTUP_DIALOGS.map((dialog) => [dialog.answered, false]));++/**+ * Answer at most ONE unanswered startup dialog for `stage`, in table order.+ *+ * One per call on purpose: answering changes what the TUI is showing, so the+ * caller returns to its poll and re-reads the tracker before trying the next.+ * The stage split is also what preserves the caller's original ordering — the+ * "trust heading painted but its choices are unrecognized" failure check sits+ * between the two stages and must keep winning over the after-composer arm.+ *+ * Mutates `answers` in place: the record is the session's, not this call's.+ *+ * @param {object} args+ * @param {object} args.inputReady - createInputReadyTracker instance.+ * @param {object} args.answers - createStartupDialogAnswers() record.+ * @param {'before-composer'|'after-composer'} args.stage+ * @param {string} args.command - TUI command name, for the transcript line.+ * @param {(keys: string) => void} args.write - writes the answer to the PTY.+ * @returns {{ id: string, message: string } | null} the dialog answered and+ * the transcript phrase for it, or null when there was nothing to answer.+ * The caller owns the log line and the idle-clock rewind, which differ by+ * stage.+ */+export function answerStartupDialogs({ inputReady, answers, stage, command, write }) {+ for (const dialog of STARTUP_DIALOGS) {+ if (dialog.stage !== stage) continue;+ if (answers[dialog.answered]) continue;+ if (!dialog.asks(inputReady)) continue;+ answers[dialog.answered] = true;+ write(dialog.keys(inputReady));+ dialog.ack(inputReady);+ return { id: dialog.id, message: dialog.describe(command) };+ }+ return null;+}++// Claude Code and Codex render a bulleted elapsed counter while a model request// is in flight; agy uses its own `Generating…` indicator.export const WORK_COUNTER_PATTERN = /\(\s*(\d+)\s*s\s*[·•]/g;diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex c2badd4be9..58846a6d4d 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -43,6 +43,9 @@ import {isPasteConfirmed,isCollapsedPasteChip,createInputReadyTracker,+ createStartupDialogAnswers,+ answerStartupDialogs,+ SUBMIT_KEY,AGY_INPUT_READY_PATTERN,createRetryStallGate,RETRY_STALL_MS,@@ -1856,3 +1859,125 @@ describe('createOomNudgeGate', () => {expect(gate.takeNudge(OOM_NUDGE_SETTLE_MS + 1, 0)).toBe(0);});});++// The four modals a TUI can paint before its prompt can be delivered used to+// be four booleans in spawnTuiAgent's closure plus four inline arms in its+// 300ms poll. They are one table here now, so these pin the contract the+// spawner depends on: table order, one answer per call, the stage split that+// keeps the "trust choices unrecognized" failure between the two groups, and+// the per-session record that stops a second answer.+describe('answerStartupDialogs', () => {+ const PASTE_OFF = '\x1b[?2004l';+ const PASTE_ON = '\x1b[?2004h';++ const EXTERNAL_IMPORTS_OFFER = "This project's CLAUDE" + '.md imports files outside the current working directory.\n'+ + '1. Yes, allow external imports\n2. No, disable external imports\n';+ const HOOK_REVIEW_OFFER = 'Hooks need review\n1. Review hooks\n'+ + "3. Continue without trusting (hooks won't run)\n";+ const TRUST_GATE = 'Is this a project you trust?\n❯ 1. Yes, I trust this folder\n2. No, exit\n';+ const AUTO_MODE_OFFER = 'Make auto mode your default permission mode?\n'+ + ' ❯ 1. Yes, set auto mode as my default permission mode\n'+ + " 2. No, keep don't ask\n";++ // A live tracker, so each row's `asks`/`keys`/`ack` is checked against the+ // real createInputReadyTracker API rather than a stub that could drift.+ const composerLive = (...chunks) => {+ const tracker = createInputReadyTracker();+ tracker.observe(`${PASTE_OFF}${PASTE_ON}`, '');+ for (const chunk of chunks) tracker.observe('', chunk);+ return tracker;+ };++ const answerOnce = (inputReady, answers, stage = 'before-composer') => {+ const written = [];+ const result = answerStartupDialogs({+ inputReady, answers, stage, command: 'claude', write: (keys) => written.push(keys),+ });+ return { result, written };+ };++ it('starts with every dialog unanswered and answers nothing when none is showing', () => {+ const answers = createStartupDialogAnswers();+ expect(Object.values(answers).every((v) => v === false)).toBe(true);++ const tracker = composerLive('Try "fix lint errors"');+ expect(answerOnce(tracker, answers).result).toBeNull();+ expect(answerOnce(tracker, answers, 'after-composer').result).toBeNull();+ });++ it('answers one before-composer dialog per call, in table order, and acks the tracker each time', () => {+ // All three up at once: order is what stops a later arm from answering a+ // modal that is not the one currently owning the terminal's input.+ const tracker = composerLive(EXTERNAL_IMPORTS_OFFER, HOOK_REVIEW_OFFER, TRUST_GATE);+ const answers = createStartupDialogAnswers();++ const first = answerOnce(tracker, answers);+ expect(first.result).toEqual({ id: 'external-imports', message: 'Declined claude external instruction imports' });+ expect(first.written).toEqual(['\x1b[B\r']); // arrow-down to option 2, never a bare Enter+ expect(tracker.needsExternalImportsChoice).toBe(false);++ const second = answerOnce(tracker, answers);+ expect(second.result).toEqual({ id: 'hook-review', message: 'Continued claude without trusting startup hooks' });+ expect(second.written).toEqual(['\x1b[B\x1b[B\r']); // option 3+ expect(tracker.needsHookReview).toBe(false);++ const third = answerOnce(tracker, answers);+ expect(third.result).toEqual({ id: 'folder-trust', message: 'Auto-confirmed claude folder-trust prompt' });+ expect(third.written).toEqual([`${tracker.trustSelectionKey}${SUBMIT_KEY}`]);+ expect(tracker.needsTrust).toBe(false);++ // Every dialog cleared, so the composer is finally reachable.+ expect(answerOnce(tracker, answers).result).toBeNull();+ expect(tracker.ready).toBe(true);+ });++ it('leaves the folder-trust gate alone until its choices have painted', () => {+ // The heading matched but no recognizable option did, so trustSelectionKey+ // has nothing to derive from. Answering here would submit whatever the TUI+ // highlighted — which can be "No, exit". The spawner's own deadline check+ // owns this state, and it only runs because nothing was answered.+ const tracker = composerLive('Is this a project you trust?\n');+ expect(tracker.needsTrust).toBe(true);+ expect(tracker.trustChoiceReady).toBe(false);++ const answers = createStartupDialogAnswers();+ expect(answerOnce(tracker, answers).result).toBeNull();+ expect(answers.trustAccepted).toBe(false);++ tracker.observe('', '❯ 1. Yes, I trust this folder\n2. No, exit\n');+ expect(answerOnce(tracker, answers).result?.id).toBe('folder-trust');+ });++ it('keeps the two stages disjoint so neither can answer the other\'s dialog', () => {+ // The stage split is load-bearing: the spawner runs before-composer for+ // every provider, then its trust-choice-unrecognized failure check, and+ // only then after-composer — for the positive input-ready providers.+ const trustUp = composerLive(TRUST_GATE);+ expect(answerOnce(trustUp, createStartupDialogAnswers(), 'after-composer').result).toBeNull();+ expect(trustUp.needsTrust).toBe(true);++ const autoModeUp = composerLive(AUTO_MODE_OFFER);+ expect(answerOnce(autoModeUp, createStartupDialogAnswers()).result).toBeNull();+ expect(autoModeUp.needsAutoModeChoice).toBe(true);++ const answered = answerOnce(autoModeUp, createStartupDialogAnswers(), 'after-composer');+ expect(answered.result).toEqual({ id: 'auto-mode', message: 'Declined claude auto-mode default offer' });+ expect(answered.written).toEqual(['\x1b[B\r']);+ expect(autoModeUp.ready).toBe(true);+ });++ it('answers each dialog at most once per session, even if the question comes back', () => {+ // The record is the guard the tracker cannot be: a TUI that re-asks (or a+ // tracker that re-arms from its rolling tail) must not start a keystroke+ // loop that outlives the paste deadline.+ const reAsking = { needsHookReview: true, ackHookReview: () => {} };+ const answers = createStartupDialogAnswers();++ expect(answerOnce(reAsking, answers).result?.id).toBe('hook-review');+ expect(answers.hookReviewDeclined).toBe(true);++ const second = answerOnce(reAsking, answers);+ expect(second.result).toBeNull();+ expect(second.written).toEqual([]);+ });+});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 054b434df2..efc42d40f3 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -55,6 +55,8 @@ import {MCP_BOOT_PASTE_DEADLINE_MS,MCP_BOOT_PASTE_RETRY_DELAY_MS,createInputReadyTracker,+ createStartupDialogAnswers,+ answerStartupDialogs,AGY_INPUT_READY_PATTERN,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,@@ -830,10 +832,11 @@ export async function spawnTuiAgent({...(isAntigravityCommand(tuiConfig.command) ? { readyTextPattern: AGY_INPUT_READY_PATTERN } : {}),directLaunch,});- let trustAccepted = false;- let autoModeDeclined = false;- let externalImportsDeclined = false;- let hookReviewDeclined = false;+ // Which of the TUI's startup dialogs this session has already answered. One+ // record instead of four sibling booleans declared ~1,000 lines above the+ // arms that set them; the arms themselves live in answerStartupDialogs, so a+ // provider's next dialog is a row there rather than a fifth flag here.+ const dialogAnswers = createStartupDialogAnswers();// True once shell.js actually injects the `claude` command (after its// round-trip readiness probe). The probe runs its OWN shell command first,// which toggles bracketed-paste mode and would otherwise advance the@@ -1777,6 +1780,9 @@ export async function spawnTuiAgent({emitLog('error', `TUI agent ${agentId} sendPrompt(${reason}) failed: ${err?.message || err}`, { agentId }));const safeFinishStartupFailure = (reason, summary) => finishStartupFailure(reason, summary).catch((err) =>emitLog('error', `TUI agent ${agentId} finishStartupFailure(${reason}) failed: ${err?.message || err}`, { agentId }));+ // The one PTY writer the startup-dialog answers go through, bound once+ // rather than rebuilt on every 300ms poll tick.+ const writeToTuiSession = (keys) => shellService.writeToSession(sessionId, keys);const promptTimer = setInterval(() => {if (finalized || promptSentAt) {clearInterval(promptTimer);@@ -1785,68 +1791,30 @@ export async function spawnTuiAgent({const now = Date.now();const elapsed = now - startedAt;- // Every dismissal below rewinds the idle clock (`lastOutputAt`) AND clears- // `firstOutputAt`, which re-arms the idle path's "has it printed anything?"- // gate. The idle heuristic that governs codex reads silence as readiness,- // and a dialog is at its quietest right after it paints — so the dismissal- // keystroke and an idle paste can otherwise go out inside the same window,- // landing the prompt in a menu that has not repainted. Demanding fresh- // output-then-silence AFTER the keystroke makes the paste wait for whatever- // the dismissal reveals; if the TUI ignores the keystroke entirely,- // PASTE_DEADLINE_MS still backstops delivery.-- // 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 parent repository's instructions- // must not leak into the target app, and option 2 leaves the target's own- // instruction files intact. Like the auto-mode offer, arrow-down + Enter- // avoids accepting the highlighted option 1.- if (inputReady.needsExternalImportsChoice && !externalImportsDeclined) {- externalImportsDeclined = true;- shellService.writeToSession(sessionId, '\x1b[B\r');- inputReady.ackExternalImportsChoice();- lastOutputAt = now;- firstOutputAt = null;- appendLine(`📟 Declined ${tuiConfig.command} external instruction imports for session ${sessionId.slice(0, 8)}`);- return;- }-- // Codex can present a hook-review selector before its composer exists.- // Do not trust hooks from an unattended run: option 3 keeps them disabled- // for this session and lets the agent continue without executing code- // outside its sandbox. This must run for every TUI, not only the positive- // input-ready providers below — Codex currently uses the idle/deadline path.- if (inputReady.needsHookReview && !hookReviewDeclined) {- hookReviewDeclined = true;- shellService.writeToSession(sessionId, '\x1b[B\x1b[B\r');- inputReady.ackHookReview();- lastOutputAt = now;- firstOutputAt = null;- appendLine(`📟 Continued ${tuiConfig.command} without trusting startup hooks for session ${sessionId.slice(0, 8)}`);- return;- }-- // Auto-confirm the first-run "trust this folder?" gate so agents can run in- // fresh worktrees. Wait for the choices themselves to paint: Claude Code- // releases disagree about their ordering, and newer builds can highlight- // "No, exit" by default. Move to the affirmative option when necessary,- // then submit it once.+ // 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+ // input-ready ones below, because codex takes the idle/deadline paste path+ // and a dialog is at its quietest right after it paints.//- // Like the hook-review selector this runs for EVERY TUI, not only the- // positive input-ready providers below: codex takes the idle/deadline path,- // and its trust dialog goes quiet the instant it paints, so the idle- // heuristic reads that silence as "ready" and pastes the task straight into- // the menu — which swallows it and all three paste retries- // (agent-671af38f, 2026-08-21, `paste-not-rendered`). Answering the dialog- // first is what lets the composer appear at all.- if (inputReady.needsTrust && inputReady.trustChoiceReady && !trustAccepted) {- trustAccepted = true;- const trustInput = `${inputReady.trustSelectionKey}${SUBMIT_KEY}`;- shellService.writeToSession(sessionId, trustInput);- inputReady.ackTrustChoice();+ // Answering rewinds the idle clock (`lastOutputAt`) AND clears+ // `firstOutputAt`, which re-arms the idle path's "has it printed anything?"+ // gate. Without that, the dismissal keystroke and an idle paste can go out+ // inside the same window, landing the prompt in a menu that has not+ // repainted. Demanding fresh output-then-silence AFTER the keystroke makes+ // the paste wait for whatever the dismissal reveals; if the TUI ignores the+ // keystroke entirely, PASTE_DEADLINE_MS still backstops delivery.+ const answeredBeforeComposer = answerStartupDialogs({+ inputReady,+ answers: dialogAnswers,+ stage: 'before-composer',+ command: tuiConfig.command,+ write: writeToTuiSession,+ });+ if (answeredBeforeComposer) {lastOutputAt = now;firstOutputAt = null;- appendLine(`📟 Auto-confirmed ${tuiConfig.command} folder-trust prompt for session ${sessionId.slice(0, 8)}`);+ appendLine(`📟 ${answeredBeforeComposer.message} for session ${sessionId.slice(0, 8)}`);return;}@@ -1868,19 +1836,20 @@ export async function spawnTuiAgent({}if (requireInputReady) {- // Decline claude's "make auto mode your default permission mode?" offer- // (v2.1.233+). Unlike the trust gate this one paints AFTER the composer is- // live, so it swallows the paste and every retry unless it is cleared- // first — see TUI_AUTO_MODE_PROMPT_PATTERN. Arrow-down + Enter rather than- // the digit `2`: it lands on "No, keep don't ask" under both of Ink's- // selection models (digit-immediate-select and navigate-then-confirm),- // whereas a bare `\r` would accept the highlighted option 1 and rewrite the- // user's global permission default.- if (inputReady.needsAutoModeChoice && !autoModeDeclined) {- autoModeDeclined = true;- shellService.writeToSession(sessionId, '\x1b[B\r');- inputReady.ackAutoModeChoice();- appendLine(`📟 Declined ${tuiConfig.command} auto-mode default offer for session ${sessionId.slice(0, 8)}`);+ // Claude's auto-mode offer paints AFTER the composer is live, so it only+ // reaches the positive input-ready providers — and unlike a dialog that+ // paints before the composer, no idle rewind is needed here: this path+ // gates on `inputReady.ready`, which the offer itself suppresses until+ // it is acked.+ const answeredAtComposer = answerStartupDialogs({+ inputReady,+ answers: dialogAnswers,+ stage: 'after-composer',+ command: tuiConfig.command,+ write: writeToTuiSession,+ });+ if (answeredAtComposer) {+ appendLine(`📟 ${answeredAtComposer.message} for session ${sessionId.slice(0, 8)}`);return;}if (inputReady.ready && elapsed >= tuiConfig.promptDelayMs) {