Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraUI/Sources/Knowledge/KnowledgeScreen.swift10// Module : Knowledge11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2214//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import UniformTypeIdentifiers90import AstraCore91import AstraDesign92import AstraPersistence9394/// Local documents for retrieval: import, list, delete, and the same search an agent's `document_search` runs.95/// Push it on any navigation stack; it needs only the app model from the environment.96struct KnowledgeScreen: View {97 @Environment(AppModel.self) private var app98 @State private var model: KnowledgeController?99100 var body: some View {101 Group {102 if let model { KnowledgeContent(model: model) }103 else { ProgressView("Opening Knowledge").frame(maxWidth: .infinity, maxHeight: .infinity) }104 }105 .background(Starfield(density: 0.35))106 .navigationTitle("Knowledge").navigationBarTitleDisplayMode(.inline)107 .task {108 if model == nil { model = KnowledgeController(store: app.store) }109 await model?.reload()110 }111 }112}113114private struct KnowledgeContent: View {115 @Environment(AppModel.self) private var app116 @Bindable var model: KnowledgeController117 @State private var showImporter = false118 @State private var deleting: KnowledgeController.Item?119 @State private var expandedHit: String?120 @FocusState private var searchFocused: Bool121122 static let importTypes: [UTType] = [.pdf, .text, .sourceCode, .json, .xml, .commaSeparatedText]123124 var body: some View {125 ScrollView {126 VStack(alignment: .leading, spacing: AstraSpace.xl) {127 privacyCard128 importSection129 if !model.items.isEmpty { searchSection }130 documentsSection131 }132 .padding(.horizontal, AstraSpace.page).padding(.vertical, AstraSpace.lg)133 }134 .scrollDismissesKeyboard(.interactively)135 .refreshable { await model.reload() }136 .toolbar {137 ToolbarItem(placement: .topBarTrailing) {138 Button { showImporter = true } label: { Image(systemName: "plus") }139 .disabled(model.isImporting)140 .accessibilityLabel("Import documents").accessibilityIdentifier("knowledge-import-toolbar")141 }142 }143 .fileImporter(isPresented: $showImporter, allowedContentTypes: Self.importTypes, allowsMultipleSelection: true) { result in144 switch result {145 case .success(let urls):146 model.importFiles(urls) { added in147 if added > 0 { AstraHaptics.success(); app.show(added == 1 ? "1 document indexed" : "\(added) documents indexed", .success) }148 else if model.issues.isEmpty { app.show("Nothing was imported.", .info) }149 }150 case .failure(let error): app.show(AstraError.wrap(error).message, .error)151 }152 }153 .task(id: model.query) {154 // Typing pauses briefly before the index is queried.155 try? await Task.sleep(nanoseconds: 220_000_000)156 guard !Task.isCancelled else { return }157 await model.search()158 }159 .confirmationDialog("Delete “\(deleting?.document.name ?? "")”?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible) {160 Button("Delete document", role: .destructive) { if let item = deleting { delete(item) } }161 Button("Cancel", role: .cancel) {}162 } message: { Text("Its passages leave the index. The original file in Files is not touched.") }163 }164165 private func delete(_ item: KnowledgeController.Item) {166 Task {167 do {168 let freed = try await model.delete(item)169 app.show(freed > 0 ? "Deleted. \(AgentFormat.bytes(freed)) freed in the app's database." : "Deleted.", .success)170 } catch { app.show(AstraError.wrap(error).message, .error) }171 }172 }173174 // MARK: Privacy175176 private var privacyCard: some View {177 AstraCard(tint: AstraColor.accentSoft) {178 HStack(alignment: .top, spacing: AstraSpace.md) {179 Image(systemName: "lock.doc").font(.title3).foregroundStyle(AstraColor.indigo).accessibilityHidden(true)180 VStack(alignment: .leading, spacing: AstraSpace.xs) {181 Text("Indexed and searched on this iPhone").font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary)182 Text("Documents are split into passages and searched with an on-device full-text index ranked by BM25. No embeddings are computed and nothing is uploaded. A retrieved passage leaves the iPhone only when the agent or chat using it runs on a cloud model: it is then sent to that provider as part of the conversation.")183 .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)184 }185 }186 }187 .accessibilityElement(children: .combine)188 .accessibilityIdentifier("knowledge-privacy")189 }190191 // MARK: Import192193 private var importSection: some View {194 VStack(alignment: .leading, spacing: AstraSpace.md) {195 if let progress = model.progress {196 AstraCard {197 VStack(alignment: .leading, spacing: AstraSpace.sm) {198 HStack(spacing: AstraSpace.sm) {199 ProgressView().controlSize(.small)200 Text("\(progress.stage) file \(progress.index) of \(progress.total)").font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary)201 }202 Text(progress.fileName).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).lineLimit(2).truncationMode(.middle)203 if progress.total > 1 { AstraProgressBar(progress.fraction) }204 Button("Stop importing") { model.cancelImport() }205 .buttonStyle(AstraSecondaryButtonStyle(compact: true)).accessibilityIdentifier("knowledge-import-cancel")206 }207 }208 .accessibilityIdentifier("knowledge-import-progress")209 } else {210 Button { showImporter = true } label: { Label("Import documents", systemImage: "square.and.arrow.down") }211 .buttonStyle(AstraPrimaryButtonStyle())212 .accessibilityIdentifier("knowledge-import")213 Text("PDFs with a text layer, text, Markdown and source files, up to 20 MB each. Scanned PDFs cannot be indexed: no text recognition is run.")214 .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)215 }216 if !model.issues.isEmpty {217 ForEach(model.issues) { issue in218 NoticeCard(issue.kind == .failed ? .error : (issue.kind == .truncated ? .warning : .info),219 title: issue.kind == .failed ? "“\(issue.fileName)” was not imported" : "“\(issue.fileName)”", message: issue.message)220 }221 Button("Dismiss") { model.dismissIssues() }222 .font(AstraFont.footnote.weight(.semibold)).foregroundStyle(AstraColor.violet)223 .frame(minHeight: AstraSpace.hit, alignment: .leading).accessibilityIdentifier("knowledge-issues-dismiss")224 }225 }226 }227228 // MARK: Search229230 private var searchSection: some View {231 VStack(alignment: .leading, spacing: AstraSpace.md) {232 SectionTitle("Try a search", detail: "What an agent would retrieve")233 HStack(spacing: AstraSpace.sm) {234 Image(systemName: "magnifyingglass").foregroundStyle(AstraColor.textTertiary).accessibilityHidden(true)235 TextField("Words to look for", text: $model.query)236 .textInputAutocapitalization(.never).submitLabel(.search).focused($searchFocused)237 .accessibilityLabel("Search your documents").accessibilityIdentifier("knowledge-search")238 if model.isSearching { ProgressView().controlSize(.small) }239 if !model.query.isEmpty {240 IconButton("xmark.circle.fill", label: "Clear search", tint: AstraColor.textTertiary) { model.query = ""; expandedHit = nil }241 }242 }243 .padding(.leading, AstraSpace.md).frame(minHeight: AstraSpace.hit + AstraSpace.xs)244 .background(AstraColor.surface, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))245 .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(searchFocused ? AstraColor.violet : AstraColor.stroke, lineWidth: 1))246247 if let error = model.searchError {248 NoticeCard(.error, title: "The search failed", message: error)249 } else if !model.searchedQuery.isEmpty {250 if model.hits.isEmpty {251 Text("No passage matches “\(model.searchedQuery)”. An agent would be told the same.")252 .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)253 .accessibilityIdentifier("knowledge-search-empty")254 } else {255 ForEach(Array(model.hits.enumerated()), id: \.element.id) { index, hit in hitCard(index: index, hit: hit) }256 Text("Best match first, ranked by BM25. An agent's search returns the first 5 of these by default, 10 at most, each cut at 1,500 characters.")257 .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)258 }259 }260 }261 }262263 private func hitCard(index: Int, hit: ChunkHit) -> some View {264 let expanded = expandedHit == hit.id265 let excerpt = KnowledgeSnippet.excerpt(hit.chunk.text, query: model.searchedQuery)266 return Button {267 expandedHit = expanded ? nil : hit.id268 } label: {269 AstraCard(padding: AstraSpace.md, radius: AstraRadius.md) {270 VStack(alignment: .leading, spacing: AstraSpace.sm) {271 HStack(alignment: .firstTextBaseline, spacing: AstraSpace.sm) {272 Text("[\(index + 1)]").font(AstraFont.monoSmall.weight(.semibold)).foregroundStyle(AstraColor.violet)273 Text(hit.documentName).font(AstraFont.subheadline.weight(.semibold)).foregroundStyle(AstraColor.textPrimary).lineLimit(2).multilineTextAlignment(.leading)274 Spacer(minLength: 0)275 Image(systemName: expanded ? "chevron.up" : "chevron.down").font(.caption.weight(.semibold)).foregroundStyle(AstraColor.textTertiary)276 }277 FlowLayout(spacing: AstraSpace.xs) {278 AstraBadge("Passage \(hit.chunk.ordinal + 1)", symbol: "text.alignleft")279 AstraBadge(hit.score > 0 ? String(format: "BM25 %.2f", hit.score) : "Substring match", symbol: "chart.bar")280 }281 Group {282 if expanded { Text(hit.chunk.text) } else { Text(KnowledgeSnippet.highlighted(excerpt, query: model.searchedQuery)) }283 }284 .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).multilineTextAlignment(.leading)285 .frame(maxWidth: .infinity, alignment: .leading)286 }287 }288 }289 .buttonStyle(.plain)290 .accessibilityElement(children: .combine)291 .accessibilityHint(expanded ? "Shows the excerpt" : "Shows the whole passage")292 .accessibilityIdentifier("knowledge-hit-\(index + 1)")293 }294295 // MARK: Documents296297 private var documentsSection: some View {298 VStack(alignment: .leading, spacing: AstraSpace.md) {299 SectionTitle("Documents", detail: model.items.isEmpty ? nil : totalsLine)300 if let error = model.loadError {301 NoticeCard(.error, title: "The documents could not be loaded", message: error, actionTitle: "Try again") { Task { await model.reload() } }302 }303 if !model.isLoaded {304 ProgressView().frame(maxWidth: .infinity).padding(.vertical, AstraSpace.xl)305 } else if model.items.isEmpty && model.loadError == nil {306 AstraCard {307 VStack(alignment: .leading, spacing: AstraSpace.xs) {308 Text("No document yet").font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary)309 Text("Import a report, notes or source files. An agent whose profile includes “Search your documents” can then quote them, after asking you.")310 .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)311 }312 }313 .accessibilityIdentifier("knowledge-empty")314 } else {315 ForEach(model.items) { item in documentCard(item) }316 }317 }318 }319320 private var totalsLine: String {321 "\(model.items.count) · \(AgentFormat.bytes(Int64(model.totalBytes))) of text · \(AgentFormat.count(model.totalChunks)) passages"322 }323324 private func documentCard(_ item: KnowledgeController.Item) -> some View {325 AstraCard(padding: 0) {326 HStack(alignment: .center, spacing: 0) {327 HStack(alignment: .top, spacing: AstraSpace.md) {328 Image(systemName: symbol(item.document.kind)).font(.title3).foregroundStyle(AstraColor.violet).frame(width: 30).accessibilityHidden(true)329 VStack(alignment: .leading, spacing: AstraSpace.xs) {330 Text(item.document.name).font(AstraFont.bodyEmphasis).foregroundStyle(AstraColor.textPrimary).lineLimit(3)331 Text("\(AgentFormat.bytes(Int64(item.document.byteSize))) of text · \(item.chunkCount == 1 ? "1 passage" : "\(AgentFormat.count(item.chunkCount)) passages")")332 .font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)333 Text("\(kindLabel(item.document.kind)) · added \(AgentFormat.stamp(item.document.createdAt))")334 .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)335 }336 Spacer(minLength: 0)337 }338 .padding(.leading, AstraSpace.lg).padding(.vertical, AstraSpace.lg)339 .accessibilityElement(children: .combine)340 IconButton("trash", label: "Delete \(item.document.name)", tint: AstraColor.danger) { deleting = item }341 .padding(.horizontal, AstraSpace.xs)342 .accessibilityIdentifier("knowledge-delete")343 }344 }345 }346347 private func symbol(_ kind: String) -> String {348 switch kind {349 case "pdf": "doc.richtext"350 case "markdown": "doc.plaintext"351 case "source": "chevron.left.forwardslash.chevron.right"352 default: "doc.text"353 }354 }355356 private func kindLabel(_ kind: String) -> String {357 switch kind {358 case "pdf": "PDF"359 case "markdown": "Markdown"360 case "source": "Source file"361 default: "Text"362 }363 }364}365