Skip to content
TypeScript

fix(threads): keep completed requests closed across clients (#10123)

Theo Brownee63ddb48e2fd
diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts
index 7d6cc39ea61..8e31719b43d 100644
--- a/apps/mobile/src/lib/threadActivity.test.ts
+++ b/apps/mobile/src/lib/threadActivity.test.ts
@@ -1,3 +1,4 @@
+import { derivePendingRequests } from "@t3tools/client-runtime/pending-requests";
import { describe, expect, it } from "vite-plus/test";
import { codexFeedbackMessage } from "@t3tools/client-runtime/state/threads";
@@ -16,8 +17,6 @@ import {
agentSpawnSummary,
buildPendingUserInputAnswers,
buildThreadFeed,
- derivePendingApprovals,
- derivePendingUserInputs,
deriveThreadFeedPresentation,
isPendingUserInputOptionSelected,
setPendingUserInputCustomAnswer,
@@ -107,7 +106,7 @@ describe("pending user input answers", () => {
createdAt: "2026-09-03T00:00:00.000Z",
payload: { requestId: "async-1", responseMode: "message", questions: [question] },
});
- const questions = derivePendingUserInputs([requested])[0]?.questions;
+ const questions = derivePendingRequests([requested]).userInputs[0]?.questions;
expect(questions).toEqual([question]);
expect(buildPendingUserInputAnswers(questions!, { "0": { customAnswer: "Example" } })).toEqual({
"0": "Example",
@@ -126,7 +125,7 @@ describe("pending user input answers", () => {
},
});
- expect(derivePendingUserInputs([requested])).toEqual([
+ expect(derivePendingRequests([requested]).userInputs).toEqual([
{
requestId: "interaction_1",
createdAt: requested.createdAt,
@@ -265,121 +264,6 @@ describe("pending user input answers", () => {
});
});
-describe("pending approvals", () => {
- it.each([{}, { requestType: "unknown" }])(
- "exposes legacy OpenCode approvals without a known request kind: %j",
- (legacyPayload) => {
- const requested = makeActivity({
- id: EventId.make("approval-legacy"),
- kind: "approval.requested",
- summary: "Approval requested",
- createdAt: "2026-08-24T00:00:00.000Z",
- payload: { requestId: "per-legacy", detail: "*", ...legacyPayload },
- });
-
- expect(derivePendingApprovals([requested])).toEqual([
- {
- requestId: "per-legacy",
- requestKind: "command",
- createdAt: requested.createdAt,
- detail: "*",
- },
- ]);
- },
- );
-
- it.each(["tool_user_input", "auth_tokens_refresh"])(
- "does not turn %s into an approval",
- (requestType) => {
- const activity = makeActivity({
- id: EventId.make("approval-non-approval"),
- kind: "approval.requested",
- summary: "Approval requested",
- createdAt: "2026-08-24T00:00:00.000Z",
- payload: { requestId: "not-an-approval", requestType },
- });
-
- expect(derivePendingApprovals([activity])).toEqual([]);
- },
- );
-
- it.each(["approval.resolved", "provider.approval.respond.failed"])(
- "removes legacy approvals after %s",
- (kind) => {
- const requested = makeActivity({
- id: EventId.make("approval-legacy-open"),
- kind: "approval.requested",
- summary: "Approval requested",
- createdAt: "2026-08-24T00:00:00.000Z",
- payload: { requestId: "per-legacy", requestType: "unknown" },
- });
- const resolved = makeActivity({
- id: EventId.make("approval-legacy-resolved"),
- kind,
- summary: "Approval resolved",
- createdAt: "2026-08-24T00:00:01.000Z",
- payload: {
- requestId: "per-legacy",
- detail: "Unknown pending permission request: per-legacy",
- },
- });
-
- expect(derivePendingApprovals([requested, resolved])).toEqual([]);
- },
- );
-
- it("keeps app access approvals and persistence choices from remote environments", () => {
- const options = [
- { decision: "decline", label: "Decline" },
- { decision: "acceptAlways", label: "Always allow Safari" },
- { decision: "accept", label: "Approve" },
- ];
- const activity = makeActivity({
- id: EventId.make("approval-safari"),
- kind: "approval.requested",
- summary: "App access approval requested",
- createdAt: "2026-08-24T00:00:00.000Z",
- payload: {
- requestId: "req-safari",
- requestType: "mcp_elicitation_approval",
- detail: "Allow ChatGPT to use Safari?",
- appName: "Safari",
- options,
- },
- });
-
- expect(derivePendingApprovals([activity])).toEqual([
- {
- requestId: "req-safari",
- requestKind: "mcp-elicitation",
- createdAt: "2026-08-24T00:00:00.000Z",
- detail: "Allow ChatGPT to use Safari?",
- appName: "Safari",
- options,
- },
- ]);
- });
-
- it("removes an app access approval after a remote client rejects it", () => {
- const requested = makeActivity({
- id: EventId.make("approval-safari-open"),
- kind: "approval.requested",
- summary: "App access approval requested",
- createdAt: "2026-08-24T00:00:00.000Z",
- payload: { requestId: "req-safari", requestKind: "mcp-elicitation" },
- });
- const resolved = makeActivity({
- id: EventId.make("approval-safari-resolved"),
- kind: "approval.resolved",
- summary: "Approval resolved",
- createdAt: "2026-08-24T00:00:01.000Z",
- payload: { requestId: "req-safari", decision: "decline" },
- });
-
- expect(derivePendingApprovals([requested, resolved])).toEqual([]);
- });
-});
-
function makeActivity(
input: Partial<OrchestrationThreadActivity> &
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
index f0ba11a0cca..42e0db669a7 100644
--- a/apps/mobile/src/lib/threadActivity.ts
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -1,9 +1,8 @@
import {
- ApprovalRequestId,
- isToolLifecycleItemType,
- ProviderApprovalOption,
- ProviderRequestKind,
-} from "@t3tools/contracts";
+ requestKindFromRequestType,
+ type PendingApproval,
+} from "@t3tools/client-runtime/pending-requests";
+import { isToolLifecycleItemType } from "@t3tools/contracts";
import type {
OrchestrationLatestTurn,
OrchestrationThread,
@@ -36,25 +35,8 @@ import { commandProgramName } from "@t3tools/client-runtime/work-log/command-lab
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
-import * as Schema from "effect/Schema";
-export interface PendingApproval {
- readonly requestId: ApprovalRequestId;
- readonly requestKind: ProviderRequestKind;
- readonly createdAt: string;
- readonly detail?: string;
- readonly appName?: string;
- readonly options?: ReadonlyArray<ProviderApprovalOption>;
-}
-
-const isProviderRequestKind = Schema.is(ProviderRequestKind);
-const isProviderApprovalOption = Schema.is(ProviderApprovalOption);
-
-export interface PendingUserInput {
- readonly requestId: ApprovalRequestId;
- readonly createdAt: string;
- readonly questions: ReadonlyArray<UserInputQuestion>;
-}
+export type { PendingApproval, PendingUserInput } from "@t3tools/client-runtime/pending-requests";
export interface PendingUserInputDraftAnswer {
readonly selectedOptionValues?: ReadonlyArray<string>;
@@ -276,94 +258,6 @@ export function isContextCompactionActivityGroup(
);
}
-function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {
- switch (requestType) {
- case "command_execution_approval":
- case "exec_command_approval":
- return "command";
- case "file_read_approval":
- return "file-read";
- case "file_change_approval":
- case "apply_patch_approval":
- return "file-change";
- case "mcp_elicitation_approval":
- return "mcp-elicitation";
- default:
- return null;
- }
-}
-
-function isStalePendingRequestFailureDetail(detail: string | undefined): boolean {
- const normalized = detail?.toLowerCase();
- if (!normalized) {
- return false;
- }
- return (
- normalized.includes("stale pending approval request") ||
- normalized.includes("stale pending user-input request") ||
- normalized.includes("unknown pending approval request") ||
- normalized.includes("unknown pending permission request") ||
- normalized.includes("unknown pending user-input request")
- );
-}
-
-function parseApprovalRequestId(value: unknown): ApprovalRequestId | null {
- return typeof value === "string" && value.length > 0 ? ApprovalRequestId.make(value) : null;
-}
-
-function parseUserInputQuestions(
- payload: Record<string, unknown> | null,
-): ReadonlyArray<UserInputQuestion> | null {
- const questions = payload?.questions;
- if (!Array.isArray(questions)) {
- return null;
- }
-
- const parsed = questions
- .map<UserInputQuestion | null>((entry) => {
- if (!entry || typeof entry !== "object") return null;
- const question = entry as Record<string, unknown>;
- if (
- typeof question.id !== "string" ||
- typeof question.header !== "string" ||
- typeof question.question !== "string" ||
- !Array.isArray(question.options)
- ) {
- return null;
- }
- const options = question.options
- .map<UserInputQuestion["options"][number] | null>((option) => {
- if (!option || typeof option !== "object") return null;
- const record = option as Record<string, unknown>;
- if (typeof record.label !== "string" || typeof record.description !== "string") {
- return null;
- }
- return {
- label: record.label,
- description: record.description,
- ...(typeof record.value === "string" ? { value: record.value } : {}),
- };
- })
- .filter((option): option is UserInputQuestion["options"][number] => option !== null);
- if (options.length === 0 && question.allowCustomAnswer === false) {
- return null;
- }
- return {
- id: question.id,
- header: question.header,
- question: question.question,
- options,
- multiSelect: question.multiSelect === true,
- ...(typeof question.allowCustomAnswer === "boolean"
- ? { allowCustomAnswer: question.allowCustomAnswer }
- : {}),
- };
- })
- .filter((question): question is UserInputQuestion => question !== null);
-
- return parsed.length > 0 ? parsed : null;
-}
-
function normalizeDraftAnswer(value: string | undefined): string | null {
if (typeof value !== "string") {
return null;
@@ -2169,116 +2063,6 @@ function liveToolActivitySummary(activity: ThreadFeedActivity, presentTense: boo
return activity.detail ?? activity.summary;
}
-/**
- * Sorts activities into lifecycle order. `derivePendingApprovals` and
- * `derivePendingUserInputs` both expect this ordering; sorting once and
- * passing the result to both avoids re-sorting the full activity history
- * per derivation.
- */
-export function sortThreadActivities(
- activities: ReadonlyArray<OrchestrationThreadActivity>,
-): ReadonlyArray<OrchestrationThreadActivity> {
- return Arr.sort(activities, activityOrder);
-}
-
-export function derivePendingApprovals(
- sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
-): PendingApproval[] {
- const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
-
- for (const activity of sortedActivities) {
- const payload =
- activity.payload && typeof activity.payload === "object"
- ? (activity.payload as Record<string, unknown>)
- : null;
- const requestId = parseApprovalRequestId(payload?.requestId);
- const requestKind = isProviderRequestKind(payload?.requestKind)
- ? payload.requestKind
- : requestKindFromRequestType(payload?.requestType);
- const detail = typeof payload?.detail === "string" ? payload.detail : undefined;
- const appName = typeof payload?.appName === "string" ? payload.appName : undefined;
- const options = Array.isArray(payload?.options)
- ? payload.options.filter(isProviderApprovalOption)
- : undefined;
-
- if (
- activity.kind === "approval.requested" &&
- requestId &&
- payload?.requestType !== "tool_user_input" &&
- payload?.requestType !== "auth_tokens_refresh"
- ) {
- openByRequestId.set(requestId, {
- requestId,
- // Older OpenCode requests can have no recognized approval kind.
- requestKind: requestKind ?? "command",
- createdAt: activity.createdAt,
- ...(detail ? { detail } : {}),
- ...(appName ? { appName } : {}),
- ...(options && options.length > 0 ? { options } : {}),
- });
- continue;
- }
-
- if (activity.kind === "approval.resolved" && requestId) {
- openByRequestId.delete(requestId);
- continue;
- }
-
- if (
- activity.kind === "provider.approval.respond.failed" &&
- requestId &&
- isStalePendingRequestFailureDetail(detail)
- ) {
- openByRequestId.delete(requestId);
- }
- }
-
- return Arr.sortWith([...openByRequestId.values()], (s) => new Date(s.createdAt), Order.Date);
-}
-
-export function derivePendingUserInputs(
- sortedActivities: ReadonlyArray<OrchestrationThreadActivity>,
-): PendingUserInput[] {
- const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
-
- for (const activity of sortedActivities) {
- const payload =
- activity.payload && typeof activity.payload === "object"
- ? (activity.payload as Record<string, unknown>)
- : null;
- const requestId = parseApprovalRequestId(payload?.requestId);
- const detail = typeof payload?.detail === "string" ? payload.detail : undefined;
-
- if (activity.kind === "user-input.requested" && requestId) {
- const questions = parseUserInputQuestions(payload);
- if (!questions) {
- continue;
- }
- openByRequestId.set(requestId, {
- requestId,
- createdAt: activity.createdAt,
- questions,
- });
- continue;
- }
-
- if (activity.kind === "user-input.resolved" && requestId) {
- openByRequestId.delete(requestId);
- continue;
- }
-
- if (
- activity.kind === "provider.user-input.respond.failed" &&
- requestId &&
- isStalePendingRequestFailureDetail(detail)
- ) {
- openByRequestId.delete(requestId);
- }
- }
-
- return Arr.sortWith(openByRequestId.values(), (s) => new Date(s.createdAt), Order.Date);
-}
-
export function setPendingUserInputCustomAnswer(
question: UserInputQuestion,
draft: PendingUserInputDraftAnswer | undefined,
diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.ts
index 6208a806819..1b5209dec31 100644
--- a/apps/mobile/src/state/use-selected-thread-requests.ts
+++ b/apps/mobile/src/state/use-selected-thread-requests.ts
@@ -1,3 +1,4 @@
+import { derivePendingRequests } from "@t3tools/client-runtime/pending-requests";
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useMemo, useState } from "react";
@@ -12,10 +13,7 @@ import { threadEnvironment } from "../state/threads";
import { scopedRequestKey } from "../lib/scopedEntities";
import {
buildPendingUserInputAnswers,
- derivePendingApprovals,
- derivePendingUserInputs,
setPendingUserInputCustomAnswer,
- sortThreadActivities,
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../lib/threadActivity";
@@ -83,20 +81,11 @@ export function useSelectedThreadRequests() {
null,
);
- // Sort once; both derivations expect the same lifecycle ordering.
- const sortedActivities = useMemo(
- () => (selectedThread ? sortThreadActivities(selectedThread.activities) : []),
- [selectedThread],
- );
- const activePendingApprovals = useMemo(
- () => derivePendingApprovals(sortedActivities),
- [sortedActivities],
+ const { approvals: activePendingApprovals, userInputs: activePendingUserInputs } = useMemo(
+ () => derivePendingRequests(selectedThread?.activities ?? []),
+ [selectedThread?.activities],
);
const activePendingApproval = activePendingApprovals[0] ?? null;
- const activePendingUserInputs = useMemo(
- () => derivePendingUserInputs(sortedActivities),
- [sortedActivities],
- );
const activePendingUserInput = activePendingUserInputs[0] ?? null;
const activePendingUserInputDrafts =
activePendingUserInput && selectedThreadShell
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index e63c77c89e7..3ff390c6640 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -6,6 +6,7 @@ import {
isUsageLimitsCommand,
} from "@t3tools/shared/usageLimits";
import { usageLimitsBannerItem } from "./chat/ComposerUsageLimits";
+import { derivePendingRequests } from "@t3tools/client-runtime/pending-requests";
import {
type AssistantCitation,
type ApprovalRequestId,
@@ -106,8 +107,6 @@ import {
} from "../composer-logic";
import {
createMessageAttachmentPreviewProjector,
- derivePendingApprovals,
- derivePendingUserInputs,
derivePhase,
deriveTimelineEntriesWithState,
deriveActiveWorkStartedAt,
@@ -2586,12 +2585,8 @@ export default function ChatView(props: ChatViewProps) {
}),
[agentSessionLive, threadActivities],
);
- const pendingApprovals = useMemo(
- () => derivePendingApprovals(threadActivities),
- [threadActivities],
- );
- const pendingUserInputs = useMemo(
- () => derivePendingUserInputs(threadActivities),
+ const { approvals: pendingApprovals, userInputs: pendingUserInputs } = useMemo(
+ () => derivePendingRequests(threadActivities),
[threadActivities],
);
const activePendingUserInput = pendingUserInputs[0] ?? null;
diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts
index f9b888fd1dd..401934bce5b 100644
--- a/apps/web/src/session-logic.test.ts
+++ b/apps/web/src/session-logic.test.ts
@@ -13,8 +13,6 @@ import {
createMessageAttachmentPreviewProjector,
deriveActiveWorkStartedAt,
deriveActivePlanState,
- derivePendingApprovals,
- derivePendingUserInputs,
deriveTimelineEntries,
deriveTimelineEntriesWithState,
deriveWorkLogEntries,
@@ -63,401 +61,6 @@ function makeActivity(overrides: {
};
}
-describe("derivePendingApprovals", () => {
- it.each([{}, { requestType: "unknown" }])(
- "exposes legacy OpenCode approvals without a known request kind: %j",
- (legacyPayload) => {
- const requested = makeActivity({
- kind: "approval.requested",
- payload: { requestId: "per-legacy", detail: "*", ...legacyPayload },
- });
-
- expect(derivePendingApprovals([requested])).toEqual([
- {
- requestId: "per-legacy",
- requestKind: "command",
- createdAt: requested.createdAt,
- detail: "*",
- },
- ]);
- },
- );
-
- it.each(["tool_user_input", "auth_tokens_refresh"])(
- "does not turn %s into an approval",
- (requestType) => {
- const activity = makeActivity({
- kind: "approval.requested",
- payload: { requestId: "not-an-approval", requestType },
- });
-
- expect(derivePendingApprovals([activity])).toEqual([]);
- },
- );
-
- it("tracks open approvals and removes resolved ones", () => {
- const activities: OrchestrationThreadActivity[] = [
- makeActivity({
- id: "approval-open",
- createdAt: "2026-02-23T00:00:01.000Z",
- kind: "approval.requested",
- summary: "Command approval requested",
- tone: "approval",
- payload: {
- requestId: "req-1",
- requestKind: "command",
- detail: "bun run lint",
- },
- }),
- makeActivity({
- id: "approval-close",
- createdAt: "2026-02-23T00:00:02.000Z",
- kind: "approval.resolved",
- summary: "Approval resolved",
- tone: "info",
- payload: { requestId: "req-2" },
- }),
- makeActivity({
- id: "approval-closed-request",
- createdAt: "2026-02-23T00:00:01.500Z",
- kind: "approval.requested",
- summary: "File-change approval requested",
- tone: "approval",
- payload: { requestId: "req-2", requestType: "unknown" },
- }),
- ];
-
- expect(derivePendingApprovals(activities)).toEqual([
- {
- requestId: "req-1",
- requestKind: "command",
- createdAt: "2026-02-23T00:00:01.000Z",
- detail: "bun run lint",
- },
- ]);
- });
-
- it("maps canonical requestType payloads into pending approvals", () => {
- const activities: OrchestrationThreadActivity[] = [
- makeActivity({
- id: "approval-open-request-type",
- createdAt: "2026-02-23T00:00:01.000Z",
- kind: "approval.requested",
- summary: "Command approval requested",
- tone: "approval",
- payload: {
- requestId: "req-request-type",
- requestType: "command_execution_approval",
- detail: "pwd",
- },
- }),
- ];
-
- expect(derivePendingApprovals(activities)).toEqual([
- {
- requestId: "req-request-type",
- requestKind: "command",
- createdAt: "2026-02-23T00:00:01.000Z",
- detail: "pwd",
- },
- ]);
- });
-
- it("keeps app access approvals and persistence choices from remote activities", () => {
- const options = [
- { decision: "decline", label: "Decline" },
- { decision: "acceptAlways", label: "Always allow Safari" },
- { decision: "accept", label: "Approve" },
- ];
- const activities = [
- makeActivity({
- kind: "approval.requested",
- summary: "App access approval requested",
- tone: "approval",
- payload: {
- requestId: "req-safari",
- requestType: "mcp_elicitation_approval",
- detail: "Allow ChatGPT to use Safari?",
- appName: "Safari",
- options,
- },
- }),
- ];
-
- expect(derivePendingApprovals(activities)).toEqual([
- {
- requestId: "req-safari",
- requestKind: "mcp-elicitation",
- createdAt: "2026-02-23T00:00:00.000Z",
- detail: "Allow ChatGPT to use Safari?",
- appName: "Safari",
- options,
- },
- ]);
- });
-
- it("derives dynamic tool requests as actionable generic approvals", () => {
- const activities: OrchestrationThreadActivity[] = [
- makeActivity({
- id: "approval-open-dynamic-tool",
- createdAt: "2026-02-23T00:00:01.000Z",
- kind: "approval.requested",
- summary: "Approval requested",
- tone: "approval",
- payload: {
- requestId: "req-dynamic-tool",
- requestType: "dynamic_tool_call",
- detail: "Search the web",
- },
- }),
- ];
-
- expect(derivePendingApprovals(activities)).toEqual([
- {
- requestId: "req-dynamic-tool",
- requestKind: "command",
- createdAt: "2026-02-23T00:00:01.000Z",
- detail: "Search the web",
- },
- ]);
- });
-
- it("clears stale pending approvals when provider reports unknown pending request", () => {
- const activities: OrchestrationThreadActivity[] = [
- makeActivity({
- id: "approval-open-stale",
- createdAt: "2026-02-23T00:00:01.000Z",
- kind: "approval.requested",
- summary: "Command approval requested",
- tone: "approval",
- payload: {
- requestId: "req-stale-1",
- requestType: "unknown",
- },
- }),
- makeActivity({
- id: "approval-failed-stale",
- createdAt: "2026-02-23T00:00:02.000Z",
- kind: "provider.approval.respond.failed",
- summary: "Provider approval response failed",
- tone: "error",
- payload: {
- requestId: "req-stale-1",
- detail: "Unknown pending permission request: req-stale-1",
- },
- }),
- ];
-
- expect(derivePendingApprovals(activities)).toEqual([]);
- });
-
- it("clears stale pending approvals when the backend marks them stale after restart", () => {
- const activities: OrchestrationThreadActivity[] = [
- makeActivity({
- id: "approval-open-stale-restart",
- createdAt: "2026-02-23T00:00:01.000Z",
- kind: "approval.requested",
- summary: "Command approval requested",
- tone: "approval",
- payload: {
- requestId: "req-stale-restart-1",
- requestKind: "command",
- },
- }),
- makeActivity({
- id: "approval-failed-stale-restart",
- createdAt: "2026-02-23T00:00:02.000Z",
- kind: "provider.approval.respond.failed",
- summary: "Provider approval response failed",
- tone: "error",
- payload: {
- requestId: "req-stale-restart-1",
- detail:
- "Stale pending approval request: req-stale-restart-1. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.",
- },
- }),
- ];
-
- expect(derivePendingApprovals(activities)).toEqual([]);
- });
-});
-
-describe("derivePendingUserInputs", () => {
- it("keeps free-text questions without suggested answers", () => {
- const question = {
- id: "0",
- header: "Question",
- question: "What should it be named?",
- options: [],
- allowCustomAnswer: true,
- multiSelect: false,
- };
- const activities = [
- makeActivity({
- id: "async-question",
- kind: "user-input.requested",
- summary: "User input requested",
- payload: { requestId: "async-1", responseMode: "message", questions: [question] },
- }),
- ];
- expect(derivePendingUserInputs(activities)[0]?.questions).toEqual([question]);
- });
-
- it("preserves native choice values and the custom-answer restriction", () => {
- const question = {
- id: "interaction-result",
- header: "Result",
- question: "Which result should be used?",
- options: [
- { value: " first\t", label: "Result", description: "First result" },
- { value: "second", label: "Result", description: "Second result" },
- ],
- allowCustomAnswer: false,
- multiSelect: false,
- };
- const activities = [
- makeActivity({
- id: "native-user-input",
- kind: "user-input.requested",
- summary: "User input requested",
- payload: { requestId: "req-native-choice", questions: [question] },
- }),
- ];
-
- expect(derivePendingUserInputs(activities)[0]?.questions).toEqual([question]);
- });
-
- it("tracks open structured prompts and removes resolved ones", () => {
- const activities: OrchestrationThreadActivity[] = [
- makeActivity({
- id: "user-input-open",
- createdAt: "2026-02-23T00:00:01.000Z",
- kind: "user-input.requested",
- summary: "User input requested",
- tone: "info",
- payload: {
- requestId: "req-user-input-1",
- questions: [
- {
- id: "sandbox_mode",
- header: "Sandbox",
- question: "Which mode should be used?",
- options: [
- {
- label: "workspace-write",
- description: "Allow workspace writes only",
- },
- ],
- multiSelect: true,
- },
- ],
- },
- }),
- makeActivity({
- id: "user-input-resolved",
- createdAt: "2026-02-23T00:00:02.000Z",
- kind: "user-input.resolved",
- summary: "User input submitted",
- tone: "info",
- payload: {
- requestId: "req-user-input-2",
- answers: {
- sandbox_mode: "workspace-write",
- },
- },
- }),
- makeActivity({
- id: "user-input-open-2",
- createdAt: "2026-02-23T00:00:01.500Z",
- kind: "user-input.requested",
- summary: "User input requested",
- tone: "info",
- payload: {
- requestId: "req-user-input-2",
- questions: [
- {
- id: "approval",
- header: "Approval",
- question: "Continue?",
- options: [
- {
- label: "yes",
- description: "Continue execution",
- },
- ],
- multiSelect: false,
- },
- ],
- },
- }),
- ];
-
- expect(derivePendingUserInputs(activities)).toEqual([
- {
- requestId: "req-user-input-1",
- createdAt: "2026-02-23T00:00:01.000Z",
- questions: [
- {
- id: "sandbox_mode",
- header: "Sandbox",
- question: "Which mode should be used?",
- options: [
- {
- label: "workspace-write",
- description: "Allow workspace writes only",
- },
- ],
- multiSelect: true,
- },
- ],
- },
- ]);
- });
-
- it("clears stale pending user-input prompts when the provider reports an orphaned request", () => {
- const activities: OrchestrationThreadActivity[] = [
- makeActivity({
- id: "user-input-open-stale",
- createdAt: "2026-02-23T00:00:01.000Z",
- kind: "user-input.requested",
- summary: "User input requested",
- tone: "info",
- payload: {
- requestId: "req-user-input-stale-1",
- questions: [
- {
- id: "sandbox_mode",
- header: "Sandbox",
- question: "Which mode should be used?",
- options: [
- {
- label: "workspace-write",
- description: "Allow workspace writes only",
- },
- ],
- multiSelect: false,
- },
- ],
- },
- }),
- makeActivity({
- id: "user-input-failed-stale",
- createdAt: "2026-02-23T00:00:02.000Z",
- kind: "provider.user-input.respond.failed",
- summary: "Provider user input response failed",
- tone: "error",
- payload: {
- requestId: "req-user-input-stale-1",
- detail:
- "Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: req-user-input-stale-1",
- },
- }),
- ];
-
- expect(derivePendingUserInputs(activities)).toEqual([]);
- });
-});
-
describe("deriveActivePlanState", () => {
it("returns the latest plan update for the active turn", () => {
const activities: OrchestrationThreadActivity[] = [
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index 4e56d742bc6..bbef3a4945a 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -1,6 +1,9 @@
+import {
+ requestKindFromRequestType,
+ type PendingApproval,
+} from "@t3tools/client-runtime/pending-requests";
import * as Option from "effect/Option";
import * as Arr from "effect/Array";
-import * as Schema from "effect/Schema";
import { shallow } from "zustand/vanilla/shallow";
import { isBackgroundTaskActivity } from "@t3tools/client-runtime/state/subagentRuntime";
import {
@@ -15,16 +18,12 @@ import {
} from "@t3tools/client-runtime/work-log/presentation";
import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
import {
- ApprovalRequestId,
isToolLifecycleItemType,
type AssetResource,
type OrchestrationLatestTurn,
type OrchestrationThreadActivity,
type OrchestrationProposedPlanId,
- ProviderApprovalOption,
- ProviderRequestKind,
type ToolLifecycleItemType,
- type UserInputQuestion,
type ThreadId,
type TurnId,
} from "@t3tools/contracts";
@@ -40,6 +39,8 @@ import {
type TurnDiffSummary,
} from "./types";
+export type { PendingApproval, PendingUserInput } from "@t3tools/client-runtime/pending-requests";
+
export { formatDuration } from "@t3tools/shared/orchestrationTiming";
export {
@@ -106,24 +107,6 @@ const derivedWorkLogEntryByActivity = new WeakMap<
DerivedWorkLogEntry
>();
-export interface PendingApproval {
- requestId: ApprovalRequestId;
- requestKind: ProviderRequestKind;
- createdAt: string;
- detail?: string;
- appName?: string;
- options?: ReadonlyArray<ProviderApprovalOption>;
-}
-
-const isProviderRequestKind = Schema.is(ProviderRequestKind);
-const isProviderApprovalOption = Schema.is(ProviderApprovalOption);
-
-export interface PendingUserInput {
- requestId: ApprovalRequestId;
- createdAt: string;
- questions: ReadonlyArray<UserInputQuestion>;
-}
-
export interface ActivePlanState {
createdAt: string;
turnId: TurnId | null;
@@ -236,208 +219,6 @@ export function deriveActiveWorkStartedAt(
return sendStartedAt;
}
-function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {
- switch (requestType) {
- case "command_execution_approval":
- case "exec_command_approval":
- case "dynamic_tool_call":
- return "command";
- case "file_read_approval":
- return "file-read";
- case "file_change_approval":
- case "apply_patch_approval":
- return "file-change";
- case "mcp_elicitation_approval":
- return "mcp-elicitation";
- default:
- return null;
- }
-}
-
-function isStalePendingRequestFailureDetail(detail: string | undefined): boolean {
- const normalized = detail?.toLowerCase();
- if (!normalized) {
- return false;
- }
- return (
- normalized.includes("stale pending approval request") ||
- normalized.includes("stale pending user-input request") ||
- normalized.includes("unknown pending approval request") ||
- normalized.includes("unknown pending permission request") ||
- normalized.includes("unknown pending user-input request") ||
- normalized.includes("unknown pending user input request") ||
- normalized.includes("unknown pending codex user input request")
- );
-}
-
-export function derivePendingApprovals(
- activities: ReadonlyArray<OrchestrationThreadActivity>,
-): PendingApproval[] {
- const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
- const ordered = [...activities].toSorted(compareActivitiesByOrder);
-
- for (const activity of ordered) {
- const payload =
- activity.payload && typeof activity.payload === "object"
- ? (activity.payload as Record<string, unknown>)
- : null;
- const requestId =
- payload && typeof payload.requestId === "string"
- ? ApprovalRequestId.make(payload.requestId)
- : null;
- const requestKind =
- payload && isProviderRequestKind(payload.requestKind)
- ? payload.requestKind
- : payload
- ? requestKindFromRequestType(payload.requestType)
- : null;
- const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined;
- const appName = payload && typeof payload.appName === "string" ? payload.appName : undefined;
- const options = Array.isArray(payload?.options)
- ? payload.options.filter(isProviderApprovalOption)
- : undefined;
-
- if (
- activity.kind === "approval.requested" &&
- requestId &&
- payload?.requestType !== "tool_user_input" &&
- payload?.requestType !== "auth_tokens_refresh"
- ) {
- openByRequestId.set(requestId, {
- requestId,
- // Older OpenCode requests can have no recognized approval kind.
- requestKind: requestKind ?? "command",
- createdAt: activity.createdAt,
- ...(detail ? { detail } : {}),
- ...(appName ? { appName } : {}),
- ...(options && options.length > 0 ? { options } : {}),
- });
- continue;
- }
-
- if (activity.kind === "approval.resolved" && requestId) {
- openByRequestId.delete(requestId);
- continue;
- }
-
- if (
- activity.kind === "provider.approval.respond.failed" &&
- requestId &&
- isStalePendingRequestFailureDetail(detail)
- ) {
- openByRequestId.delete(requestId);
- continue;
- }
- }
-
- return [...openByRequestId.values()].toSorted((left, right) =>
- left.createdAt.localeCompare(right.createdAt),
- );
-}
-
-function parseUserInputQuestions(
- payload: Record<string, unknown> | null,
-): ReadonlyArray<UserInputQuestion> | null {
- const questions = payload?.questions;
- if (!Array.isArray(questions)) {
- return null;
- }
- const parsed = questions
- .map<UserInputQuestion | null>((entry) => {
- if (!entry || typeof entry !== "object") return null;
- const question = entry as Record<string, unknown>;
- if (
- typeof question.id !== "string" ||
- typeof question.header !== "string" ||
- typeof question.question !== "string" ||
- !Array.isArray(question.options)
- ) {
- return null;
- }
- const options = question.options
- .map<UserInputQuestion["options"][number] | null>((option) => {
- if (!option || typeof option !== "object") return null;
- const optionRecord = option as Record<string, unknown>;
- if (
- typeof optionRecord.label !== "string" ||
- typeof optionRecord.description !== "string"
- ) {
- return null;
- }
- return {
- label: optionRecord.label,
- description: optionRecord.description,
- ...(typeof optionRecord.value === "string" ? { value: optionRecord.value } : {}),
- };
- })
- .filter((option): option is UserInputQuestion["options"][number] => option !== null);
- if (options.length === 0 && question.allowCustomAnswer === false) {
- return null;
- }
- return {
- id: question.id,
- header: question.header,
- question: question.question,
- options,
- multiSelect: question.multiSelect === true,
- ...(typeof question.allowCustomAnswer === "boolean"
- ? { allowCustomAnswer: question.allowCustomAnswer }
- : {}),
- };
- })
- .filter((question): question is UserInputQuestion => question !== null);
- return parsed.length > 0 ? parsed : null;
-}
-
-export function derivePendingUserInputs(
- activities: ReadonlyArray<OrchestrationThreadActivity>,
-): PendingUserInput[] {
- const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
- const ordered = [...activities].toSorted(compareActivitiesByOrder);
-
- for (const activity of ordered) {
- const payload =
- activity.payload && typeof activity.payload === "object"
- ? (activity.payload as Record<string, unknown>)
- : null;
- const requestId =
- payload && typeof payload.requestId === "string"
- ? ApprovalRequestId.make(payload.requestId)
- : null;
- const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined;
-
- if (activity.kind === "user-input.requested" && requestId) {
- const questions = parseUserInputQuestions(payload);
- if (!questions) {
- continue;
- }
- openByRequestId.set(requestId, {
- requestId,
- createdAt: activity.createdAt,
- questions,
- });
- continue;
- }
-
- if (activity.kind === "user-input.resolved" && requestId) {
- openByRequestId.delete(requestId);
- continue;
- }
-
- if (
- activity.kind === "provider.user-input.respond.failed" &&
- requestId &&
- isStalePendingRequestFailureDetail(detail)
- ) {
- openByRequestId.delete(requestId);
- }
- }
-
- return [...openByRequestId.values()].toSorted((left, right) =>
- left.createdAt.localeCompare(right.createdAt),
- );
-}
-
function planStateFromActivity(activity: OrchestrationThreadActivity): ActivePlanState | null {
const payload =
activity.payload && typeof activity.payload === "object"
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 775a4a898f8..fdab38c9cc6 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -11,6 +11,10 @@
"types": "./src/projectFaviconCache.ts",
"default": "./src/projectFaviconCache.ts"
},
+ "./pending-requests": {
+ "types": "./src/pendingRequests.ts",
+ "default": "./src/pendingRequests.ts"
+ },
"./connection": {
"types": "./src/connection/index.ts",
"default": "./src/connection/index.ts"
diff --git a/packages/client-runtime/src/pendingRequests.test.ts b/packages/client-runtime/src/pendingRequests.test.ts
new file mode 100644
index 00000000000..6ef4579044c
--- /dev/null
+++ b/packages/client-runtime/src/pendingRequests.test.ts
@@ -0,0 +1,497 @@
+import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+import { derivePendingRequests } from "./pendingRequests.ts";
+
+let nextActivityId = 0;
+
+function makeActivity(overrides: {
+ id?: string;
+ createdAt?: string;
+ kind?: string;
+ summary?: string;
+ tone?: OrchestrationThreadActivity["tone"];
+ payload?: Record<string, unknown>;
+ turnId?: string;
+ sequence?: number;
+}): OrchestrationThreadActivity {
+ return {
+ id: EventId.make(overrides.id ?? `activity-${nextActivityId++}`),
+ createdAt: overrides.createdAt ?? "2026-02-23T00:00:00.000Z",
+ kind: overrides.kind ?? "tool.started",
+ summary: overrides.summary ?? "Tool call",
+ tone: overrides.tone ?? "tool",
+ payload: overrides.payload ?? {},
+ turnId: overrides.turnId ? TurnId.make(overrides.turnId) : null,
+ ...(overrides.sequence !== undefined ? { sequence: overrides.sequence } : {}),
+ };
+}
+
+describe("pending approvals", () => {
+ it.each([{}, { requestType: "unknown" }])(
+ "exposes legacy OpenCode approvals without a known request kind: %j",
+ (legacyPayload) => {
+ const requested = makeActivity({
+ kind: "approval.requested",
+ payload: { requestId: "per-legacy", detail: "*", ...legacyPayload },
+ });
+
+ expect(derivePendingRequests([requested]).approvals).toEqual([
+ {
+ requestId: "per-legacy",
+ requestKind: "command",
+ createdAt: requested.createdAt,
+ detail: "*",
+ },
+ ]);
+ },
+ );
+
+ it.each(["tool_user_input", "auth_tokens_refresh"])(
+ "does not turn %s into an approval",
+ (requestType) => {
+ const activity = makeActivity({
+ kind: "approval.requested",
+ payload: { requestId: "not-an-approval", requestType },
+ });
+
+ expect(derivePendingRequests([activity]).approvals).toEqual([]);
+ },
+ );
+
+ it("tracks open approvals and removes resolved ones", () => {
+ const activities: OrchestrationThreadActivity[] = [
+ makeActivity({
+ id: "approval-open",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ kind: "approval.requested",
+ summary: "Command approval requested",
+ tone: "approval",
+ payload: {
+ requestId: "req-1",
+ requestKind: "command",
+ detail: "bun run lint",
+ },
+ }),
+ makeActivity({
+ id: "approval-close",
+ createdAt: "2026-02-23T00:00:02.000Z",
+ kind: "approval.resolved",
+ summary: "Approval resolved",
+ tone: "info",
+ payload: { requestId: "req-2" },
+ }),
+ makeActivity({
+ id: "approval-closed-request",
+ createdAt: "2026-02-23T00:00:01.500Z",
+ kind: "approval.requested",
+ summary: "File-change approval requested",
+ tone: "approval",
+ payload: { requestId: "req-2", requestType: "unknown" },
+ }),
+ ];
+
+ expect(derivePendingRequests(activities).approvals).toEqual([
+ {
+ requestId: "req-1",
+ requestKind: "command",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ detail: "bun run lint",
+ },
+ ]);
+ });
+
+ it("maps canonical requestType payloads into pending approvals", () => {
+ const activities: OrchestrationThreadActivity[] = [
+ makeActivity({
+ id: "approval-open-request-type",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ kind: "approval.requested",
+ summary: "Command approval requested",
+ tone: "approval",
+ payload: {
+ requestId: "req-request-type",
+ requestType: "command_execution_approval",
+ detail: "pwd",
+ },
+ }),
+ ];
+
+ expect(derivePendingRequests(activities).approvals).toEqual([
+ {
+ requestId: "req-request-type",
+ requestKind: "command",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ detail: "pwd",
+ },
+ ]);
+ });
+
+ it("keeps app access approvals and persistence choices from remote activities", () => {
+ const options = [
+ { decision: "decline", label: "Decline" },
+ { decision: "acceptAlways", label: "Always allow Safari" },
+ { decision: "accept", label: "Approve" },
+ ];
+ const activities = [
+ makeActivity({
+ kind: "approval.requested",
+ summary: "App access approval requested",
+ tone: "approval",
+ payload: {
+ requestId: "req-safari",
+ requestType: "mcp_elicitation_approval",
+ detail: "Allow ChatGPT to use Safari?",
+ appName: "Safari",
+ options,
+ },
+ }),
+ ];
+
+ expect(derivePendingRequests(activities).approvals).toEqual([
+ {
+ requestId: "req-safari",
+ requestKind: "mcp-elicitation",
+ createdAt: "2026-02-23T00:00:00.000Z",
+ detail: "Allow ChatGPT to use Safari?",
+ appName: "Safari",
+ options,
+ },
+ ]);
+ });
+
+ it("derives dynamic tool requests as actionable generic approvals", () => {
+ const activities: OrchestrationThreadActivity[] = [
+ makeActivity({
+ id: "approval-open-dynamic-tool",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ kind: "approval.requested",
+ summary: "Approval requested",
+ tone: "approval",
+ payload: {
+ requestId: "req-dynamic-tool",
+ requestType: "dynamic_tool_call",
+ detail: "Search the web",
+ },
+ }),
+ ];
+
+ expect(derivePendingRequests(activities).approvals).toEqual([
+ {
+ requestId: "req-dynamic-tool",
+ requestKind: "command",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ detail: "Search the web",
+ },
+ ]);
+ });
+
+ it("clears stale pending approvals when provider reports unknown pending request", () => {
+ const activities: OrchestrationThreadActivity[] = [
+ makeActivity({
+ id: "approval-open-stale",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ kind: "approval.requested",
+ summary: "Command approval requested",
+ tone: "approval",
+ payload: {
+ requestId: "req-stale-1",
+ requestType: "unknown",
+ },
+ }),
+ makeActivity({
+ id: "approval-failed-stale",
+ createdAt: "2026-02-23T00:00:02.000Z",
+ kind: "provider.approval.respond.failed",
+ summary: "Provider approval response failed",
+ tone: "error",
+ payload: {
+ requestId: "req-stale-1",
+ detail: "Unknown pending permission request: req-stale-1",
+ },
+ }),
+ ];
+
+ expect(derivePendingRequests(activities).approvals).toEqual([]);
+ });
+
+ it("clears stale pending approvals when the backend marks them stale after restart", () => {
+ const activities: OrchestrationThreadActivity[] = [
+ makeActivity({
+ id: "approval-open-stale-restart",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ kind: "approval.requested",
+ summary: "Command approval requested",
+ tone: "approval",
+ payload: {
+ requestId: "req-stale-restart-1",
+ requestKind: "command",
+ },
+ }),
+ makeActivity({
+ id: "approval-failed-stale-restart",
+ createdAt: "2026-02-23T00:00:02.000Z",
+ kind: "provider.approval.respond.failed",
+ summary: "Provider approval response failed",
+ tone: "error",
+ payload: {
+ requestId: "req-stale-restart-1",
+ detail:
+ "Stale pending approval request: req-stale-restart-1. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.",
+ },
+ }),
+ ];
+
+ expect(derivePendingRequests(activities).approvals).toEqual([]);
+ });
+});
+
+describe("pending questions", () => {
+ it("preserves native answer keys while ignoring malformed options", () => {
+ const question = {
+ id: " Which path?\n",
+ header: " Path ",
+ question: " Which path?\n",
+ options: [{ label: " Keep spaces ", description: "", value: " native\t" }],
+ multiSelect: false,
+ };
+ const requested = makeActivity({
+ kind: "user-input.requested",
+ payload: {
+ requestId: "native-question",
+ questions: [null, { ...question, options: [...question.options, { label: 42 }] }],
+ },
+ });
+
+ expect(derivePendingRequests([requested]).userInputs[0]?.questions).toEqual([question]);
+ });
+
+ it("keeps free-text questions without suggested answers", () => {
+ const question = {
+ id: "0",
+ header: "Question",
+ question: "What should it be named?",
+ options: [],
+ allowCustomAnswer: true,
+ multiSelect: false,
+ };
+ const activities = [
+ makeActivity({
+ id: "async-question",
+ kind: "user-input.requested",
+ summary: "User input requested",
+ payload: { requestId: "async-1", responseMode: "message", questions: [question] },
+ }),
+ ];
+ expect(derivePendingRequests(activities).userInputs[0]?.questions).toEqual([question]);
+ });
+
+ it("preserves native choice values and the custom-answer restriction", () => {
+ const question = {
+ id: "interaction-result",
+ header: "Result",
+ question: "Which result should be used?",
+ options: [
+ { value: " first\t", label: "Result", description: "First result" },
+ { value: "second", label: "Result", description: "Second result" },
+ ],
+ allowCustomAnswer: false,
+ multiSelect: false,
+ };
+ const activities = [
+ makeActivity({
+ id: "native-user-input",
+ kind: "user-input.requested",
+ summary: "User input requested",
+ payload: { requestId: "req-native-choice", questions: [question] },
+ }),
+ ];
+
+ expect(derivePendingRequests(activities).userInputs[0]?.questions).toEqual([question]);
+ });
+
+ it("tracks open structured prompts and removes resolved ones", () => {
+ const activities: OrchestrationThreadActivity[] = [
+ makeActivity({
+ id: "user-input-open",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ kind: "user-input.requested",
+ summary: "User input requested",
+ tone: "info",
+ payload: {
+ requestId: "req-user-input-1",
+ questions: [
+ {
+ id: "sandbox_mode",
+ header: "Sandbox",
+ question: "Which mode should be used?",
+ options: [
+ {
+ label: "workspace-write",
+ description: "Allow workspace writes only",
+ },
+ ],
+ multiSelect: true,
+ },
+ ],
+ },
+ }),
+ makeActivity({
+ id: "user-input-resolved",
+ createdAt: "2026-02-23T00:00:02.000Z",
+ kind: "user-input.resolved",
+ summary: "User input submitted",
+ tone: "info",
+ payload: {
+ requestId: "req-user-input-2",
+ answers: {
+ sandbox_mode: "workspace-write",
+ },
+ },
+ }),
+ makeActivity({
+ id: "user-input-open-2",
+ createdAt: "2026-02-23T00:00:01.500Z",
+ kind: "user-input.requested",
+ summary: "User input requested",
+ tone: "info",
+ payload: {
+ requestId: "req-user-input-2",
+ questions: [
+ {
+ id: "approval",
+ header: "Approval",
+ question: "Continue?",
+ options: [
+ {
+ label: "yes",
+ description: "Continue execution",
+ },
+ ],
+ multiSelect: false,
+ },
+ ],
+ },
+ }),
+ ];
+
+ expect(derivePendingRequests(activities).userInputs).toEqual([
+ {
+ requestId: "req-user-input-1",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ questions: [
+ {
+ id: "sandbox_mode",
+ header: "Sandbox",
+ question: "Which mode should be used?",
+ options: [
+ {
+ label: "workspace-write",
+ description: "Allow workspace writes only",
+ },
+ ],
+ multiSelect: true,
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("clears stale pending user-input prompts when the provider reports an orphaned request", () => {
+ const activities: OrchestrationThreadActivity[] = [
+ makeActivity({
+ id: "user-input-open-stale",
+ createdAt: "2026-02-23T00:00:01.000Z",
+ kind: "user-input.requested",
+ summary: "User input requested",
+ tone: "info",
+ payload: {
+ requestId: "req-user-input-stale-1",
+ questions: [
+ {
+ id: "sandbox_mode",
+ header: "Sandbox",
+ question: "Which mode should be used?",
+ options: [
+ {
+ label: "workspace-write",
+ description: "Allow workspace writes only",
+ },
+ ],
+ multiSelect: false,
+ },
+ ],
+ },
+ }),
+ makeActivity({
+ id: "user-input-failed-stale",
+ createdAt: "2026-02-23T00:00:02.000Z",
+ kind: "provider.user-input.respond.failed",
+ summary: "Provider user input response failed",
+ tone: "error",
+ payload: {
+ requestId: "req-user-input-stale-1",
+ detail:
+ "Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: req-user-input-stale-1",
+ },
+ }),
+ ];
+
+ expect(derivePendingRequests(activities).userInputs).toEqual([]);
+ });
+});
+
+describe.each(["approval", "user-input"])("%s request completion", (requestKind) => {
+ const requested = makeActivity({
+ id: `${requestKind}-requested`,
+ kind: `${requestKind}.requested`,
+ sequence: 42,
+ payload: {
+ requestId: "request-1",
+ requestKind: "command",
+ questions: [{ id: "answer", header: "Answer", question: "Continue?", options: [] }],
+ },
+ });
+
+ it.each([`${requestKind}.resolved`, `provider.${requestKind}.respond.failed`])(
+ "keeps %s final across reordered and repeated activities",
+ (kind) => {
+ const closed = makeActivity({
+ id: `${requestKind}-closed`,
+ kind,
+ createdAt: "2026-02-23T00:00:01.000Z",
+ payload: {
+ requestId: "request-1",
+ detail: `Unknown pending ${requestKind} request: request-1`,
+ },
+ });
+ const replayedRequest = { ...requested, id: EventId.make("replayed-request"), sequence: 43 };
+
+ for (const activities of [
+ [requested, closed, replayedRequest],
+ [closed, requested, replayedRequest],
+ ]) {
+ expect(derivePendingRequests(activities)).toEqual({ approvals: [], userInputs: [] });
+ }
+ },
+ );
+
+ it("keeps a failed reply retryable unless the text names a stale request", () => {
+ const failed = makeActivity({
+ kind: `provider.${requestKind}.respond.failed`,
+ payload: { requestId: "request-1", detail: "Provider adapter request failed: timeout" },
+ });
+ const pending = derivePendingRequests([requested, failed]);
+ expect(
+ [...pending.approvals, ...pending.userInputs].map((request) => request.requestId),
+ ).toEqual(["request-1"]);
+
+ const retried = makeActivity({
+ kind: `${requestKind}.resolved`,
+ payload: { requestId: "request-1" },
+ });
+ expect(derivePendingRequests([requested, failed, retried, failed])).toEqual({
+ approvals: [],
+ userInputs: [],
+ });
+ });
+});
diff --git a/packages/client-runtime/src/pendingRequests.ts b/packages/client-runtime/src/pendingRequests.ts
new file mode 100644
index 00000000000..a94c49514e5
--- /dev/null
+++ b/packages/client-runtime/src/pendingRequests.ts
@@ -0,0 +1,189 @@
+import {
+ ApprovalRequestId,
+ type OrchestrationThreadActivity,
+ ProviderApprovalOption,
+ ProviderRequestKind,
+ UserInputQuestion,
+} from "@t3tools/contracts";
+import * as Option from "effect/Option";
+import * as Predicate from "effect/Predicate";
+import * as Schema from "effect/Schema";
+
+export interface PendingApproval {
+ readonly requestId: ApprovalRequestId;
+ readonly requestKind: ProviderRequestKind;
+ readonly createdAt: string;
+ readonly detail?: string;
+ readonly appName?: string;
+ readonly options?: ReadonlyArray<ProviderApprovalOption>;
+}
+
+export interface PendingUserInput {
+ readonly requestId: ApprovalRequestId;
+ readonly createdAt: string;
+ readonly questions: ReadonlyArray<UserInputQuestion>;
+}
+
+const isRequestId = Schema.is(ApprovalRequestId);
+const isProviderRequestKind = Schema.is(ProviderRequestKind);
+const isProviderApprovalOption = Schema.is(ProviderApprovalOption);
+const QuestionOption = Schema.Struct({
+ ...UserInputQuestion.fields.options.value.fields,
+ label: Schema.String,
+});
+const isQuestionOption = Schema.is(QuestionOption);
+// Native question IDs and option labels can be answer keys. Do not trim them.
+const decodeQuestion = Schema.decodeUnknownOption(
+ Schema.Struct({
+ ...UserInputQuestion.fields,
+ id: Schema.String,
+ header: Schema.String,
+ question: Schema.String,
+ options: Schema.Array(QuestionOption),
+ }),
+);
+
+/** Older activities use native request types instead of a request kind. */
+export function requestKindFromRequestType(requestType: unknown): ProviderRequestKind | null {
+ switch (requestType) {
+ case "command_execution_approval":
+ case "exec_command_approval":
+ case "dynamic_tool_call":
+ return "command";
+ case "file_read_approval":
+ return "file-read";
+ case "file_change_approval":
+ case "apply_patch_approval":
+ return "file-change";
+ case "mcp_elicitation_approval":
+ return "mcp-elicitation";
+ default:
+ return null;
+ }
+}
+
+function parseQuestions(value: unknown): UserInputQuestion[] {
+ if (!Array.isArray(value)) return [];
+ return value.flatMap((question) => {
+ if (!Predicate.isObject(question) || !Array.isArray(question.options)) return [];
+ const options = question.options.filter(isQuestionOption);
+ if (options.length === 0 && question.allowCustomAnswer === false) return [];
+ const parsed = decodeQuestion({
+ id: question.id,
+ header: question.header,
+ question: question.question,
+ options,
+ multiSelect: question.multiSelect === true,
+ ...(typeof question.allowCustomAnswer === "boolean"
+ ? { allowCustomAnswer: question.allowCustomAnswer }
+ : {}),
+ });
+ return Option.isSome(parsed) ? [parsed.value] : [];
+ });
+}
+
+const requestActivityKinds = new Set([
+ "approval.requested",
+ "approval.resolved",
+ "provider.approval.respond.failed",
+ "user-input.requested",
+ "user-input.resolved",
+ "provider.user-input.respond.failed",
+]);
+
+// The server reports a stale or unknown request through the failure text.
+// A failed reply with any other text stays open so the user can retry.
+const staleRequestFailureDetails = {
+ "provider.approval.respond.failed": [
+ "stale pending approval request",
+ "unknown pending approval request",
+ "unknown pending permission request",
+ "unknown pending codex approval request",
+ ],
+ "provider.user-input.respond.failed": [
+ "stale pending user-input request",
+ "unknown pending user-input request",
+ "unknown pending user input request",
+ "unknown pending codex user input request",
+ ],
+} as const;
+
+function isStaleRequestFailure(
+ kind: keyof typeof staleRequestFailureDetails,
+ payload: Record<string, unknown>,
+): boolean {
+ const detail = typeof payload.detail === "string" ? payload.detail.toLowerCase() : "";
+ return staleRequestFailureDetails[kind].some((fragment) => detail.includes(fragment));
+}
+
+/** Reduces request state once for web, desktop, and mobile. Layout stays with each client. */
+export function derivePendingRequests(activities: ReadonlyArray<OrchestrationThreadActivity>) {
+ const approvals = new Map<ApprovalRequestId, PendingApproval>();
+ const userInputs = new Map<ApprovalRequestId, PendingUserInput>();
+ const closedApprovals = new Set<ApprovalRequestId>();
+ const closedUserInputs = new Set<ApprovalRequestId>();
+
+ // Request IDs are unique. A terminal event stays final even when provider
+ // sequences and server-generated activities arrive in a different order.
+ for (const activity of activities) {
+ if (!requestActivityKinds.has(activity.kind)) continue;
+ const payload = Predicate.isObject(activity.payload) ? activity.payload : undefined;
+ if (!payload || !isRequestId(payload.requestId)) continue;
+ const requestId = payload.requestId;
+
+ if (activity.kind === "approval.requested") {
+ if (
+ closedApprovals.has(requestId) ||
+ payload.requestType === "tool_user_input" ||
+ payload.requestType === "auth_tokens_refresh"
+ ) {
+ continue;
+ }
+ const requestKind = isProviderRequestKind(payload.requestKind)
+ ? payload.requestKind
+ : requestKindFromRequestType(payload.requestType);
+ const options = Array.isArray(payload.options)
+ ? payload.options.filter(isProviderApprovalOption)
+ : [];
+ approvals.set(requestId, {
+ requestId,
+ // Older OpenCode approvals do not always include a recognized kind.
+ requestKind: requestKind ?? "command",
+ createdAt: activity.createdAt,
+ ...(typeof payload.detail === "string" && payload.detail ? { detail: payload.detail } : {}),
+ ...(typeof payload.appName === "string" && payload.appName
+ ? { appName: payload.appName }
+ : {}),
+ ...(options.length > 0 ? { options } : {}),
+ });
+ } else if (activity.kind === "user-input.requested") {
+ if (closedUserInputs.has(requestId)) continue;
+ const questions = parseQuestions(payload.questions);
+ if (questions.length === 0) continue;
+ userInputs.set(requestId, { requestId, createdAt: activity.createdAt, questions });
+ } else if (
+ activity.kind === "approval.resolved" ||
+ (activity.kind === "provider.approval.respond.failed" &&
+ isStaleRequestFailure(activity.kind, payload))
+ ) {
+ closedApprovals.add(requestId);
+ approvals.delete(requestId);
+ } else if (
+ activity.kind === "user-input.resolved" ||
+ (activity.kind === "provider.user-input.respond.failed" &&
+ isStaleRequestFailure(activity.kind, payload))
+ ) {
+ closedUserInputs.add(requestId);
+ userInputs.delete(requestId);
+ }
+ }
+
+ const byCreatedAt = (
+ left: { readonly createdAt: string },
+ right: { readonly createdAt: string },
+ ) => left.createdAt.localeCompare(right.createdAt);
+ return {
+ approvals: [...approvals.values()].sort(byCreatedAt),
+ userInputs: [...userInputs.values()].sort(byCreatedAt),
+ };
+}