Skip to content
TypeScript

feat(web): pending approvals show on their timeline row (#26255)

maria1f8530ec3c46
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index dfdf3f5fc69..4796a8465e2 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -115,6 +115,7 @@ import { useLocation, useNavigate } from "@tanstack/react-router";
import { assistantCitationFromLocation } from "../lib/assistantCitationNavigation";
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
import { useStore } from "zustand";
+import { shallow } from "zustand/vanilla/shallow";
import { useShallow } from "zustand/react/shallow";
import {
isAtomCommandInterrupted,
@@ -1314,6 +1315,12 @@ export default function ChatView(props: ChatViewProps) {
composerRef,
setThreadError,
});
+ const [heldApprovalRequestIds, setHeldApprovalRequestIds] = useState<ReadonlySet<string>>(
+ () => new Set(),
+ );
+ const onHeldRequestIdsChange = useStableCallback((requestIds: ReadonlySet<string>) => {
+ setHeldApprovalRequestIds((current) => (shallow(current, requestIds) ? current : requestIds));
+ });
const activeProposedPlan = (() => {
if (!latestRunSettled) {
return null;
@@ -3245,6 +3252,11 @@ export default function ChatView(props: ChatViewProps) {
className="relative flex min-h-0 flex-1 flex-col bg-background"
>
<ThreadTimeline
+ pendingApprovals={pendingApprovals}
+ heldApprovalRequestIds={heldApprovalRequestIds}
+ respondingRequestIds={respondingRequestIds}
+ onRespondToApproval={onRespondToApprovalStable}
+ canOperateThread={canOperateThread}
threadDetailRef={routeThreadDetailRef}
entriesInput={timelineEntriesInput}
draftEntries={isServerThread ? null : draftTimelineEntries}
@@ -3489,6 +3501,7 @@ export default function ChatView(props: ChatViewProps) {
environmentUnavailable={activeEnvironmentUnavailableState}
activePendingApproval={activePendingApproval}
pendingApprovals={pendingApprovals}
+ onHeldRequestIdsChange={onHeldRequestIdsChange}
pendingUserInputs={pendingUserInputs}
activePendingProgress={activePendingProgress}
activePendingResolvedAnswers={activePendingResolvedAnswers}
@@ -3550,7 +3563,6 @@ export default function ChatView(props: ChatViewProps) {
onResume={onComposerResumeStable}
onInterrupt={onInterruptStable}
onImplementPlanInNewThread={onImplementPlanInNewThreadStable}
- onRespondToApproval={onRespondToApprovalStable}
onSelectActivePendingUserInputOption={
onSelectActivePendingUserInputOptionStable
}
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index da6b05b52b8..57a3a8aa419 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -20,7 +20,6 @@ import type {
ModelSelection,
ProjectId,
PreviewAnnotationPayload,
- ProviderApprovalDecision,
ThreadContextRecord,
EnvironmentContextRecord,
ProviderInteractionMode,
@@ -187,7 +186,6 @@ import {
ComposerCommandMenu,
composerSuggestionOptionId,
} from "./ComposerCommandMenu";
-import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
import {
ComposerAttachButton,
ComposerAttachmentFileList,
@@ -198,7 +196,6 @@ import {
} from "./ComposerAttachmentStrip";
import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
import { ComposerFooterPrimaryActions } from "./ComposerFooterControls";
-import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
@@ -239,7 +236,7 @@ const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidErro
const COMPOSER_SCROLL_COLLAPSE_THRESHOLD_PX = 24;
const COMPOSER_SCROLL_GESTURE_RESET_MS = 120;
import { toastManager } from "../ui/toast";
-import { PlayIcon, ShieldIcon } from "lucide-react";
+import { PlayIcon } from "lucide-react";
import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText";
import { hasProviderSetup } from "./ProviderStatusBanner";
import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection";
@@ -402,6 +399,7 @@ export interface ChatComposerProps {
activePendingApproval: PendingApproval | null;
pendingApprovals: PendingApproval[];
+ onHeldRequestIdsChange: (requestIds: ReadonlySet<string>) => void;
pendingUserInputs: PendingUserInput[];
activePendingProgress: {
questionIndex: number;
@@ -482,10 +480,6 @@ export interface ChatComposerProps {
onResume: () => void;
onInterrupt: () => void;
onImplementPlanInNewThread: () => void;
- onRespondToApproval: (
- requestId: RuntimeRequestId,
- decision: ProviderApprovalDecision,
- ) => Promise<unknown>;
onSelectActivePendingUserInputOption: (questionId: string, optionValue: string) => void;
onAdvanceActivePendingUserInput: () => void;
onDismissActivePendingUserInput: (requestId: RuntimeRequestId) => void;
@@ -550,6 +544,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
environmentUnavailable,
activePendingApproval: incomingPendingApproval,
pendingApprovals,
+ onHeldRequestIdsChange,
pendingUserInputs: incomingPendingUserInputs,
activePendingProgress: incomingPendingProgress,
activePendingResolvedAnswers,
@@ -601,7 +596,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
onResume,
onInterrupt,
onImplementPlanInNewThread,
- onRespondToApproval,
onSelectActivePendingUserInputOption,
onAdvanceActivePendingUserInput,
onDismissActivePendingUserInput,
@@ -633,6 +627,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
...pendingApprovals.map((request) => request.requestId),
...incomingPendingUserInputs.map((request) => request.requestId),
]);
+ // A layout effect so the timeline never paints a held approval as answerable.
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes held requests to the timeline without lifting per-keystroke typing state
+ useLayoutEffect(() => {
+ onHeldRequestIdsChange(heldRequestIds);
+ }, [heldRequestIds, onHeldRequestIdsChange]);
const activePendingApproval =
incomingPendingApproval && !heldRequestIds.has(incomingPendingApproval.requestId)
? incomingPendingApproval
@@ -1200,7 +1199,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const isChoiceOnlyPendingQuestion =
activePendingProgress?.activeQuestion?.allowCustomAnswer === false;
const showComposerTopDrawer =
- isComposerApprovalState ||
pendingUserInputs.length > 0 ||
(!isComposerCollapsedMobile && showPlanFollowUpPrompt && activeProposedPlan !== null);
const showCollapsedMobilePromptRow = isComposerCollapsedMobile;
@@ -2320,8 +2318,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
importContextRecords,
expandMobileComposer: expandMobileComposerStable,
});
- const hasBlockingComposerTopDrawer =
- activePendingApproval !== null || pendingUserInputs.length > 0;
+ const hasBlockingComposerTopDrawer = pendingUserInputs.length > 0;
const hasImageAttachmentAttention = standaloneComposerImages.some((image) => {
const upload = uploadsByImageId[image.id];
const failedInCurrentEnvironment =
@@ -2580,7 +2577,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
getModelDisabledReason={getModelDisabledReason}
/>
);
- // An open approval or question owns the space above the composer. Only a machine problem,
+ // An open question owns the space above the composer. Only a machine problem,
// which is why an answer could not go through, stays beside it.
const shelfItems = hasBlockingComposerTopDrawer
? props.bannerItems.filter(
@@ -3444,39 +3441,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<ComposerBannerStack items={shelfItems} />
{showComposerTopDrawer ? (
<ComposerBanner.Attachment>
- <ComposerBanner.Root
- data-chat-composer-top-drawer="true"
- variant={activePendingApproval ? "warning" : "info"}
- density={activePendingApproval ? "spacious" : "default"}
- >
- {activePendingApproval ? (
- <ComposerBanner.Row
- layout="approval"
- data-chat-composer-collapsed-controls="true"
- >
- <ComposerBanner.Icon>
- <ShieldIcon />
- </ComposerBanner.Icon>
- <ComposerBanner.Content>
- <ComposerPendingApprovalPanel
- approval={activePendingApproval}
- pendingCount={pendingApprovals.length}
- />
- </ComposerBanner.Content>
- <ComposerBanner.Actions>
- <ComposerPendingApprovalActions
- requestId={activePendingApproval.requestId}
- disabled={!canOperateThread}
- isResponding={respondingRequestIds.includes(
- activePendingApproval.requestId,
- )}
- options={activePendingApproval.options}
- canRespond={activePendingApproval.responseCapability === "live"}
- onRespondToApproval={onRespondToApproval}
- />
- </ComposerBanner.Actions>
- </ComposerBanner.Row>
- ) : pendingUserInputs.length > 0 ? (
+ <ComposerBanner.Root data-chat-composer-top-drawer="true" variant="info">
+ {pendingUserInputs.length > 0 ? (
<ComposerPendingUserInputPanel
pendingUserInputs={pendingUserInputs}
cwd={gitCwd ?? undefined}
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx
index d1b253fba60..67860e45ef2 100644
--- a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx
+++ b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx
@@ -5,12 +5,13 @@ import {
} from "@t3tools/contracts";
import { memo } from "react";
import { EllipsisIcon, TriangleAlertIcon } from "lucide-react";
-import { Button } from "../ui/button";
+import { Button, InlineButton } from "../ui/button";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { composerFloatingLayerProps } from "./composerEventScope";
interface ComposerPendingApprovalActionsProps {
+ presentation?: "composer" | "inline";
requestId: RuntimeRequestId;
isResponding: boolean;
canRespond: boolean;
@@ -30,6 +31,7 @@ const DEFAULT_APPROVAL_OPTIONS = [
] satisfies ReadonlyArray<ProviderApprovalOption>;
export const ComposerPendingApprovalActions = memo(function ComposerPendingApprovalActions({
+ presentation = "composer",
requestId,
isResponding,
canRespond,
@@ -47,23 +49,42 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
return (
<>
{primaryOptions.map((option) => {
- const button = (
- <Button
- key={option.decision}
- size="xs"
- variant={option.decision === "accept" ? "default" : "outline"}
- disabled={disabled || isResponding || !canRespond}
- aria-description={option.warning}
- onClick={() => {
- if (!disabled && !isResponding) {
- void onRespondToApproval(requestId, option.decision);
- }
- }}
- >
+ const buttonProps = {
+ disabled: disabled || isResponding || !canRespond,
+ "aria-description": option.warning,
+ onClick: () => {
+ if (!disabled && !isResponding && canRespond) {
+ void onRespondToApproval(requestId, option.decision);
+ }
+ },
+ };
+ const content = (
+ <>
{option.warning ? <TriangleAlertIcon className="size-3 shrink-0" /> : null}
- <span className="max-w-40 truncate">{option.label}</span>
- </Button>
+ <span className={presentation === "inline" ? "whitespace-normal" : "max-w-40 truncate"}>
+ {option.label}
+ </span>
+ </>
);
+ const button =
+ presentation === "inline" ? (
+ <InlineButton
+ key={option.decision}
+ {...buttonProps}
+ tone={option.decision === "accept" ? "default" : "muted"}
+ >
+ {content}
+ </InlineButton>
+ ) : (
+ <Button
+ key={option.decision}
+ {...buttonProps}
+ size="xs"
+ variant={option.decision === "accept" ? "default" : "outline"}
+ >
+ {content}
+ </Button>
+ );
return option.warning ? (
<Tooltip key={option.decision}>
<TooltipTrigger render={button} />
@@ -76,20 +97,26 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
{moreOptions.length > 0 ? (
<Menu>
<MenuTrigger
- disabled={disabled || isResponding}
- render={<Button size="icon-xs" variant="outline" aria-label="More approval options" />}
+ disabled={disabled || isResponding || !canRespond}
+ render={
+ presentation === "inline" ? (
+ <InlineButton tone="muted" aria-label="More approval options" />
+ ) : (
+ <Button size="icon-xs" variant="outline" aria-label="More approval options" />
+ )
+ }
>
- <EllipsisIcon />
+ {presentation === "inline" ? "More" : <EllipsisIcon />}
</MenuTrigger>
<MenuPopup {...composerFloatingLayerProps} side="top" align="end" width="content">
{moreOptions.map((option) => {
const item = (
<MenuItem
key={option.decision}
- disabled={disabled || isResponding}
+ disabled={disabled || isResponding || !canRespond}
aria-description={option.warning}
onClick={() => {
- if (!disabled && !isResponding)
+ if (!disabled && !isResponding && canRespond)
void onRespondToApproval(requestId, option.decision);
}}
>
diff --git a/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx b/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx
deleted file mode 100644
index 16ee9c83719..00000000000
--- a/apps/web/src/components/chat/ComposerPendingApprovalPanel.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-import {
- FULL_ACCESS_OVERRIDE_QUESTION,
- fullAccessOverrideExplanation,
-} from "@t3tools/client-runtime/state/thread-requests";
-import { memo } from "react";
-import { type PendingApproval } from "../../session-logic";
-import { InlineButton } from "../ui/button";
-import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
-import { composerFloatingLayerProps } from "./composerEventScope";
-import { cn } from "~/lib/utils";
-
-interface ComposerPendingApprovalPanelProps {
- approval: PendingApproval;
- pendingCount: number;
- className?: string;
-}
-
-export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprovalPanel({
- approval,
- pendingCount,
- className,
-}: ComposerPendingApprovalPanelProps) {
- const Detail = approval.requestKind === "mcp-elicitation" ? "span" : "code";
- const fallbackLabel =
- approval.requestKind === "mcp-elicitation"
- ? "App access approval"
- : approval.requestKind === "command"
- ? "Command approval"
- : approval.requestKind === "file-read"
- ? "File read approval"
- : approval.requestKind === "permission"
- ? "App permission approval"
- : "File change approval";
- const detailAriaLabel =
- approval.requestKind === "mcp-elicitation"
- ? "App access request"
- : approval.requestKind === "command"
- ? "Command"
- : approval.requestKind === "file-read"
- ? "File to read"
- : approval.requestKind === "permission"
- ? "Permission request"
- : "File change";
-
- return (
- <span
- aria-label={fallbackLabel}
- className={cn("flex min-w-0 flex-1 flex-col items-start gap-1", className)}
- role="group"
- >
- <span className="flex w-full min-w-0 items-center gap-2 text-2xs text-muted-foreground">
- <span className="shrink-0 font-medium text-warning">{fallbackLabel}</span>
- {approval.appName ? <span className="min-w-0 truncate">{approval.appName}</span> : null}
- {approval.fullAccessOverride ? (
- <Popover>
- <PopoverTrigger openOnHover render={<InlineButton tone="muted" />}>
- {FULL_ACCESS_OVERRIDE_QUESTION}
- </PopoverTrigger>
- <PopoverPopup
- {...composerFloatingLayerProps}
- aria-label={FULL_ACCESS_OVERRIDE_QUESTION}
- tooltipStyle
- side="top"
- className="max-w-[min(22rem,calc(100vw-2rem))] whitespace-normal"
- >
- {fullAccessOverrideExplanation(approval.fullAccessOverride)}
- </PopoverPopup>
- </Popover>
- ) : null}
- {pendingCount > 1 ? (
- <span className="ml-auto shrink-0 tabular-nums">1/{pendingCount}</span>
- ) : null}
- </span>
- <Detail
- aria-label={detailAriaLabel}
- className={cn(
- "block w-full min-w-0 overflow-auto text-xs text-foreground [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",
- approval.requestKind === "mcp-elicitation"
- ? "max-h-20 whitespace-pre-wrap font-sans wrap-break-word"
- : "max-h-40 whitespace-pre-wrap font-mono wrap-anywhere",
- )}
- data-approval-detail="complete"
- tabIndex={0}
- >
- {approval.responseCapability === "not_resumable"
- ? "Provider process is gone. Interrupt or restart the run to respond."
- : approval.detail || fallbackLabel}
- </Detail>
- {approval.reason ? (
- <span className="w-full min-w-0 text-2xs text-muted-foreground wrap-break-word">
- {approval.reason}
- </span>
- ) : null}
- </span>
- );
-});
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index bde0d35c90e..2c7aa332756 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -1,11 +1,14 @@
import { AudioPreview } from "../files/AudioPreview";
import { onTestFinished } from "vite-plus/test";
+import { page } from "vite-plus/test/browser";
import { stubGlobal } from "../../../test/render";
import {
EnvironmentId,
MessageId,
RunAttemptId,
RunId,
+ RuntimeRequestId,
+ TurnItemId,
ScheduledTaskId,
ThreadId,
} from "@t3tools/contracts";
@@ -18,7 +21,10 @@ import "~/index.css";
import { act, fakeTimers, render } from "../../../test/render";
import { MessagesTimeline } from "./MessagesTimeline";
import { makeStreamingTimelineFixture } from "../../test-fixtures";
-import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic";
+import {
+ type PendingApproval,
+ deriveTimelineEntriesFromVisibleTurnItems,
+} from "../../session-logic";
import { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
import { collectThreadFindRanges } from "./threadFindHighlights";
@@ -990,3 +996,172 @@ it("renders automatic compaction as one live divider that finishes with its reas
expect(container.querySelectorAll('[role="separator"]')).toHaveLength(1);
expect(container.textContent).not.toContain("Compacting before");
});
+
+it("keeps concurrent approvals actionable outside collapsed work and restores settled rows", async () => {
+ setup();
+ const fixture = makeStreamingTimelineFixture();
+ const source = fixture.visibleTurnItems[4]!;
+ if (source.item.type !== "dynamic_tool") throw new Error("Expected fixture tool");
+ const sourceItem = source.item;
+ const commandRequest = RuntimeRequestId.make("command-approval");
+ const appRequest = RuntimeRequestId.make("app-approval");
+ const approvals: PendingApproval[] = [
+ {
+ requestId: commandRequest,
+ requestKind: "command",
+ createdAt: fixture.time(6),
+ detail: "printf '" + "long-command ".repeat(80) + "'",
+ reason: "Needs permission to run the command",
+ fullAccessOverride: "ask_rule",
+ responseCapability: "live",
+ },
+ {
+ requestId: appRequest,
+ requestKind: "permission",
+ createdAt: fixture.time(6),
+ detail: "Open the current tab",
+ appName: "Safari",
+ options: [
+ { decision: "decline", label: "Deny" },
+ { decision: "accept", label: "Allow once" },
+ {
+ decision: "acceptAlways",
+ label: "Always allow Safari",
+ warning: "Applies to future requests",
+ },
+ ],
+ responseCapability: "live",
+ },
+ ];
+ const entries = (completed = false) =>
+ deriveTimelineEntriesFromVisibleTurnItems({
+ visibleTurnItems: [
+ { ...source, item: { ...sourceItem, status: completed ? "completed" : sourceItem.status } },
+ ...approvals.map((approval, index) => ({
+ ...source,
+ position: source.position + index + 1,
+ sourceItemId: TurnItemId.make(`approval-${index}`),
+ item: {
+ ...sourceItem,
+ id: TurnItemId.make(`approval-${index}`),
+ type: "approval_request" as const,
+ status: completed ? ("completed" as const) : ("waiting" as const),
+ requestId: approval.requestId,
+ requestKind: approval.requestKind,
+ prompt: approval.detail,
+ },
+ })),
+ ],
+ optimisticMessages: [],
+ });
+ const props = baseProps();
+ const onRespondToApproval = vi.fn(async () => {});
+ const ui = (overrides: Partial<TimelineProps> = {}) => (
+ <MessagesTimeline
+ {...props}
+ timelineEntries={entries()}
+ pendingApprovals={approvals}
+ canOperateThread
+ onRespondToApproval={onRespondToApproval}
+ isWorking
+ runningRunId={fixture.runId}
+ {...overrides}
+ />
+ );
+ await using screen = await renderElement(ui());
+ await expect.element(screen.getByRole("group", { name: "Command approval" })).toBeVisible();
+ await expect
+ .element(screen.getByRole("group", { name: "App permission approval" }))
+ .toBeVisible();
+ await expect.element(screen.getByText(approvals[0]!.detail!, { exact: true })).toBeVisible();
+ await expect.element(screen.getByText("Needs permission to run the command")).toBeVisible();
+ await vi.waitFor(() => {
+ expect(
+ getComputedStyle(screen.getByLabelText("Command", { exact: true }).element()).userSelect,
+ ).toBe("text");
+ expect(
+ getComputedStyle(screen.getByText("Needs permission to run the command").element())
+ .userSelect,
+ ).toBe("text");
+ });
+ await expect.element(screen.getByText("Safari", { exact: true })).toBeVisible();
+ await click(screen.button("Why am I being asked this?"));
+ await expect.element(page.getByText(/an ask rule in the agent's own settings/)).toBeVisible();
+ await click(screen.button("Why am I being asked this?"));
+ await click(screen.buttons("More approval options")[1]!);
+ await expect.element(page.getByRole("menuitem", { name: "Always allow Safari" })).toBeVisible();
+ await page.getByRole("menuitem", { name: "Always allow Safari" }).click();
+ expect(onRespondToApproval).toHaveBeenLastCalledWith(appRequest, "acceptAlways");
+ await click(screen.buttons("More approval options")[0]!);
+ await expect.element(page.getByRole("menuitem", { name: "Cancel", exact: true })).toBeVisible();
+ await page.getByRole("menuitem", { name: "Always allow this session" }).click();
+ expect(onRespondToApproval).toHaveBeenLastCalledWith(commandRequest, "acceptForSession");
+ await click(screen.button("Decline"));
+ expect(onRespondToApproval).toHaveBeenLastCalledWith(commandRequest, "decline");
+ await click(screen.button("Allow once"));
+ expect(onRespondToApproval).toHaveBeenLastCalledWith(appRequest, "accept");
+ for (const timelineEntries of [entries(), []]) {
+ await screen.rerender(
+ ui({ timelineEntries, heldApprovalRequestIds: new Set([commandRequest]) }),
+ );
+ await expect
+ .element(screen.getByRole("group", { name: "Command approval" }))
+ .not.toBeInTheDocument();
+ await vi.waitFor(() => expect(screen.buttons("Approve")).toHaveLength(0));
+ await expect
+ .element(screen.getByRole("button", { name: "Allow once", exact: true }))
+ .toBeVisible();
+ await screen.rerender(ui({ timelineEntries }));
+ await expect.element(screen.getByRole("group", { name: "Command approval" })).toBeVisible();
+ await vi.waitFor(() => expect(screen.buttons("Approve")).toHaveLength(1));
+ }
+ await screen.rerender(ui({ timelineEntries: [], isWorking: false }));
+ await expect.element(screen.getByRole("group", { name: "Command approval" })).toBeVisible();
+ await click(screen.button("Approve"));
+ expect(onRespondToApproval).toHaveBeenLastCalledWith(commandRequest, "accept");
+ await click(screen.button("Deny"));
+ expect(onRespondToApproval).toHaveBeenLastCalledWith(appRequest, "decline");
+ await screen.rerender(
+ ui({
+ timelineEntries: [],
+ isWorking: false,
+ pendingApprovals: [{ ...approvals[0]!, detail: "" }],
+ }),
+ );
+ await expect
+ .element(screen.getByLabelText("Command", { exact: true }))
+ .toHaveTextContent("Command approval");
+ await screen.rerender(ui({ canOperateThread: false }));
+ await expect.element(screen.getByRole("button", { name: "Approve", exact: true })).toBeDisabled();
+ await vi.waitFor(() =>
+ expect(
+ screen.buttons("More approval options").every((button) => button.hasAttribute("disabled")),
+ ).toBe(true),
+ );
+ await screen.rerender(ui({ respondingRequestIds: [commandRequest] }));
+ await expect.element(screen.getByRole("button", { name: "Approve", exact: true })).toBeDisabled();
+ await expect
+ .element(screen.getByRole("button", { name: "Allow once", exact: true }))
+ .toBeEnabled();
+ await screen.rerender(
+ ui({ pendingApprovals: [{ ...approvals[0]!, responseCapability: "not_resumable" }] }),
+ );
+ await expect
+ .element(screen.getByText("Provider process is gone. Interrupt or restart the run to respond."))
+ .toBeVisible();
+ await vi.waitFor(() => expect(screen.buttons("Approve")).toHaveLength(0));
+ await screen.rerender(
+ ui({ pendingApprovals: [], timelineEntries: entries(true), isWorking: false }),
+ );
+ await expect
+ .element(screen.getByRole("group", { name: "Command approval" }))
+ .not.toBeInTheDocument();
+ await vi.waitFor(() => expect(screen.text()).not.toContain("Waiting for approval"));
+ await screen.getByRole("button", { expanded: false }).click();
+ await expect
+ .element(screen.getByRole("button", { name: approvals[0]!.detail!, exact: true }))
+ .toBeVisible();
+ await expect
+ .element(screen.getByRole("button", { name: "Open the current tab", exact: true }))
+ .toBeVisible();
+});
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
index a3ed14223d8..dfc9c31fb3a 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
@@ -241,6 +241,37 @@ describe("deriveMessagesTimelineRows", () => {
expect(rows.some((row) => row.kind === "event")).toBe(false);
expect(workRows[0]).not.toMatchObject({ expanded: true });
expect(workRows[0]).not.toMatchObject({ isExpandedToolGroup: true });
+ const pendingRows = deriveMessagesTimelineRows({
+ timelineEntries: entries,
+ pendingApprovalRequestIds: new Set([RuntimeRequestId.make("approval-request")]),
+ isWorking: status === "waiting",
+ runningRunId: fixture.runId,
+ activeTurnStartedAt: fixture.time(0),
+ turnDiffSummaries: [],
+ supportsConversationRollback: false,
+ });
+ expect(pendingRows.filter((row) => row.kind === "work")).toContainEqual(
+ expect.objectContaining({
+ groupedEntries: [expect.objectContaining({ itemType: "approval_request" })],
+ isExpandedToolGroup: false,
+ }),
+ );
+ expect(
+ pendingRows
+ .filter((row) => row.kind === "work-live")
+ .flatMap((row) => row.groupedEntries)
+ .some((entry) => entry.itemType === "approval_request"),
+ ).toBe(false);
+ const approvalOnlyRows = deriveMessagesTimelineRows({
+ timelineEntries: entries.slice(1, 2),
+ pendingApprovalRequestIds: new Set([RuntimeRequestId.make("approval-request")]),
+ isWorking: status === "waiting",
+ runningRunId: fixture.runId,
+ activeTurnStartedAt: fixture.time(0),
+ turnDiffSummaries: [],
+ supportsConversationRollback: false,
+ });
+ expect(approvalOnlyRows.some((row) => row.kind === "thinking")).toBe(false);
},
);
@@ -3027,6 +3058,7 @@ describe("streaming v2 row projection", () => {
const previous = deriveMessagesTimelineRowsWithState({
...initial.input,
availableRevertTurnCounts: new Set([0]),
+ pendingApprovalRequestIds: new Set<RuntimeRequestId>(),
});
Object.freeze(previous.rows);
for (const row of previous.rows) Object.freeze(row);
@@ -3044,6 +3076,7 @@ describe("streaming v2 row projection", () => {
latestRun: { ...initial.input.latestRun },
turnDiffSummaries: initial.input.turnDiffSummaries.map((summary) => ({ ...summary })),
availableRevertTurnCounts: new Set([0]),
+ pendingApprovalRequestIds: new Set<RuntimeRequestId>(),
};
const next = deriveMessagesTimelineRowsWithState(input, previous);
expect(next.rows).toEqual(
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts
index fe38e16bb78..f771c1ed0d0 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts
@@ -55,6 +55,7 @@ import {
type WorktreeSetupSnapshot,
type OrchestrationV2ProjectedTurnItem,
type RunAttemptId,
+ type RuntimeRequestId,
RunId,
type ThreadId,
type TurnItemId,
@@ -1345,6 +1346,7 @@ function deriveTimelineTurnFolds(
export function deriveMessagesTimelineRows(input: {
timelineEntries: ReadonlyArray<TimelineEntry>;
+ pendingApprovalRequestIds?: ReadonlySet<RuntimeRequestId>;
latestRun?: TimelineLatestRun | null;
runningRunId?: RunId | null;
expandedRunIds?: ReadonlySet<RunId>;
@@ -1361,6 +1363,13 @@ export function deriveMessagesTimelineRows(input: {
worktreeSetup?: WorktreeSetupSnapshot | null;
}): MessagesTimelineRow[] {
const timelineEntries = timelineRowEntries(input.timelineEntries);
+ const isPendingApproval = (entry: WorkLogEntry) => {
+ const item = entry.projectedItem?.item;
+ return (
+ item?.type === "approval_request" &&
+ input.pendingApprovalRequestIds?.has(item.requestId) === true
+ );
+ };
const turnDiffSummaryByAssistantMessageId = new Map<MessageId, TurnDiffSummary>();
for (const summary of input.turnDiffSummaries) {
if (summary.assistantMessageId) {
@@ -1423,6 +1432,14 @@ export function deriveMessagesTimelineRows(input: {
}
}
}
+ if (input.pendingApprovalRequestIds?.size) {
+ for (const entry of timelineEntries) {
+ if (entry.kind === "work" && isPendingApproval(entry.entry)) {
+ collapsedEntryIds.delete(entry.id);
+ collapsedSupersededEntryIds.delete(entry.id);
+ }
+ }
+ }
const runIdIsActiveResponse = (runId: RunId | null | undefined) =>
runId == null ? runlessWorkActive : activeVisualResponseRunIds.has(runId);
const workEntryIsInActiveRun = (entry: WorkLogEntry) =>
@@ -1446,6 +1463,7 @@ export function deriveMessagesTimelineRows(input: {
entry.entry.itemType === "system_notice" ||
entry.entry.itemType === "notification" ||
entry.entry.questionAnswer !== undefined ||
+ isPendingApproval(entry.entry) ||
!runIdIsActiveResponse(entry.entry.runId) ||
entry.entry.sourceActivityKind === "context-compaction" ||
collapsedEntryIds.has(entry.id) ||
@@ -1475,7 +1493,8 @@ export function deriveMessagesTimelineRows(input: {
const latestToolKeepsActivityLive =
latestRunningToolEntry !== undefined ||
(latestVisibleToolEntry !== undefined &&
- workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry));
+ workEntryIndicatesToolSuccess(latestVisibleToolEntry.entry) &&
+ !input.pendingApprovalRequestIds?.size);
const latestToolFailed =
latestRunningToolEntry === undefined &&
latestVisibleToolEntry !== undefined &&
@@ -1717,6 +1736,7 @@ export function deriveMessagesTimelineRows(input: {
if (timelineEntry.kind === "work") {
if (
+ isPendingApproval(timelineEntry.entry) ||
(timelineEntry.entry.runId != null && failedRunIds.has(timelineEntry.entry.runId)) ||
(timelineEntry.entry.itemType === "error" &&
timelineEntry.entry.toolLifecycleStatus === "failed") ||
@@ -1748,6 +1768,7 @@ export function deriveMessagesTimelineRows(input: {
nextEntry.entry.itemType === "system_notice" ||
nextEntry.entry.itemType === "notification" ||
nextEntry.entry.questionAnswer !== undefined ||
+ isPendingApproval(nextEntry.entry) ||
activeWorkEntryIds.has(nextEntry.id) ||
collapsedEntryIds.has(nextEntry.id) ||
collapsedSupersededEntryIds.has(nextEntry.id) ||
@@ -2023,7 +2044,7 @@ export function deriveMessagesTimelineRows(input: {
!setupOwnsWorkingSlot &&
!hasActiveCompaction &&
!compactionOnlyRunFinished &&
- (!hasActivityRow || latestToolFailed)
+ (latestToolFailed || (!hasActivityRow && !input.pendingApprovalRequestIds?.size))
) {
const failedGroupAnchor = latestToolFailed ? activeWorkAnchor : undefined;
if (failedGroupAnchor) {
@@ -2173,6 +2194,7 @@ function replaceStreamingMessageRows(
expandedRunIds: previousExpandedRuns,
expandedAttemptIds: previousExpandedAttempts,
expandedWorkGroupIds: previousExpandedGroups,
+ pendingApprovalRequestIds: previousPendingApprovalRequestIds,
availableRevertTurnCounts: previousAvailableRevertTurnCounts,
...previousContext
} = previous.input;
@@ -2183,6 +2205,7 @@ function replaceStreamingMessageRows(
expandedRunIds,
expandedAttemptIds,
expandedWorkGroupIds,
+ pendingApprovalRequestIds,
availableRevertTurnCounts,
...context
} = input;
@@ -2194,6 +2217,7 @@ function replaceStreamingMessageRows(
!shallow(previousExpandedRuns, expandedRunIds) ||
!shallow(previousExpandedAttempts, expandedAttemptIds) ||
!shallow(previousExpandedGroups, expandedWorkGroupIds) ||
+ !shallow(previousPendingApprovalRequestIds, pendingApprovalRequestIds) ||
!shallow(previousAvailableRevertTurnCounts, availableRevertTurnCounts) ||
!sameCheckpointSummaries(previousCheckpoints, turnDiffSummaries)
) {
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index f5cc45730c3..a166a25e477 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -3,6 +3,7 @@ import { ThreadFindTimelineContext } from "./ThreadFindProvider";
import { MarkdownFindContext } from "./markdownFindContext";
import { useChatCanvas } from "./ChatCanvasContext";
import { WorkLogBlock } from "./WorkLog";
+import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow";
import type { WorktreeSetupSnapshot } from "@t3tools/contracts";
import { deriveTimelineMinimapItems } from "./timelineMinimapItems";
import {
@@ -22,6 +23,9 @@ import { observeResize } from "~/lib/observeResize";
import { useStableCallback } from "~/hooks/useStableCallback";
const NOOP_USE_ARTIFACT_TEMPLATE = () => {};
+const EMPTY_PENDING_APPROVALS: ReadonlyArray<PendingApproval> = [];
+const EMPTY_RESPONDING_REQUEST_IDS: TimelineRowSharedState["respondingRequestIds"] = [];
+
const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
@@ -41,7 +45,7 @@ import {
type LegendListRef,
type MaintainScrollAtEndOptions,
} from "@legendapp/list/react";
-import { type TimelineEntry } from "../../session-logic";
+import { type PendingApproval, type TimelineEntry } from "../../session-logic";
import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
import { type ChatFileAttachment, type TurnDiffSummary } from "../../types";
import { ArrowRightIcon, BotIcon, CircleAlertIcon, Minimize2Icon } from "lucide-react";
@@ -197,6 +201,11 @@ export interface MessagesTimelineHistoryControls {
}
interface MessagesTimelineProps {
+ pendingApprovals?: ReadonlyArray<PendingApproval>;
+ heldApprovalRequestIds?: ReadonlySet<string> | undefined;
+ respondingRequestIds?: TimelineRowSharedState["respondingRequestIds"];
+ canOperateThread?: boolean;
+ onRespondToApproval?: TimelineRowSharedState["onRespondToApproval"];
citationRequest?: AssistantCitationRequest | null;
citationHistory?: CitedHistory;
onCiteAssistantText?: (
@@ -304,6 +313,11 @@ export function MessagesTimeline(props: MessagesTimelineProps) {
}
const ConversationTimeline = memo(function ConversationTimeline({
+ pendingApprovals = EMPTY_PENDING_APPROVALS,
+ heldApprovalRequestIds,
+ respondingRequestIds = EMPTY_RESPONDING_REQUEST_IDS,
+ canOperateThread = false,
+ onRespondToApproval,
citationRequest = null,
citationHistory = CITED_HISTORY_LOADING,
onCiteAssistantText,
@@ -650,8 +664,15 @@ const ConversationTimeline = memo(function ConversationTimeline({
? new Set(paintedExpandedAttemptIds).add(activeFindAttemptId)
: paintedExpandedAttemptIds;
+ const pendingApprovalsByRequestId = new Map(
+ pendingApprovals
+ .filter((approval) => !heldApprovalRequestIds?.has(approval.requestId))
+ .map((approval) => [approval.requestId, approval]),
+ );
+ const pendingApprovalRequestIds = new Set(pendingApprovalsByRequestId.keys());
const rawRows = useIncrementalTimelineRows(`${listIdentityKey}\0${workspaceRoot ?? ""}`, {
timelineEntries,
+ pendingApprovalRequestIds,
latestRun,
runningRunId,
expandedRunIds: visibleExpandedRunIds,
@@ -667,6 +688,17 @@ const ConversationTimeline = memo(function ConversationTimeline({
worktreeSetup,
});
const rows = useStableRows(rawRows, listIdentityKey);
+ const unmatchedPendingApprovals = new Map(pendingApprovalsByRequestId);
+ if (unmatchedPendingApprovals.size > 0) {
+ for (const row of rows) {
+ const entries =
+ row.kind === "work" ? row.groupedEntries : row.kind === "work-live" ? [row.entry] : [];
+ for (const entry of entries) {
+ const item = entry.projectedItem?.item;
+ if (item?.type === "approval_request") unmatchedPendingApprovals.delete(item.requestId);
+ }
+ }
+ }
// Run status/timestamps change per stream event; keep them out of shared row context.
const runs = useStableHandoffRuns(runsProp);
const minimapItems = deriveTimelineMinimapItems(rows);
@@ -679,6 +711,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined;
const showsEmptyState =
rows.length === 0 &&
+ unmatchedPendingApprovals.size === 0 &&
!isWorking &&
parentThreadLink === null &&
historyControls === undefined &&
@@ -720,6 +753,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
listRef,
rememberedPosition,
restoreReady,
+ viewportRef,
]);
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
@@ -805,15 +839,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
size: true,
shouldRestorePosition: shouldRestoreVisibleContentPosition,
};
- const timelineListFooter = (
- <TimelineListFooter
- composerInset={anchoredEndSpace ? 0 : contentInsetEndAdjustment}
- onGrow={onFooterGrow}
- >
- {footer}
- </TimelineListFooter>
- );
-
const measureContentOverflow = () =>
timelineContentOverflowsViewport(listRef.current?.getState?.(), {
composerInset: contentInsetEndAdjustment,
@@ -1003,6 +1028,10 @@ const ConversationTimeline = memo(function ConversationTimeline({
};
const sharedState: TimelineRowSharedState = {
+ pendingApprovals: pendingApprovalsByRequestId,
+ respondingRequestIds,
+ canOperateThread,
+ onRespondToApproval,
citationRequest: readyCitationRequest,
listRef,
timestampFormat,
@@ -1230,6 +1259,30 @@ const ConversationTimeline = memo(function ConversationTimeline({
</TimelineRowCtx>
);
const listExtraData = { identity: listIdentityKey, rowCount: rows.length, sharedState };
+ const timelineListFooter = (
+ <TimelineListFooter
+ composerInset={anchoredEndSpace ? 0 : contentInsetEndAdjustment}
+ onGrow={onFooterGrow}
+ >
+ {footer}
+ {unmatchedPendingApprovals.size > 0 ? (
+ <TimelineRowCtx value={sharedState}>
+ <div className="messages-timeline-row-frame">
+ <div
+ className="@container/chat-lane chat-content-lane overflow-x-clip"
+ data-timeline-root="true"
+ >
+ <WorkLogBlock>
+ {[...unmatchedPendingApprovals.values()].map((approval) => (
+ <TimelinePendingApprovalRow key={approval.requestId} approval={approval} />
+ ))}
+ </WorkLogBlock>
+ </div>
+ </div>
+ </TimelineRowCtx>
+ ) : null}
+ </TimelineListFooter>
+ );
const forwardMinimapWheel = (event: WheelEvent) => {
const scrollNode = listRef.current?.getScrollableNode();
diff --git a/apps/web/src/components/chat/TimelinePendingApprovalRow.tsx b/apps/web/src/components/chat/TimelinePendingApprovalRow.tsx
new file mode 100644
index 00000000000..c425d560bf1
--- /dev/null
+++ b/apps/web/src/components/chat/TimelinePendingApprovalRow.tsx
@@ -0,0 +1,122 @@
+import {
+ FULL_ACCESS_OVERRIDE_QUESTION,
+ fullAccessOverrideExplanation,
+} from "@t3tools/client-runtime/state/thread-requests";
+import { ShieldIcon } from "lucide-react";
+import { memo, use } from "react";
+import { type PendingApproval } from "../../session-logic";
+import { InlineButton } from "../ui/button";
+import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
+import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";
+import { ToolActivityIconView, type WorkEntryIconName } from "./TimelineToolActivityIcon";
+import { TimelineRowCtx } from "./timelineRowContext";
+import { WorkLogRow } from "./WorkLog";
+
+const APPROVAL_PRESENTATION = {
+ command: { icon: "terminal", label: "Command approval", detailLabel: "Command" },
+ "file-change": { icon: "square-pen", label: "File change approval", detailLabel: "File change" },
+ "file-read": { icon: "eye", label: "File read approval", detailLabel: "File to read" },
+ permission: {
+ icon: "wrench",
+ label: "App permission approval",
+ detailLabel: "Permission request",
+ },
+ "mcp-elicitation": {
+ icon: "hammer",
+ label: "App access approval",
+ detailLabel: "App access request",
+ },
+} satisfies Record<
+ PendingApproval["requestKind"],
+ { icon: WorkEntryIconName; label: string; detailLabel: string }
+>;
+
+export const TimelinePendingApprovalRow = memo(function TimelinePendingApprovalRow({
+ approval,
+}: {
+ approval: PendingApproval;
+}) {
+ const { respondingRequestIds, canOperateThread, onRespondToApproval } = use(TimelineRowCtx);
+ const presentation = APPROVAL_PRESENTATION[approval.requestKind];
+ const canRespond = approval.responseCapability === "live";
+ return (
+ <WorkLogRow
+ role="group"
+ aria-label={presentation.label}
+ data-v2-item-type="approval_request"
+ wrapLabel
+ icon={
+ <ToolActivityIconView
+ icon={undefined}
+ fallbackName={presentation.icon}
+ className="block size-4 shrink-0 stroke-2 text-icon-muted"
+ muted
+ />
+ }
+ label={
+ <code
+ aria-label={presentation.detailLabel}
+ className="block max-h-40 min-w-0 overflow-auto whitespace-pre-wrap font-mono text-xs leading-5 text-foreground select-text! wrap-anywhere [scrollbar-width:thin] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
+ data-approval-detail="complete"
+ tabIndex={0}
+ >
+ {approval.detail || presentation.label}
+ </code>
+ }
+ >
+ <div className="ms-7.5 flex min-w-0 flex-col gap-1 pb-1 text-xs">
+ {approval.appName ? (
+ <span className="text-muted-foreground wrap-anywhere">{approval.appName}</span>
+ ) : null}
+ {approval.reason ? (
+ <span className="text-muted-foreground select-text wrap-anywhere">{approval.reason}</span>
+ ) : null}
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ {canRespond ? (
+ <>
+ <span className="inline-flex items-center gap-1 text-warning">
+ <ShieldIcon aria-hidden className="size-3 shrink-0" />
+ Waiting for approval
+ </span>
+ {onRespondToApproval ? (
+ <>
+ <span aria-hidden className="text-muted-foreground">
+ ·
+ </span>
+ <ComposerPendingApprovalActions
+ presentation="inline"
+ requestId={approval.requestId}
+ disabled={!canOperateThread}
+ isResponding={respondingRequestIds.includes(approval.requestId)}
+ canRespond={canRespond}
+ options={approval.options}
+ onRespondToApproval={onRespondToApproval}
+ />
+ </>
+ ) : null}
+ </>
+ ) : (
+ <span className="text-warning">
+ Provider process is gone. Interrupt or restart the run to respond.
+ </span>
+ )}
+ {approval.fullAccessOverride ? (
+ <Popover>
+ <PopoverTrigger openOnHover render={<InlineButton tone="muted" />}>
+ {FULL_ACCESS_OVERRIDE_QUESTION}
+ </PopoverTrigger>
+ <PopoverPopup
+ aria-label={FULL_ACCESS_OVERRIDE_QUESTION}
+ tooltipStyle
+ side="top"
+ className="max-w-[min(22rem,calc(100vw-2rem))] whitespace-normal"
+ >
+ {fullAccessOverrideExplanation(approval.fullAccessOverride)}
+ </PopoverPopup>
+ </Popover>
+ ) : null}
+ </div>
+ </div>
+ </WorkLogRow>
+ );
+});
diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx
index 49c2b8c411e..94d001be7e5 100644
--- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx
+++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx
@@ -1,3 +1,4 @@
+import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow";
import { WorkLogDetails, WorkLogRow } from "./WorkLog";
import {
getQuestionAnswerPreview,
@@ -198,6 +199,11 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {
setExpanded(next);
};
const failureItem = workEntry.projectedItem?.item;
+ const pendingApproval =
+ failureItem?.type === "approval_request"
+ ? ctx.pendingApprovals.get(failureItem.requestId)
+ : undefined;
+ if (pendingApproval) return <TimelinePendingApprovalRow approval={pendingApproval} />;
if (failureItem?.type === "error" && failureItem.status === "failed") {
const warning = failureItem.failure.class === "usage_limit";
const resetAt = failureItem.failure.resetAt;
diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx
index 22d17e5e748..a440b62a584 100644
--- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx
+++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx
@@ -1,3 +1,4 @@
+import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow";
import { WorkLogButton, WorkLogList, WorkLogRow } from "./WorkLog";
import type { WorktreeSetupSnapshot } from "@t3tools/contracts";
import { type ToolActivityIcon } from "@t3tools/contracts";
@@ -66,12 +67,17 @@ export const WorkGroupSection = memo(function WorkGroupSection({
isExpandedToolGroup: boolean;
displayLabel?: string | undefined;
}) {
- const { workspaceRoot, routeThreadKey, onToggleWorkEntry } = use(TimelineRowCtx);
+ const { workspaceRoot, routeThreadKey, onToggleWorkEntry, pendingApprovals } =
+ use(TimelineRowCtx);
const onToggleStandaloneEntry = (collapsed: boolean) =>
onToggleWorkEntry(disclosureAnchorKey, collapsed);
- const nonEmptyEntries = groupedEntries.filter((entry) =>
- workEntryIsVisibleInGroup(entry, isExpandedToolGroup),
- );
+ const nonEmptyEntries = groupedEntries.filter((entry) => {
+ const item = entry.projectedItem?.item;
+ return (
+ (item?.type === "approval_request" && pendingApprovals.has(item.requestId)) ||
+ workEntryIsVisibleInGroup(entry, isExpandedToolGroup)
+ );
+ });
if (nonEmptyEntries.length === 0) return null;
if (isExpandedToolGroup && nonEmptyEntries.every((entry) => entry.itemType === "reasoning")) {
@@ -355,7 +361,11 @@ export function ThinkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind:
const ctx = use(TimelineRowCtx);
const { isCompacting, isPreparingWorktree } = use(TimelineRowActivityCtx);
if (isPreparingWorktree || isCompacting) return <WorkLogRow label="" />;
- const activity = <LiveActivityRow label="Thinking" iconName="brain" active shimmer />;
+ // A failed group keeps this disclosure while an approval waits, but nothing is thinking then.
+ const live = ctx.pendingApprovals.size === 0;
+ const activity = (
+ <LiveActivityRow label="Thinking" iconName="brain" active={live} shimmer={live} />
+ );
const { groupId } = row;
if (groupId === undefined) return activity;
return (
@@ -484,6 +494,11 @@ export function LiveWorkEntryTimelineRow({
const label = liveWorkEntryLabel(row.entry, ctx.workspaceRoot, row.active);
const threadLabel = threadReadLabel(label, threadTarget);
+ const item = row.entry.projectedItem?.item;
+ const pendingApproval =
+ item?.type === "approval_request" ? ctx.pendingApprovals.get(item.requestId) : undefined;
+ if (pendingApproval) return <TimelinePendingApprovalRow approval={pendingApproval} />;
+
const failed = workEntryDisplayIndicatesToolFailure(row.entry);
const thoughtLine = row.thought && !row.expanded ? liveThoughtLine(row.thought.detail ?? "") : "";
const thoughtIsStatus = thoughtLine !== "" && row.entry === row.thought;
diff --git a/apps/web/src/components/chat/composerTypingGuard.test.ts b/apps/web/src/components/chat/composerTypingGuard.test.ts
index b9138362f42..e98b7c80087 100644
--- a/apps/web/src/components/chat/composerTypingGuard.test.ts
+++ b/apps/web/src/components/chat/composerTypingGuard.test.ts
@@ -19,6 +19,9 @@ describe("composer typing guard", () => {
});
state = updateComposerTypingGuard(state, { type });
expect([...state.held]).toEqual([]);
+ const released = state.held;
+ state = updateComposerTypingGuard(state, { type });
+ expect(state.held).toBe(released);
state = updateComposerTypingGuard(state, { type: "focus" });
state = updateComposerTypingGuard(state, { type: "type", now: 2000 });
state = updateComposerTypingGuard(state, { type: "requests", requestIds: [], now: 2100 });
@@ -37,13 +40,16 @@ describe("composer typing guard", () => {
requestIds: ["question"],
now: 0,
});
+ const held = state.held;
state = updateComposerTypingGuard(state, { type: "focus" });
state = updateComposerTypingGuard(state, { type: "type", now: 1000 });
+ expect(state.held).toBe(held);
state = updateComposerTypingGuard(state, {
type: "requests",
requestIds: ["question"],
now: 1100,
});
expect([...state.held]).toEqual([]);
+ expect(state.held).toBe(held);
});
});
diff --git a/apps/web/src/components/chat/composerTypingGuard.ts b/apps/web/src/components/chat/composerTypingGuard.ts
index 01c9cca77d4..1f72b98b140 100644
--- a/apps/web/src/components/chat/composerTypingGuard.ts
+++ b/apps/web/src/components/chat/composerTypingGuard.ts
@@ -32,7 +32,14 @@ export function updateComposerTypingGuard(
}
seen.add(id);
}
- return { ...state, seen, held };
+ return {
+ ...state,
+ seen,
+ held:
+ held.size === state.held.size && [...held].every((id) => state.held.has(id))
+ ? state.held
+ : held,
+ };
}
case "type":
return { ...state, lastTypedAt: event.now };
@@ -43,7 +50,7 @@ export function updateComposerTypingGuard(
case "idle":
return {
...state,
- held: new Set<string>(),
+ held: state.held.size === 0 ? state.held : new Set<string>(),
lastTypedAt: -Infinity,
focused: event.type === "blur" ? false : state.focused,
};
diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts
index e38dfecffd0..b3677b33de7 100644
--- a/apps/web/src/components/chat/timelineRowContext.ts
+++ b/apps/web/src/components/chat/timelineRowContext.ts
@@ -1,4 +1,8 @@
-import type { WorktreeSetupSnapshot } from "@t3tools/contracts";
+import type {
+ ProviderApprovalDecision,
+ RuntimeRequestId,
+ WorktreeSetupSnapshot,
+} from "@t3tools/contracts";
import {
type EnvironmentId,
type MessageId,
@@ -16,6 +20,7 @@ import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRunt
import { createContext, type MouseEvent, type ReactNode } from "react";
import { type LegendListRef } from "@legendapp/list/react";
import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
+import type { PendingApproval } from "../../session-logic";
import { type ChatFileAttachment } from "../../types";
import { ExpandedImagePreview } from "./ExpandedImagePreview";
import { type AssistantCitationTarget } from "./AssistantCitationSource";
@@ -37,6 +42,12 @@ export interface TurnItemSource {
}
export interface TimelineRowSharedState {
+ pendingApprovals: ReadonlyMap<RuntimeRequestId, PendingApproval>;
+ respondingRequestIds: ReadonlyArray<RuntimeRequestId>;
+ canOperateThread: boolean;
+ onRespondToApproval:
+ | ((requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => Promise<unknown>)
+ | undefined;
citationRequest: AssistantCitationTarget | null;
listRef: React.RefObject<LegendListRef | null>;
timestampFormat: TimestampFormat;