Skip to content

armgit / chops

Public Imported from GitHub
0

Your AI agent skills, finally organized. A macOS app to browse, edit, and manage skills across Claude Code, Cursor, Codex, Windsurf, and Amp.

feat: improve ACP compose panel UX

Josh Pigford1fa1b9a09f4b
diff --git a/Chops/Services/ACP/ACPClient.swift b/Chops/Services/ACP/ACPClient.swift
index 06314eb..2ba51fe 100644
--- a/Chops/Services/ACP/ACPClient.swift
+++ b/Chops/Services/ACP/ACPClient.swift
@@ -12,6 +12,14 @@ struct PermissionRequest: Identifiable, @unchecked Sendable {
let continuation: CheckedContinuation<RequestPermissionResponse, Error>
}
+struct PendingWrite: Sendable {
+ let path: String
+ let content: String
+ let originalText: String?
+ let originalData: Data?
+ let existedBefore: Bool
+}
+
/// Base class for ACP agent interaction. Owns an `ACP.Client` actor and conforms to `ClientDelegate`.
/// Subclass to override vendor-specific hooks: additionalFlags, postProcess, conversationalText,
/// resolvePermission, and the onXxx stream callbacks.
@@ -24,7 +32,7 @@ open class BaseACPAgent: ClientDelegate {
var responseText: String = ""
var thoughtText: String = ""
var currentActivity: String?
- var pendingWrites: [(path: String, content: String, original: String?)] = []
+ var pendingWrites: [PendingWrite] = []
private(set) var sessionConfigOptions: [SessionConfigOption] = []
private(set) var pendingPermissionRequest: PermissionRequest?
private(set) var isConnected: Bool = false
@@ -122,6 +130,12 @@ open class BaseACPAgent: ClientDelegate {
connectTask = nil
notificationTask?.cancel()
notificationTask = nil
+ // Resume any parked permission continuation before tearing down —
+ // CheckedContinuation will crash if it is never resumed.
+ if let req = pendingPermissionRequest {
+ pendingPermissionRequest = nil
+ req.continuation.resume(returning: RequestPermissionResponse(outcome: PermissionOutcome(cancelled: true)))
+ }
let client = acpClient
acpClient = nil
sessionId = nil
@@ -153,6 +167,11 @@ open class BaseACPAgent: ClientDelegate {
private func onAgentDisconnected() {
if isConnected {
isConnected = false
+ // Resume any parked permission continuation so it doesn't leak.
+ if let req = pendingPermissionRequest {
+ pendingPermissionRequest = nil
+ req.continuation.resume(returning: RequestPermissionResponse(outcome: PermissionOutcome(cancelled: true)))
+ }
acpLog.debug("Agent process ended")
}
}
@@ -243,11 +262,24 @@ open class BaseACPAgent: ClientDelegate {
URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == resolvedIncoming
}
if !alreadyCaptured {
- let original = await Task.detached {
- (try? String(contentsOfFile: path, encoding: .utf8))
- ?? (try? String(contentsOfFile: path, encoding: .utf16))
+ let snapshot = await Task.detached {
+ let existedBefore = FileManager.default.fileExists(atPath: path)
+ let originalData = existedBefore ? try? Data(contentsOf: URL(fileURLWithPath: path)) : nil
+ return (
+ existedBefore,
+ originalData,
+ Self.decodeText(from: originalData)
+ )
}.value
- pendingWrites.append((path: path, content: content, original: original))
+ pendingWrites.append(
+ PendingWrite(
+ path: path,
+ content: content,
+ originalText: snapshot.2,
+ originalData: snapshot.1,
+ existedBefore: snapshot.0
+ )
+ )
}
// Write to disk — agent expects the file to be persisted.
try await Task.detached {
@@ -351,6 +383,12 @@ open class BaseACPAgent: ClientDelegate {
acpLog.error("'\(name)' not found in PATH — launch will likely fail")
return name
}
+
+ nonisolated static func decodeText(from data: Data?) -> String? {
+ guard let data else { return nil }
+ return String(data: data, encoding: .utf8)
+ ?? String(data: data, encoding: .utf16)
+ }
}
// MARK: - Errors
@@ -369,4 +407,3 @@ enum ACPClientError: Error, LocalizedError {
}
}
}
-
diff --git a/Chops/Services/ACP/Agents/ClaudeACPAgent.swift b/Chops/Services/ACP/Agents/ClaudeACPAgent.swift
index 3af175a..815d5ff 100644
--- a/Chops/Services/ACP/Agents/ClaudeACPAgent.swift
+++ b/Chops/Services/ACP/Agents/ClaudeACPAgent.swift
@@ -89,15 +89,38 @@ final class ClaudeACPAgent: BaseACPAgent {
guard let content else { return }
for item in content {
guard case .diff(let d) = item else { continue }
- let oldText: String? = d.oldText
- ?? (try? String(contentsOfFile: d.path, encoding: .utf8))
- ?? (try? String(contentsOfFile: d.path, encoding: .utf16))
+ let existedBefore = FileManager.default.fileExists(atPath: d.path)
+ let oldData: Data? = if let oldText = d.oldText {
+ oldText.data(using: .utf8)
+ } else if existedBefore {
+ try? Data(contentsOf: URL(fileURLWithPath: d.path))
+ } else {
+ nil
+ }
+ let oldText = d.oldText ?? BaseACPAgent.decodeText(from: oldData)
// Replace any existing entry for this path — Claude may emit multiple diff blocks
// for the same file (preview then final). The last one is the most current.
- if let existing = pendingWrites.firstIndex(where: { $0.path == d.path }) {
- pendingWrites[existing] = (path: d.path, content: d.newText, original: pendingWrites[existing].original)
+ let resolvedPath = URL(fileURLWithPath: d.path).resolvingSymlinksInPath().path
+ if let existing = pendingWrites.firstIndex(where: {
+ URL(fileURLWithPath: $0.path).resolvingSymlinksInPath().path == resolvedPath
+ }) {
+ pendingWrites[existing] = PendingWrite(
+ path: d.path,
+ content: d.newText,
+ originalText: pendingWrites[existing].originalText,
+ originalData: pendingWrites[existing].originalData,
+ existedBefore: pendingWrites[existing].existedBefore
+ )
} else {
- pendingWrites.append((path: d.path, content: d.newText, original: oldText))
+ pendingWrites.append(
+ PendingWrite(
+ path: d.path,
+ content: d.newText,
+ originalText: oldText,
+ originalData: oldData,
+ existedBefore: existedBefore
+ )
+ )
}
acpLog.info("diff intercepted: \(d.path) original=\(oldText?.count ?? -1) chars (\(pendingWrites.count) total)")
}
diff --git a/Chops/Services/TemplateManager.swift b/Chops/Services/TemplateManager.swift
index fa2fb11..a59908e 100644
--- a/Chops/Services/TemplateManager.swift
+++ b/Chops/Services/TemplateManager.swift
@@ -57,14 +57,15 @@ final class TemplateManager {
}
/// Save updated template content
- func save(_ template: WizardTemplate) {
+ func save(_ template: WizardTemplate, preserveVersionMarker: Bool = false) {
let url = templatesDirectory.appendingPathComponent(template.type.fileName)
+ let persistedContent = preserveVersionMarker ? template.content : stripVersionMarker(from: template.content)
do {
- try template.content.write(to: url, atomically: true, encoding: .utf8)
+ try persistedContent.write(to: url, atomically: true, encoding: .utf8)
if let index = templates.firstIndex(where: { $0.type == template.type }) {
templates[index] = WizardTemplate(
type: template.type,
- content: template.content,
+ content: persistedContent,
lastModified: Date()
)
}
@@ -77,7 +78,7 @@ final class TemplateManager {
func resetToDefault(_ type: WizardTemplateType) {
guard let bundledContent = loadBundledTemplate(type) else { return }
let template = WizardTemplate(type: type, content: bundledContent, lastModified: Date())
- save(template)
+ save(template, preserveVersionMarker: true)
}
/// Reset all templates to defaults
@@ -128,6 +129,14 @@ final class TemplateManager {
return Int(content[start.upperBound ..< end.lowerBound])
}
+ private func stripVersionMarker(from content: String) -> String {
+ content.replacingOccurrences(
+ of: #"^<!-- chops-template-version: \d+ -->\n?"#,
+ with: "",
+ options: .regularExpression
+ )
+ }
+
private func loadTemplates() {
templates = WizardTemplateType.allCases.compactMap { type in
let url = templatesDirectory.appendingPathComponent(type.fileName)
@@ -201,4 +210,3 @@ final class TemplateManager {
}
-
diff --git a/Chops/Views/Detail/SkillDetailView.swift b/Chops/Views/Detail/SkillDetailView.swift
index 4965ad0..919f618 100644
--- a/Chops/Views/Detail/SkillDetailView.swift
+++ b/Chops/Views/Detail/SkillDetailView.swift
@@ -48,6 +48,7 @@ struct SkillDetailView: View {
templateType: .skill,
onAccept: { document.save(to: skill) }
)
+ .id(skill.filePath)
}
Divider()
diff --git a/Chops/Views/Settings/SettingsView.swift b/Chops/Views/Settings/SettingsView.swift
index c2095ea..1ec04b0 100644
--- a/Chops/Views/Settings/SettingsView.swift
+++ b/Chops/Views/Settings/SettingsView.swift
@@ -39,7 +39,7 @@ struct SettingsView: View {
Label("About", systemImage: "info.circle")
}
}
- .frame(minWidth: 480, minHeight: 550, idealHeight: 600)
+ .frame(minWidth: 480, maxWidth: 480, minHeight: 300)
.onAppear {
loadCustomPaths()
}
diff --git a/Chops/Views/Shared/ComposeModel.swift b/Chops/Views/Shared/ComposeModel.swift
index 8d21bbb..39a9c49 100644
--- a/Chops/Views/Shared/ComposeModel.swift
+++ b/Chops/Views/Shared/ComposeModel.swift
@@ -4,12 +4,14 @@ import Foundation
enum ChatRole { case user, assistant }
-enum DiffStatus { case pending, accepted, rejected }
+enum DiffStatus: Sendable { case pending, accepted, rejected }
-struct ChatDiff {
+struct ChatDiff: Sendable {
let path: String
/// Pre-edit content. `nil` means the file did not exist before the agent wrote it.
let original: String?
+ let originalData: Data?
+ let existedBefore: Bool
let proposed: String
var status: DiffStatus = .pending
}
diff --git a/Chops/Views/Shared/ComposePanel.swift b/Chops/Views/Shared/ComposePanel.swift
index e1b8814..e962b30 100644
--- a/Chops/Views/Shared/ComposePanel.swift
+++ b/Chops/Views/Shared/ComposePanel.swift
@@ -17,7 +17,7 @@ struct ComposePanel: View {
@State private var selectedTemplateType: WizardTemplateType
@State private var inputText = ""
- @State private var selectedAgentId: String?
+ @AppStorage("ACPSelectedAgentId") private var selectedAgentId: String?
@State private var acpClient: BaseACPAgent?
@State private var showingDebugLogs = false
@@ -70,11 +70,12 @@ struct ComposePanel: View {
if configuredAgents.isEmpty {
noToolsConfiguredView
+ } else if !isConnected && messages.isEmpty {
+ agentPickerEmptyState
} else {
VStack(spacing: 0) {
topBar
Divider()
- configOptionsBar
chatArea
Divider()
inputArea
@@ -94,6 +95,11 @@ struct ComposePanel: View {
.onChange(of: selectedAgentId) { _, _ in
forceDisconnect()
}
+ .onChange(of: configuredAgents.map(\.id)) { _, newIds in
+ if selectedAgentId == nil || !newIds.contains(selectedAgentId ?? "") {
+ selectedAgentId = newIds.first
+ }
+ }
.task { await ACPConfiguration.shared.loadRegistryIfNeeded() }
.sheet(isPresented: Binding(
get: { acpClient?.pendingPermissionRequest != nil },
@@ -144,21 +150,101 @@ struct ComposePanel: View {
@Environment(\.openSettings) private var openSettings
+ private var agentPickerEmptyState: some View {
+ ZStack(alignment: .topTrailing) {
+ VStack(spacing: 12) {
+ Image(systemName: "sparkles")
+ .font(.largeTitle)
+ .foregroundStyle(.tertiary)
+ Text("Choose an agent to get started")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ Picker("", selection: $selectedAgentId) {
+ Text("Select agent…").tag(nil as String?)
+ ForEach(configuredAgents) { agent in
+ Text(agent.name).tag(Optional(agent.id))
+ }
+ }
+ .labelsHidden()
+ .fixedSize()
+ if selectedAgentId != nil {
+ if isConnecting {
+ HStack(spacing: 6) {
+ ProgressView().controlSize(.small)
+ Text("Connecting…")
+ .foregroundStyle(.secondary)
+ }
+ .font(.callout)
+ } else {
+ Button {
+ connect()
+ } label: {
+ Label("Connect", systemImage: "link")
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.regular)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+
+ closeButton
+ .padding(12)
+ }
+ }
+
+ @State private var configuration = ACPConfiguration.shared
+
private var noToolsConfiguredView: some View {
- HStack(spacing: 12) {
- Image(systemName: "exclamationmark.triangle")
- .foregroundStyle(.orange)
- Text("No ACP agents enabled.")
- .foregroundStyle(.secondary)
- Button("Open Settings") {
- openSettings()
+ ZStack(alignment: .topTrailing) {
+ VStack(spacing: 16) {
+ Image(systemName: "sparkles")
+ .font(.largeTitle)
+ .foregroundStyle(.tertiary)
+ Text("Enable an agent to get started")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+
+ VStack(spacing: 0) {
+ if configuration.isLoadingRegistry {
+ HStack(spacing: 6) {
+ ProgressView().controlSize(.small)
+ Text("Loading agents…").foregroundStyle(.secondary)
+ }
+ .padding(.vertical, 12)
+ } else {
+ ForEach(configuration.registryAgents) { agent in
+ HStack(spacing: 10) {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(agent.name)
+ .font(.callout.weight(.medium))
+ Text(agent.description)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+ Spacer()
+ Toggle("", isOn: Binding(
+ get: { configuration.isEnabled(agent.id) },
+ set: { configuration.setEnabled(agent.id, $0) }
+ ))
+ .labelsHidden()
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ }
+ }
+ }
+ .background(Color.primary.opacity(0.05))
+ .clipShape(RoundedRectangle(cornerRadius: 8))
+ .frame(maxWidth: 320)
}
- .buttonStyle(.link)
- Spacer()
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+
closeButton
+ .padding(12)
}
- .padding(.horizontal, 12)
- .padding(.vertical, 8)
+ .task { await configuration.loadRegistryIfNeeded() }
}
private var topBar: some View {
@@ -193,18 +279,9 @@ struct ComposePanel: View {
.frame(maxWidth: 200)
}
- // RIGHT: Template picker + close
- // Always visible so the selection is clear; disabled after first turn.
- HStack(spacing: 12) {
- Picker("", selection: $selectedTemplateType) {
- ForEach(WizardTemplateType.allCases) { type in
- Label(type.displayName, systemImage: type.icon).tag(type)
- }
- }
- .labelsHidden()
- .frame(width: 140)
- .disabled(!isFirstTurn)
- .help(isFirstTurn ? "Template for this session" : "Reconnect to change template")
+ // RIGHT: Config options (when connected) + close
+ HStack(spacing: 8) {
+ inlineConfigOptions
closeButton
}
}
@@ -215,24 +292,16 @@ struct ComposePanel: View {
// MARK: - Config Options Bar
- /// Renders a row of pickers for session-level config options (mode, model, etc.).
- /// Visible only when connected and the agent has returned at least one config option.
+ /// Inline config option pickers shown in the top bar when connected.
@ViewBuilder
- private var configOptionsBar: some View {
+ private var inlineConfigOptions: some View {
let options = acpClient?.sessionConfigOptions ?? []
if isConnected && !options.isEmpty {
- HStack(spacing: 12) {
- ForEach(options, id: \.id) { option in
- if case .select(let select) = option.kind {
- configOptionPicker(option: option, select: select)
- }
+ ForEach(options, id: \.id) { option in
+ if case .select(let select) = option.kind {
+ configOptionPicker(option: option, select: select)
}
- Spacer()
}
- .padding(.horizontal, 12)
- .padding(.vertical, 6)
- .background(Color(.controlBackgroundColor).opacity(0.6))
- Divider()
}
}
@@ -251,7 +320,7 @@ struct ComposePanel: View {
}
)) {
ForEach(flatOptions, id: \.value) { opt in
- Text(opt.name).tag(opt.value)
+ Text(opt.name.replacingOccurrences(of: " (recommended)", with: "")).tag(opt.value)
}
}
.fixedSize()
@@ -277,8 +346,10 @@ struct ComposePanel: View {
if messages.isEmpty && !isProcessing {
if isConnected {
connectedPlaceholder
+ .frame(height: geo.size.height - 24)
} else {
disconnectedPlaceholder
+ .frame(height: geo.size.height - 24)
}
}
ForEach(visibleMessages) { message in
@@ -314,24 +385,34 @@ struct ComposePanel: View {
}
private var disconnectedPlaceholder: some View {
- VStack(spacing: 8) {
- Image(systemName: "link.badge.plus")
- .font(.title2)
- .foregroundStyle(.secondary)
- Text("Connect an agent to start composing")
+ VStack(spacing: 12) {
+ Image(systemName: "sparkles")
+ .font(.largeTitle)
+ .foregroundStyle(.tertiary)
+ Text("Connect to start editing with AI")
.font(.callout)
.foregroundStyle(.secondary)
+ Button {
+ connect()
+ } label: {
+ Label("Connect", systemImage: "link")
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.regular)
}
- .frame(maxWidth: .infinity)
- .padding(.vertical, 20)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
}
private var connectedPlaceholder: some View {
- Text("Session ready. Send your first instruction.")
- .font(.callout)
- .foregroundStyle(.secondary)
- .frame(maxWidth: .infinity)
- .padding(.vertical, 20)
+ VStack(spacing: 8) {
+ Text("Describe what you'd like to change")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ Text("The agent will edit this skill based on your instructions")
+ .font(.caption)
+ .foregroundStyle(.tertiary)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
}
// MARK: - Live Assistant Row (SDK-driven, shown while prompt is active)
@@ -353,7 +434,6 @@ struct ComposePanel: View {
Image(systemName: "sparkles").foregroundStyle(.secondary)
Text("Agent").foregroundStyle(.secondary)
Spacer()
- ProgressView().controlSize(.mini).padding(.trailing, 2)
}
.font(.caption)
.padding(.horizontal, 10).padding(.top, 8).padding(.bottom, 4)
@@ -383,7 +463,7 @@ struct ComposePanel: View {
}
}
.frame(maxWidth: bubbleWidth, alignment: .leading)
- .background(Color.primary.opacity(0.06))
+ .background(Color.primary.opacity(0.09))
.clipShape(RoundedRectangle(cornerRadius: 8))
.overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.secondary.opacity(0.2)))
}
@@ -403,8 +483,8 @@ struct ComposePanel: View {
.textSelection(.enabled)
.padding(.horizontal, 10)
.padding(.vertical, 7)
- .background(Color.accentColor.opacity(0.15))
- .clipShape(RoundedRectangle(cornerRadius: 10))
+ .background(Color.accentColor.opacity(0.22))
+ .clipShape(RoundedRectangle(cornerRadius: 8))
.frame(maxWidth: bubbleWidth, alignment: .trailing)
}
case .assistant:
@@ -461,7 +541,7 @@ struct ComposePanel: View {
.frame(maxWidth: .infinity, alignment: .leading)
// Use a primary-relative tint so the card is visibly distinct from the window
// background in both light and dark mode (controlBackgroundColor is too similar).
- .background(message.isError ? Color.orange.opacity(0.08) : Color.primary.opacity(0.06))
+ .background(message.isError ? Color.orange.opacity(0.08) : Color.primary.opacity(0.09))
.clipShape(RoundedRectangle(cornerRadius: 8))
.overlay(
RoundedRectangle(cornerRadius: 8)
@@ -505,26 +585,25 @@ struct ComposePanel: View {
// MARK: - Input Area
+ private var sendDisabled: Bool {
+ !isConnected || inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isProcessing || hasPendingDiffs
+ }
+
private var inputArea: some View {
HStack(alignment: .bottom, spacing: 8) {
- ZStack(alignment: .topLeading) {
- if inputText.isEmpty {
- Text(isFirstTurn ? "Enter instructions…" : "Follow up…")
- .foregroundStyle(.tertiary)
- .padding(.horizontal, 10)
- .padding(.vertical, 8)
+ TextField(isFirstTurn ? "Enter instructions…" : "Follow up…", text: $inputText, axis: .vertical)
+ .font(.body)
+ .textFieldStyle(.plain)
+ .lineLimit(1...4)
+ .disabled(isProcessing || !isConnected || hasPendingDiffs)
+ .onSubmit {
+ if !sendDisabled { sendMessage() }
}
- TextEditor(text: $inputText)
- .font(.body)
- .scrollContentBackground(.hidden)
- .frame(minHeight: 36, maxHeight: 80)
- .disabled(isProcessing || !isConnected || hasPendingDiffs)
- .padding(.horizontal, 4)
- .padding(.vertical, 4)
- }
- .background(Color(.textBackgroundColor))
- .clipShape(RoundedRectangle(cornerRadius: 6))
- .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.secondary.opacity(0.2)))
+ .padding(.horizontal, 8)
+ .padding(.vertical, 8)
+ .background(Color(.textBackgroundColor))
+ .clipShape(RoundedRectangle(cornerRadius: 8))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.secondary.opacity(0.25)))
Button {
sendMessage()
@@ -536,27 +615,34 @@ struct ComposePanel: View {
Image(systemName: "paperplane.fill")
}
}
- .frame(width: 24, height: 24)
+ .font(.body)
+ .foregroundStyle(.white)
+ .frame(width: 36)
+ .frame(maxHeight: .infinity)
+ .background(sendDisabled ? Color.accentColor.opacity(0.4) : Color.accentColor)
+ .clipShape(RoundedRectangle(cornerRadius: 8))
}
- .buttonStyle(.borderedProminent)
- .disabled(!isConnected || inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isProcessing || hasPendingDiffs)
+ .buttonStyle(.plain)
+ .disabled(sendDisabled)
.keyboardShortcut(.return, modifiers: .command)
+ .help("Send (⌘↩)")
}
+ .fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 12)
.padding(.vertical, 8)
.background(Color(.controlBackgroundColor))
}
private var resizeHandle: some View {
- ZStack {
+ VStack(spacing: 0) {
Color(.separatorColor)
.frame(height: 1)
RoundedRectangle(cornerRadius: 2)
.fill(Color.secondary.opacity(isDragging ? 0.5 : 0.25))
.frame(width: 36, height: 4)
+ .padding(.vertical, 3)
}
.frame(maxWidth: .infinity)
- .frame(height: 10)
.contentShape(Rectangle())
.onHover { hovering in
if hovering {
@@ -650,14 +736,6 @@ struct ComposePanel: View {
client.startConnect(agent: agent, workingDirectory: workingDirectory, systemPrompt: systemPrompt)
}
- private func forceDisconnect() {
- let client = acpClient
- acpClient = nil
- isFirstTurn = true
- messages = []
- Task { await client?.disconnect() }
- }
-
private func sendMessage() {
guard let client = acpClient else { return }
let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -724,12 +802,25 @@ struct ComposePanel: View {
client.clearPendingWrites()
let newContent = await readFile(at: filePath) ?? originalContent
if newContent != originalContent {
- await attachDiffs(messageId: messageId, writes: [(path: filePath, content: newContent, original: nil)], fallbackOriginal: originalContent)
+ await attachDiffs(
+ messageId: messageId,
+ writes: [
+ PendingWrite(
+ path: filePath,
+ content: newContent,
+ originalText: originalContent,
+ originalData: originalContent.data(using: .utf8),
+ existedBefore: true
+ )
+ ],
+ fallbackOriginal: originalContent
+ )
}
}
/// Converts pending writes into ChatDiff entries and attaches them to the message.
- /// Disk reads for non-current files are dispatched off the main actor.
+ /// Uses the pre-write snapshot captured by the ACP layer; do not reread disk here because
+ /// the agent may already have mutated the file.
/// Resolves `path` through symlinks so that e.g. a `.cursor/rules/foo.md` symlink
/// and its target `~/.aidevtools/rules/foo.md` compare as equal.
private func resolvedPath(_ path: String) -> String {
@@ -738,7 +829,7 @@ struct ComposePanel: View {
private func attachDiffs(
messageId: UUID,
- writes: [(path: String, content: String, original: String?)],
+ writes: [PendingWrite],
fallbackOriginal: String
) async {
guard let idx = messages.firstIndex(where: { $0.id == messageId }) else { return }
@@ -748,22 +839,56 @@ struct ComposePanel: View {
for write in writes {
let writtenResolved = resolvedPath(write.path)
let original: String?
- if let embedded = write.original {
+ let originalData: Data?
+ let existedBefore: Bool
+ if let embedded = write.originalText {
// Agent supplied the pre-edit content (e.g. DiffContent.oldText) — use it directly.
original = embedded
+ originalData = write.originalData
+ existedBefore = write.existedBefore
} else if write.path == filePath || writtenResolved == resolvedFilePath {
// Path matches (accounting for symlinks) — use the in-memory content from before the turn.
original = fallbackOriginal
+ originalData = fallbackOriginal.data(using: .utf8)
+ existedBefore = true
} else {
- // Different file: read from disk. nil means the file didn't exist (new file).
- original = await readFile(at: write.path)
+ original = write.originalText
+ originalData = write.originalData
+ existedBefore = write.existedBefore
}
acpLog.debug("Compose: diff \(write.path) original=\(original?.count ?? -1) chars")
- diffs.append(ChatDiff(path: write.path, original: original, proposed: write.content))
+ diffs.append(
+ ChatDiff(
+ path: write.path,
+ original: original,
+ originalData: originalData,
+ existedBefore: existedBefore,
+ proposed: write.content
+ )
+ )
}
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 {
+ 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)")
+ }
+ } else {
+ try? FileManager.default.removeItem(at: url)
+ }
+ }
+
private func acceptDiff(messageId: UUID, diffIndex: Int) {
guard let msgIdx = messages.firstIndex(where: { $0.id == messageId }),
diffIndex < messages[msgIdx].diffs.count else { return }
@@ -780,16 +905,24 @@ struct ComposePanel: View {
diffIndex < messages[msgIdx].diffs.count else { return }
let diff = messages[msgIdx].diffs[diffIndex]
messages[msgIdx].diffs[diffIndex].status = .rejected
- // Revert the file to its pre-edit state.
- // nil original means the agent created a new file — delete it on reject.
- let original = diff.original
- let path = diff.path
Task.detached(priority: .userInitiated) {
- if let original {
- try? original.write(toFile: path, atomically: true, encoding: .utf8)
- } else {
- try? FileManager.default.removeItem(atPath: path)
+ Self.revertDiffOnDisk(diff)
+ }
+ }
+
+ private func forceDisconnect() {
+ let client = acpClient
+ let pendingDiffs = pendingDiffs()
+ acpClient = nil
+ isFirstTurn = true
+ messages = []
+ Task {
+ if !pendingDiffs.isEmpty {
+ await Task.detached(priority: .userInitiated) {
+ pendingDiffs.forEach(Self.revertDiffOnDisk)
+ }.value
}
+ await client?.disconnect()
}
}
}
diff --git a/Chops/Views/Shared/ThinkingView.swift b/Chops/Views/Shared/ThinkingView.swift
index 1fadc30..c9f83fd 100644
--- a/Chops/Views/Shared/ThinkingView.swift
+++ b/Chops/Views/Shared/ThinkingView.swift
@@ -6,7 +6,7 @@ struct ThinkingView: View {
let text: String
let isStreaming: Bool
- @State private var isExpanded: Bool = true
+ @State private var isExpanded: Bool = false
/// Latched true once streaming ends — shows brain icon instead of spinner.
@State private var settled: Bool = false