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/Chat/ChatScreen.swift10// Module : Chat11// 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 AstraCore90import AstraDesign91import AstraPersistence9293/// One conversation: the transcript, the composer and the conversation-level controls.94struct ChatScreen: View {95 @Environment(AppModel.self) private var app96 let chat: ChatController9798 @State private var draftText = ""99 @State private var drafts: [AttachmentDraft] = []100 @State private var showModelPicker = false101 @State private var regenerateTarget: String?102 @State private var showSettings = false103 @State private var editing: MessageRecord?104 @State private var editText = ""105 @State private var confirmUpload = false106 @State private var confirmDelete: String?107 @State private var atBottom = true108 /// True while the transcript should follow new content: set when a message is sent, cleared when the reader scrolls away.109 @State private var follow = true110 /// Incremented to ask the transcript to scroll to its end (a ScrollPosition set to the edge it already holds is a no-op).111 @State private var scrollTick = 0112 @State private var scrollAnimated = false113 @ScaledMetric(relativeTo: .body) private var fontSize: CGFloat = 17114 @Environment(\.accessibilityReduceMotion) private var reduceMotion115116 var body: some View {117 VStack(spacing: 0) {118 transcript119 Divider().overlay(AstraColor.stroke)120 Composer(text: $draftText, drafts: $drafts, isGenerating: chat.isGenerating, model: chat.modelInfo, modelRef: chat.conversation.model,121 modelName: app.library.displayName(for: chat.conversation.model), contextFraction: chat.contextFraction,122 onSend: send, onStop: chat.stop, onPickModel: { showModelPicker = true }, onError: { app.show($0, .error) })123 .background(AstraColor.background)124 }125 .background(Starfield(density: 0.35))126 .navigationTitle(chat.conversation.title.isEmpty ? "New chat" : chat.conversation.title)127 .navigationBarTitleDisplayMode(.inline)128 .toolbar {129 ToolbarItem(placement: .topBarTrailing) {130 Button { showSettings = true } label: { Image(systemName: "slider.horizontal.3") }131 .accessibilityLabel("Conversation settings").accessibilityIdentifier("chat-settings")132 }133 }134 .sheet(isPresented: $showModelPicker) {135 ModelPickerSheet(selected: chat.conversation.model, title: "Model for this chat") { ref in136 Task { await chat.switchModel(to: ref) }137 }138 }139 .sheet(item: Binding(get: { regenerateTarget.map(IdentifiedString.init) }, set: { regenerateTarget = $0?.value })) { target in140 ModelPickerSheet(selected: chat.conversation.model, title: "Regenerate with") { ref in141 Task { await chat.regenerate(target.value, with: ref) }142 }143 }144 .sheet(isPresented: $showSettings) { ConversationSettingsSheet(chat: chat) }145 .sheet(item: $editing) { message in editSheet(message) }146 .confirmationDialog("Send attachments to \(chat.conversation.model.provider.displayName)?", isPresented: $confirmUpload, titleVisibility: .visible) {147 Button("Send to \(chat.conversation.model.provider.displayName)") { Task { await app.rememberUploadConsent(chat.conversation.model.provider); performSend() } }148 Button("Cancel", role: .cancel) {}149 } message: {150 Text("The files you attached will leave this iPhone and be processed by \(chat.conversation.model.provider.displayName) under its own terms. On-device models keep attachments on this iPhone.")151 }152 .confirmationDialog("Delete this message and everything after it?", isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }), titleVisibility: .visible) {153 Button("Delete", role: .destructive) { if let id = confirmDelete { Task { await chat.deleteFrom(id) } } }154 Button("Cancel", role: .cancel) {}155 } message: { Text("Other versions of earlier turns are kept.") }156 .task(id: app.options.autoSend) {157 #if DEBUG158 if let prompt = app.options.autoSend, chat.messages.isEmpty, !chat.isGenerating { await chat.send(prompt) }159 #endif160 }161 }162163 // MARK: Transcript164165 private var actions: MessageActions {166 MessageActions(167 copy: { Pasteboard.copy($0); AstraHaptics.tap(); app.show("Copied", .success) },168 regenerate: { id in Task { await chat.regenerate(id) } },169 regenerateWith: { regenerateTarget = $0 },170 edit: { editText = $0.text; editing = $0 },171 bookmark: { id in Task { await chat.toggleBookmark(id) } },172 delete: { confirmDelete = $0 },173 branch: { id, delta in Task { await chat.switchBranch(of: id, by: delta) } },174 retry: { Task { await chat.retryLast() } },175 openModels: { app.tab = .models })176 }177178 private var transcript: some View {179 ScrollViewReader { proxy in180 ScrollView {181 // A regular stack over a bounded window of recent messages: layout is exact (no estimated heights), so pinning to182 // the end and "jump to latest" are reliable. Long conversations stay cheap because earlier turns are paged in.183 VStack(alignment: .leading, spacing: 22) {184 if chat.messages.isEmpty { emptyState }185 if chat.hasEarlier {186 Button { Task { await chat.loadEarlier() } } label: { Label("Show earlier messages", systemImage: "arrow.up.circle") }187 .buttonStyle(AstraSecondaryButtonStyle(compact: true)).frame(maxWidth: .infinity)188 .accessibilityIdentifier("load-earlier")189 }190 ForEach(chat.messages) { message in191 row(message).id(message.id)192 }193 if let banner = chat.banner {194 NoticeCard(.error, title: banner.title, message: banner.message, actionTitle: { if case .missingCredential = banner { return "Open Models" }; return nil }(),195 action: { app.tab = .models })196 }197 if !chat.negotiationNotes.isEmpty || (chat.lastPlan?.droppedCount ?? 0) > 0 { contextNotes }198 Color.clear.frame(height: 1).id("bottom")199 }200 .padding(.horizontal, AstraSpace.page).padding(.top, 14).padding(.bottom, 10)201 .environment(\.transcriptFontSize, fontSize)202 }203 // The view stays pinned to the bottom while content grows only if the person is already there: scrolling up204 // releases it, and nothing drags them back while they read.205 .defaultScrollAnchor(.bottom, for: .initialOffset)206 .defaultScrollAnchor(.bottom, for: .sizeChanges)207 .onChange(of: scrollTick) { _, _ in208 if scrollAnimated { withAnimation(AstraMotion.resolve(AstraMotion.standard, reduceMotion: reduceMotion)) { proxy.scrollTo("bottom", anchor: .bottom) } }209 else { proxy.scrollTo("bottom", anchor: .bottom) }210 }211 .scrollDismissesKeyboard(.interactively)212 .onScrollGeometryChange(for: Bool.self) { g in213 // Distance between the end of the content and the bottom of what is visible. `visibleRect` is used because214 // `containerSize` excludes the part of the scroll view under the navigation bar (measured: 573 vs 689 pt).215 g.contentSize.height - g.visibleRect.maxY <= 48216 } action: { _, new in atBottom = new }217 // Only the reader's own gesture changes whether the transcript follows: dragging away releases it, returning to the218 // bottom re-engages it. Content growth alone never does.219 .onScrollPhaseChange { old, new in220 if old == .interacting || old == .decelerating, new == .idle || new == .animating { follow = atBottom }221 if new == .interacting { follow = false }222 }223 .onChange(of: chat.liveText) { _, _ in if follow, !atBottom { scrollAnimated = false; scrollTick += 1 } }224 .onChange(of: chat.streamingID) { _, new in225 // when the answer is finalised its footer appears: keep the end in view for a reader who was following226 if new == nil, follow { Task { @MainActor in try? await Task.sleep(nanoseconds: 120_000_000); scrollAnimated = true; scrollTick += 1 } }227 }228 .overlay(alignment: .bottomTrailing) {229 if !atBottom {230 Button {231 follow = true; scrollAnimated = true; scrollTick += 1232 } label: {233 Image(systemName: "arrow.down").font(.system(size: 14, weight: .bold)).foregroundStyle(AstraColor.textPrimary)234 .frame(width: 40, height: 40).background(AstraColor.surfaceRaised, in: Circle())235 .overlay(Circle().strokeBorder(AstraColor.strokeStrong, lineWidth: 1)).astraShadow(.low)236 .frame(width: AstraSpace.hit, height: AstraSpace.hit)237 }238 .buttonStyle(.plain).padding(.trailing, 10).padding(.bottom, 6)239 .accessibilityLabel("Jump to latest")240 .transition(.opacity.combined(with: .scale(scale: 0.85)))241 }242 }243 .animation(AstraMotion.resolve(AstraMotion.quick, reduceMotion: reduceMotion), value: atBottom)244 }245 }246247 @ViewBuilder private func row(_ message: MessageRecord) -> some View {248 switch message.role {249 case .user:250 UserMessageView(message: message, attachments: chat.attachments[message.id] ?? [], branch: chat.branches[message.id], actions: actions,251 imageURL: { try? app.store.attachmentFileURL(sha256: $0.sha256) })252 case .assistant:253 let streaming = message.id == chat.streamingID254 AssistantMessageView(message: message, text: chat.displayText(message), reasoning: chat.displayReasoning(message), isStreaming: streaming,255 isLoadingModel: streaming && chat.isLoadingModel,256 modelName: app.library.displayName(for: message.model ?? chat.conversation.model),257 reportedModel: streaming ? chat.liveStart?.reportedModel : message.reportedModel,258 servedBy: streaming ? chat.liveStart?.servedBy : message.servedBy,259 branch: chat.branches[message.id], actions: actions)260 case .tool:261 Label("Tool result: \(message.toolName ?? "tool")", systemImage: "wrench.and.screwdriver").font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)262 }263 }264265 private var contextNotes: some View {266 VStack(alignment: .leading, spacing: 4) {267 if let dropped = chat.lastPlan?.droppedCount, dropped > 0 {268 Label("\(dropped) earlier message\(dropped == 1 ? " was" : "s were") left out to fit the context window.", systemImage: "scissors")269 }270 ForEach(chat.negotiationNotes, id: \.self) { Label($0, systemImage: "info.circle") }271 }272 .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)273 .accessibilityElement(children: .combine)274 }275276 private var emptyState: some View {277 VStack(spacing: 14) {278 AstraGlyph().frame(width: 84, height: 84)279 Text("Ask anything").font(AstraFont.title).foregroundStyle(AstraColor.textPrimary)280 HStack(spacing: 6) {281 ProviderLogo(ref: chat.conversation.model, vendor: chat.modelInfo?.vendor, size: 22)282 Text(app.library.displayName(for: chat.conversation.model)).font(AstraFont.subheadline).foregroundStyle(AstraColor.textSecondary)283 }284 Text(chat.conversation.model.provider.isLocal285 ? "This model runs on your iPhone. Nothing you write here leaves the device."286 : "Messages in this chat are sent to \(chat.conversation.model.provider.displayName) with your own API key.")287 .font(AstraFont.footnote).foregroundStyle(AstraColor.textTertiary).multilineTextAlignment(.center).padding(.horizontal, 24)288 }289 .frame(maxWidth: .infinity).padding(.top, 70)290 .accessibilityElement(children: .combine)291 }292293 // MARK: Sending294295 private func send() {296 if chat.wouldUpload(drafts), !app.hasUploadConsent(chat.conversation.model.provider) { confirmUpload = true } else { performSend() }297 }298299 private func performSend() {300 let text = draftText, files = drafts301 draftText = ""; drafts = []302 follow = true; scrollAnimated = false; scrollTick += 1303 Task { await chat.send(text, attachments: files) }304 }305306 private func editSheet(_ message: MessageRecord) -> some View {307 NavigationStack {308 VStack(alignment: .leading, spacing: 12) {309 Text("The edited message starts a new version of the conversation. The original stays available with the version arrows.")310 .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)311 TextEditor(text: $editText)312 .font(AstraFont.body).scrollContentBackground(.hidden).padding(8)313 .background(AstraColor.surface, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))314 .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))315 .accessibilityLabel("Message text")316 }317 .padding(AstraSpace.page)318 .background(AstraColor.background)319 .navigationTitle("Edit message").navigationBarTitleDisplayMode(.inline)320 .toolbar {321 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { editing = nil } }322 ToolbarItem(placement: .confirmationAction) {323 Button("Resend") { let id = message.id, text = editText; editing = nil; Task { await chat.editAndResend(id, newText: text) } }324 .disabled(editText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)325 }326 }327 }328 .presentationDetents([.medium, .large])329 }330}331332struct IdentifiedString: Identifiable { let value: String; var id: String { value } }333334extension AppModel {335 /// Uploading attachments to a cloud provider is confirmed once per provider, then remembered.336 func hasUploadConsent(_ provider: ProviderKind) -> Bool { uploadConsent.contains(provider.rawValue) }337 func rememberUploadConsent(_ provider: ProviderKind) async {338 uploadConsent.insert(provider.rawValue)339 try? await store.setSetting("privacy.uploadConsent", uploadConsent.sorted())340 }341}342