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(tui): BTW is Claude-TUI-only via paste; reinforce agent-owned PR
[._.]/ Adam Eivy15896a7e77ce
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0cf5f68008..bae90f8ca4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -912,6 +912,39 @@## Changed+- **BTW ("by the way") messages are now Claude-Code-TUI-only and paste live+ into the running session.** The old flow wrote a `BTW.md` file in the+ workspace and relied on a prompt instruction telling the agent to poll+ for it — brittle, often ignored, and required ephemeral-file cleanup on+ every cleanup path. The new flow detects whether the running agent is a+ Claude Code TUI session (codex / gemini / lm-studio TUIs don't honor+ bracketed-paste the same way) and, if so, pastes the BTW message into+ the live PTY as bracketed paste + delayed Enter. Non-Claude-TUI agents+ (headless CLI, runner-spawned, other TUI kinds) reject the request with+ a clear error instead of silently writing a file the agent will never+ read. The prompt's `BTW Messages` instruction is removed entirely+ because Claude Code natively handles user input mid-session and other+ agents no longer support BTW. The client BTW input box is gated on+ `metadata.executionMode === 'tui' && metadata.tuiKind === 'claude'` so it+ never offers a feature the server can't honor. `BTW.md` cleanup paths+ (`agentLifecycle`, `agentTuiSpawning`, `agentCliSpawning`) and the+ runner-client `sendBtwToAgent` HTTP wrapper are deleted. A new+ `metadata.tuiKind` field on agent state records which TUI binary is+ running (`claude`, `codex`, `gemini`, etc.).++- **TUI agents own the full PR creation and write the body themselves.**+ Reinforced after a TUI agent's PR ended up populated with garbled+ captured-output as the PR body. The Completion Workflow section now+ explicitly states "**You own the entire commit → push → PR sequence —+ PortOS will NOT push or open a PR on your behalf**" and instructs the+ agent to write the PR title/body itself based on actual changes (not+ auto-generated from terminal output). The post-exit `cleanupAgentWorktree`+ path for TUI agents was already passing `openPR: false`,+ `requestCopilotReview: false`, `skipMerge: true`; the review-loop prompt+ section is now also suppressed for TUI so the agent isn't told the+ system will request a Copilot review (it won't — the agent does it+ inline via `gh` after `/do:pr`).+- **`setup.{sh,ps1}` and `update.{sh,ps1}` now auto-install/update slash-dovia `npx slash-do@latest`.** Previously, `update.sh` and `update.ps1`prompted the user interactively to install `slash-do` only when thediff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex ee346d4ffd..b020a89650 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -618,7 +618,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed</div>)}- {!completed && !remote && (+ {!completed && !remote && agent.metadata?.executionMode === 'tui' && agent.metadata?.tuiKind === 'claude' && (<div className="mt-2 flex gap-2"><inputtype="text"@@ -634,7 +634,7 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completedonClick={sendBtw}disabled={sendingBtw || !btwInput.trim()}className="flex items-center gap-1.5 px-3 py-1 text-xs bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 rounded transition-colors disabled:opacity-50 min-h-[32px]"- title="Send BTW message to agent"+ title="Send BTW message to agent (pastes into the live Claude Code TUI session)">{sendingBtw ? <Loader2 size={12} className="animate-spin" aria-hidden="true" /> : <Send size={12} aria-hidden="true" />}BTWdiff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex e7e73c0488..beb6d017e4 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -6,7 +6,7 @@*/import { join } from 'path';-import { readFile, writeFile, rm } from 'fs/promises';+import { readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';import { spawn } from 'child_process';import { homedir } from 'os';@@ -568,11 +568,6 @@ export async function spawnDirectly(agentId, task, prompt, workspacePath, model,// Process memory extraction and app cooldownawait processAgentCompletion(agentId, task, success, outputBuffer);- // Clean up ephemeral BTW.md before worktree removal- if (workspacePath) {- await rm(join(workspacePath, 'BTW.md')).catch(() => {});- }-// Clean up worktree if agent was using oneconst directOpenPR = isTruthyMetaFn(task.metadata?.openPR);const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 6671d89ec0..794f14f366 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -42,16 +42,6 @@ const ROOT_DIR = PATHS.root;const AGENTS_DIR = PATHS.cosAgents;-/**- * Remove BTW.md from agent workspace after completion.- * Prevents ephemeral context files from being committed to git.- */-async function cleanupBtwFile(workspacePath) {- if (!workspacePath) return;- const btwPath = join(workspacePath, 'BTW.md');- await rm(btwPath).catch(() => {});-}-/*** Sync running agents from the runner (recovery after server restart).* This allows us to receive completion events for agents spawned before restart.@@ -1134,9 +1124,6 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration.catch((err) => console.log(`⚠️ creativeDirector completion hook failed: ${err.message}`));}- // Clean up ephemeral BTW.md before worktree removal- await cleanupBtwFile(agentState?.metadata?.workspacePath);-// Clean up worktree if agent was using one (skip merge when JIRA branch — PR handles merge)if (!jiraBranch) {const taskOpenPR = isTruthyMeta(agent.task?.metadata?.openPR);diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 3ac23c6a83..b8c6e567fa 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -229,10 +229,10 @@ After completing your work and before committing, run \`/simplify\` to review thconst tuiCompletionCommand = willOpenPR ? '/do:pr' : '/do:push';const tuiCompletionSection = isTui ? `## Completion Workflow-You are running inside the Claude Code TUI, which has the project's slashdo commands available as slash commands. When your task is complete, run the following — in order — without further user input:+You are running inside the Claude Code TUI, which has the project's slashdo commands available as slash commands. **You own the entire commit → push → ${willOpenPR ? 'PR' : 'push'} sequence — PortOS will NOT push or open a PR on your behalf.** When your task is complete, run the following — in order — without further user input:1. ${simplifyEnabled ? '`/simplify` — review the changed code for reuse, quality, and efficiency, and fix any issues it surfaces.' : '(simplify is disabled for this task — skip step 1)'}-2. \`${tuiCompletionCommand}\` — commits${willOpenPR ? ', pushes, and opens a pull request against the default branch' : ' and pushes the branch'}.+2. \`${tuiCompletionCommand}\` — commits${willOpenPR ? `, pushes, and opens a pull request against the default branch. Write the PR title and body yourself based on the actual changes you made; do NOT let any tool auto-generate the body from terminal output.${willReviewLoop ? ' After the PR is open, request a Copilot review (e.g. via `gh` if available).' : ''}` : ' and pushes the branch'}.3. Write the completion sentinel so PortOS knows you finished: \`echo "done" > "${worktreeInfo?.worktreePath || workspaceDir}/.agent-done"\` (PortOS polls for this file; without it the agent will sit idle until the 3-minute fallback timer fires).4. Run \`/quit\` to exit the Claude Code session cleanly.@@ -245,8 +245,10 @@ Do not wait for further user input between these steps — run them in sequence// PRs. On non-GitHub forges (e.g. GitLab MRs) this step is skipped because the// Copilot reviewer is GitHub-only. Only meaningful when a PR will actually be// created (willOpenPR), since the Copilot review request is a no-op without a- // PR URL.- const reviewLoopSection = willReviewLoop && willOpenPR ? `+ // PR URL. Suppressed for TUI agents because TUI agents open the PR themselves+ // and the Completion Workflow above instructs them to request the Copilot+ // review inline — the system-side post-exit handler never fires for TUI.+ const reviewLoopSection = willReviewLoop && willOpenPR && !isTui ? `## Code ReviewAfter your task completes, the system will request a Copilot code review automatically for GitHub PRs (the step is skipped for GitLab MRs and other non-GitHub forges). The system will then spawn a follow-up agent that runs the full review-and-fix loop until Copilot returns zero comments and merges the PR. You do not need to open the PR, trigger the review, or address feedback yourself — focus on producing high-quality, well-tested code so the review pass goes cleanly.` : '';@@ -416,7 +418,6 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${too- Do not make unrelated changes- If blocked, explain clearly why- Never update the PortOS changelog (\`.changelog/\`) for work on managed apps — the PortOS changelog tracks PortOS core changes only-- **BTW Messages**: The user may send you additional context while you work. Check for a \`BTW.md\` file in your working directory root — if it exists, read it for important messages from the user. Incorporate that context into your work. Do not delete or modify BTW.md.${isTruthyMetaFn(task.metadata?.readOnly) ? `- **This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.` : worktreeInfo && willOpenPR ? `- On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${willReviewLoop ? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — do NOT run \`/do:rpr\` or attempt to address review comments yourself; you will have already exited.' : ''}` : worktreeInfo ? `- Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.` : ``}## Git Hygiene (CRITICAL)diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex e4bcbf054b..ba70239eba 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -267,7 +267,6 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,}await processAgentCompletion(agentId, task, finalSuccess, outputBuffer);- if (workspacePath) await rm(join(workspacePath, 'BTW.md')).catch(() => {});if (workspacePath) await rm(join(workspacePath, DONE_SENTINEL_NAME)).catch(() => {});// TUI agents run /do:pr (or /do:push) themselves before signaling via@@ -454,6 +453,11 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,doneSentinelTimer});+ // Identify which TUI binary this session is running so consumers can gate+ // features that aren't universal — e.g. only Claude Code supports+ // bracketed-paste injection of post-spawn BTW messages; codex/gemini/lm-studio+ // TUIs don't.+ const tuiKind = commandName.toLowerCase();await updateAgent(agentId, {pid,metadata: {@@ -461,6 +465,7 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,executionMode: 'tui',tuiSessionId: sessionId,tuiCommand: tuiConfig.commandLine,+ tuiKind,tuiIdleTimeoutMs: tuiConfig.idleTimeoutMs}});diff --git a/server/services/cosAgents.js b/server/services/cosAgents.jsindex 8841584dcf..ce1775473f 100644--- a/server/services/cosAgents.js+++ b/server/services/cosAgents.js@@ -500,23 +500,47 @@ export async function killAgent(agentId) {return killAgentFromSpawner(agentId);}-// Send a BTW (additional context) message to a running agent+// Send a BTW (additional context) message to a running agent.+//+// BTW is only supported for Claude Code TUI agents — the message gets+// bracket-pasted directly into the live PTY session as if the user typed it+// themselves. The legacy BTW.md path is gone: it required headless agents to+// poll a file mid-run, which most CLIs (codex / gemini / LM Studio) don't do+// reliably anyway, and the indirection had to be reflected in the prompt with+// a brittle "check this file" instruction. Other TUI kinds (codex, gemini)+// don't honor bracketed-paste in the same way, so they're not eligible+// either.export async function sendBtwToAgent(agentId, message) {- // Single locked read to validate agent and extract workspacePathconst agentInfo = await withStateLock(async () => {const state = await loadState();const agent = state.agents[agentId];if (!agent) return { error: 'Agent not found' };if (agent.status !== 'running') return { error: 'Agent is not running' };- if (!agent.metadata?.workspacePath) return { error: 'Agent has no workspace path' };- return { workspacePath: agent.metadata.workspacePath };+ if (agent.metadata?.executionMode !== 'tui') {+ return { error: 'BTW is only supported for Claude Code TUI agents.' };+ }+ if (agent.metadata?.tuiKind !== 'claude') {+ return { error: `BTW is only supported for Claude Code TUI agents (this agent runs ${agent.metadata.tuiKind || 'an unknown TUI'}).` };+ }+ if (!agent.metadata?.tuiSessionId) {+ return { error: 'Agent has no attached TUI session' };+ }+ return { tuiSessionId: agent.metadata.tuiSessionId };});if (agentInfo.error) return agentInfo;- // Send to runner to write the BTW.md file- const { sendBtwToAgent: sendViaRunner } = await import('./cosRunnerClient.js');- const result = await sendViaRunner(agentId, message);+ const shellService = await import('./shell.js');+ if (!shellService.getSession(agentInfo.tuiSessionId)) {+ return { error: 'TUI session is no longer alive' };+ }+ // Bracketed-paste + delayed Enter, mirroring the initial prompt paste in+ // agentTuiSpawning.js: Claude Code commits the paste buffer before the+ // submit arrives, so multi-line messages land as a single paste event.+ shellService.writeToSession(agentInfo.tuiSessionId, `\x1b[200~${message}\x1b[201~`);+ setTimeout(() => {+ shellService.writeToSession(agentInfo.tuiSessionId, '\r');+ }, 400);// Track in agent state (cap at 50 messages)const timestamp = new Date().toISOString();@@ -534,7 +558,7 @@ export async function sendBtwToAgent(agentId, message) {});cosEvents.emit('agent:btw', { agentId, message, timestamp });- return { success: true, ...result };+ return { success: true, delivered: 'tui-paste', tuiSessionId: agentInfo.tuiSessionId };}// Get process stats for an agent (CPU, memory)diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex 294981f5f6..c7e97e3e8d 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -207,22 +207,6 @@ export async function terminateAllAgentsViaRunner() {return response.json();}-/**- * Send a BTW (additional context) message to a running agent via the runner- */-export async function sendBtwToAgent(agentId, message) {- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/btw/${agentId}`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ message }),- }, 30000);- if (!response.ok) {- const error = await response.json();- throw new Error(error.error || 'Failed to send BTW message');- }- return response.json();-}-/*** Get agent output from runner*/diff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.jsindex 82b18fae43..24bf363a15 100644--- a/server/services/cosRunnerClient.test.js+++ b/server/services/cosRunnerClient.test.js@@ -34,7 +34,6 @@ import {killAgentViaRunner,getAgentStatsFromRunner,terminateAllAgentsViaRunner,- sendBtwToAgent,getAgentOutputFromRunner,executeCliRunViaRunner,getActiveRunsFromRunner,@@ -332,33 +331,6 @@ describe('cosRunnerClient', () => {});});- // ===========================================================================- // sendBtwToAgent- // ===========================================================================- describe('sendBtwToAgent', () => {- it('should POST BTW message and return result', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(true, { sent: true }));- const result = await sendBtwToAgent('agent-1', 'Hey, check this out');- expect(result).toEqual({ sent: true });- expect(fetchWithTimeout).toHaveBeenCalledWith(- expect.stringContaining('/btw/agent-1'),- expect.objectContaining({- method: 'POST',- headers: { 'Content-Type': 'application/json' }- }),- 30000- );-- const callBody = JSON.parse(fetchWithTimeout.mock.calls[0][1].body);- expect(callBody.message).toBe('Hey, check this out');- });-- it('should throw on failure', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(false, { error: 'Agent not running' }));- await expect(sendBtwToAgent('bad-id', 'msg')).rejects.toThrow('Agent not running');- });- });-// ===========================================================================// getAgentOutputFromRunner// ===========================================================================