Branchwell

Jotley / app · jotley.ai / scripts / mcp-demo.swift

Raw 14.2 KB on d2c8e7812d9b8c1cc5857eb6dc912d99bc5c9048
1// Captures the actual native Settings and notes views using an isolated library.
2// It never opens the user's library or edits an agent's saved configuration.
3import AppKit
4import CoreData
5import MCP
6import SwiftUI
7@testable import Jotley
8
9@main private struct MCPDemo {
10 @MainActor static func main() {
11 Task { @MainActor in
12 do {
13 if CommandLine.arguments.dropFirst().first == "--help" {
14 print("Usage: scripts/test-mcp.sh --demo --serve /absolute/output/folder")
15 } else {
16 guard ["--serve", "--backup", "--transcript", "--feature-review"].contains(CommandLine.arguments.dropFirst().first ?? "") else {
17 throw LocalError.message("Use --demo --serve /absolute/output/folder to capture the native app views.")
18 }
19 if CommandLine.arguments[1] == "--feature-review" { try await featureReview() }
20 else if ["--backup", "--transcript"].contains(CommandLine.arguments[1]) { try await backupPreview() }
21 else { try await serve() }
22 }
23 exit(0)
24 } catch { fputs("DEMO FAILED: \(error.localizedDescription)\n", stderr); exit(1) }
25 }
26 NSApplication.shared.setActivationPolicy(.regular)
27 NSApplication.shared.run()
28 }
29
30 @MainActor private static func pause(_ seconds: Double) async throws {
31 try await Task.sleep(for: .seconds(seconds))
32 }
33
34 @MainActor private static func featureReview() async throws {
35 guard CommandLine.arguments.count >= 3 else { throw LocalError.message("Provide a feature review output folder.") }
36 let controlPath = CommandLine.arguments.count > 3 ? CommandLine.arguments[3] : CommandLine.arguments[2]
37 let output = URL(fileURLWithPath: controlPath, isDirectory: true)
38 let store = try SharedPersistenceController(inMemory: true)
39 LocalAppModel.isolatedStoreForTesting = store
40 let defaults = UserDefaults.standard
41 defaults.set(true, forKey: JotleyOnboarding.completedKey)
42 defaults.set(true, forKey: "recordSystemAudio")
43 defaults.set("Light", forKey: "selectedAppearanceMode")
44 defaults.removeObject(forKey: CustomSpeechWords.defaultsKey)
45 let token = UUID().uuidString + UUID().uuidString
46 let service = JotleyMCPService(defaults: defaults, port: 0, token: token)
47 await service.attach(store: store)
48 await service.setEnabled(true, persistPreference: false)
49 service.setAllowsWriting(true)
50 let local = LocalAppModel.shared
51 if ProcessInfo.processInfo.environment["JOTLEY_DEMO_SIMULATED_RECORDING"] == "1" {
52 JotleyAppDelegate().setupStatusItem()
53 let recorder = local.recorder
54 recorder.simulatedStart = { [weak recorder] _, _, _ in
55 var speech = LocalTranscript()
56 speech.accept(text: "Jason will review the design.", start: 0, end: 3, final: true)
57 speech.accept(text: "Share the notes with the team.", start: 14, end: 17, final: true)
58 recorder?.beginSimulatedLiveTranscription(speech)
59 }
60 }
61 let host = NSHostingView(rootView: RootView(recorder: local.recorder)
62 .environment(\.managedObjectContext, store.context).environmentObject(store))
63 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1140, height: 740),
64 styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false)
65 window.title = "Jotley Feature Review"
66 window.isReleasedWhenClosed = false
67 window.contentView = host
68 window.center()
69 window.makeKeyAndOrderFront(nil)
70 NSApp.activate()
71 print("READY: isolated Mac feature review"); fflush(stdout)
72 var seeded = false
73 var changedWords = false
74 while !FileManager.default.fileExists(atPath: output.appendingPathComponent("stop").path) {
75 if !seeded, FileManager.default.fileExists(atPath: output.appendingPathComponent("seed-note").path) {
76 seeded = true
77 let note = try store.create(title: "Launch planning", text: "JSON is reviewing the design.\n\nSend JSON the revised notes. Keep JSONKit as written.") as! Note
78 note.setTranscriptUtterances([
79 TranscriptUtterance(text: "JSON is reviewing the design.", start: 0, end: 5),
80 TranscriptUtterance(text: "Send JSON the revised notes. Keep JSONKit as written.", start: 25, end: 31)
81 ])
82 note.summary = "## Launch plan\n\nReview the design and send the revised notes."
83 try store.save(); try local.reload()
84 print("READY: timed sample note"); fflush(stdout)
85 }
86 if !changedWords, FileManager.default.fileExists(atPath: output.appendingPathComponent("mcp-add").path) {
87 changedWords = true
88 let client = try await MCPIntegration.connect(endpoint: service.endpoint, token: token)
89 let current = try await client.callTool(name: "list_custom_words", arguments: [:])
90 let state = try JSONSerialization.jsonObject(with: Data(MCPIntegration.text(current.content).utf8)) as? [String: Any]
91 guard let revision = state?["revision"] as? String else { throw LocalError.message("Couldn’t read the Custom Words revision.") }
92 let updated = try await client.callTool(name: "update_custom_words", arguments: ["expected_revision": .string(revision), "add": ["North Studio"]])
93 guard updated.isError != true else { throw LocalError.message("Couldn’t update Custom Words through MCP.") }
94 print("PASS: update_custom_words added North Studio"); fflush(stdout)
95 await client.disconnect()
96 }
97 try await pause(0.25)
98 }
99 await service.setEnabled(false, persistPreference: false)
100 }
101
102 @MainActor private static func backupPreview() async throws {
103 guard CommandLine.arguments.count >= 3 else { throw LocalError.message("Provide a session output folder") }
104 let output = URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true)
105 let empty = ProcessInfo.processInfo.environment["JOTLEY_BACKUP_EMPTY"] == "1"
106 let store = try empty ? SharedPersistenceController(inMemory: true) : MCPIntegration.fixture()
107 LocalAppModel.isolatedStoreForTesting = store
108 let service = JotleyMCPService(defaults: UserDefaults(suiteName: "JotleyBackupNativeQA")!, port: 0, token: String(repeating: "a", count: 64))
109 let content: AnyView
110 if CommandLine.arguments[1] == "--transcript" {
111 let note = try store.create(title: "Transcript editing", text: "Review the disign. Keep the purple branding. Ship after both checks pass.") as! Note
112 let utterances = [TranscriptUtterance(id: "review", text: "Review the disign.", start: 0, end: 4),
113 TranscriptUtterance(id: "brand", text: "Keep the purple branding.", start: 12, end: 18),
114 TranscriptUtterance(id: "ship", text: "Ship after both checks pass.", start: 28, end: 34)]
115 try store.saveNoteChanges(note, values: ["transcriptUtterancesJSON": String(decoding: try JSONEncoder().encode(utterances), as: UTF8.self)])
116 content = AnyView(TranscriptEditorPreview(note: note, viewModel: NotesListViewModel(viewContext: store.context, recorder: ProcessTapRecorder(), persistenceController: store)).environmentObject(store))
117 } else {
118 content = AnyView(SettingsView(mcp: service, selectedSection: .general).environmentObject(store))
119 }
120 let host = NSHostingView(rootView: content.preferredColorScheme(.dark))
121 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1160, height: 800), styleMask: [.titled, .closable], backing: .buffered, defer: false)
122 window.title = "Jotley — Backup Test"
123 window.isReleasedWhenClosed = false
124 window.contentView = host
125 window.appearance = NSAppearance(named: .darkAqua)
126 window.makeKeyAndOrderFront(nil)
127 NSApp.activate(ignoringOtherApps: true)
128 print("READY: native backup Settings with \(try store.notes().count) synthetic notes; MCP stays disabled")
129 fflush(stdout)
130 while !FileManager.default.fileExists(atPath: output.appendingPathComponent("stop").path) { try await pause(0.5) }
131 let backup = try LibraryBackupService.export(from: store, templates: .shared)
132 try LibraryBackupService.encode(backup).write(to: output.appendingPathComponent("verified-library.json"), options: .atomic)
133 print("PASS: native backup test finished with \(backup.noteCount) notes")
134 window.orderOut(nil)
135 }
136
137 @MainActor private static func serve() async throws {
138 guard CommandLine.arguments.count >= 3 else { throw LocalError.message("Provide a session output folder") }
139 let folder = URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true)
140 let store = try MCPIntegration.fixture()
141 LocalAppModel.isolatedStoreForTesting = store
142 let suite = "JotleyMCPExternalDemo.\(UUID().uuidString)"
143 let defaults = UserDefaults(suiteName: suite)!
144 defaults.set(true, forKey: "foldersExpanded")
145 defer { defaults.removePersistentDomain(forName: suite) }
146 let token = (UUID().uuidString + UUID().uuidString).replacingOccurrences(of: "-", with: "").lowercased()
147 let service = JotleyMCPService(defaults: defaults, port: JotleyMCPService.defaultPort, token: token)
148 await service.attach(store: store)
149 let host = NSHostingView(rootView: SettingsView(mcp: service, selectedSection: .mcp)
150 .environmentObject(store).preferredColorScheme(.dark)
151 .background(Color(red: 0.12, green: 0.12, blue: 0.12)))
152 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 820), styleMask: [.titled, .closable], backing: .buffered, defer: false)
153 window.title = "Jotley"
154 window.isReleasedWhenClosed = false
155 window.contentView = host
156 window.appearance = NSAppearance(named: .darkAqua)
157 window.makeKeyAndOrderFront(nil)
158 NSApp.activate(ignoringOtherApps: true)
159 try await pause(1)
160 func snapshot(_ name: String) throws {
161 let frame = window.contentView?.superview ?? host
162 frame.layoutSubtreeIfNeeded()
163 guard let bitmap = frame.bitmapImageRepForCachingDisplay(in: frame.bounds) else { throw LocalError.message("Cannot capture Settings window") }
164 frame.cacheDisplay(in: frame.bounds, to: bitmap)
165 try bitmap.representation(using: .png, properties: [:])?.write(to: folder.appendingPathComponent(name))
166 }
167 try snapshot("settings-off.png")
168 await service.setEnabled(true)
169 try MCPIntegration.expect(service.enabled, service.errorMessage ?? "Sample server did not start")
170 await service.testConnection()
171 try await pause(0.5)
172 try snapshot("settings-ready.png")
173 service.setAllowsWriting(true)
174 try await pause(0.5)
175 try snapshot("settings-write.png")
176 let notesHost = NSHostingView(rootView: RootView(recorder: LocalAppModel.shared.recorder)
177 .environment(\.managedObjectContext, store.context).environmentObject(store)
178 .defaultAppStorage(defaults)
179 .preferredColorScheme(.dark))
180 let notesWindow = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1200, height: 850), styleMask: [.titled, .closable], backing: .buffered, defer: false)
181 notesWindow.title = "Jotley"
182 notesWindow.isReleasedWhenClosed = false
183 notesWindow.contentView = notesHost
184 notesWindow.appearance = NSAppearance(named: .darkAqua)
185 notesWindow.makeKeyAndOrderFront(nil)
186 try await pause(1)
187 func snapshotNote(_ name: String) throws {
188 guard notesWindow.isVisible else { return }
189 let frame = notesWindow.contentView?.superview ?? notesHost
190 frame.layoutSubtreeIfNeeded()
191 guard let bitmap = frame.bitmapImageRepForCachingDisplay(in: frame.bounds) else { throw LocalError.message("Cannot capture note window") }
192 frame.cacheDisplay(in: frame.bounds, to: bitmap)
193 try bitmap.representation(using: .png, properties: [:])?.write(to: folder.appendingPathComponent(name))
194 }
195 try snapshotNote("note-before.png")
196 let config = folder.appendingPathComponent("client.json")
197 try service.clientConfiguration!.write(to: config, atomically: true, encoding: .utf8)
198 try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: config.path)
199 print("READY: isolated sample server; client configuration saved")
200 fflush(stdout)
201 while !FileManager.default.fileExists(atPath: folder.appendingPathComponent("stop").path) {
202 try await pause(0.5)
203 try snapshot("settings-live.png")
204 try snapshotNote("note-live.png")
205 }
206 try snapshot("settings-agent.png")
207 try snapshotNote("note-after.png")
208 await service.setEnabled(false)
209 window.orderOut(nil)
210 notesWindow.orderOut(nil)
211 print("PASS: external-client demo session stopped")
212 }
213
214}
215
216private struct TranscriptEditorPreview: View {
217 @ObservedObject var note: Note
218 @ObservedObject var viewModel: NotesListViewModel
219 @State private var editing = false
220 var body: some View {
221 VStack(alignment: .leading, spacing: 16) {
222 Text("Transcript editing — isolated sample note").font(.headline)
223 Text("Correct a paragraph, then return to bubbles. Recorded times remain attached.").font(.callout)
224 if !editing { Button("Edit Transcript") { editing = true } }
225 ScrollView {
226 if editing {
227 LocalMacTranscriptEditor(note: note, viewModel: viewModel) { editing = false }
228 } else {
229 TranscriptParagraphsView(transcript: note.transcription ?? "", utterances: note.transcriptUtterances,
230 interimText: "", isRecordingActive: false, showEllipsis: false)
231 }
232 }
233 }.padding(24).frame(maxWidth: .infinity, maxHeight: .infinity)
234 }
235}