Branchwell

Jotley / app · jotley.ai / iOS / JotleyiOSApp.swift

Raw 12.0 KB on d2c8e7812d9b8c1cc5857eb6dc912d99bc5c9048
1import SwiftUI
2import CoreData
3
4@main
5struct JotleyiOSApp: App {
6 private let store: SharedPersistenceController?
7 private let launchError: String?
8 @StateObject private var transcriptionManager: LiveTranscriptionManager
9 @Environment(\.scenePhase) private var scenePhase
10
11 init() {
12 JotleySummaryNotifications.shared.install()
13 var persistence: SharedPersistenceController?
14 var failure = MobileDeviceEligibility.unsupportedReason
15 if failure == nil {
16 do {
17 #if DEBUG && targetEnvironment(simulator)
18 if ProcessInfo.processInfo.environment["JOTLEY_TEST_RESET_ONBOARDING"] == "1" {
19 UserDefaults.standard.removeObject(forKey: JotleyOnboarding.completedKey)
20 }
21 if ProcessInfo.processInfo.environment["JOTLEY_TEST_RESET_NOTIFICATIONS"] == "1" {
22 UserDefaults.standard.removeObject(forKey: JotleySummaryNotifications.enabledKey)
23 }
24 if let data = ProcessInfo.processInfo.environment["JOTLEY_SCREENSHOT_DATA"]?.data(using: .utf8) {
25 // Explicit simulator-only fixtures use a disposable in-memory store.
26 // No fixture path or data-loading hook is compiled into shipping builds.
27 if ProcessInfo.processInfo.environment["JOTLEY_TEST_RESET_CUSTOM_WORDS"] == "1" {
28 UserDefaults.standard.removeObject(forKey: CustomSpeechWords.defaultsKey)
29 }
30 let fixtureStore = try SharedPersistenceController(inMemory: true)
31 let samples = try JSONDecoder().decode([ScreenshotNote].self, from: data)
32 for (index, sample) in samples.enumerated() {
33 let object = try fixtureStore.create(title: sample.title, text: sample.transcript, noteType: "voice")
34 if let note = object as? Note {
35 note.summary = sample.summary
36 note.summaryType = sample.template ?? (sample.summary.isEmpty ? "default-summary" : "Concise")
37 note.timestamp = Date().addingTimeInterval(sample.timestampOffset ?? Double(-index * 3600))
38 if !sample.folder.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
39 note.folder = Folder.getOrCreate(named: sample.folder, in: fixtureStore.context)
40 }
41 for tag in sample.tags { try note.addTagByName(tag, in: fixtureStore.context) }
42 note.setTranscriptUtterances(sample.transcript.components(separatedBy: "\n\n").enumerated().map { TranscriptUtterance(text: $0.element, start: Double($0.offset * 25), end: Double(($0.offset + 1) * 25)) })
43 if let id = note.id {
44 for message in sample.messages ?? [] {
45 try fixtureStore.saveChatMessage(LocalChatMessage(role: message.role, content: message.content), noteID: id)
46 }
47 }
48 }
49 }
50 try fixtureStore.save()
51 persistence = fixtureStore
52 UserDefaults.standard.set(ProcessInfo.processInfo.environment["JOTLEY_SCREENSHOT_APPEARANCE"] ?? "Light", forKey: "selectedAppearanceMode")
53 } else { persistence = try SharedPersistenceController(syncMode: NoteSyncMode.application()) }
54 #else
55 persistence = try SharedPersistenceController(syncMode: NoteSyncMode.application())
56 #endif
57 if persistence?.ready != true { failure = persistence?.errorMessage }
58 } catch { failure = error.localizedDescription }
59 }
60 store = persistence; launchError = failure
61 let testNotifications: JotleySummaryNotifications?
62 #if DEBUG && targetEnvironment(simulator)
63 if ProcessInfo.processInfo.environment["JOTLEY_TEST_SUMMARY_TAGS"] == "1" {
64 testNotifications = JotleySummaryNotifications(defaults: .standard, authorization: { .denied },
65 requestAuthorization: { false }, enqueue: { _ in }, isActive: { false })
66 } else { testNotifications = nil }
67 #else
68 testNotifications = nil
69 #endif
70 let recorder = LiveTranscriptionManager(store: failure == nil ? persistence : nil, summaryNotifications: testNotifications)
71 #if DEBUG && targetEnvironment(simulator)
72 if ProcessInfo.processInfo.environment["JOTLEY_TEST_SUMMARY_TAGS"] == "1" {
73 recorder.simulatedSummaryGeneration = { update in
74 await update("AI and design guide the project research and planning.")
75 try await Task.sleep(for: .seconds(1))
76 return "AI and design guide the project research and planning."
77 }
78 recorder.simulatedTitleGeneration = { _ in "Launch Design Plan" }
79 recorder.simulatedOrganization = { _, _ in
80 LocalNoteOrganization(tags: ["Artificial Intelligence", "Design", "Research", "Planning", "Meetings", "Overflow"], folder: .work)
81 }
82 }
83 if ProcessInfo.processInfo.environment["JOTLEY_TEST_SUMMARY_SCROLL"] == "1" {
84 recorder.simulatedSummaryGeneration = { update in
85 try await Task.sleep(for: .seconds(3))
86 var content = ""
87 for index in 1...160 {
88 try await Task.sleep(for: .milliseconds(200))
89 content += "## Summary update \(index)\n\nThe team agreed to keep voice notes and summaries on the device. Maya will review the milestones and Sam will check the next steps.\n\n"
90 await update(content)
91 if index == 18, ProcessInfo.processInfo.environment["JOTLEY_TEST_SUMMARY_SCROLL_HOLD"] == "1" {
92 // Keep a known final item visible while XCTest measures its frame.
93 try await Task.sleep(for: .seconds(60))
94 }
95 }
96 return content
97 }
98 }
99 if ["1", "layout"].contains(ProcessInfo.processInfo.environment["JOTLEY_TEST_TRANSCRIPTION_LIFECYCLE"] ?? "") {
100 if let encoded = ProcessInfo.processInfo.environment["JOTLEY_SCREENSHOT_AUDIO_LEVELS"],
101 let data = encoded.data(using: .utf8),
102 let levels = try? JSONDecoder().decode([Float].self, from: data),
103 !levels.isEmpty, levels.allSatisfy({ $0.isFinite && (0...1).contains($0) }) {
104 recorder.simulatedAudioLevels = levels
105 }
106 recorder.simulatedSpeechStart = { snapshot in
107 let session = SimulatorLifecycleSpeech(snapshot: snapshot)
108 await session.publishCards()
109 return session
110 }
111 }
112 #endif
113 if failure == nil {
114 do { try LocalNoteExport.cleanupStaleExports() }
115 catch {
116 let message = "Temporary export cleanup failed: \(error.localizedDescription). Your notes and saved exports remain available."
117 recorder.errorMessage = [recorder.errorMessage, message].compactMap { $0 }.joined(separator: " ")
118 }
119 }
120 _transcriptionManager = StateObject(wrappedValue: recorder)
121 }
122 var body: some Scene {
123 WindowGroup {
124 if let store, launchError == nil {
125 MainTabView()
126 .environment(\.managedObjectContext, store.context)
127 .environmentObject(store)
128 .environmentObject(transcriptionManager)
129 .task { transcriptionManager.resumePendingSummary() }
130 .onChange(of: scenePhase) { _, phase in
131 if phase == .background { transcriptionManager.saveEdits() }
132 if phase == .active { transcriptionManager.resumePendingSummary() }
133 }
134 } else {
135 ContentUnavailableView("Jotley Unavailable", systemImage: "iphone", description: Text(launchError ?? "Local notes are unavailable."))
136 .accessibilityIdentifier("unsupportedDeviceView")
137 }
138 }
139 }
140}
141
142#if DEBUG && targetEnvironment(simulator)
143private struct ScreenshotNote: Decodable {
144 let title: String
145 let folder: String
146 let tags: [String]
147 let transcript: String
148 let summary: String
149 var template: String?
150 var timestampOffset: Double?
151 var messages: [Message]?
152 struct Message: Decodable { let role: String; let content: String }
153}
154#endif
155
156#if DEBUG && targetEnvironment(simulator)
157/// Deterministic lifecycle/UI fixture, never a speech-recognition acceptance test.
158private struct SimulatorLifecycleSpeech: MobileSpeechSession {
159 let snapshot: @Sendable (LocalTranscript) async -> Void
160 nonisolated func append(_ data: Data, sampleRate: Double) {}
161 func publishCards() async {
162 if let text = ProcessInfo.processInfo.environment["JOTLEY_SCREENSHOT_LIVE_TEXT"] {
163 var value = LocalTranscript()
164 for (index, paragraph) in text.components(separatedBy: "\n\n").enumerated() {
165 value.accept(text: paragraph, start: Double(index * 12), end: Double(index * 12 + 10), final: true)
166 }
167 await snapshot(value)
168 return
169 }
170 if ProcessInfo.processInfo.environment["JOTLEY_TEST_TRANSCRIPTION_LIFECYCLE"] == "layout" {
171 var first = LocalTranscript()
172 first.accept(text: "First spoken words.", start: 0, end: 1, final: false)
173 await snapshot(first)
174 Task {
175 try? await Task.sleep(for: .seconds(8))
176 var growing = first
177 growing.accept(text: "First spoken words.", start: 0, end: 1, final: true)
178 growing.accept(text: "Second spoken words.", start: 5, end: 6, final: false)
179 await snapshot(growing)
180 try? await Task.sleep(for: .seconds(8))
181 growing.accept(text: "Second spoken words.", start: 5, end: 6, final: true)
182 for index in 2..<18 {
183 growing.accept(text: "Transcript card \(index + 1). Words from the active session remain on this device.",
184 start: Double(index * 5), end: Double(index * 5 + 4), final: true)
185 }
186 growing.accept(text: "Full-page transcript words.", start: 90, end: 91, final: false)
187 await snapshot(growing)
188 try? await Task.sleep(for: .seconds(4))
189 growing.accept(text: "Full-page transcript words.", start: 90, end: 91, final: true)
190 growing.accept(text: "Newest transcript words.", start: 95, end: 96, final: false)
191 await snapshot(growing)
192 }
193 return
194 }
195 var value = LocalTranscript()
196 for index in 0..<16 {
197 value.accept(text: "Transcript card \(index + 1). Words from the active session remain on this device.",
198 start: Double(index * 5), end: Double(index * 5 + 4), final: true)
199 }
200 value.accept(text: "Last live words.", start: 80, end: 81, final: false)
201 await snapshot(value)
202 let initial = value
203 Task {
204 try? await Task.sleep(for: .seconds(2))
205 var next = initial
206 next.accept(text: "Last live words.", start: 80, end: 81, final: true)
207 next.accept(text: "Latest incoming words.", start: 85, end: 86, final: false)
208 await snapshot(next)
209 }
210 }
211 func finish() async throws -> LocalTranscript {
212 try await Task.sleep(for: .milliseconds(500))
213 var value = LocalTranscript()
214 value.accept(text: "Completed transcript.", start: 0, end: 1, final: true)
215 Task {
216 try? await Task.sleep(for: .seconds(2))
217 var late = LocalTranscript()
218 late.accept(text: "LATE WORDS MUST NEVER APPEAR", start: 2, end: 3, final: true)
219 await snapshot(late)
220 }
221 return value
222 }
223 func cancel() async {}
224}
225#endif