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/ConversationSettingsSheet.swift10// Module : Chat11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//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/// Conversation-level controls: instructions, generation parameters (only those the model accepts), context budget,94/// memory, OpenRouter routing, export.95struct ConversationSettingsSheet: View {96 @Environment(AppModel.self) private var app97 @Environment(\.dismiss) private var dismiss98 let chat: ChatController99100 @State private var system = ""101 @State private var useTemperature = false102 @State private var temperature = 0.7103 @State private var useMaxTokens = false104 @State private var maxTokens = 1024.0105 @State private var reasoning: ReasoningEffort = .off106 @State private var useCap = false107 @State private var cap = 8000.0108 @State private var strategy: TruncationStrategy = .dropOldest109 @State private var memory = true110 @State private var denyDataCollection = false111 @State private var allowFallbacks = true112 @State private var presets: [PresetRecord] = []113 @State private var exportDocument: ExportedFile?114 @State private var loaded = false115116 private var info: ModelInfo? { chat.modelInfo }117 private var acceptsTemperature: Bool { info?.supportedParameters.map { $0.contains("temperature") } ?? true }118 private var modelWindow: Int { info?.contextLength ?? (chat.conversation.model.provider.isLocal ? 4096 : 32000) }119120 var body: some View {121 NavigationStack {122 Form {123 Section {124 TextEditor(text: $system).frame(minHeight: 110).font(AstraFont.callout).accessibilityLabel("System instructions")125 if !presets.isEmpty {126 Menu {127 ForEach(presets) { p in Button(p.name) { system = p.system } }128 } label: { Label("Use a preset", systemImage: "text.badge.plus") }129 }130 } header: { Text("Instructions") } footer: { Text("Sent to the model at the start of every turn in this chat.") }131132 Section {133 if acceptsTemperature {134 Toggle("Set temperature", isOn: $useTemperature)135 if useTemperature {136 LabeledContent("Temperature") { Text(String(format: "%.2f", temperature)).monospacedDigit() }137 Slider(value: $temperature, in: 0...2, step: 0.05).accessibilityLabel("Temperature").accessibilityValue(String(format: "%.2f", temperature))138 }139 } else {140 Label("This model does not accept a temperature.", systemImage: "info.circle").font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)141 }142 Toggle("Limit answer length", isOn: $useMaxTokens)143 if useMaxTokens {144 LabeledContent("Maximum output") { Text("\(Int(maxTokens)) tokens").monospacedDigit() }145 Slider(value: $maxTokens, in: 64...Double(max(256, min(info?.maxOutputTokens ?? 8192, 16384))), step: 64).accessibilityLabel("Maximum output tokens")146 }147 if info?.capabilities.contains(.reasoning) ?? false {148 Picker("Reasoning effort", selection: $reasoning) { ForEach(ReasoningEffort.allCases) { Text($0.title).tag($0) } }149 }150 } header: { Text("Generation") } footer: { Text("Unset values use the provider's defaults. Controls the model does not support are hidden.") }151152 Section {153 LabeledContent("Model window") { Text(info?.contextLength != nil ? "\(modelWindow) tokens" : "Unknown, assuming \(modelWindow)").monospacedDigit() }154 Toggle("Cap the context", isOn: $useCap)155 if useCap {156 LabeledContent("Budget") { Text("\(Int(cap)) tokens").monospacedDigit() }157 Slider(value: $cap, in: 1024...Double(max(2048, modelWindow)), step: 512).accessibilityLabel("Context budget in tokens")158 }159 Picker("When it is full", selection: $strategy) { ForEach(TruncationStrategy.allCases) { Text($0.title).tag($0) } }160 LabeledContent("In use now") { Text("≈ \(Int((chat.contextFraction * 100).rounded()))%").monospacedDigit() }161 } header: { Text("Context") } footer: { Text("Token counts before sending are estimates. A lower budget costs less on cloud models and uses less memory on device.") }162163 Section {164 Toggle("Use saved memories", isOn: $memory)165 } footer: { Text("When on, the memories you saved in Lab are added to the instructions of this chat.") }166167 if chat.conversation.model.provider == .openRouter {168 Section {169 Toggle("Only providers that do not keep prompts", isOn: $denyDataCollection)170 Toggle("Allow fallback providers", isOn: $allowFallbacks)171 } header: { Text("OpenRouter routing") } footer: {172 Text("OpenRouter forwards your prompt to an upstream provider. The first option asks it to use only providers whose policy is not to retain or train on prompts.")173 }174 }175176 Section("Export") {177 Button { export(.markdown) } label: { Label("Export as Markdown", systemImage: "doc.plaintext") }178 Button { export(.json) } label: { Label("Export as JSON", systemImage: "curlybraces") }179 }180 }181 .scrollContentBackground(.hidden).background(AstraColor.background)182 .navigationTitle("Conversation").navigationBarTitleDisplayMode(.inline)183 .toolbar {184 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }185 ToolbarItem(placement: .confirmationAction) { Button("Done") { Task { await save(); dismiss() } }.accessibilityIdentifier("conversation-settings-done") }186 }187 .task { await load() }188 .sheet(item: $exportDocument) { file in ShareSheet(items: [file.url]) }189 }190 }191192 private func load() async {193 guard !loaded else { return }194 loaded = true195 let c = chat.conversation196 system = c.systemPrompt197 if let t = c.parameters.temperature { useTemperature = true; temperature = t }198 if let m = c.parameters.maxOutputTokens { useMaxTokens = true; maxTokens = Double(m) }199 reasoning = c.parameters.reasoning ?? .off200 if let capValue = c.contextWindowCap { useCap = true; cap = Double(capValue) } else { cap = Double(min(modelWindow, 8192)) }201 strategy = c.truncationStrategy; memory = c.memoryEnabled202 denyDataCollection = c.routing?.denyDataCollection ?? false203 allowFallbacks = c.routing?.allowFallbacks ?? true204 presets = (try? await app.store.presets()) ?? []205 }206207 private func save() async {208 let system = system, useTemperature = useTemperature && acceptsTemperature, temperature = temperature, useMaxTokens = useMaxTokens, maxTokens = Int(maxTokens)209 let reasoning = reasoning, capValue: Int? = useCap ? Int(cap) : nil, strategy = strategy, memory = memory210 let routing = RoutingPreferences(allowFallbacks: allowFallbacks, denyDataCollection: denyDataCollection)211 let isRouter = chat.conversation.model.provider == .openRouter212 await chat.update { c in213 c.systemPrompt = system214 c.parameters.temperature = useTemperature ? temperature : nil215 c.parameters.maxOutputTokens = useMaxTokens ? maxTokens : nil216 c.parameters.reasoning = reasoning == .off ? nil : reasoning217 c.contextWindowCap = capValue; c.truncationStrategy = strategy; c.memoryEnabled = memory218 if isRouter { c.routing = routing.isDefault ? nil : routing }219 }220 }221222 private func export(_ format: ExportFormat) {223 Task {224 do {225 let text: String226 if format == .json { text = String(decoding: try await app.store.exportConversationJSON(id: chat.conversation.id), as: UTF8.self) }227 else { text = try await app.store.exportConversationMarkdown(id: chat.conversation.id) }228 let name = (chat.conversation.title.isEmpty ? "conversation" : chat.conversation.title)229 exportDocument = try ExportedFile.write(text, name: name, ext: format == .json ? "json" : "md")230 } catch { app.show(AstraError.wrap(error).message, .error) }231 }232 }233}234235/// A file written to the temporary directory for the share sheet. Names are sanitised; the file is removed on next launch by the system.236struct ExportedFile: Identifiable {237 let url: URL238 var id: URL { url }239 static func write(_ text: String, name: String, ext: String) throws -> ExportedFile {240 let safe = name.replacingOccurrences(of: #"[^A-Za-z0-9 _\-]"#, with: "", options: .regularExpression).trimmingCharacters(in: .whitespaces).prefix(60)241 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("astra-export-\(UUID().uuidString)", isDirectory: true)242 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)243 let url = dir.appendingPathComponent((safe.isEmpty ? "export" : String(safe)) + "." + ext)244 try Data(text.utf8).write(to: url, options: [.atomic, .completeFileProtection])245 return ExportedFile(url: url)246 }247}248249#if canImport(UIKit)250import UIKit251struct ShareSheet: UIViewControllerRepresentable {252 let items: [Any]253 func makeUIViewController(context: Context) -> UIActivityViewController { UIActivityViewController(activityItems: items, applicationActivities: nil) }254 func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}255}256#else257struct ShareSheet: View { let items: [Any]; var body: some View { Text("Sharing is available on iPhone.") } }258#endif259