Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Workspace/FilesScreen.swift3// Description: File library: every uploaded file with its indexing state, storage gauge, Quick Look, save, re-index, delete, and upload into a project's knowledge base.4import SwiftUI5import QuickLook6import UniformTypeIdentifiers7import SPChatCore89/// Uploads in flight, updated from the transport's progress callback.10@Observable final class FilesUploadQueue {11 struct Item: Identifiable { let id = UUID(); var name: String; var progress: Double }12 var items: [Item] = []13 func add(_ name: String) -> UUID { let item = Item(name: name, progress: 0); items.append(item); return item.id }14 func setProgress(_ id: UUID, _ value: Double) { if let i = items.firstIndex(where: { $0.id == id }) { items[i].progress = min(max(value, 0), 1) } }15 func remove(_ id: UUID) { items.removeAll { $0.id == id } }16}1718struct FilesScreen: View {19 @Environment(AppEnvironment.self) private var env20 @State private var files: [Attachment] = []21 @State private var usedBytes = 022 @State private var quotaMb = 023 @State private var loaded = false24 @State private var loadError: String?25 @State private var query = ""26 @State private var projectFilter: String?27 @State private var refreshToken = 028 @State private var selection: Set<String> = []29 @State private var busy: Set<String> = []30 @State private var previewURL: URL?31 @State private var deleting: Attachment?32 @State private var uploads = FilesUploadQueue()33 @State private var importing = false34 @State private var importProject: String?35 @State private var dropped: [URL] = []36 @State private var choosingDropProject = false37 @State private var dropTargeted = false3839 private var loadKey: String { "\(query.trimmingCharacters(in: .whitespaces))|\(projectFilter ?? "")|\(refreshToken)" }4041 var body: some View {42 VStack(spacing: 0) {43 header44 uploadStrip45 Divider()46 content47 }48 .overlay { if dropTargeted { RoundedRectangle(cornerRadius: Metrics.corner).strokeBorder(Palette.iris, lineWidth: 2).padding(6).allowsHitTesting(false) } }49 .task(id: loadKey) { await loadLoop() }50 .quickLookPreview($previewURL)51 .fileImporter(isPresented: $importing, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in52 switch result {53 case .success(let urls): if let id = importProject { upload(urls, to: id) }54 case .failure(let error): env.toasts.error(error)55 }56 }57 .onDrop(of: [.fileURL], isTargeted: $dropTargeted) { providers in58 for p in providers { _ = p.loadObject(ofClass: URL.self) { url, _ in if let url { Task { @MainActor in received(url) } } } }59 return true60 }61 .confirmationDialog("Dans quel projet ajouter ces fichiers ?", isPresented: $choosingDropProject, titleVisibility: .visible) {62 ForEach(env.catalog.projects) { p in Button(p.name) { let urls = dropped; dropped = []; upload(urls, to: p.id) } }63 Button("Annuler", role: .cancel) { dropped = [] }64 } message: { Text("\(dropped.count) fichier\(dropped.count > 1 ? "s" : "") à téléverser dans la base de connaissances du projet choisi.") }65 .confirmationDialog("Supprimer ce fichier ?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }), titleVisibility: .visible, presenting: deleting) { a in66 Button("Supprimer", role: .destructive) { delete(a) }67 Button("Annuler", role: .cancel) {}68 } message: { a in69 Text("« \(a.filename) » sera supprimé du serveur avec son texte extrait et son index de recherche." + (a.conversationTitle.map { " Il restera mentionné dans « \($0) » mais ne pourra plus être ouvert." } ?? ""))70 }71 }7273 // MARK: Header7475 private var header: some View {76 VStack(alignment: .leading, spacing: 10) {77 HStack(spacing: 10) {78 HStack(spacing: 6) {79 Image(systemName: "magnifyingglass").foregroundStyle(.secondary)80 TextField("Rechercher par nom…", text: $query).textFieldStyle(.plain).accessibilityLabel("Rechercher un fichier")81 if !query.isEmpty { IconButton(systemImage: "xmark.circle.fill", label: "Effacer la recherche") { query = "" } }82 }83 .padding(.horizontal, 8).padding(.vertical, 5)84 .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8))85 Picker("Projet", selection: $projectFilter) {86 Text("Tous les projets").tag(String?.none)87 ForEach(env.catalog.projects) { Text($0.name).tag(String?.some($0.id)) }88 }89 .labelsHidden().frame(maxWidth: 220).accessibilityLabel("Filtrer par projet")90 Menu {91 if env.catalog.projects.isEmpty { Text("Crée d'abord un projet") }92 ForEach(env.catalog.projects) { p in Button(p.name) { importProject = p.id; importing = true } }93 } label: { Label("Téléverser…", systemImage: "square.and.arrow.up") }94 .fixedSize().disabled(!uploads.items.isEmpty).help("Ajouter des fichiers à la base de connaissances d'un projet")95 IconButton(systemImage: "arrow.clockwise", label: "Actualiser la liste") { refreshToken += 1 }96 }97 storageGauge98 }99 .padding(.horizontal, 16).padding(.vertical, 12)100 }101102 @ViewBuilder private var storageGauge: some View {103 if loaded, loadError == nil || !files.isEmpty {104 let quotaBytes = Double(quotaMb) * 1_048_576105 VStack(alignment: .leading, spacing: 4) {106 HStack {107 Text("\(files.count) fichier\(files.count > 1 ? "s" : "") affiché\(files.count > 1 ? "s" : "") · \(usedBytes > 0 ? Format.bytes(usedBytes) : "0 o") utilisés")108 Spacer()109 if quotaMb > 0 { Text("quota \(quotaMb >= 1024 ? String(format: "%.0f Go", Double(quotaMb) / 1024) : "\(quotaMb) Mo")") }110 }111 .font(.caption).foregroundStyle(.secondary)112 if quotaMb > 0 {113 ProgressView(value: min(Double(usedBytes), quotaBytes), total: quotaBytes)114 .tint(Double(usedBytes) > quotaBytes * 0.9 ? Palette.danger : Palette.iris)115 .accessibilityLabel("Stockage utilisé").accessibilityValue("\(Int(Double(usedBytes) / quotaBytes * 100)) %")116 }117 }118 }119 }120121 @ViewBuilder private var uploadStrip: some View {122 if !uploads.items.isEmpty {123 VStack(spacing: 6) {124 ForEach(uploads.items) { item in125 HStack(spacing: 10) {126 ProgressView().controlSize(.small)127 Text(item.name).lineLimit(1).truncationMode(.middle)128 ProgressView(value: item.progress).frame(maxWidth: .infinity)129 Text("\(Int(item.progress * 100)) %").font(.caption.monospacedDigit()).foregroundStyle(.secondary).frame(width: 44, alignment: .trailing)130 }131 .font(.callout).accessibilityElement(children: .combine).accessibilityLabel("Envoi de \(item.name), \(Int(item.progress * 100)) %")132 }133 }134 .padding(.horizontal, 16).padding(.bottom, 10)135 }136 }137138 // MARK: Content139140 @ViewBuilder private var content: some View {141 if !loaded {142 ProgressView("Chargement des fichiers…").frame(maxWidth: .infinity, maxHeight: .infinity)143 } else if let loadError, files.isEmpty {144 VStack(spacing: 10) {145 EmptyStateView(systemImage: "exclamationmark.triangle", title: "Bibliothèque inaccessible", message: loadError)146 Button("Réessayer") { refreshToken += 1 }147 }148 .frame(maxWidth: .infinity, maxHeight: .infinity)149 } else if files.isEmpty {150 EmptyStateView(systemImage: "folder", title: query.trimmingCharacters(in: .whitespaces).isEmpty ? (projectFilter == nil ? "Aucun fichier" : "Aucun fichier dans ce projet") : "Aucun fichier ne correspond",151 message: "Les pièces jointes de tes conversations apparaissent ici. Dépose des fichiers sur cette fenêtre pour les ajouter à un projet.")152 .frame(maxWidth: .infinity, maxHeight: .infinity)153 } else {154 table155 }156 }157158 private var table: some View {159 Table(files, selection: $selection) {160 TableColumn("Nom") { a in nameCell(a) }.width(min: 180, ideal: 260)161 TableColumn("Type") { a in Text(Self.typeLabel(a)).foregroundStyle(.secondary) }.width(min: 60, ideal: 90, max: 130)162 TableColumn("Taille") { a in Text(Format.bytes(a.sizeBytes)).monospacedDigit().foregroundStyle(.secondary) }.width(min: 50, ideal: 70, max: 90)163 TableColumn("Pages") { a in Text(a.pageCount.map { String($0) } ?? "—").monospacedDigit().foregroundStyle(.secondary) }.width(min: 40, ideal: 50, max: 60)164 TableColumn("Indexation") { a in indexCell(a) }.width(min: 110, ideal: 170)165 TableColumn("Origine") { a in Text(origin(a)).lineLimit(1).foregroundStyle(.secondary).help(origin(a)) }.width(min: 90, ideal: 170)166 TableColumn("Date") { a in dateCell(a) }.width(min: 60, ideal: 80, max: 110)167 TableColumn("Actions") { a in actionsCell(a) }.width(118)168 }169 .contextMenu(forSelectionType: String.self) { ids in170 if ids.count == 1, let a = files.first(where: { ids.contains($0.id) }) {171 Button("Coup d'œil") { preview(a) }172 Button("Enregistrer sous…") { save(a) }173 if Self.isIndexable(a) { Button("Réindexer") { reindex(a) }.disabled(a.indexStatus == "pending" || busy.contains(a.id)) }174 Divider()175 Button("Supprimer…", role: .destructive) { deleting = a }176 }177 } primaryAction: { ids in178 if let a = files.first(where: { ids.contains($0.id) }) { preview(a) }179 }180 .accessibilityIdentifier("files-list")181 }182183 private func nameCell(_ a: Attachment) -> some View {184 HStack(spacing: 8) {185 Image(systemName: FileIcon.name(for: a.filename)).foregroundStyle(.secondary).frame(width: 18).accessibilityHidden(true)186 Text(a.filename).lineLimit(1).truncationMode(.middle).help(a.filename)187 }188 }189190 private func indexCell(_ a: Attachment) -> some View {191 let info = Self.indexInfo(a)192 return HStack(spacing: 6) {193 StatusPill(text: info.label, color: info.color, systemImage: info.icon)194 if let e = a.indexError, !e.isEmpty { Text(e).font(.caption2).foregroundStyle(Palette.warning).lineLimit(1).help(e) }195 }196 .accessibilityElement(children: .combine)197 }198199 @ViewBuilder private func dateCell(_ a: Attachment) -> some View {200 if let d = a.createdAt {201 Text(Format.relative(d)).foregroundStyle(.secondary).help(d.formatted(.dateTime.day().month(.wide).year().hour().minute().locale(Locale(identifier: "fr_CA"))))202 } else { Text("—").foregroundStyle(.secondary) }203 }204205 private func actionsCell(_ a: Attachment) -> some View {206 HStack(spacing: 2) {207 if busy.contains(a.id) { ProgressView().controlSize(.small).frame(width: 22, height: 22) }208 else { IconButton(systemImage: "eye", label: "Coup d'œil sur \(a.filename)") { preview(a) } }209 IconButton(systemImage: "square.and.arrow.down", label: "Enregistrer \(a.filename) sous…") { save(a) }.disabled(busy.contains(a.id))210 if Self.isIndexable(a) {211 IconButton(systemImage: "arrow.triangle.2.circlepath", label: "Réindexer \(a.filename)") { reindex(a) }.disabled(busy.contains(a.id) || a.indexStatus == "pending")212 } else { Color.clear.frame(width: 22, height: 22) }213 IconButton(systemImage: "trash", label: "Supprimer \(a.filename)", role: .destructive) { deleting = a }.disabled(busy.contains(a.id))214 }215 }216217 // MARK: Row helpers218219 private static func isIndexable(_ a: Attachment) -> Bool { !a.mime.hasPrefix("image/") && !a.mime.hasPrefix("audio/") }220221 private static func typeLabel(_ a: Attachment) -> String {222 if a.kind == "generated-image" { return "Image générée" }223 let ext = (a.filename as NSString).pathExtension.uppercased()224 if a.mime.hasPrefix("image/") { return ext.isEmpty ? "Image" : "Image \(ext)" }225 if a.mime.hasPrefix("audio/") { return ext.isEmpty ? "Audio" : "Audio \(ext)" }226 if a.mime == "application/pdf" { return "PDF" }227 return ext.isEmpty ? a.mime : ext228 }229230 private static func indexInfo(_ a: Attachment) -> (label: String, color: Color, icon: String) {231 switch a.indexStatus {232 case "indexed": ((a.chunkCount ?? 0) > 0 ? "Indexé · \(a.chunkCount ?? 0) passages" : "Indexé", Palette.success, "checkmark.circle")233 case "pending": ("Indexation…", Palette.iris, "hourglass")234 case "error", "failed": ("Échec d'indexation", Palette.danger, "exclamationmark.triangle")235 default: ("Non indexé", .secondary, "minus.circle")236 }237 }238239 private func origin(_ a: Attachment) -> String {240 if let t = a.conversationTitle, !t.isEmpty { return t }241 if let p = env.catalog.project(a.projectId) { return "Projet : \(p.name)" }242 if a.projectId != nil { return "Projet" }243 return a.conversationId != nil ? "Conversation" : "—"244 }245246 // MARK: Loading247248 /// Debounced load, then polling while the server is still indexing a file.249 private func loadLoop() async {250 if loaded { try? await Task.sleep(for: .milliseconds(220)); if Task.isCancelled { return } }251 await reload()252 while !Task.isCancelled, files.contains(where: { $0.indexStatus == "pending" }) {253 try? await Task.sleep(for: .seconds(2.5))254 if Task.isCancelled { return }255 await reload()256 }257 }258259 private func reload() async {260 let q = query.trimmingCharacters(in: .whitespaces)261 do {262 let r = try await env.api.attachments(projectId: projectFilter, query: q.isEmpty ? nil : q)263 if Task.isCancelled { return }264 files = r.files; usedBytes = r.usedBytes; quotaMb = r.quotaMb; loadError = nil265 selection.formIntersection(Set(r.files.map(\.id)))266 } catch {267 if Task.isCancelled { return }268 if let e = error as? APIError, e.kind == .cancelled { return }269 let message = (error as? LocalizedError)?.errorDescription ?? String(describing: error)270 if loaded, loadError == nil { env.toasts.error(error) }271 loadError = message272 }273 loaded = true274 }275276 // MARK: Actions277278 private func preview(_ a: Attachment) {279 guard !busy.contains(a.id) else { return }280 busy.insert(a.id)281 Task {282 defer { busy.remove(a.id) }283 do { previewURL = try await env.files.exportedFile(attachmentId: a.id, filename: a.filename) } catch { env.toasts.error(error) }284 }285 }286287 private func save(_ a: Attachment) {288 busy.insert(a.id)289 Task {290 defer { busy.remove(a.id) }291 do {292 let data = try await env.files.data(for: a.id)293 SavePanel.save(data, name: a.filename, type: UTType(mimeType: a.mime) ?? UTType(filenameExtension: (a.filename as NSString).pathExtension) ?? .data, env: env)294 } catch { env.toasts.error(error) }295 }296 }297298 private func reindex(_ a: Attachment) {299 busy.insert(a.id)300 Task {301 defer { busy.remove(a.id) }302 do { try await env.api.reindexAttachment(a.id); env.toasts.show("Réindexation terminée : \(a.filename)"); refreshToken += 1 } catch { env.toasts.error(error); refreshToken += 1 }303 }304 }305306 private func delete(_ a: Attachment) {307 busy.insert(a.id)308 Task {309 defer { busy.remove(a.id) }310 do {311 try await env.api.deleteAttachment(a.id)312 files.removeAll { $0.id == a.id }; selection.remove(a.id)313 env.toasts.show("Fichier supprimé"); refreshToken += 1314 } catch { env.toasts.error(error) }315 }316 }317318 /// A file dropped on the screen: straight to the filtered (or only) project, else ask which one.319 private func received(_ url: URL) {320 let projects = env.catalog.projects321 guard !projects.isEmpty else { env.toasts.show("Crée d'abord un projet pour y téléverser des fichiers.", isError: true); return }322 if let id = projectFilter ?? (projects.count == 1 ? projects[0].id : nil) { upload([url], to: id) }323 else { dropped.append(url); choosingDropProject = true }324 }325326 private func upload(_ urls: [URL], to projectId: String) {327 guard !urls.isEmpty else { return }328 let maxMb = env.catalog.settings.limits.maxUploadMb329 let compress = env.preferences.compressImages330 let queue = uploads331 Task {332 var done = 0333 for url in urls {334 let item = queue.add(url.lastPathComponent)335 switch await AttachmentService.prepare(url: url, maxUploadMb: maxMb, compressImages: compress) {336 case .failure(let rejection): env.toasts.show(rejection.description, isError: true)337 case .success(let file):338 do {339 _ = try await env.files.upload(file, conversationId: nil, projectId: projectId) { p in Task { @MainActor in queue.setProgress(item, p) } }340 done += 1341 } catch { env.toasts.error(error) }342 }343 queue.remove(item)344 }345 if done > 0 {346 env.toasts.show(done > 1 ? "\(done) fichiers ajoutés au projet" : "Fichier ajouté au projet")347 refreshToken += 1348 await env.catalog.reloadProjects()349 }350 }351 }352}353