Skip to content

Commit d41eff8

Browse files
committed
feat: enhance native approval dialogs to show reasons without command details and improve question handling
1 parent 15e4d37 commit d41eff8

13 files changed

Lines changed: 219 additions & 22 deletions

‎crewcoder-agent/AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ Codex / OpenAI Responses:
246246
- If successful Codex output leaks raw SSE `data:` lines, normalize it back into CrewCoder assistant JSON before returning.
247247
- HTTP 200 does not prove a successful Codex turn: SSE `error`, `response.failed`, and `response.incomplete` events are terminal provider failures. A stream ending without assistant text, tool calls, or completion metadata is also a provider/protocol failure, never a successful `(empty Codex response)` placeholder.
248248
- Codex primarily uses official app-server durable threads stored under CrewCoder's isolated Codex home. Persist only the encoded thread/contract identifier in `providerSessionIds.codex`; never auth tokens. Local app-server turns use its native workspace-write shell/patch capabilities, and provider-native approval requests must route through the active host interaction channel. When `useProviderNativeFileTools` is false for an ACP/SDK virtual filesystem, skip app-server entirely and use the direct Responses transport so built-in local shell/patch tools cannot bypass the host filesystem. Preserve failed native `fileChange` error detail rather than projecting only its proposed patch. The direct connection-cached WebSocket and stateless SSE transports are guarded fallbacks; never replay after app-server `turn/start` has been sent.
249+
- Native Codex approval questions show the reason without appending the shell command; keep command details in tool events and preserve all provider approval decision values. See `docs/CODEX_CLI_PROVIDER.md`.
249250
- Native Codex command failures must preserve error text and otherwise report declined status or exit code. Empty `aggregatedOutput` is not a useful failure result and must not become an unexplained blank tool row.
250251
- Provider-native compaction is observable lifecycle, not merely a token-count change. Codex app-server `contextCompaction` item start/completion and legacy `thread/compacted` notifications must emit one deduplicated provider-compaction lifecycle; Claude `compact_boundary` must emit provider completion. ACP projects these through `_crewcoder/compaction_update` without claiming the CrewCoder durable transcript itself was rewritten.
251252
- Nested Codex compaction must use CrewCoder's resolved policy instead of app-server's smaller model default. Pass the known `contextWindow`, computed model-relative `autoCompactTokenLimit`, and `total` scope as process-only Codex app-server configuration; never persist these overrides into the user's Codex config. Sol, Terra, and Luna GPT-5.6 variants are all 1,050,000-token models and therefore compact at 630,000 tokens when normal auto-compaction is enabled.

‎crewcoder-agent/docs/CODEX_CLI_PROVIDER.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,13 @@ The binary is `codex` on `PATH`, or `CREWCODER_CODEX_PATH`. On Windows, npm inst
1414

1515
Over ACP, select it with a `codex-cli:<model>` model id.
1616

17+
## Approval questions
18+
19+
Native approval dialogs display the provider's reason as the wrapped question,
20+
without appending the raw shell command. The command remains in its tool transcript
21+
entry. Allow once, Allow session, and Decline keep their provider decision values;
22+
cancellation or an unrecognized answer declines the request.
23+
1724
## No fallback
1825

1926
If the app-server cannot start, the turn fails with the cause. It never falls back to the direct Responses transport, because that would need CrewCoder-owned credentials.

