Pending approvals in the composer's place

This commit is contained in:
Callum Alpass committed 2026-11-03 00:49:52 +11:00
1 parent 49b04f9012
commit 3a7c183e1c
5 files changed
+107 -34

No files matched your search

+7 -1
View File
@@ -32,6 +32,7 @@ import { useQuestion } from "./useQuestion.ts";
import { useThreadMenu } from "./useThreadMenu.ts"; import { useThreadMenu } from "./useThreadMenu.ts";
import { editInEditor } from "./editor.ts"; import { editInEditor } from "./editor.ts";
import { Palette } from "./Palette.tsx"; import { Palette } from "./Palette.tsx";
import { ApprovalPanel } from "./ApprovalPanel.tsx";
import { QuestionPanel } from "./QuestionPanel.tsx"; import { QuestionPanel } from "./QuestionPanel.tsx";
import { QueuePanel } from "./QueuePanel.tsx"; import { QueuePanel } from "./QueuePanel.tsx";
import { SecretPanel } from "./SecretPanel.tsx"; import { SecretPanel } from "./SecretPanel.tsx";
@@ -910,7 +911,6 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
// The mouse in the conversation: stable callbacks, since its rows are memoized. // The mouse in the conversation: stable callbacks, since its rows are memoized.
const conversationMouse: ConversationMouse = { const conversationMouse: ConversationMouse = {
respond: useEvent((decision: ProviderApprovalDecision) => respond(decision)),
selectTurn: useEvent((messageId: string) => turns.select(messageId)), selectTurn: useEvent((messageId: string) => turns.select(messageId)),
toggleFold: useEvent((id: string) => toggleFold: useEvent((id: string) =>
setExpandedIds((previous) => { setExpandedIds((previous) => {
@@ -1173,6 +1173,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
) : null} ) : null}
{threadId || draft ? ( {threadId || draft ? (
<box flexDirection="column" flexShrink={0} marginTop={1} marginLeft={1} marginRight={1}> <box flexDirection="column" flexShrink={0} marginTop={1} marginLeft={1} marginRight={1}>
{pendingApproval && !draft ? (
<ApprovalPanel approval={pendingApproval} onRespond={respond} />
) : (
<>
<box <box
border={["left"]} border={["left"]}
customBorderChars={BAR} customBorderChars={BAR}
@@ -1235,6 +1239,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
<box height={1} flexShrink={0} border={["left"]} borderColor={composerBarColor} customBorderChars={{ ...NO_BORDER, vertical: "╹" }}> <box height={1} flexShrink={0} border={["left"]} borderColor={composerBarColor} customBorderChars={{ ...NO_BORDER, vertical: "╹" }}>
<box height={1} border={["bottom"]} borderColor={colors.element} customBorderChars={{ ...NO_BORDER, horizontal: "▀" }} /> <box height={1} border={["bottom"]} borderColor={colors.element} customBorderChars={{ ...NO_BORDER, horizontal: "▀" }} />
</box> </box>
</>
)}
</box> </box>
) : null} ) : null}
</box> </box>
+46
View File
@@ -0,0 +1,46 @@
import type { ThreadPendingApproval } from "@t3tools/client-runtime/state/thread-requests";
import type { ProviderApprovalDecision } from "@t3tools/contracts";
import { Button, Buttons } from "./Button.tsx";
import { BAR, NO_BORDER } from "./edges.ts";
import { colors } from "./theme.ts";
/**
* A pending approval in the composer's place, as the web swaps it into the
* composer: the composer's own block and bar, the bar turned to the warning
* colour, with the same keys the hint bar names.
*/
export function ApprovalPanel(props: { readonly approval: ThreadPendingApproval; readonly onRespond: (decision: ProviderApprovalDecision) => void }) {
const { approval } = props;
return (
<>
<box border={["left"]} customBorderChars={BAR} borderColor={colors.warn} backgroundColor={colors.element} flexShrink={0} flexDirection="column" paddingTop={1} paddingBottom={1} paddingLeft={2} paddingRight={2}>
<text fg={colors.warn}>
<strong>{approvalTitle(approval.requestKind)}</strong>
</text>
{approval.detail ? <text fg={colors.text}>{approval.detail}</text> : null}
{approval.appName ? <text fg={colors.muted}>{approval.appName}</text> : null}
{approval.reason ? <text fg={colors.muted}>{approval.reason}</text> : null}
<box marginTop={1}>
<Buttons>
<Button label="Approve" shortcut="y" color={colors.good} onPress={() => props.onRespond("accept")} />
<Button label="Always allow this session" shortcut="Y" onPress={() => props.onRespond("acceptForSession")} />
<Button label="Decline" shortcut="n" color={colors.bad} onPress={() => props.onRespond("decline")} />
</Buttons>
</box>
</box>
<box height={1} flexShrink={0} border={["left"]} borderColor={colors.warn} customBorderChars={{ ...NO_BORDER, vertical: "╹" }}>
<box height={1} border={["bottom"]} borderColor={colors.element} customBorderChars={{ ...NO_BORDER, horizontal: "▀" }} />
</box>
</>
);
}
function approvalTitle(kind: string): string {
if (kind.includes("command")) return "Command approval";
if (kind.includes("read")) return "File read approval";
if (kind.includes("file")) return "File change approval";
if (kind.includes("elicitation") || kind.includes("access")) return "App access approval";
if (kind.includes("permission")) return "App permission approval";
return "Approval";
}
+18 -33
View File
@@ -1,5 +1,5 @@
import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core"; import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core";
import type { ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts"; import type { ThreadId, TurnItemId } from "@t3tools/contracts";
import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models"; import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models";
import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation"; import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation";
import { memo, useEffect, useState, type RefObject } from "react"; import { memo, useEffect, useState, type RefObject } from "react";
@@ -7,7 +7,7 @@ import { findTextSegments } from "../model/search.ts";
import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts"; import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts";
import { FindText } from "./FindText.tsx"; import { FindText } from "./FindText.tsx";
import { Button, Buttons, isLeftClick, isRightClick, useHover } from "./Button.tsx"; import { isLeftClick, isRightClick, useHover } from "./Button.tsx";
import { checkpointFileTotals, type ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import { checkpointFileTotals, type ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import { formatDuration } from "@t3tools/shared/orchestrationTiming"; import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import type { Tui3Config } from "../config.ts"; import type { Tui3Config } from "../config.ts";
@@ -27,7 +27,6 @@ export type ConversationTarget =
| { readonly kind: "command"; readonly command: string; readonly output: string; readonly omitted: boolean; readonly source: { readonly threadId: ThreadId; readonly itemId: TurnItemId } | null }; | { readonly kind: "command"; readonly command: string; readonly output: string; readonly omitted: boolean; readonly source: { readonly threadId: ThreadId; readonly itemId: TurnItemId } | null };
export interface ConversationMouse { export interface ConversationMouse {
readonly respond: (decision: ProviderApprovalDecision) => void;
/** A click on a prompt: the turn cursor, as [ and ] move it. */ /** A click on a prompt: the turn cursor, as [ and ] move it. */
readonly selectTurn: (messageId: string) => void; readonly selectTurn: (messageId: string) => void;
/** A click on a folded turn or work group: its own expansion, apart from e. */ /** A click on a folded turn or work group: its own expansion, apart from e. */
@@ -73,7 +72,7 @@ export function ThreadView(props: {
<scrollbox ref={props.scrollRef} flexGrow={1} flexShrink={1} minHeight={0} stickyScroll stickyStart="bottom"> <scrollbox ref={props.scrollRef} flexGrow={1} flexShrink={1} minHeight={0} stickyScroll stickyStart="bottom">
{props.loading && !timeline ? <text fg={colors.muted}>Loading…</text> : null} {props.loading && !timeline ? <text fg={colors.muted}>Loading…</text> : null}
{history?.hasMore || history?.error ? <LoadEarlier history={history} onLoad={props.mouse.loadEarlier} /> : null} {history?.hasMore || history?.error ? <LoadEarlier history={history} onLoad={props.mouse.loadEarlier} /> : null}
{timeline?.rows.map((row) => ( {timeline?.rows.filter((row) => !isPendingApprovalRow(row, pendingIds)).map((row) => (
<Row <Row
key={row.id} key={row.id}
row={row} row={row}
@@ -83,7 +82,6 @@ export function ThreadView(props: {
scrollRef={props.scrollRef} scrollRef={props.scrollRef}
findQuery={props.findQuery ?? ""} findQuery={props.findQuery ?? ""}
activeOccurrence={props.findMatch?.entryId === row.id ? props.findMatch.occurrence : null} activeOccurrence={props.findMatch?.entryId === row.id ? props.findMatch.occurrence : null}
pending={row.kind === "event" && pendingIds.has(eventRequestId(row) ?? "")}
workspaceRoot={props.workspaceRoot} workspaceRoot={props.workspaceRoot}
footer={assistantFooter(row, timeline, props.timestampFormat, props.now)} footer={assistantFooter(row, timeline, props.timestampFormat, props.now)}
now={row.kind === "working" ? props.now : 0} now={row.kind === "working" ? props.now : 0}
@@ -157,7 +155,6 @@ const Row = memo(function Row(props: {
readonly scrollRef: RefObject<ScrollBoxRenderable | null>; readonly scrollRef: RefObject<ScrollBoxRenderable | null>;
readonly findQuery: string; readonly findQuery: string;
readonly activeOccurrence: number | null; readonly activeOccurrence: number | null;
readonly pending: boolean;
readonly workspaceRoot: string | undefined; readonly workspaceRoot: string | undefined;
/** The turn footer's text for this row, or "" for none. */ /** The turn footer's text for this row, or "" for none. */
readonly footer: string; readonly footer: string;
@@ -247,7 +244,7 @@ const Row = memo(function Row(props: {
</box> </box>
); );
case "event": case "event":
return <EventRow item={row.projectedItem.item} pending={props.pending} onRespond={mouse.respond} />; return <EventRow item={row.projectedItem.item} />;
case "worktree-setup": case "worktree-setup":
return ( return (
<text marginTop={1} fg={colors.muted}> <text marginTop={1} fg={colors.muted}>
@@ -400,23 +397,7 @@ export function childThreadOf(entry: WorkLogEntry): ThreadId | null {
return item?.type === "subagent" ? (item.childThreadId ?? null) : null; return item?.type === "subagent" ? (item.childThreadId ?? null) : null;
} }
function EventRow({ item, pending, onRespond }: { readonly onRespond: (decision: ProviderApprovalDecision) => void; readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never; readonly pending: boolean }) { function EventRow({ item }: { readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never }) {
if (item.type === "approval_request" && pending) {
return (
<box marginTop={1} border={["left"]} customBorderChars={BAR} borderColor={colors.warn} backgroundColor={colors.panel} flexDirection="column" paddingTop={1} paddingBottom={1} paddingLeft={2} paddingRight={2}>
<text fg={colors.warn}>
<strong>{approvalTitle(item.requestKind)}</strong>
</text>
{item.prompt ? <text fg={colors.text}>{item.prompt}</text> : null}
{item.reason ? <text fg={colors.muted}>{item.reason}</text> : null}
<Buttons>
<Button label="Approve" shortcut="y" color={colors.good} onPress={() => onRespond("accept")} />
<Button label="Always allow this session" shortcut="Y" onPress={() => onRespond("acceptForSession")} />
<Button label="Decline" shortcut="n" color={colors.bad} onPress={() => onRespond("decline")} />
</Buttons>
</box>
);
}
const block = blockFor(item, new Set()); const block = blockFor(item, new Set());
if (!block) return null; if (!block) return null;
switch (block.kind) { switch (block.kind) {
@@ -438,20 +419,24 @@ function EventRow({ item, pending, onRespond }: { readonly onRespond: (decision:
} }
} }
function approvalTitle(kind: string): string {
if (kind.includes("command")) return "Command approval";
if (kind.includes("read")) return "File read approval";
if (kind.includes("file")) return "File change approval";
if (kind.includes("access")) return "App access approval";
if (kind.includes("permission")) return "App permission approval";
return "Approval";
}
function eventRequestId(row: Extract<MessagesTimelineRow, { kind: "event" }>): string | undefined { function eventRequestId(row: Extract<MessagesTimelineRow, { kind: "event" }>): string | undefined {
const item = row.projectedItem.item; const item = row.projectedItem.item;
return item.type === "approval_request" ? item.requestId : undefined; return item.type === "approval_request" ? item.requestId : undefined;
} }
function entryRequestId(entry: WorkLogEntry): string | undefined {
const item = entry.structuredPayload;
return item?.type === "approval_request" ? item.requestId : undefined;
}
/** A live approval shows in the composer's place, not again as a timeline row. */
function isPendingApprovalRow(row: MessagesTimelineRow, pendingIds: ReadonlySet<string>): boolean {
if (pendingIds.size === 0) return false;
if (row.kind === "event") return pendingIds.has(eventRequestId(row) ?? "");
if (row.kind === "work-live") return pendingIds.has(entryRequestId(row.entry) ?? "");
return row.kind === "work" && row.groupedEntries.length > 0 && row.groupedEntries.every((entry) => pendingIds.has(entryRequestId(entry) ?? ""));
}
/** A folded turn or work group: a click opens or closes just this one. */ /** A folded turn or work group: a click opens or closes just this one. */
function Toggle({ onPress, children }: { readonly onPress: () => void; readonly children: (hover: boolean) => React.ReactNode }) { function Toggle({ onPress, children }: { readonly onPress: () => void; readonly children: (hover: boolean) => React.ReactNode }) {
const [hover, hoverProps] = useHover(); const [hover, hoverProps] = useHover();
+13
View File
@@ -164,6 +164,19 @@ describe("a finished turn", () => {
}); });
describe("approvals", () => { describe("approvals", () => {
test("the request shows in the composer's place, with its buttons, and not in the timeline", async () => {
const app = await open({ session: fakeSession({ projection: withApproval() }) });
const frame = app.frame();
expect(frame).toContain("Command approval");
expect(frame).toContain("Deletes dist/ and rebuilds it.");
// Only the composer block names the command; its timeline row is hidden.
expect(frame.split("rm -rf dist && bun run build")).toHaveLength(2);
expect(frame).not.toContain("Press i to type");
const approve = app.find("Approve");
await app.click(approve.x, approve.y);
expect(app.calls("respond").map((call) => call.args[2])).toEqual(["accept"]);
});
test("y, Y and n answer the request", async () => { test("y, Y and n answer the request", async () => {
const app = await open({ session: fakeSession({ projection: withApproval() }) }); const app = await open({ session: fakeSession({ projection: withApproval() }) });
expect(app.hints()).toStartWith("y approve · Y always · n decline · j/k threads"); expect(app.hints()).toStartWith("y approve · Y always · n decline · j/k threads");
+23
View File
@@ -9,11 +9,34 @@ const after = (seconds: number) => DateTime.makeUnsafe(DateTime.toEpochMillis(at
/** The thread with a command waiting for approval. */ /** The thread with a command waiting for approval. */
export function withApproval(supportsFeedback = false): OrchestrationV2ThreadProjection { export function withApproval(supportsFeedback = false): OrchestrationV2ThreadProjection {
const item = {
id: "item-approval",
threadId: v2Projection.thread.id,
runId: null,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 0,
status: "waiting",
title: null,
startedAt: at,
completedAt: null,
updatedAt: at,
type: "approval_request",
requestId: "approval-1",
requestKind: "command",
prompt: "rm -rf dist && bun run build",
reason: "Deletes dist/ and rebuilds it.",
};
return { return {
...v2Projection, ...v2Projection,
runtimeRequests: [ runtimeRequests: [
{ id: "approval-1", nodeId: "node-1", providerTurnId: null, nativeRequestRef: null, kind: "command", status: "pending", responseCapability: { type: "live", providerSessionId: "session-1", ...(supportsFeedback ? { supportsFeedback } : {}) }, createdAt: at, resolvedAt: null }, { id: "approval-1", nodeId: "node-1", providerTurnId: null, nativeRequestRef: null, kind: "command", status: "pending", responseCapability: { type: "live", providerSessionId: "session-1", ...(supportsFeedback ? { supportsFeedback } : {}) }, createdAt: at, resolvedAt: null },
], ],
turnItems: [item],
visibleTurnItems: [{ position: 0, visibility: "local", sourceThreadId: v2Projection.thread.id, sourceItemId: item.id, item }],
} as unknown as OrchestrationV2ThreadProjection; } as unknown as OrchestrationV2ThreadProjection;
} }