Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 61 additions & 2 deletions src/CodexToolCallMapper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ToolCallContent } from "@agentclientprotocol/sdk";
import { applyPatch } from "diff";
import { applyPatch, parsePatch } from "diff";
import { readFile } from "node:fs/promises";
import path from "node:path";
import type { UpdateSessionEvent } from "./ACPSessionConnection";
Expand Down Expand Up @@ -86,6 +86,7 @@ export async function createMcpToolCallUpdate(
): Promise<UpdateSessionEvent> {
return createExecuteToolCallUpdate(item, `mcp.${item.server}.${item.tool}`);
}

export async function createDynamicToolCallUpdate(
item: ThreadItem & { type: "dynamicToolCall" }
): Promise<UpdateSessionEvent> {
Expand Down Expand Up @@ -235,7 +236,28 @@ async function createPatchContent(change: FileUpdateChange): Promise<ToolCallCon
};
}

const oldContent = change.kind.type === "add" ? "" : await readFile(change.path, { encoding: "utf8" });
if (change.kind.type === "delete") {
// If the patch deletes a file, the old content may be only available from the diff.
const oldContent = await readFile(change.path, { encoding: "utf8"} ).catch(() =>
isUnifiedDiff(change.diff) ? patchToDeletedContent(change.diff) : change.diff
);

return {
type: "diff",
oldText: oldContent,
newText: "",
path: change.path,
_meta: {
kind: "delete",
}
}
}

const oldContent = change.kind.type === "add" ? "" : await readFile(change.path, { encoding: "utf8" }).catch(() => null);
if (oldContent === null) {
return null;
}

const newContent = applyPatch(oldContent, change.diff);
if (newContent === false) {
return null;
Expand All @@ -254,3 +276,40 @@ async function createPatchContent(change: FileUpdateChange): Promise<ToolCallCon
function isUnifiedDiff(content: string): boolean {
return content.startsWith("--- ") || content.includes("\n--- ");
}

/**
* Recreates the content of a deleted file from the unified diff.
* @param unifiedDiff The unified diff of the file deletion patch
*/
function patchToDeletedContent(unifiedDiff: string): string | null {
try {
const [patch] = parsePatch(unifiedDiff);
if (!patch || patch.hunks.length === 0) {
return null;
}

const oldLines: string[] = [];
let hasNoTrailingNewlineMarker = false;

for (const hunk of patch.hunks) {
for (const line of hunk.lines) {
if (line === "\\ No newline at end of file") {
hasNoTrailingNewlineMarker = true;
continue;
}
if (line.startsWith("-") || line.startsWith(" ")) {
oldLines.push(line.slice(1));
}
}
}

if (oldLines.length === 0) {
return "";
}

const oldText = oldLines.join("\n");
return hasNoTrailingNewlineMarker || !unifiedDiff.endsWith("\n") ? oldText : `${oldText}\n`;
} catch {
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
{
"type": "diff",
"oldText": "fun main() {\n println(\"Hello, World!\")\n}\n",
"newText": "fun main() {\n println(\"Hello, World!\")\n}\n",
"newText": "",
"path": "/test/project/RawDeleteFile.kt",
"_meta": {
"kind": "delete"
Expand Down
68 changes: 67 additions & 1 deletion src/__tests__/CodexACPAgent/file-change-events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ import type { ServerNotification } from '../../app-server';
import { createCodexMockTestFixture, createTestSessionState, setupPromptAndSendNotifications, type CodexMockTestFixture } from '../acp-test-utils';
import {AgentMode} from "../../AgentMode";

const { mockFiles, mockFileContent, clearMockFiles } = vi.hoisted(() => {
const { mockFiles, mockFileContent, removeMockFile, clearMockFiles } = vi.hoisted(() => {
const files = new Map<string, string>();
return {
mockFiles: files,
mockFileContent: (path: string, content: string) => files.set(path, content),
removeMockFile: (path: string) => files.delete(path),
clearMockFiles: () => files.clear(),
};
});
Expand Down Expand Up @@ -205,4 +206,69 @@ describe('CodexEventHandler - file change events', () => {
'data/file-change-delete-raw-content.json'
);
});

it('should handle file deletion when old file is already missing', async () => {
removeMockFile('/test/project/OldFile.kt');

const deleteFileNotification: ServerNotification = {
method: 'item/started',
params: {
threadId: 'thread-1',
turnId: 'turn-1',
item: {
type: 'fileChange',
id: 'file-change-3',
changes: [
{
path: '/test/project/OldFile.kt',
kind: { type: 'delete' },
diff: `--- /test/project/OldFile.kt
+++ /dev/null
@@ -1,3 +0,0 @@
-package test.project
-
-class OldFile {}`,
},
],
status: 'completed',
},
},
};

await setupPromptAndSendNotifications(mockFixture, sessionId, sessionState, [deleteFileNotification]);

await expect(mockFixture.getAcpConnectionDump(['id'])).toMatchFileSnapshot(
'data/file-change-delete-file.json'
);
});

it('should handle file deletion with raw content when old file is already missing', async () => {
removeMockFile('/test/project/RawDeleteFile.kt');

const deletedFileNotification: ServerNotification = {
method: 'item/started',
params: {
threadId: 'thread-1',
turnId: 'turn-1',
item: {
type: 'fileChange',
id: 'file-delete-raw',
changes: [
{
path: '/test/project/RawDeleteFile.kt',
kind: { type: 'delete' },
diff: 'fun main() {\n println("Hello, World!")\n}\n',
},
],
status: 'completed',
},
},
};

await setupPromptAndSendNotifications(mockFixture, sessionId, sessionState, [deletedFileNotification]);

await expect(mockFixture.getAcpConnectionDump(['id'])).toMatchFileSnapshot(
'data/file-change-delete-raw-content.json'
);
});
});
Loading