mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
fix(acp): align permission requests with the tool call spec (#52565)
This commit is contained in:
committed by
GitHub
Unverified
parent
4a2c024ea7
commit
134d0ede4d
@@ -133,6 +133,7 @@
|
||||
"@opentui/solid": "catalog:",
|
||||
"@parcel/watcher": "2.5.1",
|
||||
"@silvia-odwyer/photon-node": "0.3.4",
|
||||
"diff": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"immer": "11.1.4",
|
||||
"jsonc-parser": "3.3.1",
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
"@opentui/solid": "catalog:",
|
||||
"@parcel/watcher": "2.5.1",
|
||||
"@silvia-odwyer/photon-node": "0.3.4",
|
||||
"diff": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"immer": "11.1.4",
|
||||
"jsonc-parser": "3.3.1",
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import type { PermissionOption, ToolCallContent, ToolCallLocation } from "@agentclientprotocol/sdk"
|
||||
import type { PermissionOption, ToolCallLocation } from "@agentclientprotocol/sdk"
|
||||
import type { EventSubscribeOutput, OpenCodeClient, PermissionReplyInput } from "@opencode/client/promise"
|
||||
import { FileDiff } from "@opencode/schema/file-diff"
|
||||
import { Patch } from "@opencode/util/patch"
|
||||
import { Cause, Effect } from "effect"
|
||||
import { applyPatch } from "diff"
|
||||
import { Cause, Effect, Option, Schema } from "effect"
|
||||
import type { ACPConnection } from "./connection"
|
||||
import { ACPPromise } from "./promise"
|
||||
import { ACPTranslate } from "./translate"
|
||||
import { absolutePath, filePath, patchHunks, pendingToolCall, stringValue, toLocations, type ToolInput } from "./tool"
|
||||
|
||||
type PermissionEvent = Extract<EventSubscribeOutput, { type: "permission.asked" }>
|
||||
type Tool = { readonly name: string; readonly input: ToolInput }
|
||||
type Tool = { readonly id: string; readonly name: string; readonly input: ToolInput }
|
||||
type Preview = ReturnType<typeof diff>
|
||||
|
||||
type Input = {
|
||||
readonly client: OpenCodeClient
|
||||
@@ -17,8 +21,7 @@ type Input = {
|
||||
readonly clientSessionID: string
|
||||
readonly cwd: string
|
||||
readonly tool?: Tool
|
||||
readonly toolCallPrefix?: string
|
||||
readonly titlePrefix?: string
|
||||
readonly child?: ACPTranslate.ChildSession
|
||||
}
|
||||
|
||||
const options: PermissionOption[] = [
|
||||
@@ -27,6 +30,8 @@ const options: PermissionOption[] = [
|
||||
{ optionId: "reject", kind: "reject_once", name: "Reject" },
|
||||
]
|
||||
|
||||
const decodeFiles = Schema.decodeUnknownOption(Schema.Array(FileDiff.Info))
|
||||
|
||||
/**
|
||||
* Asks the client, then replies to the server. Once `cancelled` completes, the client's request is cancelled or never
|
||||
* sent, and the server gets `reject`. The server reply is uninterruptible, so a server that is alive but stuck can
|
||||
@@ -45,23 +50,28 @@ export const reply = Effect.fn("cli.acp.permission.reply")(function* (input: Inp
|
||||
|
||||
const ask = Effect.fnUntraced(function* (input: Input) {
|
||||
const toolName = input.tool?.name ?? input.event.data.action
|
||||
const toolInput = { ...input.event.data.metadata, ...input.tool?.input }
|
||||
const previews = yield* permissionPreviews(toolName, toolInput, input.cwd)
|
||||
const toolCallID = input.event.data.source?.id ?? input.event.data.id
|
||||
const toolInput = input.tool?.input ?? input.event.data.metadata ?? {}
|
||||
const previews = yield* permissionPreviews(toolName, toolInput, input.event.data.metadata, input.cwd).pipe(
|
||||
Effect.orElseSucceed((): Preview[] => []),
|
||||
)
|
||||
const toolCallID = input.tool?.id ?? input.event.data.id
|
||||
const toolCall = pendingToolCall({
|
||||
toolCallId: input.child ? `${input.child.id}:${toolCallID}` : toolCallID,
|
||||
toolName,
|
||||
state: {
|
||||
input: toolInput,
|
||||
title: prefixedTitle(input.child?.title, permissionTitle(toolName, toolInput, previews)),
|
||||
},
|
||||
cwd: input.cwd,
|
||||
})
|
||||
const result = yield* input.connection.requestPermission({
|
||||
sessionId: input.clientSessionID,
|
||||
toolCall: {
|
||||
...pendingToolCall({
|
||||
toolCallId: input.toolCallPrefix ? `${input.toolCallPrefix}:${toolCallID}` : toolCallID,
|
||||
toolName,
|
||||
state: {
|
||||
input: toolInput,
|
||||
title: prefixedTitle(input.titlePrefix, permissionTitle(toolName, toolInput, previews)),
|
||||
},
|
||||
cwd: input.cwd,
|
||||
}),
|
||||
locations: permissionLocations(toolName, toolInput, input.event.data.resources, input.cwd),
|
||||
...toolCall,
|
||||
rawInput: input.tool ? toolCall.rawInput : undefined,
|
||||
locations: permissionLocations(toolName, toolInput, input.event.data, input.cwd),
|
||||
...(previews.length > 0 ? { content: previews } : {}),
|
||||
...(input.child ? { _meta: ACPTranslate.childSessionMeta(input.child) } : {}),
|
||||
},
|
||||
options,
|
||||
})
|
||||
@@ -81,29 +91,33 @@ function prefixedTitle(prefix: string | undefined, title: string | undefined) {
|
||||
return `${prefix}: ${title}`
|
||||
}
|
||||
|
||||
const permissionPreviews = Effect.fnUntraced(function* (toolName: string, input: ToolInput, cwd: string) {
|
||||
// Core sends the edit and write previews as file diffs; a diff that no longer applies to the file gets no preview.
|
||||
// The patch tool's diffs have their common indentation trimmed for display, so its previews come from its own hunks.
|
||||
const permissionPreviews = Effect.fnUntraced(function* (
|
||||
toolName: string,
|
||||
input: ToolInput,
|
||||
metadata: ToolInput | undefined,
|
||||
cwd: string,
|
||||
) {
|
||||
const tool = toolName.toLocaleLowerCase()
|
||||
if (tool === "patch" || tool === "apply_patch") return yield* patchPreviews(input, cwd)
|
||||
const file = filePath(input)
|
||||
if (!file) return []
|
||||
const path = absolutePath(file, cwd)
|
||||
if (tool === "write") {
|
||||
const content = stringValue(input.content)
|
||||
if (content === undefined) return []
|
||||
const oldText = yield* readText(path)
|
||||
return [diff(path, oldText, content)]
|
||||
}
|
||||
if (tool !== "edit") return []
|
||||
const oldString = stringValue(input.oldString)
|
||||
const newString = stringValue(input.newString)
|
||||
if (oldString === undefined || newString === undefined) return []
|
||||
const oldText = yield* readText(path)
|
||||
const newText =
|
||||
input.replaceAll === true ? oldText.replaceAll(oldString, newString) : oldText.replace(oldString, newString)
|
||||
return [diff(path, oldText, newText)]
|
||||
const files = Option.getOrElse(decodeFiles(metadata?.files), () => [])
|
||||
const previews = yield* Effect.forEach(
|
||||
files,
|
||||
(file) =>
|
||||
Effect.gen(function* () {
|
||||
const path = absolutePath(file.file, cwd)
|
||||
const oldText = file.status === "added" ? null : yield* Effect.tryPromise(() => Bun.file(path).text())
|
||||
const newText = applyPatch(oldText ?? "", file.patch)
|
||||
return newText === false ? [] : [diff(path, oldText, newText)]
|
||||
}),
|
||||
{ concurrency: "unbounded" },
|
||||
)
|
||||
return previews.flat()
|
||||
})
|
||||
|
||||
// Patch.derive throws when a hunk does not match the current file; the patch then gets no previews.
|
||||
// Patch.derive throws when a hunk does not match the current file, and a read can fail; the patch then gets no
|
||||
// previews.
|
||||
function patchPreviews(input: ToolInput, cwd: string) {
|
||||
return Effect.forEach(
|
||||
patchHunks(input),
|
||||
@@ -112,22 +126,22 @@ function patchPreviews(input: ToolInput, cwd: string) {
|
||||
const path = absolutePath(hunk.path, cwd)
|
||||
if (hunk.type === "add") {
|
||||
const newText = hunk.contents.endsWith("\n") || hunk.contents === "" ? hunk.contents : `${hunk.contents}\n`
|
||||
return diff(path, "", newText)
|
||||
return diff(path, null, newText)
|
||||
}
|
||||
const oldText = yield* readText(path)
|
||||
const oldText = yield* Effect.tryPromise(() => Bun.file(path).text())
|
||||
if (hunk.type === "delete") return diff(path, oldText, "")
|
||||
const derived = yield* Effect.try(() => Patch.derive(hunk.path, hunk.chunks, oldText))
|
||||
return diff(hunk.movePath ? absolutePath(hunk.movePath, cwd) : path, oldText, derived.content)
|
||||
}),
|
||||
{ concurrency: "unbounded" },
|
||||
).pipe(Effect.orElseSucceed((): ToolCallContent[] => []))
|
||||
)
|
||||
}
|
||||
|
||||
function diff(path: string, oldText: string, newText: string): ToolCallContent {
|
||||
return { type: "diff", path, oldText, newText }
|
||||
function diff(path: string, oldText: string | null, newText: string) {
|
||||
return { type: "diff" as const, path, oldText, newText }
|
||||
}
|
||||
|
||||
function permissionTitle(toolName: string, input: ToolInput, previews: ReadonlyArray<ToolCallContent>) {
|
||||
function permissionTitle(toolName: string, input: ToolInput, previews: ReadonlyArray<Preview>) {
|
||||
if (previews.length > 1) return `${previews.length} files`
|
||||
switch (toolName.toLocaleLowerCase()) {
|
||||
case "external_directory":
|
||||
@@ -144,26 +158,29 @@ function permissionTitle(toolName: string, input: ToolInput, previews: ReadonlyA
|
||||
case "write":
|
||||
case "patch":
|
||||
case "apply_patch":
|
||||
return filePath(input) ?? (previews[0]?.type === "diff" ? previews[0].path : undefined)
|
||||
return filePath(input) ?? previews[0]?.path
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
// Only these actions ask with path resources; an external directory asks for `<dir>/*`, located at the directory.
|
||||
// Core's wildcard matching treats only `*` and `?` as special.
|
||||
function permissionLocations(
|
||||
toolName: string,
|
||||
input: ToolInput,
|
||||
resources: ReadonlyArray<string>,
|
||||
ask: PermissionEvent["data"],
|
||||
cwd: string,
|
||||
): ToolCallLocation[] {
|
||||
const locations = toLocations(toolName, input, cwd)
|
||||
if (locations.length > 0) return locations
|
||||
return resources.filter((resource) => resource !== "*").map((path) => ({ path: absolutePath(path, cwd) }))
|
||||
if (locations.length > 0 || !PathActions.has(ask.action)) return locations
|
||||
const paths = ask.resources.flatMap((resource) => {
|
||||
const path = resource.endsWith("/*") ? resource.slice(0, -2) : resource
|
||||
return path && !/[*?]/.test(path) ? [absolutePath(path, cwd)] : []
|
||||
})
|
||||
return Array.from(new Set(paths), (path) => ({ path }))
|
||||
}
|
||||
|
||||
// A missing file previews as empty.
|
||||
function readText(path: string) {
|
||||
return Effect.tryPromise(() => Bun.file(path).text()).pipe(Effect.orElseSucceed(() => ""))
|
||||
}
|
||||
const PathActions = new Set(["read", "edit", "external_directory"])
|
||||
|
||||
export * as ACPPermission from "./permission"
|
||||
|
||||
@@ -599,8 +599,16 @@ function compactionUpdate(marker: CompactionMarker): SessionUpdate {
|
||||
|
||||
function projectChildUpdate(update: SessionUpdate, child: ChildSession) {
|
||||
const projected = { ...update }
|
||||
projected._meta = {
|
||||
...projected._meta,
|
||||
projected._meta = { ...projected._meta, ...childSessionMeta(child) }
|
||||
if (projected.sessionUpdate === "tool_call" || projected.sessionUpdate === "tool_call_update") {
|
||||
projected.toolCallId = `${child.id}:${projected.toolCallId}`
|
||||
if (projected.title && child.title) projected.title = `${child.title}: ${projected.title}`
|
||||
}
|
||||
return projected
|
||||
}
|
||||
|
||||
export function childSessionMeta(child: ChildSession) {
|
||||
return {
|
||||
"opencode/child-session": {
|
||||
id: child.id,
|
||||
parentID: child.parentID,
|
||||
@@ -608,11 +616,6 @@ function projectChildUpdate(update: SessionUpdate, child: ChildSession) {
|
||||
...(child.title ? { title: child.title } : {}),
|
||||
},
|
||||
}
|
||||
if (projected.sessionUpdate === "tool_call" || projected.sessionUpdate === "tool_call_update") {
|
||||
projected.toolCallId = `${child.id}:${projected.toolCallId}`
|
||||
if (projected.title && child.title) projected.title = `${child.title}: ${projected.title}`
|
||||
}
|
||||
return projected
|
||||
}
|
||||
|
||||
function matchesStart(event: EventSubscribeOutput, start: TurnStart) {
|
||||
|
||||
@@ -142,7 +142,7 @@ export const make = Effect.fnUntraced(function* (input: {
|
||||
clientSessionID: ctx.sessionID,
|
||||
cwd: ctx.cwd,
|
||||
tool: ask.tool,
|
||||
...(ask.child ? { toolCallPrefix: ask.child.id, titlePrefix: ask.child.title } : {}),
|
||||
child: ask.child,
|
||||
},
|
||||
Deferred.await(subscription.cancelled),
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { AnyRequest, RequestPermissionResponse } from "@agentclientprotocol/sdk"
|
||||
import { createTwoFilesPatch } from "diff"
|
||||
import { Cause } from "effect"
|
||||
import fs from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
@@ -31,6 +32,10 @@ describe("acp permissions over the wire", () => {
|
||||
turn(
|
||||
sessionID,
|
||||
id,
|
||||
toolStarted(sessionID, "call_once", "shell"),
|
||||
toolCalled(sessionID, "call_once", { command: "printf hello" }),
|
||||
toolStarted(sessionID, "call_always", "read"),
|
||||
toolCalled(sessionID, "call_always", { path: "/workspace/file.ts" }),
|
||||
permissionAsked(sessionID, "perm_once", {
|
||||
action: "shell",
|
||||
metadata: { command: "printf hello" },
|
||||
@@ -101,8 +106,84 @@ describe("acp permissions over the wire", () => {
|
||||
expect(acp.permissions[0]?.toolCall).toMatchObject({
|
||||
title: "/tmp/outside",
|
||||
locations: [{ path: "/tmp/outside/a.ts" }],
|
||||
rawInput: { filepath: "/tmp/outside/a.ts", parentDir: "/tmp/outside" },
|
||||
})
|
||||
expect(acp.permissions[0]?.toolCall).not.toHaveProperty("rawInput")
|
||||
})
|
||||
|
||||
test("locates path resources without glob patterns when the ask has no tool locations", async () => {
|
||||
await using acp = await startSession({
|
||||
onPrompt: ({ sessionID, id }) =>
|
||||
turn(
|
||||
sessionID,
|
||||
id,
|
||||
permissionAsked(sessionID, "perm_external", {
|
||||
action: "external_directory",
|
||||
resources: ["/tmp/outside/*", "/tmp/other/*", "/tmp/outside/*"],
|
||||
metadata: {},
|
||||
}),
|
||||
permissionAsked(sessionID, "perm_read", {
|
||||
action: "read",
|
||||
resources: ["src/[slug].ts", "src/{a,b}.ts", "**/*.ts", "src/?.ts"],
|
||||
}),
|
||||
permissionAsked(sessionID, "perm_search", { action: "websearch", resources: ["acp spec"] }),
|
||||
),
|
||||
permission: allowOnce,
|
||||
})
|
||||
|
||||
await acp.prompt(acp.sessionId, "hello")
|
||||
|
||||
expect(acp.permissions.map((request) => request.toolCall.locations)).toEqual([
|
||||
[{ path: "/tmp/outside" }, { path: "/tmp/other" }],
|
||||
[{ path: path.resolve("/workspace", "src/[slug].ts") }, { path: path.resolve("/workspace", "src/{a,b}.ts") }],
|
||||
[],
|
||||
])
|
||||
})
|
||||
|
||||
test("asks under the permission ID when ACP does not track the asking tool call", async () => {
|
||||
await using acp = await startSession({
|
||||
onPrompt: ({ sessionID, id }) =>
|
||||
turn(
|
||||
sessionID,
|
||||
id,
|
||||
permissionAsked(sessionID, "perm_untracked", {
|
||||
source: { type: "tool", messageID: "msg_tools", id: "call_untracked" },
|
||||
}),
|
||||
),
|
||||
permission: allowOnce,
|
||||
})
|
||||
|
||||
await acp.prompt(acp.sessionId, "hello")
|
||||
|
||||
expect(acp.permissions.map((request) => request.toolCall.toolCallId)).toEqual(["perm_untracked"])
|
||||
expect(acp.permissions[0]?.toolCall).not.toHaveProperty("rawInput")
|
||||
})
|
||||
|
||||
test("asks about a tracked tool call with its own input", async () => {
|
||||
await using acp = await startSession({
|
||||
onPrompt: ({ sessionID, id }) =>
|
||||
turn(
|
||||
sessionID,
|
||||
id,
|
||||
toolStarted(sessionID, "call_read", "read"),
|
||||
toolCalled(sessionID, "call_read", { path: "/workspace/file.ts" }),
|
||||
permissionAsked(sessionID, "perm_read", {
|
||||
action: "read",
|
||||
metadata: { files: ["file.ts"] },
|
||||
source: { type: "tool", messageID: "msg_read", id: "call_read" },
|
||||
}),
|
||||
),
|
||||
permission: allowOnce,
|
||||
})
|
||||
|
||||
await acp.prompt(acp.sessionId, "hello")
|
||||
|
||||
const running = acp.updates.flatMap((item) =>
|
||||
item.update.sessionUpdate === "tool_call_update" && item.update.status === "in_progress"
|
||||
? [item.update.rawInput]
|
||||
: [],
|
||||
)
|
||||
expect(running).toEqual([{ path: "/workspace/file.ts" }])
|
||||
expect(acp.permissions[0]?.toolCall).toMatchObject({ toolCallId: "call_read", rawInput: running[0] })
|
||||
})
|
||||
|
||||
test("routes foreground child permissions through the parent ACP session", async () => {
|
||||
@@ -113,9 +194,10 @@ describe("acp permissions over the wire", () => {
|
||||
id,
|
||||
childCreated("ses_child", sessionID, "Review code"),
|
||||
durableEvent("session.execution.started", { sessionID: "ses_child" }),
|
||||
toolStarted("ses_child", "call_child", "read"),
|
||||
toolCalled("ses_child", "call_child", { path: "/workspace/child.ts" }),
|
||||
permissionAsked("ses_child", "perm_child", {
|
||||
action: "read",
|
||||
metadata: { path: "/workspace/child.ts" },
|
||||
source: { type: "tool", messageID: "msg_child", id: "call_child" },
|
||||
}),
|
||||
succeeded("ses_child"),
|
||||
@@ -125,11 +207,17 @@ describe("acp permissions over the wire", () => {
|
||||
|
||||
await acp.prompt(acp.sessionId, "hello")
|
||||
|
||||
const childMeta = {
|
||||
"opencode/child-session": { id: "ses_child", parentID: acp.sessionId, depth: 1, title: "Review code" },
|
||||
}
|
||||
expect(acp.permissions).toHaveLength(1)
|
||||
expect(acp.permissions[0]).toMatchObject({
|
||||
sessionId: acp.sessionId,
|
||||
toolCall: { toolCallId: "ses_child:call_child", title: "Review code: /workspace/child.ts" },
|
||||
toolCall: { toolCallId: "ses_child:call_child", title: "Review code: /workspace/child.ts", _meta: childMeta },
|
||||
})
|
||||
expect(
|
||||
acp.updates.flatMap((item) => (item.update.sessionUpdate === "tool_call" ? [item.update._meta] : [])),
|
||||
).toEqual([childMeta])
|
||||
expect(acp.server.replies).toEqual([{ sessionID: "ses_child", requestID: "perm_child", decision: "once" }])
|
||||
})
|
||||
|
||||
@@ -149,10 +237,17 @@ describe("acp permissions over the wire", () => {
|
||||
)
|
||||
await acp.until(() => acp.server.replies.length === 1, "background permission reply")
|
||||
|
||||
const childMeta = {
|
||||
"opencode/child-session": { id: "ses_background", parentID: acp.sessionId, depth: 1, title: "Research" },
|
||||
}
|
||||
expect(acp.permissions).toMatchObject([
|
||||
{
|
||||
sessionId: acp.sessionId,
|
||||
toolCall: { toolCallId: "ses_background:perm_background", title: "Research: /workspace/notes.md" },
|
||||
toolCall: {
|
||||
toolCallId: "ses_background:perm_background",
|
||||
title: "Research: /workspace/notes.md",
|
||||
_meta: childMeta,
|
||||
},
|
||||
},
|
||||
])
|
||||
expect(acp.server.replies).toEqual([
|
||||
@@ -353,27 +448,24 @@ describe("acp permissions over the wire", () => {
|
||||
})
|
||||
|
||||
describe("acp edit previews over the wire", () => {
|
||||
test("previews edits during approval", async () => {
|
||||
test("previews core's edit diff during approval", async () => {
|
||||
await using dir = await tmpdir()
|
||||
const file = path.join(dir.path, "file.ts")
|
||||
await fs.writeFile(file, "before")
|
||||
await fs.writeFile(file, "one\r\ntwo\r\n")
|
||||
await using acp = await startWire({
|
||||
onPrompt: ({ sessionID, id }) => [
|
||||
delivered(sessionID, id),
|
||||
toolStarted(sessionID, "call_edit", "edit"),
|
||||
toolCalled(sessionID, "call_edit", { path: "file.ts", oldString: "before", newString: "after" }),
|
||||
permissionAsked(sessionID, "perm_edit", {
|
||||
action: "edit",
|
||||
source: { type: "tool", messageID: "msg_edit", id: "call_edit" },
|
||||
}),
|
||||
],
|
||||
onPermissionReply: async ({ sessionID }) => {
|
||||
await fs.writeFile(file, "after")
|
||||
return [
|
||||
toolSucceeded(sessionID, "call_edit", { files: [{ file: "file.ts" }], replacements: 1 }, "edited"),
|
||||
succeeded(sessionID),
|
||||
]
|
||||
},
|
||||
onPrompt: ({ sessionID, id }) =>
|
||||
turn(
|
||||
sessionID,
|
||||
id,
|
||||
toolStarted(sessionID, "call_edit", "edit"),
|
||||
toolCalled(sessionID, "call_edit", { path: "file.ts", oldString: "one\ntwo", newString: "one\nthree" }),
|
||||
permissionAsked(sessionID, "perm_edit", {
|
||||
action: "edit",
|
||||
resources: ["file.ts"],
|
||||
metadata: { files: [fileDiff("file.ts", "one\r\ntwo\r\n", "one\r\nthree\r\n")] },
|
||||
source: { type: "tool", messageID: "msg_edit", id: "call_edit" },
|
||||
}),
|
||||
),
|
||||
permission: allowOnce,
|
||||
})
|
||||
await acp.initialize()
|
||||
@@ -385,7 +477,7 @@ describe("acp edit previews over the wire", () => {
|
||||
title: "file.ts",
|
||||
kind: "edit",
|
||||
locations: [{ path: file }],
|
||||
content: [{ type: "diff", path: file, oldText: "before", newText: "after" }],
|
||||
content: [{ type: "diff", path: file, oldText: "one\r\ntwo\r\n", newText: "one\r\nthree\r\n" }],
|
||||
})
|
||||
})
|
||||
|
||||
@@ -445,6 +537,85 @@ describe("acp edit previews over the wire", () => {
|
||||
})
|
||||
})
|
||||
|
||||
test("previews added files as new and deleted files as empty", async () => {
|
||||
await using dir = await tmpdir()
|
||||
await fs.writeFile(path.join(dir.path, "gone.ts"), "gone\n")
|
||||
const patchText = ["*** Begin Patch", "*** Add File: added.ts", "+one", "*** End Patch"].join("\n")
|
||||
await using acp = await startWire({
|
||||
onPrompt: ({ sessionID, id }) =>
|
||||
turn(
|
||||
sessionID,
|
||||
id,
|
||||
toolStarted(sessionID, "call_write", "write"),
|
||||
toolCalled(sessionID, "call_write", { path: "written.ts", content: "two\n" }),
|
||||
permissionAsked(sessionID, "perm_write", {
|
||||
action: "edit",
|
||||
metadata: { files: [fileDiff("written.ts", "", "two\n", "added")] },
|
||||
source: { type: "tool", messageID: "msg_write", id: "call_write" },
|
||||
}),
|
||||
toolStarted(sessionID, "call_patch", "patch"),
|
||||
toolCalled(sessionID, "call_patch", { patchText }),
|
||||
permissionAsked(sessionID, "perm_patch", {
|
||||
action: "edit",
|
||||
source: { type: "tool", messageID: "msg_patch", id: "call_patch" },
|
||||
}),
|
||||
permissionAsked(sessionID, "perm_delete", {
|
||||
action: "edit",
|
||||
metadata: { files: [fileDiff("gone.ts", "gone\n", "", "deleted")] },
|
||||
}),
|
||||
),
|
||||
permission: allowOnce,
|
||||
})
|
||||
await acp.initialize()
|
||||
const session = await acp.newSession(dir.path)
|
||||
|
||||
await acp.prompt(session.sessionId, "hello")
|
||||
|
||||
expect(acp.permissions.map((request) => request.toolCall.content)).toEqual([
|
||||
[{ type: "diff", path: path.join(dir.path, "written.ts"), oldText: null, newText: "two\n" }],
|
||||
[{ type: "diff", path: path.join(dir.path, "added.ts"), oldText: null, newText: "one\n" }],
|
||||
[{ type: "diff", path: path.join(dir.path, "gone.ts"), oldText: "gone\n", newText: "" }],
|
||||
])
|
||||
})
|
||||
|
||||
test("asks without previews when core's diff no longer applies or the file cannot be read", async () => {
|
||||
await using dir = await tmpdir()
|
||||
await fs.writeFile(path.join(dir.path, "file.ts"), "changed\n")
|
||||
await fs.mkdir(path.join(dir.path, "folder"))
|
||||
await using acp = await startWire({
|
||||
onPrompt: ({ sessionID, id }) =>
|
||||
turn(
|
||||
sessionID,
|
||||
id,
|
||||
permissionAsked(sessionID, "perm_stale", {
|
||||
action: "edit",
|
||||
resources: ["file.ts"],
|
||||
metadata: { files: [fileDiff("file.ts", "one\n", "two\n")] },
|
||||
}),
|
||||
permissionAsked(sessionID, "perm_folder", {
|
||||
action: "edit",
|
||||
resources: ["folder"],
|
||||
metadata: { files: [fileDiff("folder", "one\n", "two\n")] },
|
||||
}),
|
||||
),
|
||||
permission: allowOnce,
|
||||
})
|
||||
await acp.initialize()
|
||||
const session = await acp.newSession(dir.path)
|
||||
|
||||
await acp.prompt(session.sessionId, "hello")
|
||||
|
||||
expect(acp.permissions.map((request) => request.toolCall)).toMatchObject([
|
||||
{ kind: "edit", locations: [{ path: path.join(dir.path, "file.ts") }] },
|
||||
{ kind: "edit", locations: [{ path: path.join(dir.path, "folder") }] },
|
||||
])
|
||||
expect(acp.permissions.map((request) => request.toolCall.content)).toEqual([undefined, undefined])
|
||||
expect(decisions(acp)).toEqual([
|
||||
["perm_stale", "once"],
|
||||
["perm_folder", "once"],
|
||||
])
|
||||
})
|
||||
|
||||
test("asks without previews when a patch does not apply to the current file", async () => {
|
||||
await using dir = await tmpdir()
|
||||
await fs.writeFile(path.join(dir.path, "first.ts"), "changed\n")
|
||||
@@ -563,3 +734,7 @@ describe("acp edit previews over the wire", () => {
|
||||
function decisions(acp: Wire) {
|
||||
return acp.server.replies.map((reply) => [reply.requestID, reply.decision])
|
||||
}
|
||||
|
||||
function fileDiff(file: string, before: string, after: string, status: "added" | "deleted" | "modified" = "modified") {
|
||||
return { file, patch: createTwoFilesPatch(file, file, before, after), additions: 1, deletions: 1, status }
|
||||
}
|
||||
|
||||
@@ -370,6 +370,7 @@ export function permissionAsked(
|
||||
id: string,
|
||||
input: {
|
||||
readonly action?: string
|
||||
readonly resources?: EventData<"permission.asked">["resources"]
|
||||
readonly metadata?: EventData<"permission.asked">["metadata"]
|
||||
readonly source?: { readonly type: "tool"; readonly messageID: string; readonly id: string }
|
||||
} = {},
|
||||
@@ -378,7 +379,7 @@ export function permissionAsked(
|
||||
id,
|
||||
sessionID,
|
||||
action: input.action ?? "shell",
|
||||
resources: ["*"],
|
||||
resources: input.resources ?? ["*"],
|
||||
metadata: input.metadata ?? { command: "printf hello" },
|
||||
...(input.source ? { source: input.source } : {}),
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user