TypeScript
fix(server): Codex file-change approvals list the files they change (#18248)
Victor Vogel21cbec39d2a6
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.tsindex 51d072951b4..c0dbc441fdc 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts@@ -17,6 +17,7 @@ import {type OrchestrationV2AppThread,type OrchestrationV2ProviderThread,type OrchestrationV2ProviderTurn,+ type OrchestrationV2RuntimeRequest,type OrchestrationV2TurnItem,ProjectId,type ProviderApprovalDecision,@@ -35,6 +36,7 @@ import { SpawnExecutableResolution } from "@t3tools/shared/shell";import * as CodexClient from "effect-codex-app-server/client";import * as CodexError from "effect-codex-app-server/errors";import * as CodexReplay from "effect-codex-app-server/replay";+import type * as CodexSchema from "effect-codex-app-server/schema";import * as DateTime from "effect/DateTime";import * as Deferred from "effect/Deferred";import * as Crypto from "effect/Crypto";@@ -47,6 +49,7 @@ import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";import * as Path from "effect/Path";import * as PlatformError from "effect/PlatformError";+import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";@@ -9533,4 +9536,214 @@ describe("CodexAdapterV2 post-settle continuation", () => {),);});++ describe("Codex file-change approval paths", () => {+ const nativeThreadId = "file-approval-thread";+ const nativeTurnId = "file-approval-turn";+ const prompt = "Edit the files.";+ type FileUpdateChange = CodexSchema.V2ItemStartedNotification__FileUpdateChange;+ const addA: FileUpdateChange = { path: "/w/a.ts", kind: { type: "add" }, diff: "export {};" };+ const updateB: FileUpdateChange = {+ path: "/w/b.ts",+ kind: { type: "update", move_path: null },+ diff: "@@",+ };+ const renameC: FileUpdateChange = {+ path: "/w/c.ts",+ kind: { type: "update", move_path: "/w/d.ts" },+ diff: "@@",+ };++ const deleteE: FileUpdateChange = { path: "/w/e.ts", kind: { type: "delete" }, diff: "gone" };++ const fileChange = (+ phase: "started" | "completed",+ turnId: string,+ itemId: string,+ changes: ReadonlyArray<FileUpdateChange>,+ ): CodexReplay.CodexAppServerReplayEntry => ({+ type: "emit_inbound",+ label: `${phase} ${itemId}`,+ frame: {+ method: `item/${phase}`,+ params: {+ threadId: nativeThreadId,+ turnId,+ ...(phase === "started" ? { startedAtMs: 1 } : { completedAtMs: 3 }),+ item: {+ type: "fileChange",+ id: itemId,+ status: phase === "started" ? "inProgress" : "completed",+ changes,+ },+ },+ },+ });++ const approval = (input: {+ readonly id: number;+ readonly turnId: string;+ readonly itemId: string;+ }): Array<CodexReplay.CodexAppServerReplayEntry> => [+ {+ type: "emit_inbound",+ label: `approval ${input.itemId}`,+ frame: {+ id: input.id,+ method: "item/fileChange/requestApproval",+ params: {+ threadId: nativeThreadId,+ turnId: input.turnId,+ itemId: input.itemId,+ startedAtMs: 2,+ reason: null,+ grantRoot: null,+ },+ },+ },+ {+ type: "expect_outbound",+ label: `approval ${input.itemId}`,+ frame: { id: input.id, result: { decision: "accept" } },+ },+ ];++ const turnCompleted = (turnId: string): CodexReplay.CodexAppServerReplayEntry => ({+ type: "emit_inbound",+ label: `complete ${turnId}`,+ frame: {+ method: "turn/completed",+ params: {+ threadId: nativeThreadId,+ turn: makeCodexReplayTurn({ id: turnId, status: "completed" }),+ },+ },+ });++ const startApprovalTurn = (+ scenario: string,+ entries: ReadonlyArray<CodexReplay.CodexAppServerReplayEntry>,+ ) =>+ Effect.gen(function* () {+ const pending = yield* Queue.unbounded<OrchestrationV2RuntimeRequest>();+ const harness = yield* makeCodexReplayHarness(+ makeCodexReplayTranscript({+ scenario,+ entries: [...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }), ...entries],+ }),+ (event) =>+ event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending"+ ? Queue.offer(pending, event.runtimeRequest)+ : Effect.void,+ );+ yield* harness.runtime.startTurn(+ makeCodexTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make(`${scenario}-attempt`),+ text: prompt,+ }),+ );+ return {+ harness,+ answerNext: Queue.take(pending).pipe(+ Effect.tap((request) =>+ harness.runtime.respondToRuntimeRequest({+ requestId: request.id,+ decision: "accept",+ }),+ ),+ ),+ };+ });++ const approvalItem = (+ events: ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>,+ request: OrchestrationV2RuntimeRequest,+ ) =>+ events.flatMap((event) =>+ event.type === "turn_item.updated" &&+ event.turnItem.type === "approval_request" &&+ event.turnItem.requestId === request.id+ ? [event.turnItem]+ : [],+ )[0];++ it.effect("answers without waiting for late paths or borrowing another item's paths", () =>+ Effect.gen(function* () {+ const { harness, answerNext } = yield* startApprovalTurn("file-approval-after", [+ fileChange("started", nativeTurnId, "other-patch", [updateB]),+ // Late details cannot arrive until the approval response has been sent.+ ...approval({ id: 0, turnId: nativeTurnId, itemId: "patch-a" }),+ fileChange("started", nativeTurnId, "patch-a", [addA]),+ fileChange("completed", nativeTurnId, "patch-a", [addA]),+ fileChange("completed", nativeTurnId, "other-patch", [updateB]),+ turnCompleted(nativeTurnId),+ ]);+ const request = yield* answerNext;+ yield* harness.firstTerminal;++ const items = harness.events.flatMap((event) =>+ event.type === "turn_item.updated" &&+ event.turnItem.type === "approval_request" &&+ event.turnItem.requestId === request.id+ ? [event.turnItem]+ : [],+ );+ assert.equal(request.nativeRequestRef?.nativeId, "patch-a");+ assert.isNotEmpty(items);+ for (const item of items) {+ assert.equal(item.requestKind, "file-change");+ assert.isUndefined(item.prompt);+ }+ assert.deepEqual(+ harness.terminalEvents().map((event) => event.status),+ ["completed"],+ );+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ );++ it.effect("matches file paths to items approved out of order", () =>+ Effect.gen(function* () {+ const { harness, answerNext } = yield* startApprovalTurn("file-approval-concurrent", [+ fileChange("started", nativeTurnId, "patch-a", [renameC, deleteE, addA]),+ fileChange("started", nativeTurnId, "patch-b", [updateB]),+ ...approval({ id: 0, turnId: nativeTurnId, itemId: "patch-b" }),+ fileChange("completed", nativeTurnId, "patch-b", [updateB]),+ ...approval({ id: 1, turnId: nativeTurnId, itemId: "patch-a" }),+ fileChange("completed", nativeTurnId, "patch-a", [renameC, deleteE, addA]),+ turnCompleted(nativeTurnId),+ ]);+ const first = yield* answerNext;+ const second = yield* answerNext;+ yield* harness.firstTerminal;++ assert.deepEqual(+ [first, second].map((request) => [+ request.nativeRequestRef?.nativeId,+ approvalItem(harness.events, request)?.prompt,+ ]),+ [+ ["patch-b", "update /w/b.ts"],+ ["patch-a", "add /w/a.ts\nupdate /w/c.ts -> /w/d.ts\ndelete /w/e.ts"],+ ],+ );+ assert.deepEqual(+ harness.terminalEvents().map((event) => event.status),+ ["completed"],+ );+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ );+ });});diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.tsindex d9316c7a691..994ec334246 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts@@ -153,10 +153,14 @@ const CODEX_PROVIDER = ProviderDriverKind.make("codex");export const CODEX_DRIVER_KIND = CODEX_PROVIDER;export const CODEX_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CODEX_DRIVER_KIND);+type CodexFileChangeKinds = Readonly<+ Record<string, CodexSchema.V2ItemStartedNotification__PatchChangeKind>+>;+export function codexFileChangeApprovalPrompt(input: {readonly reason?: string | null;readonly grantRoot?: string | null;- readonly fileChanges?: CodexSchema.ServerRequest__ApplyPatchApprovalParams["fileChanges"];+ readonly fileChanges?: CodexFileChangeKinds;}): string | undefined {const reason = input.reason?.trim();if (reason) return reason;@@ -1126,6 +1130,8 @@ interface ActiveCodexTurnContext {readonly rootNodeId: OrchestrationV2ExecutionNode["id"];readonly subagent: CodexSubagentThreadContext | null;readonly startedAt: DateTime.Utc;+ // Modern approval requests omit paths; keep the kinds without retaining patch bodies.+ readonly fileChangeKindsByItem: Map<string, CodexFileChangeKinds>;readonly itemPositions: Map<string,{ readonly ordinal: number; readonly startedAt: DateTime.Utc }@@ -2010,6 +2016,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (subagent: null,startedAt: input.startedAt,itemPositions: new Map(),+ fileChangeKindsByItem: new Map(),};yield* Ref.update(limitedTurnItems, (current) => {const next = new Map(current);@@ -2581,6 +2588,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (subagent,startedAt: turn.startedAt,itemPositions: new Map(),+ fileChangeKindsByItem: new Map(),};beginTurnTokenUsage(activeContext);endSessionApprovalsOnModeChange(activeContext);@@ -4659,6 +4667,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ();}+ if (payload.item.type === "fileChange") {+ context.fileChangeKindsByItem.set(+ payload.item.id,+ Object.fromEntries(payload.item.changes.map(({ path, kind }) => [path, kind])),+ );+ return;+ }+if (payload.item.type === "agentMessage") {if (payload.item.phase !== "commentary") {yield* Ref.update(finalAnswerItemIdsByTurn, (current) => {@@ -4875,6 +4891,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (}if (payload.item.type === "fileChange") {+ context.fileChangeKindsByItem.delete(payload.item.id);const artifacts = yield* buildFileChangeArtifacts(context, payload.item);if (artifacts === null) {return;@@ -5127,7 +5144,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (nativeItemId: payload.itemId,nativeRequestId: payload.itemId,requestKind: "file-change",- prompt: codexFileChangeApprovalPrompt(payload) ?? null,+ prompt:+ codexFileChangeApprovalPrompt({+ ...payload,+ fileChanges: context.fileChangeKindsByItem.get(payload.itemId) ?? {},+ }) ?? null,});const decision = yield* Deferred.make<ProviderApprovalDecision, never>();yield* Ref.update(pendingRuntimeRequests, (current) => {@@ -5752,6 +5773,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (if (current !== input.context) {return false;}+ input.context.fileChangeKindsByItem.clear();const providerRetry = yield* Ref.modify(providerRetries, (current) => {const retry = current.get(input.context.providerTurnId);if (retry === undefined) {@@ -6050,6 +6072,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (subagent: null,startedAt: now,itemPositions: new Map(),+ fileChangeKindsByItem: new Map(),};const providerTurn = {id: context.providerTurnId,diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_output.tsindex ec6981cccd2..0ef9af47e3a 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_output.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_restricted_granular/codex_output.ts@@ -1,3 +1,4 @@+import { assert } from "@effect/vitest";import type { ProviderReplayTranscript } from "@t3tools/contracts";import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";@@ -33,4 +34,10 @@ export function assertToolCallRestrictedGranularOutput(assertRuntimeRequestKinds(projection, ["file-change"]);assertAllRuntimeRequestsResolved(projection);assertUserMessagesInclude(projection, [TOOL_CALL_WRITE_PROMPT]);++ const approval = projection.turnItems.find((item) => item.type === "approval_request");+ assert.equal(+ approval?.prompt,+ "add /home/replay-user/t3code/packages/effect-codex-app-server/.codex-probe-write-action.txt",+ );}