‎crewcoder-agent/src/providers/codex-app-server-provider.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -547,9 +547,9 @@ export function codexTurnPermissions(input: ProviderRunInput, hostedToolsOnly =
547547
async function approvalDecision(params: RpcRecord, input: ProviderRunInput): Promise<string> {
548548
if (!input.stream?.requestQuestion) return "decline";
549549
const reason = typeof params.reason === "string" ? params.reason : undefined;
550-
const command = typeof params.command === "string" ? params.command : undefined;
550+
551551
const answer = await input.stream.requestQuestion({
552-
title: [reason ?? `${input.provider.title} requests approval`, command].filter(Boolean).join("\n"),
552+
title: reason?.trim() || `${input.provider.title} requests approval`,
553553
options: [
554554
{ label: "Allow once", value: "accept" },
555555
{ label: "Allow session", value: "acceptForSession" },

‎crewcoder-agent/src/tests/codex-app-server-provider.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ const rl=readline.createInterface({input:process.stdin});rl.on('line',line=>{con
251251
expect(result?.exitCode).toBe(0);
252252
expect(thinking).toEqual(["Raw reasoning", " from content.", "I'll inspect the repository first."]);
253253
expect(assistant).toEqual(["Inspection complete."]);
254-
expect(questions).toEqual(["Inspect the repository\npwd"]);
254+
expect(questions).toEqual(["Inspect the repository"]);
255255
expect(JSON.parse(result?.text ?? "{}").content).toEqual([{ type: "text", text: "Inspection complete." }]);
256256
});
257257

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { runCodexCliProvider } from "../providers/codex-app-server-provider.js";
6+
import type { ModelQuestion } from "../core/model-client.js";
7+
import type { ProviderDefinition } from "../providers/types.js";
8+
9+
const originalPath = process.env.CREWCODER_CODEX_PATH;
10+
afterEach(() => {
11+
if (originalPath === undefined) delete process.env.CREWCODER_CODEX_PATH;
12+
else process.env.CREWCODER_CODEX_PATH = originalPath;
13+
});
14+
const provider: ProviderDefinition = {
15+
id: "codex-cli", title: "Codex CLI", kind: "builtin", runtime: "process", command: "codex", args: []
16+
};
17+
18+
describe("native approval questions", () => {
19+
it.each(["accept", "acceptForSession", "decline", undefined])("shows only the reason and preserves decision %s", async (answer) => {
20+
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "crew-question-"));
21+
// Node runs this extensionless fixture on Windows as well as POSIX.
22+
process.env.CREWCODER_CODEX_PATH = process.execPath;
23+
fs.writeFileSync(path.join(cwd, "app-server"), `
24+
const readline = require("node:readline");
25+
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
26+
readline.createInterface({ input: process.stdin }).on("line", (line) => {
27+
const message = JSON.parse(line);
28+
if (message.method === "initialize") send({ id: message.id, result: {} });
29+
else if (message.method === "thread/start") send({ id: message.id, result: { thread: { id: "test" } } });
30+
else if (message.method === "turn/start") {
31+
send({ id: message.id, result: {} });
32+
send({ id: 900, method: "item/commandExecution/requestApproval", params: {
33+
reason: "May I run the focused checks?", command: "powershell.exe -Command " + "source code ".repeat(1000)
34+
} });
35+
} else if (message.id === 900) {
36+
send({ method: "item/agentMessage/delta", params: { delta: message.result.decision } });
37+
send({ method: "turn/completed", params: { turn: { status: "completed" } } });
38+
}
39+
});
40+
`);
41+
const questions: ModelQuestion[] = [];
42+
try {
43+
const result = await runCodexCliProvider({
44+
provider, prompt: "check", cwd, model: "test",
45+
modelInput: { systemPrompt: "test", messages: [], availableTools: [] },
46+
stream: { requestQuestion: async (question) => { questions.push(question); return answer; } }
47+
});
48+
expect(result.exitCode).toBe(0);
49+
expect(result.stdout).toBe(answer ?? "decline");
50+
expect(questions).toEqual([{
51+
title: "May I run the focused checks?",
52+
options: [
53+
{ label: "Allow once", value: "accept" },
54+
{ label: "Allow session", value: "acceptForSession" },
55+
{ label: "Decline", value: "decline" }
56+
]
57+
}]);
58+
} finally {
59+
// Windows can retain the fixture's cwd briefly after SIGTERM.
60+
await fs.promises.rm(cwd, { recursive: true, force: true, maxRetries: 10, retryDelay: 30 });
61+
}
62+
});
63+
});

‎crewcoder-tui/AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,8 @@ While the backend bridge is running, ordinary non-command composer submissions m
268268

269269
Extension UI requests follow the same live control-channel pattern. `extension_ui_request` opens a focused popup (`ExtensionUiOverlay`) for `confirm`/`input`/`select`; the answer is written back over the `ui_response` control message via `CrewCoderProcessBridge.resolveUiRequest(requestId, value)`. The request renders as an `extension_ui` block that stays `pending` until `extension_ui_resolved`, then becomes `answered`/`cancelled`. `esc` cancels the request (sends `null`). `extension_ui_notify` renders inline (error/warning levels as error blocks, otherwise a system log). Do not collapse these into passive logs — they gate a live extension call.
270270

271+
Question dialogs show the question and reply controls without internal extension/request metadata. Keep reply controls visible even for long questions; PageUp/PageDown scrolls question text independently of selection. See `docs/QUESTIONS.md`. Transcript rows must normalize Windows line endings and contain terminal controls before painting; see `docs/TRANSCRIPT.md` and `src/tests/transcript-containment.test.ts`.
272+
271273
`ExtensionUiOverlay` must wrap, not truncate. The question title, the message, option labels, and option descriptions all wrap to the modal width; a description renders indented beneath its label rather than trailing it on the same row. Agent-authored questions are usually a full sentence and their options carry the rationale needed to choose, so a single truncated row hid the deciding text. `desiredHeight(width)` is measured from the wrapped content (App passes the modal `contentWidth`), and the option list scroll-windows to keep the whole selected option visible when the terminal is too short. Every rendered row of an option maps back to that option in `selectableRows`, so a click on a wrapped description row still selects it. Guarded by `src/tests/extension-ui-overlay.test.ts`.
272274

273275
## Live UI sandbox wiring

‎crewcoder-tui/docs/QUESTIONS.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Question dialogs
2+
3+
Question dialogs show the wrapped question and its reply controls. Confirmations
4+
offer Yes/No; selection requests show their supplied reply labels and wrapped
5+
descriptions; input requests show a text field. Internal extension IDs and request
6+
kinds stay out of the dialog.
7+
8+
The dialog measures its height from wrapped content. Long questions and messages
9+
scroll with PageUp/PageDown while keeping room for reply choices and keyboard
10+
hints. Up/Down changes the selected reply; Enter submits it. Clicking a wrapped
11+
option or description submits that option. Escape retains the existing cancellation
12+
behavior.
13+
14+
Codex native approval prompts use the reason as the question without appending
15+
the shell command. Command details remain in the tool transcript. The provider's
16+
Allow once / Allow session / Decline values retain their original meaning.
17+
18+
Regression coverage: `src/tests/extension-ui-overlay.test.ts`.

‎crewcoder-tui/docs/TRANSCRIPT.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,16 @@ visible screen in place.
3232
- `/repaint` (alias `/redraw`) clears terminal scrollback and reprints the
3333
settled transcript. Use it after a resize artifact.
3434

35+
## Row layout
36+
37+
Windows CRLF and bare carriage returns are normalized to transcript line breaks;
38+
tabs expand to four spaces before layout. Tool output loses terminal escape sequences
39+
before syntax highlighting. Final padded/truncated rows preserve TUI colors but
40+
contain cursor movement, erase commands, embedded newlines, and other control
41+
characters so output cannot overwrite neighboring rows.
42+
43+
Regression coverage: `src/tests/transcript-containment.test.ts`.
44+
3545
## Limitations
3646

3747
- New output (streaming tokens, spinner ticks) typically jumps the terminal

‎crewcoder-tui/src/components/ExtensionUiOverlay.ts‎

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ type OptionRow = { option: number; text: string; kind: "label" | "description" |
2020
const FOOTER_HEIGHT = 2;
2121
/** Upper bound on how tall the modal may ask to be before the App clamps it. */
2222
const MAX_DESIRED_HEIGHT = 30;
23-
const MAX_MESSAGE_LINES = 6;
23+
2424
const MAX_COMPONENT_LINES = 8;
2525

2626
/**
@@ -38,6 +38,8 @@ const MAX_COMPONENT_LINES = 8;
3838
export class ExtensionUiOverlay implements Component {
3939
private selected = 0;
4040
private value: string;
41+
private questionOffset = 0;
42+
private maxQuestionOffset = 0;
4143
/** Rendered line index -> selectable option index, for mouse clicks. */
4244
private selectableRows = new Map<number, number>();
4345

@@ -54,17 +56,25 @@ export class ExtensionUiOverlay implements Component {
5456
const lines: string[] = [];
5557
this.selectableRows = new Map();
5658

57-
for (const line of wrapText(this.request.title, width)) {
58-
lines.push(padRight(`${fg(ctx.theme.accent)}${bold()}${line}${reset()}`, width));
59-
}
60-
lines.push(padRight(`${fg(ctx.theme.muted)}[${this.request.extensionId}] ${this.request.uiKind}${reset()}`, width));
61-
59+
const question = wrapText(this.request.title, width).map((line) =>
60+
padRight(`${fg(ctx.theme.accent)}${bold()}${line}${reset()}`, width));
6261
if (this.request.message) {
63-
lines.push(emptyLine(width));
64-
for (const line of wrapText(this.request.message, width).slice(0, MAX_MESSAGE_LINES)) {
65-
lines.push(padRight(`${fg(ctx.theme.text)}${line}${reset()}`, width));
62+
question.push(emptyLine(width));
63+
for (const line of wrapText(this.request.message, width)) {
64+
question.push(padRight(`${fg(ctx.theme.text)}${line}${reset()}`, width));
6665
}
6766
}
67+
// Reserve room for replies before windowing an unusually long question.
68+
const replyRows = this.request.uiKind === "confirm" ? 2
69+
: this.request.uiKind === "select" ? Math.min(6, optionRows(this.request.options ?? [], width).length || 1)
70+
: 1;
71+
const questionBudget = Math.max(1, ctx.size.height - FOOTER_HEIGHT - replyRows - 1);
72+
const clipped = question.length > questionBudget;
73+
const questionHeight = Math.max(1, questionBudget - (clipped ? 1 : 0));
74+
this.maxQuestionOffset = Math.max(0, question.length - questionHeight);
75+
this.questionOffset = Math.min(this.questionOffset, this.maxQuestionOffset);
76+
lines.push(...question.slice(this.questionOffset, this.questionOffset + questionHeight));
77+
if (clipped) lines.push(padRight(`${fg(ctx.theme.muted)}PgUp/PgDn to read question${reset()}`, width));
6878

6979
lines.push(emptyLine(width));
7080
const bodyHeight = Math.max(1, ctx.size.height - lines.length - FOOTER_HEIGHT);
@@ -90,8 +100,8 @@ export class ExtensionUiOverlay implements Component {
90100
desiredHeight(width = 60): number {
91101
try {
92102
const safeWidth = Math.max(8, width);
93-
let height = wrapText(this.request.title, safeWidth).length + 1;
94-
if (this.request.message) height += 1 + Math.min(MAX_MESSAGE_LINES, wrapText(this.request.message, safeWidth).length);
103+
let height = wrapText(this.request.title, safeWidth).length;
104+
if (this.request.message) height += 1 + wrapText(this.request.message, safeWidth).length;
95105
height += 1 + FOOTER_HEIGHT;
96106

97107
if (this.request.uiKind === "confirm") height += 2;
@@ -107,6 +117,10 @@ export class ExtensionUiOverlay implements Component {
107117

108118
handleInput(event: KeyEvent): boolean {
109119
try {
120+
if (event.name === "pageup" || event.name === "pagedown") {
121+
this.questionOffset = Math.max(0, Math.min(this.maxQuestionOffset, this.questionOffset + (event.name === "pageup" ? -3 : 3)));
122+
return true;
123+
}
110124
if (event.name === "mouse" && event.mouse?.kind === "press") return this.handleMouse(event.mouse.y - 1);
111125
if (this.request.uiKind === "confirm") return this.handleConfirm(event);
112126
if (this.request.uiKind === "select") return this.handleSelect(event);
@@ -157,9 +171,9 @@ export class ExtensionUiOverlay implements Component {
157171
// ── confirm ──────────────────────────────────────────────────────────────
158172
private renderConfirm(ctx: RenderContext, lines: string[]): void {
159173
this.selectableRows.set(lines.length, 0);
160-
lines.push(this.renderAction(ctx, 0, "Yes", "confirm"));
174+
lines.push(this.renderAction(ctx, 0, "Yes"));
161175
this.selectableRows.set(lines.length, 1);
162-
lines.push(this.renderAction(ctx, 1, "No", "decline"));
176+
lines.push(this.renderAction(ctx, 1, "No"));
163177
}
164178

165179
private handleConfirm(event: KeyEvent): boolean {
@@ -299,13 +313,13 @@ export class ExtensionUiOverlay implements Component {
299313
return "type a value ↵ submit esc cancel";
300314
}
301315

302-
private renderAction(ctx: RenderContext, index: number, label: string, hint: string): string {
316+
private renderAction(ctx: RenderContext, index: number, label: string): string {
303317
const width = ctx.size.width;
304318
const active = this.selected === index;
305-
const text = `${active ? "●" : " "} ${label} ${hint}`;
319+
const text = `${active ? "●" : " "} ${label}`;
306320
if (active) return `${bg(ctx.theme.accent)}${fg(ctx.theme.background)}${bold()}${padRight(text, width)}${reset()}`;
307321
// Keep the inactive row on the same column as the bulleted active row.
308-
return padRight(` ${fg(index === 0 ? ctx.theme.success : ctx.theme.danger)}${label}${reset()} ${fg(ctx.theme.muted)}${hint}${reset()}`, width);
322+
return padRight(` ${fg(index === 0 ? ctx.theme.success : ctx.theme.danger)}${label}${reset()}`, width);
309323
}
310324
}
311325

‎crewcoder-tui/src/components/MainViewport.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { stripVTControlCharacters } from "node:util";
12
import type { Component, KeyEvent, RenderContext, RenderedImagePlacement } from "../tui/component.js";
23
import type { TuiDeclarativeComponent, TuiEventBlock } from "../state/tui-store.js";
34
import type { TuiState } from "../state/tui-store.js";
@@ -929,7 +930,7 @@ function toolFilePath(args?: Record<string, unknown>): string | undefined {
929930
}
930931

931932
function toolBody(block: Extract<TuiEventBlock, { type: "tool" }>): ToolBodyLine[] {
932-
const text = block.text?.trim();
933+
const text = block.text ? stripVTControlCharacters(block.text).trim() : undefined;
933934
if (text) return splitLines(text).map((line) => ({ text: truncate(line, 140), kind: "plain" as const }));
934935
const args = formatArgs(block.args);
935936
return args ? splitLines(args).map((line) => ({ text: line, kind: "plain" as const })) : [];

0 commit comments

Comments
 (0)