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.

add acp support (#69)

Miguel Zavala55fbd7cdd783
diff --git a/CLAUDE.md b/CLAUDE.md
index c13a93f..767930d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -49,8 +49,13 @@ No test suite exists. Validate manually by building and running.
- `SkillScanner` — probes tool directories (~/.claude/skills/, ~/.cursor/rules/, etc.), parses frontmatter, upserts into SwiftData. Deduplicates via resolved symlink paths.
- `FileWatcher` — FSEvents via `DispatchSourceFileSystemObject`, triggers re-scan on changes.
- `SkillParser` → dispatches to `FrontmatterParser` (.md) or `MDCParser` (.mdc).
+- **ACP agent hierarchy** — `BaseACPAgent` owns all transport/session logic. Vendor subclasses override three hooks:
+ - `shouldFilter(JsonRpcMessage) → Bool` — drop messages before SDK decoding (e.g. Augment's `usage_update`)
+ - `postProcess(String) → String` — strip vendor-specific XML tags before text is stored
+ - `resolvePermission(title, options)` — present permission UI; hook for future session-wide allow-all
+ - `ACPAgentFactory.make(for: ToolSource)` instantiates the right subclass; `ComposePanel` holds `BaseACPAgent?`.
-**Views:** Three-column `NavigationSplitView` (Sidebar → List → Detail). Editor uses native `NSTextView` with markdown highlighting. Cmd+S save via `FocusedValues`.
+**Views:** Three-column `NavigationSplitView` (Sidebar → List → Detail). Editor uses native `NSTextView` with markdown highlighting. Cmd+S save via `FocusedValues`. Agent responses render via `MarkdownMessageView` (MarkdownUI `.gitHub` theme + syntax highlighting).
**Tool sources** are defined in `ToolSource.swift` — each enum case knows its display name, icon, and filesystem paths to scan.
diff --git a/Chops.xcodeproj/project.pbxproj b/Chops.xcodeproj/project.pbxproj
index da51d83..09d3445 100644
--- a/Chops.xcodeproj/project.pbxproj
+++ b/Chops.xcodeproj/project.pbxproj
@@ -7,17 +7,29 @@
objects = {
/* Begin PBXBuildFile section */
+ 038F5975DA97A3211EF4D448 /* ThinkingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D07C2CD05E172DB71F63033 /* ThinkingView.swift */; };
+ 08B4E2A065E192F17F2568B6 /* TemplateDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E792EE2E83B2068F8C5305F /* TemplateDetailView.swift */; };
09D3F065191A83BDEE922789 /* SkillDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 168E103488DEA623E712852B /* SkillDetailView.swift */; };
+ 0DC3536F86CAA3C4680958AF /* ACPModel in Frameworks */ = {isa = PBXBuildFile; productRef = 86292938A0949F325E358FA5 /* ACPModel */; };
+ 1BBEBC85C24BBC4E08AA1821 /* ACPLogViewer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F236C158C893B626A51E385 /* ACPLogViewer.swift */; };
2263A0A3B358FBA099D0086D /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A924245DDDA4C6A59BE15567 /* SettingsView.swift */; };
25A4FB387DB5BD96DB630C14 /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 231C267216AF1BCA8628B667 /* AppState.swift */; };
309B12E0B72A22C9772BBC99 /* ChopsApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2787064DC7DF112E70C4E4D0 /* ChopsApp.swift */; };
+ 322C22C23073C29FC0C6098D /* MarkdownMessageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 947EAED7376B7762A373EF08 /* MarkdownMessageView.swift */; };
331F55021A7E6C9F0B666514 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = 4338FC540625A275BBC9AAC9 /* Sparkle */; };
+ 3BF88469DCE0B56DD15DDB09 /* ACPClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DAD83C176F3A71A5B360BFD /* ACPClient.swift */; };
+ 3F0ED402E77D8D25C600BAED /* TemplateManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 12C5CD1627D4EFF58AEF4F71 /* TemplateManager.swift */; };
480681BAD19F7CAF6AE154A2 /* RemoteServersSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E684304D1723CA691F40335B /* RemoteServersSettingsView.swift */; };
53C393C13E30EC439317509F /* ToolBadge.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7B6AE242CAD6A285DD57079 /* ToolBadge.swift */; };
+ 590A98554CAF058BC006CC53 /* ACPAgentFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BBC9E32924CF525F1C96BAE /* ACPAgentFactory.swift */; };
5B81DED237A60776ADB04134 /* RemoteServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3314080A44DEB895223E36D5 /* RemoteServer.swift */; };
60A6711BAB0C3B8A3ACBF985 /* SkillParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5155D141EF812A3FE9ADF59C /* SkillParser.swift */; };
+ 62C6C8687D8A1E3C1EBBBC8C /* ClaudeACPAgent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5E201054F47FC1E66D6E0BE2 /* ClaudeACPAgent.swift */; };
6A8E0927D95BB14C9F377F4E /* SkillScanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6A5B26D335C1AFB6CDE8207 /* SkillScanner.swift */; };
+ 6E02BA7498763274DD403CD0 /* DiffReviewPanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = B955C8B935BD62ED4811FCA2 /* DiffReviewPanel.swift */; };
71E92A838AB4D1D6DC6174AF /* NewSkillSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = F02A00F80E4712872205EA7B /* NewSkillSheet.swift */; };
+ 72F7688C0EDA2DAF80C6512B /* ACPLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 511C5A2149EFF77BDA7D4692 /* ACPLogger.swift */; };
+ 74045816B0CF10369DB51ADD /* ComposePanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 937F83BF3496CB231C535608 /* ComposePanel.swift */; };
791AA125E9170DBA81BCBE62 /* Highlightr in Frameworks */ = {isa = PBXBuildFile; productRef = 704A14702546BFBD29BE27A8 /* Highlightr */; };
7A17C99C5EFAE3AA9E788D50 /* Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9AFE1AF02B0F8057791C2A9 /* Collection.swift */; };
7EC6156934D559226BC78859 /* CollectionListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CA102A49ACFB23BC15794F8 /* CollectionListView.swift */; };
@@ -25,6 +37,7 @@
801A39D725B59A2F2BAF5DF2 /* cmark in Frameworks */ = {isa = PBXBuildFile; productRef = 9F4BE66CFE1E8401894FEF1F /* cmark */; };
846B58F3B105D1734DC6FA75 /* SkillRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9FC9D3E83D8640CC258CF361 /* SkillRegistry.swift */; };
87A469B631CC80C89B14B1C7 /* SkillMetadataBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C812515FD8DC222B89745F2 /* SkillMetadataBar.swift */; };
+ 87AEE95EAD9793D3241D4387 /* ACP in Frameworks */ = {isa = PBXBuildFile; productRef = F642568B19B420E64E62307D /* ACP */; };
91EA572FCA75A2EA848C3429 /* ChopsTextView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A58EBE34E8A678FC897DFCB /* ChopsTextView.swift */; };
95163AEB7980654C901EC693 /* Skill.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27D6ED655F951177D2152351 /* Skill.swift */; };
98434D3DDFEEC7239F6F7B79 /* RegistrySheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FCD6C2A8BE68F553A9CA392 /* RegistrySheet.swift */; };
@@ -38,13 +51,19 @@
BFF9964529E6C48F4F7BCB97 /* MarkdownSyntaxHighlighter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 135976FA0E8358E099157DE1 /* MarkdownSyntaxHighlighter.swift */; };
C30BEAE03E54BD36F257A925 /* ToolFilterView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A5774429CCE83C2AFBE046C /* ToolFilterView.swift */; };
C6CFF37CC0B155E8846344A4 /* ChopsIcon.icon in Resources */ = {isa = PBXBuildFile; fileRef = 04C3C644B72DD508A7CBC403 /* ChopsIcon.icon */; };
+ C983C685C6296C2EF73CE57D /* CursorACPAgent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07899C351E63B32277272A59 /* CursorACPAgent.swift */; };
CBD8FECF1C5A453C8B021665 /* FrontmatterParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C77C5B30E6C885B39444E5B /* FrontmatterParser.swift */; };
CCD92CB102DFA0965D6AFDB5 /* SidebarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CF7822031FD82A28978D9C5 /* SidebarView.swift */; };
CECE9BEEC1D933C543B66A4E /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 17F7FE50C96124BA4EE43A6F /* Assets.xcassets */; };
D4C107BE303FC07CAF9C66AF /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60E0F71982C4AF0045962380 /* ContentView.swift */; };
+ E15FE0630C11B3D0BC4C25ED /* ACPConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = D946A13468984E6DEBC20B9A /* ACPConfiguration.swift */; };
+ E46A2BA5FA20531A06AFB418 /* ComposeModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CAA9B98C7A69F32C6950710 /* ComposeModel.swift */; };
E6F4E1CF50F2F78F5BA9BAC9 /* SkillPreviewView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77E332B9970E6E3D00DCFBA3 /* SkillPreviewView.swift */; };
E7ED248D6F94C1B1DEF1E8BA /* MarkdownRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 372FA72F2C179B79470DF86A /* MarkdownRenderer.swift */; };
E98F7490B18A194F82ED2C0E /* SkillListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA64A368BBF950CD36C4F495 /* SkillListView.swift */; };
+ F16A5D53C17EB72817E1282F /* WizardTemplate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 181FD0056E54DEB3957FB4DC /* WizardTemplate.swift */; };
+ F3F5B40B2B8F6C684313097D /* ACPRegistry in Frameworks */ = {isa = PBXBuildFile; productRef = 642A52CB994BF3466A09E6A6 /* ACPRegistry */; };
+ F482F0222F6C14110B01D47F /* ACPSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C052B94D025127C9823E7BC /* ACPSettingsView.swift */; };
F98B1E8579B139FD2A801650 /* SearchService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FFC47BDE92105F4736B379F /* SearchService.swift */; };
FB295303DD30AED03290C726 /* SkillEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31B4DB87833D5160A11E39C9 /* SkillEditorView.swift */; };
FD8D2544AE423F4AB2843C0F /* AgentTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 907E59B064AB8366B60BF611 /* AgentTarget.swift */; };
@@ -52,40 +71,56 @@
/* Begin PBXFileReference section */
04C3C644B72DD508A7CBC403 /* ChopsIcon.icon */ = {isa = PBXFileReference; lastKnownFileType = wrapper.icon; path = ChopsIcon.icon; sourceTree = "<group>"; };
+ 07899C351E63B32277272A59 /* CursorACPAgent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CursorACPAgent.swift; sourceTree = "<group>"; };
+ 12C5CD1627D4EFF58AEF4F71 /* TemplateManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateManager.swift; sourceTree = "<group>"; };
135976FA0E8358E099157DE1 /* MarkdownSyntaxHighlighter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownSyntaxHighlighter.swift; sourceTree = "<group>"; };
168E103488DEA623E712852B /* SkillDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillDetailView.swift; sourceTree = "<group>"; };
17F7FE50C96124BA4EE43A6F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+ 181FD0056E54DEB3957FB4DC /* WizardTemplate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WizardTemplate.swift; sourceTree = "<group>"; };
231C267216AF1BCA8628B667 /* AppState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppState.swift; sourceTree = "<group>"; };
2787064DC7DF112E70C4E4D0 /* ChopsApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChopsApp.swift; sourceTree = "<group>"; };
27D6ED655F951177D2152351 /* Skill.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Skill.swift; sourceTree = "<group>"; };
2CF7822031FD82A28978D9C5 /* SidebarView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarView.swift; sourceTree = "<group>"; };
+ 2D07C2CD05E172DB71F63033 /* ThinkingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThinkingView.swift; sourceTree = "<group>"; };
31B4DB87833D5160A11E39C9 /* SkillEditorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillEditorView.swift; sourceTree = "<group>"; };
3314080A44DEB895223E36D5 /* RemoteServer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteServer.swift; sourceTree = "<group>"; };
372FA72F2C179B79470DF86A /* MarkdownRenderer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownRenderer.swift; sourceTree = "<group>"; };
3A4F680B33C74A38FCF5ADD5 /* MDCParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MDCParser.swift; sourceTree = "<group>"; };
4CA102A49ACFB23BC15794F8 /* CollectionListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CollectionListView.swift; sourceTree = "<group>"; };
+ 511C5A2149EFF77BDA7D4692 /* ACPLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPLogger.swift; sourceTree = "<group>"; };
5155D141EF812A3FE9ADF59C /* SkillParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillParser.swift; sourceTree = "<group>"; };
5487D9027B97F7E9EE9A1F4A /* ToolSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolSource.swift; sourceTree = "<group>"; };
+ 5CAA9B98C7A69F32C6950710 /* ComposeModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposeModel.swift; sourceTree = "<group>"; };
+ 5E201054F47FC1E66D6E0BE2 /* ClaudeACPAgent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeACPAgent.swift; sourceTree = "<group>"; };
+ 5F236C158C893B626A51E385 /* ACPLogViewer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPLogViewer.swift; sourceTree = "<group>"; };
60E0F71982C4AF0045962380 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
6797D4AC1970DB9ACB5ACA73 /* SSHService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SSHService.swift; sourceTree = "<group>"; };
+ 6E792EE2E83B2068F8C5305F /* TemplateDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemplateDetailView.swift; sourceTree = "<group>"; };
77E332B9970E6E3D00DCFBA3 /* SkillPreviewView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillPreviewView.swift; sourceTree = "<group>"; };
7C77C5B30E6C885B39444E5B /* FrontmatterParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FrontmatterParser.swift; sourceTree = "<group>"; };
7FCD6C2A8BE68F553A9CA392 /* RegistrySheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RegistrySheet.swift; sourceTree = "<group>"; };
7FFC47BDE92105F4736B379F /* SearchService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SearchService.swift; sourceTree = "<group>"; };
8A58EBE34E8A678FC897DFCB /* ChopsTextView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ChopsTextView.swift; sourceTree = "<group>"; };
8C812515FD8DC222B89745F2 /* SkillMetadataBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillMetadataBar.swift; sourceTree = "<group>"; };
+ 8DAD83C176F3A71A5B360BFD /* ACPClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPClient.swift; sourceTree = "<group>"; };
907E59B064AB8366B60BF611 /* AgentTarget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentTarget.swift; sourceTree = "<group>"; };
+ 937F83BF3496CB231C535608 /* ComposePanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposePanel.swift; sourceTree = "<group>"; };
+ 947EAED7376B7762A373EF08 /* MarkdownMessageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MarkdownMessageView.swift; sourceTree = "<group>"; };
9A5774429CCE83C2AFBE046C /* ToolFilterView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolFilterView.swift; sourceTree = "<group>"; };
+ 9BBC9E32924CF525F1C96BAE /* ACPAgentFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPAgentFactory.swift; sourceTree = "<group>"; };
+ 9C052B94D025127C9823E7BC /* ACPSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPSettingsView.swift; sourceTree = "<group>"; };
9FC9D3E83D8640CC258CF361 /* SkillRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillRegistry.swift; sourceTree = "<group>"; };
A7B6AE242CAD6A285DD57079 /* ToolBadge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToolBadge.swift; sourceTree = "<group>"; };
A924245DDDA4C6A59BE15567 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
AA64A368BBF950CD36C4F495 /* SkillListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillListView.swift; sourceTree = "<group>"; };
B1F8AA042D5D8A9F92F35CA3 /* SchemaVersions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SchemaVersions.swift; sourceTree = "<group>"; };
B3F5CF5BB1FC8455FDDB004A /* Chops.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Chops.app; sourceTree = BUILT_PRODUCTS_DIR; };
+ B955C8B935BD62ED4811FCA2 /* DiffReviewPanel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiffReviewPanel.swift; sourceTree = "<group>"; };
C9AFE1AF02B0F8057791C2A9 /* Collection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Collection.swift; sourceTree = "<group>"; };
CAD26AA4787A2E0CDC86AADC /* FileWatcher.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileWatcher.swift; sourceTree = "<group>"; };
D24B049638C76AC6248FD5D2 /* EditorTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EditorTheme.swift; sourceTree = "<group>"; };
D5D3C2567FBF8DBA4DE957B3 /* DiagnosticExporter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticExporter.swift; sourceTree = "<group>"; };
+ D946A13468984E6DEBC20B9A /* ACPConfiguration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ACPConfiguration.swift; sourceTree = "<group>"; };
E684304D1723CA691F40335B /* RemoteServersSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteServersSettingsView.swift; sourceTree = "<group>"; };
E6A5B26D335C1AFB6CDE8207 /* SkillScanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SkillScanner.swift; sourceTree = "<group>"; };
F02A00F80E4712872205EA7B /* NewSkillSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewSkillSheet.swift; sourceTree = "<group>"; };
@@ -100,6 +135,9 @@
331F55021A7E6C9F0B666514 /* Sparkle in Frameworks */,
791AA125E9170DBA81BCBE62 /* Highlightr in Frameworks */,
801A39D725B59A2F2BAF5DF2 /* cmark in Frameworks */,
+ 87AEE95EAD9793D3241D4387 /* ACP in Frameworks */,
+ 0DC3536F86CAA3C4680958AF /* ACPModel in Frameworks */,
+ F3F5B40B2B8F6C684313097D /* ACPRegistry in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -141,16 +179,34 @@
1B016A7C37052B1801FCFD6A /* Shared */ = {
isa = PBXGroup;
children = (
+ 5F236C158C893B626A51E385 /* ACPLogViewer.swift */,
+ 5CAA9B98C7A69F32C6950710 /* ComposeModel.swift */,
+ 937F83BF3496CB231C535608 /* ComposePanel.swift */,
+ B955C8B935BD62ED4811FCA2 /* DiffReviewPanel.swift */,
+ 947EAED7376B7762A373EF08 /* MarkdownMessageView.swift */,
F02A00F80E4712872205EA7B /* NewSkillSheet.swift */,
7FCD6C2A8BE68F553A9CA392 /* RegistrySheet.swift */,
+ 2D07C2CD05E172DB71F63033 /* ThinkingView.swift */,
A7B6AE242CAD6A285DD57079 /* ToolBadge.swift */,
);
path = Shared;
sourceTree = "<group>";
};
+ 3B8985D8816557B264BF0AD8 /* ACP */ = {
+ isa = PBXGroup;
+ children = (
+ 9BBC9E32924CF525F1C96BAE /* ACPAgentFactory.swift */,
+ 8DAD83C176F3A71A5B360BFD /* ACPClient.swift */,
+ 511C5A2149EFF77BDA7D4692 /* ACPLogger.swift */,
+ 89F9D9F176DFDB3FDF02DEFC /* Agents */,
+ );
+ path = ACP;
+ sourceTree = "<group>";
+ };
40FF74A5B2D0A1E16B14B7A4 /* Settings */ = {
isa = PBXGroup;
children = (
+ 9C052B94D025127C9823E7BC /* ACPSettingsView.swift */,
D5D3C2567FBF8DBA4DE957B3 /* DiagnosticExporter.swift */,
E684304D1723CA691F40335B /* RemoteServersSettingsView.swift */,
A924245DDDA4C6A59BE15567 /* SettingsView.swift */,
@@ -189,6 +245,8 @@
9FC9D3E83D8640CC258CF361 /* SkillRegistry.swift */,
E6A5B26D335C1AFB6CDE8207 /* SkillScanner.swift */,
6797D4AC1970DB9ACB5ACA73 /* SSHService.swift */,
+ 12C5CD1627D4EFF58AEF4F71 /* TemplateManager.swift */,
+ 3B8985D8816557B264BF0AD8 /* ACP */,
);
path = Services;
sourceTree = "<group>";
@@ -196,16 +254,27 @@
75334DE5CD1545A8E1E63699 /* Models */ = {
isa = PBXGroup;
children = (
+ D946A13468984E6DEBC20B9A /* ACPConfiguration.swift */,
907E59B064AB8366B60BF611 /* AgentTarget.swift */,
C9AFE1AF02B0F8057791C2A9 /* Collection.swift */,
3314080A44DEB895223E36D5 /* RemoteServer.swift */,
B1F8AA042D5D8A9F92F35CA3 /* SchemaVersions.swift */,
27D6ED655F951177D2152351 /* Skill.swift */,
5487D9027B97F7E9EE9A1F4A /* ToolSource.swift */,
+ 181FD0056E54DEB3957FB4DC /* WizardTemplate.swift */,
);
path = Models;
sourceTree = "<group>";
};
+ 89F9D9F176DFDB3FDF02DEFC /* Agents */ = {
+ isa = PBXGroup;
+ children = (
+ 5E201054F47FC1E66D6E0BE2 /* ClaudeACPAgent.swift */,
+ 07899C351E63B32277272A59 /* CursorACPAgent.swift */,
+ );
+ path = Agents;
+ sourceTree = "<group>";
+ };
95530102A99D9A389717E414 /* Sidebar */ = {
isa = PBXGroup;
children = (
@@ -227,6 +296,7 @@
31B4DB87833D5160A11E39C9 /* SkillEditorView.swift */,
8C812515FD8DC222B89745F2 /* SkillMetadataBar.swift */,
77E332B9970E6E3D00DCFBA3 /* SkillPreviewView.swift */,
+ 6E792EE2E83B2068F8C5305F /* TemplateDetailView.swift */,
);
path = Detail;
sourceTree = "<group>";
@@ -267,6 +337,9 @@
4338FC540625A275BBC9AAC9 /* Sparkle */,
704A14702546BFBD29BE27A8 /* Highlightr */,
9F4BE66CFE1E8401894FEF1F /* cmark */,
+ F642568B19B420E64E62307D /* ACP */,
+ 86292938A0949F325E358FA5 /* ACPModel */,
+ 642A52CB994BF3466A09E6A6 /* ACPRegistry */,
);
productName = Chops;
productReference = B3F5CF5BB1FC8455FDDB004A /* Chops.app */;
@@ -293,6 +366,7 @@
mainGroup = 08ECEAD013847D8F110E61B4;
minimizedProjectReferenceProxies = 1;
packageReferences = (
+ EFEB40047FCA0FF6CF09B7EC /* XCRemoteSwiftPackageReference "swift-acp" */,
7FA62842E4E9A8FD27AE24AF /* XCRemoteSwiftPackageReference "Highlightr" */,
FD1D69AB767CC40E2CE9FED9 /* XCRemoteSwiftPackageReference "Sparkle" */,
05A6F59368DE6489DCD607F1 /* XCRemoteSwiftPackageReference "cmark-gfm" */,
@@ -324,19 +398,31 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
+ 590A98554CAF058BC006CC53 /* ACPAgentFactory.swift in Sources */,
+ 3BF88469DCE0B56DD15DDB09 /* ACPClient.swift in Sources */,
+ E15FE0630C11B3D0BC4C25ED /* ACPConfiguration.swift in Sources */,
+ 1BBEBC85C24BBC4E08AA1821 /* ACPLogViewer.swift in Sources */,
+ 72F7688C0EDA2DAF80C6512B /* ACPLogger.swift in Sources */,
+ F482F0222F6C14110B01D47F /* ACPSettingsView.swift in Sources */,
FD8D2544AE423F4AB2843C0F /* AgentTarget.swift in Sources */,
A99BA179E0520DCDC98E1382 /* AppLogger.swift in Sources */,
25A4FB387DB5BD96DB630C14 /* AppState.swift in Sources */,
309B12E0B72A22C9772BBC99 /* ChopsApp.swift in Sources */,
91EA572FCA75A2EA848C3429 /* ChopsTextView.swift in Sources */,
+ 62C6C8687D8A1E3C1EBBBC8C /* ClaudeACPAgent.swift in Sources */,
7A17C99C5EFAE3AA9E788D50 /* Collection.swift in Sources */,
7EC6156934D559226BC78859 /* CollectionListView.swift in Sources */,
+ E46A2BA5FA20531A06AFB418 /* ComposeModel.swift in Sources */,
+ 74045816B0CF10369DB51ADD /* ComposePanel.swift in Sources */,
D4C107BE303FC07CAF9C66AF /* ContentView.swift in Sources */,
+ C983C685C6296C2EF73CE57D /* CursorACPAgent.swift in Sources */,
AFDC3DAB708B352A7606F119 /* DiagnosticExporter.swift in Sources */,
+ 6E02BA7498763274DD403CD0 /* DiffReviewPanel.swift in Sources */,
B4526ECE136AC044CD3C7603 /* EditorTheme.swift in Sources */,
99EE8F6124FE91AC9576D6FD /* FileWatcher.swift in Sources */,
CBD8FECF1C5A453C8B021665 /* FrontmatterParser.swift in Sources */,
7FD1DE6640F9339D5E97E09A /* MDCParser.swift in Sources */,
+ 322C22C23073C29FC0C6098D /* MarkdownMessageView.swift in Sources */,
E7ED248D6F94C1B1DEF1E8BA /* MarkdownRenderer.swift in Sources */,
BFF9964529E6C48F4F7BCB97 /* MarkdownSyntaxHighlighter.swift in Sources */,
71E92A838AB4D1D6DC6174AF /* NewSkillSheet.swift in Sources */,
@@ -357,9 +443,13 @@
E6F4E1CF50F2F78F5BA9BAC9 /* SkillPreviewView.swift in Sources */,
846B58F3B105D1734DC6FA75 /* SkillRegistry.swift in Sources */,
6A8E0927D95BB14C9F377F4E /* SkillScanner.swift in Sources */,
+ 08B4E2A065E192F17F2568B6 /* TemplateDetailView.swift in Sources */,
+ 3F0ED402E77D8D25C600BAED /* TemplateManager.swift in Sources */,
+ 038F5975DA97A3211EF4D448 /* ThinkingView.swift in Sources */,
53C393C13E30EC439317509F /* ToolBadge.swift in Sources */,
C30BEAE03E54BD36F257A925 /* ToolFilterView.swift in Sources */,
BD584933CCE2B650345C4CF1 /* ToolSource.swift in Sources */,
+ F16A5D53C17EB72817E1282F /* WizardTemplate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -650,6 +740,14 @@
minimumVersion = 2.2.1;
};
};
+ EFEB40047FCA0FF6CF09B7EC /* XCRemoteSwiftPackageReference "swift-acp" */ = {
+ isa = XCRemoteSwiftPackageReference;
+ repositoryURL = "https://github.com/wiedymi/swift-acp";
+ requirement = {
+ branch = main;
+ kind = branch;
+ };
+ };
FD1D69AB767CC40E2CE9FED9 /* XCRemoteSwiftPackageReference "Sparkle" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/sparkle-project/Sparkle";
@@ -666,16 +764,31 @@
package = FD1D69AB767CC40E2CE9FED9 /* XCRemoteSwiftPackageReference "Sparkle" */;
productName = Sparkle;
};
+ 642A52CB994BF3466A09E6A6 /* ACPRegistry */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = EFEB40047FCA0FF6CF09B7EC /* XCRemoteSwiftPackageReference "swift-acp" */;
+ productName = ACPRegistry;
+ };
704A14702546BFBD29BE27A8 /* Highlightr */ = {
isa = XCSwiftPackageProductDependency;
package = 7FA62842E4E9A8FD27AE24AF /* XCRemoteSwiftPackageReference "Highlightr" */;
productName = Highlightr;
};
+ 86292938A0949F325E358FA5 /* ACPModel */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = EFEB40047FCA0FF6CF09B7EC /* XCRemoteSwiftPackageReference "swift-acp" */;
+ productName = ACPModel;
+ };
9F4BE66CFE1E8401894FEF1F /* cmark */ = {
isa = XCSwiftPackageProductDependency;
package = 05A6F59368DE6489DCD607F1 /* XCRemoteSwiftPackageReference "cmark-gfm" */;
productName = cmark;
};
+ F642568B19B420E64E62307D /* ACP */ = {
+ isa = XCSwiftPackageProductDependency;
+ package = EFEB40047FCA0FF6CF09B7EC /* XCRemoteSwiftPackageReference "swift-acp" */;
+ productName = ACP;
+ };
/* End XCSwiftPackageProductDependency section */
};
rootObject = 0BF6016099FDE9BFD3432654 /* Project object */;
diff --git a/Chops.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Chops.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
index 5e4a5a4..e56d94b 100644
--- a/Chops.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
+++ b/Chops.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved
@@ -1,5 +1,5 @@
{
- "originHash" : "cced8d2c7e8017967b1fbc19bce1489634e299f796e5c0826981d26ef3f07509",
+ "originHash" : "e0ac615d8e4bebcfc18f6c3a73bc868431f4021df8a008148a52f6b4be44d7d4",
"pins" : [
{
"identity" : "cmark-gfm",
@@ -27,6 +27,15 @@
"revision" : "21d8df80440b1ca3b65fa82e40782f1e5a9e6ba2",
"version" : "2.9.0"
}
+ },
+ {
+ "identity" : "swift-acp",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/wiedymi/swift-acp",
+ "state" : {
+ "branch" : "main",
+ "revision" : "c22dc706b8b985f7d140f245ba5de36a7a2a7493"
+ }
}
],
"version" : 3
diff --git a/Chops/App/AppState.swift b/Chops/App/AppState.swift
index 855753d..e1164f9 100644
--- a/Chops/App/AppState.swift
+++ b/Chops/App/AppState.swift
@@ -18,4 +18,5 @@ enum SidebarFilter: Hashable {
case tool(ToolSource)
case collection(String)
case server(String)
+ case wizardTemplate(WizardTemplateType)
}
diff --git a/Chops/App/ChopsApp.swift b/Chops/App/ChopsApp.swift
index 61dcc31..3cad963 100644
--- a/Chops/App/ChopsApp.swift
+++ b/Chops/App/ChopsApp.swift
@@ -5,6 +5,7 @@ import Sparkle
@main
struct ChopsApp: App {
@State private var appState = AppState()
+ @AppStorage("ACPDebugLogging") private var debugLoggingEnabled = false
private let updaterController: SPUStandardUpdaterController
init() {
@@ -45,6 +46,8 @@ struct ChopsApp: App {
CheckForUpdatesView(updater: updaterController.updater)
}
CommandGroup(after: .help) {
+ Toggle("Enable Debug Logging", isOn: $debugLoggingEnabled)
+ Divider()
Button("Export Diagnostic Log…") {
let context = sharedModelContainer.mainContext
DiagnosticExporter.export(modelContext: context)
diff --git a/Chops/App/ContentView.swift b/Chops/App/ContentView.swift
index 1026760..b526380 100644
--- a/Chops/App/ContentView.swift
+++ b/Chops/App/ContentView.swift
@@ -17,26 +17,19 @@ struct ContentView: View {
} content: {
SkillListView()
} detail: {
- if let skill = appState.selectedSkill {
+ if case .wizardTemplate(let templateType) = appState.sidebarFilter {
+ TemplateDetailView(templateType: templateType)
+ } else if let skill = appState.selectedSkill {
SkillDetailView(skill: skill)
} else {
- switch appState.sidebarFilter {
- case .allAgents:
- ContentUnavailableView(
- "Select an Agent",
- systemImage: "person.crop.rectangle",
- description: Text("Choose an agent from the sidebar to view and edit it.")
- )
- default:
- ContentUnavailableView(
- "Select a Skill",
- systemImage: "doc.text",
- description: Text("Choose a skill from the sidebar to view and edit it.")
- )
- }
+ ContentUnavailableView(
+ "Select a Skill",
+ systemImage: "doc.text",
+ description: Text("Choose a skill from the sidebar to view and edit it.")
+ )
}
}
- .searchable(text: $appState.searchText, prompt: appState.sidebarFilter == .allAgents ? "Search agents..." : "Search skills...")
+ .searchable(text: $appState.searchText, prompt: "Search skills...")
.onAppear {
startScanning()
}
@@ -55,12 +48,6 @@ struct ContentView: View {
} label: {
Label("New Skill", systemImage: "doc.text")
}
- Button {
- appState.newItemKind = .agent
- appState.showingNewSkillSheet = true
- } label: {
- Label("New Agent", systemImage: "person.crop.rectangle")
- }
Divider()
Button {
appState.showingRegistrySheet = true
diff --git a/Chops/Models/ACPConfiguration.swift b/Chops/Models/ACPConfiguration.swift
new file mode 100644
index 0000000..8a655aa
--- /dev/null
+++ b/Chops/Models/ACPConfiguration.swift
@@ -0,0 +1,95 @@
+import Foundation
+import ACPRegistry
+
+// MARK: - ACP Configuration Manager
+
+/// Manages registry-based ACP agent discovery, selection, and installation.
+@Observable
+@MainActor
+final class ACPConfiguration {
+ static let shared = ACPConfiguration()
+
+ private static let enabledIdsKey = "acpEnabledAgentIds"
+
+ /// Allowlist of registry agent IDs surfaced in the UI.
+ /// Extend this set to support additional agents.
+ static let supportedAgentIds: Set<String> = [
+ "claude-acp",
+ "auggie",
+ "codex-acp",
+ "cursor"
+ ]
+
+ private let registryClient = RegistryClient()
+ private let installer = AgentInstaller()
+
+ // MARK: - Observable State
+
+ /// Registry agents filtered to `supportedAgentIds`, in allowlist order.
+ private(set) var registryAgents: [RegistryAgent] = []
+ private(set) var isLoadingRegistry = false
+ private(set) var registryError: String?
+
+ private var enabledIds: Set<String> {
+ didSet {
+ UserDefaults.standard.set(Array(enabledIds), forKey: Self.enabledIdsKey)
+ }
+ }
+
+ // MARK: - Derived
+
+ var enabledAgents: [RegistryAgent] {
+ registryAgents.filter { enabledIds.contains($0.id) }
+ }
+
+ var hasEnabledACP: Bool { !enabledAgents.isEmpty }
+
+ // MARK: - Init
+
+ private init() {
+ let stored = UserDefaults.standard.stringArray(forKey: Self.enabledIdsKey) ?? []
+ enabledIds = Set(stored)
+ }
+
+ // MARK: - Enable / Disable
+
+ func isEnabled(_ agentId: String) -> Bool { enabledIds.contains(agentId) }
+
+ func setEnabled(_ agentId: String, _ on: Bool) {
+ if on { enabledIds.insert(agentId) } else { enabledIds.remove(agentId) }
+ }
+
+ // MARK: - Registry
+
+ func loadRegistryIfNeeded() async {
+ guard registryAgents.isEmpty, !isLoadingRegistry else { return }
+ await refreshRegistry()
+ }
+
+ func refreshRegistry() async {
+ isLoadingRegistry = true
+ registryError = nil
+ do {
+ let registry = try await registryClient.fetch(forceRefresh: true)
+ let allowed = Self.supportedAgentIds
+ let order: [String] = ["claude-acp", "auggie", "codex-acp", "cursor"]
+ registryAgents = order.compactMap { id in
+ registry.agents.first { $0.id == id && allowed.contains($0.id) }
+ }
+ } catch {
+ registryError = error.localizedDescription
+ }
+ isLoadingRegistry = false
+ }
+
+ // MARK: - Resolve
+
+ /// Returns a ready-to-launch `InstalledAgent` for the given registry agent.
+ /// For npx/uvx agents this is instant; for binary agents it downloads on first use.
+ func resolve(_ agent: RegistryAgent) async throws -> InstalledAgent {
+ if let existing = await installer.installedAgent(agent.id) {
+ return existing
+ }
+ return try await installer.install(agent)
+ }
+}
diff --git a/Chops/Models/ToolSource.swift b/Chops/Models/ToolSource.swift
index d20deab..31171c9 100644
--- a/Chops/Models/ToolSource.swift
+++ b/Chops/Models/ToolSource.swift
@@ -2,6 +2,7 @@ import SwiftUI
enum ToolSource: String, Codable, CaseIterable, Identifiable {
case agents
+ case augment
case claude
case cursor
case windsurf
@@ -18,8 +19,19 @@ enum ToolSource: String, Codable, CaseIterable, Identifiable {
var id: String { rawValue }
+ /// Whether this tool should appear in the sidebar tools list.
+ var listable: Bool {
+ switch self {
+ case .custom, .openclaw, .claudeDesktop, .agents, .aider:
+ return false
+ default:
+ return true
+ }
+ }
+
var displayName: String {
switch self {
+ case .augment: "Auggie"
case .claude: "Claude Code"
case .cursor: "Cursor"
case .windsurf: "Windsurf"
@@ -40,6 +52,7 @@ enum ToolSource: String, Codable, CaseIterable, Identifiable {
/// SF Symbol fallback icon name
var iconName: String {
switch self {
+ case .augment: "wand.and.sparkles"
case .claude: "brain.head.profile"
case .cursor: "cursorarrow.rays"
case .windsurf: "wind"
@@ -60,6 +73,7 @@ enum ToolSource: String, Codable, CaseIterable, Identifiable {
/// Asset catalog image name, nil if no custom logo
var logoAssetName: String? {
switch self {
+ case .augment: "tool-augment"
case .claude: "tool-claude"
case .cursor: "tool-cursor"
case .codex: "tool-codex"
@@ -75,6 +89,7 @@ enum ToolSource: String, Codable, CaseIterable, Identifiable {
var color: Color {
switch self {
+ case .augment: .cyan
case .claude: .orange
case .cursor: .blue
case .windsurf: .teal
@@ -111,6 +126,7 @@ enum ToolSource: String, Codable, CaseIterable, Identifiable {
return "\(home)/.config"
}()
switch self {
+ case .augment: return ["\(home)/.augment/skills"]
case .claude: return ["\(home)/.claude/skills"]
case .cursor: return ["\(home)/.cursor/skills", "\(home)/.cursor/rules"]
case .windsurf: return ["\(home)/.codeium/windsurf/memories", "\(home)/.windsurf/rules"]
@@ -141,34 +157,41 @@ enum ToolSource: String, Codable, CaseIterable, Identifiable {
|| fm.fileExists(atPath: "\(home)/.claude/CLAUDE.md")
|| fm.fileExists(atPath: "\(home)/.claude/plugins/installed_plugins.json")
|| Self.cliBinaryExists("claude")
+ || globalPaths.contains { fm.fileExists(atPath: $0) }
case .cursor:
return fm.fileExists(atPath: "/Applications/Cursor.app")
|| fm.fileExists(atPath: "\(home)/.cursor/argv.json")
+ || globalPaths.contains { fm.fileExists(atPath: $0) }
case .windsurf:
return fm.fileExists(atPath: "/Applications/Windsurf.app")
|| fm.fileExists(atPath: "\(home)/.codeium/windsurf/argv.json")
+ || globalPaths.contains { fm.fileExists(atPath: $0) }
case .codex:
return fm.fileExists(atPath: "\(home)/.codex/config.toml")
|| fm.fileExists(atPath: "\(home)/.codex/auth.json")
|| Self.cliBinaryExists("codex")
+ || globalPaths.contains { fm.fileExists(atPath: $0) }
case .amp:
let configHome = ProcessInfo.processInfo.environment["XDG_CONFIG_HOME"]
.flatMap { $0.isEmpty ? nil : $0 } ?? "\(home)/.config"
return fm.fileExists(atPath: "\(configHome)/amp/config.json")
|| fm.fileExists(atPath: "\(configHome)/amp/settings.json")
|| Self.cliBinaryExists("amp")
+ || globalPaths.contains { fm.fileExists(atPath: $0) }
case .pi:
return Self.cliBinaryExists("pi")
+ || globalPaths.contains { fm.fileExists(atPath: $0) }
case .copilot:
return fm.fileExists(atPath: "\(home)/.copilot")
|| Self.cliBinaryExists("copilot")
+ || globalPaths.contains { fm.fileExists(atPath: $0) }
case .agents:
return fm.fileExists(atPath: "\(home)/.agents/skills")
case .antigravity:
return Self.appBundleExists("Antigravity")
- || fm.fileExists(atPath: "\(home)/.gemini/antigravity/skills")
|| fm.fileExists(atPath: "\(home)/.antigravity")
|| Self.cliBinaryExists("antigravity")
+ || globalPaths.contains { fm.fileExists(atPath: $0) }
case .opencode:
let configHome = ProcessInfo.processInfo.environment["XDG_CONFIG_HOME"]
.flatMap { $0.isEmpty ? nil : $0 } ?? "\(home)/.config"
@@ -177,6 +200,11 @@ enum ToolSource: String, Codable, CaseIterable, Identifiable {
|| fm.fileExists(atPath: "\(configHome)/opencode/opencode.jsonc")
|| fm.fileExists(atPath: "\(home)/.local/share/opencode")
|| Self.cliBinaryExists("opencode")
+ || globalPaths.contains { fm.fileExists(atPath: $0) }
+ case .augment:
+ return fm.fileExists(atPath: "\(home)/.augment")
+ || Self.cliBinaryExists("augment")
+ || globalPaths.contains { fm.fileExists(atPath: $0) }
case .claudeDesktop:
return Self.appBundleExists("Claude")
case .aider, .openclaw, .custom:
diff --git a/Chops/Models/WizardTemplate.swift b/Chops/Models/WizardTemplate.swift
new file mode 100644
index 0000000..a49c667
--- /dev/null
+++ b/Chops/Models/WizardTemplate.swift
@@ -0,0 +1,39 @@
+import Foundation
+
+// MARK: - Wizard Template Type
+
+/// Types of wizard templates for AI-assisted composition
+enum WizardTemplateType: String, CaseIterable, Codable, Identifiable {
+ case skill = "skill"
+
+ var id: String { rawValue }
+
+ var displayName: String {
+ "Skill Composer"
+ }
+
+ var fileName: String {
+ "\(rawValue)-composer.md"
+ }
+
+ var icon: String {
+ "doc.text.fill"
+ }
+}
+
+// MARK: - Wizard Template
+
+/// A wizard template with content and metadata
+struct WizardTemplate: Identifiable, Equatable {
+ var id: String { type.rawValue }
+ let type: WizardTemplateType
+ var content: String
+ var lastModified: Date
+
+ /// Render template with placeholders replaced
+ func render(fileContent: String, userInstructions: String) -> String {
+ content
+ .replacingOccurrences(of: "{{file_content}}", with: fileContent)
+ .replacingOccurrences(of: "{{user_instructions}}", with: userInstructions)
+ }
+}
diff --git a/Chops/Resources/Assets.xcassets/tool-augment.imageset/Contents.json b/Chops/Resources/Assets.xcassets/tool-augment.imageset/Contents.json
new file mode 100644
index 0000000..69c1978
--- /dev/null
+++ b/Chops/Resources/Assets.xcassets/tool-augment.imageset/Contents.json
@@ -0,0 +1,16 @@
+{
+ "images" : [
+ {
+ "filename" : "logo.svg",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "preserves-vector-representation" : true,
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/Chops/Resources/Assets.xcassets/tool-augment.imageset/logo.svg b/Chops/Resources/Assets.xcassets/tool-augment.imageset/logo.svg
new file mode 100644
index 0000000..4275659
--- /dev/null
+++ b/Chops/Resources/Assets.xcassets/tool-augment.imageset/logo.svg
@@ -0,0 +1 @@
+<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Augment</title><path d="M7.5 4C6.12 4 5 5.12 5 6.5v3.25c0 .97-.79 1.75-1.75 1.75a.75.75 0 000 1.5c.97 0 1.75.78 1.75 1.75v3.25c0 1.38 1.12 2.5 2.5 2.5h1a.75.75 0 000-1.5h-1a1 1 0 01-1-1v-3.25a3.24 3.24 0 00-1.17-2.5 3.24 3.24 0 001.17-2.5V6.5a1 1 0 011-1h1a.75.75 0 000-1.5h-1zm9 0a.75.75 0 000 1.5h1a1 1 0 011 1v3.25c0 .97.53 1.82 1.17 2.5a3.24 3.24 0 00-1.17 2.5v3.25a1 1 0 01-1 1h-1a.75.75 0 000 1.5h1c1.38 0 2.5-1.12 2.5-2.5v-3.25c0-.97.78-1.75 1.75-1.75a.75.75 0 000-1.5 1.75 1.75 0 01-1.75-1.75V6.5c0-1.38-1.12-2.5-2.5-2.5h-1zm-6.25 7a1.25 1.25 0 100 2.5 1.25 1.25 0 000-2.5zm3.5 0a1.25 1.25 0 100 2.5 1.25 1.25 0 000-2.5z"/></svg>
diff --git a/Chops/Services/ACP/ACPAgentFactory.swift b/Chops/Services/ACP/ACPAgentFactory.swift
new file mode 100644
index 0000000..0599942
--- /dev/null
+++ b/Chops/Services/ACP/ACPAgentFactory.swift
@@ -0,0 +1,15 @@
+import Foundation
+
+/// Returns the vendor-specific agent for a given registry agent ID.
+/// Maps known agent IDs to their subclass; unknown agents use the base class.
+@MainActor
+enum ACPAgentFactory {
+ static func make(for agentId: String) -> BaseACPAgent {
+ switch agentId {
+ case "claude-acp": return ClaudeACPAgent()
+ case "cursor": return CursorACPAgent()
+ case "auggie": return BaseACPAgent()
+ default: return BaseACPAgent()
+ }
+ }
+}
diff --git a/Chops/Services/ACP/ACPClient.swift b/Chops/Services/ACP/ACPClient.swift
new file mode 100644
index 0000000..06314eb
--- /dev/null
+++ b/Chops/Services/ACP/ACPClient.swift
@@ -0,0 +1,372 @@
+import ACP
+import ACPModel
+import ACPRegistry
+import Foundation
+
+// MARK: - Permission Request
+
+struct PermissionRequest: Identifiable, @unchecked Sendable {
+ let id: UUID = UUID()
+ let title: String
+ let options: [PermissionOption]
+ let continuation: CheckedContinuation<RequestPermissionResponse, Error>
+}
+
+/// 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.
+@Observable
+@MainActor
+open class BaseACPAgent: ClientDelegate {
+
+ // MARK: - Observable State
+
+ var responseText: String = ""
+ var thoughtText: String = ""
+ var currentActivity: String?
+ var pendingWrites: [(path: String, content: String, original: String?)] = []
+ private(set) var sessionConfigOptions: [SessionConfigOption] = []
+ private(set) var pendingPermissionRequest: PermissionRequest?
+ private(set) var isConnected: Bool = false
+ private(set) var isConnecting: Bool = false
+ private(set) var isProcessing: Bool = false
+ private(set) var lastError: String?
+ private(set) var currentAgentId: String?
+
+ // MARK: - Private Handles
+
+ private var acpClient: ACP.Client?
+ private var sessionId: SessionId?
+ private var connectTask: Task<Void, Never>?
+ private var notificationTask: Task<Void, Never>?
+ private var pendingSystemPrompt: String?
+
+ // MARK: - Connect / Disconnect
+
+ /// Starts connecting non-blocking. Observe isConnecting / isConnected / lastError for state.
+ func startConnect(agent: RegistryAgent, workingDirectory: URL, systemPrompt: String?) {
+ connectTask?.cancel()
+ lastError = nil
+ connectTask = Task {
+ defer { connectTask = nil }
+ do {
+ try await connect(agent: agent, workingDirectory: workingDirectory, systemPrompt: systemPrompt)
+ } catch is CancellationError {
+ // user-initiated — no error shown
+ } catch {
+ acpLog.error("Connection failed: \(error.localizedDescription)")
+ lastError = error.localizedDescription
+ }
+ }
+ }
+
+ private func connect(agent: RegistryAgent, workingDirectory: URL, systemPrompt: String?) async throws {
+ guard ACPConfiguration.shared.isEnabled(agent.id) else {
+ throw ACPClientError.agentNotConfigured(agent.id)
+ }
+ currentAgentId = agent.id
+ acpLog.debug("Resolving agent: \(agent.id) v\(agent.version)")
+ let installed = try await ACPConfiguration.shared.resolve(agent)
+ acpLog.debug("Resolved: \(installed.executablePath) args=[\(installed.arguments.joined(separator: " "))]")
+ try await attemptConnect(installed: installed, workingDirectory: workingDirectory, systemPrompt: systemPrompt)
+ }
+
+ private func attemptConnect(installed: InstalledAgent, workingDirectory: URL, systemPrompt: String?) async throws {
+ pendingSystemPrompt = systemPrompt
+ isConnecting = true
+ defer { isConnecting = false }
+
+ let arguments = installed.arguments + additionalFlags()
+ let environment = installed.environment.isEmpty ? nil : installed.environment
+
+ let execPath = await resolveExecutable(installed.executablePath)
+ acpLog.debug("launch: \(execPath) | args: \(arguments.joined(separator: " "))")
+
+ let client = ACP.Client()
+ await client.setDelegate(self)
+
+ // SDK's ProcessManager loads the full login-shell environment internally.
+ // Custom env from the registry (e.g. API keys) is merged on top by the SDK.
+ try await client.launch(
+ agentPath: execPath,
+ arguments: arguments,
+ workingDirectory: workingDirectory.path,
+ environment: environment
+ )
+ guard !Task.isCancelled else { await client.terminate(); return }
+
+ let initResp = try await client.initialize(
+ capabilities: ClientCapabilities(
+ fs: FileSystemCapabilities(readTextFile: true, writeTextFile: true),
+ terminal: false
+ ),
+ clientInfo: ClientInfo(name: "Chops", version: "1.0")
+ )
+ guard !Task.isCancelled else { await client.terminate(); return }
+ acpLog.debug("Connected: \(initResp.agentInfo?.name ?? "?") (protocol v\(initResp.protocolVersion))")
+
+ let cwd = sessionCwd(for: workingDirectory)
+ let sessionResp = try await client.newSession(workingDirectory: cwd.path)
+ guard !Task.isCancelled else { await client.terminate(); return }
+ sessionId = sessionResp.sessionId
+ sessionConfigOptions = sessionResp.configOptions ?? []
+ acpLog.debug("Session created: \(sessionResp.sessionId) (\(sessionConfigOptions.count) config options)")
+
+ acpClient = client
+ isConnected = true
+ startNotificationMonitor(client: client)
+ }
+
+ func disconnect() async {
+ connectTask?.cancel()
+ connectTask = nil
+ notificationTask?.cancel()
+ notificationTask = nil
+ let client = acpClient
+ acpClient = nil
+ sessionId = nil
+ isConnected = false
+ currentAgentId = nil
+ lastError = nil
+ sessionConfigOptions = []
+ pendingSystemPrompt = nil
+ await client?.terminate()
+ acpLog.debug("Disconnected")
+ }
+
+ // MARK: - Notification Monitor
+
+ private func startNotificationMonitor(client: ACP.Client) {
+ notificationTask?.cancel()
+ notificationTask = Task.detached { [weak self] in
+ let stream = await client.notifications
+ for await notification in stream {
+ guard !Task.isCancelled else { break }
+ guard notification.method == "session/update" else { continue }
+ await self?.handleRawNotification(notification)
+ }
+ // Stream ended — agent process likely exited
+ await self?.onAgentDisconnected()
+ }
+ }
+
+ private func onAgentDisconnected() {
+ if isConnected {
+ isConnected = false
+ acpLog.debug("Agent process ended")
+ }
+ }
+
+ private func handleRawNotification(_ notification: JSONRPCNotification) {
+ guard let params = notification.params else { return }
+ do {
+ let data = try JSONEncoder().encode(params)
+ struct SessionUpdateParams: Codable {
+ let sessionId: String
+ let update: SessionUpdate
+ }
+ let decoded = try JSONDecoder().decode(SessionUpdateParams.self, from: data)
+ handleUpdate(decoded.update)
+ } catch {
+ acpLog.debug("Failed to decode session update: \(error)")
+ }
+ }
+
+ // MARK: - Session
+
+ func setConfigOption(id: SessionConfigId, value: SessionConfigValueId) async throws {
+ guard let client = acpClient, let sid = sessionId else { return }
+ let resp = try await client.setConfigOption(sessionId: sid, configId: id, value: value)
+ sessionConfigOptions = resp.configOptions
+ }
+
+ // MARK: - Prompt
+
+ func prompt(_ text: String) async throws {
+ guard let client = acpClient, let sid = sessionId else { throw ACPClientError.noSession }
+ responseText = ""; thoughtText = ""; pendingWrites = []; currentActivity = nil
+ isProcessing = true
+ defer { isProcessing = false }
+
+ // Prepend system prompt context to the first message of the session.
+ let fullText: String
+ if let sp = pendingSystemPrompt {
+ pendingSystemPrompt = nil
+ fullText = sp.isEmpty ? text : "\(sp)\n\n---\n\n\(text)"
+ } else {
+ fullText = text
+ }
+
+ let resp = try await client.sendPrompt(
+ sessionId: sid,
+ content: [.text(TextContent(text: fullText))]
+ )
+ currentActivity = nil
+ acpLog.debug("Prompt done: \(resp.stopReason)")
+ }
+
+ func clearPendingWrites() { pendingWrites = [] }
+
+ // MARK: - Permission
+
+ func parkPermissionRequest(title: String, options: [PermissionOption]) async throws -> RequestPermissionResponse {
+ try await withCheckedThrowingContinuation { cont in
+ pendingPermissionRequest = PermissionRequest(title: title, options: options, continuation: cont)
+ }
+ }
+
+ func respondToPermission(optionId: String?) {
+ guard let req = pendingPermissionRequest else { return }
+ pendingPermissionRequest = nil
+ if let id = optionId {
+ req.continuation.resume(returning: RequestPermissionResponse(outcome: PermissionOutcome(optionId: id)))
+ } else {
+ req.continuation.resume(returning: RequestPermissionResponse(outcome: PermissionOutcome(cancelled: true)))
+ }
+ }
+
+ // MARK: - ClientDelegate
+
+ public func handleFileReadRequest(_ path: String, sessionId: String, line: Int?, limit: Int?) async throws -> ReadTextFileResponse {
+ acpLog.debug("readTextFile: \(path)")
+ let content = try await Task.detached { try String(contentsOfFile: path, encoding: .utf8) }.value
+ return 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.
+ // 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
+ let alreadyCaptured = pendingWrites.contains {
+ 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))
+ }.value
+ pendingWrites.append((path: path, content: content, original: original))
+ }
+ // 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
+ return WriteTextFileResponse()
+ }
+
+ public func handleTerminalCreate(command: String, sessionId: String, args: [String]?, cwd: String?, env: [EnvVariable]?, outputByteLimit: Int?) async throws -> CreateTerminalResponse {
+ throw ACPClientError.terminalNotSupported
+ }
+
+ public func handleTerminalOutput(terminalId: TerminalId, sessionId: String) async throws -> TerminalOutputResponse {
+ throw ACPClientError.terminalNotSupported
+ }
+
+ public func handleTerminalWaitForExit(terminalId: TerminalId, sessionId: String) async throws -> WaitForExitResponse {
+ throw ACPClientError.terminalNotSupported
+ }
+
+ public func handleTerminalKill(terminalId: TerminalId, sessionId: String) async throws -> KillTerminalResponse {
+ throw ACPClientError.terminalNotSupported
+ }
+
+ public func handleTerminalRelease(terminalId: TerminalId, sessionId: String) async throws -> ReleaseTerminalResponse {
+ throw ACPClientError.terminalNotSupported
+ }
+
+ public func handlePermissionRequest(request: RequestPermissionRequest) async throws -> RequestPermissionResponse {
+ let title = request.message ?? "Permission Required"
+ let options = request.options ?? []
+ acpLog.debug("Permission: \(title)")
+ return try await resolvePermission(title: title, options: options)
+ }
+
+ // MARK: - Session Update Dispatch
+
+ func handleUpdate(_ update: SessionUpdate) {
+ switch update {
+ case .agentMessageChunk(let c): onMessageChunk(c)
+ case .agentThoughtChunk(let c): onThoughtChunk(c)
+ case .toolCall(let t): onToolCall(t)
+ case .toolCallUpdate(let d): onToolCallUpdate(d)
+ case .configOptionUpdate(let u): sessionConfigOptions = u
+ case .sessionInfoUpdate(let i): if let t = i.title { acpLog.debug("Session: \(t)") }
+ default: break
+ }
+ }
+
+ // MARK: - Vendor Hooks (override in subclass)
+
+ func onThoughtChunk(_ content: ContentBlock) {
+ if case .text(let t) = content { currentActivity = String(t.text.prefix(80)) }
+ }
+
+ func onMessageChunk(_ content: ContentBlock) {
+ if case .text(let t) = content { responseText += t.text }
+ }
+
+ func onToolCall(_ update: ToolCallUpdate) {
+ currentActivity = (update.status == .completed || update.status == .failed) ? nil : update.title
+ }
+
+ func onToolCallUpdate(_ update: ToolCallUpdateDetails) {
+ if let status = update.status, status == .completed || status == .failed {
+ currentActivity = nil
+ } else if let title = update.title {
+ currentActivity = title
+ }
+ }
+
+ func additionalFlags() -> [String] { [] }
+ func sessionCwd(for workingDirectory: URL) -> URL { workingDirectory }
+ func postProcess(_ text: String) -> String { text }
+ func conversationalText(from text: String) -> String { postProcess(text) }
+
+ func resolvePermission(title: String, options: [PermissionOption]) async throws -> RequestPermissionResponse {
+ try await parkPermissionRequest(title: title, options: options)
+ }
+
+ // MARK: - Helpers
+
+ /// Resolves a bare executable name (e.g. "npx") to its absolute path via the user's shell PATH.
+ /// Returns the original name unchanged if it is already absolute or not found in PATH.
+ private func resolveExecutable(_ name: String) async -> String {
+ guard !name.hasPrefix("/") else { return name }
+ let env = await ShellEnvironment.loadUserShellEnvironmentAsync()
+ let dirs = (env["PATH"] ?? "").split(separator: ":").map(String.init)
+ for dir in dirs {
+ let full = (dir as NSString).appendingPathComponent(name)
+ if FileManager.default.isExecutableFile(atPath: full) {
+ acpLog.debug("Resolved '\(name)' to \(full)")
+ return full
+ }
+ }
+ acpLog.error("'\(name)' not found in PATH — launch will likely fail")
+ return name
+ }
+}
+
+// MARK: - Errors
+
+/// Chops-specific errors not covered by the SDK's errors.
+enum ACPClientError: Error, LocalizedError {
+ case agentNotConfigured(String)
+ case noSession
+ case terminalNotSupported
+
+ var errorDescription: String? {
+ switch self {
+ case .agentNotConfigured(let id): "Agent '\(id)' not enabled. Go to Settings → ACP."
+ case .noSession: "No active ACP session."
+ case .terminalNotSupported: "Terminal operations are not supported."
+ }
+ }
+}
+
diff --git a/Chops/Services/ACP/ACPLogger.swift b/Chops/Services/ACP/ACPLogger.swift
new file mode 100644
index 0000000..85d23ff
--- /dev/null
+++ b/Chops/Services/ACP/ACPLogger.swift
@@ -0,0 +1,149 @@
+import Foundation
+import os.log
+
+/// Centralized ACP logging with optional debug mode and file storage
+final class ACPLogger: @unchecked Sendable {
+ static let shared = ACPLogger()
+
+ private let osLog = Logger(subsystem: "md.chops", category: "ACP")
+ private let logFileURL: URL
+ private let queue = DispatchQueue(label: "md.chops.acplogger", qos: .utility)
+ private static let isoFormatter = ISO8601DateFormatter()
+ private var fileHandle: FileHandle?
+
+ /// Enable verbose debug logging (send/receive payloads)
+ var debugEnabled: Bool {
+ get { UserDefaults.standard.bool(forKey: "ACPDebugLogging") }
+ set {
+ UserDefaults.standard.set(newValue, forKey: "ACPDebugLogging")
+ if newValue {
+ info("Debug logging enabled")
+ }
+ }
+ }
+
+ private init() {
+ let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
+ let logsDir = appSupport.appendingPathComponent("Chops/Logs", isDirectory: true)
+ try? FileManager.default.createDirectory(at: logsDir, withIntermediateDirectories: true)
+
+ let dateFormatter = DateFormatter()
+ dateFormatter.dateFormat = "yyyy-MM-dd"
+ let filename = "acp-\(dateFormatter.string(from: Date())).log"
+ logFileURL = logsDir.appendingPathComponent(filename)
+
+ if !FileManager.default.fileExists(atPath: logFileURL.path) {
+ FileManager.default.createFile(atPath: logFileURL.path, contents: nil)
+ }
+ fileHandle = try? FileHandle(forWritingTo: logFileURL)
+ fileHandle?.seekToEndOfFile()
+ }
+
+ deinit {
+ try? fileHandle?.close()
+ }
+
+ // MARK: - Public API
+
+ func info(_ message: String) {
+ log(level: .info, message: message)
+ }
+
+ func debug(_ message: String) {
+ guard debugEnabled else { return }
+ log(level: .debug, message: message)
+ }
+
+ func error(_ message: String) {
+ log(level: .error, message: message)
+ }
+
+ enum Direction { case send, receive }
+
+ /// Log a JSON-encodable value in debug mode. Centralises encoding so callers never duplicate it.
+ func debugLogJSON<T: Encodable>(_ value: T, direction: Direction) {
+ guard debugEnabled else { return }
+ guard let data = try? JSONEncoder().encode(value),
+ let str = String(data: data, encoding: .utf8) else { return }
+ switch direction {
+ case .send: log(level: .debug, message: ">>> SEND: \(str)")
+ case .receive: log(level: .debug, message: "<<< RECV: \(str)")
+ }
+ }
+
+ /// Log send payload (only in debug mode)
+ func logSend(_ payload: String) {
+ guard debugEnabled else { return }
+ log(level: .debug, message: ">>> SEND: \(payload)")
+ }
+
+ /// Log receive payload (only in debug mode)
+ func logReceive(_ payload: String) {
+ guard debugEnabled else { return }
+ log(level: .debug, message: "<<< RECV: \(payload)")
+ }
+
+ /// Get the log file URL for viewing
+ var logURL: URL { logFileURL }
+
+ /// Get recent log content — runs on the logger's background queue, never blocks the caller.
+ func recentLogs(lines: Int = 200) async -> String {
+ await withCheckedContinuation { continuation in
+ queue.async { [self] in
+ guard let data = try? Data(contentsOf: logFileURL),
+ let content = String(data: data, encoding: .utf8) else {
+ continuation.resume(returning: "(No logs available)")
+ return
+ }
+ let allLines = content.components(separatedBy: .newlines)
+ let recentLines = allLines.suffix(lines)
+ continuation.resume(returning: recentLines.joined(separator: "\n"))
+ }
+ }
+ }
+
+ /// Clear logs — truncates the file and writes a single marker entry.
+ func clearLogs() {
+ queue.async { [weak self] in
+ guard let self else { return }
+ try? self.fileHandle?.truncate(atOffset: 0)
+ self.fileHandle?.seek(toFileOffset: 0)
+ // Call log() directly on the queue to avoid an extra async hop.
+ let timestamp = Self.isoFormatter.string(from: Date())
+ let line = "[\(timestamp)] [INFO] Logs cleared\n"
+ if let data = line.data(using: .utf8) {
+ self.fileHandle?.write(data)
+ }
+ self.osLog.info("Logs cleared")
+ }
+ }
+
+ // MARK: - Private
+
+ private enum Level: String {
+ case info = "INFO"
+ case debug = "DEBUG"
+ case error = "ERROR"
+ }
+
+ private func log(level: Level, message: String) {
+ let timestamp = Self.isoFormatter.string(from: Date())
+ let line = "[\(timestamp)] [\(level.rawValue)] \(message)\n"
+
+ switch level {
+ case .info: osLog.info("\(message)")
+ case .debug: osLog.debug("\(message)")
+ case .error: osLog.error("\(message)")
+ }
+
+ queue.async { [weak self] in
+ if let data = line.data(using: .utf8) {
+ self?.fileHandle?.write(data)
+ }
+ }
+ }
+}
+
+// MARK: - Global convenience
+
+let acpLog = ACPLogger.shared
diff --git a/Chops/Services/ACP/Agents/ClaudeACPAgent.swift b/Chops/Services/ACP/Agents/ClaudeACPAgent.swift
new file mode 100644
index 0000000..3af175a
--- /dev/null
+++ b/Chops/Services/ACP/Agents/ClaudeACPAgent.swift
@@ -0,0 +1,138 @@
+import Foundation
+import ACPModel
+
+/// ACP agent for Claude Code.
+///
+/// Claude-specific stream classification:
+/// - `agentThoughtChunk` → accumulates into `thoughtText`; shown in collapsible Thinking section.
+/// - `agentMessageChunk` → accumulates raw into `responseText`; tag stripping applied at read time.
+/// - `toolCall` → activity label only; Claude does not embed diffs here.
+/// - `toolCallUpdate` → diffs captured from status-less updates; completed/failed clears activity.
+@Observable
+@MainActor
+final class ClaudeACPAgent: BaseACPAgent {
+
+ // MARK: - Tag Stripping
+
+ /// Claude uses both bare and `antml:` namespaced variants of these tags.
+ private static let tagsToStrip = [
+ "function_calls", "invoke", "parameter", "thinking",
+ "antml:function_calls", "antml:invoke", "antml:parameter"
+ ]
+
+ // MARK: - Content Hooks
+
+ /// Thought chunks are Claude's extended-thinking / reasoning stream.
+ /// Accumulated in full into `thoughtText` for display in a collapsible "Thinking" section.
+ /// `currentActivity` is set to a short label so the activity row shows "Thinking…"
+ /// rather than truncated reasoning mid-sentence.
+ override func onThoughtChunk(_ content: ContentBlock) {
+ currentActivity = "Thinking…"
+ if case .text(let t) = content, !t.text.isEmpty {
+ thoughtText += t.text
+ }
+ }
+
+ /// Message chunks are Claude's conversational reply.
+ /// Accumulated raw into `responseText` — postProcess (tag stripping) is applied at
+ /// read time by `conversationalText()`, not per-chunk, to avoid splitting tags across chunks.
+ override func onMessageChunk(_ content: ContentBlock) {
+ if case .text(let t) = content {
+ responseText += t.text
+ acpLog.debug("onMessageChunk: +\(t.text.count) chars, total=\(responseText.count)")
+ }
+ }
+
+ /// `toolCall` notifications from Claude carry no diff content — update activity label only.
+ override func onToolCall(_ toolCall: ToolCallUpdate) {
+ switch toolCall.status {
+ case .completed, .failed:
+ currentActivity = nil
+ default:
+ currentActivity = toolCall.title
+ }
+ }
+
+ /// `toolCallUpdate` is Claude's primary diff delivery channel.
+ ///
+ /// Claude emits two distinct `tool_call_update` shapes for the `Write` tool:
+ ///
+ /// 1. **Status-less** — carries `content[{type:"diff", path, newText, oldText}]`.
+ /// This is the pre-write preview delivered before the file is touched on disk.
+ /// Diffs are captured here so `oldText` (or a disk read) is reliable.
+ ///
+ /// 2. **Status: completed/failed** — carries `rawOutput` but no diff content.
+ /// Used only to clear the activity label.
+ ///
+ /// `inProgress` updates carry a `title` to display while the tool is running.
+ override func onToolCallUpdate(_ update: ToolCallUpdateDetails) {
+ captureDiffs(from: update.content)
+
+ guard let status = update.status else { return }
+ switch status {
+ case .completed, .failed:
+ currentActivity = nil
+ logToolResultContent(update.content)
+ case .inProgress:
+ if let title = update.title { currentActivity = title }
+ default:
+ break
+ }
+ }
+
+ // MARK: - Diff Capture
+
+ /// Extracts `ToolCallContent.diff` blocks and appends them to `pendingWrites`.
+ /// Reading `oldText` here is safe — the diff block is delivered before Claude's
+ /// write tool has touched the file on disk.
+ private func captureDiffs(from content: [ToolCallContent]?) {
+ 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))
+ // 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)
+ } else {
+ pendingWrites.append((path: d.path, content: d.newText, original: oldText))
+ }
+ acpLog.info("diff intercepted: \(d.path) original=\(oldText?.count ?? -1) chars (\(pendingWrites.count) total)")
+ }
+ }
+
+ // MARK: - Response Post-Processing
+
+ override func postProcess(_ text: String) -> String {
+ Self.stripXMLTags(text, tags: Self.tagsToStrip)
+ }
+
+ // MARK: - Private Helpers
+
+ private static func stripXMLTags(_ text: String, tags: [String]) -> String {
+ var result = text
+ for tag in tags {
+ for prefix in ["</\(tag)", "<\(tag)"] {
+ var i = result.startIndex
+ while i < result.endIndex,
+ let open = result.range(of: prefix, range: i ..< result.endIndex),
+ let close = result.range(of: ">", range: open.lowerBound ..< result.endIndex) {
+ result.removeSubrange(open.lowerBound ... close.lowerBound)
+ i = open.lowerBound
+ }
+ }
+ }
+ while result.contains("\n\n\n") { result = result.replacingOccurrences(of: "\n\n\n", with: "\n\n") }
+ return result.trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ private func logToolResultContent(_ content: [ToolCallContent]?) {
+ content?.forEach {
+ if case .content(let cc) = $0, case .text(let t) = cc {
+ acpLog.debug("Tool result: \(String(t.text.prefix(200)))")
+ }
+ }
+ }
+}
diff --git a/Chops/Services/ACP/Agents/CursorACPAgent.swift b/Chops/Services/ACP/Agents/CursorACPAgent.swift
new file mode 100644
index 0000000..768fd4f
--- /dev/null
+++ b/Chops/Services/ACP/Agents/CursorACPAgent.swift
@@ -0,0 +1,17 @@
+import Foundation
+import ACPModel
+
+/// ACP agent for Cursor.
+///
+/// Cursor delivers conversational replies via `agentMessageChunk` with no XML wrapping.
+/// Diffs arrive through `handleFileWriteRequest` in the base class.
+@Observable
+@MainActor
+final class CursorACPAgent: BaseACPAgent {
+
+ override func onThoughtChunk(_ content: ContentBlock) {}
+
+ override func postProcess(_ text: String) -> String {
+ return text.trimmingCharacters(in: .newlines)
+ }
+}
diff --git a/Chops/Services/AppLogger.swift b/Chops/Services/AppLogger.swift
index dcf5888..67a6d7e 100644
--- a/Chops/Services/AppLogger.swift
+++ b/Chops/Services/AppLogger.swift
@@ -7,4 +7,5 @@ enum AppLogger {
static let scanning = Logger(subsystem: subsystem, category: "scanning")
static let fileIO = Logger(subsystem: subsystem, category: "fileIO")
static let ui = Logger(subsystem: subsystem, category: "ui")
+ static let settings = Logger(subsystem: subsystem, category: "settings")
}
diff --git a/Chops/Services/SkillParser.swift b/Chops/Services/SkillParser.swift
index fe10a28..90a4a50 100644
--- a/Chops/Services/SkillParser.swift
+++ b/Chops/Services/SkillParser.swift
@@ -12,7 +12,7 @@ enum SkillParser {
return MDCParser.parse(content)
}
return FrontmatterParser.parse(content)
- case .codex, .amp, .windsurf, .copilot, .aider, .openclaw, .opencode, .pi, .agents, .antigravity, .custom:
+ case .codex, .amp, .windsurf, .copilot, .aider, .openclaw, .opencode, .pi, .agents, .augment, .antigravity, .custom:
// Try frontmatter first, fall back to heading
let parsed = FrontmatterParser.parse(content)
if !parsed.name.isEmpty { return parsed }
diff --git a/Chops/Services/SkillScanner.swift b/Chops/Services/SkillScanner.swift
index 42d7a2e..aa194f0 100644
--- a/Chops/Services/SkillScanner.swift
+++ b/Chops/Services/SkillScanner.swift
@@ -163,31 +163,49 @@ final class SkillScanner {
guard isDir.boolValue else { return }
+ // Enumerate through the resolved directory so symlinked directories are traversed.
+ let resolvedDirectory = directory.resolvingSymlinksInPath()
+
guard let contents = try? fm.contentsOfDirectory(
- at: directory,
+ at: resolvedDirectory,
includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey, .contentModificationDateKey, .fileSizeKey],
options: [.skipsHiddenFiles]
) else { return }
- for item in contents {
+ // Track both bases so each entry can be remapped back to the canonical path for storage.
+ let originalBase = directory.path
+ let resolvedBase = resolvedDirectory.path
+
+ for rawItem in contents {
guard !Task.isCancelled else { return }
+ // Remap to canonical path for storage; use rawItem for filesystem operations.
+ let item: URL
+ if originalBase != resolvedBase, rawItem.path.hasPrefix(resolvedBase + "/") {
+ let suffix = String(rawItem.path.dropFirst(resolvedBase.count))
+ item = URL(fileURLWithPath: originalBase + suffix)
+ } else {
+ item = rawItem
+ }
var itemIsDir: ObjCBool = false
- fm.fileExists(atPath: item.path, isDirectory: &itemIsDir)
+ fm.fileExists(atPath: rawItem.path, isDirectory: &itemIsDir)
if itemIsDir.boolValue {
let skillFile = item.appendingPathComponent("SKILL.md")
let agentsFile = item.appendingPathComponent("AGENTS.md")
+ let rawSkillFile = rawItem.appendingPathComponent("SKILL.md")
+ let rawAgentsFile = rawItem.appendingPathComponent("AGENTS.md")
- if fm.fileExists(atPath: skillFile.path) {
+ if fm.fileExists(atPath: rawSkillFile.path) {
if let data = collectSkillData(at: skillFile, toolSource: toolSource, isDirectory: true, isGlobal: isGlobal, kind: kind) {
results.append(data)
}
- } else if fm.fileExists(atPath: agentsFile.path) {
+ } else if fm.fileExists(atPath: rawAgentsFile.path) {
if let data = collectSkillData(at: agentsFile, toolSource: toolSource, isDirectory: true, isGlobal: isGlobal, kind: kind) {
results.append(data)
}
- } else if kind == .agent, let agentFile = preferredAgentFile(in: item) {
- if let data = collectSkillData(at: agentFile, toolSource: toolSource, isDirectory: true, isGlobal: isGlobal, kind: kind) {
+ } else if kind == .agent, let agentFile = preferredAgentFile(in: rawItem) {
+ let remappedAgentFile = item.appendingPathComponent(agentFile.lastPathComponent)
+ if let data = collectSkillData(at: remappedAgentFile, toolSource: toolSource, isDirectory: true, isGlobal: isGlobal, kind: kind) {
results.append(data)
}
}
@@ -276,15 +294,16 @@ final class SkillScanner {
let fm = FileManager.default
let resolved = canonicalResolvedPath(for: fileURL, toolSource: toolSource)
- guard let parsed = SkillParser.parse(fileURL: fileURL, toolSource: toolSource) else {
+ // Resolve symlinks for the actual read — fileURL may be a remapped canonical path
+ // that does not physically exist when a parent directory is a symlink.
+ let physicalURL = fileURL.resolvingSymlinksInPath()
+ guard let parsed = SkillParser.parse(fileURL: physicalURL, toolSource: toolSource) else {
AppLogger.scanning.warning("Failed to parse: \(fileURL.path)")
return nil
}
- // Use the actual filesystem path for attributes (resolved may be a canonical identifier)
- let attrPath = fileURL.resolvingSymlinksInPath().path
- let attrs = try? fm.attributesOfItem(atPath: attrPath)
- let modDate = (attrs?[.modificationDate] as? Date) ?? .now
+ let attrs = try? fm.attributesOfItem(atPath: physicalURL.path)
+ let modDate = (attrs?[.modificationDate] as? Date) ?? .now
let fileSize = (attrs?[.size] as? Int) ?? 0
let name: String
diff --git a/Chops/Services/TemplateManager.swift b/Chops/Services/TemplateManager.swift
new file mode 100644
index 0000000..fa2fb11
--- /dev/null
+++ b/Chops/Services/TemplateManager.swift
@@ -0,0 +1,204 @@
+import Foundation
+
+// MARK: - Template Manager
+
+/// Manages wizard templates for AI-assisted composition
+@Observable
+@MainActor
+final class TemplateManager {
+ static let shared = TemplateManager()
+
+ private(set) var templates: [WizardTemplate] = []
+
+ private let fileManager = FileManager.default
+
+ private var templatesDirectory: URL {
+ let appSupport = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
+ return appSupport.appendingPathComponent("Chops/templates", isDirectory: true)
+ }
+
+ private init() {
+ ensureTemplatesExist()
+ loadTemplates()
+ }
+
+ // MARK: - Public API
+
+ /// Get template for a specific type
+ func template(for type: WizardTemplateType) -> WizardTemplate? {
+ templates.first { $0.type == type }
+ }
+
+ /// Build a context-aware system prompt for a given template type.
+ /// Substitutes `{{skill_name}}`, `{{skill_description}}`, `{{file_path}}`,
+ /// `{{frontmatter}}`, and `{{kind}}` from the supplied skill context.
+ func systemPrompt(
+ for type: WizardTemplateType,
+ skillName: String,
+ skillDescription: String,
+ filePath: String,
+ frontmatter: [String: String]
+ ) -> String {
+ let base = systemPromptContent(for: type)
+ let frontmatterText = frontmatter.isEmpty
+ ? "(none)"
+ : frontmatter.sorted(by: { $0.key < $1.key })
+ .map { "\($0.key): \($0.value)" }.joined(separator: "\n")
+ return base
+ .replacingOccurrences(of: "{{skill_name}}", with: skillName.isEmpty ? "(unnamed)" : skillName)
+ .replacingOccurrences(of: "{{skill_description}}", with: skillDescription.isEmpty ? "(no description)" : skillDescription)
+ .replacingOccurrences(of: "{{file_path}}", with: filePath)
+ .replacingOccurrences(of: "{{frontmatter}}", with: frontmatterText)
+ .replacingOccurrences(of: "{{kind}}", with: type.rawValue)
+ }
+
+ private func systemPromptContent(for type: WizardTemplateType) -> String {
+ Self.defaultSkillSystemPrompt
+ }
+
+ /// Save updated template content
+ func save(_ template: WizardTemplate) {
+ let url = templatesDirectory.appendingPathComponent(template.type.fileName)
+ do {
+ try template.content.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,
+ lastModified: Date()
+ )
+ }
+ } catch {
+ AppLogger.fileIO.error("Failed to save template: \(error.localizedDescription)")
+ }
+ }
+
+ /// Reset a template to bundled default
+ func resetToDefault(_ type: WizardTemplateType) {
+ guard let bundledContent = loadBundledTemplate(type) else { return }
+ let template = WizardTemplate(type: type, content: bundledContent, lastModified: Date())
+ save(template)
+ }
+
+ /// Reset all templates to defaults
+ func resetAllToDefaults() {
+ for type in WizardTemplateType.allCases {
+ resetToDefault(type)
+ }
+ }
+
+ // MARK: - Private
+
+ private func ensureTemplatesExist() {
+ if !fileManager.fileExists(atPath: templatesDirectory.path) {
+ try? fileManager.createDirectory(at: templatesDirectory, withIntermediateDirectories: true)
+ }
+
+ // Write bundled templates on first run; overwrite outdated stored versions.
+ for type in WizardTemplateType.allCases {
+ let destURL = templatesDirectory.appendingPathComponent(type.fileName)
+ guard let bundled = loadBundledTemplate(type) else { continue }
+
+ if !fileManager.fileExists(atPath: destURL.path) {
+ try? bundled.write(to: destURL, atomically: true, encoding: .utf8)
+ } else if let stored = try? String(contentsOf: destURL, encoding: .utf8),
+ templateNeedsUpdate(stored: stored, bundled: bundled) {
+ try? bundled.write(to: destURL, atomically: true, encoding: .utf8)
+ }
+ }
+ }
+
+ /// Returns true when a stored template's version marker is older than the bundled version.
+ /// Only auto-updates templates that still carry the default version header — user-customized
+ /// templates that omit the marker are left untouched.
+ private func templateNeedsUpdate(stored: String, bundled: String) -> Bool {
+ guard let storedVersion = extractVersion(from: stored),
+ let bundledVersion = extractVersion(from: bundled) else {
+ return false
+ }
+ return storedVersion < bundledVersion
+ }
+
+ private func extractVersion(from content: String) -> Int? {
+ let prefix = "<!-- chops-template-version: "
+ guard let start = content.range(of: prefix),
+ let end = content.range(of: " -->", range: start.upperBound ..< content.endIndex) else {
+ return nil
+ }
+ return Int(content[start.upperBound ..< end.lowerBound])
+ }
+
+ private func loadTemplates() {
+ templates = WizardTemplateType.allCases.compactMap { type in
+ let url = templatesDirectory.appendingPathComponent(type.fileName)
+ guard let content = try? String(contentsOf: url, encoding: .utf8) else {
+ return nil
+ }
+ let attrs = try? fileManager.attributesOfItem(atPath: url.path)
+ let modified = attrs?[.modificationDate] as? Date ?? Date()
+ return WizardTemplate(type: type, content: content, lastModified: modified)
+ }
+ }
+
+ private func loadBundledTemplate(_ type: WizardTemplateType) -> String? {
+ guard let url = Bundle.main.url(
+ forResource: type.rawValue + "-composer",
+ withExtension: "md",
+ subdirectory: "Templates"
+ ) else {
+ return defaultTemplateContent(for: type)
+ }
+ return try? String(contentsOf: url, encoding: .utf8)
+ }
+
+ private func defaultTemplateContent(for type: WizardTemplateType) -> String {
+ Self.defaultSkillTemplate
+ }
+
+ // MARK: - Default Templates
+
+ private static let defaultSkillTemplate = """
+ <!-- chops-template-version: 2 -->
+ # Skill Composer
+
+ You are helping create or improve a skill definition.
+
+ ## Context
+ - File type: Skill
+ - Skills are reusable knowledge/instructions for AI assistants
+
+ ## Current Content
+ {{file_content}}
+
+ ## User Instructions
+ {{user_instructions}}
+
+ ## Guidelines
+ 1. Use YAML frontmatter for metadata (name, description)
+ 2. Write clear, actionable instructions
+ 3. Include examples where helpful
+ 4. Keep scope focused and composable
+ """
+
+
+ // MARK: - Default System Prompts
+
+ private static let defaultSkillSystemPrompt = """
+ You are an expert in writing skills for AI coding assistants that use the Model Context Protocol (MCP).
+
+ ## Current skill context
+ - Name: {{skill_name}}
+ - Description: {{skill_description}}
+ - File: {{file_path}}
+ - Frontmatter:
+ {{frontmatter}}
+
+ ## Your role
+ When 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.
+ """
+
+}
+
+
diff --git a/Chops/Views/Detail/SkillDetailView.swift b/Chops/Views/Detail/SkillDetailView.swift
index 57984b5..4965ad0 100644
--- a/Chops/Views/Detail/SkillDetailView.swift
+++ b/Chops/Views/Detail/SkillDetailView.swift
@@ -23,6 +23,7 @@ struct SkillDetailView: View {
@State private var document = SkillEditorDocument()
@State private var activeAlert: ActiveAlert?
@State private var autoSaveTask: Task<Void, Never>?
+ @State private var showingComposePanel = false
var body: some View {
@Bindable var document = document
@@ -34,6 +35,21 @@ struct SkillDetailView: View {
SkillEditorView(document: document)
}
+ // Inline compose panel
+ if showingComposePanel {
+ ComposePanel(
+ content: $document.editorContent,
+ isVisible: $showingComposePanel,
+ skillName: skill.name,
+ skillDescription: skill.skillDescription,
+ frontmatter: skill.frontmatter,
+ filePath: skill.filePath,
+ workingDirectory: URL(fileURLWithPath: skill.filePath).deletingLastPathComponent(),
+ templateType: .skill,
+ onAccept: { document.save(to: skill) }
+ )
+ }
+
Divider()
SkillMetadataBar(skill: skill)
@@ -66,6 +82,16 @@ struct SkillDetailView: View {
Text(document.saveErrorMessage)
}
.toolbar {
+ ToolbarItem {
+ Button {
+ document.save(to: skill)
+ } label: {
+ Label("Save", systemImage: "square.and.arrow.down")
+ }
+ .buttonStyle(.bordered)
+ .disabled(!document.hasUnsavedChanges)
+ .help("Save (⌘S)")
+ }
ToolbarItem {
Picker("Mode", selection: $preferPreview) {
Image(systemName: "pencil").tag(false)
@@ -73,6 +99,14 @@ struct SkillDetailView: View {
}
.pickerStyle(.segmented)
}
+ ToolbarItemGroup {
+ Button {
+ showingComposePanel.toggle()
+ } label: {
+ Image(systemName: showingComposePanel ? "sparkles.rectangle.stack.fill" : "sparkles")
+ }
+ .help(showingComposePanel ? "Hide Compose Panel" : "Compose with AI")
+ }
ToolbarItem {
Button {
skill.isFavorite.toggle()
diff --git a/Chops/Views/Detail/TemplateDetailView.swift b/Chops/Views/Detail/TemplateDetailView.swift
new file mode 100644
index 0000000..f9c23cd
--- /dev/null
+++ b/Chops/Views/Detail/TemplateDetailView.swift
@@ -0,0 +1,100 @@
+import SwiftUI
+
+struct TemplateDetailView: View {
+ let templateType: WizardTemplateType
+ @State private var templateManager = TemplateManager.shared
+ @State private var content: String = ""
+ @State private var hasChanges = false
+ @State private var showingResetConfirm = false
+
+ var body: some View {
+ VStack(spacing: 0) {
+ // Editor
+ TextEditor(text: $content)
+ .font(.system(.body, design: .monospaced))
+ .scrollContentBackground(.hidden)
+ .padding(12)
+ .onChange(of: content) { _, _ in
+ hasChanges = true
+ }
+
+ Divider()
+
+ // Footer
+ HStack {
+ Text("Template for \(templateType.displayName.lowercased())")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+
+ Spacer()
+
+ if hasChanges {
+ Text("Unsaved changes")
+ .font(.caption)
+ .foregroundStyle(.orange)
+ }
+
+ Button("Reset to Default") {
+ showingResetConfirm = true
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(.red)
+ .font(.caption)
+
+ Button("Save") {
+ save()
+ }
+ .buttonStyle(.borderedProminent)
+ .controlSize(.small)
+ .disabled(!hasChanges)
+ .keyboardShortcut("s", modifiers: .command)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ .background(Color(NSColor.controlBackgroundColor))
+ }
+ .onAppear {
+ loadTemplate()
+ }
+ .onChange(of: templateType) { _, _ in
+ loadTemplate()
+ }
+ .confirmationDialog(
+ "Reset Template?",
+ isPresented: $showingResetConfirm,
+ titleVisibility: .visible
+ ) {
+ Button("Reset to Default", role: .destructive) {
+ templateManager.resetToDefault(templateType)
+ loadTemplate()
+ }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ Text("This will replace your custom template with the default version.")
+ }
+ .navigationTitle(templateType.displayName)
+ }
+
+ private func loadTemplate() {
+ if let template = templateManager.template(for: templateType) {
+ content = template.content
+ hasChanges = false
+ }
+ }
+
+ private func save() {
+ let template = WizardTemplate(
+ type: templateType,
+ content: content,
+ lastModified: Date()
+ )
+ templateManager.save(template)
+ hasChanges = false
+ }
+}
+
+#Preview {
+ TemplateDetailView(templateType: .skill)
+ .frame(width: 600, height: 400)
+}
+
diff --git a/Chops/Views/Settings/ACPSettingsView.swift b/Chops/Views/Settings/ACPSettingsView.swift
new file mode 100644
index 0000000..3f10e9e
--- /dev/null
+++ b/Chops/Views/Settings/ACPSettingsView.swift
@@ -0,0 +1,98 @@
+import ACPRegistry
+import SwiftUI
+
+struct ACPSettingsView: View {
+ @State private var configuration = ACPConfiguration.shared
+
+ var body: some View {
+ Form {
+ Section {
+ Text("Enable AI assistants to help compose and improve skills, agents, and rules.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ }
+
+ agentListSection
+
+ Section {
+ Button("Refresh Registry") {
+ Task { await configuration.refreshRegistry() }
+ }
+ .disabled(configuration.isLoadingRegistry)
+ }
+ }
+ .formStyle(.grouped)
+ .padding()
+ .task { await configuration.loadRegistryIfNeeded() }
+ }
+
+ // MARK: - Agent List
+
+ @ViewBuilder
+ private var agentListSection: some View {
+ Section {
+ if configuration.isLoadingRegistry {
+ HStack {
+ ProgressView()
+ .controlSize(.small)
+ Text("Loading registry…")
+ .foregroundStyle(.secondary)
+ }
+ } else if let error = configuration.registryError {
+ HStack(spacing: 6) {
+ Image(systemName: "exclamationmark.triangle.fill")
+ .foregroundStyle(.orange)
+ Text(error)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ } else if configuration.registryAgents.isEmpty {
+ Text("No agents found.")
+ .foregroundStyle(.secondary)
+ } else {
+ ForEach(configuration.registryAgents) { agent in
+ AgentRow(agent: agent, configuration: configuration)
+ }
+ }
+ } header: {
+ Text("Agents")
+ }
+ }
+}
+
+// MARK: - Agent Row
+
+private struct AgentRow: View {
+ let agent: RegistryAgent
+ @Bindable var configuration: ACPConfiguration
+
+ var body: some View {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(agent.name)
+ .fontWeight(.medium)
+ Text(agent.description)
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ .lineLimit(2)
+ Text("v\(agent.version)")
+ .font(.caption2)
+ .foregroundStyle(.tertiary)
+ }
+ Spacer()
+ Toggle("", isOn: Binding(
+ get: { configuration.isEnabled(agent.id) },
+ set: { configuration.setEnabled(agent.id, $0) }
+ ))
+ .labelsHidden()
+ }
+ .padding(.vertical, 2)
+ }
+}
+
+// MARK: - Preview
+
+#Preview {
+ ACPSettingsView()
+ .frame(width: 500, height: 500)
+}
diff --git a/Chops/Views/Settings/SettingsView.swift b/Chops/Views/Settings/SettingsView.swift
index 1ab5058..c2095ea 100644
--- a/Chops/Views/Settings/SettingsView.swift
+++ b/Chops/Views/Settings/SettingsView.swift
@@ -6,6 +6,8 @@ extension Notification.Name {
}
struct SettingsView: View {
+ private static let logger = AppLogger.settings
+
let updater: SPUUpdater
@State private var customPaths: [String] = []
@State private var defaultTool: ToolSource = .claude
@@ -17,6 +19,11 @@ struct SettingsView: View {
Label("General", systemImage: "gearshape")
}
+ ACPSettingsView()
+ .tabItem {
+ Label("AI Assist", systemImage: "sparkles")
+ }
+
scanSettings
.tabItem {
Label("Scan Directories", systemImage: "folder.badge.gearshape")
@@ -32,7 +39,7 @@ struct SettingsView: View {
Label("About", systemImage: "info.circle")
}
}
- .frame(width: 480, height: 380)
+ .frame(minWidth: 480, minHeight: 550, idealHeight: 600)
.onAppear {
loadCustomPaths()
}
diff --git a/Chops/Views/Shared/ACPLogViewer.swift b/Chops/Views/Shared/ACPLogViewer.swift
new file mode 100644
index 0000000..e65b4fc
--- /dev/null
+++ b/Chops/Views/Shared/ACPLogViewer.swift
@@ -0,0 +1,110 @@
+import SwiftUI
+
+/// Viewer for ACP debug logs
+struct ACPLogViewer: View {
+ @State private var logContent = ""
+ @State private var debugEnabled = acpLog.debugEnabled
+ @State private var autoRefresh = true
+ @State private var refreshTask: Task<Void, Never>?
+
+ var body: some View {
+ VStack(spacing: 0) {
+ // Toolbar
+ HStack {
+ Text("ACP Logs")
+ .font(.headline)
+
+ Spacer()
+
+ Toggle("Debug Mode", isOn: $debugEnabled)
+ .toggleStyle(.switch)
+ .controlSize(.small)
+ .onChange(of: debugEnabled) { _, newValue in
+ acpLog.debugEnabled = newValue
+ }
+
+ Toggle("Auto-refresh", isOn: $autoRefresh)
+ .toggleStyle(.switch)
+ .controlSize(.small)
+
+ Button {
+ refreshLogs()
+ } label: {
+ Image(systemName: "arrow.clockwise")
+ }
+ .buttonStyle(.borderless)
+ .help("Refresh")
+
+ Button {
+ acpLog.clearLogs()
+ refreshLogs()
+ } label: {
+ Image(systemName: "trash")
+ }
+ .buttonStyle(.borderless)
+ .help("Clear Logs")
+
+ Button {
+ NSWorkspace.shared.selectFile(acpLog.logURL.path, inFileViewerRootedAtPath: "")
+ } label: {
+ Image(systemName: "folder")
+ }
+ .buttonStyle(.borderless)
+ .help("Show in Finder")
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ .background(Color(.controlBackgroundColor))
+
+ Divider()
+
+ // Log content
+ ScrollViewReader { proxy in
+ ScrollView {
+ Text(logContent)
+ .font(.system(.caption, design: .monospaced))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .textSelection(.enabled)
+ .padding(8)
+ .id("bottom")
+ }
+ .onChange(of: logContent) { _, _ in
+ withAnimation {
+ proxy.scrollTo("bottom", anchor: .bottom)
+ }
+ }
+ }
+ .background(Color(.textBackgroundColor))
+ }
+ .onAppear {
+ refreshLogs()
+ startAutoRefresh()
+ }
+ .onDisappear {
+ refreshTask?.cancel()
+ }
+ }
+
+ private func refreshLogs() {
+ Task {
+ let content = await acpLog.recentLogs(lines: 500)
+ logContent = content
+ }
+ }
+
+ private func startAutoRefresh() {
+ refreshTask = Task {
+ while !Task.isCancelled {
+ try? await Task.sleep(for: .seconds(1))
+ guard autoRefresh else { continue }
+ let content = await acpLog.recentLogs(lines: 500)
+ logContent = content
+ }
+ }
+ }
+}
+
+#Preview {
+ ACPLogViewer()
+ .frame(width: 600, height: 400)
+}
diff --git a/Chops/Views/Shared/ComposeModel.swift b/Chops/Views/Shared/ComposeModel.swift
new file mode 100644
index 0000000..8d21bbb
--- /dev/null
+++ b/Chops/Views/Shared/ComposeModel.swift
@@ -0,0 +1,47 @@
+import Foundation
+
+// MARK: - Chat Model
+
+enum ChatRole { case user, assistant }
+
+enum DiffStatus { case pending, accepted, rejected }
+
+struct ChatDiff {
+ let path: String
+ /// Pre-edit content. `nil` means the file did not exist before the agent wrote it.
+ let original: String?
+ let proposed: String
+ var status: DiffStatus = .pending
+}
+
+struct ChatMessage: Identifiable {
+ let id: UUID
+ let role: ChatRole
+ var text: String
+ var thoughtText: String
+ var isError: Bool
+ var diffs: [ChatDiff]
+
+ init(
+ id: UUID = UUID(),
+ role: ChatRole,
+ text: String,
+ thoughtText: String = "",
+ isError: Bool = false,
+ diffs: [ChatDiff] = []
+ ) {
+ self.id = id
+ self.role = role
+ self.text = text
+ self.thoughtText = thoughtText
+ self.isError = isError
+ self.diffs = diffs
+ }
+}
+
+// MARK: - Layout Constants
+
+enum ComposeConstants {
+ static let defaultPanelHeight: CGFloat = 400
+ static let bubbleWidthRatio: CGFloat = 0.80
+}
diff --git a/Chops/Views/Shared/ComposePanel.swift b/Chops/Views/Shared/ComposePanel.swift
new file mode 100644
index 0000000..e1b8814
--- /dev/null
+++ b/Chops/Views/Shared/ComposePanel.swift
@@ -0,0 +1,815 @@
+import ACPModel
+import ACPRegistry
+import SwiftUI
+
+/// Inline panel for composing/editing skill content with ACP
+struct ComposePanel: View {
+ @Binding var content: String
+ @Binding var isVisible: Bool
+ let skillName: String
+ let skillDescription: String
+ let frontmatter: [String: String]
+ /// Absolute path of the file being edited — used to read source-of-truth from disk.
+ let filePath: String
+ let workingDirectory: URL
+ /// Called after a diff is accepted — use to persist the change immediately.
+ let onAccept: () -> Void
+
+ @State private var selectedTemplateType: WizardTemplateType
+ @State private var inputText = ""
+ @State private var selectedAgentId: String?
+ @State private var acpClient: BaseACPAgent?
+ @State private var showingDebugLogs = false
+
+ /// Completed conversation history. Never holds in-flight messages — the SDK drives live state.
+ @State private var messages: [ChatMessage] = []
+ /// True until the first successful prompt in this session.
+ @State private var isFirstTurn = true
+
+ @AppStorage("ACPDebugLogging") private var debugLoggingEnabled = false
+ @State private var panelHeight: CGFloat = ComposeConstants.defaultPanelHeight
+ @State private var isDragging = false
+ @State private var dragStartHeight: CGFloat?
+
+ private static let minPanelHeight: CGFloat = 160
+ private static let maxPanelHeight: CGFloat = 700
+
+ init(
+ content: Binding<String>,
+ isVisible: Binding<Bool>,
+ skillName: String,
+ skillDescription: String = "",
+ frontmatter: [String: String] = [:],
+ filePath: String,
+ workingDirectory: URL,
+ templateType: WizardTemplateType,
+ onAccept: @escaping () -> Void = {}
+ ) {
+ self._content = content
+ self._isVisible = isVisible
+ self.skillName = skillName
+ self.skillDescription = skillDescription
+ self.frontmatter = frontmatter
+ self.filePath = filePath
+ self.workingDirectory = workingDirectory
+ self.onAccept = onAccept
+ self._selectedTemplateType = State(initialValue: templateType)
+ }
+
+ private var configuredAgents: [RegistryAgent] { ACPConfiguration.shared.enabledAgents }
+ private var selectedAgent: RegistryAgent? { configuredAgents.first { $0.id == selectedAgentId } }
+
+ private var isConnected: Bool { acpClient?.isConnected ?? false }
+ private var isConnecting: Bool { acpClient?.isConnecting ?? false }
+ private var isProcessing: Bool { acpClient?.isProcessing ?? false }
+ private var hasPendingDiffs: Bool { messages.contains { $0.diffs.contains { $0.status == .pending } } }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ resizeHandle
+
+ if configuredAgents.isEmpty {
+ noToolsConfiguredView
+ } else {
+ VStack(spacing: 0) {
+ topBar
+ Divider()
+ configOptionsBar
+ chatArea
+ Divider()
+ inputArea
+ }
+ }
+ }
+ .frame(height: panelHeight)
+ .background(Color(.windowBackgroundColor))
+ .onAppear {
+ if selectedAgentId == nil {
+ selectedAgentId = configuredAgents.first?.id
+ }
+ }
+ .onDisappear {
+ forceDisconnect()
+ }
+ .onChange(of: selectedAgentId) { _, _ in
+ forceDisconnect()
+ }
+ .task { await ACPConfiguration.shared.loadRegistryIfNeeded() }
+ .sheet(isPresented: Binding(
+ get: { acpClient?.pendingPermissionRequest != nil },
+ set: { if !$0 { acpClient?.respondToPermission(optionId: nil) } }
+ )) {
+ if let request = acpClient?.pendingPermissionRequest {
+ permissionSheet(request: request)
+ }
+ }
+ }
+
+ @ViewBuilder
+ private func permissionSheet(request: PermissionRequest) -> some View {
+ VStack(alignment: .leading, spacing: 16) {
+ Label("Permission Required", systemImage: "hand.raised.fill")
+ .font(.headline)
+ Text(request.title)
+ .foregroundStyle(.secondary)
+ Divider()
+ VStack(alignment: .leading, spacing: 8) {
+ ForEach(request.options, id: \.optionId) { option in
+ Button(option.name) {
+ acpClient?.respondToPermission(optionId: option.optionId)
+ }
+ .buttonStyle(.bordered)
+ .tint(permissionOptionTint(for: option.kind))
+ }
+ }
+ Divider()
+ Button("Cancel") {
+ acpClient?.respondToPermission(optionId: nil)
+ }
+ .foregroundStyle(.secondary)
+ }
+ .padding(24)
+ .frame(minWidth: 320, maxWidth: 440)
+ }
+
+ private func permissionOptionTint(for kind: String) -> Color {
+ switch kind {
+ case "allow_once", "allow_always": return .green
+ case "reject_once", "reject_always": return .red
+ default: return .secondary
+ }
+ }
+
+ // MARK: - Views
+
+ @Environment(\.openSettings) private var openSettings
+
+ 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()
+ }
+ .buttonStyle(.link)
+ Spacer()
+ closeButton
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ }
+
+ private var topBar: some View {
+ HStack(spacing: 8) {
+ // LEFT: Tool picker + connection + debug
+ HStack(spacing: 8) {
+ Picker("", selection: $selectedAgentId) {
+ Text("Select...").tag(nil as String?)
+ ForEach(configuredAgents) { agent in
+ Text(agent.name).tag(Optional(agent.id))
+ }
+ }
+ .labelsHidden()
+ .frame(width: 120)
+
+ connectionButton
+ debugLogButton
+ }
+
+ Spacer()
+
+ // Error indicator — connection errors reported by the agent.
+ if let error = acpClient?.lastError {
+ HStack(spacing: 4) {
+ Image(systemName: "exclamationmark.circle.fill")
+ .foregroundStyle(.red)
+ Text(error)
+ .font(.caption)
+ .foregroundStyle(.red)
+ .lineLimit(1)
+ }
+ .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")
+ closeButton
+ }
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ .background(Color(.controlBackgroundColor))
+ }
+
+ // 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.
+ @ViewBuilder
+ private var configOptionsBar: 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)
+ }
+ }
+ Spacer()
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .background(Color(.controlBackgroundColor).opacity(0.6))
+ Divider()
+ }
+ }
+
+ @ViewBuilder
+ private func configOptionPicker(option: SessionConfigOption, select: SessionConfigSelect) -> some View {
+ let flatOptions: [SessionConfigSelectOption] = {
+ switch select.options {
+ case .ungrouped(let opts): return opts
+ case .grouped(let groups): return groups.flatMap(\.options)
+ }
+ }()
+ Picker(option.name, selection: Binding(
+ get: { select.currentValue },
+ set: { newValue in
+ Task { try? await acpClient?.setConfigOption(id: option.id, value: newValue) }
+ }
+ )) {
+ ForEach(flatOptions, id: \.value) { opt in
+ Text(opt.name).tag(opt.value)
+ }
+ }
+ .fixedSize()
+ .help(option.description ?? option.name)
+ }
+
+ // MARK: - Chat Area
+
+ /// Completed messages worth showing — assistant turns with no text and no diffs are omitted.
+ private var visibleMessages: [ChatMessage] {
+ messages.filter { msg in
+ guard msg.role == .assistant else { return true }
+ return !msg.text.isEmpty || msg.isError || !msg.diffs.isEmpty
+ }
+ }
+
+ private var chatArea: some View {
+ GeometryReader { geo in
+ let bubbleWidth = max(200, floor(geo.size.width * ComposeConstants.bubbleWidthRatio))
+ ScrollViewReader { proxy in
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 12) {
+ if messages.isEmpty && !isProcessing {
+ if isConnected {
+ connectedPlaceholder
+ } else {
+ disconnectedPlaceholder
+ }
+ }
+ ForEach(visibleMessages) { message in
+ chatRow(message: message, bubbleWidth: bubbleWidth)
+ .id(message.id)
+ }
+ // Live assistant bubble — reads directly from the SDK while prompt is active.
+ if isProcessing {
+ liveAssistantRow(bubbleWidth: bubbleWidth)
+ .id("live-assistant")
+ }
+ }
+ .padding(12)
+ }
+ .background(Color(.textBackgroundColor).opacity(0.3))
+ .onChange(of: messages.count) { _, _ in
+ withAnimation { proxy.scrollTo("live-assistant", anchor: .bottom) }
+ }
+ .onChange(of: isProcessing) { _, active in
+ if active {
+ withAnimation { proxy.scrollTo("live-assistant", anchor: .bottom) }
+ } else if let last = messages.last {
+ withAnimation { proxy.scrollTo(last.id, anchor: .bottom) }
+ }
+ }
+ .onChange(of: acpClient?.currentActivity) { _, _ in
+ if isProcessing {
+ withAnimation { proxy.scrollTo("live-assistant", anchor: .bottom) }
+ }
+ }
+ }
+ }
+ }
+
+ private var disconnectedPlaceholder: some View {
+ VStack(spacing: 8) {
+ Image(systemName: "link.badge.plus")
+ .font(.title2)
+ .foregroundStyle(.secondary)
+ Text("Connect an agent to start composing")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 20)
+ }
+
+ private var connectedPlaceholder: some View {
+ Text("Session ready. Send your first instruction.")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 20)
+ }
+
+ // MARK: - Live Assistant Row (SDK-driven, shown while prompt is active)
+
+ @ViewBuilder
+ private func liveAssistantRow(bubbleWidth: CGFloat) -> some View {
+ let thoughtText = acpClient?.thoughtText ?? ""
+ let responseText = acpClient?.responseText ?? ""
+ let displayText = acpClient?.conversationalText(from: responseText) ?? responseText
+ let activity = acpClient?.currentActivity
+
+ VStack(alignment: .leading, spacing: 6) {
+ if !thoughtText.isEmpty {
+ ThinkingView(text: thoughtText, isStreaming: true)
+ .frame(maxWidth: bubbleWidth, alignment: .leading)
+ }
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 4) {
+ 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)
+
+ Divider().padding(.horizontal, 8)
+
+ if !displayText.isEmpty {
+ Text(displayText)
+ .font(.body)
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 10).padding(.vertical, 8)
+ } else if let activity {
+ HStack(spacing: 6) {
+ ProgressView().controlSize(.mini)
+ Text(activity).foregroundStyle(.secondary)
+ }
+ .font(.callout)
+ .padding(.horizontal, 10).padding(.vertical, 8)
+ } else {
+ HStack(spacing: 6) {
+ ProgressView().controlSize(.mini)
+ Text("Working…").foregroundStyle(.secondary)
+ }
+ .font(.callout)
+ .padding(.horizontal, 10).padding(.vertical, 8)
+ }
+ }
+ .frame(maxWidth: bubbleWidth, alignment: .leading)
+ .background(Color.primary.opacity(0.06))
+ .clipShape(RoundedRectangle(cornerRadius: 8))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.secondary.opacity(0.2)))
+ }
+ }
+
+ // MARK: - Completed Message Rows
+
+ @ViewBuilder
+ private func chatRow(message: ChatMessage, bubbleWidth: CGFloat) -> some View {
+ VStack(alignment: message.role == .user ? .trailing : .leading, spacing: 6) {
+ switch message.role {
+ case .user:
+ HStack(spacing: 0) {
+ Spacer(minLength: 16)
+ Text(message.text)
+ .font(.body)
+ .textSelection(.enabled)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 7)
+ .background(Color.accentColor.opacity(0.15))
+ .clipShape(RoundedRectangle(cornerRadius: 10))
+ .frame(maxWidth: bubbleWidth, alignment: .trailing)
+ }
+ case .assistant:
+ if !message.thoughtText.isEmpty {
+ ThinkingView(text: message.thoughtText, isStreaming: false)
+ .frame(maxWidth: bubbleWidth, alignment: .leading)
+ }
+ assistantCard(message: message)
+ .frame(maxWidth: bubbleWidth, alignment: .leading)
+ }
+ ForEach(message.diffs.indices, id: \.self) { i in
+ diffCard(messageId: message.id, diffIndex: i, diff: message.diffs[i])
+ }
+ }
+ }
+
+ @ViewBuilder
+ private func assistantCard(message: ChatMessage) -> some View {
+ let displayText = message.text
+
+ VStack(alignment: .leading, spacing: 0) {
+ HStack(spacing: 4) {
+ if message.isError {
+ Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.orange)
+ Text("Error").foregroundStyle(.orange)
+ } else {
+ Image(systemName: "sparkles").foregroundStyle(.secondary)
+ Text("Agent").foregroundStyle(.secondary)
+ }
+ Spacer()
+ }
+ .font(.caption)
+ .padding(.horizontal, 10)
+ .padding(.top, 8)
+ .padding(.bottom, 4)
+
+ Divider()
+ .padding(.horizontal, 8)
+
+ if message.isError {
+ Text(displayText)
+ .font(.body.italic())
+ .foregroundStyle(.orange)
+ .textSelection(.enabled)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ } else if !displayText.isEmpty {
+ MarkdownMessageView(text: displayText)
+ .font(.body)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 8)
+ }
+ }
+ .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))
+ .clipShape(RoundedRectangle(cornerRadius: 8))
+ .overlay(
+ RoundedRectangle(cornerRadius: 8)
+ .stroke(message.isError ? Color.orange.opacity(0.35) : Color.secondary.opacity(0.2))
+ )
+ }
+
+ @ViewBuilder
+ private func diffCard(messageId: UUID, diffIndex: Int, diff: ChatDiff) -> some View {
+ switch diff.status {
+ case .accepted:
+ HStack(spacing: 6) {
+ Label("Changes accepted", systemImage: "checkmark.circle.fill")
+ .foregroundStyle(.green)
+ Text("· \(diff.path.split(separator: "/").last.map(String.init) ?? diff.path)")
+ .foregroundStyle(.secondary)
+ }
+ .font(.caption)
+ .padding(.horizontal, 8)
+ case .rejected:
+ HStack(spacing: 6) {
+ Label("Changes rejected", systemImage: "xmark.circle.fill")
+ .foregroundStyle(.secondary)
+ Text("· \(diff.path.split(separator: "/").last.map(String.init) ?? diff.path)")
+ .foregroundStyle(.secondary)
+ }
+ .font(.caption)
+ .padding(.horizontal, 8)
+ case .pending:
+ DiffReviewPanel(
+ original: diff.original ?? "",
+ proposed: diff.proposed,
+ onAccept: { acceptDiff(messageId: messageId, diffIndex: diffIndex) },
+ onReject: { rejectDiff(messageId: messageId, diffIndex: diffIndex) }
+ )
+ .frame(height: 260)
+ .clipShape(RoundedRectangle(cornerRadius: 8))
+ .overlay(RoundedRectangle(cornerRadius: 8).stroke(Color.secondary.opacity(0.2)))
+ }
+ }
+
+ // MARK: - Input Area
+
+ 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)
+ }
+ 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)))
+
+ Button {
+ sendMessage()
+ } label: {
+ Group {
+ if isProcessing {
+ ProgressView().controlSize(.small)
+ } else {
+ Image(systemName: "paperplane.fill")
+ }
+ }
+ .frame(width: 24, height: 24)
+ }
+ .buttonStyle(.borderedProminent)
+ .disabled(!isConnected || inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || isProcessing || hasPendingDiffs)
+ .keyboardShortcut(.return, modifiers: .command)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ .background(Color(.controlBackgroundColor))
+ }
+
+ private var resizeHandle: some View {
+ ZStack {
+ Color(.separatorColor)
+ .frame(height: 1)
+ RoundedRectangle(cornerRadius: 2)
+ .fill(Color.secondary.opacity(isDragging ? 0.5 : 0.25))
+ .frame(width: 36, height: 4)
+ }
+ .frame(maxWidth: .infinity)
+ .frame(height: 10)
+ .contentShape(Rectangle())
+ .onHover { hovering in
+ if hovering {
+ NSCursor.resizeUpDown.push()
+ } else {
+ NSCursor.pop()
+ }
+ }
+ .gesture(
+ DragGesture(minimumDistance: 1)
+ .onChanged { value in
+ isDragging = true
+ if dragStartHeight == nil {
+ dragStartHeight = panelHeight
+ }
+ let newHeight = (dragStartHeight ?? panelHeight) - value.translation.height
+ panelHeight = max(Self.minPanelHeight, min(Self.maxPanelHeight, newHeight))
+ }
+ .onEnded { _ in
+ isDragging = false
+ dragStartHeight = nil
+ }
+ )
+ }
+
+ private var connectionButton: some View {
+ Button {
+ if isConnected || isConnecting {
+ forceDisconnect()
+ } else {
+ connect()
+ }
+ } label: {
+ Group {
+ if isConnecting {
+ ProgressView().controlSize(.mini)
+ } else {
+ Image(systemName: "link")
+ .foregroundStyle(isConnected ? .green : .red)
+ }
+ }
+ .frame(width: 20, height: 20)
+ }
+ .buttonStyle(.plain)
+ .help(isConnected ? "Disconnect" : isConnecting ? "Cancel connection" : "Connect to \(selectedAgent?.name ?? "agent")")
+ .disabled(selectedAgentId == nil)
+ }
+
+ private var closeButton: some View {
+ Button {
+ forceDisconnect()
+ isVisible = false
+ } label: {
+ Image(systemName: "xmark")
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(.secondary)
+ }
+
+ @ViewBuilder
+ private var debugLogButton: some View {
+ if debugLoggingEnabled {
+ Button {
+ showingDebugLogs = true
+ } label: {
+ Image(systemName: "ladybug")
+ .foregroundStyle(.orange)
+ }
+ .buttonStyle(.plain)
+ .help("View ACP Logs")
+ .popover(isPresented: $showingDebugLogs) {
+ ACPLogViewer()
+ .frame(width: 600, height: 400)
+ }
+ }
+ }
+
+ // MARK: - Actions
+
+ private func connect() {
+ guard let agent = selectedAgent, !isConnected, !isConnecting else { return }
+ let client = ACPAgentFactory.make(for: agent.id)
+ acpClient = client // agent's @Observable state drives the UI from this point
+ let systemPrompt = TemplateManager.shared.systemPrompt(
+ for: selectedTemplateType,
+ skillName: skillName,
+ skillDescription: skillDescription,
+ filePath: filePath,
+ frontmatter: frontmatter
+ )
+ 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)
+ guard !text.isEmpty else { return }
+
+ inputText = ""
+ messages.append(ChatMessage(role: .user, text: text))
+
+ let assistantId = UUID()
+
+ Task {
+ do {
+ let fp = filePath
+ let original: String? = await readFile(at: fp)
+ guard let original else {
+ messages.append(ChatMessage(id: assistantId, role: .assistant, text: "Cannot read file: \(filePath)", isError: true))
+ return
+ }
+ let prompt = buildPrompt(text: text, originalContent: original)
+ try await client.prompt(prompt) // agent sets isProcessing true → false via defer
+ isFirstTurn = false
+
+ let raw = client.responseText
+ let processed = client.conversationalText(from: raw)
+ let finalText = processed.isEmpty ? raw : processed
+ acpLog.info("Compose: turn done — raw=\(raw.count) chars, thought=\(client.thoughtText.count) chars")
+
+ messages.append(ChatMessage(id: assistantId, role: .assistant, text: finalText, thoughtText: client.thoughtText))
+ await handleWrites(client: client, messageId: assistantId, filePath: fp, originalContent: original)
+ } catch {
+ client.clearPendingWrites()
+ messages.append(ChatMessage(id: assistantId, role: .assistant, text: error.localizedDescription, isError: true))
+ }
+ }
+ }
+
+ /// Reads a file off the main actor (UTF-8 with UTF-16 fallback).
+ private func readFile(at path: String) async -> String? {
+ await Task.detached(priority: .userInitiated) {
+ (try? String(contentsOfFile: path, encoding: .utf8))
+ ?? (try? String(contentsOfFile: path, encoding: .utf16))
+ }.value
+ }
+
+ /// Expands the template on the first turn; returns plain text on subsequent turns.
+ private func buildPrompt(text: String, originalContent: String) -> String {
+ guard isFirstTurn, let template = TemplateManager.shared.template(for: selectedTemplateType) else {
+ return text
+ }
+ return template.content
+ .replacingOccurrences(of: "{{file_content}}", with: originalContent.isEmpty ? "(empty)" : originalContent)
+ .replacingOccurrences(of: "{{user_instructions}}", with: text)
+ }
+
+ /// 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)")
+ 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)
+ client.clearPendingWrites()
+ return
+ }
+ 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)
+ }
+ }
+
+ /// Converts pending writes into ChatDiff entries and attaches them to the message.
+ /// Disk reads for non-current files are dispatched off the main actor.
+ /// 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 {
+ URL(fileURLWithPath: path).resolvingSymlinksInPath().path
+ }
+
+ private func attachDiffs(
+ messageId: UUID,
+ writes: [(path: String, content: String, original: String?)],
+ fallbackOriginal: String
+ ) async {
+ guard let idx = messages.firstIndex(where: { $0.id == messageId }) else { return }
+ let resolvedFilePath = resolvedPath(filePath)
+ acpLog.debug("Compose: attachDiffs — filePath=\(filePath) resolved=\(resolvedFilePath) fallback.count=\(fallbackOriginal.count)")
+ var diffs: [ChatDiff] = []
+ for write in writes {
+ let writtenResolved = resolvedPath(write.path)
+ let original: String?
+ if let embedded = write.original {
+ // Agent supplied the pre-edit content (e.g. DiffContent.oldText) — use it directly.
+ original = embedded
+ } else if write.path == filePath || writtenResolved == resolvedFilePath {
+ // Path matches (accounting for symlinks) — use the in-memory content from before the turn.
+ original = fallbackOriginal
+ } else {
+ // Different file: read from disk. nil means the file didn't exist (new file).
+ original = await readFile(at: write.path)
+ }
+ acpLog.debug("Compose: diff \(write.path) original=\(original?.count ?? -1) chars")
+ diffs.append(ChatDiff(path: write.path, original: original, proposed: write.content))
+ }
+ messages[idx].diffs = diffs
+ }
+
+ private func acceptDiff(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 = .accepted
+ if resolvedPath(diff.path) == resolvedPath(filePath) {
+ content = diff.proposed
+ onAccept()
+ }
+ }
+
+ 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
+ // 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)
+ }
+ }
+ }
+}
+
+// MARK: - Preview
+
+#Preview {
+ @Previewable @State var content = "# Sample Skill\n\nThis is sample content."
+ @Previewable @State var isVisible = true
+ VStack {
+ Text("Editor content above")
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ ComposePanel(
+ content: $content,
+ isVisible: $isVisible,
+ skillName: "sample-skill",
+ filePath: "/tmp/sample-skill.md",
+ workingDirectory: URL(fileURLWithPath: "/tmp"),
+ templateType: .skill
+ )
+ }
+ .frame(width: 600, height: 400)
+}
diff --git a/Chops/Views/Shared/DiffReviewPanel.swift b/Chops/Views/Shared/DiffReviewPanel.swift
new file mode 100644
index 0000000..9bfcec5
--- /dev/null
+++ b/Chops/Views/Shared/DiffReviewPanel.swift
@@ -0,0 +1,195 @@
+import SwiftUI
+
+// MARK: - Diff Model
+
+enum DiffLineKind {
+ case unchanged, added, removed
+
+ var prefix: String {
+ switch self {
+ case .unchanged: " "
+ case .added: "+"
+ case .removed: "-"
+ }
+ }
+
+ var prefixColor: Color {
+ switch self {
+ case .unchanged: .secondary
+ case .added: .green
+ case .removed: .red
+ }
+ }
+
+ var background: Color {
+ switch self {
+ case .unchanged: .clear
+ case .added: Color.green.opacity(0.12)
+ case .removed: Color.red.opacity(0.12)
+ }
+ }
+}
+
+struct DiffLine: Identifiable {
+ let id = UUID()
+ let text: String
+ let kind: DiffLineKind
+}
+
+// MARK: - LCS Diff Engine
+
+/// Computes a unified diff via LCS. O(n·m) — suitable for files up to ~3 000 lines.
+/// Must not be called on the main actor for large inputs; use Task.detached at the call site.
+func computeDiff(from original: String, to proposed: String) -> [DiffLine] {
+ let a = original.components(separatedBy: .newlines)
+ let b = proposed.components(separatedBy: .newlines)
+
+ let m = a.count, n = b.count
+
+ // Guard: ClosedRange 1...0 traps at runtime; handle empty inputs explicitly.
+ guard m > 0, n > 0 else {
+ let removals = a.map { DiffLine(text: $0, kind: .removed) }
+ let additions = b.map { DiffLine(text: $0, kind: .added) }
+ return removals + additions
+ }
+
+ // Guard: prevent OOM on very large files. Beyond 3 000 lines the LCS matrix
+ // exceeds ~72 MB. Treat oversized input as a full replacement diff.
+ let lineLimit = 3_000
+ guard m <= lineLimit, n <= lineLimit else {
+ let removals = a.map { DiffLine(text: $0, kind: .removed) }
+ let additions = b.map { DiffLine(text: $0, kind: .added) }
+ return removals + additions
+ }
+
+ var dp = Array(repeating: Array(repeating: 0, count: n + 1), count: m + 1)
+ for i in 1...m {
+ for j in 1...n {
+ dp[i][j] = a[i-1] == b[j-1] ? dp[i-1][j-1] + 1 : max(dp[i-1][j], dp[i][j-1])
+ }
+ }
+
+ // Backtrack to collect LCS pairs (originalIndex, proposedIndex)
+ var pairs: [(Int, Int)] = []
+ var i = m, j = n
+ while i > 0 && j > 0 {
+ if a[i-1] == b[j-1] { pairs.append((i-1, j-1)); i -= 1; j -= 1 }
+ else if dp[i-1][j] >= dp[i][j-1] { i -= 1 } else { j -= 1 }
+ }
+ pairs.reverse()
+
+ // Walk both arrays, emitting diff lines
+ var result: [DiffLine] = []
+ var ai = 0, bi = 0
+ for (oi, pi) in pairs {
+ while ai < oi { result.append(DiffLine(text: a[ai], kind: .removed)); ai += 1 }
+ while bi < pi { result.append(DiffLine(text: b[bi], kind: .added)); bi += 1 }
+ result.append(DiffLine(text: a[ai], kind: .unchanged))
+ ai += 1; bi += 1
+ }
+ while ai < m { result.append(DiffLine(text: a[ai], kind: .removed)); ai += 1 }
+ while bi < n { result.append(DiffLine(text: b[bi], kind: .added)); bi += 1 }
+ return result
+}
+
+// MARK: - DiffReviewPanel
+
+/// Shows a unified diff between `original` and `proposed` with Accept / Reject controls.
+struct DiffReviewPanel: View {
+ let original: String
+ let proposed: String
+ let onAccept: () -> Void
+ let onReject: () -> Void
+
+ @State private var lines: [DiffLine] = []
+
+ private var addedCount: Int { lines.filter { $0.kind == .added }.count }
+ private var removedCount: Int { lines.filter { $0.kind == .removed }.count }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ header
+ Divider()
+ diffScroll
+ }
+ .task {
+ // Compute off the main actor — LCS allocates O(n·m) memory; blocks UI for large files.
+ let result = await Task.detached(priority: .userInitiated) {
+ computeDiff(from: original, to: proposed)
+ }.value
+ lines = result
+ }
+ }
+
+ // MARK: - Subviews
+
+ private var header: some View {
+ HStack(spacing: 10) {
+ Image(systemName: "plusminus")
+ .foregroundStyle(.secondary)
+
+ Label("+\(addedCount)", systemImage: "")
+ .font(.caption.monospaced())
+ .foregroundStyle(.green)
+ Label("-\(removedCount)", systemImage: "")
+ .font(.caption.monospaced())
+ .foregroundStyle(.red)
+
+ Spacer()
+
+ Text("Review Changes")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+
+ Spacer()
+
+ Button("Reject", action: onReject)
+ .buttonStyle(.bordered)
+ .controlSize(.small)
+
+ Button("Accept", action: onAccept)
+ .buttonStyle(.borderedProminent)
+ .controlSize(.small)
+ .tint(.green)
+ .keyboardShortcut(.return, modifiers: .command)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .background(Color(.controlBackgroundColor))
+ }
+
+ private var diffScroll: some View {
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 0) {
+ ForEach(lines) { line in
+ HStack(alignment: .top, spacing: 4) {
+ Text(line.kind.prefix)
+ .font(.system(.caption2, design: .monospaced))
+ .foregroundStyle(line.kind.prefixColor)
+ .frame(width: 10, alignment: .center)
+ Text(line.text.isEmpty ? " " : line.text)
+ .font(.system(.caption2, design: .monospaced))
+ .foregroundStyle(line.kind == .unchanged ? .primary : line.kind.prefixColor)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .padding(.horizontal, 8)
+ .padding(.vertical, 1)
+ .background(line.kind.background)
+ }
+ }
+ }
+ .background(Color(.textBackgroundColor))
+ }
+}
+
+// MARK: - Preview
+
+#Preview {
+ DiffReviewPanel(
+ 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: {}
+ )
+ .frame(width: 600, height: 300)
+}
diff --git a/Chops/Views/Shared/MarkdownMessageView.swift b/Chops/Views/Shared/MarkdownMessageView.swift
new file mode 100644
index 0000000..63e1ba6
--- /dev/null
+++ b/Chops/Views/Shared/MarkdownMessageView.swift
@@ -0,0 +1,29 @@
+import SwiftUI
+
+struct MarkdownMessageView: View {
+ let text: String
+ @State private var attributed: AttributedString?
+
+ var body: some View {
+ Text(attributed ?? AttributedString(text))
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .fixedSize(horizontal: false, vertical: true)
+ .task(id: text) {
+ let normalized = normalize(text)
+ attributed = (try? AttributedString(markdown: normalized, options: .init(
+ allowsExtendedAttributes: true,
+ interpretedSyntax: .inlineOnlyPreservingWhitespace,
+ failurePolicy: .returnPartiallyParsedIfPossible
+ ))) ?? AttributedString(normalized)
+ }
+ }
+
+ private func normalize(_ input: String) -> String {
+ var result = input
+ while result.contains("\n\n\n") {
+ result = result.replacingOccurrences(of: "\n\n\n", with: "\n\n")
+ }
+ return result.trimmingCharacters(in: .newlines)
+ }
+}
diff --git a/Chops/Views/Shared/ThinkingView.swift b/Chops/Views/Shared/ThinkingView.swift
new file mode 100644
index 0000000..1fadc30
--- /dev/null
+++ b/Chops/Views/Shared/ThinkingView.swift
@@ -0,0 +1,69 @@
+import SwiftUI
+
+/// Collapsible "Thinking" section rendered outside the assistant bubble.
+/// `isStreaming` is passed from the parent and should only flip false once (when the turn ends).
+struct ThinkingView: View {
+ let text: String
+ let isStreaming: Bool
+
+ @State private var isExpanded: Bool = true
+ /// Latched true once streaming ends — shows brain icon instead of spinner.
+ @State private var settled: Bool = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 0) {
+ Button {
+ withAnimation(.easeInOut(duration: 0.2)) { isExpanded.toggle() }
+ } label: {
+ HStack(spacing: 5) {
+ Image(systemName: isExpanded ? "chevron.down" : "chevron.right")
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ if !settled {
+ ProgressView().controlSize(.mini)
+ } else {
+ Image(systemName: "brain")
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+ }
+ Text("Thinking")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ Spacer()
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+
+ if isExpanded {
+ ScrollView(.vertical) {
+ Text(text)
+ .font(.caption.monospaced())
+ .foregroundStyle(.secondary)
+ .opacity(0.75)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .textSelection(.enabled)
+ .padding(.horizontal, 10)
+ .padding(.bottom, 8)
+ }
+ .frame(maxHeight: 140)
+ }
+ }
+ .padding(.bottom, 4)
+ .onAppear {
+ // Already settled when created for a completed message (isStreaming never flips).
+ if !isStreaming {
+ settled = true
+ isExpanded = false
+ }
+ }
+ .onChange(of: isStreaming) { _, streaming in
+ if !streaming {
+ settled = true
+ withAnimation(.easeInOut(duration: 0.3)) { isExpanded = false }
+ }
+ }
+ }
+}
diff --git a/Chops/Views/Shared/ToolBadge.swift b/Chops/Views/Shared/ToolBadge.swift
index bdbcfc1..0fa7372 100644
--- a/Chops/Views/Shared/ToolBadge.swift
+++ b/Chops/Views/Shared/ToolBadge.swift
@@ -36,6 +36,7 @@ struct ToolIcon: View {
extension ToolSource {
var shortLabel: String {
switch self {
+ case .augment: "AU"
case .claude: "CC"
case .cursor: "CU"
case .windsurf: "WS"
diff --git a/Chops/Views/Sidebar/SidebarView.swift b/Chops/Views/Sidebar/SidebarView.swift
index a01ab7b..4818745 100644
--- a/Chops/Views/Sidebar/SidebarView.swift
+++ b/Chops/Views/Sidebar/SidebarView.swift
@@ -5,7 +5,6 @@ struct SidebarView: View {
@Environment(AppState.self) private var appState
@Environment(\.modelContext) private var modelContext
@Query(sort: \Skill.name) private var allSkills: [Skill]
- @Query(sort: \SkillCollection.sortOrder) private var collections: [SkillCollection]
@Query(sort: \RemoteServer.label) private var servers: [RemoteServer]
@State private var syncingServerIDs: Set<String> = []
@State private var serverErrors: [String: String] = [:]
@@ -13,7 +12,8 @@ struct SidebarView: View {
private var activeSources: [ToolSource] {
ToolSource.allCases.filter { tool in
- allSkills.contains { $0.toolSources.contains(tool) }
+ guard tool.listable else { return false }
+ return allSkills.contains { $0.toolSources.contains(tool) }
}
}
@@ -27,13 +27,9 @@ struct SidebarView: View {
List(selection: $appState.sidebarFilter) {
Section("Library") {
Label("All Skills", systemImage: "doc.text")
- .badge(allSkills.filter { $0.itemKind == .skill }.count)
+ .badge(allSkills.count)
.tag(SidebarFilter.allSkills)
- Label("All Agents", systemImage: "person.crop.rectangle")
- .badge(allSkills.filter { $0.itemKind == .agent }.count)
- .tag(SidebarFilter.allAgents)
-
Label("Favorites", systemImage: "star")
.badge(allSkills.filter(\.isFavorite).count)
.tag(SidebarFilter.favorites)
@@ -51,6 +47,13 @@ struct SidebarView: View {
}
}
+ Section("Wizard Templates") {
+ ForEach(WizardTemplateType.allCases) { templateType in
+ Label(templateType.displayName, systemImage: templateType.icon)
+ .tag(SidebarFilter.wizardTemplate(templateType))
+ }
+ }
+
if !servers.isEmpty {
Section("Servers") {
ForEach(servers) { server in
@@ -115,14 +118,13 @@ struct SidebarView: View {
private func syncServer(_ server: RemoteServer) {
syncingServerIDs.insert(server.id)
serverErrors.removeValue(forKey: server.id)
- Task {
- let scanner = SkillScanner(modelContext: modelContext)
+ let context = modelContext
+ Task { @MainActor in
+ let scanner = SkillScanner(modelContext: context)
await scanner.scanRemoteServer(server)
- await MainActor.run {
- syncingServerIDs.remove(server.id)
- if let error = server.lastSyncError {
- serverErrors[server.id] = error
- }
+ syncingServerIDs.remove(server.id)
+ if let error = server.lastSyncError {
+ serverErrors[server.id] = error
}
}
}
diff --git a/Chops/Views/Sidebar/SkillListView.swift b/Chops/Views/Sidebar/SkillListView.swift
index a22396a..ee7a05d 100644
--- a/Chops/Views/Sidebar/SkillListView.swift
+++ b/Chops/Views/Sidebar/SkillListView.swift
@@ -40,6 +40,8 @@ struct SkillListView: View {
}
case .server(let serverID):
result = result.filter { $0.remoteServer?.id == serverID }
+ case .wizardTemplate:
+ result = []
}
if !appState.searchText.isEmpty {
@@ -62,6 +64,7 @@ struct SkillListView: View {
case .collection(let name): name
case .server(let id):
allSkills.first(where: { $0.remoteServer?.id == id })?.remoteServer?.label ?? "Remote"
+ case .wizardTemplate(let templateType): templateType.displayName
}
}
diff --git a/project.yml b/project.yml
index 2bdf8e2..79d01a7 100644
--- a/project.yml
+++ b/project.yml
@@ -15,6 +15,9 @@ packages:
Sparkle:
url: https://github.com/sparkle-project/Sparkle
from: "2.6.0"
+ ACP:
+ url: https://github.com/wiedymi/swift-acp
+ branch: main
Highlightr:
url: https://github.com/raspu/Highlightr
from: "2.2.1"
@@ -36,6 +39,12 @@ targets:
- package: Highlightr
- package: cmark-gfm
product: cmark
+ - package: ACP
+ product: ACP
+ - package: ACP
+ product: ACPModel
+ - package: ACP
+ product: ACPRegistry
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: com.joshpigford.Chops