Repository Public
1//2// VQuant iOS3// File: VQuant/Next/StudioViews.swift4// Description: Research Studio: projects (question, hypotheses, items), notes, automated reviews, export with the5// share sheet and Quick Look, plus the account's usage and the sync status screen. Projects, notes and6// reviews are synced objects: edits made offline are queued and merged.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10//1112import QuickLook13import SwiftUI14import VQuantKit15import VQuantUI1617enum StudioText {18 static func status(_ s: VQOpen<VQProject.Status>?) -> String {19 switch s?.known { case .active: "Actif"; case .paused: "En pause"; case .done: "Terminé"; case .archived: "Archivé"; case nil: s?.rawValue ?? "Actif" }20 }21 static func hypothesis(_ s: VQOpen<VQProject.Hypothesis.Status>) -> (String, String, Color) {22 switch s.known {23 case .open: ("Ouverte", "circle", Theme.textSecondary)24 case .supported: ("Étayée", "checkmark.circle", Theme.up)25 case .rejected: ("Rejetée", "xmark.circle", Theme.down)26 case .inconclusive: ("Non concluante", "questionmark.circle", Theme.warning)27 case nil: (s.rawValue, "circle", Theme.textSecondary)28 }29 }30 static func item(_ t: VQOpen<VQProject.Item.ItemType>) -> (String, String) {31 switch t.known {32 case .conversation: ("Analyse", "text.bubble"); case .quantJob: ("Calcul", "function"); case .note: ("Note", "note.text"); case .chart: ("Graphique", "chart.xyaxis.line")33 case .report: ("Rapport partagé", "doc.richtext"); case .notebook: ("Carnet", "book.closed"); case .dataset: ("Jeu de données", "tablecells"); case .review: ("Revue", "checkmark.seal")34 case .portfolio: ("Portefeuille", "briefcase"); case .watchlist: ("Liste de suivi", "star"); case nil: (t.rawValue, "doc")35 }36 }37 static func route(_ item: VQProject.Item) -> Route? {38 switch item.type.known {39 case .conversation: .conversation(item.ref); case .quantJob: .quantJob(item.ref); case .note: .note(item.ref); case .review: .review(item.ref)40 case .portfolio: .portfolio(item.ref); case .report: .sharedReport(item.ref); default: nil41 }42 }43}4445struct StudioView: View {46 @Environment(AppModel.self) private var model47 @State private var creating = false48 @State private var title = ""49 @State private var question = ""50 @State private var pendingDelete: VQObject<VQProject>?5152 var body: some View {53 List {54 Section { ConflictBanner().listRowInsets(EdgeInsets()) }55 Section {56 let projects = model.next.studio.projects57 if projects.isEmpty {58 Text(model.next.sync.projects.isLoaded ? "Aucun projet. Un projet réunit une question, des hypothèses, des analyses, des calculs, des notes et des revues." : "Chargement…")59 .font(.footnote).foregroundStyle(Theme.textSecondary)60 }61 ForEach(projects) { p in62 RouteLink(.project(p.id)) {63 VStack(alignment: .leading, spacing: 3) {64 HStack(spacing: 6) {65 Text(p.data.title).font(.body.weight(.medium)).lineLimit(2)66 if model.next.sync.projects.pendingIDs.contains(p.id) { Image(systemName: "arrow.up.circle").font(.caption).foregroundStyle(Theme.orange).accessibilityLabel("En attente d’envoi") }67 }68 if let q = p.data.question, !q.isEmpty { Text(q).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(2) }69 Text("\(StudioText.status(p.data.status)) · \(p.data.items.count) élément\(p.data.items.count > 1 ? "s" : "") · \(Fmt.relative(p.updatedAt))").font(.caption2).foregroundStyle(Theme.textSecondary)70 }71 }72 .accessibilityIdentifier("project-\(p.id)")73 .swipeActions { Button("Supprimer", role: .destructive) { pendingDelete = p } }74 }75 } header: { Text("Projets") }76 Section {77 let notes = model.next.studio.notes(of: nil)78 if notes.isEmpty { Text("Aucune note libre.").font(.footnote).foregroundStyle(Theme.textSecondary) }79 ForEach(notes) { n in80 RouteLink(.note(n.id)) { NoteRow(note: n) }81 .swipeActions { Button("Supprimer", role: .destructive) { Task { await model.next.sync.notes.delete(n.id) } } }82 }83 RouteLink(.note("new")) { Label("Nouvelle note", systemImage: "square.and.pencil") }.accessibilityIdentifier("note-new")84 } header: { Text("Notes hors projet") }85 }86 .listStyle(.insetGrouped)87 .navigationTitle("Studio")88 .toolbar {89 ToolbarItem(placement: .primaryAction) { Button { title = ""; question = ""; creating = true } label: { Label("Nouveau projet", systemImage: "plus") }.accessibilityIdentifier("project-new") }90 }91 .refreshable { await model.next.sync.syncNow() }92 .sheet(isPresented: $creating) {93 NavigationStack {94 Form {95 Section("Projet") {96 TextField("Titre", text: $title).accessibilityIdentifier("project-title")97 TextField("Question de recherche (facultative)", text: $question, axis: .vertical).lineLimit(2...5).accessibilityIdentifier("project-question")98 }99 }100 .navigationTitle("Nouveau projet").navigationBarTitleDisplayMode(.inline)101 .toolbar {102 ToolbarItem(placement: .cancellationAction) { Button("Annuler") { creating = false } }103 ToolbarItem(placement: .confirmationAction) {104 Button("Créer") {105 let t = title.trimmingCharacters(in: .whitespaces), q = question106 creating = false107 Task { let id = await model.next.studio.createProject(title: t, question: q); model.router.open(.project(id), compact: UIDevice.current.userInterfaceIdiom == .phone) }108 }109 .disabled(title.trimmingCharacters(in: .whitespaces).isEmpty).accessibilityIdentifier("project-create")110 }111 }112 }113 .presentationDetents([.medium])114 }115 .confirmationDialog("Supprimer « \(pendingDelete?.data.title ?? "") » ?", isPresented: Binding(get: { pendingDelete != nil }, set: { if !$0 { pendingDelete = nil } }), titleVisibility: .visible) {116 Button("Supprimer le projet", role: .destructive) { if let p = pendingDelete { Task { await model.next.sync.projects.delete(p.id) } } }117 } message: { Text("Le projet est effacé du compte, sur tous vos appareils. Ses analyses, calculs et notes restent où ils sont.") }118 .accessibilityIdentifier("studio")119 }120}121122struct NoteRow: View {123 let note: VQObject<VQNote>124 var body: some View {125 VStack(alignment: .leading, spacing: 2) {126 Text(note.data.title.isEmpty ? "Sans titre" : note.data.title).font(.subheadline.weight(.medium)).lineLimit(1)127 Text(note.data.body.replacingOccurrences(of: "\n", with: " ")).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(2)128 }129 .accessibilityElement(children: .combine)130 }131}132133struct ProjectView: View {134 let projectId: String135 @Environment(AppModel.self) private var model136 @Environment(\.horizontalSizeClass) private var sizeClass137 @State private var bundle: VQProjectBundle?138 @State private var newHypothesis = ""139 @State private var exporting: VQExportFormat?140 @State private var preview: URL?141 @State private var share: ChartScreen.ShareItem?142 @State private var alert: String?143 @State private var editing = false144 @State private var draftTitle = ""145 @State private var draftQuestion = ""146 @State private var draftSummary = ""147148 private var object: VQObject<VQProject>? { model.next.sync.projects[projectId] }149150 var body: some View {151 ScrollView {152 if let p = object {153 VStack(alignment: .leading, spacing: 20) {154 header(p)155 hypotheses(p)156 items(p)157 notes158 reviews159 if let s = p.data.summary, !s.isEmpty { VStack(alignment: .leading, spacing: 8) { EditorialHeader("Synthèse"); MarkdownView(text: s) } }160 }161 .padding(16).frame(maxWidth: 900, alignment: .leading).frame(maxWidth: .infinity)162 } else if model.next.sync.projects.isLoaded {163 StateView(kind: .empty, title: "Projet introuvable", message: "Il a peut-être été supprimé sur un autre appareil.", systemImage: "books.vertical")164 } else { StateView(kind: .loading, title: "Chargement…") }165 }166 .background(Theme.background)167 .navigationTitle("Projet").navigationBarTitleDisplayMode(.inline)168 .toolbar {169 ToolbarItemGroup(placement: .primaryAction) {170 Button { model.router.compose(mode: .research, projectId: projectId) } label: { Label("Lancer une étude dans ce projet", systemImage: "sparkles") }171 .requiresNetwork(model.network.isOnline).accessibilityIdentifier("project-run")172 Menu {173 Section("Exporter le projet") {174 ForEach(VQExportFormat.allCases, id: \.self) { f in Button(Self.formatLabel(f)) { export(f) } }175 }176 OpenWindowButton(route: .project(projectId))177 if let p = object {178 Button { draftTitle = p.data.title; draftQuestion = p.data.question ?? ""; draftSummary = p.data.summary ?? ""; editing = true } label: { Label("Modifier", systemImage: "pencil") }179 Picker("État", selection: Binding(get: { p.data.status?.known ?? .active }, set: { s in Task { await model.next.sync.projects.update(projectId) { $0.status = .known(s) } } })) {180 ForEach(VQProject.Status.allCases, id: \.self) { Text(StudioText.status(.known($0))).tag($0) }181 }182 }183 } label: { Label("Actions", systemImage: "ellipsis.circle") }184 .accessibilityIdentifier("project-actions")185 }186 }187 .overlay { if let f = exporting { ProgressView("Export \(f.rawValue.uppercased()) sur le serveur…").padding(20).background(.regularMaterial, in: RoundedRectangle(cornerRadius: 14)) } }188 .task(id: object?.rev) { if let b = try? await model.next.studio.bundle(projectId) { bundle = b.value } }189 .refreshable { await model.next.sync.syncNow(); if let b = try? await model.next.studio.bundle(projectId) { bundle = b.value } }190 .quickLookPreview($preview)191 .sheet(item: $share) { ActivityView(items: [$0.url]) }192 .sheet(isPresented: $editing) {193 NavigationStack {194 Form {195 Section("Titre") { TextField("Titre", text: $draftTitle) }196 Section("Question de recherche") { TextField("Question", text: $draftQuestion, axis: .vertical).lineLimit(2...6) }197 Section("Synthèse (Markdown)") { TextEditor(text: $draftSummary).frame(minHeight: 140).font(.mono(.footnote)) }198 }199 .navigationTitle("Modifier le projet").navigationBarTitleDisplayMode(.inline)200 .toolbar {201 ToolbarItem(placement: .cancellationAction) { Button("Annuler") { editing = false } }202 ToolbarItem(placement: .confirmationAction) {203 Button("Enregistrer") {204 let (t, q, s) = (draftTitle, draftQuestion, draftSummary)205 editing = false206 Task { await model.next.sync.projects.update(projectId) { $0.title = t; $0.question = q.isEmpty ? nil : q; $0.summary = s.isEmpty ? nil : s } }207 }208 .disabled(draftTitle.trimmingCharacters(in: .whitespaces).isEmpty)209 }210 }211 }212 }213 .errorAlert($alert)214 .accessibilityIdentifier("project")215 }216217 static func formatLabel(_ f: VQExportFormat) -> String {218 switch f { case .pdf: "PDF (mis en page par le serveur)"; case .md: "Markdown"; case .tex: "LaTeX (source non compilée)"; case .zip: "Archive ZIP (rapport, données, code)" }219 }220221 private func header(_ p: VQObject<VQProject>) -> some View {222 VStack(alignment: .leading, spacing: 8) {223 Text(p.data.title).font(.serif(.title2, weight: .medium)).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("project-heading")224 if let q = p.data.question, !q.isEmpty { Text(q).font(.callout).foregroundStyle(Theme.textSecondary).fixedSize(horizontal: false, vertical: true) }225 HStack(spacing: 8) {226 Tag(text: StudioText.status(p.data.status))227 if model.next.sync.projects.pendingIDs.contains(p.id) { Tag(text: "En attente d’envoi", systemImage: "arrow.up.circle", color: Theme.orange) }228 Text("Révision \(p.rev) · \(Fmt.relative(p.updatedAt))").font(.caption).foregroundStyle(Theme.textSecondary)229 }230 }231 }232233 private func hypotheses(_ p: VQObject<VQProject>) -> some View {234 VStack(alignment: .leading, spacing: 10) {235 EditorialHeader("Hypothèses")236 ForEach(p.data.hypotheses) { h in237 let s = StudioText.hypothesis(h.status)238 HStack(alignment: .top, spacing: 10) {239 Menu {240 ForEach(VQProject.Hypothesis.Status.allCases, id: \.self) { st in241 Button(StudioText.hypothesis(.known(st)).0) { Task { await model.next.sync.projects.update(projectId) { d in var l = d.hypotheses; if let i = l.firstIndex(where: { $0.id == h.id }) { l[i].status = .known(st) }; d.hypotheses = l } } }242 }243 Button("Supprimer", role: .destructive) { Task { await model.next.sync.projects.update(projectId) { d in d.hypotheses = d.hypotheses.filter { $0.id != h.id } } } }244 } label: { Image(systemName: s.1).foregroundStyle(s.2).frame(minWidth: 44, minHeight: 44) }245 .accessibilityLabel("État : \(s.0). Modifier")246 VStack(alignment: .leading, spacing: 2) { Text(h.text).font(.subheadline).fixedSize(horizontal: false, vertical: true); Text(s.0).font(.caption).foregroundStyle(s.2) }247 Spacer(minLength: 0)248 }249 }250 HStack {251 TextField("Ajouter une hypothèse", text: $newHypothesis, axis: .vertical).lineLimit(1...3).accessibilityIdentifier("hypothesis-field")252 Button("Ajouter") {253 let t = newHypothesis.trimmingCharacters(in: .whitespacesAndNewlines); newHypothesis = ""254 Task { await model.next.sync.projects.update(projectId) { d in var l = d.hypotheses; l.append(VQProject.Hypothesis(text: t)); d.hypotheses = l } }255 }256 .disabled(newHypothesis.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty).accessibilityIdentifier("hypothesis-add")257 }258 }259 }260261 private func items(_ p: VQObject<VQProject>) -> some View {262 VStack(alignment: .leading, spacing: 10) {263 EditorialHeader("Éléments du projet") { Text("\(p.data.items.count)").font(.mono(.caption)).foregroundStyle(Theme.textSecondary) }264 if p.data.items.isEmpty { Text("Lancez une étude dans ce projet, ou ajoutez-y un calcul ou une note : ils apparaîtront ici.").font(.footnote).foregroundStyle(Theme.textSecondary) }265 ForEach(p.data.items) { item in266 let resolved = bundle?.items.first { $0.id == item.id }?.resolved267 let kind = StudioText.item(item.type)268 let row = HStack(alignment: .top, spacing: 10) {269 Image(systemName: kind.1).foregroundStyle(Theme.orange).frame(width: 24)270 VStack(alignment: .leading, spacing: 2) {271 Text(resolved?.title ?? item.title ?? item.ref).font(.subheadline.weight(.medium)).lineLimit(2).multilineTextAlignment(.leading)272 Text([kind.0, resolved?.status.map(Self.statusLabel), (resolved?.updatedAt ?? item.addedAt).map { Fmt.relative($0) }].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(Theme.textSecondary)273 if let s = resolved?.summary, !s.isEmpty { Text(s).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(2) }274 }275 Spacer(minLength: 0)276 }277 .padding(.vertical, 6).contentShape(Rectangle())278 Group {279 if let route = StudioText.route(item) { RouteLink(route) { row }.buttonStyle(.plain) } else { row }280 }281 .contextMenu {282 if item.type == .conversation || item.type == .quantJob || item.type == .note {283 Button { review(item) } label: { Label("Demander une revue automatisée", systemImage: "checkmark.seal") }284 }285 Button("Retirer du projet", role: .destructive) { Task { await model.next.sync.projects.update(projectId) { d in d.items = d.items.filter { $0.id != item.id } } } }286 }287 Divider()288 }289 }290 }291 static func statusLabel(_ s: String) -> String {292 switch s { case "running": "en cours"; case "done": "terminé"; case "error": "en échec"; case "cancelled": "annulé"; case "shared": "partagé"; default: s }293 }294295 private var notes: some View {296 VStack(alignment: .leading, spacing: 10) {297 EditorialHeader("Notes") { RouteLink(.note("new:\(projectId)")) { Label("Nouvelle note", systemImage: "square.and.pencil").font(.subheadline) }.accessibilityIdentifier("project-note-new") }298 let list = model.next.studio.notes(of: projectId)299 if list.isEmpty { Text("Aucune note dans ce projet.").font(.footnote).foregroundStyle(Theme.textSecondary) }300 ForEach(list) { n in RouteLink(.note(n.id)) { NoteRow(note: n).frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 4) }.buttonStyle(.plain); Divider() }301 }302 }303304 private var reviews: some View {305 VStack(alignment: .leading, spacing: 10) {306 EditorialHeader("Revues automatisées")307 let list = model.next.studio.reviews(of: projectId)308 if list.isEmpty { Text("Aucune revue. Une revue vérifie les nombres cités, les tailles d’échantillon, les fuites d’information et la provenance ; ce n’est pas une relecture par des pairs.").font(.footnote).foregroundStyle(Theme.textSecondary) }309 ForEach(list) { r in RouteLink(.review(r.id)) { ReviewRow(review: r).padding(.vertical, 4) }.buttonStyle(.plain); Divider() }310 }311 }312313 private func review(_ item: VQProject.Item) {314 let type: VQReview.Target.TargetType = item.type == .quantJob ? .quantJob : item.type == .note ? .note : .session315 Task {316 do {317 let id = try await model.next.studio.review(VQReview.Target(type: type, id: item.ref), projectId: projectId)318 model.router.open(.review(id), compact: sizeClass == .compact)319 } catch { alert = nextMessage(error) }320 }321 }322323 /// The server builds the document; the file is downloaded, shown in Quick Look, and can be shared from there.324 private func export(_ format: VQExportFormat) {325 exporting = format326 Task {327 defer { exporting = nil }328 do {329 let e = try await model.next.studio.export(projectId, format: format)330 let data = try await model.api.file(e.url.hasPrefix("/") ? e.url : "/api/download/\(e.filename)")331 let url = FileManager.default.temporaryDirectory.appendingPathComponent(e.filename.isEmpty ? "projet.\(format.rawValue)" : e.filename)332 try data.write(to: url, options: .atomic)333 if format == .zip { share = .init(url: url) } else { preview = url }334 } catch { alert = nextMessage(error) }335 }336 }337}338339struct ReviewRow: View {340 let review: VQObject<VQReview>341 var body: some View {342 HStack(alignment: .top, spacing: 10) {343 Image(systemName: "checkmark.seal").foregroundStyle(Theme.orange).frame(width: 24)344 VStack(alignment: .leading, spacing: 2) {345 Text(review.data.verdict?.isEmpty == false ? review.data.verdict! : "Revue automatisée").font(.subheadline).lineLimit(2).multilineTextAlignment(.leading)346 Text("\(ReviewView.status(review.data.status)) · \(review.data.checks.count) constat\(review.data.checks.count > 1 ? "s" : "") · \(Fmt.relative(review.updatedAt))").font(.caption).foregroundStyle(Theme.textSecondary)347 }348 Spacer(minLength: 0)349 }350 .contentShape(Rectangle())351 .accessibilityElement(children: .combine)352 }353}354355/// A review written by the server: deterministic checks first, then the reviewer model's findings. Always labelled356/// as automated.357struct ReviewView: View {358 let reviewId: String359 @Environment(AppModel.self) private var model360 private var review: VQObject<VQReview>? { model.next.sync.reviews[reviewId] }361362 static func status(_ s: VQOpen<VQReview.Status>) -> String { switch s.known { case .running: "En cours"; case .done: "Terminée"; case .error: "Interrompue"; case nil: s.rawValue } }363 static func category(_ c: VQOpen<VQReview.Check.Category>) -> String {364 switch c.known { case .math: "Calcul"; case .statistics: "Statistique"; case .leakage: "Fuite d’information"; case .interpretation: "Interprétation"; case .citations: "Citations"; case .reproducibility: "Reproductibilité"; case nil: c.rawValue }365 }366367 var body: some View {368 ScrollView {369 if let r = review {370 VStack(alignment: .leading, spacing: 16) {371 Label("Revue automatisée — ce n’est pas une relecture par des pairs", systemImage: "cpu").font(.subheadline.weight(.semibold)).foregroundStyle(Theme.warning)372 .padding(12).frame(maxWidth: .infinity, alignment: .leading).background(Theme.warning.opacity(0.1), in: RoundedRectangle(cornerRadius: 10))373 .accessibilityIdentifier("review-automated-label")374 HStack(spacing: 8) {375 JobStatusBadge(text: Self.status(r.data.status), color: r.data.status == .done ? Theme.up : r.data.status == .error ? Theme.down : Theme.orange, running: r.data.status == .running)376 if let m = r.data.model { ModelBadge(id: m) }377 Spacer()378 }379 if let v = r.data.verdict, !v.isEmpty { VStack(alignment: .leading, spacing: 6) { EditorialHeader("Verdict"); MarkdownView(text: v) } }380 if let e = r.data.error { Label("Le relecteur n’a pas terminé : \(e). Les contrôles déterministes ci-dessous restent valables.", systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.down) }381 EditorialHeader("Constats") { Text("\(r.data.checks.count)").font(.mono(.caption)).foregroundStyle(Theme.textSecondary) }382 ForEach(r.data.checks) { c in383 let color: Color = c.severity == .error ? Theme.down : c.severity == .warning ? Theme.warning : Theme.textSecondary384 VStack(alignment: .leading, spacing: 4) {385 HStack(spacing: 6) {386 Image(systemName: c.severity == .error ? "xmark.octagon" : c.severity == .warning ? "exclamationmark.triangle" : "info.circle").foregroundStyle(color)387 Text(Self.category(c.category)).font(.caption.weight(.semibold)).foregroundStyle(color)388 Tag(text: c.isFromReviewerModel ? "Modèle relecteur" : "Contrôle déterministe")389 }390 Text(c.finding).font(.subheadline).fixedSize(horizontal: false, vertical: true)391 if let e = c.evidence, !e.isEmpty { Text(e).font(.mono(.caption2)).foregroundStyle(Theme.textSecondary).textSelection(.enabled) }392 }393 .paperCard(padding: 12)394 .accessibilityElement(children: .combine)395 }396 if let d = r.data.disclaimer { Text(d).font(.caption).foregroundStyle(Theme.textSecondary) }397 if let u = r.data.usage { UsageLine(usage: u) }398 }399 .padding(16).frame(maxWidth: 860, alignment: .leading).frame(maxWidth: .infinity)400 } else {401 StateView(kind: .loading, title: "La revue arrive du serveur…")402 }403 }404 .background(Theme.background)405 .navigationTitle("Revue").navigationBarTitleDisplayMode(.inline)406 .task {407 // The review object is written by the server and reaches the device through the sync feed.408 for _ in 0..<20 where review == nil || review?.data.status == .running { await model.next.sync.syncNow(); try? await Task.sleep(for: .seconds(3)) }409 }410 .accessibilityIdentifier("review")411 }412}413414/// A note (Markdown). `new` or `new:<projectId>` creates one at the first save.415struct NoteView: View {416 let noteId: String417 @Environment(AppModel.self) private var model418 @Environment(\.dismiss) private var dismiss419 @State private var title = ""420 @State private var text = ""421 @State private var loadedRev: Int?422 @State private var currentId: String?423 @State private var preview = false424 @State private var saved = true425426 private var isNew: Bool { noteId == "new" || noteId.hasPrefix("new:") }427 private var projectForNew: String? { noteId.hasPrefix("new:") ? String(noteId.dropFirst(4)) : nil }428 private var object: VQObject<VQNote>? { (currentId ?? (isNew ? nil : noteId)).flatMap { model.next.sync.notes[$0] } }429430 var body: some View {431 VStack(spacing: 0) {432 TextField("Titre", text: $title).font(.serif(.title2, weight: .medium)).padding(.horizontal, 16).padding(.top, 12)433 .accessibilityIdentifier("note-title")434 Divider().padding(.top, 8)435 if preview {436 ScrollView { MarkdownView(text: text).padding(16).frame(maxWidth: .infinity, alignment: .leading) }437 } else {438 TextEditor(text: $text).font(.body).padding(.horizontal, 12).scrollContentBackground(.hidden)439 .accessibilityLabel("Texte de la note").accessibilityIdentifier("note-body")440 }441 }442 .background(Theme.background)443 .navigationTitle(isNew && currentId == nil ? "Nouvelle note" : "Note").navigationBarTitleDisplayMode(.inline)444 .toolbar {445 ToolbarItemGroup(placement: .primaryAction) {446 Button { preview.toggle() } label: { Label(preview ? "Modifier" : "Aperçu", systemImage: preview ? "pencil" : "eye") }.accessibilityIdentifier("note-preview")447 Button("Enregistrer") { save() }.disabled(saved || title.trimmingCharacters(in: .whitespaces).isEmpty && text.isEmpty)448 .keyboardShortcut("s", modifiers: .command).accessibilityIdentifier("note-save")449 }450 ToolbarItem(placement: .status) {451 Text(saved ? (object.map { model.next.sync.notes.pendingIDs.contains($0.id) ? "En attente d’envoi" : "Enregistrée" } ?? "") : "Modifications non enregistrées").font(.caption).foregroundStyle(Theme.textSecondary)452 }453 }454 .onAppear(perform: load)455 .onChange(of: object?.rev) { _, rev in456 // The note changed on another device while it is open: take it if nothing was typed here.457 if saved, rev != loadedRev { load() }458 }459 .onChange(of: title) { _, _ in saved = title == (object?.data.title ?? "") && text == (object?.data.body ?? "") }460 .onChange(of: text) { _, _ in saved = title == (object?.data.title ?? "") && text == (object?.data.body ?? "") }461 .onDisappear { if !saved { save() } }462 .accessibilityIdentifier("note")463 }464465 private func load() {466 guard let o = object else { return }467 title = o.data.title; text = o.data.body; loadedRev = o.rev; saved = true468 }469470 private func save() {471 let t = title.trimmingCharacters(in: .whitespaces).isEmpty ? "Sans titre" : title, b = text472 saved = true473 Task {474 if let id = currentId ?? (isNew ? nil : noteId) {475 await model.next.sync.notes.update(id) { $0.title = t; $0.body = b }476 } else {477 currentId = await model.next.studio.createNote(title: t, body: b, projectId: projectForNew)478 }479 loadedRev = object?.rev480 }481 }482}483484// MARK: - Usage485486struct UsageView: View {487 @Environment(AppModel.self) private var model488 var body: some View {489 List {490 if let u = model.next.models.usage.value {491 Section("\(u.days) derniers jours") {492 KeyValueRow(key: "Appels aux modèles", value: VQFormat.int(u.totals.calls))493 KeyValueRow(key: "Jetons en entrée", value: VQFormat.tokens(u.totals.inputTokens))494 KeyValueRow(key: "Jetons en sortie", value: VQFormat.tokens(u.totals.outputTokens))495 KeyValueRow(key: "Coût", value: u.totals.costUsd.map { VQFormat.cost($0) } ?? "inconnu (au moins un appel sans prix)")496 if u.totals.costUsd == nil, let k = u.totals.knownCostUsd { KeyValueRow(key: "Coût des appels tarifés", value: VQFormat.cost(k)) }497 }498 Section("Par modèle") {499 ForEach(Array(u.byModel.enumerated()), id: \.offset) { _, m in500 HStack {501 VQProviderLogo(provider: m.provider, size: 14)502 VStack(alignment: .leading, spacing: 2) {503 Text(model.next.models.label(m.model)).font(.subheadline)504 Text("\(m.role?.rawValue ?? "") · \(VQFormat.int(m.counters.calls)) appels").font(.caption).foregroundStyle(Theme.textSecondary)505 }506 Spacer()507 Text(m.counters.costUsd.map { VQFormat.cost($0) } ?? "—").font(.mono(.footnote))508 }509 .accessibilityElement(children: .combine)510 }511 }512 CachedNotice(at: model.next.models.usage.cachedAt)513 } else if model.next.models.usage.isUnavailable {514 StateView(kind: .failed, title: "Consommation indisponible", message: model.next.models.usage.error) { Task { await model.next.models.refreshUsage() } }515 } else { ProgressView() }516 }517 .navigationTitle("Consommation")518 .task { await model.next.models.refresh(); await model.next.models.refreshUsage() }519 .refreshable { await model.next.models.refreshUsage() }520 .accessibilityIdentifier("usage")521 }522}523524// MARK: - Sync status, queue, conflicts525526struct SyncStatusView: View {527 @Environment(AppModel.self) private var model528 @State private var pending: [VQPendingWrite] = []529530 var body: some View {531 let sync = model.next.sync532 let s = sync.status.status533 let spec = SyncStatusChip.spec(s, online: model.network.isOnline)534 List {535 Section {536 Label { VStack(alignment: .leading, spacing: 2) { Text(spec.text).font(.body.weight(.medium)); Text(spec.detail).font(.caption).foregroundStyle(Theme.textSecondary) } } icon: { Image(systemName: spec.symbol).foregroundStyle(spec.color) }537 if let t = s.lastPulledAt { KeyValueRow(key: "Dernière relève", value: Fmt.relative(t)) }538 KeyValueRow(key: "Position dans le flux", value: "\(s.cursor)")539 if let e = s.lastError { Label(e, systemImage: "exclamationmark.triangle").font(.caption).foregroundStyle(Theme.warning) }540 Button("Synchroniser maintenant") { Task { await sync.syncNow(); pending = await sync.engine.pendingWrites } }.accessibilityIdentifier("sync-now")541 } header: { Text("Un compte, synchronisé") } footer: {542 Text("Listes de suivi, portefeuilles, graphiques, projets, notes, espaces de travail et préférences sont les mêmes sur le web, le Mac, l’iPhone et l’iPad. La copie de cet appareil est chiffrée et effacée à la déconnexion.").foregroundStyle(Theme.textSecondary)543 }544 Section {545 if pending.isEmpty { Text("Aucune modification en attente.").foregroundStyle(Theme.textSecondary) }546 ForEach(pending, id: \.opId) { w in547 HStack {548 Image(systemName: "arrow.up.circle").foregroundStyle(Theme.orange)549 VStack(alignment: .leading, spacing: 2) {550 Text(Self.kind(w.key.kind)).font(.subheadline)551 Text("\(w.key.id) · \(Fmt.relative(w.createdAt))").font(.mono(.caption2)).foregroundStyle(Theme.textSecondary).lineLimit(1)552 }553 }554 .accessibilityElement(children: .combine)555 }556 } header: { Text("File d’attente hors ligne (\(pending.count))") } footer: {557 Text("Les modifications faites sans connexion partent dans l’ordre au retour du réseau.").foregroundStyle(Theme.textSecondary)558 }559 Section {560 let conflicts = sync.status.conflicts561 if conflicts.isEmpty { Text("Aucun conflit.").foregroundStyle(Theme.textSecondary) }562 ForEach(conflicts) { c in ConflictRow(conflict: c) }563 } header: { Text("Conflits") } footer: {564 Text("Deux appareils ont modifié le même objet. Les listes (symboles, positions, éléments, tracés) sont fusionnées ; pour le reste, la dernière écriture l’emporte champ par champ et l’autre version reste récupérable ici.").foregroundStyle(Theme.textSecondary)565 }566 if !sync.migrationNotes.isEmpty {567 Section("Migration depuis la version 1.0") { ForEach(sync.migrationNotes, id: \.self) { Text($0).font(.footnote) } }568 }569 }570 .navigationTitle("Synchronisation")571 .task { pending = await sync.engine.pendingWrites }572 .onChange(of: s.pendingWrites) { _, _ in Task { pending = await sync.engine.pendingWrites } }573 .accessibilityIdentifier("sync-status")574 }575576 static func kind(_ k: VQObjectKind) -> String {577 switch k.rawValue {578 case "watchlist": "Liste de suivi"; case "portfolio": "Portefeuille"; case "chart": "Graphique"; case "project": "Projet"; case "note": "Note"579 case "workspace": "Espace de travail"; case "preference": "Préférences"; case "review": "Revue"; default: k.rawValue580 }581 }582}583584struct ConflictRow: View {585 @Environment(AppModel.self) private var model586 let conflict: VQConflictRecord587 @State private var showVersions = false588589 var body: some View {590 VStack(alignment: .leading, spacing: 6) {591 HStack {592 Image(systemName: conflict.needsAttention ? "exclamationmark.triangle.fill" : "arrow.triangle.merge").foregroundStyle(conflict.needsAttention ? Theme.warning : Theme.textSecondary)593 Text("\(SyncStatusView.kind(conflict.key.kind)) · \(conflict.key.id)").font(.subheadline.weight(.medium)).lineLimit(1)594 }595 Text(summary).font(.caption).foregroundStyle(Theme.textSecondary)596 if let m = conflict.message { Text(m).font(.caption2).foregroundStyle(Theme.textSecondary) }597 if conflict.needsAttention {598 HStack {599 Button("Garder la mienne") { Task { await model.next.sync.status.dismiss(conflict.id) } }.buttonStyle(.bordered)600 Button("Reprendre celle de l’autre appareil") { Task { await model.next.sync.status.keepRemote(conflict.id) } }.buttonStyle(.bordered)601 Button("Comparer") { showVersions = true }.buttonStyle(.borderless)602 }603 .font(.caption)604 }605 }606 .sheet(isPresented: $showVersions) {607 NavigationStack {608 ScrollView {609 VStack(alignment: .leading, spacing: 14) {610 Text("Cet appareil").font(.serif(.headline)); Text(conflict.local?.text(pretty: true) ?? "—").font(.mono(.caption2)).textSelection(.enabled)611 Divider()612 Text("Autre appareil (\(conflict.remoteDevice.isEmpty ? "serveur" : conflict.remoteDevice))").font(.serif(.headline)); Text(conflict.remote?.text(pretty: true) ?? "—").font(.mono(.caption2)).textSelection(.enabled)613 }614 .padding(16).frame(maxWidth: .infinity, alignment: .leading)615 }616 .navigationTitle("Deux versions").navigationBarTitleDisplayMode(.inline)617 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Fermer") { showVersions = false } } }618 }619 }620 }621 private var summary: String {622 var parts: [String] = [Fmt.relative(conflict.at)]623 if !conflict.mergedLists.isEmpty { parts.append("listes fusionnées : \(conflict.mergedLists.joined(separator: ", "))") }624 if !conflict.differingKeys.isEmpty { parts.append("champs en désaccord : \(conflict.differingKeys.joined(separator: ", "))") }625 return parts.joined(separator: " · ")626 }627}628