Your AI agent skills, finally organized. A macOS app to browse, edit, and manage skills across Claude Code, Cursor, Codex, Windsurf, and Amp.
fix: Defer AI Assist file writes until user accepts the diff (#84)
Josh Pigfordac22f511af8d
diff --git a/Chops/Services/ACP/ACPClient.swift b/Chops/Services/ACP/ACPClient.swiftindex 4c47df6..21fc1a9 100644--- a/Chops/Services/ACP/ACPClient.swift+++ b/Chops/Services/ACP/ACPClient.swift@@ -33,7 +33,21 @@ open class BaseACPAgent: ClientDelegate {var thoughtText: String = ""var currentActivity: String?var pendingWrites: [PendingWrite] = []+ /// Maps resolved file paths to proposed content not yet accepted by the user.+ /// Lets handleFileReadRequest return the "virtual" state during the same turn.+ var deferredContent: [String: String] = [:]private(set) var sessionConfigOptions: [SessionConfigOption] = []++ /// True when the agent's permission mode is set to bypass — writes should be+ /// auto-accepted without user review.+ var isBypassMode: Bool {+ sessionConfigOptions.contains { option in+ if case .select(let select) = option.kind {+ return select.currentValue.value.lowercased().contains("bypass")+ }+ return false+ }+ }private(set) var pendingPermissionRequest: PermissionRequest?private(set) var isConnected: Bool = falseprivate(set) var isConnecting: Bool = false@@ -224,7 +238,7 @@ open class BaseACPAgent: ClientDelegate {acpLog.debug("Prompt done: \(resp.stopReason)")}- func clearPendingWrites() { pendingWrites = [] }+ func clearPendingWrites() { pendingWrites = []; deferredContent = [:] }/// Sends a session/cancel notification to the agent to interrupt the current turn.func cancelPrompt() {@@ -260,13 +274,18 @@ open class BaseACPAgent: ClientDelegate {public func handleFileReadRequest(_ path: String, sessionId: String, line: Int?, limit: Int?) async throws -> ReadTextFileResponse {acpLog.debug("readTextFile: \(path)")+ let resolved = URL(fileURLWithPath: path).resolvingSymlinksInPath().path+ if let deferred = deferredContent[resolved] {+ acpLog.debug("Returning deferred content for: \(path)")+ return ReadTextFileResponse(content: deferred)+ }let content = try await Task.detached { try String(contentsOfFile: path, encoding: .utf8) }.valuereturn ReadTextFileResponse(content: content)}public func handleFileWriteRequest(_ path: String, content: String, sessionId: String) async throws -> WriteTextFileResponse {acpLog.debug("Write via ACP: \(path)")- // Read original before writing so reject can revert.+ // Read original snapshot so the diff panel can show before/after.// Skip if a diff block already captured this path (e.g. ClaudeACPAgent.captureDiffs).// Resolve symlinks on both sides so that e.g. a symlink path and its target compare equal.let resolvedIncoming = URL(fileURLWithPath: path).resolvingSymlinksInPath().path@@ -281,7 +300,7 @@ open class BaseACPAgent: ClientDelegate {do {originalData = try Data(contentsOf: URL(fileURLWithPath: path))} catch {- acpLog.error("Failed to read original for diff revert (\(path)): \(error.localizedDescription)")+ acpLog.error("Failed to read original for diff (\(path)): \(error.localizedDescription)")originalData = nil}} else {@@ -299,15 +318,20 @@ open class BaseACPAgent: ClientDelegate {))}- // Write to disk — agent expects the file to be persisted.- try await Task.detached {- let url = URL(fileURLWithPath: path)- let parent = url.deletingLastPathComponent()- if !FileManager.default.fileExists(atPath: parent.path) {- try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)- }- try content.write(to: url, atomically: true, encoding: .utf8)- }.value+ // Store proposed content so subsequent agent reads return it.+ deferredContent[resolvedIncoming] = content+ if isBypassMode {+ // Bypass mode: write to disk immediately — user opted out of review.+ try await Task.detached {+ let url = URL(fileURLWithPath: path)+ let parent = url.deletingLastPathComponent()+ if !FileManager.default.fileExists(atPath: parent.path) {+ try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true)+ }+ try content.write(to: url, atomically: true, encoding: .utf8)+ }.value+ }+ // Non-bypass: do NOT write to disk — deferred until user accepts the diff.return WriteTextFileResponse()}diff --git a/Chops/Services/TemplateManager.swift b/Chops/Services/TemplateManager.swiftindex fc0d439..a109d56 100644--- a/Chops/Services/TemplateManager.swift+++ b/Chops/Services/TemplateManager.swift@@ -274,7 +274,8 @@ final class TemplateManager {## Your roleWhen the user asks you to create or update this skill, use the ACP `write_text_file` tool to write the complete updated file content directly to the file path shown above.Do not show the content in a code block or ask for confirmation — write it directly via `write_text_file`.- Always write the full file, including YAML frontmatter.+ Write the complete file including YAML frontmatter. Preserve all unchanged lines exactly as they appear — do not reformat, reindent, or alter any content you are not intentionally changing.+ Important: Your file writes are proposals that the user must review and accept before they take effect. Frame your responses accordingly — say "I've proposed the changes" or "Here are the changes for your review", not "Done" or "I've updated the file"."""private static let defaultAgentSystemPrompt = """@@ -290,7 +291,8 @@ final class TemplateManager {## Your roleWhen the user asks you to create or update this agent, use the ACP `write_text_file` tool to write the complete updated file content directly to the file path shown above.Do not show the content in a code block or ask for confirmation — write it directly via `write_text_file`.- Always write the full file, including YAML frontmatter.+ Write the complete file including YAML frontmatter. Preserve all unchanged lines exactly as they appear — do not reformat, reindent, or alter any content you are not intentionally changing.+ Important: Your file writes are proposals that the user must review and accept before they take effect. Frame your responses accordingly — say "I've proposed the changes" or "Here are the changes for your review", not "Done" or "I've updated the file"."""private static let defaultRuleSystemPrompt = """@@ -306,7 +308,8 @@ final class TemplateManager {## Your roleWhen the user asks you to create or update this rule, use the ACP `write_text_file` tool to write the complete updated file content directly to the file path shown above.Do not show the content in a code block or ask for confirmation — write it directly via `write_text_file`.- Always write the full file, including YAML frontmatter.+ Write the complete file including YAML frontmatter. Preserve all unchanged lines exactly as they appear — do not reformat, reindent, or alter any content you are not intentionally changing.+ Important: Your file writes are proposals that the user must review and accept before they take effect. Frame your responses accordingly — say "I've proposed the changes" or "Here are the changes for your review", not "Done" or "I've updated the file"."""}diff --git a/Chops/Views/Shared/ComposePanel.swift b/Chops/Views/Shared/ComposePanel.swiftindex 119c7a1..012a455 100644--- a/Chops/Views/Shared/ComposePanel.swift+++ b/Chops/Views/Shared/ComposePanel.swift@@ -4,6 +4,11 @@ import SwiftUI/// Inline panel for composing/editing skill content with ACPstruct ComposePanel: View {+ private struct DiffApplyError: Identifiable {+ let id = UUID()+ let message: String+ }+@Binding var content: String@Binding var isVisible: Boollet skillName: String@@ -30,6 +35,8 @@ struct ComposePanel: View {@State private var panelHeight: CGFloat = ComposeConstants.defaultPanelHeight@State private var isDragging = false@State private var dragStartHeight: CGFloat?+ @State private var applyingDiffID: String?+ @State private var diffApplyError: DiffApplyError?private static let minPanelHeight: CGFloat = 160private static let maxPanelHeight: CGFloat = 700@@ -109,6 +116,13 @@ struct ComposePanel: View {permissionSheet(request: request)}}+ .alert(item: $diffApplyError) { error in+ Alert(+ title: Text("Apply Failed"),+ message: Text(error.message),+ dismissButton: .default(Text("OK"))+ )+ }}@ViewBuilder@@ -575,7 +589,8 @@ struct ComposePanel: View {original: diff.original ?? "",proposed: diff.proposed,onAccept: { acceptDiff(messageId: messageId, diffIndex: diffIndex) },- onReject: { rejectDiff(messageId: messageId, diffIndex: diffIndex) }+ onReject: { rejectDiff(messageId: messageId, diffIndex: diffIndex) },+ isApplying: applyingDiffID == diffActionID(messageId: messageId, diffIndex: diffIndex)).frame(height: 260).clipShape(RoundedRectangle(cornerRadius: 8))@@ -805,10 +820,11 @@ struct ComposePanel: View {/// Attaches diffs from pending writes or disk changes; logs text-only turns.private func handleWrites(client: BaseACPAgent, messageId: UUID, filePath: String, originalContent: String) async {- acpLog.info("Compose: handleWrites — filePath=\(filePath) originalContent.count=\(originalContent.count)")+ let autoAccept = client.isBypassMode+ acpLog.info("Compose: handleWrites — filePath=\(filePath) originalContent.count=\(originalContent.count) autoAccept=\(autoAccept)")if !client.pendingWrites.isEmpty {acpLog.info("Compose: attaching \(client.pendingWrites.count) diff(s) from write_text_file")- await attachDiffs(messageId: messageId, writes: client.pendingWrites, fallbackOriginal: originalContent)+ await attachDiffs(messageId: messageId, writes: client.pendingWrites, fallbackOriginal: originalContent, autoAccept: autoAccept)client.clearPendingWrites()return}@@ -826,7 +842,8 @@ struct ComposePanel: View {existedBefore: true)],- fallbackOriginal: originalContent+ fallbackOriginal: originalContent,+ autoAccept: autoAccept)}}@@ -843,7 +860,8 @@ struct ComposePanel: View {private func attachDiffs(messageId: UUID,writes: [PendingWrite],- fallbackOriginal: String+ fallbackOriginal: String,+ autoAccept: Bool = false) async {guard let idx = messages.firstIndex(where: { $0.id == messageId }) else { return }let resolvedFilePath = resolvedPath(filePath)@@ -881,31 +899,17 @@ struct ComposePanel: View {)}messages[idx].diffs = diffs- }-- private func pendingDiffs() -> [ChatDiff] {- messages.flatMap(\.diffs).filter { $0.status == .pending }- }- nonisolated private static func revertDiffOnDisk(_ diff: ChatDiff) {- let url = URL(fileURLWithPath: diff.path)- if diff.existedBefore {- do {- if let originalData = diff.originalData {- try originalData.write(to: url)- } else if let original = diff.original {- try original.write(to: url, atomically: true, encoding: .utf8)- } else {- acpLog.error("Reject failed: missing original snapshot for \(diff.path)")+ if autoAccept {+ // Bypass mode: auto-accept all diffs. Disk writes already happened in handleFileWriteRequest.+ let resolvedFilePath = resolvedPath(filePath)+ for i in messages[idx].diffs.indices {+ messages[idx].diffs[i].status = .accepted+ let diff = messages[idx].diffs[i]+ if resolvedPath(diff.path) == resolvedFilePath {+ content = diff.proposed+ onAccept()}- } catch {- acpLog.error("Reject failed writing \(diff.path): \(error.localizedDescription)")- }- } else {- do {- try FileManager.default.removeItem(at: url)- } catch {- acpLog.error("Reject failed removing \(diff.path): \(error.localizedDescription)")}}}@@ -914,35 +918,65 @@ struct ComposePanel: View {guard let msgIdx = messages.firstIndex(where: { $0.id == messageId }),diffIndex < messages[msgIdx].diffs.count else { return }let diff = messages[msgIdx].diffs[diffIndex]- messages[msgIdx].diffs[diffIndex].status = .acceptedif resolvedPath(diff.path) == resolvedPath(filePath) {+ messages[msgIdx].diffs[diffIndex].status = .accepted+ // Currently-open file: update editor binding, onAccept() persists to disk.content = diff.proposedonAccept()+ } else {+ let actionID = diffActionID(messageId: messageId, diffIndex: diffIndex)+ guard applyingDiffID != actionID else { return }+ applyingDiffID = actionID+ Task {+ do {+ try await Self.persistAcceptedDiff(diff)+ guard let updatedMsgIdx = messages.firstIndex(where: { $0.id == messageId }),+ diffIndex < messages[updatedMsgIdx].diffs.count else {+ applyingDiffID = nil+ return+ }+ messages[updatedMsgIdx].diffs[diffIndex].status = .accepted+ } catch {+ let fileName = URL(fileURLWithPath: diff.path).lastPathComponent+ AppLogger.fileIO.error("Deferred diff apply failed for \(diff.path): \(error.localizedDescription)")+ diffApplyError = DiffApplyError(+ message: "Couldn't apply changes to \(fileName): \(error.localizedDescription)"+ )+ }+ applyingDiffID = nil+ }}}private func rejectDiff(messageId: UUID, diffIndex: Int) {guard let msgIdx = messages.firstIndex(where: { $0.id == messageId }),diffIndex < messages[msgIdx].diffs.count else { return }- let diff = messages[msgIdx].diffs[diffIndex]messages[msgIdx].diffs[diffIndex].status = .rejected- Task.detached(priority: .userInitiated) {- Self.revertDiffOnDisk(diff)- }+ // No disk revert needed — file was never written.+ }++ private func diffActionID(messageId: UUID, diffIndex: Int) -> String {+ "\(messageId.uuidString)-\(diffIndex)"+ }++ nonisolated private static func persistAcceptedDiff(_ diff: ChatDiff) async throws {+ try await Task.detached(priority: .userInitiated) {+ let url = URL(fileURLWithPath: diff.path)+ let parent = url.deletingLastPathComponent()+ if !FileManager.default.fileExists(atPath: parent.path) {+ try FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true, attributes: nil)+ }+ try diff.proposed.write(to: url, atomically: true, encoding: .utf8)+ }.value}private func forceDisconnect() {let client = acpClient- let pendingDiffs = pendingDiffs()acpClient = nilisFirstTurn = truemessages = []+ applyingDiffID = nilTask {- if !pendingDiffs.isEmpty {- await Task.detached(priority: .userInitiated) {- pendingDiffs.forEach(Self.revertDiffOnDisk)- }.value- }await client?.disconnect()}}diff --git a/Chops/Views/Shared/DiffReviewPanel.swift b/Chops/Views/Shared/DiffReviewPanel.swiftindex 9bfcec5..c328925 100644--- a/Chops/Views/Shared/DiffReviewPanel.swift+++ b/Chops/Views/Shared/DiffReviewPanel.swift@@ -100,6 +100,7 @@ struct DiffReviewPanel: View {let proposed: Stringlet onAccept: () -> Voidlet onReject: () -> Void+ var isApplying = false@State private var lines: [DiffLine] = []@@ -146,12 +147,14 @@ struct DiffReviewPanel: View {Button("Reject", action: onReject).buttonStyle(.bordered).controlSize(.small)+ .disabled(isApplying)- Button("Accept", action: onAccept)+ Button(isApplying ? "Applying..." : "Accept", action: onAccept).buttonStyle(.borderedProminent).controlSize(.small).tint(.green).keyboardShortcut(.return, modifiers: .command)+ .disabled(isApplying)}.padding(.horizontal, 12).padding(.vertical, 6)@@ -189,7 +192,8 @@ struct DiffReviewPanel: View {original: "# My Skill\n\nOld content here.\nLine two.\n",proposed: "# My Skill\n\nNew content here.\nLine two.\nLine three added.\n",onAccept: {},- onReject: {}+ onReject: {},+ isApplying: false).frame(width: 600, height: 300)}