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
feat: let pr-reviewer Stage 3 run as an attachable TUI session (#6062)
Adam Eivyb5ca43e29d6e
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 014f1fd1a0..377a022fb4 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -378,12 +378,13 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,const lastOutput = output.length > 0 ? output[output.length - 1]?.line : null;// Why this run has NO "Open Shell" link. Scoped to the one case where the user- // configured a TUI provider and got no shell anyway: a public-review stage is- // forced headless regardless (`spawnHeadless = publicReview || !isTui`). An- // ordinary headless CLI agent gets no chip — nobody expected a shell there, and- // one on every card would be the noise this exists to remove.+ // configured a TUI provider and got no shell anyway: a public-review stage+ // runs headless unless it is the sandboxed-actions stage on a provider whose+ // vendor declares an attachable recipe. An ordinary headless CLI agent gets no+ // chip — nobody expected a shell there, and one on every card would be the+ // noise this exists to remove.const noShellReason = !agent.metadata?.tuiSessionId && agent.metadata?.publicReviewPosture- ? 'No shell: a public-review stage always runs headless, even when you configure it onto a TUI provider — the screened PR content stays inside the sandboxed child. Watch the live output below to see what it is doing.'+ ? 'No shell: this public-review stage runs headless — either it is a tool-free reasoning stage, or its provider has no attachable sandbox recipe — so the screened PR content stays inside the sandboxed child. Watch the live output below to see what it is doing.': null;// Why this run can be silent for minutes and still be perfectly healthy: itsdiff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsxindex e01404afe2..033934d6d8 100644--- a/client/src/components/cos/tabs/AgentCard.test.jsx+++ b/client/src/components/cos/tabs/AgentCard.test.jsx@@ -384,14 +384,28 @@ describe('AgentCard missing shell explanation', () => {);it('says why a public-review stage has no shell instead of leaving the card silent', () => {- // These stages are forced headless even on a TUI provider, so the "Open+ // A tool-free stage — or an actions stage on a provider with no attachable+ // sandbox recipe — runs headless even on a TUI provider, so the "Open// Shell" link never appears. Silence made a slow run look wedged with// nowhere to look.renderCard(running({ publicReviewPosture: 'sandboxed-actions', executionMode: 'direct' }));expect(screen.queryByText('Open Shell')).not.toBeInTheDocument();expect(screen.getByText('No shell')).toBeInTheDocument();- expect(screen.getByTitle(/public-review stage always runs headless/)).toBeInTheDocument();+ expect(screen.getByTitle(/this public-review stage runs headless/)).toBeInTheDocument();+ });++ it('keeps the shell link on an attachable sandboxed-actions run', () => {+ // Stage 3 on a TUI provider whose vendor declares an attachable recipe DOES+ // get a PTY (#6062) — the chip above must not fire on it, or the card would+ // claim there is no shell while linking to one.+ renderCard(running({+ publicReviewPosture: 'sandboxed-actions',+ executionMode: 'tui',+ tuiSessionId: 'sess-6062',+ }));++ expect(screen.queryByText('No shell')).not.toBeInTheDocument();});it('stays silent on a TUI run that has not registered its session yet', () => {diff --git a/server/lib/providerVendors.js b/server/lib/providerVendors.jsindex 2ac353ae67..9dfd6280f0 100644--- a/server/lib/providerVendors.js+++ b/server/lib/providerVendors.js@@ -143,11 +143,13 @@ function defaultSpawnArgs(cliArgsFn, fallbackCommand) {}/**- * A provider record that names a local binary PortOS can spawn headless. A- * public-review stage never runs interactively: a TUI record of the same- * vendor (`codex-tui`, `grok-tui`, …) is spawned through the vendor's headless- * recipe exactly like its CLI sibling, so the user's enabled TUI providers are- * legal stage choices. API/custom providers have no binary and no recipe.+ * A provider record that names a local binary PortOS can spawn. A TUI record of+ * a vendor (`codex-tui`, `grok-tui`, …) is spawned through that vendor's+ * headless public-review recipe exactly like its CLI sibling, so the user's+ * enabled TUI providers are legal stage choices. The one exception is a recipe+ * marked `tui: true` (see `supportsTuiPublicReviewPosture`), which the+ * sandboxed-actions stage may run as an attachable session so an operator can+ * watch and steer it. API/custom providers have no binary and no recipe.*/const isDirectBinaryProvider = (provider) => provider?.type === PROVIDER_TYPES.CLI || provider?.type === PROVIDER_TYPES.TUI;@@ -642,6 +644,17 @@ const CLAUDE = {[PUBLIC_REVIEW_ACTIONS_POSTURE]: {spawnArgs: claudePublicReviewSpawnArgsFor(CLAUDE_PUBLIC_REVIEW_ACTIONS_ARGS),matchProvider: matchClaudeBinary,+ // The only posture/vendor pairing that may run as an ATTACHABLE session.+ // `claudePublicReviewArgs` drops only the headless output flags for+ // `tui: true`; every enforcement flag above (`--permission-mode+ // acceptEdits`, the `--settings` sandbox JSON, `--disallowedTools`, and+ // the shared no-MCP/no-chrome/no-slash-command set) is still emitted, so+ // an operator who drops into the PTY inherits the same boundary the+ // headless run had. Nothing inside the session can widen it: the only+ // lever that lifts Claude Code's filesystem protection is+ // `sandbox.filesystem.disabled`, which this recipe never emits, and+ // `--disable-slash-commands` removes the in-session settings surface.+ tui: true,},},};@@ -709,8 +722,11 @@ export function inferTuiCommand(id) {/*** `applyCommandDefaults` (tuiHandshake.js): interactive-session flag dispatch.- * Public-review stages never reach this — they always spawn headless through- * `buildVendorSpawnConfig`, which is where a posture is enforced.+ * Public-review stages never reach this — headless OR attachable, their argv+ * comes from `buildVendorSpawnConfig`, which is where a posture is enforced.+ * (That is load-bearing for the attachable case: `ensureAntigravityTuiArgs` and+ * friends append `--dangerously-skip-permissions`-class defaults, which would+ * undo the recipe.)*/export function applyCommandDefaults(command, args) {const vendor = PROVIDER_VENDORS.find((v) => v.tuiArgs && v.matchCommand(command));@@ -752,6 +768,18 @@ export function buildVendorSpawnConfig(provider, ctx) {const posture = publicReviewPostureForProfile(ctx?.safetyProfile);if (posture) {const recipe = publicReviewRecipe(provider, posture);+ // An interactive spawn has no headless fallback tier: the ordinary+ // `spawnArgs` of a vendor without a TUI-capable recipe emits that vendor's+ // HEADLESS argv (`--print`, `exec`, `run`), which in a PTY neither accepts+ // a pasted prompt nor enforces anything. Fail closed rather than open a+ // session whose posture is decorative. Callers decide TUI-vs-headless from+ // `supportsTuiPublicReviewPosture`, so reaching this is a routing bug.+ if (ctx?.tui) {+ if (!recipe?.tui) {+ throw new Error(`Provider '${providerLabel(provider)}' has no attachable ${posture} public-review recipe`);+ }+ return recipe.spawnArgs(provider, ctx);+ }if (recipe) return recipe.spawnArgs(provider, ctx);// See supportsPublicReviewPosture for why the actions stage may fall// through to the vendor's ordinary headless recipe and the gate may not.@@ -771,8 +799,9 @@ export function buildVendorSpawnConfig(provider, ctx) {** API/custom providers have no maintained recipe: a generic read-only prompt* is not enforcement, so they fail closed. A TUI record IS eligible — the- * stage spawns its binary headless through the vendor's enforced recipe, never- * as an interactive session (see `isDirectBinaryProvider`).+ * stage spawns its binary through the vendor's enforced recipe, headless unless+ * that recipe is also marked `tui: true` (see `isDirectBinaryProvider` and+ * `supportsTuiPublicReviewPosture`).*/export function publicReviewPosturesForProvider(provider) {return PUBLIC_REVIEW_POSTURES.filter((posture) => supportsPublicReviewPosture(provider, posture));@@ -850,6 +879,30 @@ export function supportsPublicReviewActionsProvider(provider) {return supportsPublicReviewPosture(provider, PUBLIC_REVIEW_ACTIONS_POSTURE);}+/**+ * Whether `provider` may run a `posture` stage as an ATTACHABLE PTY session+ * rather than headless.+ *+ * Deliberately much narrower than `supportsPublicReviewPosture`: that one lets+ * the actions stage fall through to a vendor's ordinary headless recipe when it+ * declares none, which is fine for a `--print` child and useless in a PTY. An+ * interactive session requires a recipe that has been reviewed for it and says+ * so with `tui: true` — the recipe still owns the argv (`spawnArgs(provider,+ * { ...ctx, tui: true })`), it just drops the headless output flags.+ *+ * `no-tool` is structurally excluded: an interactive session for a reasoner+ * with no tools buys nothing and widens the boundary for free, so no row+ * declares it and this returns false for that posture by construction.+ */+export function supportsTuiPublicReviewPosture(provider, posture) {+ return isDirectBinaryProvider(provider) && Boolean(publicReviewRecipe(provider, posture)?.tui);+}++/** Whether the sandboxed final public-review stage can attach a PTY here. */+export function supportsTuiPublicReviewActionsProvider(provider) {+ return supportsTuiPublicReviewPosture(provider, PUBLIC_REVIEW_ACTIONS_POSTURE);+}+/*** Shared TUI model+effort injection — the piece that had ALREADY drifted once* before #3618 was filed (an antigravity Bedrock exemption landed indiff --git a/server/lib/providerVendors.publicReview.test.js b/server/lib/providerVendors.publicReview.test.jsindex 010dd2f81d..aa38f71b48 100644--- a/server/lib/providerVendors.publicReview.test.js+++ b/server/lib/providerVendors.publicReview.test.js@@ -13,6 +13,8 @@ import {publicReviewProviderBlock,supportsPublicReviewProvider,supportsPublicReviewActionsProvider,+ supportsTuiPublicReviewActionsProvider,+ supportsTuiPublicReviewPosture,} from './providerVendors.js';const localClaude = {@@ -309,6 +311,83 @@ describe('public-review provider postures', () => {expect(cloudGate.args).toContain('--restricted');});+ // #6062 — Stage 3 may run as an ATTACHABLE session so an operator can watch+ // and steer the longest, least predictable stage in the pipeline. `tui: true`+ // is a per-recipe opt-in, and it drops ONLY the headless output flags.+ it('keeps every Claude actions enforcement flag when the recipe is built for a TUI session', () => {+ const claudeTui = { id: 'claude-tui', type: 'tui', command: 'claude', args: ['--dangerously-skip-permissions'] };+ const headless = buildVendorSpawnConfig(claudeTui, {+ effectiveModel: 'sonnet',+ safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,+ });+ const tui = buildVendorSpawnConfig(claudeTui, {+ effectiveModel: 'sonnet',+ safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,+ tui: true,+ });++ expect(tui.command).toBe('claude');+ // The whole sandbox recipe survives — this is what makes attaching safe.+ expect(tui.args).toEqual(expect.arrayContaining([+ '--permission-mode', 'acceptEdits',+ '--settings', headless.args[headless.args.indexOf('--settings') + 1],+ '--disallowedTools', 'WebFetch,WebSearch',+ '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',+ '--no-chrome', '--no-session-persistence', '--disable-slash-commands',+ '--model', 'sonnet',+ ]));+ // Nothing inside the session can lift the sandbox: the only lever is+ // `sandbox.filesystem.disabled`, and the recipe never emits it.+ expect(JSON.parse(tui.args[tui.args.indexOf('--settings') + 1]).sandbox)+ .not.toHaveProperty('filesystem');+ // A saved skip-permissions arg is still ignored — provider.args is never+ // forwarded on this path, headless or attachable.+ expect(tui.args).not.toContain('--dangerously-skip-permissions');+ // …and ONLY the headless output flags are gone.+ expect(headless.args).toEqual(expect.arrayContaining(['--print', '--output-format', 'stream-json', '--verbose', '--include-partial-messages']));+ for (const flag of ['--print', '--output-format', 'stream-json', '--verbose', '--include-partial-messages']) {+ expect(tui.args).not.toContain(flag);+ }+ expect(headless.args.filter((a) => !['--print', '--output-format', 'stream-json', '--verbose', '--include-partial-messages'].includes(a)))+ .toEqual(tui.args);+ });++ it('declares attachability per recipe, and never for the tool-free postures', () => {+ const claudeTui = { id: 'claude-tui', type: 'tui', command: 'claude' };+ expect(supportsTuiPublicReviewActionsProvider(claudeTui)).toBe(true);+ // An interactive session for a reasoner with no tools buys nothing and+ // widens the boundary for free — no row declares it.+ expect(supportsTuiPublicReviewPosture(claudeTui, PUBLIC_REVIEW_NO_TOOL_POSTURE)).toBe(false);+ // Vendors whose actions recipe has not been reviewed for a PTY stay headless.+ expect(supportsTuiPublicReviewActionsProvider({ id: 'codex-tui', type: 'tui', command: 'codex' })).toBe(false);+ expect(supportsTuiPublicReviewActionsProvider({ id: 'grok-tui', type: 'tui', command: 'grok' })).toBe(false);+ expect(supportsTuiPublicReviewActionsProvider(antigravity)).toBe(false);+ // …as do vendors with no actions recipe at all, and non-binary records.+ expect(supportsTuiPublicReviewActionsProvider({ id: 'opencode-tui', type: 'tui', command: 'opencode' })).toBe(false);+ expect(supportsTuiPublicReviewActionsProvider({ id: 'claude-api', type: 'api', command: 'claude' })).toBe(false);+ });++ it('refuses to build an attachable argv for a vendor with no attachable recipe', () => {+ // Failing closed matters more here than anywhere else on this path: the+ // headless fallback tier emits `--print`/`exec`/`run` argv, which in a PTY+ // neither accepts a pasted prompt nor enforces anything.+ for (const provider of [+ { id: 'codex-tui', type: 'tui', command: 'codex' },+ { id: 'grok-tui', type: 'tui', command: 'grok' },+ { id: 'opencode-tui', type: 'tui', command: 'opencode' },+ { id: 'antigravity-tui', type: 'tui', command: 'agy' },+ ]) {+ expect(() => buildVendorSpawnConfig(provider, {+ safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,+ tui: true,+ })).toThrow(/no attachable sandboxed-actions public-review recipe/);+ }+ expect(() => buildVendorSpawnConfig({ id: 'claude-tui', type: 'tui', command: 'claude' }, {+ safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,+ tui: true,+ })).toThrow(/no attachable no-tool public-review recipe/);+ });+it('runs a vendor with no sandbox recipe through its ordinary headless recipe for the actions stage only', () => {const opencode = { id: 'opencode-tui', type: 'tui', command: 'opencode', args: ['--agent', 'build'] };const config = buildVendorSpawnConfig(opencode, {diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex bef6821ba7..0abdd60282 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -63,7 +63,7 @@ import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';import { dropUnsupportedOllamaThinking } from './ollamaAgentContext.js';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';-import { publicReviewProviderBlock, publicReviewPostureForProfile, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib/providerVendors.js';+import { publicReviewProviderBlock, publicReviewPostureForProfile, supportsTuiPublicReviewActionsProvider, PUBLIC_REVIEW_NO_TOOL_POSTURE } from '../lib/providerVendors.js';import { PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE } from '../lib/agentExecutionProfiles.js';import { formatPublicReviewInputPrompt } from '../lib/modelAbuseGuard.js';import { materializePublicReviewInput, materializePublicReviewPatches, readPublicReviewInputSnapshot, validatePublicReviewModel } from './modelAbuseGuard.js';@@ -438,12 +438,23 @@ async function runAgentSpawn(task) {const publicReviewActions = executionProfile === PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE;const publicReview = Boolean(publicReviewPosture);const isTui = isTuiProvider(provider);- // A public-content stage never runs as an interactive session: a TUI- // provider record is spawned headless through its vendor's enforced- // recipe (the same binary as its CLI sibling) — the recipe that makes it- // eligible in `providerVendors.js` — so the user's enabled TUI providers- // are legal stage choices without opening a PTY.- const spawnHeadless = publicReview || !isTui;+ // Stage 3 (`sandboxed-actions`) is the longest-running and least+ // predictable stage in the pr-reviewer pipeline — it applies a screened+ // patch and runs the repo's tests — so it is the one an operator actually+ // wants to attach to and steer. It may run as an interactive session when+ // its configured provider is a TUI record AND that vendor declares an+ // attachable recipe (`tui: true`), which keeps every enforcement flag and+ // drops only the headless output flags.+ //+ // Everything else stays headless. The `no-tool` postures (Stage 1's+ // security scan, Stage 2's eligibility gate) are excluded by design: an+ // interactive session for a reasoner with no tools buys nothing and widens+ // the boundary for free. A TUI record whose vendor has no attachable+ // recipe also stays headless — its ordinary recipe emits `--print`/`exec`+ // argv that a PTY can neither prompt nor enforce.+ const publicReviewTui = publicReviewActions && isTui+ && supportsTuiPublicReviewActionsProvider(provider);+ const spawnHeadless = !isTui || (publicReview && !publicReviewTui);if (publicReview) {const scanBlock = publicReviewScanBlock(task);if (scanBlock) {@@ -811,9 +822,10 @@ async function runAgentSpawn(task) {// The public-review posture this run executes under (null for an ordinary// task). Projected beside `executionMode` because the UI cannot otherwise// explain why the card has no "Open Shell" link: a public-review stage is- // forced headless (`spawnHeadless = publicReview || !isTui` above) even- // when the user configured it onto a TUI provider, so without this the- // card is indistinguishable from an agent whose PTY failed to attach.+ // forced headless (`spawnHeadless` above) unless it is the sandboxed-+ // actions stage on a TUI provider whose vendor declares an attachable+ // recipe, so without this the card is indistinguishable from an agent+ // whose PTY failed to attach.publicReviewPosture,taskAnalysisType: task.metadata?.analysisType || null,taskReviewType: task.metadata?.reviewType || null,@@ -981,7 +993,7 @@ async function runAgentSpawn(task) {const maxConcurrentThreads = cloudSwarmThreadCapacity(runProvider, task.metadata?.swarmCount);const safetyProfile = publicReview ? executionProfile : null;const cliConfig = !spawnHeadless- ? buildTuiSpawnConfig(runProvider, selectedModel, { systemPromptFile, effort: taskEffort, maxConcurrentThreads })+ ? buildTuiSpawnConfig(runProvider, selectedModel, { systemPromptFile, effort: taskEffort, maxConcurrentThreads, safetyProfile }): buildCliSpawnConfig(runProvider, selectedModel, cliSettingsEnv, { systemPromptFile, effort: taskEffort, maxConcurrentThreads, safetyProfile });emitLog('success', `Spawning agent for task ${task.id}`, {@@ -1021,6 +1033,7 @@ async function runAgentSpawn(task) {isTruthyMetaFn: isTruthyMeta,leanMode,useDurableRunner: dispatchUseRunner,+ safetyProfile,});}if (dispatchUseRunner) {diff --git a/server/services/agentLifecycle.postureGate.test.js b/server/services/agentLifecycle.postureGate.test.jsindex 46b3574470..136e7b4b7a 100644--- a/server/services/agentLifecycle.postureGate.test.js+++ b/server/services/agentLifecycle.postureGate.test.js@@ -147,7 +147,7 @@ vi.mock('./modelAbuseGuard.js', () => ({import { spawnAgentForTask } from './agentLifecycle.js';import { prepareAgentWorkspace } from './agentWorkspacePrep.js';-import { materializePublicReviewInput, readPublicReviewInputSnapshot } from './modelAbuseGuard.js';+import { materializePublicReviewInput, materializePublicReviewPatches, readPublicReviewInputSnapshot } from './modelAbuseGuard.js';import { removeWorktree } from './worktreeManager.js';import { resolveAgentProviderAndModel } from './agentProviderResolution.js';import { buildAgentPrompt } from './agentPromptBuilder.js';@@ -187,6 +187,9 @@ function reachDispatch() {worktreeInfo: null,});vi.mocked(materializePublicReviewInput).mockResolvedValue(true);+ // The actions stage also materializes the read-only patch files; without this+ // its dispatch cases block on `public-review-input-missing` before routing.+ vi.mocked(materializePublicReviewPatches).mockResolvedValue(true);vi.mocked(readPublicReviewInputSnapshot).mockResolvedValue({ pullRequests: [] });vi.mocked(buildAgentPrompt).mockResolvedValue('review the cleared input');vi.mocked(createAgentRun).mockResolvedValue({ runId: 'run-1' });@@ -304,6 +307,94 @@ describe('public-review posture gate — spawn behavior (#5866)', () => {expect(buildTuiSpawnConfig).not.toHaveBeenCalled();expect(spawnTuiAgent).not.toHaveBeenCalled();});++ // #6062 — Stage 3 is the longest-running, least predictable stage (it applies+ // a patch and runs the repo's tests), so it is the one an operator wants to+ // attach to and steer. It gets a PTY when its provider is a TUI record whose+ // vendor declares an attachable recipe.+ it('spawns the sandboxed-actions stage as a PTY when its TUI provider has an attachable recipe', async () => {+ const { buildTuiSpawnConfig, spawnTuiAgent } = await import('./agentTuiSpawning.js');+ vi.mocked(buildTuiSpawnConfig).mockReturnValue({ command: 'claude', args: [], commandLine: 'claude' });+ reachDispatch();++ await spawnAgentForTask({+ id: 'task-public-review-actions-tui',+ metadata: {+ executionProfile: 'public-review-actions',+ issueWatcher: { pullRequests: [{ number: 42 }] },+ pipeline: {+ securityScan: { completed: true, status: 'passed', safePrCount: 1 },+ eligibility: { complete: true, eligibleNumbers: [42] },+ },+ },+ });++ expect(postureBlockWrites()).toEqual([]);+ expect(spawnDirectly).not.toHaveBeenCalled();+ expect(spawnTuiAgent).toHaveBeenCalledTimes(1);+ // The posture must reach BOTH the argv builder (so the vendor recipe, not+ // the generic assembly, decides the flags) and the session (so the PTY+ // child gets the same allowlisted env its headless sibling would).+ expect(buildTuiSpawnConfig).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'claude-code-tui' }),+ 'sonnet',+ expect.objectContaining({ safetyProfile: 'public-review-actions' }),+ );+ expect(spawnTuiAgent).toHaveBeenCalledWith(+ expect.objectContaining({ safetyProfile: 'public-review-actions' }),+ );+ });++ // The narrow half of the same rule. A vendor whose actions recipe has not been+ // reviewed for a PTY emits headless argv (`exec`, `--print`, `run`) that a PTY+ // can neither prompt nor enforce, so it stays headless rather than opening a+ // session whose posture is decorative.+ it('keeps the sandboxed-actions stage headless on a TUI provider with no attachable recipe', async () => {+ const { buildTuiSpawnConfig, spawnTuiAgent } = await import('./agentTuiSpawning.js');+ vi.mocked(resolveAgentProviderAndModel).mockResolvedValue({+ ok: true, provider: { id: 'codex-tui', type: 'tui', command: 'codex', envVars: {} },+ selectedModel: 'gpt-5.6', modelSelection: {},+ });+ reachDispatch();++ await spawnAgentForTask({+ id: 'task-public-review-actions-codex',+ metadata: {+ executionProfile: 'public-review-actions',+ issueWatcher: { pullRequests: [{ number: 42 }] },+ pipeline: {+ securityScan: { completed: true, status: 'passed', safePrCount: 1 },+ eligibility: { complete: true, eligibleNumbers: [42] },+ },+ },+ });++ expect(postureBlockWrites()).toEqual([]);+ expect(spawnDirectly).toHaveBeenCalledTimes(1);+ expect(buildTuiSpawnConfig).not.toHaveBeenCalled();+ expect(spawnTuiAgent).not.toHaveBeenCalled();+ });++ // The other exclusion, and the one that is a security posture rather than a+ // capability gap: an interactive session for a reasoner with no tools buys+ // nothing and widens the boundary for free.+ it('keeps a no-tool stage headless even on a provider whose actions recipe is attachable', async () => {+ const { buildTuiSpawnConfig, spawnTuiAgent } = await import('./agentTuiSpawning.js');+ reachDispatch();++ await spawnAgentForTask({+ id: 'task-public-review-no-tool-claude',+ metadata: {+ executionProfile: 'public-review-gate',+ pipeline: { securityScan: { completed: true, status: 'passed', safePrCount: 1 } },+ },+ });++ expect(postureBlockWrites()).toEqual([]);+ expect(spawnDirectly).toHaveBeenCalledTimes(1);+ expect(buildTuiSpawnConfig).not.toHaveBeenCalled();+ expect(spawnTuiAgent).not.toHaveBeenCalled();+ });});/**diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex fd25ce503b..d6c3b4f77e 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -739,8 +739,9 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'});it('projects the public-review posture so the UI can explain the missing shell link', () => {- // `spawnHeadless = publicReview || !isTui` forces a public-review stage- // headless even on a TUI provider, so its card never gets an "Open Shell"+ // `spawnHeadless` forces a public-review stage headless even on a TUI+ // provider — unless it is the sandboxed-actions stage on a vendor with an+ // attachable recipe (#6062) — so its card usually gets no "Open Shell"// link. Without this projection the card cannot tell that apart from a PTY// that failed to attach, and the run reads as wedged.const registerIdx = RUN_SPAWN_BODY.indexOf('registerAgent(agentId, task.id, {');diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex e3aec2e955..d21df2ddfe 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -318,6 +318,33 @@ describe('sandboxed public-review actions stage completion', () => {expect(prompt).not.toMatch(/## Completion \(No Code Output\)/);expect(prompt).not.toMatch(/## Completion \(Tool-Free Reasoning\)/);});++ // #6062 made this stage attachable on a TUI provider whose vendor declares an+ // attachable recipe. A TUI run finalizes on the `.agent-done` watcher and+ // `dispatchTaskOutputHook` reads the payload from that same file, so the+ // contract only holds if the posture — not the provider type — decides it.+ // Were the TUI arm to win here, an attachable Stage 3 would be told to run+ // `/simplify` + `/do:pr` in a discarded worktree and its decision payload+ // would have to be scraped back out of repaint-heavy PTY output.+ it('gives the same sentinel-payload contract on a TUI provider as on a headless one', () => {+ const task = () => makeTask({+ metadata: { noCodeOutput: true, discardWorktree: true, openPR: false, executionProfile: 'public-review-actions' },+ });+ // Same provider record, spawned two ways — so the ONLY variable is the+ // spawn mode, which is exactly the thing that must not move the contract.+ const headless = buildLightContextPrompt(task(), '/repo', null, isTruthyMeta, {+ providerType: 'cli', providerId: 'claude-code', providerCommand: 'claude',+ });+ const tui = buildLightContextPrompt(task(), '/repo', null, isTruthyMeta, {+ providerType: 'tui', providerId: 'claude-code', providerCommand: 'claude',+ });+ expect(tui).toMatch(/exact payload format described in your task instructions/);+ expect(tui).toMatch(/\.agent-done/);+ // The TUI push/PR workflow must stay suppressed — the worktree is discarded.+ expect(tui).not.toMatch(/## Completion Workflow/);+ expect(tui).not.toMatch(/YOU run the Completion Workflow/);+ expect(tui).toBe(headless);+ });});describe('no-code / API-action task completion (CD agents must NOT be told to /do:push)', () => {diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 600d368160..a30d3fbde7 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -67,9 +67,10 @@ import {isPasteConfirmed,SUBMIT_KEY,} from '../lib/tuiHandshake.js';-import { injectTuiModelAndEffort } from '../lib/providerVendors.js';+import { buildVendorSpawnConfig, injectTuiModelAndEffort, supportsTuiPublicReviewPosture } from '../lib/providerVendors.js';+import { isPublicReviewRestrictedProfile, publicReviewPostureForProfile } from '../lib/agentExecutionProfiles.js';import { agentGuardEnv } from '../lib/agentGuard/index.js';-import { composeProviderEnv } from '../lib/cliChildEnv.js';+import { buildCliChildEnv, composeProviderEnv } from '../lib/cliChildEnv.js';import { cliProviderAuthDescriptor } from '../lib/processEnv.js';import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import { isOllamaBackedProvider } from './providers.js';@@ -111,12 +112,41 @@ export async function createAgentTuiSession({forgeTokenEnv = {},doneSentinelPath = null,useDurableRunner = false,+ safetyProfile = null,onData,onExit,onInitialCommandSent,}) {- const env = { ...composeProviderEnv({ before: forgeTokenEnv, provider, model }), ...agentGuardEnv() };+ const restricted = isPublicReviewRestrictedProfile(safetyProfile);+ // A public-content stage's PTY starts from the SAME environment its headless+ // sibling gets — no forge credential, no SSH config, no cloud key, no+ // arbitrary provider var — so it calls the very builder the headless path+ // uses rather than re-deriving the profile→allowlist mapping here. The result+ // is a COMPLETE environment, not the delta `createShellSession` normally+ // takes: the shell service unions a delta onto `buildSafeEnv(process.env)`,+ // which would restore everything the allowlist just withheld, hence+ // `envReplace` below.+ //+ // KNOWN RESIDUAL (tracked separately, see #6159): this path hosts the CLI inside an+ // interactive login shell, so the operator's own rc file runs before the+ // provider does and can re-export anything it likes. That is not a hole this+ // allowlist can close — closing it means spawning the recipe command as the+ // PTY directly, the way the runner's `/spawn-tui` already does. What the+ // allowlist DOES close is the server's own process environment, which is+ // where a newly-added PortOS secret would otherwise appear for free.+ const env = restricted+ ? buildCliChildEnv({ before: forgeTokenEnv, provider, model, cwd, guard: true, safetyProfile })+ : { ...composeProviderEnv({ before: forgeTokenEnv, provider, model }), ...agentGuardEnv() };if (useDurableRunner) {+ // The CoS runner is a shared long-lived process and builds its own child+ // env from ITS ambient environment (`/spawn-tui` → `buildCliChildEnv`+ // without a profile), so a public-content stage routed through it would+ // silently lose the allowlist resolved above. `agentLifecycle.js` forces+ // every such stage direct-only (`dispatchUseRunner`); fail closed here so+ // that stays true by construction rather than by remembering it.+ if (restricted) {+ throw new Error(`Public-content stage cannot spawn via the CoS runner (profile '${safetyProfile}')`);+ }// The runner launches the TUI command directly (there is no intermediate// login-shell readiness probe), so output can arrive before the spawn HTTP// response. Open the readiness gate before handing off to avoid discarding@@ -180,6 +210,9 @@ export async function createAgentTuiSession({// whose real base env is assembled downstream. Only AI agent sessions get// the shim; the user's own Shell page does not.env,+ // …except under a public-content posture, where `env` above is not a delta+ // at all but the complete, allowlisted environment (see its construction).+ envReplace: restricted,onData,onExit,});@@ -196,8 +229,38 @@ export function buildTuiSpawnConfig(provider, model, {systemPromptFile = null,effort = null,maxConcurrentThreads = null,+ safetyProfile = null,shell = resolveInteractiveShell(),} = {}) {+ // A public-content stage's argv is the vendor's maintained recipe, never the+ // generic assembly below — that path forwards `provider.args` and applies+ // `applyCommandDefaults`, either of which can hand a contributor-controlled+ // review a saved `--dangerously-skip-permissions`. `tui: true` tells the+ // recipe to drop only its headless output flags and keep every enforcement+ // flag. Fail closed when the pairing declares no attachable recipe: the+ // caller is supposed to have asked `supportsTuiPublicReviewPosture` first, so+ // reaching this is a routing bug and must not silently open a PTY whose+ // posture is decorative.+ const posture = publicReviewPostureForProfile(safetyProfile);+ if (posture) {+ if (!supportsTuiPublicReviewPosture(provider, posture)) {+ throw new Error(`Provider '${provider?.id || provider?.command || 'unknown'}' cannot run an attachable ${posture} session`);+ }+ const recipe = buildVendorSpawnConfig(provider, {+ effectiveModel: model,+ effort,+ maxConcurrentThreads,+ systemPromptFile,+ safetyProfile,+ tui: true,+ });+ return {+ command: recipe.command,+ args: recipe.args,+ commandLine: formatShellCommandLine(recipe.command, recipe.args, shell),+ promptDelayMs: provider?.tuiPromptDelayMs || DEFAULT_TUI_PROMPT_DELAY_MS,+ };+ }const command = provider?.command || inferTuiCommand(provider?.id);const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);// Model+effort injection (including the antigravity-validates-the-pair special@@ -554,6 +617,10 @@ export async function spawnTuiAgent({isTruthyMetaFn,leanMode = false,useDurableRunner = false,+ // The public-content execution profile this run enforces (null for an+ // ordinary agent task). Threaded through to the session so the PTY child+ // gets the same allowlisted environment its headless sibling would.+ safetyProfile = null,}) {const outputFile = join(agentDir, 'output.txt');// Raw PTY bytes spool to disk continuously rather than accumulate in-memory.@@ -1349,8 +1416,10 @@ export async function spawnTuiAgent({// Repo-owner-pinned GH_TOKEN for the agent's own `gh pr create` (see// resolveForgeTokenEnv). Resolved here since createAgentTuiSession is sync.// Skip when the provider supplies its own GH_TOKEN/GITHUB_TOKEN so its explicit- // credential wins.- const forgeTokenEnv = providerSuppliesGithubToken(provider)+ // credential wins — and skip for a public-content stage, which must never hold+ // a forge credential (the allowlist in createAgentTuiSession strips it anyway;+ // not resolving it means it is never read out of the keychain to begin with).+ const forgeTokenEnv = providerSuppliesGithubToken(provider) || isPublicReviewRestrictedProfile(safetyProfile)? {}: await git.resolveForgeTokenEnv(cwd);@@ -1395,6 +1464,7 @@ export async function spawnTuiAgent({forgeTokenEnv,doneSentinelPath,useDurableRunner,+ safetyProfile,onData: handleData,onExit: handleExit,onInitialCommandSent: () => { commandInjected = true; },diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 5f95d5a01d..589cb27324 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -229,6 +229,10 @@ import { existsSync } from 'fs';import { readFile, rm } from 'fs/promises';import { execFile } from '../lib/childProcess.js';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';+import {+ PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,+ PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,+} from '../lib/agentExecutionProfiles.js';import { releaseRetryHold } from './agentWorktreeCleanup.js';import { spawnTuiSessionViaRunner, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';import * as shellService from './shell.js';@@ -270,6 +274,55 @@ describe('agent TUI spawning', () => {// on a Bedrock box launched with a rewritten, unroutable model id. Both copies// now delegate to `resolveInjectedTuiModel`; re-inlining the mapper here would// break this test.+ // #6062 — Stage 3 (`sandboxed-actions`) may run attachable. When it does, its+ // argv MUST come from the vendor's maintained recipe, never the generic+ // assembly below: that path forwards `provider.args` and runs+ // `applyCommandDefaults`, either of which can hand a contributor-controlled+ // review a `--dangerously-skip-permissions` session.+ it('builds an actions-posture TUI session from the vendor recipe, not the generic argv', () => {+ const config = buildTuiSpawnConfig({+ id: 'claude-tui',+ type: 'tui',+ command: 'claude',+ args: ['--dangerously-skip-permissions'],+ }, 'sonnet', { safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE, effort: 'high' });++ expect(config.command).toBe('claude');+ expect(config.args).toEqual(expect.arrayContaining([+ '--permission-mode', 'acceptEdits', '--settings', '--disallowedTools',+ '--strict-mcp-config', '--disable-slash-commands', '--model', 'sonnet',+ ]));+ // The saved arg is dropped, and the headless output flags are gone so the+ // PTY actually gets an interactive session to attach to.+ expect(config.args).not.toContain('--dangerously-skip-permissions');+ expect(config.args).not.toContain('--print');+ expect(config.args).not.toContain('--output-format');+ // The command LINE is still rendered the same way every TUI spawn renders it.+ expect(config.commandLine.startsWith('claude ')).toBe(true);+ expect(config.commandLine).toContain('--permission-mode');+ });++ it('fails closed rather than opening an actions-posture PTY with no maintained recipe', () => {+ // Reaching this is a routing bug (`agentLifecycle` asks+ // `supportsTuiPublicReviewActionsProvider` first) — but the fallback tier+ // would emit codex's headless `exec` argv, which in a PTY neither accepts a+ // pasted prompt nor enforces anything.+ expect(() => buildTuiSpawnConfig({ id: 'codex-tui', type: 'tui', command: 'codex' }, 'gpt-5.6', {+ safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,+ })).toThrow(/cannot run an attachable sandboxed-actions session/);+ expect(() => buildTuiSpawnConfig({ id: 'claude-tui', type: 'tui', command: 'claude' }, 'sonnet', {+ safetyProfile: PUBLIC_REVIEW_GATE_EXECUTION_PROFILE,+ })).toThrow(/cannot run an attachable no-tool session/);+ });++ it('leaves the ordinary TUI argv untouched when no posture is requested', () => {+ const config = buildTuiSpawnConfig({+ id: 'claude-tui', type: 'tui', command: 'claude', args: ['--dangerously-skip-permissions'],+ }, 'sonnet');+ expect(config.args).toContain('--dangerously-skip-permissions');+ expect(config.args).not.toContain('--settings');+ });+it('does not Bedrock-map a cursor TUI model id that merely contains "claude"', () => {process.env.CLAUDE_CODE_USE_BEDROCK = '1';const config = buildTuiSpawnConfig({@@ -597,6 +650,7 @@ describe('spawnTuiAgent runtime', () => {laneName,leanMode: overrides.leanMode ?? false,useDurableRunner: overrides.useDurableRunner ?? false,+ safetyProfile: overrides.safetyProfile ?? null,...helpers,});}@@ -717,6 +771,73 @@ describe('spawnTuiAgent runtime', () => {await completeDone;});+ // #6062 — the attachable Stage 3. The PTY child must get the SAME allowlisted+ // environment its headless sibling would; a TUI Stage 3 running with the+ // server's own inherited environment would be a real regression, not a+ // cosmetic one — the whole posture assumes no forge credential is reachable.+ it('hands an actions-posture PTY the allowlisted env verbatim instead of unioning it onto the shell base', async () => {+ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });+ process.env.PORTOS_TEST_6062_SECRET = 'must-not-reach-the-review';++ runSpawn({+ provider: { id: 'claude-tui', name: 'Local Claude TUI', type: 'tui', command: 'claude', envVars: {} },+ safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,+ });+ await flushMicrotasks();++ const opts = vi.mocked(shellService.createShellSession).mock.calls[0][1];+ // envReplace is what stops shell.js unioning buildSafeEnv(process.env) back+ // underneath the allowlist we just applied.+ expect(opts.envReplace).toBe(true);+ expect(opts.env.PORTOS_TEST_6062_SECRET).toBeUndefined();+ expect(opts.env.GH_TOKEN).toBeUndefined();+ // …while the variables the stage legitimately needs survive.+ expect(opts.env.PATH).toBeTruthy();+ expect(opts.env.HOME).toBeTruthy();+ // The forge credential is never even read out of the keychain for this stage.+ expect(gitService.resolveForgeTokenEnv).not.toHaveBeenCalled();++ delete process.env.PORTOS_TEST_6062_SECRET;+ await capturedOnExit({ exitCode: 0, killed: false });+ await completeDone;+ });++ it('keeps the ordinary TUI session on the shell service\u2019s own base env', async () => {+ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ runSpawn();+ await flushMicrotasks();++ // `env` stays a DELTA here — the regression this guards is flipping every+ // agent session onto the public-review allowlist, which would strip the+ // toolchain vars an ordinary coding agent needs.+ expect(vi.mocked(shellService.createShellSession).mock.calls[0][1].envReplace).toBeFalsy();++ await capturedOnExit({ exitCode: 0, killed: false });+ await completeDone;+ });++ it('refuses to route a public-content stage through the shared CoS runner', async () => {+ // The runner builds its own child env from ITS ambient environment+ // (`/spawn-tui` → `buildCliChildEnv` with no profile), so a restricted stage+ // routed through it would silently lose the allowlist. `agentLifecycle`+ // forces every such stage direct-only; this keeps that true by construction.+ const spawned = runSpawn({+ provider: { id: 'claude-tui', name: 'Local Claude TUI', type: 'tui', command: 'claude', envVars: {} },+ safetyProfile: PUBLIC_REVIEW_ACTIONS_EXECUTION_PROFILE,+ useDurableRunner: true,+ });+ await flushMicrotasks();++ expect(spawnTuiSessionViaRunner).not.toHaveBeenCalled();+ expect(shellService.createShellSession).not.toHaveBeenCalled();+ await expect(spawned).resolves.toBeNull();+ });+it('makes the login shell exit with the TUI command instead of lingering after it exits', async () => {runSpawn();await flushMicrotasks();diff --git a/server/services/shell.js b/server/services/shell.jsindex cb08c2c225..c625fa1bbd 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -159,7 +159,12 @@ export function createShellSession(socket, options = {}) {// login shell rewrites PWD itself at startup, but a non-login shell may// not, and an agent-TUI session injects its CLI command into this shell.env: withSpawnCwdEnv({- ...buildSafeEnv(), // filters process.env to prevent leaking inherited secrets (e.g. shell-inherited API keys)+ // `envReplace` callers own the WHOLE environment: buildSafeEnv is a+ // union, so a caller that has already narrowed its env to a strict+ // allowlist (a public-content review stage — see+ // agentTuiSpawning.js#createAgentTuiSession) would have every inherited+ // variable it just withheld added straight back underneath it.+ ...(options.envReplace ? {} : buildSafeEnv()), // filters process.env to prevent leaking inherited secrets (e.g. shell-inherited API keys)// options.env is the caller's explicit opt-in env (e.g. TUI provider API keys for codex/claude).// Callers are responsible for not passing vars they don't want visible inside attachable shells.// Single-user/single-instance deployment (Tailscale-only) makes this acceptable.