💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Enable shared linting for Ensu iOS
Manav Rathidd62e037f1ed
diff --git a/apple/.swiftlint.yml b/apple/.swiftlint.ymlindex b814018b52..00baf1b3a7 100644--- a/apple/.swiftlint.yml+++ b/apple/.swiftlint.yml@@ -16,6 +16,6 @@ empty_count:only_after_dot: trueexcluded:- - apps/ensu # TODO: Include Ensu.+ - apps/ensu/Ensu/Generated/ensu.swift- apps/cast/Cast/Generated/cast.swift- .builddiff --git a/apple/apps/ensu/Ensu/Chat/ChatView.swift b/apple/apps/ensu/Ensu/Chat/ChatView.swiftindex 6c1d597569..f1c0baa6af 100644--- a/apple/apps/ensu/Ensu/Chat/ChatView.swift+++ b/apple/apps/ensu/Ensu/Chat/ChatView.swift@@ -81,7 +81,8 @@ struct ChatView: View {guard value.startLocation.x <= 24 else { return }let horizontal = value.translation.widthlet vertical = value.translation.height- guard abs(horizontal) > abs(vertical), horizontal > 40 else { return }+ guard abs(horizontal) > abs(vertical), horizontal > 40+ else { return }viewState.isDrawerOpen = true})@@ -96,7 +97,8 @@ struct ChatView: View {.onEnded { value inlet horizontal = value.translation.widthlet vertical = value.translation.height- guard abs(horizontal) > abs(vertical), horizontal < -40 else { return }+ guard abs(horizontal) > abs(vertical), horizontal < -40+ else { return }viewState.isDrawerOpen = false})@@ -116,7 +118,8 @@ struct ChatView: View {isInputFocused = falseviewState.wasDrawerOpen = true} else if viewState.wasDrawerOpen {- let shouldRestoreFocus = viewModel.isModelDownloaded+ let shouldRestoreFocus =+ viewModel.isModelDownloaded&& !viewModel.isChatUnsupported&& !viewModel.isDownloading&& !viewModel.isGenerating@@ -164,9 +167,12 @@ struct ChatView: View {handleSignInRequest()}}- .sheet(item: $viewState.pendingWhatsNew, onDismiss: {- markWhatsNewSeen()- }) { pending in+ .sheet(+ item: $viewState.pendingWhatsNew,+ onDismiss: {+ markWhatsNewSeen()+ }+ ) { pending inWhatsNewSheet(entries: pending.entries) {markWhatsNewSeen()}@@ -181,14 +187,18 @@ struct ChatView: View {secondaryButton: .cancel())}- .alert("Chat unavailable on this device", isPresented: $viewModel.showUnsupportedDeviceDialog) {+ .alert(+ "Chat unavailable on this device", isPresented: $viewModel.showUnsupportedDeviceDialog+ ) {Button("Got it") {viewModel.dismissUnsupportedDeviceDialog()}} message: {Text(viewModel.unsupportedDeviceMessage)}- .confirmationDialog("Conversation too long", isPresented: overflowDialogPresented, titleVisibility: .visible) {+ .confirmationDialog(+ "Conversation too long", isPresented: overflowDialogPresented, titleVisibility: .visible+ ) {Button("Continue") {viewModel.confirmOverflowTrim()}@@ -196,7 +206,9 @@ struct ChatView: View {viewModel.cancelOverflowDialog()}} message: {- Text("This conversation is too long for the model to process. Some older messages will be dropped to make room.")+ Text(+ "This conversation is too long for the model to process. Some older messages will be dropped to make room."+ )}.overlay {if viewState.showSignInComingSoon {@@ -232,7 +244,8 @@ struct ChatView: View {private func mainContent(showsMenuButton: Bool) -> some View {VStack(spacing: 0) {ChatAppBar(- sessionTitle: viewModel.currentSessionId.map { viewModel.sessionTitle(for: $0) } ?? "New chat",+ sessionTitle: viewModel.currentSessionId.map { viewModel.sessionTitle(for: $0) }+ ?? "New chat",showBrand: viewModel.messages.isEmpty,showSignIn: false,showsMenuButton: showsMenuButton,@@ -257,7 +270,8 @@ struct ChatView: View {.animation(.easeInOut(duration: 0.32))ZStack(alignment: .bottom) {- let shouldShowDownloadOnboarding = !viewModel.isModelDownloaded && !viewModel.isChatUnsupported+ let shouldShowDownloadOnboarding =+ !viewModel.isModelDownloaded && !viewModel.isChatUnsupportedMessageListView(messages: viewModel.messages,@@ -266,14 +280,17 @@ struct ChatView: View {isGenerating: viewModel.isGenerating,sessionId: viewModel.currentSessionId,keyboardHeight: keyboard.height,- inputBarHeight: (viewModel.isModelDownloaded || viewModel.isChatUnsupported) ? viewState.inputBarHeight : 0,+ inputBarHeight: (viewModel.isModelDownloaded || viewModel.isChatUnsupported)+ ? viewState.inputBarHeight : 0,emptyStateTitle: "Welcome",emptyStateSubtitle: "Start typing to begin a conversation",onEdit: { message inviewModel.beginEditing(message: message)},onCopy: { message in- copyToPasteboard(message.role == .assistant ? cleanAssistantText(storedText: message.text) : message.text)+ copyToPasteboard(+ message.role == .assistant+ ? cleanAssistantText(storedText: message.text) : message.text)showToast("Copied to clipboard", duration: 1)},onRetry: { message indiff --git a/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift b/apple/apps/ensu/Ensu/Chat/ChatViewModel.swiftindex 6caef076b1..ce413c78db 100644--- a/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift+++ b/apple/apps/ensu/Ensu/Chat/ChatViewModel.swift@@ -22,7 +22,8 @@ final class ChatViewModel: ObservableObject {formatter.dateFormat = "yyyy-MM-dd"return formatter}()- private static let systemPromptDatePlaceholder = ConfigDefaults.shared.systemPromptDatePlaceholder+ private static let systemPromptDatePlaceholder = ConfigDefaults.shared+ .systemPromptDatePlaceholderprivate static let defaultGenerationMaxTokens = 8_192private static let overflowSafetyTokens = 256private static let imageTokenEstimate = 768@@ -48,8 +49,9 @@ final class ChatViewModel: ObservableObject {var displayedStreamingResponse: String {guard let activeSession = activeGenerationSessionId,- activeSession == currentSessionId,- activeGenerationId != nil else {+ activeSession == currentSessionId,+ activeGenerationId != nil+ else {return ""}return streamingResponse@@ -57,8 +59,9 @@ final class ChatViewModel: ObservableObject {var displayedStreamingParentId: UUID? {guard let activeSession = activeGenerationSessionId,- activeSession == currentSessionId,- activeGenerationId != nil else {+ activeSession == currentSessionId,+ activeGenerationId != nil+ else {return nil}return streamingParentId@@ -101,7 +104,7 @@ final class ChatViewModel: ObservableObject {private var sessionSummaries: [String: String] = [:]private var sessionSummaryTask: Task<Void, Never>?private var reloadTask: Task<Void, Never>?- private let rootId = UUID(uuidString: "00000000-0000-0000-0000-000000000000")!+ private let rootId = UUID(uuid: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))private var generationTask: Task<Void, Never>?private var modelDownloadTask: Task<Void, Never>?private var voiceTransientErrorTask: Task<Void, Never>?@@ -118,10 +121,12 @@ final class ChatViewModel: ObservableObject {init(assetStore: AssetStore) async {logger.info("Initializing")- let summaries = Self.loadSessionSummaries().reduce(into: [String: String]()) { result, item in+ let summaries = Self.loadSessionSummaries().reduce(into: [String: String]()) {+ result, item inresult[item.key.lowercased()] = item.value}- let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ let baseDir =+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?? FileManager.default.temporaryDirectorylet config = ConfigDefaults.shared@@ -132,25 +137,34 @@ final class ChatViewModel: ObservableObject {modelDir: assetStore.assetDir(transcription).path,vadModelPath: assetStore.voiceActivityModelPath().path)- let provider = LlmProvider(assetStore: assetStore, transcriber: transcriber, knowledgeEmbedding: config.knowledgeEmbedding)+ let provider = LlmProvider(+ assetStore: assetStore, transcriber: transcriber,+ knowledgeEmbedding: config.knowledgeEmbedding)let notesStore = NotesStore(provider: provider)provider.modelMaintenance = notesStore- let voiceTranscriber = VoiceTranscriptionService(transcriber: transcriber, assetStore: assetStore)+ let voiceTranscriber = VoiceTranscriptionService(+ transcriber: transcriber, assetStore: assetStore)voiceTranscriber.modelMaintenance = notesStorelet knowledgeProvider = KnowledgeProvider(assetStore: assetStore)- let knowledgeStore = KnowledgeStore(datasets: config.knowledgeDatasets, provider: knowledgeProvider)+ let knowledgeStore = KnowledgeStore(+ datasets: config.knowledgeDatasets, provider: knowledgeProvider)let dbDir = baseDir.appendingPathComponent("llmchat", isDirectory: true)- try? FileManager.default.createDirectory(at: dbDir, withIntermediateDirectories: true, attributes: nil)+ try? FileManager.default.createDirectory(+ at: dbDir, withIntermediateDirectories: true, attributes: nil)let attachmentsDir = dbDir.appendingPathComponent("chat_attachments", isDirectory: true)- try? FileManager.default.createDirectory(at: attachmentsDir, withIntermediateDirectories: true, attributes: nil)+ try? FileManager.default.createDirectory(+ at: attachmentsDir, withIntermediateDirectories: true, attributes: nil)let chatDbPath = dbDir.appendingPathComponent("llmchat.db").path- let hasChatData = FileManager.default.fileExists(atPath: chatDbPath) ||- (try? FileManager.default.contentsOfDirectory(atPath: attachmentsDir.path).isEmpty) != true+ let hasChatData =+ FileManager.default.fileExists(atPath: chatDbPath)+ || (try? FileManager.default.contentsOfDirectory(atPath: attachmentsDir.path).isEmpty)+ != truelet chatDbKey: Datado {- chatDbKey = try await CredentialStore.shared.getOrCreateChatDbKey(hasChatData: hasChatData)+ chatDbKey = try await CredentialStore.shared.getOrCreateChatDbKey(+ hasChatData: hasChatData)} catch {fatalError("Failed to load chat DB key: \(error)")}@@ -240,8 +254,8 @@ final class ChatViewModel: ObservableObject {}static let unsupportedDeviceMessage =- "This device doesn't have enough memory to run Ensu's AI model. " +- "You can view existing chats, but can't send new messages."+ "This device doesn't have enough memory to run Ensu's AI model. "+ + "You can view existing chats, but can't send new messages."private func reopenChatStoreIfNeeded(force: Bool = false) {let hasChatDb = FileManager.default.fileExists(atPath: chatDbPath)@@ -289,7 +303,9 @@ final class ChatViewModel: ObservableObject {}func sessionTitle(for sessionId: UUID) -> String {- guard let title = sessions.first(where: { $0.id == sessionId })?.title else { return "Chat" }+ guard let title = sessions.first(where: { $0.id == sessionId })?.title else {+ return "Chat"+ }return Self.sessionTitle(from: title, fallback: "Chat")}@@ -322,7 +338,11 @@ final class ChatViewModel: ObservableObject {if let nodes = messageStore[session.id] {for node in nodes {- logger.info("Message deleted", details: "id=\(node.id.uuidString) session=\(session.id.uuidString) role=\(node.role.rawValue)")+ logger.info(+ "Message deleted",+ details:+ "id=\(node.id.uuidString) session=\(session.id.uuidString) role=\(node.role.rawValue)"+ )}}logger.info("Session deleted", details: "id=\(session.id.uuidString)")@@ -385,8 +405,9 @@ final class ChatViewModel: ObservableObject {}guard !isGenerating,- !isDownloading,- editingMessageId == nil else {+ !isDownloading,+ editingMessageId == nil+ else {return}@@ -397,10 +418,8 @@ final class ChatViewModel: ObservableObject {},shouldStartRecording: { [weak self] inguard let self else { return false }- return self.currentSessionId == voiceSessionId &&- !self.isGenerating &&- !self.isDownloading &&- self.editingMessageId == nil+ return self.currentSessionId == voiceSessionId && !self.isGenerating+ && !self.isDownloading && self.editingMessageId == nil})}@@ -446,8 +465,9 @@ final class ChatViewModel: ObservableObject {func addImageAttachment(data: Data, fileName: String?) {guard !isGenerating,- !isDownloading,- draftImageAttachmentCount < ChatAttachmentLimits.maxImagesPerMessage else { return }+ !isDownloading,+ draftImageAttachmentCount < ChatAttachmentLimits.maxImagesPerMessage+ else { return }isProcessingAttachments = trueTask.detached { [weak self] in@@ -493,15 +513,15 @@ final class ChatViewModel: ObservableObject {}private nonisolated func normalizedJpegAttachmentName(_ fileName: String?) -> String {- let raw = fileName?+ let raw =+ fileName?.replacingOccurrences(of: "\0", with: "").replacingOccurrences(of: "\\", with: "/").split(separator: "/").last.map(String.init)?- .trimmingCharacters(in: .whitespacesAndNewlines)- let cleaned = raw?.isEmpty == false ? raw! : "photo"- let base = (cleaned as NSString).deletingPathExtension+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ let base = (raw as NSString).deletingPathExtensionreturn "\(base.isEmpty ? "photo" : base).jpg"}@@ -514,7 +534,9 @@ final class ChatViewModel: ObservableObject {do {let id = UUID()let storedUrl = try self.copyAttachment(from: url, attachmentId: id)- let size = (try? FileManager.default.attributesOfItem(atPath: storedUrl.path)[.size] as? NSNumber)?.int64Value ?? 0+ let size =+ (try? FileManager.default.attributesOfItem(atPath: storedUrl.path)[.size]+ as? NSNumber)?.int64Value ?? 0let attachment = ChatAttachment(id: id,name: url.lastPathComponent,@@ -539,9 +561,10 @@ final class ChatViewModel: ObservableObject {}private func discardUnstoredAttachments(_ attachments: [ChatAttachment]) {- let storedIds = Set(messageStore.values.flatMap { messages in- messages.flatMap { $0.attachments.map(\.id) }- })+ let storedIds = Set(+ messageStore.values.flatMap { messages in+ messages.flatMap { $0.attachments.map(\.id) }+ })for attachment in attachments where !storedIds.contains(attachment.id) {if let url = attachment.url {try? FileManager.default.removeItem(at: url)@@ -556,17 +579,20 @@ final class ChatViewModel: ObservableObject {) {let referenced: Set<String>do {- referenced = Set(try sessions.flatMap { session in- try chatDb.getMessages(sessionUuid: session.uuid)- .flatMap { $0.attachments.map(\.id) }- })+ referenced = Set(+ try sessions.flatMap { session in+ try chatDb.getMessages(sessionUuid: session.uuid)+ .flatMap { $0.attachments.map(\.id) }+ })} catch {return}- guard let files = try? FileManager.default.contentsOfDirectory(- at: attachmentsDir,- includingPropertiesForKeys: nil- ) else { return }+ guard+ let files = try? FileManager.default.contentsOfDirectory(+ at: attachmentsDir,+ includingPropertiesForKeys: nil+ )+ else { return }for file in files where !referenced.contains(file.lastPathComponent) {try? FileManager.default.removeItem(at: file)}@@ -629,19 +655,22 @@ final class ChatViewModel: ObservableObject {)}- guard let inserted = try? chatDb.insertMessage(- sessionUuid: sessionId.uuidString,- sender: .selfUser,- text: trimmed,- parentMessageUuid: parentId?.uuidString,- attachments: meta- ), let messageId = UUID(uuidString: inserted.uuid) else {+ guard+ let inserted = try? chatDb.insertMessage(+ sessionUuid: sessionId.uuidString,+ sender: .selfUser,+ text: trimmed,+ parentMessageUuid: parentId?.uuidString,+ attachments: meta+ ), let messageId = UUID(uuidString: inserted.uuid)+ else {return}logger.info("Sent message",- details: "id=\(messageId.uuidString) session=\(sessionId.uuidString) len=\(trimmed.count) attachments=\(attachments.count) edited=\(editingMessageId != nil)"+ details:+ "id=\(messageId.uuidString) session=\(sessionId.uuidString) len=\(trimmed.count) attachments=\(attachments.count) edited=\(editingMessageId != nil)")let timestamp = Date(timeIntervalSince1970: Double(inserted.createdAtUs) / 1_000_000.0)@@ -679,7 +708,11 @@ final class ChatViewModel: ObservableObject {func confirmOverflowTrim() {guard let pendingOverflow else { return }- guard let node = messageStore[pendingOverflow.sessionId]?.first(where: { $0.id == pendingOverflow.messageId }) else {+ guard+ let node = messageStore[pendingOverflow.sessionId]?.first(where: {+ $0.id == pendingOverflow.messageId+ })+ else {cancelOverflowDialog()return}@@ -717,11 +750,16 @@ final class ChatViewModel: ObservableObject {guard let self else { return }let size = await provider.missingModelDownloadSize(selection)await MainActor.run {- guard self.modelReadyKey(for: self.modelSettings.currentSelection()) == self.modelReadyKey(for: selection) else {+ guard+ self.modelReadyKey(for: self.modelSettings.currentSelection())+ == self.modelReadyKey(for: selection)+ else {return}- if self.sharedModelReadyTask == nil &&- (self.downloadToast?.phase == .downloading || self.downloadToast?.phase == .loading) {+ if self.sharedModelReadyTask == nil+ && (self.downloadToast?.phase == .downloading+ || self.downloadToast?.phase == .loading)+ {self.downloadToast = nilself.isDownloading = falseself.clearDownloadProgressMemory()@@ -755,7 +793,8 @@ final class ChatViewModel: ObservableObject {}return} catch {- if isCancellation(error) || !shouldRetryModelDownload(error, retryCount: retryCount) {+ if isCancellation(error) || !shouldRetryModelDownload(error, retryCount: retryCount)+ {throw error}retryCount += 1@@ -943,12 +982,16 @@ final class ChatViewModel: ObservableObject {let userNode: MessageNode?if message.isSynthetic {guard let syntheticIndex = messages.firstIndex(where: { $0.id == message.id }),- syntheticIndex > 0 else { return }+ syntheticIndex > 0+ else { return }let parentMessage = messages[syntheticIndex - 1]guard parentMessage.role == .user else { return }userNode = messageStore[sessionId]?.first(where: { $0.id == parentMessage.id })} else {- guard let parentId = messageStore[sessionId]?.first(where: { $0.id == message.id })?.parentId else { return }+ guard+ let parentId = messageStore[sessionId]?.first(where: { $0.id == message.id })?+ .parentId+ else { return }userNode = messageStore[sessionId]?.first(where: { $0.id == parentId })}guard let userNode else { return }@@ -969,7 +1012,9 @@ final class ChatViewModel: ObservableObject {stopGenerating()}guard let sessionId = currentSessionId else { return }- guard let node = messageStore[sessionId]?.first(where: { $0.id == message.id }) else { return }+ guard let node = messageStore[sessionId]?.first(where: { $0.id == message.id }) else {+ return+ }let parentKey = node.parentId?.uuidString ?? "__root__"let parentId = node.parentId ?? rootIdlet siblings = dedupeSiblings(childrenFor(sessionId: sessionId, parentId: parentId))@@ -985,10 +1030,14 @@ final class ChatViewModel: ObservableObject {private func createSessionForDraft() -> UUID {let created = (try? chatDb.createSession(title: "New chat"))let sessionId = created.flatMap { UUID(uuidString: $0.uuid) } ?? UUID()- let updatedAt = created.map { Date(timeIntervalSince1970: Double($0.updatedAtUs) / 1_000_000.0) } ?? Date()+ let updatedAt =+ created.map { Date(timeIntervalSince1970: Double($0.updatedAtUs) / 1_000_000.0) }+ ?? Date()logger.info("Session created", details: "id=\(sessionId.uuidString)")- let session = ChatSession(id: sessionId, title: created?.title ?? "New chat", lastMessage: "", updatedAt: updatedAt)+ let session = ChatSession(+ id: sessionId, title: created?.title ?? "New chat", lastMessage: "",+ updatedAt: updatedAt)sessions.insert(session, at: 0)currentSessionId = session.idmessageStore[session.id] = []@@ -1042,18 +1091,23 @@ final class ChatViewModel: ObservableObject {let enabledDatasets = knowledgeStore.enabledReadyDatasetslet queryText = userNode.text.trimmingCharacters(in: .whitespacesAndNewlines)if !queryText.isEmpty,- (!enabledDatasets.isEmpty || notesStore.collections.contains(where: { $0.eligible })) {+ (!enabledDatasets.isEmpty+ || notesStore.collections.contains(where: { $0.eligible }))+ {do {let hits = try await provider.withChatModelReleasedForRetrieval { embed intry Task.checkCancellation()let query = try embed(queryText)try Task.checkCancellation()let packs = await knowledgeProvider.search(- datasets: enabledDatasets, query: query, maxHits: knowledgeEmbedding.maxHits+ datasets: enabledDatasets, query: query,+ maxHits: knowledgeEmbedding.maxHits)let notes = try await notesStore.retrieve(query: query)let candidates = try selectMixedGroundingCandidates(- packHits: packs.map { KnowledgePromptHit(datasetId: $0.dataset.stableId, hit: $0.hit) },+ packHits: packs.map {+ KnowledgePromptHit(datasetId: $0.dataset.stableId, hit: $0.hit)+ },notesHits: notes, notesLimit: UInt32(notes.count))return try await notesStore.verify(candidates)@@ -1091,7 +1145,8 @@ final class ChatViewModel: ObservableObject {downloadToast = DownloadToastState(phase: .errorDownload,percent: nil,- status: self.userFacingModelReadyError(error, wasDownloaded: self.provider.isChatModelReady(selection)),+ status: self.userFacingModelReadyError(+ error, wasDownloaded: self.provider.isChatModelReady(selection)),offerRetryDownload: true)activeGenerationId = nil@@ -1114,7 +1169,8 @@ final class ChatViewModel: ObservableObject {if normalHistorySelection.wasTrimmed && overflowBypassMessageId != userNode.id {overflowBypassMessageId = nil- pendingOverflow = PendingOverflow(sessionId: userNode.sessionId, messageId: userNode.id)+ pendingOverflow = PendingOverflow(+ sessionId: userNode.sessionId, messageId: userNode.id)activeGenerationId = nilactiveGenerationSessionId = nilisGenerating = false@@ -1144,10 +1200,11 @@ final class ChatViewModel: ObservableObject {)let knowledgeContext = try? buildGroundedPromptContext(excerpts: knowledgeHits,- maxUtf8Bytes: UInt32(min(- Int(knowledgeEmbedding.maxContextUtf8Bytes),- remainingKnowledgeBytes- ))+ maxUtf8Bytes: UInt32(+ min(+ Int(knowledgeEmbedding.maxContextUtf8Bytes),+ remainingKnowledgeBytes+ )))let candidateSystemPrompt = knowledgeContext.map {"\(normalSystemPrompt)\n\n\($0.text)"@@ -1163,19 +1220,21 @@ final class ChatViewModel: ObservableObject {)}let useKnowledge = knowledgeHistorySelection?.wasTrimmed == false- let historySelection = useKnowledge ?- (knowledgeHistorySelection ?? normalHistorySelection) : normalHistorySelection+ let historySelection =+ useKnowledge+ ? (knowledgeHistorySelection ?? normalHistorySelection) : normalHistorySelectionvar activeCitations = useKnowledge ? (knowledgeContext?.sources ?? []) : []- let effectiveSystemPrompt = useKnowledge ?- (candidateSystemPrompt ?? normalSystemPrompt) : normalSystemPrompt+ let effectiveSystemPrompt =+ useKnowledge ? (candidateSystemPrompt ?? normalSystemPrompt) : normalSystemPromptlet userMessage = LlmMessage(text: prompt.text,role: .user,hasAttachments: !userNode.attachments.isEmpty)- var messages = [- LlmMessage(text: effectiveSystemPrompt, role: .system, hasAttachments: false)- ] + historySelection.messages + [userMessage]+ var messages =+ [+ LlmMessage(text: effectiveSystemPrompt, role: .system, hasAttachments: false)+ ] + historySelection.messages + [userMessage]let buffer = OSAllocatedUnfairLock(initialState: StreamingBuffer())let uiUpdateInterval: TimeInterval = 0.05@@ -1213,7 +1272,8 @@ final class ChatViewModel: ObservableObject {return state.text}guard let self, let snapshot,- self.activeGenerationId == generationId else { return }+ self.activeGenerationId == generationId+ else { return }self.streamingResponse = snapshot}}@@ -1233,16 +1293,18 @@ final class ChatViewModel: ObservableObject {summary = try await runGeneration()} catch {if case LlmError.PromptTooLong = error,- buffer.withLock({ $0.text.isEmpty }),- !activeCitations.isEmpty {+ buffer.withLock({ $0.text.isEmpty }),+ !activeCitations.isEmpty+ {activeCitations = []- messages = [- LlmMessage(- text: normalSystemPrompt,- role: .system,- hasAttachments: false- )- ] + normalHistorySelection.messages + [userMessage]+ messages =+ [+ LlmMessage(+ text: normalSystemPrompt,+ role: .system,+ hasAttachments: false+ )+ ] + normalHistorySelection.messages + [userMessage]summary = try await runGeneration()} else {throw error@@ -1250,16 +1312,23 @@ final class ChatViewModel: ObservableObject {}let snapshot = buffer.withLock { $0 }- finishGeneration(parent: userNode, response: snapshot.text, tokenCount: snapshot.tokenCount, totalTimeMs: summary.totalTimeMs, interrupted: false, generationId: generationId, citations: activeCitations)+ finishGeneration(+ parent: userNode, response: snapshot.text, tokenCount: snapshot.tokenCount,+ totalTimeMs: summary.totalTimeMs, interrupted: false,+ generationId: generationId, citations: activeCitations)} catch {let snapshot = buffer.withLock { $0 }let wasCancelled = stopRequested || isCancellation(error)if activeGenerationId == generationId && !wasCancelled {- let details = "session=\(userNode.sessionId.uuidString) promptLen=\(prompt.text.count) responseLen=\(snapshot.text.count) tokens=\(snapshot.tokenCount)"+ let details =+ "session=\(userNode.sessionId.uuidString) promptLen=\(prompt.text.count) responseLen=\(snapshot.text.count) tokens=\(snapshot.tokenCount)"logger.error("Generation failed", error, details: details)generationErrorMessage = "Response failed. Try again."}- finishGeneration(parent: userNode, response: snapshot.text, tokenCount: snapshot.tokenCount, totalTimeMs: nil, interrupted: true, generationId: generationId, citations: activeCitations)+ finishGeneration(+ parent: userNode, response: snapshot.text, tokenCount: snapshot.tokenCount,+ totalTimeMs: nil, interrupted: true, generationId: generationId,+ citations: activeCitations)}if embeddingAssetInvalid {refreshModelDownloadInfo()@@ -1267,7 +1336,10 @@ final class ChatViewModel: ObservableObject {}}- private func finishGeneration(parent: MessageNode, response: String, tokenCount: Int, totalTimeMs: Int64?, interrupted: Bool, generationId: UUID, citations: [GroundedSource] = []) {+ private func finishGeneration(+ parent: MessageNode, response: String, tokenCount: Int, totalTimeMs: Int64?,+ interrupted: Bool, generationId: UUID, citations: [GroundedSource] = []+ ) {let rawText = response.trimmingCharacters(in: .whitespacesAndNewlines)let trimmed: Stringif rawText.isEmpty {@@ -1280,16 +1352,18 @@ final class ChatViewModel: ObservableObject {)} catch {logger.error("Assistant source finalization failed", error)- trimmed = (try? finalizeGroundedAssistantText(- rawAssistantText: rawText,- sources: []- )) ?? ""+ trimmed =+ (try? finalizeGroundedAssistantText(+ rawAssistantText: rawText,+ sources: []+ )) ?? ""}}let isActiveGeneration = activeGenerationId == generationIdif trimmed.isEmpty {if isActiveGeneration && !interrupted && generationErrorMessage == nil {- let details = "session=\(parent.sessionId.uuidString) promptLen=\(parent.text.count)"+ let details =+ "session=\(parent.sessionId.uuidString) promptLen=\(parent.text.count)"logger.warning("Generation returned empty response", details: details)generationErrorMessage = "No response from model. Try again."}@@ -1311,8 +1385,13 @@ final class ChatViewModel: ObservableObject {)if let assistantId = UUID(uuidString: inserted.uuid) {- logger.info("Message created", details: "id=\(assistantId.uuidString) session=\(parent.sessionId.uuidString) role=assistant")- let timestamp = Date(timeIntervalSince1970: Double(inserted.createdAtUs) / 1_000_000.0)+ logger.info(+ "Message created",+ details:+ "id=\(assistantId.uuidString) session=\(parent.sessionId.uuidString) role=assistant"+ )+ let timestamp = Date(+ timeIntervalSince1970: Double(inserted.createdAtUs) / 1_000_000.0)let assistant = MessageNode(id: assistantId,sessionId: parent.sessionId,@@ -1327,24 +1406,31 @@ final class ChatViewModel: ObservableObject {messageStore[parent.sessionId, default: []].append(assistant)invalidateChildrenCache(for: parent.sessionId)- updateSelection(for: parent.sessionId, parentId: parent.id, childId: assistant.id)- updateSessionPreview(sessionId: parent.sessionId, preview: cleanAssistantText(storedText: trimmed), date: assistant.timestamp)+ updateSelection(+ for: parent.sessionId, parentId: parent.id, childId: assistant.id)+ updateSessionPreview(+ sessionId: parent.sessionId,+ preview: cleanAssistantText(storedText: trimmed),+ date: assistant.timestamp)} else {logger.warning("Skipping assistant message persistence",- details: "session=\(parent.sessionId.uuidString) parent=\(parent.id.uuidString) interrupted=\(interrupted) reason=invalid_uuid"+ details:+ "session=\(parent.sessionId.uuidString) parent=\(parent.id.uuidString) interrupted=\(interrupted) reason=invalid_uuid")}} catch {logger.warning("Skipping assistant message persistence",- details: "session=\(parent.sessionId.uuidString) parent=\(parent.id.uuidString) interrupted=\(interrupted) error=\(error)"+ details:+ "session=\(parent.sessionId.uuidString) parent=\(parent.id.uuidString) interrupted=\(interrupted) error=\(error)")}} else {logger.info("Dropped stale generation response",- details: "session=\(parent.sessionId.uuidString) parent=\(parent.id.uuidString) interrupted=\(interrupted)"+ details:+ "session=\(parent.sessionId.uuidString) parent=\(parent.id.uuidString) interrupted=\(interrupted)")}}@@ -1398,7 +1484,8 @@ final class ChatViewModel: ObservableObject {logger.info("Model download complete", details: progress.status)modelDownloadLoggedStart = false}- downloadToast = DownloadToastState(phase: .ready, percent: 100, status: progress.status, offerRetryDownload: false)+ downloadToast = DownloadToastState(+ phase: .ready, percent: 100, status: progress.status, offerRetryDownload: false)isDownloading = falseisModelDownloaded = provider.isModelDownloaded(modelSettings.currentSelection())modelDownloadSizeBytes = nil@@ -1430,14 +1517,18 @@ final class ChatViewModel: ObservableObject {guard let id = UUID(uuidString: session.uuid) else { return nil }let messages = (try? chatDb.getMessages(sessionUuid: session.uuid)) ?? []let sortedMessages = messages.sorted { $0.createdAtUs < $1.createdAtUs }- let firstUserMessage = sortedMessages.first(where: { $0.sender == .selfUser })?.text ?? ""+ let firstUserMessage =+ sortedMessages.first(where: { $0.sender == .selfUser })?.text ?? ""let lastMessageNode = sortedMessages.last- let lastMessage = lastMessageNode.map { message in- message.sender == .other ? cleanAssistantText(storedText: message.text) : message.text- } ?? ""+ let lastMessage =+ lastMessageNode.map { message in+ message.sender == .other+ ? cleanAssistantText(storedText: message.text) : message.text+ } ?? ""let summary = summaries[session.uuid.lowercased()]- let isPlaceholderTitle = session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||- session.title.caseInsensitiveCompare("New chat") == .orderedSame+ let isPlaceholderTitle =+ session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ || session.title.caseInsensitiveCompare("New chat") == .orderedSamelet seedTitle = summary ?? (isPlaceholderTitle ? firstUserMessage : session.title)let title = Self.sessionTitle(from: seedTitle, fallback: session.title)let updatedAtUs = lastMessageNode?.createdAtUs ?? session.updatedAtUs@@ -1462,9 +1553,10 @@ final class ChatViewModel: ObservableObject {let loaded = (try? chatDb.listSessions()) ?? []let refreshed = Self.buildSessions(from: loaded, chatDb: chatDb, summaries: summaries)- let resolved = selected.flatMap { id in- refreshed.first(where: { $0.id == id })?.id- } ?? (selected == nil ? nil : refreshed.first?.id)+ let resolved =+ selected.flatMap { id in+ refreshed.first(where: { $0.id == id })?.id+ } ?? (selected == nil ? nil : refreshed.first?.id)if Task.isCancelled { return }@@ -1485,9 +1577,12 @@ final class ChatViewModel: ObservableObject {self.childrenByParentCache = [:]for session in refreshed {- if shouldPreserveMessages, session.id == resolved, let nodes = preservedMessageStore[session.id] {+ if shouldPreserveMessages, session.id == resolved,+ let nodes = preservedMessageStore[session.id]+ {self.messageStore[session.id] = nodes- self.branchSelections[session.id] = preservedBranchSelections[session.id] ?? [:]+ self.branchSelections[session.id] =+ preservedBranchSelections[session.id] ?? [:]} else {self.messageStore[session.id] = []self.branchSelections[session.id] = [:]@@ -1601,14 +1696,15 @@ final class ChatViewModel: ObservableObject {let next = i + 1 < messages.count ? messages[i + 1] : nillet isLastAndGenerating = i == messages.count - 1 && isGeneratingif next?.role != .assistant && !isLastAndGenerating {- augmented.append(RenderedChatMessage(- id: deterministicSyntheticMessageId(parentId: msg.id),- role: .assistant,- text: "Response was interrupted",- timestamp: msg.timestamp,- isInterrupted: true,- isSynthetic: true- ))+ augmented.append(+ RenderedChatMessage(+ id: deterministicSyntheticMessageId(parentId: msg.id),+ role: .assistant,+ text: "Response was interrupted",+ timestamp: msg.timestamp,+ isInterrupted: true,+ isSynthetic: true+ ))}}}@@ -1622,17 +1718,21 @@ final class ChatViewModel: ObservableObject {return UUID(uuid: uuid)}- private func buildSelectedPath(for sessionId: UUID, childrenMap: [UUID: [MessageNode]]) -> [MessageNode] {+ private func buildSelectedPath(for sessionId: UUID, childrenMap: [UUID: [MessageNode]])+ -> [MessageNode]+ {guard let nodes = messageStore[sessionId], !nodes.isEmpty else { return [] }let byId = Dictionary(uniqueKeysWithValues: nodes.map { ($0.id, $0) })- let roots = dedupeSiblings(nodes.filter { node in- guard let parentId = node.parentId else { return true }- return byId[parentId] == nil- })+ let roots = dedupeSiblings(+ nodes.filter { node in+ guard let parentId = node.parentId else { return true }+ return byId[parentId] == nil+ })guard !roots.isEmpty else { return [] }let selectionMap = branchSelections[sessionId, default: [:]]- var current = selectChild(selectionMap: selectionMap, selectionKey: "__root__", candidates: roots)+ var current = selectChild(+ selectionMap: selectionMap, selectionKey: "__root__", candidates: roots)var path: [MessageNode] = []var visited = Set<UUID>()@@ -1641,15 +1741,19 @@ final class ChatViewModel: ObservableObject {if node.id == streamingParentId { break }let children = dedupeSiblings(childrenMap[node.id] ?? [])if children.isEmpty { break }- current = selectChild(selectionMap: selectionMap, selectionKey: node.id.uuidString, candidates: children)+ current = selectChild(+ selectionMap: selectionMap, selectionKey: node.id.uuidString, candidates: children)}return path}- private func selectChild(selectionMap: [String: UUID], selectionKey: String, candidates: [MessageNode]) -> MessageNode? {+ private func selectChild(+ selectionMap: [String: UUID], selectionKey: String, candidates: [MessageNode]+ ) -> MessageNode? {guard !candidates.isEmpty else { return nil }if let selectedId = selectionMap[selectionKey],- let selected = candidates.first(where: { $0.id == selectedId }) {+ let selected = candidates.first(where: { $0.id == selectedId })+ {return selected}return candidates.last@@ -1695,7 +1799,9 @@ final class ChatViewModel: ObservableObject {private func isDuplicate(_ lhs: MessageNode, _ rhs: MessageNode) -> Bool {guard lhs.role == rhs.role else { return false }guard lhs.text == rhs.text else { return false }- guard attachmentSignature(lhs.attachments) == attachmentSignature(rhs.attachments) else { return false }+ guard attachmentSignature(lhs.attachments) == attachmentSignature(rhs.attachments) else {+ return false+ }return abs(lhs.timestamp.timeIntervalSince(rhs.timestamp)) <= 2}@@ -1712,12 +1818,14 @@ final class ChatViewModel: ObservableObject {sessions = sessions.map { session inguard session.id == sessionId else { return session }var updated = session- let isPlaceholderTitle = session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||- session.title.caseInsensitiveCompare("New chat") == .orderedSame+ let isPlaceholderTitle =+ session.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ || session.title.caseInsensitiveCompare("New chat") == .orderedSameif isPlaceholderTitle {let updatedTitle = Self.sessionTitle(from: preview, fallback: session.title)if updatedTitle != session.title {- _ = try? chatDb.updateSessionTitle(uuid: sessionId.uuidString, title: updatedTitle)+ _ = try? chatDb.updateSessionTitle(+ uuid: sessionId.uuidString, title: updatedTitle)}updated.title = updatedTitle}@@ -1804,7 +1912,9 @@ final class ChatViewModel: ObservableObject {}private static func loadSessionSummaries() -> [String: String] {- guard let data = UserDefaults.standard.data(forKey: Self.sessionSummaryStoreKey) else { return [:] }+ guard let data = UserDefaults.standard.data(forKey: Self.sessionSummaryStoreKey) else {+ return [:]+ }return (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:]}@@ -1826,7 +1936,8 @@ final class ChatViewModel: ObservableObject {.trimmingCharacters(in: .whitespacesAndNewlines)}- nonisolated static func sessionTitle(from text: String, fallback: String = "New chat") -> String {+ nonisolated static func sessionTitle(from text: String, fallback: String = "New chat") -> String+ {let trimmed = sanitizeTitleText(text)guard !trimmed.isEmpty else { return fallback }if trimmed.count <= Self.sessionTitleMaxLength {@@ -1849,7 +1960,7 @@ final class ChatViewModel: ObservableObject {let messages = [LlmMessage(text: sessionSummarySystemPrompt, role: .system, hasAttachments: false),- LlmMessage(text: cleanedInput, role: .user, hasAttachments: false)+ LlmMessage(text: cleanedInput, role: .user, hasAttachments: false),]let buffer = OSAllocatedUnfairLock(initialState: "")@@ -1867,7 +1978,8 @@ final class ChatViewModel: ObservableObject {}} catch {let fallbackSummary = summarizeQuestion(fallback)- return fallbackSummary.isEmpty ? nil : sessionTitle(from: fallbackSummary, fallback: fallback)+ return fallbackSummary.isEmpty+ ? nil : sessionTitle(from: fallbackSummary, fallback: fallback)}let raw = sanitizeTitleText(buffer.withLock { $0 })@@ -1926,7 +2038,8 @@ final class ChatViewModel: ObservableObject {return Self.unsupportedDeviceMessage}if isOutOfStorageError(error) {- return "Not enough storage space to download the model. Please free up space and try again."+ return+ "Not enough storage space to download the model. Please free up space and try again."}return wasDownloaded ? "Model load failed" : "Download failed. Please try again."}@@ -1937,11 +2050,13 @@ final class ChatViewModel: ObservableObject {}private nonisolated func attachmentsDirectory() throws -> URL {- let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ let base =+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?? FileManager.default.temporaryDirectorylet dir = base.appendingPathComponent("llmchat", isDirectory: true).appendingPathComponent("chat_attachments", isDirectory: true)- try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)+ try FileManager.default.createDirectory(+ at: dir, withIntermediateDirectories: true, attributes: nil)return dir}@@ -2024,9 +2139,11 @@ final class ChatViewModel: ObservableObject {let path = buildSelectedPath(for: sessionId, childrenMap: childrenMap)let historyMessages = path.prefix { $0.id != currentMessageId }- let inputBudget = max(0, limits.contextLength - limits.maxOutput - Self.overflowSafetyTokens)+ let inputBudget = max(+ 0, limits.contextLength - limits.maxOutput - Self.overflowSafetyTokens)let systemTokens = estimateTokens(systemPrompt)- let promptTokens = estimatePromptTokens(promptText: promptText, imageCount: promptImageCount)+ let promptTokens = estimatePromptTokens(+ promptText: promptText, imageCount: promptImageCount)let historyTokens = historyMessages.reduce(0) { total, node intotal + estimateTokens(historyText(node))}@@ -2034,7 +2151,9 @@ final class ChatViewModel: ObservableObject {let remaining = inputBudget - systemTokens - promptTokensif remaining <= 0 || historyMessages.isEmpty {- return HistorySelection(messages: [], inputTokens: inputTokens, inputBudget: inputBudget, wasTrimmed: inputTokens > inputBudget)+ return HistorySelection(+ messages: [], inputTokens: inputTokens, inputBudget: inputBudget,+ wasTrimmed: inputTokens > inputBudget)}let quantum = max(1, inputBudget / 4)@@ -2049,21 +2168,29 @@ final class ChatViewModel: ObservableObject {}var retained = historyMessages[startIndex...]- if retained.isEmpty, let last = historyMessages.last, estimateTokens(historyText(last)) <= remaining {+ if retained.isEmpty, let last = historyMessages.last,+ estimateTokens(historyText(last)) <= remaining+ {retained = historyMessages.suffix(1)}let selected = retained.map { node inlet text = historyText(node)- return LlmMessage(text: text, role: node.role == .user ? .user : .assistant, hasAttachments: !node.attachments.isEmpty)+ return LlmMessage(+ text: text, role: node.role == .user ? .user : .assistant,+ hasAttachments: !node.attachments.isEmpty)}- return HistorySelection(messages: selected, inputTokens: inputTokens, inputBudget: inputBudget, wasTrimmed: inputTokens > inputBudget)+ return HistorySelection(+ messages: selected, inputTokens: inputTokens, inputBudget: inputBudget,+ wasTrimmed: inputTokens > inputBudget)}private func resolveGenerationLimits(_ selection: LlmModelSelection) async -> GenerationLimits {- let contextLength = await provider.loadedContextLength(selection) ?? selection.contextLength ?? 12000- let maxOutput = resolveMaxOutputTokens(configuredMaxTokens: selection.maxTokens, contextLength: contextLength)+ let contextLength =+ await provider.loadedContextLength(selection) ?? selection.contextLength ?? 12000+ let maxOutput = resolveMaxOutputTokens(+ configuredMaxTokens: selection.maxTokens, contextLength: contextLength)return GenerationLimits(contextLength: contextLength, maxOutput: maxOutput)}@@ -2079,15 +2206,19 @@ final class ChatViewModel: ObservableObject {text = cleanAssistantText(storedText: text)if let regex = ChatMessageTagRegex.think {let range = NSRange(text.startIndex..., in: text)- text = regex.stringByReplacingMatches(in: text, options: [], range: range, withTemplate: "")+ text = regex.stringByReplacingMatches(+ in: text, options: [], range: range, withTemplate: "")} else {- text = text.replacingOccurrences(of: "<think>[\\s\\S]*?</think>", with: "", options: .regularExpression)+ text = text.replacingOccurrences(+ of: "<think>[\\s\\S]*?</think>", with: "", options: .regularExpression)}if let regex = ChatMessageTagRegex.todoList {let range = NSRange(text.startIndex..., in: text)- text = regex.stringByReplacingMatches(in: text, options: [], range: range, withTemplate: "")+ text = regex.stringByReplacingMatches(+ in: text, options: [], range: range, withTemplate: "")} else {- text = text.replacingOccurrences(of: "<todo_list>[\\s\\S]*?</todo_list>", with: "", options: .regularExpression)+ text = text.replacingOccurrences(+ of: "<todo_list>[\\s\\S]*?</todo_list>", with: "", options: .regularExpression)}} else if !node.attachments.isEmpty {text += "\n\n[\(node.attachments.count) attachments attached]"@@ -2115,7 +2246,8 @@ final class ChatViewModel: ObservableObject {}private func resolveTemperature() -> Float {- let value = Float(modelSettings.temperature.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))+ let value = Float(+ modelSettings.temperature.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))let resolved = value.map { max(0, $0) } ?? Self.defaultTemperaturereturn min(max(resolved, 0.35), 0.7)}diff --git a/apple/apps/ensu/Ensu/Chat/Components/ChatViewComponents.swift b/apple/apps/ensu/Ensu/Chat/Components/ChatViewComponents.swiftindex 6d26e66c91..008e5d5afa 100644--- a/apple/apps/ensu/Ensu/Chat/Components/ChatViewComponents.swift+++ b/apple/apps/ensu/Ensu/Chat/Components/ChatViewComponents.swift@@ -24,7 +24,8 @@ struct DownloadOnboardingView: View {if let totalBytes, let percent = downloadPercent {let clamped = min(max(percent, 0), 100)let downloaded = Int64(Double(totalBytes) * Double(clamped) / 100.0)- return "Downloading... \(downloaded.formattedFileSize) / \(totalBytes.formattedFileSize)"+ return+ "Downloading... \(downloaded.formattedFileSize) / \(totalBytes.formattedFileSize)"}if let statusText, !statusText.isEmpty {return statusText@@ -143,7 +144,9 @@ struct SignInComingSoonDialog: View {.frame(maxWidth: .infinity).padding(.vertical, EnsuSpacing.md).background(EnsuColor.accent)- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.button, style: .continuous))+ .clipShape(+ RoundedRectangle(+ cornerRadius: EnsuCornerRadius.button, style: .continuous))}.buttonStyle(.plain)}diff --git a/apple/apps/ensu/Ensu/Chat/LaTeXView.swift b/apple/apps/ensu/Ensu/Chat/LaTeXView.swiftindex e07593c1e5..656f7540de 100644--- a/apple/apps/ensu/Ensu/Chat/LaTeXView.swift+++ b/apple/apps/ensu/Ensu/Chat/LaTeXView.swift@@ -52,7 +52,9 @@ private struct MathLabelView: UIViewRepresentable {}func updateUIView(_ view: MathLabelContainerView, context: Context) {- view.update(latex: latex, rawLatex: rawLatex, textColor: textColor, fontSize: fontSize, isInline: isInline)+ view.update(+ latex: latex, rawLatex: rawLatex, textColor: textColor, fontSize: fontSize,+ isInline: isInline)}}@@ -80,10 +82,12 @@ private final class MathLabelContainerView: UIView {height: childSize.height + currentInsets.top + currentInsets.bottom)}- let maxLabelWidth = fallbackLabel.preferredMaxLayoutWidth > 0+ let maxLabelWidth =+ fallbackLabel.preferredMaxLayoutWidth > 0? fallbackLabel.preferredMaxLayoutWidth: CGFloat.greatestFiniteMagnitude- let labelSize = fallbackLabel.sizeThatFits(CGSize(width: maxLabelWidth, height: .greatestFiniteMagnitude))+ let labelSize = fallbackLabel.sizeThatFits(+ CGSize(width: maxLabelWidth, height: .greatestFiniteMagnitude))return CGSize(width: labelSize.width + currentInsets.left + currentInsets.right,height: labelSize.height + currentInsets.top + currentInsets.bottom@@ -102,8 +106,11 @@ private final class MathLabelContainerView: UIView {}}- func update(latex: String, rawLatex: String, textColor: PlatformColor, fontSize: CGFloat, isInline: Bool) {- currentInsets = isInline+ func update(+ latex: String, rawLatex: String, textColor: PlatformColor, fontSize: CGFloat, isInline: Bool+ ) {+ currentInsets =+ isInline? UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1): UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)@@ -125,4 +132,3 @@ private final class MathLabelContainerView: UIView {invalidateIntrinsicContentSize()}}-diff --git a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift b/apple/apps/ensu/Ensu/Chat/MessageInputView.swiftindex 433082e3da..09f08dcc17 100644--- a/apple/apps/ensu/Ensu/Chat/MessageInputView.swift+++ b/apple/apps/ensu/Ensu/Chat/MessageInputView.swift@@ -30,12 +30,14 @@ struct MessageInputView: View {private let placeholder = "Write a message..."private var canSend: Bool {- let hasContent = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty+ let hasContent =+ !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmptyreturn hasContent && !isGenerating && !isDownloading && !voiceInputState.blocksSend}private var isSendEnabled: Bool {- let hasContent = !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty+ let hasContent =+ !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmptyreturn hasContent && !isDownloading && !voiceInputState.blocksSend}@@ -60,7 +62,8 @@ struct MessageInputView: View {VStack(alignment: .leading, spacing: inputStackSpacing) {if !attachments.isEmpty {let hasImageAttachment = attachments.contains { $0.kind == .image }- let maxAttachmentHeight = hasImageAttachment+ let maxAttachmentHeight =+ hasImageAttachment? CGFloat(2) * 76 + EnsuSpacing.sm: CGFloat(3) * 40 + CGFloat(2) * EnsuSpacing.smlet shouldScroll = attachments.count > 4@@ -78,230 +81,255 @@ struct MessageInputView: View {.padding(.horizontal, EnsuSpacing.pageHorizontal)}- if isProcessingAttachments {- HStack(spacing: EnsuSpacing.sm) {- ProgressView()- .scaleEffect(0.8)- Text("Reading attachment...")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)- Spacer()- }- .padding(.horizontal, EnsuSpacing.pageHorizontal)- }-- if let voiceStatus = voiceInputState.statusText {- HStack(spacing: EnsuSpacing.sm) {- switch voiceInputState {- case .downloading, .transcribing:+ if isProcessingAttachments {+ HStack(spacing: EnsuSpacing.sm) {ProgressView().scaleEffect(0.8)- case .recording:- Image("Mic02Icon")- .resizable()- .scaledToFit()- .frame(width: 14, height: 14)- .foregroundStyle(EnsuColor.stopButton)- case .error:- Image(systemName: "exclamationmark.circle")- .font(.system(size: 12, weight: .semibold))- .foregroundStyle(EnsuColor.stopButton)- case .idle:- EmptyView()+ Text("Reading attachment...")+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)+ Spacer()}- Text(voiceStatus)- .font(EnsuTypography.small)- .foregroundStyle(voiceInputState.isError ? EnsuColor.stopButton : EnsuColor.textMuted)- Spacer()+ .padding(.horizontal, EnsuSpacing.pageHorizontal)}- .padding(.horizontal, EnsuSpacing.pageHorizontal)- }- HStack(alignment: .bottom, spacing: EnsuSpacing.sm) {- TextField(placeholder, text: $text, axis: .vertical)- .id(inputResetToken)- .focused($isFocused)- .onChange(of: isFocused) { focused in- if focused {- onUserFocus()+ if let voiceStatus = voiceInputState.statusText {+ HStack(spacing: EnsuSpacing.sm) {+ switch voiceInputState {+ case .downloading, .transcribing:+ ProgressView()+ .scaleEffect(0.8)+ case .recording:+ Image("Mic02Icon")+ .resizable()+ .scaledToFit()+ .frame(width: 14, height: 14)+ .foregroundStyle(EnsuColor.stopButton)+ case .error:+ Image(systemName: "exclamationmark.circle")+ .font(.system(size: 12, weight: .semibold))+ .foregroundStyle(EnsuColor.stopButton)+ case .idle:+ EmptyView()}+ Text(voiceStatus)+ .font(EnsuTypography.small)+ .foregroundStyle(+ voiceInputState.isError+ ? EnsuColor.stopButton : EnsuColor.textMuted)+ Spacer()}- .lineLimit(1...5)- .font(EnsuTypography.message)- .foregroundStyle(EnsuColor.textPrimary)- .textInputAutocapitalization(.sentences)- .padding(.vertical, textFieldPadding)- .onSubmit {- if canSend {- onSend()- isFocused = false- hideKeyboard()- onDismissKeyboard()+ .padding(.horizontal, EnsuSpacing.pageHorizontal)+ }++ HStack(alignment: .bottom, spacing: EnsuSpacing.sm) {+ TextField(placeholder, text: $text, axis: .vertical)+ .id(inputResetToken)+ .focused($isFocused)+ .onChange(of: isFocused) { focused in+ if focused {+ onUserFocus()+ }}- }- .onChange(of: text) { newValue in- if newValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !isFocused {- inputResetToken = UUID()+ .lineLimit(1...5)+ .font(EnsuTypography.message)+ .foregroundStyle(EnsuColor.textPrimary)+ .textInputAutocapitalization(.sentences)+ .padding(.vertical, textFieldPadding)+ .onSubmit {+ if canSend {+ onSend()+ isFocused = false+ hideKeyboard()+ onDismissKeyboard()+ }}- }- .background(- CursorEndSynchronizer(- token: moveCursorToEndToken,- text: text- )- .frame(width: 0, height: 0)- )-- if editingMessage == nil {- let canUseAttachment = !isGenerating &&- !isDownloading &&- !isImageAttachmentLimitReached- PhotosPicker(selection: $selectedPhotoItem, matching: .images) {- Image("Upload01Icon")- .resizable()- .scaledToFit()- .frame(width: attachmentIconSize, height: attachmentIconSize)- .frame(width: 32, height: 32, alignment: .center)- }- .disabled(!canUseAttachment)- .foregroundStyle(canUseAttachment ? EnsuColor.textPrimary : EnsuColor.textMuted)- .simultaneousGesture(TapGesture().onEnded {- if canUseAttachment {- hapticTap()+ .onChange(of: text) { newValue in+ if newValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ && !isFocused+ {+ inputResetToken = UUID()+ }}- })- .onChange(of: selectedPhotoItem) { newItem in- guard let newItem else { return }- guard !isImageAttachmentLimitReached else {- selectedPhotoItem = nil- return+ .background(+ CursorEndSynchronizer(+ token: moveCursorToEndToken,+ text: text+ )+ .frame(width: 0, height: 0)+ )++ if editingMessage == nil {+ let canUseAttachment =+ !isGenerating && !isDownloading && !isImageAttachmentLimitReached+ PhotosPicker(selection: $selectedPhotoItem, matching: .images) {+ Image("Upload01Icon")+ .resizable()+ .scaledToFit()+ .frame(width: attachmentIconSize, height: attachmentIconSize)+ .frame(width: 32, height: 32, alignment: .center)}- Task {- let data = try? await newItem.loadTransferable(type: Data.self)- await MainActor.run {- if let data {- onAddImage(data, nil)+ .disabled(!canUseAttachment)+ .foregroundStyle(+ canUseAttachment ? EnsuColor.textPrimary : EnsuColor.textMuted+ )+ .simultaneousGesture(+ TapGesture().onEnded {+ if canUseAttachment {+ hapticTap()}+ }+ )+ .onChange(of: selectedPhotoItem) { newItem in+ guard let newItem else { return }+ guard !isImageAttachmentLimitReached else {selectedPhotoItem = nil+ return+ }+ Task {+ let data = try? await newItem.loadTransferable(type: Data.self)+ await MainActor.run {+ if let data {+ onAddImage(data, nil)+ }+ selectedPhotoItem = nil+ }}}}- }- if editingMessage == nil {- let isVoiceBusy = voiceInputState.isTranscriptionBusy- let canUseVoice = voiceInputState.isRecording ||- (!isGenerating && !isDownloading && !isVoiceBusy)+ if editingMessage == nil {+ let isVoiceBusy = voiceInputState.isTranscriptionBusy+ let canUseVoice =+ voiceInputState.isRecording+ || (!isGenerating && !isDownloading && !isVoiceBusy)++ Button {+ if voiceInputState.isRecording {+ hapticWarning()+ } else {+ hapticTap()+ isFocused = false+ hideKeyboard()+ onDismissKeyboard()+ }+ onVoiceInput()+ } label: {+ if isVoiceBusy {+ ProgressView()+ .scaleEffect(0.75)+ .frame(width: 32, height: 32)+ } else if voiceInputState.isRecording {+ Image("StopIcon")+ .resizable()+ .scaledToFit()+ .frame(+ width: attachmentIconSize, height: attachmentIconSize+ )+ .foregroundStyle(EnsuColor.stopButton)+ .frame(width: 32, height: 32)+ } else {+ Image("Mic02Icon")+ .resizable()+ .scaledToFit()+ .frame(+ width: attachmentIconSize, height: attachmentIconSize+ )+ .foregroundStyle(+ canUseVoice+ ? EnsuColor.textPrimary : EnsuColor.textMuted+ )+ .frame(width: 32, height: 32)+ }+ }+ .disabled(!canUseVoice)+ }Button {- if voiceInputState.isRecording {+ if isGenerating {hapticWarning()- } else {- hapticTap()+ onStop()+ } else if isSendEnabled {+ hapticMedium()+ onSend()isFocused = falsehideKeyboard()onDismissKeyboard()}- onVoiceInput()} label: {- if isVoiceBusy {- ProgressView()- .scaleEffect(0.75)- .frame(width: 32, height: 32)- } else if voiceInputState.isRecording {- Image("StopIcon")- .resizable()- .scaledToFit()- .frame(width: attachmentIconSize, height: attachmentIconSize)- .foregroundStyle(EnsuColor.stopButton)- .frame(width: 32, height: 32)+ if sendIcon == "StopIcon" {+ ZStack {+ Circle()+ .fill(Color.white)+ .frame(+ width: attachmentIconSize + 6,+ height: attachmentIconSize + 6)+ Image(sendIcon)+ .resizable()+ .scaledToFit()+ .frame(+ width: attachmentIconSize - 4,+ height: attachmentIconSize - 4+ )+ .foregroundStyle(EnsuColor.stopButton)+ }+ .frame(width: 32, height: 32)} else {- Image("Mic02Icon")+ Image(sendIcon).resizable().scaledToFit().frame(width: attachmentIconSize, height: attachmentIconSize)- .foregroundStyle(canUseVoice ? EnsuColor.textPrimary : EnsuColor.textMuted)+ .rotationEffect(+ sendIcon == "Navigation06Icon" ? .degrees(90) : .zero+ )+ .foregroundStyle(sendColor).frame(width: 32, height: 32)}}- .disabled(!canUseVoice)+ .disabled(isDownloading || (!canSend && !isGenerating))}-- Button {- if isGenerating {- hapticWarning()- onStop()- } else if isSendEnabled {- hapticMedium()- onSend()- isFocused = false- hideKeyboard()- onDismissKeyboard()- }- } label: {- if sendIcon == "StopIcon" {- ZStack {- Circle()- .fill(Color.white)- .frame(width: attachmentIconSize + 6, height: attachmentIconSize + 6)- Image(sendIcon)- .resizable()- .scaledToFit()- .frame(width: attachmentIconSize - 4, height: attachmentIconSize - 4)- .foregroundStyle(EnsuColor.stopButton)+ .padding(.horizontal, EnsuSpacing.inputHorizontal)+ .padding(.vertical, inputVerticalPadding)+ .frame(maxWidth: .infinity)+ .background(.ultraThinMaterial)+ .clipShape(+ RoundedRectangle(+ cornerRadius: EnsuCornerRadius.input + 4, style: .continuous)+ )+ .shadow(color: Color.black.opacity(0.12), radius: 10, x: 0, y: 6)+ .overlay(alignment: .topTrailing) {+ if isFocused {+ Button {+ hapticTap()+ isFocused = false+ hideKeyboard()+ onDismissKeyboard()+ } label: {+ Image(systemName: keyboardDismissIconName)+ .font(.system(size: 14, weight: .semibold))+ .foregroundStyle(EnsuColor.textPrimary)+ .frame(width: 32, height: 32)+ .background(.ultraThinMaterial)+ .clipShape(Circle())+ .shadow(color: .black.opacity(0.15), radius: 4, y: 2)}- .frame(width: 32, height: 32)- } else {- Image(sendIcon)- .resizable()- .scaledToFit()- .frame(width: attachmentIconSize, height: attachmentIconSize)- .rotationEffect(sendIcon == "Navigation06Icon" ? .degrees(90) : .zero)- .foregroundStyle(sendColor)- .frame(width: 32, height: 32)+ .offset(y: -(32 + EnsuSpacing.sm))}}- .disabled(isDownloading || (!canSend && !isGenerating))+ .padding(.horizontal, EnsuSpacing.pageHorizontal)+ .padding(.bottom, bottomPadding)}- .padding(.horizontal, EnsuSpacing.inputHorizontal)- .padding(.vertical, inputVerticalPadding)- .frame(maxWidth: .infinity)- .background(.ultraThinMaterial)- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input + 4, style: .continuous))- .shadow(color: Color.black.opacity(0.12), radius: 10, x: 0, y: 6)- .overlay(alignment: .topTrailing) {- if isFocused {- Button {- hapticTap()- isFocused = false- hideKeyboard()- onDismissKeyboard()- } label: {- Image(systemName: keyboardDismissIconName)- .font(.system(size: 14, weight: .semibold))- .foregroundStyle(EnsuColor.textPrimary)- .frame(width: 32, height: 32)- .background(.ultraThinMaterial)- .clipShape(Circle())- .shadow(color: .black.opacity(0.15), radius: 4, y: 2)- }- .offset(y: -(32 + EnsuSpacing.sm))+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(+ GeometryReader { proxy in+ Color.clear+ .preference(key: InputBarHeightKey.self, value: proxy.size.height)}- }- .padding(.horizontal, EnsuSpacing.pageHorizontal)- .padding(.bottom, bottomPadding)+ )}- .frame(maxWidth: .infinity, alignment: .leading)- .background(- GeometryReader { proxy in- Color.clear- .preference(key: InputBarHeightKey.self, value: proxy.size.height)- }- )}+ .padding(.top, EnsuSpacing.sm)}- .padding(.top, EnsuSpacing.sm)-}private let attachmentIconSize: CGFloat = 16@@ -438,8 +466,9 @@ private struct CursorEndSynchronizer: UIViewRepresentable {var currentView: UIView? = viewwhile let candidate = currentView {let inputs = candidate.cursorEndTextInputs()- let target = inputs.first(where: { $0.isFirstResponder }) ??- inputs.first(where: { $0.cursorText == text })+ let target =+ inputs.first(where: { $0.isFirstResponder })+ ?? inputs.first(where: { $0.cursorText == text })if let target {target.moveCursorToEnd()returndiff --git a/apple/apps/ensu/Ensu/Chat/MessageList/MessageListComponents.swift b/apple/apps/ensu/Ensu/Chat/MessageList/MessageListComponents.swiftindex 36fe0d7d50..b6a652faf4 100644--- a/apple/apps/ensu/Ensu/Chat/MessageList/MessageListComponents.swift+++ b/apple/apps/ensu/Ensu/Chat/MessageList/MessageListComponents.swift@@ -91,11 +91,14 @@ struct ImageAttachmentPreview: View {}}- private func fittedPreviewSize(imageSize: CGSize, containerSize: CGSize, padding: CGFloat) -> CGSize {+ private func fittedPreviewSize(imageSize: CGSize, containerSize: CGSize, padding: CGFloat)+ -> CGSize+ {let availableWidth = max(0, containerSize.width - (padding * 2))let availableHeight = max(0, containerSize.height - (padding * 2))- guard imageSize.width > 0, imageSize.height > 0, availableWidth > 0, availableHeight > 0 else {+ guard imageSize.width > 0, imageSize.height > 0, availableWidth > 0, availableHeight > 0+ else {return .zero}@@ -137,7 +140,9 @@ struct QuickLookPreview: UIViewControllerRepresentable {1}- func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {+ func previewController(_ controller: QLPreviewController, previewItemAt index: Int)+ -> QLPreviewItem+ {url as NSURL}}@@ -253,12 +258,15 @@ struct AssistantMessageBubbleView: View {HStack(alignment: .bottom) {VStack(alignment: .leading, spacing: 0) {VStack(alignment: .leading, spacing: EnsuSpacing.sm) {- AssistantMessageRenderer(text: parsed.text, isStreaming: false, storageId: message.id.uuidString)+ AssistantMessageRenderer(+ text: parsed.text, isStreaming: false, storageId: message.id.uuidString)if !parsed.sourceLabels.isEmpty {ViewThatFits(in: .horizontal) {HStack(spacing: EnsuSpacing.sm) { sourceChips(parsed.sourceLabels) }- VStack(alignment: .leading, spacing: EnsuSpacing.sm) { sourceChips(parsed.sourceLabels) }+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {+ sourceChips(parsed.sourceLabels)+ }}}@@ -313,7 +321,9 @@ struct AssistantMessageBubbleView: View {private func sourceChips(_ labels: [String]) -> some View {ForEach(Array(labels.enumerated()), id: \.offset) { _, label in- Button { showSources = true } label: {+ Button {+ showSources = true+ } label: {Text(label).font(EnsuTypography.small).foregroundStyle(EnsuColor.textPrimary)@@ -363,7 +373,9 @@ private struct KnowledgeSourcesSheet: View {Text(reference.documentId).font(EnsuTypography.small).foregroundStyle(EnsuColor.textMuted)- Button { notes.open(reference) } label: {+ Button {+ notes.open(reference)+ } label: {Label("Open note", systemImage: "arrow.up.right.square").frame(minHeight: 44)}@@ -375,7 +387,9 @@ private struct KnowledgeSourcesSheet: View {ViewThatFits(in: .horizontal) {HStack(spacing: EnsuSpacing.lg) { sourceLinks(citation) }- VStack(alignment: .leading, spacing: EnsuSpacing.sm) { sourceLinks(citation) }+ VStack(alignment: .leading, spacing: EnsuSpacing.sm) {+ sourceLinks(citation)+ }}.font(EnsuTypography.small)}@@ -395,7 +409,8 @@ private struct KnowledgeSourcesSheet: View {private func sourceHeader(_ source: GroundedSource, number: Int) -> String {switch source {case .localNote(let reference):- return "SOURCE \(number) · YOUR NOTES" + (reference.collectionLabel.map { " · \($0.uppercased())" } ?? "")+ return "SOURCE \(number) · YOUR NOTES"+ + (reference.collectionLabel.map { " · \($0.uppercased())" } ?? "")case .ensuPack(let citation):return "SOURCE \(number) · ENSU PACK · \(citation.datasetLabel.uppercased())"}@@ -410,13 +425,17 @@ private struct KnowledgeSourcesSheet: View {@ViewBuilderprivate func sourceLinks(_ citation: SourceCitation) -> some View {- Link(destination: URL(string: citation.sourceUrl)!) {- Label("Open source", systemImage: "arrow.up.right.square")- .frame(minHeight: 44)+ if let sourceUrl = URL(string: citation.sourceUrl) {+ Link(destination: sourceUrl) {+ Label("Open source", systemImage: "arrow.up.right.square")+ .frame(minHeight: 44)+ }}- Link(destination: URL(string: citation.licenseUrl)!) {- Label(citation.licenseLabel, systemImage: "arrow.up.right.square")- .frame(minHeight: 44)+ if let licenseUrl = URL(string: citation.licenseUrl) {+ Link(destination: licenseUrl) {+ Label(citation.licenseLabel, systemImage: "arrow.up.right.square")+ .frame(minHeight: 44)+ }}}@@ -434,7 +453,8 @@ struct StreamingBubbleView: View {@State private var renderedText = ""var body: some View {- let hasText = isGenerating && !renderedText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ let hasText =+ isGenerating && !renderedText.trimmingCharacters(in: .whitespacesAndNewlines).isEmptylet bubbleVerticalPadding = hasText ? EnsuSpacing.md : 0let contentSpacing = hasText ? EnsuSpacing.sm : 0@@ -588,16 +608,20 @@ struct ParsedMessage {var remaining = textvar todos: [TodoBlock] = []- let thinkMatches = ParsedMessage.extractTags(using: ChatMessageTagRegex.think, from: remaining)+ let thinkMatches = ParsedMessage.extractTags(+ using: ChatMessageTagRegex.think, from: remaining)remaining = thinkMatches.cleaned- let todoMatches = ParsedMessage.extractTags(using: ChatMessageTagRegex.todoList, from: remaining)+ let todoMatches = ParsedMessage.extractTags(+ using: ChatMessageTagRegex.todoList, from: remaining)remaining = todoMatches.cleanedfor content in todoMatches.contents {if let data = content.data(using: .utf8),- let payload = try? JSONDecoder().decode(TodoPayload.self, from: data) {- todos.append(TodoBlock(title: payload.title, status: payload.status, items: payload.items))+ let payload = try? JSONDecoder().decode(TodoPayload.self, from: data)+ {+ todos.append(+ TodoBlock(title: payload.title, status: payload.status, items: payload.items))}}@@ -606,7 +630,9 @@ struct ParsedMessage {self.markdownBlocks = MarkdownParser.parse(remaining)}- private static func extractTags(using regex: NSRegularExpression?, from text: String) -> (contents: [String], cleaned: String) {+ private static func extractTags(using regex: NSRegularExpression?, from text: String) -> (+ contents: [String], cleaned: String+ ) {guard let regex else {return ([], text)}@@ -616,7 +642,8 @@ struct ParsedMessage {guard let range = Range(match.range(at: 1), in: text) else { return nil }return String(text[range])}- let cleaned = regex.stringByReplacingMatches(in: text, range: NSRange(text.startIndex..., in: text), withTemplate: "")+ let cleaned = regex.stringByReplacingMatches(+ in: text, range: NSRange(text.startIndex..., in: text), withTemplate: "")return (contents, cleaned)}@@ -683,14 +710,15 @@ struct MarkdownView: View {var body: some View {let lastKind = blocks.last?.kind- let inlineCursorSupported = lastKind.map { kind in- switch kind {- case .heading, .paragraph, .blockquote, .list:- return true- case .code, .math, .divider:- return false- }- } ?? false+ let inlineCursorSupported =+ lastKind.map { kind in+ switch kind {+ case .heading, .paragraph, .blockquote, .list:+ return true+ case .code, .math, .divider:+ return false+ }+ } ?? falselet showTrailingCursor = showCursor && (!inlineCursorSupported || blocks.isEmpty)VStack(alignment: .leading, spacing: EnsuSpacing.md) {@@ -704,7 +732,8 @@ struct MarkdownView: View {text: displayText,fonts: InlineFontSet(normal: headingFont(for: level),- code: EnsuFont.code(size: headingFontSize(for: level), weight: .semibold),+ code: EnsuFont.code(+ size: headingFontSize(for: level), weight: .semibold),mathSize: headingFontSize(for: level)),textColor: EnsuColor.textPrimary@@ -736,7 +765,8 @@ struct MarkdownView: View {case .math(let text):MathBlockView(text: text)case .list(let items):- let resolvedItems = (showCursor && isLast)+ let resolvedItems =+ (showCursor && isLast)? items.enumerated().map { offset, item inoffset == items.count - 1 ? item + StreamingCursor.glyph : item}@@ -830,6 +860,7 @@ private let messageInlineFonts = InlineFontSet(mathSize: 15)+// swift-format-ignore: NeverUseForceTryprivate let inlineMathPattern = try! NSRegularExpression(pattern: #"(?<!\\)\$(?!\$)(?:[^$\n\\]|\\.)+?(?<!\\)\$(?!\$)|\\\((?:[^\n\\]|\\.)+?\\\)"#,options: []@@ -887,18 +918,18 @@ private func parseInlineSegments(_ text: String) -> [InlineSegment] {}case .normal:switch true {- case hasPrefix(characters, at: index, token: ["*", "*"]) && hasClosingDelimiter(characters, startIndex: index + 2, delimiter: ["*", "*"]):+ case hasPrefix(characters, at: index, token: ["*", "*"])+ && hasClosingDelimiter(characters, startIndex: index + 2, delimiter: ["*", "*"]):flushBuffer()currentStyle = .boldindex += 2- case characters[index] == "*" &&- !hasPrefix(characters, at: index, token: ["*", "*"]) &&- hasClosingSingleAsterisk(characters, startIndex: index + 1):+ case characters[index] == "*" && !hasPrefix(characters, at: index, token: ["*", "*"])+ && hasClosingSingleAsterisk(characters, startIndex: index + 1):flushBuffer()currentStyle = .italicindex += 1- case characters[index] == "`" &&- hasClosingDelimiter(characters, startIndex: index + 1, delimiter: ["`"]):+ case characters[index] == "`"+ && hasClosingDelimiter(characters, startIndex: index + 1, delimiter: ["`"]):flushBuffer()currentStyle = .codeindex += 1@@ -954,9 +985,9 @@ private func findInlineMathMatch(_ characters: [Character], startIndex: Int) ->if characters[index] == "\n" {return nil}- if characters[index] == "$" &&- characters[index - 1] != "\\" &&- (index + 1 >= characters.count || characters[index + 1] != "$") {+ if characters[index] == "$" && characters[index - 1] != "\\"+ && (index + 1 >= characters.count || characters[index + 1] != "$")+ {if index == startIndex + 1 {return nil}@@ -979,7 +1010,9 @@ private func hasPrefix(_ characters: [Character], at startIndex: Int, token: [Chreturn Array(characters[startIndex..<endIndex]) == token}-private func hasClosingDelimiter(_ characters: [Character], startIndex: Int, delimiter: [Character]) -> Bool {+private func hasClosingDelimiter(_ characters: [Character], startIndex: Int, delimiter: [Character])+ -> Bool+{var index = startIndexwhile index < characters.count {if characters[index] == "\n" {@@ -1009,7 +1042,8 @@ private func hasClosingSingleAsterisk(_ characters: [Character], startIndex: Intprivate func containsInlineMath(_ text: String) -> Bool {let nsText = text as NSString- return inlineMathPattern.firstMatch(in: text, range: NSRange(location: 0, length: nsText.length)) != nil+ return inlineMathPattern.firstMatch(+ in: text, range: NSRange(location: 0, length: nsText.length)) != nil}private func styledInlineText(@@ -1075,17 +1109,23 @@ private struct InlineMathTextView: View {var body: some View {VStack(alignment: .leading, spacing: 2) {- ForEach(Array(text.split(separator: "\n", omittingEmptySubsequences: false).enumerated()), id: \.offset) { _, rawLine in+ ForEach(+ Array(text.split(separator: "\n", omittingEmptySubsequences: false).enumerated()),+ id: \.offset+ ) { _, rawLine inlet line = String(rawLine)FlowLayout(spacing: 0) {- ForEach(Array(parseInlineSegments(line).enumerated()), id: \.offset) { _, segment in+ ForEach(Array(parseInlineSegments(line).enumerated()), id: \.offset) {+ _, segment inswitch segment {case .math(let latex):InlineLaTeXView(latex: latex, fontSize: fonts.mathSize).fixedSize()case .text(let content, let style):- ForEach(Array(splitTextChunks(content).enumerated()), id: \.offset) { _, chunk in- styledInlineText(chunk, style: style, fonts: fonts, textColor: textColor)+ ForEach(Array(splitTextChunks(content).enumerated()), id: \.offset) {+ _, chunk in+ styledInlineText(+ chunk, style: style, fonts: fonts, textColor: textColor)}}}@@ -1178,7 +1218,9 @@ enum MarkdownParser {flushMarkdown()mathEndDelimiter = endDelimitermathLines.removeAll()- if let initial = initialContent?.trimmingCharacters(in: .whitespacesAndNewlines), !initial.isEmpty {+ if let initial = initialContent?.trimmingCharacters(in: .whitespacesAndNewlines),+ !initial.isEmpty+ {mathLines.append(initial)}}@@ -1202,7 +1244,8 @@ enum MarkdownParser {continue}if endDelimiter != "]" && trimmed.hasSuffix(endDelimiter) {- let content = String(trimmed.dropLast(endDelimiter.count)).trimmingCharacters(in: .whitespaces)+ let content = String(trimmed.dropLast(endDelimiter.count)).trimmingCharacters(+ in: .whitespaces)if !content.isEmpty {mathLines.append(content)}@@ -1244,7 +1287,8 @@ enum MarkdownParser {}if isBracketMathLine(trimmed) {- let inner = String(trimmed.dropFirst().dropLast()).trimmingCharacters(in: .whitespaces)+ let inner = String(trimmed.dropFirst().dropLast()).trimmingCharacters(+ in: .whitespaces)flushMarkdown()segments.append(.math(inner))continue@@ -1294,10 +1338,12 @@ enum MarkdownParser {case _ as ThematicBreak:return [.divider]case let orderedList as OrderedList:- let items = orderedList.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ let items = orderedList.children.compactMap { $0 as? ListItem }.map(renderListItem)+ .filter { !$0.isEmpty }return items.isEmpty ? [] : [.list(items: items)]case let unorderedList as UnorderedList:- let items = unorderedList.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ let items = unorderedList.children.compactMap { $0 as? ListItem }.map(renderListItem)+ .filter { !$0.isEmpty }return items.isEmpty ? [] : [.list(items: items)]default:var nestedBlocks: [MarkdownBlock.Kind] = []@@ -1326,14 +1372,16 @@ enum MarkdownParser {continue}if let list = child as? OrderedList {- let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter+ { !$0.isEmpty }if !items.isEmpty {parts.append(items.joined(separator: "\n"))}continue}if let list = child as? UnorderedList {- let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter+ { !$0.isEmpty }if !items.isEmpty {parts.append(items.joined(separator: "\n"))}@@ -1354,14 +1402,16 @@ enum MarkdownParser {continue}if let list = child as? OrderedList {- let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter+ { !$0.isEmpty }if !items.isEmpty {parts.append(items.joined(separator: "\n"))}continue}if let list = child as? UnorderedList {- let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter { !$0.isEmpty }+ let items = list.children.compactMap { $0 as? ListItem }.map(renderListItem).filter+ { !$0.isEmpty }if !items.isEmpty {parts.append(items.joined(separator: "\n"))}@@ -1453,7 +1503,8 @@ struct MathBlockView: View {RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock).stroke(EnsuColor.border, lineWidth: 1))- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock, style: .continuous))+ .clipShape(+ RoundedRectangle(cornerRadius: EnsuCornerRadius.codeBlock, style: .continuous))}}diff --git a/apple/apps/ensu/Ensu/Chat/MessageListView.swift b/apple/apps/ensu/Ensu/Chat/MessageListView.swiftindex 6ca0769c0b..ed87adcf8f 100644--- a/apple/apps/ensu/Ensu/Chat/MessageListView.swift+++ b/apple/apps/ensu/Ensu/Chat/MessageListView.swift@@ -161,7 +161,8 @@ struct MessageListView: View {@ViewBuilderprivate func messageListContent(containerHeight: CGFloat) -> some View {- let emptyStateMinHeight = max(0, containerHeight - contentBottomPadding - (EnsuSpacing.lg * 2))+ let emptyStateMinHeight = max(+ 0, containerHeight - contentBottomPadding - (EnsuSpacing.lg * 2))VStack(alignment: .leading, spacing: 0) {LazyVStack(alignment: .leading, spacing: EnsuSpacing.lg) {@@ -236,7 +237,9 @@ struct MessageListView: View {.background(GeometryReader { geo inColor.clear- .preference(key: BottomOffsetKey.self, value: geo.frame(in: .named("scroll")).maxY)+ .preference(+ key: BottomOffsetKey.self,+ value: geo.frame(in: .named("scroll")).maxY)})}@@ -304,7 +307,9 @@ struct MessageListView: View {}}- private func scrollToBottom(_ proxy: ScrollViewProxy, force: Bool = false, animated: Bool = true) {+ private func scrollToBottom(+ _ proxy: ScrollViewProxy, force: Bool = false, animated: Bool = true+ ) {guard force || (autoScrollEnabled && isAtBottom) else { return }if animated {withAnimation(.easeOut(duration: 0.2)) {@@ -317,8 +322,9 @@ struct MessageListView: View {private func performStreamingStartHapticIfNeeded() {guard isGenerating,- !didPerformStreamingStartHaptic,- hasVisibleStreamingContent(streamingResponse) else {+ !didPerformStreamingStartHaptic,+ hasVisibleStreamingContent(streamingResponse)+ else {return}hapticTap()@@ -361,8 +367,8 @@ struct MessageListView: View {let textWithoutUnclosedThink = removingUnclosedStreamingTag("think", from: text)let visibleText = removingUnclosedStreamingTag("todo_list", from: textWithoutUnclosedThink)let parsed = ParsedMessage(text: visibleText)- return !parsed.todoBlocks.isEmpty ||- !parsed.markdown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ return !parsed.todoBlocks.isEmpty+ || !parsed.markdown.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty}private func removingUnclosedStreamingTag(_ tag: String, from text: String) -> String {@@ -373,7 +379,10 @@ struct MessageListView: View {while let openRange = text.range(of: openingTag, range: cursor..<text.endIndex) {result.append(contentsOf: text[cursor..<openRange.lowerBound])- guard let closeRange = text.range(of: closingTag, range: openRange.upperBound..<text.endIndex) else {+ guard+ let closeRange = text.range(+ of: closingTag, range: openRange.upperBound..<text.endIndex)+ else {return result}result.append(contentsOf: text[openRange.lowerBound..<closeRange.upperBound])diff --git a/apple/apps/ensu/Ensu/Chat/Models/ChatModels.swift b/apple/apps/ensu/Ensu/Chat/Models/ChatModels.swiftindex 50ee316315..5c27dc5ffa 100644--- a/apple/apps/ensu/Ensu/Chat/Models/ChatModels.swift+++ b/apple/apps/ensu/Ensu/Chat/Models/ChatModels.swift@@ -2,7 +2,8 @@ import Foundationenum ChatMessageTagRegex {static let think = try? NSRegularExpression(pattern: "<think>([\\s\\S]*?)</think>", options: [])- static let todoList = try? NSRegularExpression(pattern: "<todo_list>([\\s\\S]*?)</todo_list>", options: [])+ static let todoList = try? NSRegularExpression(+ pattern: "<todo_list>([\\s\\S]*?)</todo_list>", options: [])}struct ChatAttachment: Identifiable, Equatable {@@ -18,7 +19,10 @@ struct ChatAttachment: Identifiable, Equatable {let url: URL?var isUploading: Bool- init(id: UUID = UUID(), name: String, size: Int64, kind: Kind, url: URL? = nil, isUploading: Bool = false) {+ init(+ id: UUID = UUID(), name: String, size: Int64, kind: Kind, url: URL? = nil,+ isUploading: Bool = false+ ) {self.id = idself.name = nameself.size = sizediff --git a/apple/apps/ensu/Ensu/Chat/SessionDrawerView.swift b/apple/apps/ensu/Ensu/Chat/SessionDrawerView.swiftindex 0562911fcf..72108b28d9 100644--- a/apple/apps/ensu/Ensu/Chat/SessionDrawerView.swift+++ b/apple/apps/ensu/Ensu/Chat/SessionDrawerView.swift@@ -160,7 +160,9 @@ struct SessionDrawerView: View {.contentShape(Rectangle())}- private func drawerPrimaryTile(icon: String, title: String, action: @escaping () -> Void, expands: Bool = true) -> some View {+ private func drawerPrimaryTile(+ icon: String, title: String, action: @escaping () -> Void, expands: Bool = true+ ) -> some View {Button(action: {hapticTap()action()@@ -204,7 +206,8 @@ struct SessionDrawerView: View {let order = ["TODAY", "YESTERDAY", "THIS WEEK", "LAST WEEK", "THIS MONTH", "OLDER"]return order.compactMap { title inguard let items = grouped[title], !items.isEmpty else { return nil }- return SessionSection(title: title, sessions: items.sorted { $0.updatedAt > $1.updatedAt })+ return SessionSection(+ title: title, sessions: items.sorted { $0.updatedAt > $1.updatedAt })}}@@ -215,7 +218,9 @@ struct SessionDrawerView: View {if calendar.isDate(date, equalTo: Date(), toGranularity: .weekOfYear) { return "THIS WEEK" }let lastWeek = calendar.date(byAdding: .weekOfYear, value: -1, to: Date()) ?? Date()- if calendar.isDate(date, equalTo: lastWeek, toGranularity: .weekOfYear) { return "LAST WEEK" }+ if calendar.isDate(date, equalTo: lastWeek, toGranularity: .weekOfYear) {+ return "LAST WEEK"+ }if calendar.isDate(date, equalTo: Date(), toGranularity: .month) { return "THIS MONTH" }return "OLDER"}diff --git a/apple/apps/ensu/Ensu/Chat/VoiceTranscriptionService.swift b/apple/apps/ensu/Ensu/Chat/VoiceTranscriptionService.swiftindex 3607775782..a107605fd0 100644--- a/apple/apps/ensu/Ensu/Chat/VoiceTranscriptionService.swift+++ b/apple/apps/ensu/Ensu/Chat/VoiceTranscriptionService.swift@@ -108,7 +108,8 @@ final class VoiceTranscriptionService {let session = AVAudioSession.sharedInstance()switch session.recordPermission {case .granted:- prepareModelAndStartRecording(onState: onState, shouldStartRecording: shouldStartRecording)+ prepareModelAndStartRecording(+ onState: onState, shouldStartRecording: shouldStartRecording)case .denied:onState(.error("Microphone permission is required for voice input."))case .undetermined:@@ -271,13 +272,17 @@ final class VoiceTranscriptionService {return}await MainActor.run { [weak self] in- guard self?.isDownloadActive(taskId: taskId, downloadId: downloadId) == true else { return }+ guard self?.isDownloadActive(taskId: taskId, downloadId: downloadId) == true else {+ return+ }onState(.downloading(percent: nil))}try await assetStore.download(assets: assets) { [weak self] progress inlet percent = min(max(Int(progress.percentage), 0), 100)Task { @MainActor [weak self] in- guard self?.isDownloadActive(taskId: taskId, downloadId: downloadId) == true else { return }+ guard self?.isDownloadActive(taskId: taskId, downloadId: downloadId) == true else {+ return+ }onState(.downloading(percent: percent))}}@@ -372,7 +377,8 @@ private final class PcmAudioRecorder {lock.unlock()let session = AVAudioSession.sharedInstance()- try session.setCategory(.playAndRecord, mode: .measurement, options: [.allowBluetoothHFP, .defaultToSpeaker])+ try session.setCategory(+ .playAndRecord, mode: .measurement, options: [.allowBluetoothHFP, .defaultToSpeaker])try session.setActive(true)let input = engine.inputNodediff --git a/apple/apps/ensu/Ensu/Components/EnsuComponents.swift b/apple/apps/ensu/Ensu/Components/EnsuComponents.swiftindex 8d3e90f7e2..ed253b45a5 100644--- a/apple/apps/ensu/Ensu/Components/EnsuComponents.swift+++ b/apple/apps/ensu/Ensu/Components/EnsuComponents.swift@@ -252,8 +252,11 @@ struct ImageAttachmentThumbnail: View {thumbnailContent(loadedImage).frame(width: size.width, height: size.height).background(EnsuColor.fillFaint)- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))- .contentShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))+ .clipShape(+ RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous)+ )+ .contentShape(+ RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous))if isUploading {RoundedRectangle(cornerRadius: EnsuCornerRadius.card, style: .continuous)@@ -307,12 +310,14 @@ struct ImageAttachmentThumbnail: View {return CGSize(width: width, height: height)}if loadedImage.pixelHeight > loadedImage.pixelWidth,- let portraitWidth,- let portraitHeight {+ let portraitWidth,+ let portraitHeight+ {return CGSize(width: portraitWidth, height: portraitHeight)}if loadedImage.pixelHeight == loadedImage.pixelWidth,- let squareSize {+ let squareSize+ {return CGSize(width: squareSize, height: squareSize)}return CGSize(width: width, height: height)diff --git a/apple/apps/ensu/Ensu/DesignSystem/FlowLayout.swift b/apple/apps/ensu/Ensu/DesignSystem/FlowLayout.swiftindex 76af6975ba..138e78fbc2 100644--- a/apple/apps/ensu/Ensu/DesignSystem/FlowLayout.swift+++ b/apple/apps/ensu/Ensu/DesignSystem/FlowLayout.swift@@ -40,7 +40,9 @@ struct FlowLayout: Layout {return CGSize(width: finalWidth, height: totalHeight)}- func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {+ func placeSubviews(+ in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()+ ) {let sizes = subviews.map { childSize(for: $0, maxWidth: bounds.width) }struct RowItem {diff --git a/apple/apps/ensu/Ensu/DesignSystem/KeyboardObserver.swift b/apple/apps/ensu/Ensu/DesignSystem/KeyboardObserver.swiftindex 642d016a72..c3fcaccc4e 100644--- a/apple/apps/ensu/Ensu/DesignSystem/KeyboardObserver.swift+++ b/apple/apps/ensu/Ensu/DesignSystem/KeyboardObserver.swift@@ -46,6 +46,7 @@ final class KeyboardObserver: ObservableObject {extension View {@MainActorfunc hideKeyboard() {- UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)+ UIApplication.shared.sendAction(+ #selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)}}diff --git a/apple/apps/ensu/Ensu/ModelSettings/ModelSettingsView.swift b/apple/apps/ensu/Ensu/ModelSettings/ModelSettingsView.swiftindex 9d7d068c26..76ed81ef02 100644--- a/apple/apps/ensu/Ensu/ModelSettings/ModelSettingsView.swift+++ b/apple/apps/ensu/Ensu/ModelSettings/ModelSettingsView.swift@@ -24,9 +24,10 @@ struct ModelSettingsView: View {let defaultModel = policy.defaultModelreturn [ModelChoice(id: Self.defaultOptionId, name: defaultModel.title, isDefault: true)- ] + policy.visibleModels.filter { $0.id != defaultModel.id }.map { preset in- ModelChoice(id: preset.id, name: preset.title)- }+ ]+ + policy.visibleModels.filter { $0.id != defaultModel.id }.map { preset in+ ModelChoice(id: preset.id, name: preset.title)+ }}()init(embeddedInNavigation: Bool = false) {@@ -67,7 +68,9 @@ struct ModelSettingsView: View {contextLength = settings.contextLengthmaxTokens = settings.maxTokenstemperature = settings.temperature- showAdvancedLimits = !settings.contextLength.isEmpty || !settings.maxTokens.isEmpty || !settings.temperature.isEmpty+ showAdvancedLimits =+ !settings.contextLength.isEmpty || !settings.maxTokens.isEmpty+ || !settings.temperature.isEmpty}.overlay(alignment: .bottom) {if let toastMessage {@@ -145,7 +148,9 @@ struct ModelSettingsView: View {Divider().background(EnsuColor.border)VStack(spacing: EnsuSpacing.md) {- PrimaryButton(text: "Save Model Settings", isLoading: isSaving, isEnabled: !isSaving) {+ PrimaryButton(+ text: "Save Model Settings", isLoading: isSaving, isEnabled: !isSaving+ ) {saveTapped()}@@ -280,7 +285,9 @@ struct ModelSettingsView: View {isValid = false}- if let contextValue = Int(contextLength), let maxValue = Int(maxTokens), maxValue > contextValue {+ if let contextValue = Int(contextLength), let maxValue = Int(maxTokens),+ maxValue > contextValue+ {maxTokensError = "Must be <= context length"isValid = false}diff --git a/apple/apps/ensu/Ensu/Services/AssetStore.swift b/apple/apps/ensu/Ensu/Services/AssetStore.swiftindex 89b1a86a9a..66e00f22db 100644--- a/apple/apps/ensu/Ensu/Services/AssetStore.swift+++ b/apple/apps/ensu/Ensu/Services/AssetStore.swift@@ -8,7 +8,8 @@ final class AssetStore: Sendable {@MainActorinit() async {- let baseDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ let baseDir =+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?? FileManager.default.temporaryDirectoryvar assetsDir = baseDir.appendingPathComponent("assets", isDirectory: true)try? FileManager.default.createDirectory(at: assetsDir, withIntermediateDirectories: true)@@ -18,12 +19,14 @@ final class AssetStore: Sendable {core = AssetStoreCore(assetsDir: assetsDir.path)let settings = UserDefaults.standardlet pendingSelection = settings.object(forKey: "ensu.model.id") == nil- let legacyModelUrl = pendingSelection && settings.bool(forKey: "ensu.model.use_custom")+ let legacyModelUrl =+ pendingSelection && settings.bool(forKey: "ensu.model.use_custom")? settings.string(forKey: "ensu.model.url"): nillet legacy = LegacyAssets(llmDir: baseDir.appendingPathComponent("llm", isDirectory: true).path,- transcriptionDir: baseDir.appendingPathComponent("transcription", isDirectory: true).path,+ transcriptionDir: baseDir.appendingPathComponent("transcription", isDirectory: true)+ .path,modelUrl: legacyModelUrl,mmprojUrl: settings.string(forKey: "ensu.model.mmproj"))diff --git a/apple/apps/ensu/Ensu/Services/CredentialStore.swift b/apple/apps/ensu/Ensu/Services/CredentialStore.swiftindex b3a66a8bfa..8936fda3c7 100644--- a/apple/apps/ensu/Ensu/Services/CredentialStore.swift+++ b/apple/apps/ensu/Ensu/Services/CredentialStore.swift@@ -13,7 +13,9 @@ actor CredentialStore {}func getOrCreateChatDbKey(hasChatData: Bool) throws -> Data {- if let existing = try KeychainStore.get(service: keychainService, account: KeychainAccount.chatDbKey) {+ if let existing = try KeychainStore.get(+ service: keychainService, account: KeychainAccount.chatDbKey)+ {guard existing.count == 32 else { throw KeychainStoreError.invalidItemFormat }return existing}diff --git a/apple/apps/ensu/Ensu/Services/IOSNotesSource.swift b/apple/apps/ensu/Ensu/Services/IOSNotesSource.swiftindex 66efc17550..2766290787 100644--- a/apple/apps/ensu/Ensu/Services/IOSNotesSource.swift+++ b/apple/apps/ensu/Ensu/Services/IOSNotesSource.swift@@ -33,18 +33,26 @@ final class IOSNotesSource: NotesSource, @unchecked Sendable {private static let byteLimit = Int(limits.maxSourceBytes)private static let entryLimit = 250_000- init(bookmark: Data, cancellation: NotesCancellation, coordinator: NSFileCoordinator = NSFileCoordinator()) throws {+ init(+ bookmark: Data, cancellation: NotesCancellation,+ coordinator: NSFileCoordinator = NSFileCoordinator()+ ) throws {var stale = falselet url: URL- do { url = try URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale) }- catch { throw NotesError.Unavailable }- guard !stale, url.startAccessingSecurityScopedResource() else { throw NotesError.Unavailable }+ do { url = try URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale) } catch {+ throw NotesError.Unavailable+ }+ guard !stale, url.startAccessingSecurityScopedResource() else {+ throw NotesError.Unavailable+ }root = urlself.cancellation = cancellationself.coordinator = coordinatordo {let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])- guard values.isDirectory == true, values.isSymbolicLink != true else { throw NotesError.Unavailable }+ guard values.isDirectory == true, values.isSymbolicLink != true else {+ throw NotesError.Unavailable+ }} catch {url.stopAccessingSecurityScopedResource()throw NotesError.Unavailable@@ -62,7 +70,9 @@ final class IOSNotesSource: NotesSource, @unchecked Sendable {}try cancellation.check()if let error { throw error }- guard let result else { throw NotesError.SourceRead(detail: "Could not read the Notes folder.") }+ guard let result else {+ throw NotesError.SourceRead(detail: "Could not read the Notes folder.")+ }return try result.get()}@@ -76,45 +86,66 @@ final class IOSNotesSource: NotesSource, @unchecked Sendable {var documents: [NotesDocument] = []var count = 0var total: UInt64 = 0- let keys: Set<URLResourceKey> = [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey, .contentModificationDateKey]+ let keys: Set<URLResourceKey> = [+ .isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey,+ .contentModificationDateKey,+ ]while let (directory, prefix) = pending.popLast() {try cancellation.check()let identity = directory.standardizedFileURL.resolvingSymlinksInPath().path- guard seen.insert(identity).inserted else { throw NotesError.SourceRead(detail: "Ambiguous directory structure.") }+ guard seen.insert(identity).inserted else {+ throw NotesError.SourceRead(detail: "Ambiguous directory structure.")+ }let children = try coordinate(directory) {- try FileManager.default.contentsOfDirectory(at: $0, includingPropertiesForKeys: Array(keys))+ try FileManager.default.contentsOfDirectory(+ at: $0, includingPropertiesForKeys: Array(keys))}var names = Set<String>()for child in children {try cancellation.check()count += 1- guard count <= Self.entryLimit else { throw NotesError.InvalidInput(detail: "The Notes folder contains too many entries.") }+ guard count <= Self.entryLimit else {+ throw NotesError.InvalidInput(+ detail: "The Notes folder contains too many entries.")+ }let name = child.lastPathComponent- guard names.insert(name).inserted else { throw NotesError.SourceRead(detail: "Duplicate document names.") }+ guard names.insert(name).inserted else {+ throw NotesError.SourceRead(detail: "Duplicate document names.")+ }if name.hasPrefix(".") { continue }let id = prefix + namelet values = try child.resourceValues(forKeys: keys)if values.isSymbolicLink == true { continue }if values.isDirectory != true && values.isRegularFile != true { continue }guard values.isDirectory == true || Self.supported(name) else { continue }- do { try validateNotesDocumentId(documentId: id) }- catch NotesError.InvalidInput { continue }+ do { try validateNotesDocumentId(documentId: id) } catch NotesError.InvalidInput {+ continue+ }if values.isDirectory == true {pending.append((child, id + "/"))} else {let size: Int- if let advertised = values.fileSize { size = advertised }- else {- do { size = try readBounded(documentId: id).bytes.count }- catch ReadError.tooLarge { continue }+ if let advertised = values.fileSize {+ size = advertised+ } else {+ do { size = try readBounded(documentId: id).bytes.count } catch ReadError+ .tooLarge+ { continue }}guard size <= Self.byteLimit else { continue }total += UInt64(size)- guard documents.count < Int(Self.limits.maxCollectionDocuments), total <= Self.limits.maxCollectionSourceBytes else {- throw NotesError.InvalidInput(detail: "The Notes folder is too large to index.")+ guard documents.count < Int(Self.limits.maxCollectionDocuments),+ total <= Self.limits.maxCollectionSourceBytes+ else {+ throw NotesError.InvalidInput(+ detail: "The Notes folder is too large to index.")}- documents.append(NotesDocument(documentId: id, size: UInt64(size),- modifiedAtMs: values.contentModificationDate.map { Int64($0.timeIntervalSince1970 * 1000) }))+ documents.append(+ NotesDocument(+ documentId: id, size: UInt64(size),+ modifiedAtMs: values.contentModificationDate.map {+ Int64($0.timeIntervalSince1970 * 1000)+ }))}}}@@ -122,9 +153,9 @@ final class IOSNotesSource: NotesSource, @unchecked Sendable {}func readDocument(documentId: String) throws -> NotesRead {- do { return try readBounded(documentId: documentId) }- catch ReadError.tooLarge { throw NotesError.SourceChanged }- catch { throw Self.documentReadError(error, root: root) }+ do { return try readBounded(documentId: documentId) } catch ReadError.tooLarge {+ throw NotesError.SourceChanged+ } catch { throw Self.documentReadError(error, root: root) }}private enum ReadError: Error { case tooLarge }@@ -132,15 +163,20 @@ final class IOSNotesSource: NotesSource, @unchecked Sendable {private func readBounded(documentId: String) throws -> NotesRead {try validateNotesDocumentId(documentId: documentId)let parts = documentId.split(separator: "/").map(String.init)- guard parts.allSatisfy({ !$0.hasPrefix(".") }), Self.supported(parts.last ?? "") else { throw NotesError.SourceChanged }+ guard parts.allSatisfy({ !$0.hasPrefix(".") }), Self.supported(parts.last ?? "") else {+ throw NotesError.SourceChanged+ }let url = parts.reduce(root) { $0.appendingPathComponent($1) }return try coordinate(url) { coordinated in- guard coordinated.standardizedFileURL.path == url.standardizedFileURL.path else { throw NotesError.SourceChanged }+ guard coordinated.standardizedFileURL.path == url.standardizedFileURL.path else {+ throw NotesError.SourceChanged+ }var fd = Darwin.open(root.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW)guard fd >= 0 else { throw NotesError.Unavailable }for (index, part) in parts.enumerated() {- let flags = O_RDONLY | O_NOFOLLOW | O_CLOEXEC |- (index == parts.count - 1 ? O_NONBLOCK : O_DIRECTORY)+ let flags =+ O_RDONLY | O_NOFOLLOW | O_CLOEXEC+ | (index == parts.count - 1 ? O_NONBLOCK : O_DIRECTORY)let next = openat(fd, part, flags)let code = errnoclose(fd)@@ -150,7 +186,9 @@ final class IOSNotesSource: NotesSource, @unchecked Sendable {let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true)defer { try? file.close() }var before = stat()- guard fstat(fd, &before) == 0, before.st_mode & S_IFMT == S_IFREG else { throw NotesError.SourceChanged }+ guard fstat(fd, &before) == 0, before.st_mode & S_IFMT == S_IFREG else {+ throw NotesError.SourceChanged+ }let flags = fcntl(fd, F_GETFL)guard flags >= 0, fcntl(fd, F_SETFL, flags & ~O_NONBLOCK) == 0 else {throw Self.fileError(errno)@@ -164,12 +202,18 @@ final class IOSNotesSource: NotesSource, @unchecked Sendable {bytes.append(chunk)}var after = stat()- guard fstat(fd, &after) == 0, before.st_ino == after.st_ino, before.st_size == after.st_size,- before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec,- before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec,- bytes.count == after.st_size else { throw NotesError.SourceChanged }- return NotesRead(bytes: bytes, source: NotesDocument(documentId: documentId, size: UInt64(bytes.count),- modifiedAtMs: Int64(after.st_mtimespec.tv_sec) * 1000 + Int64(after.st_mtimespec.tv_nsec) / 1_000_000))+ guard fstat(fd, &after) == 0, before.st_ino == after.st_ino,+ before.st_size == after.st_size,+ before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec,+ before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec,+ bytes.count == after.st_size+ else { throw NotesError.SourceChanged }+ return NotesRead(+ bytes: bytes,+ source: NotesDocument(+ documentId: documentId, size: UInt64(bytes.count),+ modifiedAtMs: Int64(after.st_mtimespec.tv_sec) * 1000 + Int64(+ after.st_mtimespec.tv_nsec) / 1_000_000))}}@@ -188,7 +232,8 @@ final class IOSNotesSource: NotesSource, @unchecked Sendable {let fd = Darwin.open(root.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW)guard fd >= 0 else {let code = errno- if code == ENOENT || code == ENOTDIR || code == ELOOP || code == EACCES || code == EPERM {+ if code == ENOENT || code == ENOTDIR || code == ELOOP || code == EACCES || code == EPERM+ {return NotesError.Unavailable}return accessError(error)@@ -200,13 +245,19 @@ final class IOSNotesSource: NotesSource, @unchecked Sendable {private static func isMissingFile(_ error: Error) -> Bool {let ns = error as NSErrorif ns.domain == NSPOSIXErrorDomain && ns.code == Int(ENOENT) { return true }- if ns.domain == NSCocoaErrorDomain && (ns.code == NSFileNoSuchFileError || ns.code == NSFileReadNoSuchFileError) { return true }+ if ns.domain == NSCocoaErrorDomain+ && (ns.code == NSFileNoSuchFileError || ns.code == NSFileReadNoSuchFileError)+ {+ return true+ }return (ns.userInfo[NSUnderlyingErrorKey] as? Error).map(isMissingFile) ?? false}private static func accessError(_ error: Error) -> Error {if let error = error as? NotesError { return error }let ns = error as NSError- if ns.domain == NSCocoaErrorDomain && ns.code == NSFileReadNoPermissionError { return NotesError.Unavailable }+ if ns.domain == NSCocoaErrorDomain && ns.code == NSFileReadNoPermissionError {+ return NotesError.Unavailable+ }return NotesError.SourceRead(detail: "Could not access the Notes folder. Please try again.")}}diff --git a/apple/apps/ensu/Ensu/Services/KeychainStore.swift b/apple/apps/ensu/Ensu/Services/KeychainStore.swiftindex 6839f3aab3..163f86d9bd 100644--- a/apple/apps/ensu/Ensu/Services/KeychainStore.swift+++ b/apple/apps/ensu/Ensu/Services/KeychainStore.swift@@ -15,7 +15,7 @@ final class KeychainStore {]let attributes: [String: Any] = [- kSecValueData as String: data,+ kSecValueData as String: data]let updateStatus = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)diff --git a/apple/apps/ensu/Ensu/Services/KnowledgeProvider.swift b/apple/apps/ensu/Ensu/Services/KnowledgeProvider.swiftindex c75881899c..3326ea0efe 100644--- a/apple/apps/ensu/Ensu/Services/KnowledgeProvider.swift+++ b/apple/apps/ensu/Ensu/Services/KnowledgeProvider.swift@@ -28,10 +28,11 @@ actor KnowledgeProvider {let asset = try knowledgePackAsset(stableId: dataset.stableId)task = Task.detached(priority: .utility) {try await assetStore.download(assets: [asset]) {- onProgress(KnowledgeDownloadProgress(- label: $0.label,- percentage: $0.percentage- ))+ onProgress(+ KnowledgeDownloadProgress(+ label: $0.label,+ percentage: $0.percentage+ ))}}}@@ -132,7 +133,8 @@ actor KnowledgeProvider {) async -> [KnowledgeSearchHit] {do {return try await withIndexGate {- let selected = datasets.compactMap { dataset -> (KnowledgeDatasetConfig, RetrievalIndex)? in+ let selected = datasets.compactMap {+ dataset -> (KnowledgeDatasetConfig, RetrievalIndex)? inguard let index = indexes[dataset.stableId]?.index else { return nil }return (dataset, index)}@@ -151,11 +153,13 @@ actor KnowledgeProvider {continue}if Task.isCancelled { return [] }- merged.append(contentsOf: hits.map {- KnowledgeSearchHit(dataset: dataset, hit: $0)- })+ merged.append(+ contentsOf: hits.map {+ KnowledgeSearchHit(dataset: dataset, hit: $0)+ })}- return merged+ return+ merged.sorted { $0.hit.score > $1.hit.score }.prefix(Int(maxHits)).map { $0 }diff --git a/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift b/apple/apps/ensu/Ensu/Services/KnowledgeStore.swiftindex 190609efb1..f2bce21e69 100644--- a/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift+++ b/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift@@ -24,7 +24,8 @@ final class KnowledgeStore: ObservableObject {var enabledReadyDatasets: [KnowledgeDatasetConfig] {packs.compactMap { pack inguard pack.enabled,- pack.status == .ready || pack.status == .updateAvailable else {+ pack.status == .ready || pack.status == .updateAvailable+ else {return nil}return pack.config@@ -82,8 +83,9 @@ final class KnowledgeStore: ObservableObject {func downloadOrUpdate(stableId: String) {guard downloadsAllowed,- mutationTasks[stableId] == nil,- let index = packs.firstIndex(where: { $0.id == stableId }) else {+ mutationTasks[stableId] == nil,+ let index = packs.firstIndex(where: { $0.id == stableId })+ else {return}let dataset = packs[index].config@@ -110,7 +112,8 @@ final class KnowledgeStore: ObservableObject {if shouldEnable {preferences.setDatasetEnabled(id: stableId, enabled: true)}- let preservedEnablement = packs+ let preservedEnablement =+ packs.first(where: { $0.id == stableId })?.enabled == trueapplyReconciliation(result,@@ -119,7 +122,8 @@ final class KnowledgeStore: ObservableObject {)} catch {if let result = try? await provider.reconcile(dataset: dataset) {- let enabled = packs+ let enabled =+ packs.first(where: { $0.id == stableId })?.enabled == trueapplyReconciliation(result,@@ -153,7 +157,8 @@ final class KnowledgeStore: ObservableObject {return}if let result {- let enabled = packs+ let enabled =+ packs.first(where: { $0.id == stableId })?.enabled == trueapplyReconciliation(result, stableId: stableId, enabled: enabled)}@@ -167,8 +172,9 @@ final class KnowledgeStore: ObservableObject {func setEnabled(stableId: String, enabled: Bool) {guard let index = packs.firstIndex(where: { $0.id == stableId }),- packs[index].activeIdentity != nil,- !packs[index].isMutating else {+ packs[index].activeIdentity != nil,+ !packs[index].isMutating+ else {return}updatePack(stableId) { pack in@@ -213,7 +219,7 @@ final class KnowledgeStore: ObservableObject {case AssetDownloadError.Http:return "The knowledge pack is currently unavailable. Please try again later."case AssetDownloadError.Validation,- AssetDownloadError.InvalidDownload:+ AssetDownloadError.InvalidDownload:return "The knowledge pack couldn't be verified. Please try again."case AssetDownloadError.Io:return "Couldn't save the knowledge pack. Please try again."diff --git a/apple/apps/ensu/Ensu/Services/LlmProvider.swift b/apple/apps/ensu/Ensu/Services/LlmProvider.swiftindex 5f12078f91..4c4538c418 100644--- a/apple/apps/ensu/Ensu/Services/LlmProvider.swift+++ b/apple/apps/ensu/Ensu/Services/LlmProvider.swift@@ -148,7 +148,10 @@ actor LlmProvider {return try await modelLoadGate.withLock(operation)}- init(assetStore: AssetStore, transcriber: Transcriber, knowledgeEmbedding: KnowledgeEmbeddingConfig) {+ init(+ assetStore: AssetStore, transcriber: Transcriber,+ knowledgeEmbedding: KnowledgeEmbeddingConfig+ ) {self.assetStore = assetStoreself.transcriber = transcriberself.knowledgeEmbedding = knowledgeEmbedding@@ -164,8 +167,7 @@ actor LlmProvider {}nonisolated func isModelDownloaded(_ selection: LlmModelSelection) -> Bool {- isChatModelReady(selection) &&- (!isEnsuPacksEnabled || isEmbeddingModelReady())+ isChatModelReady(selection) && (!isEnsuPacksEnabled || isEmbeddingModelReady())}func missingModelDownloadSize(_ selection: LlmModelSelection) async -> Int64? {@@ -248,7 +250,8 @@ actor LlmProvider {if !capability.isChatSupported {throw UnsupportedDeviceMemoryError(capability: capability)}- let modelKey = LoadedModelKey(id: selection.id, requestedContextLength: selection.contextLength)+ let modelKey = LoadedModelKey(+ id: selection.id, requestedContextLength: selection.contextLength)if currentModelKey == modelKey, loadedModel != nil, loadedContext != nil {return}@@ -268,14 +271,15 @@ actor LlmProvider {onProgress(DownloadProgress(percent: 100, status: "Loading model...", phase: .loading))do {- try loadModel(- selection,- modelPath: assetStore.llmModelPath(asset)!- )+ guard let modelPath = assetStore.llmModelPath(asset) else {+ throw RequiredModelValidationError(modelId: selection.id)+ }+ try loadModel(selection, modelPath: modelPath)} catch {if allowRecovery, wasAlreadyDownloaded, assetStore.removeDownloaded(asset) {onProgress(DownloadProgress(percent: 0, status: "Starting download..."))- try await ensureModelReadyLocked(selection, onProgress: onProgress, allowRecovery: false)+ try await ensureModelReadyLocked(+ selection, onProgress: onProgress, allowRecovery: false)return}throw error@@ -330,7 +334,9 @@ actor LlmProvider {throw UnsupportedDeviceMemoryError(capability: capability)}guard let context = loadedContext else {- throw NSError(domain: "LlmProvider", code: -1, userInfo: [NSLocalizedDescriptionKey: "Model not loaded"])+ throw NSError(+ domain: "LlmProvider", code: -1,+ userInfo: [NSLocalizedDescriptionKey: "Model not loaded"])}currentJobId.withLock { $0 = nil }@@ -339,7 +345,8 @@ actor LlmProvider {}let asset = chatAsset(selection)- let mmprojPath = imageFiles.isEmpty+ let mmprojPath =+ imageFiles.isEmpty? nil: assetStore.llmMmprojPath(asset)?.pathlet clampedTemperature = min(max(temperature, 0.35), 0.7)@@ -465,11 +472,13 @@ actor LlmProvider {let asset = self.chatAsset(selection)guard self.assetStore.isDownloaded(asset) else { return }guard let mmprojPath = self.assetStore.llmMmprojPath(asset),- FileManager.default.fileExists(atPath: mmprojPath.path) else {+ FileManager.default.fileExists(atPath: mmprojPath.path)+ else {return}- try await self.ensureModelReadyLocked(selection, onProgress: { _ in }, allowRecovery: true)+ try await self.ensureModelReadyLocked(+ selection, onProgress: { _ in }, allowRecovery: true)guard let context = self.loadedContext else {return}@@ -478,7 +487,7 @@ actor LlmProvider {try context.prewarmMultimodal(mmprojPath: mmprojPath.path,mediaMarker: nil- )+ )}} catch {return@@ -488,14 +497,16 @@ actor LlmProvider {func resetContext() async {try? await withModelLock {guard let model = loadedModel else { return }- let contextParams = LlmContextParams(contextSize: currentContextLength.map(Int32.init), nThreads: nil, nBatch: nil)+ let contextParams = LlmContextParams(+ contextSize: currentContextLength.map(Int32.init), nThreads: nil, nBatch: nil)loadedContext = nilloadedContext = try? model.newContext(params: contextParams)}}func loadedContextLength(_ selection: LlmModelSelection) -> Int? {- let modelKey = LoadedModelKey(id: selection.id, requestedContextLength: selection.contextLength)+ let modelKey = LoadedModelKey(+ id: selection.id, requestedContextLength: selection.contextLength)guard currentModelKey == modelKey, loadedModel != nil, loadedContext != nil else {return nil}@@ -518,7 +529,8 @@ actor LlmProvider {}private func loadModel(_ selection: LlmModelSelection, modelPath: URL) throws {- let params = LlmModelLoadParams(modelPath: modelPath.path, nGpuLayers: 0, useMmap: true, useMlock: false)+ let params = LlmModelLoadParams(+ modelPath: modelPath.path, nGpuLayers: 0, useMmap: true, useMlock: false)let model = try LlmModel.load(params: params)loadedModel = model@@ -530,16 +542,21 @@ actor LlmProvider {for contextSize in candidates {do {- let contextParams = LlmContextParams(contextSize: Int32(contextSize), nThreads: Int32(threadCount), nBatch: Int32(512))+ let contextParams = LlmContextParams(+ contextSize: Int32(contextSize), nThreads: Int32(threadCount),+ nBatch: Int32(512))loadedContext = try model.newContext(params: contextParams)- currentModelKey = LoadedModelKey(id: selection.id, requestedContextLength: selection.contextLength)+ currentModelKey = LoadedModelKey(+ id: selection.id, requestedContextLength: selection.contextLength)currentContextLength = contextSizereturn} catch {continue}}- throw NSError(domain: "LlmProvider", code: -5, userInfo: [NSLocalizedDescriptionKey: "Failed to create context"])+ throw NSError(+ domain: "LlmProvider", code: -5,+ userInfo: [NSLocalizedDescriptionKey: "Failed to create context"])}}diff --git a/apple/apps/ensu/Ensu/Services/Logging/EnsuLogging.swift b/apple/apps/ensu/Ensu/Services/Logging/EnsuLogging.swiftindex baa3574815..7afce56f03 100644--- a/apple/apps/ensu/Ensu/Services/Logging/EnsuLogging.swift+++ b/apple/apps/ensu/Ensu/Services/Logging/EnsuLogging.swift@@ -1,7 +1,7 @@import Foundationimport UIKit#if canImport(ZIPFoundation)-import ZIPFoundation+ import ZIPFoundation#endifenum EnsuLogLevel: String {@@ -45,15 +45,20 @@ final class EnsuLogging: Sendable {private init(maxLogFiles: Int = 5) {self.maxLogFiles = maxLogFiles- let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+ let support = FileManager.default.urls(+ for: .applicationSupportDirectory, in: .userDomainMask+ ).firstlet base = support ?? FileManager.default.temporaryDirectorylet directory = base.appendingPathComponent("logs", isDirectory: true)do {- try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: directory, withIntermediateDirectories: true)logsDirectory = directory} catch {- logsDirectory = FileManager.default.temporaryDirectory.appendingPathComponent("logs", isDirectory: true)- try? FileManager.default.createDirectory(at: logsDirectory, withIntermediateDirectories: true)+ logsDirectory = FileManager.default.temporaryDirectory.appendingPathComponent(+ "logs", isDirectory: true)+ try? FileManager.default.createDirectory(+ at: logsDirectory, withIntermediateDirectories: true)}}@@ -70,7 +75,10 @@ final class EnsuLogging: Sendable {EnsuLogger(tag: tag)}- func log(level: EnsuLogLevel, tag: String, message: String, details: String? = nil, error: Error? = nil) {+ func log(+ level: EnsuLogLevel, tag: String, message: String, details: String? = nil,+ error: Error? = nil+ ) {let safeMessage = EnsuLogSanitizer.sanitize(message) ?? ""let safeDetails = EnsuLogSanitizer.sanitize(combineDetails(details: details, error: error))@@ -94,8 +102,11 @@ final class EnsuLogging: Sendable {}func listLogFiles() -> [URL] {- let urls = (try? FileManager.default.contentsOfDirectory(at: logsDirectory, includingPropertiesForKeys: nil)) ?? []- return urls+ let urls =+ (try? FileManager.default.contentsOfDirectory(+ at: logsDirectory, includingPropertiesForKeys: nil)) ?? []+ return+ urls.filter { $0.pathExtension.lowercased() == "txt" }.sorted { $0.lastPathComponent < $1.lastPathComponent }}@@ -108,17 +119,18 @@ final class EnsuLogging: Sendable {}func createLogsArchive() throws -> URL {- let name = "ensu-logs-\(dayFormatter.string(from: Date()))-\(Int(Date().timeIntervalSince1970)).zip"+ let name =+ "ensu-logs-\(dayFormatter.string(from: Date()))-\(Int(Date().timeIntervalSince1970)).zip"let dest = FileManager.default.temporaryDirectory.appendingPathComponent(name)if FileManager.default.fileExists(atPath: dest.path) {try? FileManager.default.removeItem(at: dest)}#if canImport(ZIPFoundation)- if #available(iOS 16.0, macOS 13.0, *) {- try FileManager.default.zipItem(at: logsDirectory, to: dest, shouldKeepParent: true)- return dest- }+ if #available(iOS 16.0, macOS 13.0, *) {+ try FileManager.default.zipItem(at: logsDirectory, to: dest, shouldKeepParent: true)+ return dest+ }#endif// Fallback: concatenate logs into a single text file.@@ -214,7 +226,8 @@ struct EnsuLogger {}func error(_ message: String, _ error: Error? = nil, details: String? = nil) {- EnsuLogging.shared.log(level: .error, tag: tag, message: message, details: details, error: error)+ EnsuLogging.shared.log(+ level: .error, tag: tag, message: message, details: details, error: error)}}@@ -235,8 +248,10 @@ private final class EnsuRustLogSink: RustLogSink {private enum EnsuLogSanitizer {private static let emailPattern = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"private static let bearerPattern = "(?i)bearer\\s+[A-Za-z0-9._-]+"- private static let keyValuePattern = "(?i)(token|authToken|accessToken|refreshToken|authorization|password|otp|secret|secretKey|masterKey|encryptedToken|srpA|srpB|srpM1|srpM2|kek)\\s*[:=]\\s*([^\\s,;]+)"- private static let queryPattern = "(?i)(token|key|sig|signature|auth|session|passkey|otp)=([^&\\s]+)"+ private static let keyValuePattern =+ "(?i)(token|authToken|accessToken|refreshToken|authorization|password|otp|secret|secretKey|masterKey|encryptedToken|srpA|srpB|srpM1|srpM2|kek)\\s*[:=]\\s*([^\\s,;]+)"+ private static let queryPattern =+ "(?i)(token|key|sig|signature|auth|session|passkey|otp)=([^&\\s]+)"private static let longBlobPattern = "[A-Za-z0-9+/=]{40,}"static func sanitize(_ input: String?) -> String? {@@ -253,8 +268,11 @@ private enum EnsuLogSanitizer {private extension String {func replacingRegex(_ pattern: String, with replacement: String) -> String {- guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return self }+ guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {+ return self+ }let range = NSRange(startIndex..<endIndex, in: self)- return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replacement)+ return regex.stringByReplacingMatches(+ in: self, options: [], range: range, withTemplate: replacement)}}diff --git a/apple/apps/ensu/Ensu/Services/NotesProvider.swift b/apple/apps/ensu/Ensu/Services/NotesProvider.swiftindex 9bdce9b591..9b792a5c14 100644--- a/apple/apps/ensu/Ensu/Services/NotesProvider.swift+++ b/apple/apps/ensu/Ensu/Services/NotesProvider.swift@@ -26,8 +26,11 @@ actor NotesProvider {private let diskGate = AsyncSerialGate()private var registrations: [Registration] = []- init(root: URL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]- .appendingPathComponent("notes", isDirectory: true)) {+ init(+ root: URL = FileManager.default.urls(+ for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("notes", isDirectory: true)+ ) {self.root = root}@@ -58,8 +61,9 @@ actor NotesProvider {guard let path = Self.identityPath(registered) else { continue }let existingPrefix = path.hasSuffix("/") ? path : path + "/"guard canonical != path,- !canonical.hasPrefix(existingPrefix),- !path.hasPrefix(selectedPrefix) else {+ !canonical.hasPrefix(existingPrefix),+ !path.hasPrefix(selectedPrefix)+ else {throw NotesError.InvalidInput(detail: "This folder overlaps a folder already added to Your Notes.")@@ -71,7 +75,8 @@ actor NotesProvider {includingResourceValuesForKeys: [.pathKey],relativeTo: nil)- let source = try IOSNotesSource(bookmark: bookmark, cancellation: NotesCancellation())+ let source = try IOSNotesSource(+ bookmark: bookmark, cancellation: NotesCancellation())let record = Registration(id: UUID().uuidString.lowercased(),label: source.root.lastPathComponent,@@ -109,7 +114,9 @@ actor NotesProvider {}}- func inspectFreshness(_ id: String, operation: NotesReadOperation) async throws -> NotesFreshness {+ func inspectFreshness(_ id: String, operation: NotesReadOperation) async throws+ -> NotesFreshness+ {try await diskGate.withLock {let root = self.rootlet record = try self.registration(id)@@ -174,9 +181,11 @@ actor NotesProvider {let bytes = try Self.readVerified(record, reference, operation: operation)let folder = FileManager.default.temporaryDirectory.appendingPathComponent("note-preview-" + UUID().uuidString)- try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ try FileManager.default.createDirectory(+ at: folder, withIntermediateDirectories: true)do {- let url = folder.appendingPathComponent((reference.documentId as NSString).lastPathComponent)+ let url = folder.appendingPathComponent(+ (reference.documentId as NSString).lastPathComponent)try bytes.write(to: url, options: [.atomic, .completeFileProtection])return url} catch {@@ -194,7 +203,9 @@ actor NotesProvider {return record}- private static func source(_ record: Registration, operation: NotesReadOperation) throws -> IOSNotesSource {+ private static func source(_ record: Registration, operation: NotesReadOperation) throws+ -> IOSNotesSource+ {try IOSNotesSource(bookmark: record.bookmark,cancellation: operation.cancellation,@@ -224,8 +235,9 @@ actor NotesProvider {) {return url.standardizedFileURL.resolvingSymlinksInPath().path}- return record.canonicalPath ??- (NSURL.resourceValues(forKeys: [.pathKey], fromBookmarkData: record.bookmark)?[.pathKey] as? String)+ return record.canonicalPath+ ?? (NSURL.resourceValues(forKeys: [.pathKey], fromBookmarkData: record.bookmark)?[+ .pathKey] as? String)}private static func handle(_ root: URL, _ id: String) throws -> NotesCollection {@@ -244,11 +256,17 @@ actor NotesProvider {let registry = try JSONDecoder().decode(Registry.self, from: data)let registeredIds = Set(registry.collections.map(\.id))guard registry.schemaVersion == 1,- registeredIds.count == registry.collections.count,- registry.collections.allSatisfy({ UUID(uuidString: $0.id)?.uuidString.lowercased() == $0.id }) else {+ registeredIds.count == registry.collections.count,+ registry.collections.allSatisfy({+ UUID(uuidString: $0.id)?.uuidString.lowercased() == $0.id+ })+ else {throw NotesError.InvalidInput(detail: "Invalid Notes registry.")}- for child in (try? FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)) ?? [] {+ for child+ in (try? FileManager.default.contentsOfDirectory(+ at: root, includingPropertiesForKeys: nil)) ?? []+ {let id = child.lastPathComponentif !registeredIds.contains(id), UUID(uuidString: id)?.uuidString.lowercased() == id {try? handle(root, id).remove()@@ -258,7 +276,9 @@ actor NotesProvider {for index in records.indices where records[index].canonicalPath == nil {records[index].canonicalPath = identityPath(records[index])}- if zip(registry.collections, records).contains(where: { $0.canonicalPath != $1.canonicalPath }) {+ if zip(registry.collections, records).contains(where: {+ $0.canonicalPath != $1.canonicalPath+ }) {try? save(records, root: root)}return records@@ -278,7 +298,9 @@ actor NotesProvider {guard data.count <= 1024 * 1024 else {throw NotesError.InvalidInput(detail: "Notes registry is too large.")}- try data.write(to: root.appendingPathComponent("collections.json"), options: [.atomic, .completeFileProtection])+ try data.write(+ to: root.appendingPathComponent("collections.json"),+ options: [.atomic, .completeFileProtection])}}diff --git a/apple/apps/ensu/Ensu/Services/NotesStore.swift b/apple/apps/ensu/Ensu/Services/NotesStore.swiftindex 201bc36b01..d19d73cdfb 100644--- a/apple/apps/ensu/Ensu/Services/NotesStore.swift+++ b/apple/apps/ensu/Ensu/Services/NotesStore.swift@@ -77,8 +77,10 @@ final class NotesStore: ObservableObject, ModelMaintenance {collections.append(NoteCollectionState(id: record.id, label: record.label))enqueue(record.id, rebuild: true, due: .distantPast)} catch {- collections.append(NoteCollectionState(id: record.id, label: record.label, status: .error,- error: Self.message(error)))+ collections.append(+ NoteCollectionState(+ id: record.id, label: record.label, status: .error,+ error: Self.message(error)))}}loaded = true@@ -162,7 +164,8 @@ final class NotesStore: ObservableObject, ModelMaintenance {func retry(_ id: String) {guard let collection = collections.first(where: { $0.id == id }),- collection.status == .error || collection.status == .unavailable else {+ collection.status == .error || collection.status == .unavailable+ else {return}failed.remove(id)@@ -209,16 +212,18 @@ final class NotesStore: ObservableObject, ModelMaintenance {continue}guard accepted < Int(limits.maxGroundingHits),- collections.contains(where: { $0.id == reference.collectionId }) else {+ collections.contains(where: { $0.id == reference.collectionId })+ else {continue}do {let reference = try await provider.verify(reference)- result.append(GroundedExcerpt(- score: excerpt.score,- source: .localNote(reference: reference),- text: excerpt.text- ))+ result.append(+ GroundedExcerpt(+ score: excerpt.score,+ source: .localNote(reference: reference),+ text: excerpt.text+ ))accepted += 1} catch is CancellationError {throw CancellationError()@@ -250,7 +255,9 @@ final class NotesStore: ObservableObject, ModelMaintenance {}}- private func enqueue(_ id: String, forced: Set<String> = [], rebuild: Bool = false, due: Date? = nil) {+ private func enqueue(+ _ id: String, forced: Set<String> = [], rebuild: Bool = false, due: Date? = nil+ ) {guard collections.contains(where: { $0.id == id }) else { return }let old = pending[id]generation &+= 1@@ -266,11 +273,19 @@ final class NotesStore: ObservableObject, ModelMaintenance {guard loaded, !disabled, foreground, scopes == 0, active == nil else { return }wake?.cancel()let embeddingReady = modelProvider.isEmbeddingModelReady()- let request = embeddingReady ?- pending.filter { !failed.contains($0.key) && $0.value.due <= Date() }.min { $0.key < $1.key } : nil- guard let id = request?.key ?? scans.filter({ pending[$0] == nil && !failed.contains($0) }).min(),- let collection = collections.first(where: { $0.id == id }) else {- let due = embeddingReady ? pending.filter { !failed.contains($0.key) }.values.map(\.due).min() : nil+ let request =+ embeddingReady+ ? pending.filter { !failed.contains($0.key) && $0.value.due <= Date() }.min {+ $0.key < $1.key+ } : nil+ guard+ let id = request?.key+ ?? scans.filter({ pending[$0] == nil && !failed.contains($0) }).min(),+ let collection = collections.first(where: { $0.id == id })+ else {+ let due =+ embeddingReady+ ? pending.filter { !failed.contains($0.key) }.values.map(\.due).min() : nillet seconds = min(300, max(0.1, due?.timeIntervalSinceNow ?? 300))wake = Task { [weak self] indo {@@ -279,8 +294,10 @@ final class NotesStore: ObservableObject, ModelMaintenance {return}guard let self else { return }- self.scans.formUnion(self.collections.filter { $0.status != .unavailable &&- ($0.status != .error || $0.completedEmpty) }.map(\.id))+ self.scans.formUnion(+ self.collections.filter {+ $0.status != .unavailable && ($0.status != .error || $0.completedEmpty)+ }.map(\.id))self.pump()}return@@ -305,7 +322,9 @@ final class NotesStore: ObservableObject, ModelMaintenance {$0.status = hadIndex ? .updating : .indexing$0.error = nil}- let result = try await modelProvider.withEmbeddingContext(checkCancellation: cancellation.check) { context in+ let result = try await modelProvider.withEmbeddingContext(+ checkCancellation: cancellation.check+ ) { context intry await self.provider.index(id,context: context,@@ -342,7 +361,9 @@ final class NotesStore: ObservableObject, ModelMaintenance {$0.status = .pending$0.documentCount = result.summary.documentCount$0.lastUpdatedAtMs = result.summary.lastUpdatedAtMs- $0.indexAvailable = hadIndex && result.summary.initialComplete && result.summary.documentCount > 0+ $0.indexAvailable =+ hadIndex && result.summary.initialComplete+ && result.summary.documentCount > 0}}} else {@@ -351,7 +372,9 @@ final class NotesStore: ObservableObject, ModelMaintenance {$0 = Self.state(record, result.summary, progress: $0.progress)}if result.changed {- enqueue(id, forced: Set(result.forcedDocumentIds), due: result.summary.initialComplete ? nil : .distantPast)+ enqueue(+ id, forced: Set(result.forcedDocumentIds),+ due: result.summary.initialComplete ? nil : .distantPast)update(id) {$0.status = .pending$0.error = nil@@ -364,7 +387,9 @@ final class NotesStore: ObservableObject, ModelMaintenance {update(id) {$0.status = .pendingif let saved { $0.lastUpdatedAtMs = saved.lastUpdatedAtMs }- $0.indexAvailable = hadIndex && saved?.initialComplete == true && (saved?.documentCount ?? 0) > 0+ $0.indexAvailable =+ hadIndex && saved?.initialComplete == true+ && (saved?.documentCount ?? 0) > 0}} catch NotesError.RebuildRequired {if snapshot == nil {@@ -395,13 +420,18 @@ final class NotesStore: ObservableObject, ModelMaintenance {}}private static func message(_ error: Error) -> String {- guard let error = error as? NotesError else { return "Could not update Your Notes. Please try again." }+ guard let error = error as? NotesError else {+ return "Could not update Your Notes. Please try again."+ }switch error {- case .Unavailable: return "This Notes folder is unavailable. Check access and try again. If access has expired, remove the folder and add it again."+ case .Unavailable:+ return+ "This Notes folder is unavailable. Check access and try again. If access has expired, remove the folder and add it again."case .SourceChanged: return "The folder changed. Retry to update Your Notes."case .SourceRead(let detail), .InvalidInput(let detail): return detailcase .Storage: return "Could not save the Notes index. Check storage and try again."- case .RebuildRequired: return "The Notes index needs rebuilding. Retry to update Your Notes."+ case .RebuildRequired:+ return "The Notes index needs rebuilding. Retry to update Your Notes."default: return "Could not update Your Notes. Please try again."}}@@ -410,12 +440,16 @@ final class NotesStore: ObservableObject, ModelMaintenance {guard let index = collections.firstIndex(where: { $0.id == id }) else { return }body(&collections[index])}- private static func state(_ record: NotesCollectionInfo, _ summary: NotesSummary, progress: UInt8? = nil) -> NoteCollectionState {+ private static func state(+ _ record: NotesCollectionInfo, _ summary: NotesSummary, progress: UInt8? = nil+ ) -> NoteCollectionState {let ready = summary.initialComplete && summary.documentCount > 0let empty = summary.initialComplete && !ready- return NoteCollectionState(id: record.id, label: record.label,+ return NoteCollectionState(+ id: record.id, label: record.label,status: ready ? .ready : summary.initialComplete ? .error : .pending,- documentCount: summary.documentCount, lastUpdatedAtMs: summary.lastUpdatedAtMs, indexAvailable: ready,+ documentCount: summary.documentCount, lastUpdatedAtMs: summary.lastUpdatedAtMs,+ indexAvailable: ready,progress: summary.initialComplete ? nil : progress,error: empty ? emptyNotes : nil,completedEmpty: empty)diff --git a/apple/apps/ensu/Ensu/Services/WhatsNewContent.swift b/apple/apps/ensu/Ensu/Services/WhatsNewContent.swiftindex c16d210ff8..b82ac8b32f 100644--- a/apple/apps/ensu/Ensu/Services/WhatsNewContent.swift+++ b/apple/apps/ensu/Ensu/Services/WhatsNewContent.swift@@ -14,11 +14,12 @@ enum WhatsNewContent {),WhatsNewEntry(title: "Chat with Your Notes",- description: "Add your markdown notes folder, and chat with your notes. Ask questions or discuss the thoughts you put down."+ description:+ "Add your markdown notes folder, and chat with your notes. Ask questions or discuss the thoughts you put down."),WhatsNewEntry(title: "Gemma for high RAM phones",description: "For phones with >8GB RAM, Gemma 4 is the new default model."- )+ ),]}diff --git a/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swift b/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swiftindex 23c66325b6..4780f1a214 100644--- a/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swift+++ b/apple/apps/ensu/Ensu/Settings/KnowledgeSettingsView.swift@@ -125,13 +125,17 @@ private struct PackAttributionSheet: View {.foregroundStyle(EnsuColor.textPrimary)HStack(spacing: EnsuSpacing.md) {- Link(destination: URL(string: attribution.publicPackUrl)!) {- Label("Source", systemImage: "arrow.up.right.square")- .frame(minHeight: 44)+ if let sourceUrl = URL(string: attribution.publicPackUrl) {+ Link(destination: sourceUrl) {+ Label("Source", systemImage: "arrow.up.right.square")+ .frame(minHeight: 44)+ }}- Link(destination: URL(string: attribution.licenseUrl)!) {- Label("License", systemImage: "doc.text")- .frame(minHeight: 44)+ if let licenseUrl = URL(string: attribution.licenseUrl) {+ Link(destination: licenseUrl) {+ Label("License", systemImage: "doc.text")+ .frame(minHeight: 44)+ }}}.font(EnsuTypography.mini)@@ -140,9 +144,11 @@ private struct PackAttributionSheet: View {Divider()- Text("Wikimedia and Ensu are not affiliated. Wikimedia project names identify the source material only.")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)+ Text(+ "Wikimedia and Ensu are not affiliated. Wikimedia project names identify the source material only."+ )+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)}}}diff --git a/apple/apps/ensu/Ensu/Settings/LogsView.swift b/apple/apps/ensu/Ensu/Settings/LogsView.swiftindex c36702d651..b0e8bd8862 100644--- a/apple/apps/ensu/Ensu/Settings/LogsView.swift+++ b/apple/apps/ensu/Ensu/Settings/LogsView.swift@@ -133,14 +133,17 @@ struct LogsView: View {for line in text.components(separatedBy: .newlines) {guard !line.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { continue }- if let match = logLineRegex.firstMatch(in: line, options: [], range: NSRange(line.startIndex..., in: line)),- let tagRange = Range(match.range(at: 1), in: line),- let levelRange = Range(match.range(at: 2), in: line),- let timestampRange = Range(match.range(at: 3), in: line),- let messageRange = Range(match.range(at: 4), in: line) {+ if let match = logLineRegex.firstMatch(+ in: line, options: [], range: NSRange(line.startIndex..., in: line)),+ let tagRange = Range(match.range(at: 1), in: line),+ let levelRange = Range(match.range(at: 2), in: line),+ let timestampRange = Range(match.range(at: 3), in: line),+ let messageRange = Range(match.range(at: 4), in: line)+ {entries.append(EnsuLogEntry(- timestamp: logLineFormatter.date(from: String(line[timestampRange])) ?? Date(),+ timestamp: logLineFormatter.date(from: String(line[timestampRange]))+ ?? Date(),level: EnsuLogLevel(rawValue: String(line[levelRange])) ?? .info,tag: String(line[tagRange]),message: String(line[messageRange]),@@ -157,7 +160,8 @@ struct LogsView: View {)} else {entries.append(- EnsuLogEntry(timestamp: Date(), level: .info, tag: "Log", message: line, details: nil)+ EnsuLogEntry(+ timestamp: Date(), level: .info, tag: "Log", message: line, details: nil))}}@@ -322,6 +326,7 @@ private let logLineFormatter: DateFormatter = {private let logLineRegex: NSRegularExpression = {let pattern = "^\\[(.+?)\\]\\[(.+?)\\] \\[(.+?)\\] (.*)$"+ // swift-format-ignore: NeverUseForceTryreturn try! NSRegularExpression(pattern: pattern, options: [])}()@@ -346,6 +351,7 @@ struct ExportDocumentPicker: UIViewControllerRepresentable {return picker}- func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {}+ func updateUIViewController(+ _ uiViewController: UIDocumentPickerViewController, context: Context+ ) {}}-diff --git a/apple/apps/ensu/Ensu/Settings/NotesSettingsView.swift b/apple/apps/ensu/Ensu/Settings/NotesSettingsView.swiftindex 8dec591358..19bee6af5d 100644--- a/apple/apps/ensu/Ensu/Settings/NotesSettingsView.swift+++ b/apple/apps/ensu/Ensu/Settings/NotesSettingsView.swift@@ -24,7 +24,10 @@ struct NotesSettingsView: View {.fixedSize(horizontal: false, vertical: true)}Spacer()- ActionButton(icon: "Delete01Icon", tooltip: "Remove \(collection.label)", size: 44) {+ ActionButton(+ icon: "Delete01Icon", tooltip: "Remove \(collection.label)",+ size: 44+ ) {removing = collection}}@@ -59,9 +62,11 @@ struct NotesSettingsView: View {CompactButton(text: "Add notes folder") {showPicker = true}- Text("Ensu reads and indexes markdown files in the selected folder. Source files are never modified.")- .font(EnsuTypography.small)- .foregroundStyle(EnsuColor.textMuted)+ Text(+ "Ensu reads and indexes markdown files in the selected folder. Source files are never modified."+ )+ .font(EnsuTypography.small)+ .foregroundStyle(EnsuColor.textMuted)if let error = store.operationError {Text(error).font(EnsuTypography.small)@@ -74,19 +79,26 @@ struct NotesSettingsView: View {.navigationTitle("Your Notes").navigationBarTitleDisplayMode(.inline).sheet(isPresented: $showPicker) { NotesFolderPicker { store.add($0) } }- .alert("Remove folder?", isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } })) {+ .alert(+ "Remove folder?",+ isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } })+ ) {Button("Remove", role: .destructive) {if let collection = removing { store.remove(collection.id) }removing = nil}Button("Cancel", role: .cancel) { removing = nil }- } message: { Text("Remove this folder from Your Notes? Your original files will be kept.") }+ } message: {+ Text("Remove this folder from Your Notes? Your original files will be kept.")+ }}private func summary(_ collection: NoteCollectionState) -> String {let count = collection.documentCountlet indexing = collection.status == .indexing || collection.status == .updating- var text = indexing && count == 0 ? "Preparing notes…" : "\(count) \(count == 1 ? "note indexed" : "notes indexed")"+ var text =+ indexing && count == 0+ ? "Preparing notes…" : "\(count) \(count == 1 ? "note indexed" : "notes indexed")"if let timestamp = collection.lastUpdatedAtMs {let date = Date(timeIntervalSince1970: Double(timestamp) / 1000)text += " · Updated at \(date.formatted(date: .abbreviated, time: .shortened))"@@ -99,7 +111,8 @@ private struct NotesFolderPicker: UIViewControllerRepresentable {let selected: (URL) -> Voidfunc makeCoordinator() -> Coordinator { Coordinator(selected: selected) }func makeUIViewController(context: Context) -> UIDocumentPickerViewController {- let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.folder], asCopy: false)+ let picker = UIDocumentPickerViewController(+ forOpeningContentTypes: [.folder], asCopy: false)picker.allowsMultipleSelection = falsepicker.delegate = context.coordinatorreturn picker@@ -108,7 +121,9 @@ private struct NotesFolderPicker: UIViewControllerRepresentable {final class Coordinator: NSObject, UIDocumentPickerDelegate {let selected: (URL) -> Voidinit(selected: @escaping (URL) -> Void) { self.selected = selected }- func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {+ func documentPicker(+ _ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]+ ) {if let url = urls.first { selected(url) }}}@@ -123,7 +138,9 @@ struct NotesPreviewView: UIViewControllerRepresentable {return preview}func updateUIViewController(_ controller: QLPreviewController, context: Context) {}- static func dismantleUIViewController(_ controller: QLPreviewController, coordinator: Coordinator) {+ static func dismantleUIViewController(+ _ controller: QLPreviewController, coordinator: Coordinator+ ) {controller.dataSource = niltry? FileManager.default.removeItem(at: coordinator.url.deletingLastPathComponent())}@@ -131,6 +148,8 @@ struct NotesPreviewView: UIViewControllerRepresentable {let url: URLinit(url: URL) { self.url = url }func numberOfPreviewItems(in controller: QLPreviewController) -> Int { 1 }- func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { url as NSURL }+ func previewController(_ controller: QLPreviewController, previewItemAt index: Int)+ -> QLPreviewItem+ { url as NSURL }}}diff --git a/apple/apps/ensu/Ensu/Settings/SettingsView.swift b/apple/apps/ensu/Ensu/Settings/SettingsView.swiftindex a7d6291365..db83436b5e 100644--- a/apple/apps/ensu/Ensu/Settings/SettingsView.swift+++ b/apple/apps/ensu/Ensu/Settings/SettingsView.swift@@ -24,7 +24,9 @@ struct SettingsView: View {VStack(alignment: .leading, spacing: EnsuSpacing.lg) {if let aboutItem = filteredAboutItem {Button(action: aboutItem.action) {- settingsCard(title: aboutItem.title, iconName: aboutItem.iconName, showsChevron: true)+ settingsCard(+ title: aboutItem.title, iconName: aboutItem.iconName,+ showsChevron: true)}.buttonStyle(.plain)}@@ -33,21 +35,24 @@ struct SettingsView: View {NavigationLink {item.destination} label: {- settingsCard(title: item.title, iconName: item.iconName, showsChevron: true)+ settingsCard(+ title: item.title, iconName: item.iconName, showsChevron: true)}.buttonStyle(.plain)}if shouldShowSignInRow {Button(action: onSignIn) {- settingsCard(title: signInTitle, iconName: "Upload01Icon", showsChevron: true)+ settingsCard(+ title: signInTitle, iconName: "Upload01Icon", showsChevron: true)}.buttonStyle(.plain)}ForEach(filteredLegalLinkItems) { item inButton(action: item.action) {- settingsCard(title: item.title, iconName: item.iconName, showsChevron: true)+ settingsCard(+ title: item.title, iconName: item.iconName, showsChevron: true)}.buttonStyle(.plain)}@@ -62,7 +67,8 @@ struct SettingsView: View {NavigationLink {item.destination} label: {- settingsCard(title: item.title, iconName: item.iconName, showsChevron: true)+ settingsCard(+ title: item.title, iconName: item.iconName, showsChevron: true)}.buttonStyle(.plain)}@@ -139,7 +145,7 @@ struct SettingsView: View {title: "Terms of Service",iconName: "DescriptionIcon",action: { openExternalLink("https://ente.com/terms") }- )+ ),]}@@ -166,17 +172,20 @@ struct SettingsView: View {private var signInTitle: String { "Sign In to Backup" }private var allItems: [SettingsItem] {- var items = [SettingsItem(- title: "Your Notes",- iconName: "Folder01Icon",- destination: AnyView(NotesSettingsView(store: notesStore))- )]+ var items = [+ SettingsItem(+ title: "Your Notes",+ iconName: "Folder01Icon",+ destination: AnyView(NotesSettingsView(store: notesStore))+ )+ ]if isEnsuPacksEnabled {- items.append(SettingsItem(- title: "Ensu Packs",- iconName: "PackageIcon",- destination: AnyView(KnowledgeSettingsView(store: knowledgeStore))- ))+ items.append(+ SettingsItem(+ title: "Ensu Packs",+ iconName: "PackageIcon",+ destination: AnyView(KnowledgeSettingsView(store: knowledgeStore))+ ))}items.append(SettingsItem(@@ -199,7 +208,7 @@ struct SettingsView: View {title: "System prompt",iconName: "Edit01Icon",destination: AnyView(SystemPromptSettingsView(embeddedInNavigation: true))- )+ ),]}@@ -341,7 +350,8 @@ private struct SystemPromptSettingsView: View {.padding(.horizontal, EnsuSpacing.inputHorizontal).padding(.vertical, EnsuSpacing.inputVertical).background(EnsuColor.fillFaint)- .clipShape(RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))+ .clipShape(+ RoundedRectangle(cornerRadius: EnsuCornerRadius.input, style: .continuous))Text("Leave this blank to use the default prompt.").font(EnsuTypography.small)@@ -377,7 +387,8 @@ private struct SystemPromptSettingsView: View {Task { @MainActor intry? await Task.sleep(nanoseconds: 200_000_000)let trimmedPrompt = promptBody.trimmingCharacters(in: .whitespacesAndNewlines)- let defaultPrompt = ModelSettingsStore.defaultSystemPromptBody.trimmingCharacters(in: .whitespacesAndNewlines)+ let defaultPrompt = ModelSettingsStore.defaultSystemPromptBody.trimmingCharacters(+ in: .whitespacesAndNewlines)settings.systemPromptBody = trimmedPrompt == defaultPrompt ? "" : trimmedPromptpromptBody = ModelSettingsStore.resolveSystemPromptBody(settings.systemPromptBody)isSaving = falsediff --git a/apple/apps/ensu/Ensu/Utils/Haptics.swift b/apple/apps/ensu/Ensu/Utils/Haptics.swiftindex b715dc3c14..269ec6c0b2 100644--- a/apple/apps/ensu/Ensu/Utils/Haptics.swift+++ b/apple/apps/ensu/Ensu/Utils/Haptics.swift@@ -31,4 +31,3 @@ func hapticWarning() {func hapticError() {UINotificationFeedbackGenerator().notificationOccurred(.error)}-diff --git a/apple/apps/ensu/EnsuTests/LlmIntegrationTests.swift b/apple/apps/ensu/EnsuTests/LlmIntegrationTests.swiftindex 74c37507ff..e81c9f0a90 100644--- a/apple/apps/ensu/EnsuTests/LlmIntegrationTests.swift+++ b/apple/apps/ensu/EnsuTests/LlmIntegrationTests.swift@@ -54,7 +54,7 @@ final class LlmIntegrationTests: XCTestCase {let request = LlmChatRequest(messages: [LlmChatMessage(role: "system", content: "You are a helpful assistant."),- LlmChatMessage(role: "user", content: "Say hello in one short sentence.")+ LlmChatMessage(role: "user", content: "Say hello in one short sentence."),],templateOverride: nil,addAssistant: true,@@ -104,7 +104,7 @@ final class LlmIntegrationTests: XCTestCase {let request = LlmChatRequest(messages: [LlmChatMessage(role: "system", content: "You are a helpful assistant."),- LlmChatMessage(role: "user", content: "What color is the car? Answer in one word.")+ LlmChatMessage(role: "user", content: "What color is the car? Answer in one word."),],templateOverride: nil,addAssistant: true,diff --git a/apple/apps/ensu/EnsuTests/NotesIntegrationTests.swift b/apple/apps/ensu/EnsuTests/NotesIntegrationTests.swiftindex 96f39adfc0..0c3ea12698 100644--- a/apple/apps/ensu/EnsuTests/NotesIntegrationTests.swift+++ b/apple/apps/ensu/EnsuTests/NotesIntegrationTests.swift@@ -14,14 +14,19 @@ final class NotesIntegrationTests: XCTestCase {func testNativeSourceFailureAndCancellationCrossTheBridge() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)defer { try? FileManager.default.removeItem(at: root) }- let collection = try NotesCollection(indexRoot: root.path, collectionId: UUID().uuidString.lowercased())+ let collection = try NotesCollection(+ indexRoot: root.path, collectionId: UUID().uuidString.lowercased())let source = UnavailableNotesSource()- XCTAssertThrowsError(try collection.inspectFreshness(source: source, cancellation: NotesCancellation())) {+ XCTAssertThrowsError(+ try collection.inspectFreshness(source: source, cancellation: NotesCancellation())+ ) {XCTAssertEqual($0 as? NotesError, .Unavailable)}let cancellation = NotesCancellation()cancellation.cancel()- XCTAssertThrowsError(try collection.inspectFreshness(source: source, cancellation: cancellation)) {+ XCTAssertThrowsError(+ try collection.inspectFreshness(source: source, cancellation: cancellation)+ ) {XCTAssertEqual($0 as? NotesError, .Cancelled)}}diff --git a/apple/scripts/lint.sh b/apple/scripts/lint.shindex 82316a7bef..a4451c4f9c 100755--- a/apple/scripts/lint.sh+++ b/apple/scripts/lint.sh@@ -3,7 +3,6 @@ set -eo pipefailcd "$(dirname "$0")/.."-# TODO: Include Ensu.-git ls-files -z --cached --others --exclude-standard -- '*.swift' ':!:apps/ensu/**' |+git ls-files -z --cached --others --exclude-standard -- '*.swift' |xargs -0 swift format lint --strictswift package plugin --allow-writing-to-package-directory swiftlint lint --strict