TypeScript
feat(clients): surface child approvals in parent threads (#28516)
Yash Singh70f475f51127
diff --git a/apps/mobile/src/features/threads/ChildThreadApprovals.tsx b/apps/mobile/src/features/threads/ChildThreadApprovals.tsxnew file mode 100644index 00000000000..392d185e9af--- /dev/null+++ b/apps/mobile/src/features/threads/ChildThreadApprovals.tsx@@ -0,0 +1,88 @@+import { useAtomValue } from "@effect/atom-react";+import { AuthOrchestrationOperateScope, type ScopedThreadRef } from "@t3tools/contracts";+import type { ChildThreadApproval } from "@t3tools/client-runtime/state/thread-requests";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import { useState } from "react";+import { useEnvironmentScope } from "../../state/session";+import { ScrollView, View } from "react-native";+import Animated, { useAnimatedStyle, type DerivedValue } from "react-native-reanimated";+import { AppText } from "../../components/ui/AppText";+import { childThreadApprovalsAtom, threadEnvironment } from "../../state/threads";+import { useAtomCommand } from "../../state/use-atom-command";+import { PendingApprovalCard } from "./PendingApprovalCard";++function ChildApproval({ entry }: { entry: ChildThreadApproval }) {+ const canRespond = useEnvironmentScope(entry.thread.environmentId, AuthOrchestrationOperateScope);+ const respond = useAtomCommand(threadEnvironment.respondToApproval, { reportFailure: false });+ const [responding, setResponding] = useState(false);+ const [error, setError] = useState<string | null>(null);+ return (+ <View className="mx-3.5 my-2 gap-2">+ <AppText className="font-t3-bold text-sm text-foreground">+ Approval from {entry.title}+ </AppText>+ <PendingApprovalCard+ canOperateThread={canRespond}+ approval={entry.approval}+ respondingApprovalId={responding ? entry.approval.requestId : null}+ onRespond={async (requestId, decision) => {+ if (!canRespond || responding) return;+ setResponding(true);+ setError(null);+ const result = await respond({+ environmentId: entry.thread.environmentId,+ input: { threadId: entry.thread.threadId, requestId, decision },+ });+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ const failure = squashAtomCommandFailure(result);+ setError(+ failure instanceof Error ? failure.message : "Failed to submit approval decision.",+ );+ }+ setResponding(false);+ return result;+ }}+ />+ {error !== null ? (+ <AppText+ accessibilityRole="alert"+ accessibilityLiveRegion="polite"+ className="font-sans text-sm text-danger-foreground"+ >+ {error}+ </AppText>+ ) : null}+ </View>+ );+}++export function ChildThreadApprovals({+ threadRef,+ maxHeight,+}: {+ threadRef: ScopedThreadRef | null;+ maxHeight: DerivedValue<number>;+}) {+ const approvals = useAtomValue(childThreadApprovalsAtom(threadRef));+ const heightStyle = useAnimatedStyle(() => ({ maxHeight: Math.min(320, maxHeight.value / 2) }));+ if (approvals.length === 0) return null;+ return (+ <Animated.View style={heightStyle} className="overflow-hidden">+ <ScrollView keyboardShouldPersistTaps="handled" nestedScrollEnabled style={{ flexShrink: 1 }}>+ {approvals.map((entry) => (+ <ChildApproval+ key={JSON.stringify([+ entry.thread.environmentId,+ entry.thread.threadId,+ entry.approval.requestId,+ ])}+ entry={entry}+ />+ ))}+ </ScrollView>+ </Animated.View>+ );+}diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex 870ab31f000..a71920c199f 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -1,3 +1,4 @@+import { ChildThreadApprovals } from "./ChildThreadApprovals";import { useOpenThreadInspector } from "./thread-inspector-navigation";import { useSidebarWorkspaceTabs } from "../workspace/useSystemWorkspaceTabBar";import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";@@ -306,6 +307,8 @@ export interface ThreadDetailScreenProps {readonly showContent?: boolean;}+// iOS questions overlay the controls; Android questions stack with child approvals.+const ComposerPanels = Platform.OS === "android" ? Animated.ScrollView : Animated.View;const USAGE_LIMITS_PANEL_GAP = 12;const USAGE_LIMITS_PANEL_MIN_HEIGHT = 44;@@ -960,6 +963,10 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {composerOverlapHeight: composerBottomInset,}),);+ const composerPanelsHeightStyle = useAnimatedStyle(() => ({+ maxHeight: pendingUserInputMaxHeight.value,+ flexGrow: 0,+ }));// The usage panel stacks with the composer and any approval card, so it gets// whatever room they leave below the header. Measured only while it is open// so typing in the composer does not re-render the screen.@@ -1504,130 +1511,141 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {});}}/>- {props.queuedRunEdit !== null ? (- <Animated.View- className="shrink-0"- entering={FadeInDown.duration(180)}- exiting={FadeOut.duration(120)}- >- <ComposerQueuedEditBanner- saving={props.isSavingQueuedEdit}- onCancel={() => {- voiceInputSession.cancel(props.composerDraftKey);- props.onCancelQueuedRunEdit();- }}- />- </Animated.View>- ) : null}- <UsageLimitRecoveryCard- key={props.selectedThread.latestRun?.runId}- thread={props.selectedThread}- environmentId={props.environmentId}- />- <ChatGptUsageLimitNotice- key={`chatgpt-limit:${props.selectedThread.latestRun?.runId}`}- thread={props.selectedThread}- />- <ThreadGuestShareBar- threadRef={props.selectedThreadDetailRef}- canOperateThread={props.canOperateThread}- />- {props.draftMode ? null : (- <ThreadSideChatsRow+ <ComposerPanels+ className="w-full"+ style={Platform.OS === "android" ? composerPanelsHeightStyle : undefined}+ keyboardShouldPersistTaps="handled"+ nestedScrollEnabled+ >+ {props.queuedRunEdit !== null ? (+ <Animated.View+ className="shrink-0"+ entering={FadeInDown.duration(180)}+ exiting={FadeOut.duration(120)}+ >+ <ComposerQueuedEditBanner+ saving={props.isSavingQueuedEdit}+ onCancel={() => {+ voiceInputSession.cancel(props.composerDraftKey);+ props.onCancelQueuedRunEdit();+ }}+ />+ </Animated.View>+ ) : null}+ <UsageLimitRecoveryCard+ key={props.selectedThread.latestRun?.runId}+ thread={props.selectedThread}environmentId={props.environmentId}- threadId={props.selectedThread.id}/>- )}- {props.feedbackSubmissions.map((submission) => (- <ComposerFeedback- key={submission.id}- submission={submission}- onDismiss={() => props.onDismissFeedback(submission.id)}+ <ChatGptUsageLimitNotice+ key={`chatgpt-limit:${props.selectedThread.latestRun?.runId}`}+ thread={props.selectedThread}/>- ))}- {composerError !== null ? (- <Animated.View- className="shrink-0"- entering={FadeInDown.duration(180)}- exiting={FadeOut.duration(120)}- >- <ComposerErrorNotice- message={composerError}- onDismiss={() => clearThreadComposerError(selectedThreadKey)}- />- </Animated.View>- ) : null}- {usageLimitsReport && activeUserInputRequestId === null ? (- <Animated.View- className="shrink-0 px-4"- style={{ paddingBottom: USAGE_LIMITS_PANEL_GAP }}- onLayout={handleUsageLimitsLayout}- entering={FadeInDown.duration(220)}- exiting={FadeOut.duration(140)}- >- <ComposerUsageLimits- report={usageLimitsReport}+ <ChildThreadApprovals+ threadRef={props.selectedThreadDetailRef}+ maxHeight={pendingUserInputMaxHeight}+ />+ <ThreadGuestShareBar+ threadRef={props.selectedThreadDetailRef}+ canOperateThread={props.canOperateThread}+ />+ {props.draftMode ? null : (+ <ThreadSideChatsRowenvironmentId={props.environmentId}- maxHeight={usageLimitsMaxHeight}- onClose={dismissUsageLimits}+ threadId={props.selectedThread.id}/>- </Animated.View>- ) : null}- {props.creationState?.kind === "failed" ? (- <Animated.View- className="shrink-0 px-4"- style={{ paddingBottom: composerBottomInset }}- entering={FadeInDown.duration(220)}- exiting={FadeOut.duration(140)}- >- <ThreadCreationFailedCard- reason={props.creationState.reason}- onEditTask={props.creationState.onEditTask}+ )}+ {props.feedbackSubmissions.map((submission) => (+ <ComposerFeedback+ key={submission.id}+ submission={submission}+ onDismiss={() => props.onDismissFeedback(submission.id)}/>- </Animated.View>- ) : null}- {props.activePendingApproval || props.activePendingUserInput ? (- <Animated.View- className="shrink-0 gap-3 px-4 pb-3"- style={- activeUserInputRequestId !== null- ? { paddingBottom: composerBottomInset }- : undefined- }- entering={FadeInDown.duration(220)}- exiting={FadeOut.duration(140)}- >- {props.activePendingApproval ? (- <PendingApprovalCard- canOperateThread={props.canOperateThread}- approval={props.activePendingApproval}- respondingApprovalId={props.respondingApprovalId}- onRespond={props.onRespondToApproval}+ ))}+ {composerError !== null ? (+ <Animated.View+ className="shrink-0"+ entering={FadeInDown.duration(180)}+ exiting={FadeOut.duration(120)}+ >+ <ComposerErrorNotice+ message={composerError}+ onDismiss={() => clearThreadComposerError(selectedThreadKey)}/>- ) : null}- {props.activePendingUserInput ? (- <PendingUserInputCard+ </Animated.View>+ ) : null}+ {usageLimitsReport && activeUserInputRequestId === null ? (+ <Animated.View+ className="shrink-0 px-4"+ style={{ paddingBottom: USAGE_LIMITS_PANEL_GAP }}+ onLayout={handleUsageLimitsLayout}+ entering={FadeInDown.duration(220)}+ exiting={FadeOut.duration(140)}+ >+ <ComposerUsageLimits+ report={usageLimitsReport}environmentId={props.environmentId}- canOperateThread={props.canOperateThread}- pendingUserInput={props.activePendingUserInput}- maxHeight={pendingUserInputMaxHeight}- collapsed={userInputCollapsed}- onToggleCollapsed={handleToggleUserInputCollapsed}- onStopThread={props.onStopThread}- cardProgress={userInputCardProgress}- cardCoverage={userInputCardCoverage}- onInputFocusChange={handleOwnedInputFocusChange}- drafts={props.activePendingUserInputDrafts}- answers={props.activePendingUserInputAnswers}- respondingUserInputId={props.respondingUserInputId}- onSelectOption={props.onSelectUserInputOption}- onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}- onSubmit={props.onSubmitUserInput}- onDismiss={props.onDismissUserInput}+ maxHeight={usageLimitsMaxHeight}+ onClose={dismissUsageLimits}/>- ) : null}- </Animated.View>- ) : null}+ </Animated.View>+ ) : null}+ {props.creationState?.kind === "failed" ? (+ <Animated.View+ className="shrink-0 px-4"+ style={{ paddingBottom: composerBottomInset }}+ entering={FadeInDown.duration(220)}+ exiting={FadeOut.duration(140)}+ >+ <ThreadCreationFailedCard+ reason={props.creationState.reason}+ onEditTask={props.creationState.onEditTask}+ />+ </Animated.View>+ ) : null}+ {props.activePendingApproval || props.activePendingUserInput ? (+ <Animated.View+ className="shrink-0 gap-3 px-4 pb-3"+ style={+ activeUserInputRequestId !== null+ ? { paddingBottom: composerBottomInset }+ : undefined+ }+ entering={FadeInDown.duration(220)}+ exiting={FadeOut.duration(140)}+ >+ {props.activePendingApproval ? (+ <PendingApprovalCard+ canOperateThread={props.canOperateThread}+ approval={props.activePendingApproval}+ respondingApprovalId={props.respondingApprovalId}+ onRespond={props.onRespondToApproval}+ />+ ) : null}+ {props.activePendingUserInput ? (+ <PendingUserInputCard+ environmentId={props.environmentId}+ canOperateThread={props.canOperateThread}+ pendingUserInput={props.activePendingUserInput}+ maxHeight={pendingUserInputMaxHeight}+ collapsed={userInputCollapsed}+ onToggleCollapsed={handleToggleUserInputCollapsed}+ onStopThread={props.onStopThread}+ cardProgress={userInputCardProgress}+ cardCoverage={userInputCardCoverage}+ onInputFocusChange={handleOwnedInputFocusChange}+ drafts={props.activePendingUserInputDrafts}+ answers={props.activePendingUserInputAnswers}+ respondingUserInputId={props.respondingUserInputId}+ onSelectOption={props.onSelectUserInputOption}+ onChangeCustomAnswer={props.onChangeUserInputCustomAnswer}+ onSubmit={props.onSubmitUserInput}+ onDismiss={props.onDismissUserInput}+ />+ ) : null}+ </Animated.View>+ ) : null}+ </ComposerPanels></View><View style={composerSlotHidden ? { display: "none" } : undefined}>diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.tsindex 6ba5c635685..bfd088ccf7f 100644--- a/apps/mobile/src/state/threads.ts+++ b/apps/mobile/src/state/threads.ts@@ -1,3 +1,4 @@+import { createChildThreadApprovalsAtom } from "@t3tools/client-runtime/state/thread-requests";import { useAtomValue } from "@effect/atom-react";import {createEnvironmentThreadDetailAtoms,@@ -43,6 +44,10 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({catalogValueAtom: environmentCatalog.catalogValueAtom,snapshotAtom: threadEnvironment.snapshotAtom,});+export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({+ childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,+ pendingRequestsAtom: environmentThreadDetails.pendingRequestsAtom,+});// Long enough for the opened screen to subscribe; its subscription keeps the thread after this.const OPENING_THREAD_HOLD_MS = 3_000;diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsindex 342f6ced28b..8494c4cab78 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts@@ -1512,6 +1512,74 @@ describe("ClaudeAdapterV2 resume compaction", () => {assert.isFunction(callback);const canUseTool = openedOptions?.canUseTool;assert.isFunction(canUseTool);+ const shellSafetyReason =+ "Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed";+ for (const [safetyIndex, { askRule, reason }] of [+ { askRule: false, reason: shellSafetyReason },+ { askRule: true, reason: shellSafetyReason },+ {+ askRule: false,+ reason:+ "Dangerous rm operation on possibly-empty variable path: $TARGET\nUse a literal absolute path instead.",+ },+ { askRule: false, reason: "This shell -c script runs rm and could not be checked" },+ { askRule: false, reason: "A permission rule denies a command in this shell -c script" },+ ].entries()) {+ const safetyRequest = yield* runtime.events.pipe(+ Stream.filter((event) => event.type === "runtime_request.updated"),+ Stream.runHead,+ Effect.forkScoped,+ );+ const safetySignal = yield* Effect.abortSignal;+ const safetyDecision = yield* Effect.promise(() =>+ canUseTool!(+ "Bash",+ { command: "for pair in a b; do echo $pair; done" },+ {+ signal: safetySignal,+ toolUseID: `tool-shell-safety-${safetyIndex}`,+ requestId: `request-shell-safety-${safetyIndex}`,+ decisionReason: `\u001b[33m${reason}\u001b[39m`,+ suppressAlwaysAllowRule: true,+ ...(askRule+ ? {+ matchedAskRule: {+ source: "userSettings" as const,+ toolName: "Bash",+ ruleContent: "*",+ },+ }+ : {}),+ },+ ),+ ).pipe(Effect.forkScoped);+ const safety = yield* Effect.raceFirst(+ Fiber.join(safetyDecision).pipe(+ Effect.map((result) => ({ type: "decision", result }) as const),+ ),+ Fiber.join(safetyRequest).pipe(+ Effect.map((event) => ({ type: "approval", event }) as const),+ ),+ );+ assert.equal(safety.type, askRule ? "approval" : "decision");+ if (safety.type === "decision") {+ assert.equal(safety.result?.behavior, "deny");+ if (safety.result?.behavior === "deny") {+ assert.include(safety.result.message, reason);+ assert.notInclude(safety.result.message, "\u001b[");+ }+ } else if (+ Option.isSome(safety.event) &&+ safety.event.value.type === "runtime_request.updated"+ ) {+ yield* runtime.respondToRuntimeRequest({+ requestId: safety.event.value.runtimeRequest.id,+ decision: "decline",+ });+ assert.equal((yield* Fiber.join(safetyDecision))?.behavior, "deny");+ }+ yield* Fiber.interrupt(safetyRequest);+ }const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`;const questionRequestEvent = yield* runtime.events.pipe(Stream.filter((event) => event.type === "runtime_request.updated"),@@ -3877,6 +3945,32 @@ describe("ClaudeAdapterV2 background wake turns", () => {assert.equal((yield* Fiber.join(forwardedDecision))?.behavior, "deny");yield* harness.offerAndWait(frame);}+ const fallbackDecision = yield* Effect.promise(() =>+ harness.getOpenedOptions()!.canUseTool!(+ "Bash",+ { command: "echo checked" },+ {+ signal: new AbortController().signal,+ toolUseID: "safety-check-after-downgrade",+ requestId: "request-safety-check-after-downgrade",+ decisionReason:+ "Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed",+ },+ ),+ ).pipe(Effect.forkScoped);+ const fallbackFirst = yield* Effect.raceFirst(+ Queue.take(harness.runtimeRequestReceipts).pipe(+ Effect.map((event) => ({ type: "request", event }) as const),+ ),+ Fiber.join(fallbackDecision).pipe(Effect.map(() => ({ type: "decision" }) as const)),+ );+ assert.equal(fallbackFirst.type, "request");+ if (fallbackFirst.type !== "request") return;+ yield* harness.runtime.respondToRuntimeRequest({+ requestId: fallbackFirst.event.runtimeRequest.id,+ decision: "decline",+ });+ assert.equal((yield* Fiber.join(fallbackDecision))?.behavior, "deny");yield* finish;const unrestrictedOptions = harness.getOpenedOptions();yield* start("/unrestricted");diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex d8a88b7dd2b..48ed26517c2 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -9763,6 +9763,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (} satisfies PermissionResult;}+ const activePermissionMode =+ (yield* Ref.get(queryContext))?.permissionMode ?? context.queryPolicy.permissionMode;+ const safetyReason = NodeUtil.stripVTControlCharacters(+ callbackOptions.decisionReason ?? "",+ ).trim();+ // The SDK omits the CLI's dangerousRemoval discriminator, so match its removal warnings.+ if (+ toolName === "Bash" &&+ activePermissionMode === "bypassPermissions" &&+ callbackOptions.matchedAskRule === undefined &&+ (/^Dangerous rm(?:dir)?\b/i.test(safetyReason) ||+ safetyReason === "This shell -c script runs rm and could not be checked" ||+ safetyReason === "A permission rule denies a command in this shell -c script")+ ) {+ return {+ behavior: "deny",+ message: `Claude Code's removal safety check denied this command; the user did not reject it. The command did not run. Do not bypass the check by splitting the removal, putting it in a script, or using another tool or shell. If the warning below supplies a safe rewrite, use it and let the same check evaluate it. Otherwise continue the rest of the task without the removal and tell the user what you needed to delete and why. Warning: ${safetyReason}`,+ toolUseID: callbackOptions.toolUseID,+ } satisfies PermissionResult;+ }+const requestKind = providerRequestKindFromClaudeTool(toolName);// The user approves the command itself; Claude's title and description only summarize it.const command = inputRecordValue(nativeToolInput, "command");diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex ea477b91447..55d951d1bdf 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -1,3 +1,4 @@+import { ChildThreadApprovals } from "./chat/ChildThreadApprovals";import { workspaceAreaProps } from "../lib/workspaceFocus";import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits";@@ -3539,6 +3540,7 @@ export default function ChatView(props: ChatViewProps) {: undefined}>+ <ChildThreadApprovals threadRef={activeThreadRef} /><ComposerSurface.Shell contextRow={showComposerContextStrip}><ComposerSurface.Hostinert={queuedRunEdit.isSaving}diff --git a/apps/web/src/components/chat/ChildThreadApprovals.browser.test.tsx b/apps/web/src/components/chat/ChildThreadApprovals.browser.test.tsxnew file mode 100644index 00000000000..ef136a17601--- /dev/null+++ b/apps/web/src/components/chat/ChildThreadApprovals.browser.test.tsx@@ -0,0 +1,52 @@+import type { ChildThreadApproval } from "@t3tools/client-runtime/state/thread-requests";+import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import { AsyncResult, Atom } from "effect/reactivity";+import { expect, it, vi } from "vite-plus/test";++import { render } from "../../../test/render";++const state = vi.hoisted(() => ({ respond: vi.fn(), approvalsAtom: null as unknown }));++vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true }));+vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.respond }));+vi.mock("../../state/threads", () => ({+ childThreadApprovalsAtom: () => state.approvalsAtom,+ threadEnvironment: { respondToApproval: {} },+}));++import { ChildThreadApprovals } from "./ChildThreadApprovals";++function setup() {+ state.respond.mockReset();+ state.respond+ .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Child environment offline"))))+ .mockResolvedValueOnce(AsyncResult.success(undefined));+ const thread = {+ environmentId: EnvironmentId.make("child-env"),+ threadId: ThreadId.make("child"),+ };+ state.approvalsAtom = Atom.make<ReadonlyArray<ChildThreadApproval>>([+ {+ thread,+ title: "Compile task",+ approval: {+ requestId: RuntimeRequestId.make("approval"),+ requestKind: "command",+ detail: "Run compiler",+ createdAt: "2026-11-01T00:00:00.000Z",+ responseCapability: "live",+ },+ },+ ]);+ return thread;+}++it("shows a failed decision and clears the error when the user retries", async () => {+ const thread = setup();+ await using screen = await render(<ChildThreadApprovals threadRef={thread} />);+ await screen.getByRole("button", { name: "Approve", exact: true }).click();+ await expect.element(screen.getByRole("alert")).toHaveTextContent("Child environment offline");+ await screen.getByRole("button", { name: "Approve", exact: true }).click();+ await expect.element(screen.getByRole("alert")).not.toBeInTheDocument();+});diff --git a/apps/web/src/components/chat/ChildThreadApprovals.tsx b/apps/web/src/components/chat/ChildThreadApprovals.tsxnew file mode 100644index 00000000000..5a7cb3074b4--- /dev/null+++ b/apps/web/src/components/chat/ChildThreadApprovals.tsx@@ -0,0 +1,95 @@+import { useAtomValue } from "@effect/atom-react";+import { AuthOrchestrationOperateScope, type ScopedThreadRef } from "@t3tools/contracts";+import type { ChildThreadApproval } from "@t3tools/client-runtime/state/thread-requests";+import { fullAccessOverrideExplanation } from "@t3tools/client-runtime/state/thread-requests";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import { useState } from "react";+import { useEnvironmentScope } from "../../state/session";+import { childThreadApprovalsAtom, threadEnvironment } from "../../state/threads";+import { useAtomCommand } from "../../state/use-atom-command";+import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";++function ChildApproval({ entry }: { entry: ChildThreadApproval }) {+ const canRespond = useEnvironmentScope(entry.thread.environmentId, AuthOrchestrationOperateScope);+ const respond = useAtomCommand(threadEnvironment.respondToApproval, { reportFailure: false });+ const [responding, setResponding] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const { approval } = entry;+ return (+ <section+ aria-label={`Approval from ${entry.title}`}+ className="rounded-lg border border-border bg-background p-3 text-xs"+ >+ <p className="mb-2 font-medium">Approval needed from {entry.title}</p>+ <pre className="max-h-40 overflow-auto whitespace-pre-wrap break-words font-mono">+ {approval.detail || approval.requestKind}+ </pre>+ {approval.appName ? <p className="mt-2 text-muted-foreground">{approval.appName}</p> : null}+ {approval.responseCapability !== "live" ? (+ <p className="mt-2 text-warning">+ Provider process is gone. Interrupt or restart the child thread to respond.+ </p>+ ) : null}+ {approval.reason ? <p className="mt-2 text-muted-foreground">{approval.reason}</p> : null}+ {approval.fullAccessOverride ? (+ <p className="mt-2 text-muted-foreground">+ {fullAccessOverrideExplanation(approval.fullAccessOverride)}+ </p>+ ) : null}+ <div className="mt-2 flex flex-wrap gap-2">+ <ComposerPendingApprovalActions+ presentation="inline"+ requestId={approval.requestId}+ isResponding={responding}+ canRespond={approval.responseCapability === "live"}+ disabled={!canRespond}+ options={approval.options}+ onRespondToApproval={async (requestId, decision) => {+ if (!canRespond || responding) return;+ setResponding(true);+ setError(null);+ const result = await respond({+ environmentId: entry.thread.environmentId,+ input: { threadId: entry.thread.threadId, requestId, decision },+ });+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ const failure = squashAtomCommandFailure(result);+ setError(+ failure instanceof Error ? failure.message : "Failed to submit approval decision.",+ );+ }+ setResponding(false);+ return result;+ }}+ />+ </div>+ {error !== null ? (+ <p role="alert" className="mt-2 text-destructive">+ {error}+ </p>+ ) : null}+ </section>+ );+}++export function ChildThreadApprovals({ threadRef }: { threadRef: ScopedThreadRef | null }) {+ const approvals = useAtomValue(childThreadApprovalsAtom(threadRef));+ if (approvals.length === 0) return null;+ return (+ <div className="mb-2 flex max-h-80 flex-col gap-2 overflow-auto">+ {approvals.map((entry) => (+ <ChildApproval+ key={JSON.stringify([+ entry.thread.environmentId,+ entry.thread.threadId,+ entry.approval.requestId,+ ])}+ entry={entry}+ />+ ))}+ </div>+ );+}diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.tsindex c7919d658cc..9d7aae58033 100644--- a/apps/web/src/state/threads.ts+++ b/apps/web/src/state/threads.ts@@ -1,3 +1,4 @@+import { createChildThreadApprovalsAtom } from "@t3tools/client-runtime/state/thread-requests";import { useAtomValue } from "@effect/atom-react";import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections";import { arrayElementsEqual } from "@t3tools/client-runtime/state/entities";@@ -39,6 +40,10 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({catalogValueAtom: environmentCatalog.catalogValueAtom,snapshotAtom: threadEnvironment.snapshotAtom,});+export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({+ childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,+ pendingRequestsAtom: environmentThreadDetails.pendingRequestsAtom,+});const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(Atom.withLabel("web-environment-thread:empty"),diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.mdindex a344d98f645..3c330bc6bae 100644--- a/docs/user/permission-modes.md+++ b/docs/user/permission-modes.md@@ -18,7 +18,8 @@ and modes you choose in a draft keep their permissions.| **Full access** | Allows commands and edits without approval prompts. |Approve or reject requests in the conversation to let the agent continue. Permission modes do-not prevent the agent from asking questions about the task.+not prevent the agent from asking questions about the task. Subagent approval requests appear in+the parent conversation with the subagent's name, so you can respond without switching threads.## Provider differences@@ -41,7 +42,9 @@ ACP Registry agents run their own tools in their own mode; T3 Code answers theirby the permission mode. See [ACP Registry permissions](./providers-acp.md#permissions-and-terminals).Claude can still ask in **Full access** when its settings disable bypass permissions or require-approval for an action.+approval for an action. Dangerous-removal safety checks in bypass mode reject the command with+the original warning. Claude can use a safe rewrite when the warning supplies one; otherwise it+continues without the removal and tells you what it skipped.While a Claude approval is pending, type a text reply to decline that request and give feedbackdirectly to the agent that asked, including a subagent. Other pending requests stay unanswered.diff --git a/packages/client-runtime/src/state/threadRequests.test.ts b/packages/client-runtime/src/state/threadRequests.test.tsindex d5d2c4ec16d..d9aaf9fdca7 100644--- a/packages/client-runtime/src/state/threadRequests.test.ts+++ b/packages/client-runtime/src/state/threadRequests.test.ts@@ -1,5 +1,9 @@+import { presentThreadShell } from "./models.ts";+import { threadKey } from "./entities.ts";import {EnvironmentId,+ ThreadId,+ type ScopedThreadRef,NodeId,ProviderSessionId,RuntimeRequestId,@@ -7,11 +11,13 @@ import {type OrchestrationV2ThreadProjection,} from "@t3tools/contracts";import { describe, expect, it, vi } from "vite-plus/test";-import { AsyncResult } from "effect/reactivity";+import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity";import * as Cause from "effect/Cause";-import { v2Now, v2Projection } from "./orchestrationV2TestFixtures.ts";+import { v2Now, v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";import {createQuestionHistoryProjector,+ createChildThreadApprovalsAtom,+ type PendingThreadRequests,derivePendingThreadRequests,declinePendingApprovals,sendApprovalFeedback,@@ -353,3 +359,59 @@ it("restores old text answers without mutating history or replacing unchanged roexpect(project(answered)).toBe(result);expect(project({ ...answered, visibleTurnItems: [...rows] })[0]).toBe(result[0]);});++it("loads only child approvals and retains their destination across environments", () => {+ const local = EnvironmentId.make("local");+ const remote = EnvironmentId.make("remote");+ const parent = { environmentId: local, threadId: ThreadId.make("parent") };+ const childId = ThreadId.make("child");+ const children = Atom.make(+ [local, remote].map((environmentId) => ({+ ...presentThreadShell(environmentId, v2ThreadShell),+ id: childId,+ title: environmentId,+ hasPendingApprovals: true,+ })),+ );+ const details = Atom.family((key: string) =>+ Atom.make<PendingThreadRequests | null>({+ approvals: [+ {+ requestId: RuntimeRequestId.make(key),+ requestKind: "command",+ createdAt: "2026-10-19T00:00:00Z",+ responseCapability: "live",+ },+ ],+ userInputs: [],+ }),+ );+ const readDetails = vi.fn((ref: ScopedThreadRef) => details(threadKey(ref)));+ const approvalsAtom = createChildThreadApprovalsAtom({+ childThreadInputsAtom: () => children,+ pendingRequestsAtom: readDetails,+ });+ const registry = AtomRegistry.make();+ const unmount = registry.mount(approvalsAtom(parent));+ const pending = registry.get(approvalsAtom(parent));+ expect(pending.map((entry) => entry.thread)).toEqual(+ [local, remote].map((environmentId) => ({ environmentId, threadId: childId })),+ );+ expect(pending.map((entry) => entry.title)).toEqual(["local", "remote"]);+ registry.set(details(threadKey({ environmentId: remote, threadId: childId })), {+ approvals: [],+ userInputs: [],+ });+ expect(registry.get(approvalsAtom(parent))).toEqual([pending[0]]);+ readDetails.mockClear();+ registry.set(+ children,+ registry+ .get(children)+ .map((child) => ({ ...child, hasPendingApprovals: false, hasPendingUserInput: true })),+ );+ expect(registry.get(approvalsAtom(parent))).toEqual([]);+ expect(readDetails).not.toHaveBeenCalled();+ unmount();+ registry.dispose();+});diff --git a/packages/client-runtime/src/state/threadRequests.ts b/packages/client-runtime/src/state/threadRequests.tsindex e089eb36d08..a010018c505 100644--- a/packages/client-runtime/src/state/threadRequests.ts+++ b/packages/client-runtime/src/state/threadRequests.ts@@ -1,5 +1,6 @@import type {EnvironmentId,+ ScopedThreadRef,ThreadId,OrchestrationV2ThreadProjection,OrchestrationV2RuntimeRequest,@@ -10,6 +11,9 @@ import type {ProviderRequestKind,RuntimeRequestId,} from "@t3tools/contracts";+import { Atom } from "effect/reactivity";+import { parseThreadKey, threadKey } from "./entities.ts";+import type { EnvironmentThreadShell } from "./models.ts";import * as DateTime from "effect/DateTime";import type { AtomCommandResult } from "./runtime.ts";import type { ThreadStructure, ThreadStructureVisibleTurnItem } from "./models.ts";@@ -339,3 +343,48 @@ export function createQuestionHistoryProjector<return previousResult;};}++export interface ChildThreadApproval {+ readonly thread: ScopedThreadRef;+ readonly title: string;+ readonly approval: ThreadPendingApproval;+}++export function createChildThreadApprovalsAtom(input: {+ readonly childThreadInputsAtom: (+ ref: ScopedThreadRef,+ ) => Atom.Atom<ReadonlyArray<EnvironmentThreadShell>>;+ readonly pendingRequestsAtom: (ref: ScopedThreadRef) => Atom.Atom<PendingThreadRequests | null>;+}) {+ const family = Atom.family((key: string) => {+ let previous: ReadonlyArray<ChildThreadApproval> = [];+ return Atom.make((get) => {+ const next = get(input.childThreadInputsAtom(parseThreadKey(key))).flatMap((child) => {+ if (!child.hasPendingApprovals) return [];+ const thread = { environmentId: child.environmentId, threadId: child.id };+ // Only children asking for approval need a detail subscription.+ return (get(input.pendingRequestsAtom(thread))?.approvals ?? []).map((approval) => ({+ thread,+ title: child.title,+ approval,+ }));+ });+ if (+ next.length === previous.length &&+ next.every((entry, index) => {+ const old = previous[index]!;+ return (+ old.approval === entry.approval &&+ old.title === entry.title &&+ threadKey(old.thread) === threadKey(entry.thread)+ );+ })+ )+ return previous;+ previous = next;+ return next;+ });+ });+ const empty = Atom.make<ReadonlyArray<ChildThreadApproval>>([]);+ return (ref: ScopedThreadRef | null) => (ref === null ? empty : family(threadKey(ref)));+}