Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(approvals): add auto review and bot prompts (#133)

Leo01ae157f2ec9
diff --git a/apps/server/src/orchestration/Layers/BotPersistence.test.ts b/apps/server/src/orchestration/Layers/BotPersistence.test.ts
index 8b71b683b..5974ab721 100644
--- a/apps/server/src/orchestration/Layers/BotPersistence.test.ts
+++ b/apps/server/src/orchestration/Layers/BotPersistence.test.ts
@@ -637,11 +637,11 @@ it.layer(TestLayer)("bot persistence", (it) => {
const bots = (yield* snapshots.getShellSnapshot()).bots;
assert.equal(
bots.find((bot) => bot.id === BotId.make("bot-default-null"))?.runtimeMode,
- "approval-required",
+ "auto",
);
assert.equal(
bots.find((bot) => bot.id === BotId.make("bot-default-local"))?.runtimeMode,
- "approval-required",
+ "auto",
);
assert.equal(
bots.find((bot) => bot.id === BotId.make("bot-default-vercel"))?.runtimeMode,
diff --git a/apps/server/src/provider/AkeruMastraHarness.test.ts b/apps/server/src/provider/AkeruMastraHarness.test.ts
index 586a7f208..62af4a0e1 100644
--- a/apps/server/src/provider/AkeruMastraHarness.test.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.test.ts
@@ -52,19 +52,46 @@ describe("Akeru action classifier", () => {
['curl -X POST --data \'{"text":"hello"}\' https://example.com/messages', "send"],
["cd workspace && git push origin main", "publish"],
["find . -name '*.tmp' -delete", "delete"],
+ ["git reset --hard HEAD~1", "delete"],
+ ["git clean -fd", "delete"],
+ ["find . -name '*.tmp' -exec rm -rf {} \\;", "delete"],
["python -c 'import os; os.remove(\"tmp.txt\")'", "delete"],
+ ["shred important-file", "delete"],
+ ["sudo shred -u important-file", "delete"],
+ ["command shred -u important-file", "delete"],
+ ['bash -c "shred -u important-file"', "delete"],
+ ["dd if=/dev/zero of=important-file", "delete"],
+ ["sudo dd if=image.img of=/dev/disk4 bs=4m", "delete"],
+ ["dd if=/dev/zero > important-file", "delete"],
+ ['bash -c "dd if=/dev/zero 1> important-file"', "delete"],
+ ["mv replacement important-file", "delete"],
+ ["mv -f replacement important-file", "delete"],
+ ["command mv --force replacement important-file", "delete"],
+ ["bash -lc 'command shred -u important-file'", "delete"],
+ ["printf '%s\\n' important-file | xargs shred -u", "delete"],
+ ["printf '%s\\n' important-file | xargs rm -f", "delete"],
+ ["printf '%s\\n' important-file | xargs env rm -f", "delete"],
+ ["printf '%s\\n' empty-dir | xargs rmdir", "delete"],
+ ["printf '%s\\n' important-link | xargs unlink", "delete"],
+ ["find . -name important-file -exec shred -u {} \\;", "delete"],
+ ["find . -name important-file -exec env rm -f {} \\;", "delete"],
+ ["printf '%s\\n' important-file | xargs sh -c 'rm -f \"$1\"' _", "delete"],
+ ["find . -name important-file -exec sh -c 'rm -f \"$1\"' _ {} \\;", "delete"],
] as const)("classifies %s as %s", (command, action) => {
expect(criticalAkeruAction("execute_command", { command })).toBe(action);
expect(akeruActionNeedsApproval("execute_command", { command })).toBe(true);
});
- it.each(["bun test", "git status", "rg -n TODO apps", "cat README.md"])(
- "leaves ordinary local command %s unclassified",
- (command) => {
- expect(criticalAkeruAction("execute_command", { command })).toBeNull();
- expect(akeruActionNeedsApproval("execute_command", { command })).toBe(false);
- },
- );
+ it.each([
+ "bun test",
+ "git status",
+ "rg -n TODO apps",
+ "cat README.md",
+ 'echo "shred important-file"',
+ ])("leaves ordinary local command %s unclassified", (command) => {
+ expect(criticalAkeruAction("execute_command", { command })).toBeNull();
+ expect(akeruActionNeedsApproval("execute_command", { command })).toBe(false);
+ });
it("requires approval when nested input exceeds the inspection limit", () => {
let args: unknown = { action: "send" };
diff --git a/apps/server/src/provider/AkeruMastraHarness.ts b/apps/server/src/provider/AkeruMastraHarness.ts
index 11dec844f..be129d8f2 100644
--- a/apps/server/src/provider/AkeruMastraHarness.ts
+++ b/apps/server/src/provider/AkeruMastraHarness.ts
@@ -687,6 +687,21 @@ const CRITICAL_SHELL_ACTIONS: ReadonlyArray<readonly [AkeruCriticalAction, RegEx
"delete",
/(?:^|[;&|]\s*)(?:sudo\s+)?(?:rm|rmdir|unlink)\b|\b(?:drop|truncate)\s+(?:database|schema|table)\b|\bdelete\s+from\b/i,
],
+ ["delete", /(?:^|[;&|]\s*)(?:(?:sudo|command|builtin|exec|nohup)\s+)*shred\b/i],
+ [
+ "delete",
+ /(?:^|[;&|]\s*)(?:(?:sudo|command|builtin|exec|nohup)\s+)*dd\b[^\n;&|]*(?:\sof=(?:"[^"]*"|'[^']*'|[^\s;&|]+)|\s1?>>?\s*[^\s;&|]+)/i,
+ ],
+ ["delete", /(?:^|[;&|]\s*)(?:(?:sudo|command|builtin|exec|nohup)\s+)*mv\b/i],
+ ["delete", /(?:^|[;&|]\s*)git\s+(?:reset\s+--hard|clean\s+-[a-z]*[fdx][a-z]*)\b/i],
+ [
+ "delete",
+ /\bfind\b[^\n;&|]*\s-exec(?:dir)?\s+(?:(?:sudo|command|builtin|exec|nohup|env)\s+)*(?:rm|rmdir|shred|unlink)\b/i,
+ ],
+ [
+ "delete",
+ /\bxargs\b[^\n;&|]*\s(?:(?:sudo|command|builtin|exec|nohup)\s+)*(?:rm|rmdir|shred|unlink)\b/i,
+ ],
["publish", /(?:^|[;&|]\s*)git\s+push\b/i],
[
"production",
@@ -701,6 +716,10 @@ const CRITICAL_SHELL_ACTIONS: ReadonlyArray<readonly [AkeruCriticalAction, RegEx
/(?:^|[;&|]\s*)(?:(?:mail|mailx)\b|curl\b[^\n;&|]*(?:--data(?:-raw|-binary)?|-d\b|--form|-F\b|--request\s+post|-X\s*post))/i,
],
];
+const SHELL_COMMAND_WRAPPER_PATTERNS = [
+ /(?:^|[;&|]\s*)(?:(?:sudo|command|builtin|exec|nohup)\s+)*(?:\/(?:usr\/)?bin\/)?(?:ba|da|z)?sh\s+-[a-z]*c[a-z]*\s+(?:"((?:\\.|[^"])*)"|'([^']*)'|([^\s;&|]+))/gi,
+ /(?:\bxargs\b[^\n;&|]*?\s+|\bfind\b[^\n;&|]*\s-exec(?:dir)?\s+)(?:(?:sudo|command|builtin|exec|nohup)\s+)*(?:\/(?:usr\/)?bin\/)?(?:ba|da|z)?sh\s+-[a-z]*c[a-z]*\s+(?:"((?:\\.|[^"])*)"|'([^']*)'|([^\s;&|]+))/gi,
+];
function textTokens(value: string): ReadonlySet<string> {
return new Set(
@@ -727,10 +746,23 @@ function criticalActionFromText(value: string): AkeruCriticalAction | null {
return null;
}
-function criticalActionFromShellCommand(value: string): AkeruCriticalAction | null {
+function criticalActionFromShellCommand(
+ value: string,
+ wrapperDepth = 0,
+): AkeruCriticalAction | null {
for (const [action, pattern] of CRITICAL_SHELL_ACTIONS) {
if (pattern.test(value)) return action;
}
+ if (wrapperDepth < 5) {
+ for (const wrapperPattern of SHELL_COMMAND_WRAPPER_PATTERNS) {
+ for (const match of value.matchAll(wrapperPattern)) {
+ const nestedCommand = match[1] ?? match[2] ?? match[3];
+ if (!nestedCommand) continue;
+ const action = criticalActionFromShellCommand(nestedCommand, wrapperDepth + 1);
+ if (action) return action;
+ }
+ }
+ }
return criticalActionFromText(value);
}
diff --git a/apps/server/src/provider/Layers/AgentController.test.ts b/apps/server/src/provider/Layers/AgentController.test.ts
index 8ccdd21ae..1a0c8c92e 100644
--- a/apps/server/src/provider/Layers/AgentController.test.ts
+++ b/apps/server/src/provider/Layers/AgentController.test.ts
@@ -1932,6 +1932,7 @@ describe("AgentControllerLive", () => {
disconnect: vi.fn(async () => undefined),
getTools: vi.fn(() => ({
indexed_read: { mcp: { annotations: { readOnlyHint: true } } },
+ ask_user: { mcp: { annotations: {} } },
})),
getServerStatuses: vi.fn(() => []),
};
@@ -1972,6 +1973,7 @@ describe("AgentControllerLive", () => {
for (const [toolCallId, toolName, args] of [
["builtin-safe", "execute_command", { command: "bun test" }],
["indexed-read", "indexed_read", { query: "status" }],
+ ["connector-name-collision", "ask_user", { prompt: "Run connector action" }],
["missing-index", "new_mcp_tool", { value: "unknown" }],
] as const) {
mastra.emit({
@@ -1992,6 +1994,10 @@ describe("AgentControllerLive", () => {
decision: "approve",
});
expect(events.filter((event) => event.type === "request.opened")).toEqual([
+ expect.objectContaining({
+ requestId: "connector-name-collision",
+ payload: expect.objectContaining({ target: "ask_user" }),
+ }),
expect.objectContaining({
requestId: "missing-index",
payload: expect.objectContaining({ target: "new_mcp_tool" }),
@@ -2081,6 +2087,227 @@ describe("AgentControllerLive", () => {
);
});
+ it.effect("approves question tools without showing an approval request", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ const events: ProviderRuntimeEvent[] = [];
+ const collector = yield* controller.streamEvents.pipe(
+ Stream.runForEach((event) => Effect.sync(() => events.push(event))),
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* resolveCodex(controller);
+ yield* controller.startSession(codexThreadId, {
+ threadId: codexThreadId,
+ provider: ProviderDriverKind.make("codex"),
+ providerInstanceId: codexInstanceId,
+ cwd: process.cwd(),
+ modelSelection: codexSelection,
+ runtimeMode: "approval-required",
+ });
+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Ask me a question." });
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "question-1",
+ toolName: "ask_user",
+ args: {
+ question: "Pick one.",
+ options: [{ label: "First", description: "Choose the first option" }],
+ },
+ } as AgentControllerEvent);
+ yield* Effect.yieldNow;
+
+ expect(mastra.session.respondToToolApproval).toHaveBeenCalledWith({
+ toolCallId: "question-1",
+ decision: "approve",
+ });
+ expect(events.some((event) => event.type === "request.opened")).toBe(false);
+
+ mastra.emit({
+ type: "tool_suspended",
+ toolCallId: "question-1",
+ toolName: "ask_user",
+ args: {},
+ suspendPayload: {
+ question: "Pick one.",
+ options: [{ label: "First", description: "Choose the first option" }],
+ selectionMode: "single_select",
+ },
+ } as AgentControllerEvent);
+ yield* Effect.yieldNow;
+
+ expect(events).toContainEqual(
+ expect.objectContaining({
+ type: "user-input.requested",
+ requestId: "question-1",
+ payload: expect.objectContaining({
+ questions: [
+ expect.objectContaining({
+ question: "Pick one.",
+ options: [{ label: "First", description: "Choose the first option" }],
+ }),
+ ],
+ }),
+ }),
+ );
+ yield* Fiber.interrupt(collector);
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
+ it.effect("auto review allows safe commands and asks before destructive commands", () => {
+ const bridge = makeBridge();
+ const mastra = makeMastraHarness();
+ return provideController(
+ Effect.gen(function* () {
+ const controller = yield* AgentController;
+ const events: ProviderRuntimeEvent[] = [];
+ const collector = yield* controller.streamEvents.pipe(
+ Stream.runForEach((event) => Effect.sync(() => events.push(event))),
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* resolveCodex(controller);
+ yield* controller.startSession(codexThreadId, {
+ threadId: codexThreadId,
+ provider: ProviderDriverKind.make("codex"),
+ providerInstanceId: codexInstanceId,
+ cwd: process.cwd(),
+ modelSelection: codexSelection,
+ runtimeMode: "auto",
+ });
+ yield* controller.sendTurn({ threadId: codexThreadId, input: "Inspect, then clean up." });
+
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "read-safe",
+ toolName: "execute_command",
+ args: { command: "pwd" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "delete-risky",
+ toolName: "execute_command",
+ args: { command: "rm -rf ./temporary-output" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "shred-risky",
+ toolName: "execute_command",
+ args: { command: "shred important-file" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "wrapped-shred-risky",
+ toolName: "execute_command",
+ args: { command: 'bash -c "shred -u important-file"' },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "command-shred-risky",
+ toolName: "execute_command",
+ args: { command: "command shred -u important-file" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "xargs-shred-risky",
+ toolName: "execute_command",
+ args: { command: "printf '%s\\n' important-file | xargs shred -u" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "xargs-rm-risky",
+ toolName: "execute_command",
+ args: { command: "printf '%s\\n' important-file | xargs rm -f" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "xargs-env-rm-risky",
+ toolName: "execute_command",
+ args: { command: "printf '%s\\n' important-file | xargs env rm -f" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "xargs-shell-rm-risky",
+ toolName: "execute_command",
+ args: { command: "printf '%s\\n' important-file | xargs sh -c 'rm -f \"$1\"' _" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "find-shred-risky",
+ toolName: "execute_command",
+ args: { command: "find . -name important-file -exec shred -u {} \\;" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "find-env-rm-risky",
+ toolName: "execute_command",
+ args: { command: "find . -name important-file -exec env rm -f {} \\;" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "dd-risky",
+ toolName: "execute_command",
+ args: { command: "dd if=/dev/zero of=important-file" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "redirected-dd-risky",
+ toolName: "execute_command",
+ args: { command: "dd if=/dev/zero > important-file" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "plain-move-risky",
+ toolName: "execute_command",
+ args: { command: "mv replacement important-file" },
+ } as AgentControllerEvent);
+ mastra.emit({
+ type: "tool_approval_required",
+ toolCallId: "forced-move-risky",
+ toolName: "execute_command",
+ args: { command: "mv -f replacement important-file" },
+ } as AgentControllerEvent);
+ yield* Effect.yieldNow;
+
+ expect(mastra.session.respondToToolApproval).toHaveBeenCalledWith({
+ toolCallId: "read-safe",
+ decision: "approve",
+ });
+ for (const requestId of [
+ "delete-risky",
+ "shred-risky",
+ "wrapped-shred-risky",
+ "command-shred-risky",
+ "xargs-shred-risky",
+ "xargs-rm-risky",
+ "xargs-env-rm-risky",
+ "xargs-shell-rm-risky",
+ "find-shred-risky",
+ "find-env-rm-risky",
+ "dd-risky",
+ "redirected-dd-risky",
+ "plain-move-risky",
+ "forced-move-risky",
+ ]) {
+ expect(mastra.session.respondToToolApproval).not.toHaveBeenCalledWith({
+ toolCallId: requestId,
+ decision: "approve",
+ });
+ expect(events).toContainEqual(
+ expect.objectContaining({ type: "request.opened", requestId }),
+ );
+ }
+ yield* Fiber.interrupt(collector);
+ }),
+ bridge.service,
+ mastra.factory,
+ );
+ });
+
it.effect("keeps a suspended Mastra turn active until tool input resumes", () => {
const bridge = makeBridge();
const mastra = makeMastraHarness();
diff --git a/apps/server/src/provider/Layers/AgentController.ts b/apps/server/src/provider/Layers/AgentController.ts
index d64c4310d..0a3cf8830 100644
--- a/apps/server/src/provider/Layers/AgentController.ts
+++ b/apps/server/src/provider/Layers/AgentController.ts
@@ -140,6 +140,7 @@ const PLAN_MODE_ID = "plan";
const BUILTIN_MASTRA_TOOL_NAMES: ReadonlySet<string> = new Set(
Object.values(TOOL_NAME_OVERRIDES).map((tool) => tool.name),
);
+const APPROVAL_FREE_MASTRA_TOOL_NAMES: ReadonlySet<string> = new Set(["ask_user"]);
type MastraSession = AkeruMastraSession;
interface ResolvedEngine {
@@ -376,14 +377,11 @@ function permissionPolicy(
}
function mcpToolNeedsApproval(manager: McpManager | undefined, toolName: string): boolean {
- if (BUILTIN_MASTRA_TOOL_NAMES.has(toolName)) return false;
- if (!manager) return true;
- const tools = manager.getTools();
- if (!tools || !Object.hasOwn(tools, toolName)) return true;
- const tool = tools[toolName] as {
- readonly mcp?: { readonly annotations?: { readonly readOnlyHint?: boolean } };
- };
- return tool.mcp?.annotations?.readOnlyHint !== true;
+ const tool = manager?.getTools()?.[toolName] as
+ | { readonly mcp?: { readonly annotations?: { readonly readOnlyHint?: boolean } } }
+ | undefined;
+ if (tool) return tool.mcp?.annotations?.readOnlyHint !== true;
+ return !BUILTIN_MASTRA_TOOL_NAMES.has(toolName);
}
function approvalDetail(toolName: string, action: string | null, oneUse: boolean): string {
@@ -1357,10 +1355,22 @@ const make = (options?: AgentControllerLiveOptions) =>
if (!turn) return;
completeAssistantMessages(threadId, active, turn);
active.toolNames.set(event.toolCallId, event.toolName);
+ const mcpManager = sessionResources.getMcpManager(String(threadId));
+ const connectorTools = mcpManager?.getTools();
+ if (
+ APPROVAL_FREE_MASTRA_TOOL_NAMES.has(event.toolName) &&
+ (!connectorTools || !Object.hasOwn(connectorTools, event.toolName))
+ ) {
+ active.session.respondToToolApproval({
+ toolCallId: event.toolCallId,
+ decision: "approve",
+ });
+ return;
+ }
const action = criticalAkeruAction(event.toolName, event.args);
const oneUseApproval =
akeruActionNeedsApproval(event.toolName, event.args) ||
- mcpToolNeedsApproval(sessionResources.getMcpManager(String(threadId)), event.toolName);
+ mcpToolNeedsApproval(mcpManager, event.toolName);
if (
event.toolName !== AKERU_PRODUCT_FEEDBACK_TOOL_NAME &&
!oneUseApproval &&
diff --git a/apps/web/src/components/chat/ChatComposer.controls.test.tsx b/apps/web/src/components/chat/ChatComposer.controls.test.tsx
index dc8792c78..5a72ba438 100644
--- a/apps/web/src/components/chat/ChatComposer.controls.test.tsx
+++ b/apps/web/src/components/chat/ChatComposer.controls.test.tsx
@@ -139,7 +139,7 @@ describe("ChatComposer launch-control removal", () => {
expect(markup).toContain("rm -rf node_modules");
expect(markup).toContain("Allow once");
- expect(markup).toContain("Always allow");
+ expect(markup).toContain("Enable Auto Review");
expect(markup).toContain("Never");
expectNoLaunchControls(markup);
});
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index b9d01757f..9a3eef5cc 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -3196,7 +3196,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? (activePendingApproval?.detail ??
"Resolve this approval request to continue")
: activePendingProgress
- ? "Type your own answer, or leave this blank to use the selected option"
+ ? "Write a custom answer..."
: showPlanFollowUpPrompt && activeProposedPlan
? "Add feedback to refine the plan, or leave this blank to implement it"
: projectSelectionRequired
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx b/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx
index ed1768a1a..e44cc066f 100644
--- a/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx
+++ b/apps/web/src/components/chat/ComposerPendingApprovalActions.test.tsx
@@ -1,4 +1,8 @@
-import { AKERU_CREATE_ROUTINE_TOOL_NAME, ApprovalRequestId } from "@t3tools/contracts";
+import {
+ AKERU_CREATE_ROUTINE_TOOL_NAME,
+ AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
+ ApprovalRequestId,
+} from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
@@ -17,9 +21,10 @@ describe("ComposerPendingApprovalActions", () => {
expect(markup).toContain(">Cancel<");
expect(markup).toContain("Always allow this session");
expect(markup).not.toContain(">Always allow<");
- expect(markup).toContain("h-5");
- expect(markup).toContain("sm:text-[11px]");
- expect(markup).not.toContain("sm:h-6");
+ expect(markup).toContain("h-7");
+ expect(markup).toContain("sm:h-6");
+ expect(markup).toContain("bg-primary");
+ expect(markup).toContain("border-input");
});
it("shows only the approval choices advertised by an MCP server", () => {
@@ -56,7 +61,7 @@ describe("ComposerPendingApprovalActions", () => {
expect(markup).toContain(label);
});
- it("uses the three clear command permission choices", () => {
+ it("does not invent persistent permission for a one-use command", () => {
const markup = renderToStaticMarkup(
<ComposerPendingApprovalActions
requestId={ApprovalRequestId.make("approval-shell")}
@@ -70,12 +75,32 @@ describe("ComposerPendingApprovalActions", () => {
/>,
);
- expect(markup).toContain("Always allow");
+ expect(markup).not.toContain("Enable Auto Review");
expect(markup).toContain("Allow once");
expect(markup).toContain("Never");
expect(markup).not.toContain(">Decline<");
});
+ it("uses the three clear choices when session approval is available", () => {
+ const markup = renderToStaticMarkup(
+ <ComposerPendingApprovalActions
+ requestId={ApprovalRequestId.make("approval-shell-session")}
+ requestKind="command"
+ isResponding={false}
+ options={[
+ { decision: "acceptForSession", label: "Allow for session" },
+ { decision: "accept", label: "Allow" },
+ { decision: "decline", label: "Decline" },
+ ]}
+ onRespondToApproval={async () => undefined}
+ />,
+ );
+
+ expect(markup).toContain("Enable Auto Review");
+ expect(markup).toContain("Allow once");
+ expect(markup).toContain("Never");
+ });
+
it("uses one create or cancel choice for a routine", () => {
const markup = renderToStaticMarkup(
<ComposerPendingApprovalActions
@@ -93,7 +118,7 @@ describe("ComposerPendingApprovalActions", () => {
expect(markup).toContain("Create routine");
expect(markup).toContain(">Cancel<");
- expect(markup).not.toContain("Always allow");
+ expect(markup).not.toContain("Enable Auto Review");
expect(markup).not.toContain("Allow once");
expect(markup).not.toContain(">Never<");
@@ -108,6 +133,27 @@ describe("ComposerPendingApprovalActions", () => {
);
expect(fallbackMarkup).toContain("Create routine");
expect(fallbackMarkup).toContain(">Cancel<");
- expect(fallbackMarkup).not.toContain("Always allow");
+ expect(fallbackMarkup).not.toContain("Enable Auto Review");
+ });
+
+ it("keeps product feedback action labels", () => {
+ const markup = renderToStaticMarkup(
+ <ComposerPendingApprovalActions
+ requestId={ApprovalRequestId.make("approval-feedback")}
+ requestKind="command"
+ toolName={AKERU_PRODUCT_FEEDBACK_TOOL_NAME}
+ isResponding={false}
+ options={[
+ { decision: "accept", label: "Add to feedback draft" },
+ { decision: "decline", label: "Cancel" },
+ ]}
+ onRespondToApproval={async () => undefined}
+ />,
+ );
+
+ expect(markup).toContain("Add to feedback draft");
+ expect(markup).toContain(">Cancel<");
+ expect(markup).not.toContain("Allow once");
+ expect(markup).not.toContain(">Never<");
});
});
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx
index 19f31d3d4..2061c88b3 100644
--- a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx
+++ b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx
@@ -1,10 +1,12 @@
import {
AKERU_CREATE_ROUTINE_TOOL_NAME,
+ AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
type ApprovalRequestId,
type ProviderApprovalDecision,
type ProviderApprovalOption,
type ProviderRequestKind,
} from "@t3tools/contracts";
+import { ShieldCheckIcon } from "lucide-react";
import { memo } from "react";
import { Button } from "../ui/button";
@@ -20,7 +22,7 @@ interface ComposerPendingApprovalActionsProps {
) => Promise<unknown>;
}
-const APPROVAL_ACTION_CLASS_NAME = "font-normal";
+const APPROVAL_ACTION_CLASS_NAME = "font-medium";
const DEFAULT_APPROVAL_OPTIONS = [
{ decision: "cancel", label: "Cancel" },
{ decision: "decline", label: "Decline" },
@@ -37,8 +39,7 @@ function commandApprovalOptions(
): ReadonlyArray<ProviderApprovalOption> {
const always =
options.find((option) => option.decision === "acceptAlways") ??
- options.find((option) => option.decision === "acceptForSession") ??
- ({ decision: "acceptForSession", label: "Always allow" } as const);
+ options.find((option) => option.decision === "acceptForSession");
const once =
options.find((option) => option.decision === "accept") ??
({ decision: "accept", label: "Allow once" } as const);
@@ -48,12 +49,14 @@ function commandApprovalOptions(
({ decision: "decline", label: "Never" } as const);
return [
- { ...always, label: "Always allow" },
- { ...once, label: "Allow once" },
{ ...never, label: "Never" },
+ ...(always ? [{ ...always, label: "Enable Auto Review" } as const] : []),
+ { ...once, label: "Allow once" },
];
}
+const AUTO_REVIEW_DECISIONS = new Set(["acceptAlways", "acceptForSession"]);
+
export const ComposerPendingApprovalActions = memo(function ComposerPendingApprovalActions({
requestId,
requestKind,
@@ -65,30 +68,44 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
const visibleOptions =
toolName === AKERU_CREATE_ROUTINE_TOOL_NAME
? ROUTINE_APPROVAL_OPTIONS
- : requestKind === "command"
- ? commandApprovalOptions(options)
- : options;
+ : toolName === AKERU_PRODUCT_FEEDBACK_TOOL_NAME
+ ? options
+ : requestKind === "command"
+ ? commandApprovalOptions(options)
+ : options;
return (
<>
- {visibleOptions.map((option) => (
- <Button
- key={option.decision}
- size="micro"
- variant="ghost-muted"
- className={`${APPROVAL_ACTION_CLASS_NAME}${
- option.decision === "decline" && requestKind !== "command"
- ? " text-destructive-foreground [:hover,[data-pressed]]:text-destructive-foreground"
- : option.decision === "accept"
- ? " text-foreground"
- : ""
- }`}
- disabled={isResponding}
- onClick={() => void onRespondToApproval(requestId, option.decision)}
- >
- <span className="max-w-40 truncate">{option.label}</span>
- </Button>
- ))}
+ {visibleOptions.map((option) => {
+ const isAutoReview =
+ requestKind === "command" && AUTO_REVIEW_DECISIONS.has(option.decision);
+ return (
+ <Button
+ key={option.decision}
+ size="xs"
+ variant={
+ option.decision === "accept"
+ ? "default"
+ : option.decision === "acceptAlways" || option.decision === "acceptForSession"
+ ? "outline"
+ : "ghost-muted"
+ }
+ className={`${APPROVAL_ACTION_CLASS_NAME}${
+ option.decision === "decline" || option.decision === "cancel"
+ ? " text-destructive-foreground [:hover,[data-pressed]]:text-destructive-foreground"
+ : isAutoReview
+ ? " border-primary/45 bg-primary/[0.04] [--control-icon-color:var(--color-primary)] [:hover,[data-pressed]]:border-primary/70 [:hover,[data-pressed]]:bg-primary/[0.08]"
+ : ""
+ }`}
+ disabled={isResponding}
+ onClick={() => void onRespondToApproval(requestId, option.decision)}
+ {...(isAutoReview ? { title: "Let Auto Review decide the rest of this session" } : {})}
+ >
+ {isAutoReview ? <ShieldCheckIcon aria-hidden="true" /> : null}
+ <span className="max-w-40 truncate">{option.label}</span>
+ </Button>
+ );
+ })}
</>
);
});
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx b/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx
index 18c7eeda9..ab65e7ce4 100644
--- a/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx
+++ b/apps/web/src/components/chat/ComposerPendingApprovalPanel.test.tsx
@@ -5,7 +5,7 @@ import { describe, expect, it } from "vite-plus/test";
import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
describe("ComposerPendingApprovalPanel", () => {
- it("keeps the complete command readable in the compact row", () => {
+ it("shows a complete highlighted command without a duplicate disclosure", () => {
const detail = `bun run release -- ${"x".repeat(500)}\nsecond line`;
const markup = renderToStaticMarkup(
<ComposerPendingApprovalPanel
@@ -24,19 +24,65 @@ describe("ComposerPendingApprovalPanel", () => {
expect(markup).toContain('role="group"');
expect(markup).toContain('tabindex="0"');
expect(markup).toContain(detail);
- expect(markup).toContain("max-h-40");
+ expect(markup).toContain("max-h-28");
expect(markup).toContain("overflow-auto");
expect(markup).toContain("whitespace-pre-wrap");
expect(markup).toContain("[scrollbar-width:thin]");
expect(markup).toContain("[&amp;::-webkit-scrollbar]:h-1.5");
- expect(markup).toContain("truncate");
+ expect(markup).toContain("break-words");
expect(markup).not.toContain("line-clamp");
expect(markup).toContain("min-w-0");
- expect(markup).toContain("Expand");
- expect(markup).toContain("Collapse");
+ expect(markup).not.toContain("Expand");
+ expect(markup).not.toContain("Collapse");
+ expect(markup).not.toContain("<details");
expect(markup).not.toContain("Command approval requested");
});
+ it("drops the expander when a short command has nothing more to show", () => {
+ const markup = renderToStaticMarkup(
+ <ComposerPendingApprovalPanel
+ approval={{
+ requestId: ApprovalRequestId.make("approval-pwd"),
+ requestKind: "command",
+ createdAt: "2026-09-01T00:00:00.000Z",
+ detail: "pwd",
+ args: { command: "pwd" },
+ }}
+ pendingCount={1}
+ />,
+ );
+
+ expect(markup).toContain("pwd");
+ expect(markup).toContain('data-approval-detail="complete"');
+ expect(markup).not.toContain("Expand");
+ expect(markup).not.toContain("Collapse");
+ expect(markup).not.toContain("<details");
+ });
+
+ it("shows the folder, reason, and effects under the command", () => {
+ const markup = renderToStaticMarkup(
+ <ComposerPendingApprovalPanel
+ approval={{
+ requestId: ApprovalRequestId.make("approval-risky"),
+ requestKind: "command",
+ createdAt: "2026-09-01T00:00:00.000Z",
+ detail: "cd apps/web && rm -rf dist",
+ args: {
+ command: "cd apps/web && rm -rf dist",
+ cwd: "/tmp/work",
+ justification: "Clear the stale build",
+ },
+ }}
+ pendingCount={1}
+ />,
+ );
+
+ expect(markup).not.toContain("Expand");
+ expect(markup).toContain("Deletes files");
+ expect(markup).toContain("/tmp/work");
+ expect(markup).toContain("Clear the stale build");
+ });
+
it("falls back to the approval kind when the provider sends an empty detail", () => {
const markup = renderToStaticMarkup(
<ComposerPendingApprovalPanel
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx b/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx
index 42aab016b..0fc817498 100644
--- a/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx
+++ b/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx
@@ -4,19 +4,40 @@ import {
AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
} from "@t3tools/contracts";
import { type PendingApproval } from "../../session-logic";
+import { useTheme } from "../../hooks/useTheme";
+import { describeCommandApproval } from "~/lib/commandApprovalDetails";
import { cn } from "~/lib/utils";
+import { ShellCommandCode } from "./ShellCommandCode";
interface ComposerPendingApprovalPanelProps {
approval: PendingApproval;
pendingCount: number;
className?: string;
+ hideLabel?: boolean;
+}
+
+// The drawer already owns a surface, so the detail well is an inset fill rather
+// than a second bordered card.
+const DETAIL_SURFACE_CLASS_NAME = "rounded-lg bg-background/45 px-3 py-2.5";
+
+function CommandGlyph() {
+ return (
+ <span
+ aria-hidden="true"
+ className="flex size-5 shrink-0 items-center justify-center rounded-md bg-foreground/[0.07] font-mono text-[10px] text-muted-foreground"
+ >
+ $
+ </span>
+ );
}
export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprovalPanel({
approval,
pendingCount,
className,
+ hideLabel = false,
}: ComposerPendingApprovalPanelProps) {
+ const { resolvedTheme } = useTheme();
const isProductFeedback = approval.toolName === AKERU_PRODUCT_FEEDBACK_TOOL_NAME;
const isRoutine = approval.toolName === AKERU_CREATE_ROUTINE_TOOL_NAME;
const routineArgs =
@@ -65,7 +86,7 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
: approval.requestKind === "file-read"
? "File to read"
: "File change";
- const command =
+ const argsCommand =
approval.requestKind === "command" &&
approval.args &&
typeof approval.args === "object" &&
@@ -73,7 +94,17 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
typeof approval.args.command === "string"
? approval.args.command
: null;
+ const command =
+ approval.requestKind === "command"
+ ? (argsCommand ?? (approval.detail?.trim() ? approval.detail : fallbackLabel))
+ : null;
const detail = command ?? approval.detail ?? fallbackLabel;
+ const details = command ? describeCommandApproval(command, approval.args) : null;
+ const firstLine = detail.split("\n", 1)[0] ?? detail;
+ const detailLineCount = detail.split("\n").length;
+ // Only hide detail behind a disclosure when there is more than one screenful
+ // of it. A one-line path behind "Expand" wastes a click.
+ const detailFitsInline = detailLineCount <= 4 && detail.length <= 400;
if (isRoutine) {
return (
@@ -116,40 +147,100 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
className={cn("flex min-w-0 flex-1 flex-col gap-1.5", className)}
role="group"
>
- <div className="flex w-full min-w-0 items-center gap-2">
- <span className="text-xs font-medium text-foreground">{fallbackLabel}</span>
- {approval.appName ? (
- <span className="max-w-32 shrink truncate text-[11px] text-muted-foreground">
- {approval.appName}
- </span>
- ) : null}
- {pendingCount > 1 ? (
- <span className="ml-auto shrink-0 text-[10px] font-medium text-muted-foreground tabular-nums">
- 1/{pendingCount}
- </span>
- ) : null}
- </div>
- <details className="group w-full min-w-0">
- <summary className="flex cursor-pointer list-none items-center gap-2 rounded-md bg-foreground/[0.04] px-2.5 py-2 marker:content-none">
- <code className="min-w-0 flex-1 truncate font-mono text-[11px] text-foreground/85">
- {detail.split("\n", 1)[0]}
+ {!hideLabel ? (
+ <div className="flex w-full min-w-0 items-center gap-2">
+ <span className="text-xs font-medium text-foreground">{fallbackLabel}</span>
+ {approval.appName ? (
+ <span className="max-w-32 shrink truncate text-[11px] text-muted-foreground">
+ {approval.appName}
+ </span>
+ ) : null}
+ {pendingCount > 1 ? (
+ <span className="ml-auto shrink-0 text-[10px] font-medium text-muted-foreground tabular-nums">
+ 1/{pendingCount}
+ </span>
+ ) : null}
+ </div>
+ ) : null}
+ {command ? (
+ <>
+ <div
+ aria-label={detailAriaLabel}
+ className={cn("flex min-w-0 items-start gap-2", DETAIL_SURFACE_CLASS_NAME)}
+ role="region"
+ >
+ <CommandGlyph />
+ <code
+ className="block max-h-28 min-w-0 flex-1 overflow-auto whitespace-pre-wrap break-words font-mono text-xs leading-5 text-foreground/90 [scrollbar-width:thin] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70 [&::-webkit-scrollbar]:h-1.5"
+ data-approval-detail="complete"
+ tabIndex={0}
+ >
+ <ShellCommandCode command={command} theme={resolvedTheme} />
+ </code>
+ </div>
+ {details && (details.signals.length > 0 || details.workingDirectory || details.reason) ? (
+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 px-0.5">
+ {details.signals.map((signal) => (
+ <span
+ className="rounded-full bg-amber-400/15 px-2 py-0.5 text-[10px] font-medium text-amber-700 dark:text-amber-300"
+ key={signal}
+ >
+ {signal}
+ </span>
+ ))}
+ {details.workingDirectory ? (
+ <span className="min-w-0 truncate font-mono text-[11px] text-muted-foreground">
+ {details.workingDirectory}
+ </span>
+ ) : null}
+ {details.reason ? (
+ <span className="min-w-0 truncate text-[11px] text-muted-foreground">
+ {details.reason}
+ </span>
+ ) : null}
+ </div>
+ ) : null}
+ </>
+ ) : detailFitsInline ? (
+ <div className={cn("flex min-w-0 flex-col", DETAIL_SURFACE_CLASS_NAME)}>
+ <code
+ aria-label={detailAriaLabel}
+ className="block min-w-0 whitespace-pre-wrap break-words font-mono text-xs leading-5 text-foreground/90"
+ data-approval-detail="complete"
+ >
+ {detail}
</code>
- <span className="shrink-0 text-[10px] text-muted-foreground group-open:hidden">
- Expand
- </span>
- <span className="hidden shrink-0 text-[10px] text-muted-foreground group-open:inline">
- Collapse
- </span>
- </summary>
- <code
- aria-label={detailAriaLabel}
- className="mt-1.5 block max-h-40 overflow-auto whitespace-pre-wrap rounded-md bg-foreground/[0.04] px-2.5 py-2 font-mono text-[11px] text-foreground/85 [scrollbar-width:thin] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70 [&::-webkit-scrollbar]:h-1.5"
- data-approval-detail="complete"
- tabIndex={0}
- >
- {detail}
- </code>
- </details>
+ </div>
+ ) : (
+ <details className="group w-full min-w-0">
+ <summary
+ className={cn(
+ "flex cursor-pointer list-none items-center gap-2 marker:content-none",
+ DETAIL_SURFACE_CLASS_NAME,
+ )}
+ >
+ <code className="min-w-0 flex-1 truncate font-mono text-xs text-foreground/90">
+ {firstLine}
+ </code>
+ <span className="shrink-0 text-[11px] text-muted-foreground group-open:hidden">
+ {detailLineCount} lines
+ </span>
+ <span className="hidden shrink-0 text-[11px] text-muted-foreground group-open:inline">
+ Collapse
+ </span>
+ </summary>
+ <div className="mt-1.5 flex min-w-0 flex-col gap-2 rounded-lg bg-background/45 px-3 py-2.5">
+ <code
+ aria-label={detailAriaLabel}
+ className="block max-h-40 overflow-auto whitespace-pre-wrap font-mono text-xs leading-5 text-foreground/90 [scrollbar-width:thin] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70 [&::-webkit-scrollbar]:h-1.5"
+ data-approval-detail="complete"
+ tabIndex={0}
+ >
+ {detail}
+ </code>
+ </div>
+ </details>
+ )}
</div>
);
});
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
index b68e82eb4..84fef3b17 100644
--- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
+++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx
@@ -8,6 +8,7 @@ import {
import { CheckIcon, ChevronDownIcon } from "lucide-react";
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
import { Button } from "../ui/button";
+import { Kbd } from "../ui/kbd";
import { cn } from "~/lib/utils";
interface PendingUserInputPanelProps {
@@ -174,7 +175,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
return (
<Collapsible
- className="py-2"
+ className="pt-2 pb-2.5"
open={!isCollapsed}
onOpenChange={(open) => {
setCollapsedQuestionId(open ? null : activeQuestion.id);
@@ -186,15 +187,15 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
header label and the chevron still line up with the left and right
edges of the question text below. The negative block margin keeps the
taller hit area from pushing the panel down. */}
- <div className="flex items-center gap-1 px-1 sm:px-2">
+ <div className="flex items-center px-3 sm:px-4">
<CollapsibleTrigger
title={
isCollapsed ? "Show the question and its options" : "Hide the question and its options"
}
data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
- className="group -my-1 flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left outline-none transition-colors duration-150 hover:bg-muted/35 focus-visible:ring-1 focus-visible:ring-primary/25"
+ className="group -mx-1 flex min-w-0 flex-1 items-center gap-2 rounded-md px-1 py-1 text-left outline-none transition-colors duration-150 hover:text-foreground focus-visible:ring-1 focus-visible:ring-primary/25"
>
- <span className="text-xs font-medium text-muted-foreground group-hover:text-foreground/85">
+ <span className="text-[11px] font-medium text-muted-foreground group-hover:text-foreground/85">
{activeQuestion.header}
</span>
{prompt.questions.length > 1 ? (
@@ -225,12 +226,14 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
while the height animates, so the option buttons have to sit inside
that padding or their focus rings get shaved off at the edges. */}
<CollapsiblePanel className="px-3 sm:px-4">
- <div className="pt-2 pb-0.5">
- <p className="text-sm text-foreground/85">{activeQuestion.question}</p>
+ <div className="pt-1.5">
+ <p className="text-[15px] font-medium leading-5 text-foreground">
+ {activeQuestion.question}
+ </p>
{activeQuestion.multiSelect ? (
<p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
) : null}
- <div className="mt-2 space-y-0.5">
+ <div className="mt-3 space-y-1.5">
{activeQuestion.options.map((option, index) => {
const isOptimisticallySelected =
optimisticSingleSelect?.questionId === activeQuestion.id &&
@@ -240,32 +243,34 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
(!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
const shortcutKey = index < 9 ? index + 1 : null;
const className = cn(
- "group flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-primary/25",
+ "group flex w-full items-center gap-2.5 rounded-lg border px-2.5 py-2.5 text-left outline-none transition-[background-color,border-color,color] duration-150 focus-visible:ring-2 focus-visible:ring-primary/25",
isSelected
- ? "bg-muted/55 text-foreground"
- : "bg-transparent text-foreground/85 hover:bg-muted/30",
+ ? "border-primary/35 bg-primary/[0.08] text-foreground"
+ : "border-border/55 bg-background/25 text-foreground/85 hover:border-border/80 hover:bg-muted/30",
isResponding && "opacity-50 cursor-not-allowed",
!isResponding && "cursor-pointer",
);
const content = (
<>
- <div className="min-w-0 flex-1 flex flex-col gap-0.5">
- <span className="text-sm font-medium">{option.label}</span>
- {option.description && option.description !== option.label ? (
- <span className="text-secondary-label text-[11px]">{option.description}</span>
- ) : null}
- </div>
- {isSelected ? (
- <CheckIcon className="size-3.5 shrink-0 text-primary" />
- ) : shortcutKey !== null ? (
- <kbd
+ {shortcutKey !== null ? (
+ <Kbd
className={cn(
- "flex size-5 shrink-0 items-center justify-center text-[10px] font-medium text-muted-foreground tabular-nums",
+ "size-5 shrink-0 rounded-md bg-foreground/[0.06] px-0 text-[10px]",
+ isSelected && "bg-primary/15 text-primary",
)}
>
{shortcutKey}
- </kbd>
+ </Kbd>
) : null}
+ <div className="min-w-0 flex-1 flex flex-col gap-0.5">
+ <span className="text-[13px] font-medium leading-4">{option.label}</span>
+ {option.description && option.description !== option.label ? (
+ <span className="text-secondary-label text-[11px] leading-4">
+ {option.description}
+ </span>
+ ) : null}
+ </div>
+ {isSelected ? <CheckIcon className="size-3.5 shrink-0 text-primary" /> : null}
</>
);
return (
diff --git a/apps/web/src/components/chat/ShellCommandCode.tsx b/apps/web/src/components/chat/ShellCommandCode.tsx
new file mode 100644
index 000000000..83faecfbb
--- /dev/null
+++ b/apps/web/src/components/chat/ShellCommandCode.tsx
@@ -0,0 +1,76 @@
+import { getFiletypeFromFileName } from "@pierre/diffs";
+import { memo, Suspense, use, useMemo, type CSSProperties } from "react";
+
+import { resolveDiffThemeName } from "~/lib/diffRendering";
+import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";
+
+import { RenderErrorBoundary } from "../RenderErrorBoundary";
+
+/** Matches the language the diff viewer resolves for shell files, so both use one theme set. */
+const SHELL_LANGUAGE = getFiletypeFromFileName("command.sh");
+
+interface CodeToken {
+ readonly content: string;
+ readonly color?: string;
+ readonly fontStyle?: number;
+}
+
+function tokenStyle(token: CodeToken): CSSProperties {
+ const fontStyle = token.fontStyle ?? 0;
+ return {
+ ...(token.color ? { color: token.color } : {}),
+ ...(fontStyle & 1 ? { fontStyle: "italic" } : {}),
+ ...(fontStyle & 2 ? { fontWeight: 700 } : {}),
+ ...(fontStyle & 4 ? { textDecoration: "underline" } : {}),
+ };
+}
+
+function PlainCommand({ command }: { readonly command: string }) {
+ return <>{command}</>;
+}
+
+function HighlightedCommand(props: { readonly command: string; readonly theme: "light" | "dark" }) {
+ const highlighter = use(getSyntaxHighlighterPromise(SHELL_LANGUAGE));
+ const lines = useMemo(() => {
+ try {
+ return highlighter.codeToTokens(props.command, {
+ lang: SHELL_LANGUAGE,
+ theme: resolveDiffThemeName(props.theme),
+ }).tokens;
+ } catch {
+ return undefined;
+ }
+ }, [highlighter, props.command, props.theme]);
+
+ if (!lines) return <PlainCommand command={props.command} />;
+
+ return lines.map((tokens, lineIndex) => (
+ <span key={`line-${String(lineIndex)}`}>
+ {lineIndex > 0 ? "\n" : null}
+ {tokens.map((token: CodeToken, tokenIndex: number) => (
+ <span key={`token-${String(tokenIndex)}`} style={tokenStyle(token)}>
+ {token.content}
+ </span>
+ ))}
+ </span>
+ ));
+}
+
+/**
+ * Shell command text with syntax colors. Falls back to the same plain text while the
+ * highlighter loads and whenever it fails, so the row never blanks or shifts.
+ */
+export const ShellCommandCode = memo(function ShellCommandCode(props: {
+ readonly command: string;
+ readonly theme: "light" | "dark";
+}) {
+ const fallback = <PlainCommand command={props.command} />;
+
+ return (
+ <RenderErrorBoundary fallback={fallback}>
+ <Suspense fallback={fallback}>
+ <HighlightedCommand command={props.command} theme={props.theme} />
+ </Suspense>
+ </RenderErrorBoundary>
+ );
+});
diff --git a/apps/web/src/components/roster/BotApprovalPrompt.test.tsx b/apps/web/src/components/roster/BotApprovalPrompt.test.tsx
index 5415f80fd..209f8b224 100644
--- a/apps/web/src/components/roster/BotApprovalPrompt.test.tsx
+++ b/apps/web/src/components/roster/BotApprovalPrompt.test.tsx
@@ -1,11 +1,15 @@
-import { ApprovalRequestId } from "@t3tools/contracts";
+import {
+ AKERU_CREATE_ROUTINE_TOOL_NAME,
+ AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
+ ApprovalRequestId,
+} from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
import { BotApprovalPrompt } from "./BotApprovalPrompt";
describe("BotApprovalPrompt", () => {
- it("renders a one-use warning and only the hub-provided decisions", () => {
+ it("renders a compact one-use command review with only valid decisions", () => {
const markup = renderToStaticMarkup(
<BotApprovalPrompt
approval={{
@@ -26,13 +30,77 @@ describe("BotApprovalPrompt", () => {
);
expect(markup).toContain('data-testid="bot-approval-prompt"');
- expect(markup).toContain("This approval applies only to this action.");
- expect(markup).toContain("It cannot undo completed work.");
- expect(markup).toContain(">Decline<");
- expect(markup).toContain(">Allow<");
- expect(markup).not.toContain("Always allow");
+ expect(markup).toContain("Run this command?");
+ expect(markup).toContain("Runs once");
+ expect(markup).toContain("Allow once");
+ expect(markup).toContain("Never");
+ expect(markup).not.toContain("Enable Auto Review");
+ // Attaches to the top of the prompt box instead of floating in the transcript.
+ expect(markup).not.toContain("max-w-xl");
+ expect(markup).toContain("rounded-t-[1.65rem]");
+ expect(markup).toContain("border-b-transparent");
+ expect(markup).toContain("bg-primary");
expect(markup.match(/disabled=""/g)).toHaveLength(2);
expect(markup).toContain('role="alert"');
expect(markup).toContain("Could not answer approval.");
});
+
+ it("offers the three command decisions without extra status copy", () => {
+ const markup = renderToStaticMarkup(
+ <BotApprovalPrompt
+ approval={{
+ requestId: ApprovalRequestId.make("review-command-session"),
+ requestKind: "command",
+ createdAt: "2026-08-27T00:00:00.000Z",
+ args: { command: "pwd" },
+ options: [
+ { decision: "acceptForSession", label: "Allow for session" },
+ { decision: "accept", label: "Allow" },
+ { decision: "decline", label: "Decline" },
+ ],
+ }}
+ pendingCount={1}
+ responding={false}
+ error={null}
+ onRespond={vi.fn()}
+ />,
+ );
+
+ expect(markup).toContain("Enable Auto Review");
+ expect(markup).toContain("Allow once");
+ expect(markup).toContain("Never");
+ expect(markup).not.toContain("Auto Review paused");
+ });
+
+ it.each([
+ [AKERU_CREATE_ROUTINE_TOOL_NAME, "Review routine", "Create routine"],
+ [AKERU_PRODUCT_FEEDBACK_TOOL_NAME, "Review product feedback", "Add to feedback draft"],
+ ] as const)("keeps the specific review UI for %s", (toolName, heading, acceptLabel) => {
+ const markup = renderToStaticMarkup(
+ <BotApprovalPrompt
+ approval={{
+ requestId: ApprovalRequestId.make(`review-${toolName}`),
+ requestKind: "command",
+ toolName,
+ appName: "Safari",
+ createdAt: "2026-08-27T00:00:00.000Z",
+ detail: heading,
+ options: [
+ { decision: "accept", label: acceptLabel },
+ { decision: "decline", label: "Cancel" },
+ ],
+ }}
+ pendingCount={1}
+ responding={false}
+ error={null}
+ onRespond={vi.fn()}
+ />,
+ );
+
+ expect(markup).toContain(heading);
+ expect(markup).toContain("Safari");
+ expect(markup).toContain(acceptLabel);
+ expect(markup).not.toContain("Run this command?");
+ expect(markup).not.toContain("Runs once");
+ });
});
diff --git a/apps/web/src/components/roster/BotApprovalPrompt.tsx b/apps/web/src/components/roster/BotApprovalPrompt.tsx
index e0fdee39b..d91d43d35 100644
--- a/apps/web/src/components/roster/BotApprovalPrompt.tsx
+++ b/apps/web/src/components/roster/BotApprovalPrompt.tsx
@@ -1,4 +1,8 @@
-import type { ProviderApprovalDecision } from "@t3tools/contracts";
+import {
+ AKERU_CREATE_ROUTINE_TOOL_NAME,
+ AKERU_PRODUCT_FEEDBACK_TOOL_NAME,
+ type ProviderApprovalDecision,
+} from "@t3tools/contracts";
import type { PendingApproval } from "../../session-logic";
import { ComposerPendingApprovalActions } from "../chat/ComposerPendingApprovalActions";
@@ -17,31 +21,62 @@ export function BotApprovalPrompt({
readonly error: string | null;
readonly onRespond: (decision: ProviderApprovalDecision) => Promise<unknown>;
}) {
+ const isSpecialReview =
+ approval.toolName === AKERU_CREATE_ROUTINE_TOOL_NAME ||
+ approval.toolName === AKERU_PRODUCT_FEEDBACK_TOOL_NAME;
const oneUse =
- approval.options?.every(
+ !isSpecialReview &&
+ (approval.options?.every(
(option) => option.decision !== "acceptForSession" && option.decision !== "acceptAlways",
- ) ?? false;
+ ) ??
+ false);
+ const heading =
+ approval.toolName === AKERU_CREATE_ROUTINE_TOOL_NAME
+ ? "Review routine"
+ : approval.toolName === AKERU_PRODUCT_FEEDBACK_TOOL_NAME
+ ? "Review product feedback"
+ : approval.toolName === "Computer Use"
+ ? "Use the computer?"
+ : approval.requestKind === "command"
+ ? "Run this command?"
+ : approval.requestKind === "file-read"
+ ? "Read this file?"
+ : approval.requestKind === "file-change"
+ ? "Change this file?"
+ : "Allow app access?";
return (
<section
aria-label="Approval required"
- className="w-full max-w-2xl rounded-2xl border border-border bg-foreground/5 p-3"
+ className="mb-1 w-full rounded-t-[1.65rem] rounded-b-md border border-white/10 border-b-transparent bg-foreground/[0.12] px-3.5 pt-3 pb-2.5 dark:bg-white/[0.16]"
data-testid="bot-approval-prompt"
>
- <p className="text-sm font-medium">Approval required</p>
- {oneUse ? (
- <p className="mt-1 text-xs text-muted-foreground">
- This approval applies only to this action. It cannot undo completed work.
- </p>
- ) : null}
+ <div className="flex min-w-0 items-center gap-2">
+ <span aria-hidden="true" className="size-1.5 shrink-0 rounded-full bg-amber-400" />
+ <p className="text-sm font-semibold text-foreground">{heading}</p>
+ {approval.appName ? (
+ <span className="max-w-32 truncate text-xs text-muted-foreground">
+ {approval.appName}
+ </span>
+ ) : null}
+ {oneUse ? <span className="text-xs text-muted-foreground">Runs once</span> : null}
+ {pendingCount > 1 ? (
+ <span className="ml-auto text-[11px] font-medium text-muted-foreground tabular-nums">
+ 1 of {pendingCount}
+ </span>
+ ) : null}
+ </div>
<ComposerPendingApprovalPanel
approval={approval}
pendingCount={pendingCount}
className="mt-2"
+ hideLabel
/>
- <div className="mt-3 flex justify-end gap-1">
+ <div className="mt-2.5 flex flex-wrap items-center justify-end gap-1.5">
<ComposerPendingApprovalActions
requestId={approval.requestId}
+ requestKind={approval.requestKind}
+ toolName={approval.toolName}
isResponding={responding}
options={approval.options}
onRespondToApproval={(_requestId, decision) => onRespond(decision)}
diff --git a/apps/web/src/components/roster/BotPromptComposer.test.tsx b/apps/web/src/components/roster/BotPromptComposer.test.tsx
index 2d2c3652d..b043d0837 100644
--- a/apps/web/src/components/roster/BotPromptComposer.test.tsx
+++ b/apps/web/src/components/roster/BotPromptComposer.test.tsx
@@ -97,6 +97,42 @@ describe("bot prompt composer", () => {
expect(markup).not.toContain("max-w-4xl");
});
+ it("attaches a pending question above the custom answer field", () => {
+ const markup = renderToStaticMarkup(
+ <BotPromptComposer
+ botName="Akeru"
+ disabled={false}
+ pendingActionSlot={<div data-testid="pending-question">Question</div>}
+ placeholder="Write a custom answer..."
+ onSubmit={vi.fn(async () => true)}
+ />,
+ );
+
+ expect(markup).toContain('data-testid="pending-question"');
+ expect(markup).toContain('data-testid="bot-pending-action-motion"');
+ expect(markup).toContain('placeholder="Write a custom answer..."');
+ expect(markup).toContain("rounded-t-md border-t-transparent");
+ });
+
+ it("squares the prompt box against an approval rendered above it", () => {
+ const withoutApproval = renderToStaticMarkup(
+ <BotPromptComposer botName="Akeru" disabled={false} onSubmit={vi.fn(async () => true)} />,
+ );
+ const withApproval = renderToStaticMarkup(
+ <BotPromptComposer
+ botName="Akeru"
+ disabled={false}
+ pendingActionSlot={<div data-testid="approval-slot">Run this command?</div>}
+ onSubmit={vi.fn(async () => true)}
+ />,
+ );
+
+ expect(withoutApproval).not.toContain("rounded-t-md");
+ expect(withApproval).toContain('data-testid="approval-slot"');
+ expect(withApproval).toContain("rounded-t-md");
+ expect(withApproval).toContain("border-t-transparent");
+ });
+
it("renders an inert preview with the production composer", () => {
const markup = renderToStaticMarkup(
<BotPromptComposer
diff --git a/apps/web/src/components/roster/BotPromptComposer.tsx b/apps/web/src/components/roster/BotPromptComposer.tsx
index 6ed818a88..be20788f1 100644
--- a/apps/web/src/components/roster/BotPromptComposer.tsx
+++ b/apps/web/src/components/roster/BotPromptComposer.tsx
@@ -1,7 +1,8 @@
import { useAtomValue } from "@effect/atom-react";
import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts";
import { ArrowUpIcon, AtSignIcon, PaperclipIcon, PlusIcon } from "lucide-react";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { AnimatePresence, motion, useReducedMotion } from "motion/react";
+import { type ReactNode, useCallback, useEffect, useRef, useState } from "react";
import {
hydrateImagesFromPersisted,
@@ -109,6 +110,8 @@ export function BotPromptComposer({
disabled,
readOnly = false,
mentionBots = EMPTY_MENTION_BOTS,
+ pendingActionSlot = null,
+ placeholder,
onSubmit,
}: {
botName: string;
@@ -116,8 +119,12 @@ export function BotPromptComposer({
disabled: boolean;
readOnly?: boolean;
mentionBots?: ReadonlyArray<MentionBot>;
+ /** Rendered above the prompt box so a pending decision reads as part of the composer. */
+ pendingActionSlot?: ReactNode;
+ placeholder?: string;
onSubmit: (prompt: string, files: readonly File[], respondingBotId?: string) => Promise<boolean>;
}) {
+ const prefersReducedMotion = useReducedMotion();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const [draft, setDraft] = useState(() => (draftKey ? readBotDraft(draftKey) : ""));
const [attachments, setAttachments] = useState<BotPromptAttachment[]>([]);
@@ -515,12 +522,27 @@ export function BotPromptComposer({
onToggleMenu={() => setIsStashMenuOpen((open) => !open)}
/>
</ComposerBanner.Dock>
+ <AnimatePresence initial={false}>
+ {pendingActionSlot ? (
+ <motion.div
+ key="pending-action"
+ data-testid="bot-pending-action-motion"
+ initial={prefersReducedMotion ? false : { opacity: 0, y: 6 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={prefersReducedMotion ? { opacity: 1, y: 0 } : { opacity: 0, y: 4 }}
+ transition={{ duration: prefersReducedMotion ? 0 : 0.16, ease: "easeOut" }}
+ >
+ {pendingActionSlot}
+ </motion.div>
+ ) : null}
+ </AnimatePresence>
<div
data-testid="bot-prompt-composer"
data-expanded={expanded || undefined}
className={cn(
"relative flex min-h-13 flex-col overflow-hidden rounded-[1.65rem] border border-white/10 bg-foreground/[0.12] shadow-[0_12px_36px_-24px_rgb(0_0_0/80%)] transition-[min-height,border-radius,background-color,box-shadow] duration-200 ease-out dark:bg-white/[0.16]",
expanded && "min-h-28",
+ pendingActionSlot ? "rounded-t-md border-t-transparent" : undefined,
)}
>
<BotPromptAttachments
@@ -537,7 +559,7 @@ export function BotPromptComposer({
ref={promptInputRef}
aria-label={`Message ${botName}`}
data-testid="bot-prompt-input"
- placeholder={`Message ${botName}`}
+ placeholder={placeholder ?? `Message ${botName}`}
rows={1}
value={draft}
readOnly={readOnly}
diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsx
index 49c7fe380..03729ea62 100644
--- a/apps/web/src/components/roster/BotThreadLanding.tsx
+++ b/apps/web/src/components/roster/BotThreadLanding.tsx
@@ -34,6 +34,7 @@ import ChatMarkdown from "../ChatMarkdown";
import { WorkspacePageHeader } from "../WorkspacePageHeader";
import { BotActivityStatus } from "./BotActivityStatus";
import { BotApprovalPrompt } from "./BotApprovalPrompt";
+import { BotUserInputPrompt } from "./BotUserInputPrompt";
import { BotInboxAlertStack } from "./BotInboxAlertStack";
import { BotAvatarView } from "./BotAvatarView";
import { BotConversationScrollArea } from "./BotConversationScrollArea";
@@ -170,6 +171,7 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
});
const messages = visibleBotChatMessages(runtime.messages, working);
const pendingApproval = approvalState.pendingApproval;
+ const pendingUserInput = runtime.pendingUserInputs[0] ?? null;
const inboxItems = selectOpenBotInboxItems(inboxQuery.data?.inbox ?? [], new Set([bot.id]));
const delegations = runtime.linkedThreadRef
? (snapshot?.delegations.filter(
@@ -264,15 +266,6 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
),
)
)}
- {pendingApproval ? (
- <BotApprovalPrompt
- approval={pendingApproval}
- pendingCount={approvalState.pendingCount}
- responding={approvalState.responding}
- error={approvalState.responseError}
- onRespond={(decision) => approvalState.respond(pendingApproval.requestId, decision)}
- />
- ) : null}
{delegations.map((delegation) => (
<DelegationCard
key={delegation.delegationId}
@@ -299,8 +292,33 @@ export function BotThreadLanding({ botId }: { readonly botId: string }) {
<BotPromptComposer
botName={bot.name}
draftKey={bot.id}
+ pendingActionSlot={
+ pendingApproval ? (
+ <BotApprovalPrompt
+ approval={pendingApproval}
+ pendingCount={approvalState.pendingCount}
+ responding={approvalState.responding}
+ error={approvalState.responseError}
+ onRespond={(decision) =>
+ approvalState.respond(pendingApproval.requestId, decision)
+ }
+ />
+ ) : pendingUserInput ? (
+ <BotUserInputPrompt
+ pendingUserInputs={runtime.pendingUserInputs}
+ respondingRequestIds={runtime.respondingRequestIds}
+ answers={runtime.pendingUserInputAnswers}
+ questionIndex={runtime.pendingUserInputQuestionIndex}
+ onToggleOption={runtime.selectPendingUserInputOption}
+ onSelectSingleOption={runtime.selectPendingUserInputOption}
+ onAdvance={runtime.advancePendingUserInput}
+ />
+ ) : null
+ }
+ {...(pendingUserInput ? { placeholder: "Write a custom answer..." } : {})}
disabled={
pendingApproval !== null ||
+ runtime.respondingRequestIds.length > 0 ||
voiceCall.activeCall?.botId === bot.id ||
voiceCall.startingBotId === bot.id ||
stickyEngine === null ||
diff --git a/apps/web/src/components/roster/BotUserInputPrompt.test.tsx b/apps/web/src/components/roster/BotUserInputPrompt.test.tsx
new file mode 100644
index 000000000..a669a3e70
--- /dev/null
+++ b/apps/web/src/components/roster/BotUserInputPrompt.test.tsx
@@ -0,0 +1,65 @@
+import { ApprovalRequestId } from "@t3tools/contracts";
+import type { ReactElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+import type { PendingUserInput } from "../../session-logic";
+import { BotUserInputPrompt } from "./BotUserInputPrompt";
+
+const prompt: PendingUserInput = {
+ requestId: ApprovalRequestId.make("request-1"),
+ createdAt: "2026-09-01T00:00:00.000Z",
+ questions: [
+ {
+ id: "review-mode",
+ header: "Review mode",
+ question: "How should Auto Review handle commands that change files?",
+ options: [
+ {
+ label: "Review risky commands",
+ description: "Allow routine commands and ask before risky changes.",
+ },
+ ],
+ multiSelect: false,
+ },
+ ],
+};
+
+describe("BotUserInputPrompt", () => {
+ it("renders the pending question as an attached composer action", () => {
+ const markup = renderToStaticMarkup(
+ <BotUserInputPrompt
+ pendingUserInputs={[prompt]}
+ respondingRequestIds={[]}
+ answers={{}}
+ questionIndex={0}
+ onToggleOption={vi.fn()}
+ onSelectSingleOption={vi.fn()}
+ onAdvance={vi.fn()}
+ />,
+ );
+
+ expect(markup).toContain('data-testid="bot-user-input-prompt"');
+ expect(markup).toContain("How should Auto Review handle commands that change files?");
+ expect(markup).toContain("Review risky commands");
+ });
+
+ it("uses one callback for single-select answers", () => {
+ const onToggleOption = vi.fn();
+ const onSelectSingleOption = vi.fn();
+ const element = BotUserInputPrompt({
+ pendingUserInputs: [prompt],
+ respondingRequestIds: [],
+ answers: {},
+ questionIndex: 0,
+ onToggleOption,
+ onSelectSingleOption,
+ onAdvance: vi.fn(),
+ });
+ const panel = element.props.children as ReactElement<{
+ onSelectSingleOption?: (questionId: string, optionLabel: string) => void;
+ }>;
+
+ expect(panel.props.onSelectSingleOption).toBe(onSelectSingleOption);
+ });
+});
diff --git a/apps/web/src/components/roster/BotUserInputPrompt.tsx b/apps/web/src/components/roster/BotUserInputPrompt.tsx
new file mode 100644
index 000000000..f7e04b892
--- /dev/null
+++ b/apps/web/src/components/roster/BotUserInputPrompt.tsx
@@ -0,0 +1,41 @@
+import { type ApprovalRequestId } from "@t3tools/contracts";
+
+import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
+import type { PendingUserInput } from "../../session-logic";
+import { ComposerPendingUserInputPanel } from "../chat/ComposerPendingUserInputPanel";
+
+export function BotUserInputPrompt({
+ pendingUserInputs,
+ respondingRequestIds,
+ answers,
+ questionIndex,
+ onToggleOption,
+ onSelectSingleOption,
+ onAdvance,
+}: {
+ readonly pendingUserInputs: PendingUserInput[];
+ readonly respondingRequestIds: ApprovalRequestId[];
+ readonly answers: Record<string, PendingUserInputDraftAnswer>;
+ readonly questionIndex: number;
+ readonly onToggleOption: (questionId: string, optionLabel: string) => void;
+ readonly onSelectSingleOption: (questionId: string, optionLabel: string) => void;
+ readonly onAdvance: () => void;
+}) {
+ return (
+ <section
+ aria-label="Question"
+ className="mb-1.5 w-full rounded-t-[1.65rem] rounded-b-lg border border-white/10 bg-foreground/[0.12] dark:bg-white/[0.16]"
+ data-testid="bot-user-input-prompt"
+ >
+ <ComposerPendingUserInputPanel
+ pendingUserInputs={pendingUserInputs}
+ respondingRequestIds={respondingRequestIds}
+ answers={answers}
+ questionIndex={questionIndex}
+ onToggleOption={onToggleOption}
+ onSelectSingleOption={onSelectSingleOption}
+ onAdvance={onAdvance}
+ />
+ </section>
+ );
+}
diff --git a/apps/web/src/components/roster/GroupThreadLanding.tsx b/apps/web/src/components/roster/GroupThreadLanding.tsx
index 3092a4347..d30515bb6 100644
--- a/apps/web/src/components/roster/GroupThreadLanding.tsx
+++ b/apps/web/src/components/roster/GroupThreadLanding.tsx
@@ -17,6 +17,7 @@ import { WorkspacePageHeader } from "../WorkspacePageHeader";
import { ThreadErrorBanner } from "../chat/ThreadErrorBanner";
import { BotActivityStatus } from "./BotActivityStatus";
import { BotApprovalPrompt } from "./BotApprovalPrompt";
+import { BotUserInputPrompt } from "./BotUserInputPrompt";
import { BotInboxAlertStack } from "./BotInboxAlertStack";
import { BotAvatarView } from "./BotAvatarView";
import { BotConversationScrollArea } from "./BotConversationScrollArea";
@@ -66,9 +67,11 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
if (!group) return null;
const members = groupBotMembers(group, bots).filter((bot) => bot.archivedAt === null);
const boss = resolveAvailableGroupBoss(members, group.bossBotId);
- const working = runtime.sending || presence === "working";
+ const working =
+ runtime.sending || runtime.respondingRequestIds.length > 0 || presence === "working";
const messages = visibleBotChatMessages(runtime.messages);
const pendingApproval = approvalState.pendingApproval;
+ const pendingUserInput = runtime.pendingUserInputs[0] ?? null;
const activeBot = members.find((bot) => bot.id === runtime.respondingBotId) ?? boss;
const inboxItems = selectOpenBotInboxItems(
inboxQuery.data?.inbox ?? [],
@@ -180,15 +183,6 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
);
})
)}
- {pendingApproval ? (
- <BotApprovalPrompt
- approval={pendingApproval}
- pendingCount={approvalState.pendingCount}
- responding={approvalState.responding}
- error={approvalState.responseError}
- onRespond={(decision) => approvalState.respond(pendingApproval.requestId, decision)}
- />
- ) : null}
{delegations.map((delegation) => (
<DelegationCard
key={delegation.delegationId}
@@ -222,9 +216,32 @@ export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {
<BotPromptComposer
botName={group.name}
draftKey={`group:${group.id}`}
+ pendingActionSlot={
+ pendingApproval ? (
+ <BotApprovalPrompt
+ approval={pendingApproval}
+ pendingCount={approvalState.pendingCount}
+ responding={approvalState.responding}
+ error={approvalState.responseError}
+ onRespond={(decision) => approvalState.respond(pendingApproval.requestId, decision)}
+ />
+ ) : pendingUserInput ? (
+ <BotUserInputPrompt
+ pendingUserInputs={runtime.pendingUserInputs}
+ respondingRequestIds={runtime.respondingRequestIds}
+ answers={runtime.pendingUserInputAnswers}
+ questionIndex={runtime.pendingUserInputQuestionIndex}
+ onToggleOption={runtime.selectPendingUserInputOption}
+ onSelectSingleOption={runtime.selectPendingUserInputOption}
+ onAdvance={runtime.advancePendingUserInput}
+ />
+ ) : null
+ }
+ {...(pendingUserInput ? { placeholder: "Write a custom answer..." } : {})}
disabled={
runtime.sending ||
pendingApproval !== null ||
+ runtime.respondingRequestIds.length > 0 ||
!runtime.groupReady ||
!runtime.bootstrapped ||
runtime.defaultProject === null ||
diff --git a/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx b/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
index 615ae297b..7dd293323 100644
--- a/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
+++ b/apps/web/src/components/roster/ThreadLanding.delegations.test.tsx
@@ -12,6 +12,7 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { reactHookHarness as hooks } from "../../test/reactHookHarness";
import { visitElements } from "../../test/reactElementTree";
import type { Bot, Group } from "./types";
+import type { PendingUserInput } from "../../session-logic";
const mocks = vi.hoisted(() => ({
providersAtom: Symbol("providers"),
@@ -20,6 +21,7 @@ const mocks = vi.hoisted(() => ({
snapshot: null as OrchestrationShellSnapshot | null,
bots: [] as Bot[],
groups: [] as Group[],
+ groupPendingUserInputs: [] as PendingUserInput[],
}));
vi.mock("react", async (importOriginal) => {
@@ -98,6 +100,11 @@ vi.mock("./useBotThreadRuntime", () => ({
error: null,
latestTurn: null,
defaultProject: null,
+ pendingUserInputs: [],
+ pendingUserInputAnswers: {},
+ pendingUserInputQuestionIndex: 0,
+ selectPendingUserInputOption: vi.fn(),
+ advancePendingUserInput: vi.fn(),
botReady: true,
bootstrapped: true,
linkedThreadRef: {
@@ -110,6 +117,7 @@ vi.mock("./useBotThreadRuntime", () => ({
vi.mock("./useGroupThreadRuntime", () => ({
useGroupThreadRuntime: () => ({
sending: false,
+ respondingRequestIds: [],
messages: [],
error: null,
defaultProject: null,
@@ -120,6 +128,11 @@ vi.mock("./useGroupThreadRuntime", () => ({
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-parent"),
},
+ pendingUserInputs: mocks.groupPendingUserInputs,
+ pendingUserInputAnswers: {},
+ pendingUserInputQuestionIndex: 0,
+ selectPendingUserInputOption: vi.fn(),
+ advancePendingUserInput: vi.fn(),
send: vi.fn(),
}),
}));
@@ -127,6 +140,7 @@ vi.mock("./useGroupThreadRuntime", () => ({
import { BotThreadLanding } from "./BotThreadLanding";
import { DelegationCard } from "./DelegationCard";
import { GroupThreadLanding } from "./GroupThreadLanding";
+import { BotUserInputPrompt } from "./BotUserInputPrompt";
const decodeDelegation = Schema.decodeUnknownSync(AkeruDelegationRecord);
const parentBot: Bot = {
@@ -203,6 +217,7 @@ describe("thread landing delegations", () => {
hooks.reset();
mocks.bots = [parentBot, childBot];
mocks.groups = [group];
+ mocks.groupPendingUserInputs = [];
mocks.snapshot = {
snapshotSequence: 1,
bots: [],
@@ -227,4 +242,31 @@ describe("thread landing delegations", () => {
expect(card?.props.delegation.delegationId).toBe("matching");
expect(card?.props.childBot).toBe(childBot);
});
+
+ it("renders pending provider questions in group threads", () => {
+ mocks.groupPendingUserInputs = [
+ {
+ requestId: "group-question" as PendingUserInput["requestId"],
+ createdAt: "2026-09-01T00:00:00.000Z",
+ questions: [
+ {
+ id: "scope",
+ header: "Scope",
+ question: "Which workspace should I use?",
+ options: [{ label: "Current", description: "Use the current workspace." }],
+ multiSelect: false,
+ },
+ ],
+ },
+ ];
+
+ hooks.beginRender();
+ const prompt = visitElements(
+ GroupThreadLanding({ groupId: group.id }),
+ (element) => element.type === BotUserInputPrompt,
+ ) as ReactElement<Parameters<typeof BotUserInputPrompt>[0]> | null;
+
+ expect(prompt?.props.pendingUserInputs).toEqual(mocks.groupPendingUserInputs);
+ expect(prompt?.props.onSelectSingleOption).toBe(prompt?.props.onToggleOption);
+ });
});
diff --git a/apps/web/src/components/roster/botSandbox.test.ts b/apps/web/src/components/roster/botSandbox.test.ts
index 60ac6e42e..9b3676861 100644
--- a/apps/web/src/components/roster/botSandbox.test.ts
+++ b/apps/web/src/components/roster/botSandbox.test.ts
@@ -15,8 +15,8 @@ describe("botSandbox", () => {
expect(botSandboxChoice("vercel")).toBe("vercel");
});
- it("asks before local tools unless full access is enabled", () => {
- expect(DEFAULT_BOT_RUNTIME_MODE).toBe("approval-required");
+ it("auto-reviews local tools unless another mode is selected", () => {
+ expect(DEFAULT_BOT_RUNTIME_MODE).toBe("auto");
expect(resolveBotRuntimeMode(null, "approval-required")).toBe("approval-required");
expect(resolveBotRuntimeMode("local", "full-access")).toBe("full-access");
});
diff --git a/apps/web/src/components/roster/useGroupThreadRuntime.ts b/apps/web/src/components/roster/useGroupThreadRuntime.ts
index 5bb3acacd..2ca240d75 100644
--- a/apps/web/src/components/roster/useGroupThreadRuntime.ts
+++ b/apps/web/src/components/roster/useGroupThreadRuntime.ts
@@ -3,6 +3,7 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import {
BotId,
+ type ApprovalRequestId,
EnvironmentId,
GroupId,
ProviderInstanceId,
@@ -10,7 +11,7 @@ import {
type ModelSelection,
type ScopedThreadRef,
} from "@t3tools/contracts";
-import { useCallback, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { usePrimarySettings } from "../../hooks/useSettings";
import { newMessageId, newThreadId } from "../../lib/utils";
@@ -19,6 +20,7 @@ import { environmentGroupsAtom } from "../../state/bots";
import {
useAllEnvironmentShellsBootstrapped,
useProjects,
+ useThreadActivities,
useThreadMessages,
useThreadShell,
useThreadShells,
@@ -27,6 +29,13 @@ import { usePrimaryEnvironmentId } from "../../state/environments";
import { primaryServerProvidersAtom } from "../../state/server";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
+import {
+ applyPendingUserInputSingleSelect,
+ buildPendingUserInputAnswers,
+ type PendingUserInputDraftAnswer,
+ togglePendingUserInputOptionSelection,
+} from "../../pendingUserInput";
+import { derivePendingUserInputs } from "../../session-logic";
import { DEFAULT_INTERACTION_MODE } from "../../types";
import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
import { resolveBotRuntimeMode } from "./botSandbox";
@@ -109,6 +118,8 @@ export function useGroupThreadRuntime(groupId: string) {
}
if (linkedThreadRef) retainedThreadRef.current.threadRef = linkedThreadRef;
const messages = useThreadMessages(linkedThreadRef);
+ const activities = useThreadActivities(linkedThreadRef);
+ const pendingUserInputs = useMemo(() => derivePendingUserInputs(activities), [activities]);
const defaultProject = useMemo(
() =>
bootstrapped && primaryEnvironmentId
@@ -134,14 +145,67 @@ export function useGroupThreadRuntime(groupId: string) {
reportFailure: false,
});
const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });
+ const respondToUserInputCommand = useAtomCommand(threadEnvironment.respondToUserInput, {
+ reportFailure: false,
+ });
const groupReady = serverGroups.some((candidate) => candidate.id === groupId);
const sendInFlightRef = useRef(false);
const [sending, setSending] = useState(false);
+ const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
+ const respondingRequestIdsRef = useRef(new Set<ApprovalRequestId>());
+ const singleSelectInFlightRef = useRef<string | null>(null);
+ const [pendingUserInputAnswers, setPendingUserInputAnswers] = useState<
+ Record<string, PendingUserInputDraftAnswer>
+ >({});
+ const [pendingUserInputQuestionIndex, setPendingUserInputQuestionIndex] = useState(0);
const [error, setError] = useState<string | null>(null);
+ const submitPendingUserInput = useCallback(
+ async (
+ requestId: ApprovalRequestId,
+ answers: Record<string, string | string[]>,
+ ): Promise<boolean> => {
+ if (!linkedThreadRef || respondingRequestIdsRef.current.has(requestId)) return false;
+ respondingRequestIdsRef.current.add(requestId);
+ setRespondingRequestIds((current) =>
+ current.includes(requestId) ? current : [...current, requestId],
+ );
+ const result = await respondToUserInputCommand({
+ environmentId: linkedThreadRef.environmentId,
+ input: { threadId: linkedThreadRef.threadId, requestId, answers },
+ });
+ if (result._tag === "Failure") {
+ respondingRequestIdsRef.current.delete(requestId);
+ setRespondingRequestIds((current) => current.filter((id) => id !== requestId));
+ setError(errorMessage(result));
+ return false;
+ }
+ return true;
+ },
+ [linkedThreadRef, respondToUserInputCommand],
+ );
+
const send = useCallback(
async (prompt: string, files: readonly File[], requestedBotId?: string): Promise<boolean> => {
if (sendInFlightRef.current) return false;
+ const pendingUserInput = pendingUserInputs[0];
+ if (pendingUserInput && linkedThreadRef && files.length === 0) {
+ if (respondingRequestIds.includes(pendingUserInput.requestId)) return false;
+ const question = pendingUserInput.questions[pendingUserInputQuestionIndex];
+ if (!question || !prompt.trim()) return false;
+ const nextAnswers = {
+ ...pendingUserInputAnswers,
+ [question.id]: { customAnswer: prompt.trim() },
+ };
+ setPendingUserInputAnswers(nextAnswers);
+ if (pendingUserInputQuestionIndex < pendingUserInput.questions.length - 1) {
+ setPendingUserInputQuestionIndex((index) => index + 1);
+ return true;
+ }
+ const answers = buildPendingUserInputAnswers(pendingUserInput.questions, nextAnswers);
+ if (!answers) return false;
+ return submitPendingUserInput(pendingUserInput.requestId, answers);
+ }
if (!groupReady || !group) {
setError("The group is still connecting.");
return false;
@@ -243,13 +307,93 @@ export function useGroupThreadRuntime(groupId: string) {
group,
groupId,
groupReady,
+ linkedThreadRef,
+ pendingUserInputAnswers,
+ pendingUserInputQuestionIndex,
+ pendingUserInputs,
rememberedThread?.runtimeMode,
+ respondingRequestIds,
settings.localExecutionMode,
setRuntimeMode,
startTurn,
+ submitPendingUserInput,
],
);
+ useEffect(() => {
+ setPendingUserInputAnswers({});
+ setPendingUserInputQuestionIndex(0);
+ singleSelectInFlightRef.current = null;
+ const pendingIds = new Set(pendingUserInputs.map((pending) => pending.requestId));
+ for (const requestId of respondingRequestIdsRef.current) {
+ if (!pendingIds.has(requestId)) respondingRequestIdsRef.current.delete(requestId);
+ }
+ setRespondingRequestIds((current) => current.filter((requestId) => pendingIds.has(requestId)));
+ }, [pendingUserInputs[0]?.requestId]);
+
+ const selectPendingUserInputOption = useCallback(
+ (questionId: string, optionLabel: string) => {
+ const pending = pendingUserInputs[0];
+ const question = pending?.questions.find((entry) => entry.id === questionId);
+ if (!pending || !question) return;
+ if (!question.multiSelect) {
+ const selectionKey = `${pending.requestId}:${questionId}`;
+ if (singleSelectInFlightRef.current === selectionKey) return;
+ const selection = applyPendingUserInputSingleSelect(
+ pending.questions,
+ pendingUserInputAnswers,
+ pendingUserInputQuestionIndex,
+ questionId,
+ optionLabel,
+ );
+ if (!selection) return;
+ singleSelectInFlightRef.current = selectionKey;
+ setPendingUserInputAnswers(selection.draftAnswers);
+ if (!selection.answers) {
+ setPendingUserInputQuestionIndex(selection.questionIndex);
+ return;
+ }
+ void submitPendingUserInput(pending.requestId, selection.answers).then((submitted) => {
+ if (!submitted) singleSelectInFlightRef.current = null;
+ });
+ return;
+ }
+ setPendingUserInputAnswers((current) => ({
+ ...current,
+ [questionId]: togglePendingUserInputOptionSelection(
+ question,
+ current[questionId],
+ optionLabel,
+ ),
+ }));
+ },
+ [
+ pendingUserInputAnswers,
+ pendingUserInputQuestionIndex,
+ pendingUserInputs,
+ submitPendingUserInput,
+ ],
+ );
+
+ const advancePendingUserInput = useCallback(async () => {
+ const pending = pendingUserInputs[0];
+ if (!pending || !linkedThreadRef || respondingRequestIds.includes(pending.requestId)) return;
+ if (pendingUserInputQuestionIndex < pending.questions.length - 1) {
+ setPendingUserInputQuestionIndex((index) => index + 1);
+ return;
+ }
+ const answers = buildPendingUserInputAnswers(pending.questions, pendingUserInputAnswers);
+ if (!answers) return;
+ await submitPendingUserInput(pending.requestId, answers);
+ }, [
+ linkedThreadRef,
+ pendingUserInputAnswers,
+ pendingUserInputQuestionIndex,
+ pendingUserInputs,
+ respondingRequestIds,
+ submitPendingUserInput,
+ ]);
+
return {
bootstrapped,
defaultProject: activeProject,
@@ -257,7 +401,13 @@ export function useGroupThreadRuntime(groupId: string) {
groupReady,
linkedThreadRef,
messages,
+ pendingUserInputs,
+ pendingUserInputAnswers,
+ pendingUserInputQuestionIndex,
+ respondingRequestIds,
respondingBotId: rememberedThread?.respondingBotId ?? group?.bossBotId ?? null,
+ selectPendingUserInputOption,
+ advancePendingUserInput,
send,
sending,
};
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index 0792d01a1..95202446c 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -2261,7 +2261,7 @@ export function GeneralSettingsPanel() {
<SettingsRow
{...searchableSetting("local-execution")}
- description="Ask before local file changes and shell commands. Full access skips these prompts. Sensitive actions still ask."
+ description="Auto review runs safe actions and asks before sensitive ones."
resetAction={
settings.localExecutionMode !== DEFAULT_UNIFIED_SETTINGS.localExecutionMode ? (
<SettingResetButton
@@ -2278,17 +2278,24 @@ export function GeneralSettingsPanel() {
<Select
value={settings.localExecutionMode}
onValueChange={(value) => {
- if (value === "approval-required" || value === "full-access") {
+ if (value === "approval-required" || value === "auto" || value === "full-access") {
updateSettings({ localExecutionMode: value });
}
}}
>
<SelectTrigger className="w-full sm:w-40" aria-label="Local execution">
<SelectValue>
- {settings.localExecutionMode === "full-access" ? "Full access" : "Ask first"}
+ {settings.localExecutionMode === "full-access"
+ ? "Full access"
+ : settings.localExecutionMode === "approval-required"
+ ? "Ask first"
+ : "Auto review"}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
+ <SelectItem hideIndicator value="auto">
+ Auto review
+ </SelectItem>
<SelectItem hideIndicator value="approval-required">
Ask first
</SelectItem>
diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts
index 75fa41a5d..ad8832a29 100644
--- a/apps/web/src/composerDraftStore.test.ts
+++ b/apps/web/src/composerDraftStore.test.ts
@@ -806,7 +806,7 @@ describe("composerDraftStore project draft thread mapping", () => {
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
envMode: "worktree",
- runtimeMode: "approval-required",
+ runtimeMode: "auto",
interactionMode: "default",
createdAt: "2026-01-01T00:00:00.000Z",
});
@@ -817,7 +817,7 @@ describe("composerDraftStore project draft thread mapping", () => {
branch: "feature/test",
worktreePath: "/tmp/worktree-test",
envMode: "worktree",
- runtimeMode: "approval-required",
+ runtimeMode: "auto",
interactionMode: "default",
createdAt: "2026-01-01T00:00:00.000Z",
});
diff --git a/apps/web/src/lib/commandApprovalDetails.test.ts b/apps/web/src/lib/commandApprovalDetails.test.ts
new file mode 100644
index 000000000..e9ba3234f
--- /dev/null
+++ b/apps/web/src/lib/commandApprovalDetails.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { describeCommandApproval } from "./commandApprovalDetails";
+
+describe("describeCommandApproval", () => {
+ it("reports no details for a short safe command so the row hides its expander", () => {
+ const details = describeCommandApproval("pwd", { command: "pwd" });
+
+ expect(details.hasDetails).toBe(false);
+ expect(details.programs).toEqual(["pwd"]);
+ expect(details.signals).toEqual([]);
+ expect(details.workingDirectory).toBeNull();
+ expect(details.reason).toBeNull();
+ });
+
+ it("reads the folder and reason the provider sent", () => {
+ const details = describeCommandApproval("ls", {
+ command: "ls",
+ cwd: "/tmp/work",
+ justification: "List the build output",
+ });
+
+ expect(details.workingDirectory).toBe("/tmp/work");
+ expect(details.reason).toBe("List the build output");
+ expect(details.hasDetails).toBe(true);
+ });
+
+ it("names every program in a chained command", () => {
+ const details = describeCommandApproval(
+ "cd apps/web && NODE_ENV=test bun run build | tee log",
+ {
+ command: "x",
+ },
+ );
+
+ expect(details.programs).toEqual(["cd", "bun", "tee"]);
+ expect(details.hasDetails).toBe(true);
+ });
+
+ it("flags the effects that change a review decision", () => {
+ expect(describeCommandApproval("sudo rm -rf build", {}).signals).toEqual([
+ "Runs as root",
+ "Deletes files",
+ ]);
+ expect(describeCommandApproval("curl https://example.com > out.txt", {}).signals).toEqual([
+ "Network access",
+ "Writes files",
+ ]);
+ expect(describeCommandApproval("git push origin main", {}).signals).toEqual(["Publishes"]);
+ expect(describeCommandApproval("chmod +x run.sh", {}).signals).toEqual(["Changes permissions"]);
+ });
+
+ it("treats a multi-line or long command as worth expanding", () => {
+ expect(describeCommandApproval("echo one\necho two", {}).hasDetails).toBe(true);
+ expect(describeCommandApproval(`echo ${"x".repeat(80)}`, {}).hasDetails).toBe(true);
+ });
+});
diff --git a/apps/web/src/lib/commandApprovalDetails.ts b/apps/web/src/lib/commandApprovalDetails.ts
new file mode 100644
index 000000000..e5dd49c00
--- /dev/null
+++ b/apps/web/src/lib/commandApprovalDetails.ts
@@ -0,0 +1,92 @@
+/**
+ * Facts about a pending command approval that the collapsed row cannot show.
+ * The approval panel opens its details section only when one of these is present,
+ * so a bare command such as "pwd" never offers an expander that repeats itself.
+ */
+export interface CommandApprovalDetails {
+ readonly command: string;
+ readonly workingDirectory: string | null;
+ readonly reason: string | null;
+ readonly programs: ReadonlyArray<string>;
+ readonly signals: ReadonlyArray<string>;
+ /** True when the collapsed row already shows every character, so expanding must not repeat it. */
+ readonly fitsCollapsedRow: boolean;
+ readonly hasDetails: boolean;
+}
+
+/** Longer than this and the collapsed row truncates, so the full text is worth expanding. */
+const TRUNCATING_COMMAND_LENGTH = 64;
+const SEGMENT_SEPARATOR = /\s*(?:&&|\|\||[;|\n])\s*/;
+const ENVIRONMENT_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
+const COMMAND_PREFIXES = new Set(["sudo", "command", "exec", "nohup", "time", "env", "xargs"]);
+
+function readString(args: Record<string, unknown>, keys: ReadonlyArray<string>): string | null {
+ for (const key of keys) {
+ const value = args[key];
+ if (typeof value === "string" && value.trim().length > 0) return value.trim();
+ }
+ return null;
+}
+
+/** First real program in a segment, past any env assignments and wrappers like "sudo". */
+function programOfSegment(segment: string): string | null {
+ for (const token of segment.split(/\s+/)) {
+ const bare = token.replace(/^['"]|['"]$/g, "");
+ if (bare.length === 0) continue;
+ if (ENVIRONMENT_ASSIGNMENT.test(bare)) continue;
+ if (bare.startsWith("-")) continue;
+ if (COMMAND_PREFIXES.has(bare)) continue;
+ return bare.split("/").at(-1) ?? bare;
+ }
+ return null;
+}
+
+function programsOf(command: string): ReadonlyArray<string> {
+ const seen: string[] = [];
+ for (const segment of command.split(SEGMENT_SEPARATOR)) {
+ const program = programOfSegment(segment.trim());
+ if (program && !seen.includes(program)) seen.push(program);
+ }
+ return seen;
+}
+
+/** Short labels for the operations a reviewer needs to see before approving. */
+function signalsOf(command: string): ReadonlyArray<string> {
+ const signals: string[] = [];
+ const add = (label: string) => {
+ if (!signals.includes(label)) signals.push(label);
+ };
+
+ if (/(^|\s)sudo(\s|$)/.test(command)) add("Runs as root");
+ if (/(^|\s)rm\s+(-\S*\s+)*-?\S*[rf]/.test(command)) add("Deletes files");
+ if (/(^|\s)(curl|wget|ssh|scp|nc|rsync)(\s|$)/.test(command)) add("Network access");
+ if (/(^|\s)(git\s+push|npm\s+publish|bun\s+publish|pnpm\s+publish)(\s|$)/.test(command)) {
+ add("Publishes");
+ }
+ if (/>>?\s*\S/.test(command) || /(^|\s|\|)\s*tee(\s|$)/.test(command)) add("Writes files");
+ if (/(^|\s)(chmod|chown)(\s|$)/.test(command)) add("Changes permissions");
+
+ return signals;
+}
+
+export function describeCommandApproval(command: string, args: unknown): CommandApprovalDetails {
+ const record = args && typeof args === "object" ? (args as Record<string, unknown>) : {};
+ const workingDirectory = readString(record, [
+ "cwd",
+ "workdir",
+ "working_directory",
+ "workingDirectory",
+ ]);
+ const reason = readString(record, ["justification", "reason", "explanation", "purpose"]);
+ const programs = programsOf(command);
+ const signals = signalsOf(command);
+ const fitsCollapsedRow = !command.includes("\n") && command.length <= TRUNCATING_COMMAND_LENGTH;
+ const hasDetails =
+ !fitsCollapsedRow ||
+ workingDirectory !== null ||
+ reason !== null ||
+ programs.length > 1 ||
+ signals.length > 0;
+
+ return { command, workingDirectory, reason, programs, signals, fitsCollapsedRow, hasDetails };
+}
diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts
index a807f6326..5d331227d 100644
--- a/apps/web/src/session-logic.test.ts
+++ b/apps/web/src/session-logic.test.ts
@@ -302,6 +302,38 @@ describe("derivePendingApprovals", () => {
});
describe("derivePendingUserInputs", () => {
+ it("keeps free-text questions that do not have options", () => {
+ const pending = derivePendingUserInputs([
+ makeActivity({
+ kind: "user-input.requested",
+ payload: {
+ requestId: "req-free-text",
+ questions: [
+ {
+ id: "answer",
+ header: "Question",
+ question: "What should the bot do next?",
+ options: [],
+ },
+ ],
+ },
+ }),
+ ]);
+
+ expect(pending).toMatchObject([
+ {
+ requestId: "req-free-text",
+ questions: [
+ {
+ id: "answer",
+ question: "What should the bot do next?",
+ options: [],
+ },
+ ],
+ },
+ ]);
+ });
+
it("tracks open structured prompts and removes resolved ones", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index ce29d3098..940fa5c41 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -534,9 +534,6 @@ function parseUserInputQuestions(
};
})
.filter((option): option is UserInputQuestion["options"][number] => option !== null);
- if (options.length === 0) {
- return null;
- }
return {
id: question.id,
header: question.header,
diff --git a/docs/internals/providers.md b/docs/internals/providers.md
index c8d518848..5b9b8dd87 100644
--- a/docs/internals/providers.md
+++ b/docs/internals/providers.md
@@ -45,9 +45,10 @@ resolves the selected subscription model through explicit server-owned auth. Age
maps Mastra message, tool, approval, usage, completion, and error events to
`ProviderRuntimeEvent`.
-Mastra keeps approval callbacks enabled in every runtime mode. `AgentController` auto-approves only
-the routine actions allowed by the selected mode. It always asks before an MCP tool call or an action
-that sends, pays, deletes, changes production, exposes secrets, publishes, signs, refunds, or changes
+Mastra keeps approval callbacks enabled in every runtime mode. `AgentController` auto-approves
+`ask_user`, then converts its suspension into a user-input request. In automatic mode, it approves
+only the routine actions allowed by the selected mode. It always asks before an MCP tool call or an action
+that can write through MCP, sends, pays, deletes, changes production, exposes secrets, publishes, signs, refunds, or changes
an account. Unknown mutating intent also asks. The pending approval map binds the response to the
exact tool-call ID, deletes that entry before execution, and treats session-wide or permanent answers
as one-use approval.
diff --git a/docs/user/bots.md b/docs/user/bots.md
index b302ccfb0..6f845a6d7 100644
--- a/docs/user/bots.md
+++ b/docs/user/bots.md
@@ -22,9 +22,10 @@ lets bots share files and browser cookies.
Bots can use Local, E2B, Daytona, Vercel Sandbox, or Upstash Box. Connect remote services under
**Settings > Sandbox**. A bot-specific sandbox overrides the environment default.
-Local bots ask before file changes and shell commands by default. Set **Settings > General > Local
-execution** to **Full access** to skip routine local prompts. Protected actions still ask. Cloud
-sandboxes do not show the local-computer prompt.
+Local bots use **Auto review** by default. Safe actions continue without a prompt. Actions that send,
+pay, delete, change production, use secrets, or have unclear intent still ask. Select **Settings >
+General > Local execution** to ask before each local change or grant full access. Bots that run in a
+cloud sandbox do not show the local computer prompt.
## Run a routine
diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md
index b3399ac04..9929f3814 100644
--- a/docs/user/permission-modes.md
+++ b/docs/user/permission-modes.md
@@ -2,9 +2,10 @@
A permission mode controls which actions an agent can take before it must ask you.
-Set the mode per thread from the message composer. A child thread keeps its parent thread's mode.
-Other new threads use **Settings > General > Local execution** and ask before local file changes and
-shell commands by default.
+The mode is set per thread, from the mode control in the message composer. Changing it in one
+thread does not change any other thread. A thread created from inside another thread keeps that
+thread's mode. Otherwise, new threads use **Settings > General > Local execution** and use
+**Auto review** by default.
## The modes
@@ -20,6 +21,9 @@ questions and still stops at protected actions.
## Protected actions
+Questions never need approval. A question with choices shows those choices inline. A free-text
+question uses the message composer for the answer.
+
Akeru's Codex and Kimi runtime always asks before an action that sends data, pays, deletes, changes
production, publishes, exposes secrets, signs, refunds, or changes an account. Unknown mutating
actions also ask. Each approval applies only to the pending action.
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index 617c7be50..f2b8dbd1c 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -154,9 +154,9 @@ export const RuntimeMode = Schema.Literals([
export type RuntimeMode = typeof RuntimeMode.Type;
// Event decoders keep the historical full-access fallback for old persisted data.
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
-export const LocalExecutionMode = Schema.Literals(["approval-required", "full-access"]);
+export const LocalExecutionMode = Schema.Literals(["approval-required", "auto", "full-access"]);
export type LocalExecutionMode = typeof LocalExecutionMode.Type;
-export const DEFAULT_LOCAL_EXECUTION_MODE: LocalExecutionMode = "approval-required";
+export const DEFAULT_LOCAL_EXECUTION_MODE: LocalExecutionMode = "auto";
export const ProviderInteractionMode = Schema.Literals(["default", "plan"]);
export type ProviderInteractionMode = typeof ProviderInteractionMode.Type;
export const DEFAULT_PROVIDER_INTERACTION_MODE: ProviderInteractionMode = "default";
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index 5d2a18d56..708441775 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -130,15 +130,20 @@ describe("ClaudeSettings auto-compaction", () => {
});
describe("ServerSettings local execution", () => {
- it("asks before local execution by default and accepts an explicit full-access opt-in", () => {
- expect(decodeServerSettings({}).localExecutionMode).toBe("approval-required");
+ it("auto-reviews local execution by default and accepts each supported policy", () => {
+ expect(decodeServerSettings({}).localExecutionMode).toBe("auto");
+ expect(
+ decodeServerSettingsPatch({ localExecutionMode: "approval-required" }).localExecutionMode,
+ ).toBe("approval-required");
+ expect(decodeServerSettingsPatch({ localExecutionMode: "auto" }).localExecutionMode).toBe(
+ "auto",
+ );
expect(
decodeServerSettingsPatch({ localExecutionMode: "full-access" }).localExecutionMode,
).toBe("full-access");
});
- it("rejects other runtime modes", () => {
- expect(() => decodeServerSettingsPatch({ localExecutionMode: "auto" })).toThrow();
+ it("rejects edit-only automatic approval", () => {
expect(() => decodeServerSettingsPatch({ localExecutionMode: "auto-accept-edits" })).toThrow();
});
});
@@ -311,12 +316,14 @@ describe("ServerSettings sandbox providers", () => {
});
describe("ServerSettings local execution", () => {
- it("asks first by default and accepts full access only as an opt-in", () => {
- expect(decodeServerSettings({}).localExecutionMode).toBe("approval-required");
+ it("keeps auto review as the unified default", () => {
+ expect(decodeServerSettings({}).localExecutionMode).toBe("auto");
+ expect(decodeServerSettingsPatch({ localExecutionMode: "auto" }).localExecutionMode).toBe(
+ "auto",
+ );
expect(
decodeServerSettingsPatch({ localExecutionMode: "full-access" }).localExecutionMode,
).toBe("full-access");
- expect(() => decodeServerSettingsPatch({ localExecutionMode: "auto" })).toThrow();
});
});