fix(acp): stop echoing edited files to the client (#52466)

This commit is contained in:
Shoubhit Dash
2026-10-01 16:20:16 +05:30
committed by GitHub
Unverified
parent cf0c9fb914
commit 966e718b31
5 changed files with 31 additions and 76 deletions
-4
View File
@@ -5,15 +5,12 @@ import {
type RequestPermissionResponse,
type SendRequestOptions,
type SessionNotification,
type WriteTextFileRequest,
type WriteTextFileResponse,
} from "@agentclientprotocol/sdk"
export type Connection = {
readonly signal?: AbortSignal
sessionUpdate(params: SessionNotification): Promise<void>
requestPermission(params: RequestPermissionRequest, options?: SendRequestOptions): Promise<RequestPermissionResponse>
writeTextFile?(params: WriteTextFileRequest, options?: SendRequestOptions): Promise<WriteTextFileResponse>
extNotification?(method: string, params: Record<string, unknown>): Promise<void>
}
@@ -23,7 +20,6 @@ export function make(connection: AgentConnection): Connection {
sessionUpdate: (params) => connection.client.notify(methods.client.session.update, params),
requestPermission: (params, options) =>
connection.client.request(methods.client.session.requestPermission, params, options),
writeTextFile: (params, options) => connection.client.request(methods.client.fs.writeTextFile, params, options),
extNotification: (method, params) => connection.client.notify(method, params),
}
}
+2 -13
View File
@@ -9,7 +9,7 @@ import type {
import type { ACPConnection } from "./connection"
import { partsToContentChunks, type ReplayPart } from "./content"
import { ACPError } from "./error"
import { replyPermission, syncEditedFiles } from "./permission"
import { replyPermission } from "./permission"
import {
completedToolUpdate,
errorToolUpdate,
@@ -19,7 +19,7 @@ import {
type ToolInput,
} from "./tool"
type Connection = Pick<ACPConnection.Connection, "sessionUpdate" | "requestPermission" | "writeTextFile">
type Connection = Pick<ACPConnection.Connection, "sessionUpdate" | "requestPermission">
export type TurnControl = {
cancelled: boolean
@@ -84,7 +84,6 @@ export async function streamTurn(input: {
readonly sessionID: string
readonly cwd: string
readonly start: TurnStart
readonly writeTextFile: boolean
readonly action?: boolean
readonly submit: (signal: AbortSignal) => Promise<unknown>
readonly control: TurnControl
@@ -284,16 +283,6 @@ export async function streamTurn(input: {
const key = toolKey(event.data.sessionID, event.data.id)
const current = tools.get(key) ?? emptyToolState()
tools.delete(key)
await syncEditedFiles({
connection: input.connection,
writeTextFile: input.writeTextFile,
sessionID: input.sessionID,
cwd: input.cwd,
toolName: current.name,
toolInput: current.input,
metadata: event.data.metadata ?? {},
signal: control.admission.signal,
}).catch(() => {})
await send({
sessionUpdate: "tool_call_update",
...completedToolUpdate({
+4 -41
View File
@@ -2,12 +2,12 @@ import type { PermissionOption, ToolCallContent, ToolCallLocation } from "@agent
import type { EventSubscribeOutput, OpenCodeClient } from "@opencode/client/promise"
import { Patch } from "@opencode/util/patch"
import { Result } from "effect"
import { isAbsolute, resolve } from "node:path"
import { resolve } from "node:path"
import type { ACPConnection } from "./connection"
import { pendingToolCall, stringValue, toLocations, toToolKind, type ToolInput } from "./tool"
import { pendingToolCall, stringValue, toLocations, type ToolInput } from "./tool"
type PermissionEvent = Extract<EventSubscribeOutput, { type: "permission.asked" }>
type Connection = Pick<ACPConnection.Connection, "requestPermission" | "writeTextFile">
type Connection = Pick<ACPConnection.Connection, "requestPermission">
type Tool = { readonly name: string; readonly input: ToolInput }
const options: PermissionOption[] = [
@@ -69,39 +69,6 @@ function prefixedTitle(prefix: string | undefined, title: string | undefined) {
return `${prefix}: ${title}`
}
export async function syncEditedFiles(input: {
readonly connection: Pick<ACPConnection.Connection, "writeTextFile">
readonly writeTextFile: boolean
readonly sessionID: string
readonly cwd: string
readonly toolName: string
readonly toolInput: ToolInput
readonly metadata: Readonly<Record<string, unknown>>
readonly signal?: AbortSignal
}) {
if (!input.writeTextFile || !input.connection.writeTextFile || toToolKind(input.toolName) !== "edit") return
const files = Array.isArray(input.metadata.files)
? input.metadata.files.flatMap((file): string[] => {
if (!file || typeof file !== "object") return []
const path = "file" in file ? file.file : undefined
return typeof path === "string" ? [path] : []
})
: []
const path = filePath(input.toolInput)
const paths = [...new Set([...files, ...(path ? [path] : [])])]
await Promise.all(
paths.map(async (path) => {
const target = resolvePath(path, input.cwd)
const file = Bun.file(target)
if (!(await file.exists())) return
await input.connection.writeTextFile?.(
{ sessionId: input.sessionID, path: target, content: await file.text() },
{ cancellationSignal: input.signal },
)
}),
)
}
async function permissionPreviews(toolName: string, input: ToolInput, cwd: string): Promise<ToolCallContent[]> {
const tool = toolName.toLocaleLowerCase()
if (tool === "patch" || tool === "apply_patch") return patchPreviews(input, cwd)
@@ -186,7 +153,7 @@ function permissionLocations(
}
function readText(path: string, cwd: string) {
return Bun.file(resolvePath(path, cwd))
return Bun.file(resolve(cwd, path))
.text()
.catch(() => "")
}
@@ -195,8 +162,4 @@ function filePath(input: ToolInput) {
return stringValue(input.path) ?? stringValue(input.filePath) ?? stringValue(input.filepath)
}
function resolvePath(path: string, cwd: string) {
return isAbsolute(path) ? path : resolve(cwd, path)
}
export * as ACPPermission from "./permission"
+1 -3
View File
@@ -99,7 +99,7 @@ export function make(input: {
const sessions = new Map<string, Attached>()
const registeredMcp = new Map<string, Set<string>>()
const active = new Map<string, { readonly control: TurnControl; readonly turn: Promise<PromptResponse> }>()
const capabilities = { writeTextFile: false, childSessionUpdates: false }
const capabilities = { childSessionUpdates: false }
const catalogs = ACPCatalog.make({
client: input.client,
@@ -202,7 +202,6 @@ export function make(input: {
return {
initialize: async (params) => {
capabilities.writeTextFile = params.clientCapabilities?.fs?.writeTextFile === true
capabilities.childSessionUpdates = params.clientCapabilities?._meta?.[ChildSessionUpdatesCapability] === true
const authMethod: AuthMethod = {
description: "Run `opencode auth login` in the terminal",
@@ -351,7 +350,6 @@ export function make(input: {
sessionID: state.id,
cwd: state.cwd,
start: prepared.start,
writeTextFile: capabilities.writeTextFile,
action: prepared.command !== undefined,
control,
connectionSignal: input.connection.signal,
+24 -15
View File
@@ -263,8 +263,8 @@ describe("acp permissions over the wire", () => {
})
})
describe("acp edit previews and client file sync over the wire", () => {
test("previews edits during approval and syncs the completed file", async () => {
describe("acp edit previews over the wire", () => {
test("previews edits during approval", async () => {
await using dir = await tmpdir()
const file = path.join(dir.path, "file.ts")
await fs.writeFile(file, "before")
@@ -287,7 +287,7 @@ describe("acp edit previews and client file sync over the wire", () => {
},
permission: allowOnce,
})
await acp.initialize({ writeTextFile: true })
await acp.initialize()
const session = await acp.newSession(dir.path)
await acp.prompt(session.sessionId, "hello")
@@ -298,10 +298,9 @@ describe("acp edit previews and client file sync over the wire", () => {
locations: [{ path: "file.ts" }],
content: [{ type: "diff", path: "file.ts", oldText: "before", newText: "after" }],
})
expect(acp.writes).toEqual([{ sessionId: session.sessionId, path: file, content: "after" }])
})
test("previews and syncs each file in a patch", async () => {
test("previews each file in a patch", async () => {
await using dir = await tmpdir()
await Promise.all([
fs.writeFile(path.join(dir.path, "first.ts"), "one\n"),
@@ -341,7 +340,7 @@ describe("acp edit previews and client file sync over the wire", () => {
},
permission: allowOnce,
})
await acp.initialize({ writeTextFile: true })
await acp.initialize()
const session = await acp.newSession(dir.path)
await acp.prompt(session.sessionId, "hello")
@@ -355,30 +354,40 @@ describe("acp edit previews and client file sync over the wire", () => {
{ type: "diff", path: "second.ts", oldText: "alpha\n", newText: "beta\n" },
],
})
expect(acp.writes.toSorted((a, b) => a.path.localeCompare(b.path))).toEqual([
{ sessionId: session.sessionId, path: path.join(dir.path, "first.ts"), content: "two\n" },
{ sessionId: session.sessionId, path: path.join(dir.path, "second.ts"), content: "beta\n" },
])
})
test("does not sync edits when the client did not advertise writeTextFile", async () => {
test("does not echo completed edits to a client that advertises writeTextFile", async () => {
await using dir = await tmpdir()
await fs.writeFile(path.join(dir.path, "file.ts"), "after")
const file = path.join(dir.path, "file.ts")
await fs.writeFile(file, "after")
await using acp = await startWire({
onPrompt: ({ sessionID, id }) =>
turn(
sessionID,
id,
toolStarted(sessionID, "call_edit", "edit"),
toolCalled(sessionID, "call_edit", { filePath: path.join(dir.path, "file.ts") }),
toolSucceeded(sessionID, "call_edit", {}, "edited"),
toolCalled(sessionID, "call_edit", { filePath: file, oldString: "before", newString: "after" }),
toolSucceeded(sessionID, "call_edit", { files: [{ file }] }, "edited"),
),
})
await acp.initialize()
await acp.initialize({ writeTextFile: true })
const session = await acp.newSession(dir.path)
expect(await acp.prompt(session.sessionId, "hello")).toMatchObject({ stopReason: "end_turn" })
expect(acp.writes).toEqual([])
expect(
acp.updates.flatMap((item) =>
item.update.sessionUpdate === "tool_call_update" && item.update.status === "completed" ? [item.update] : [],
),
).toMatchObject([
{
toolCallId: "call_edit",
content: [
{ type: "content", content: { type: "text", text: "edited" } },
{ type: "diff", path: file, oldText: "before", newText: "after" },
],
},
])
})
})