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/Lab/PromptStudio.swift10// Module : Lab11// 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/// Prompt studio: reusable templates with `{{variables}}` and a version history, plus the presets offered in conversation settings.94struct PromptStudioView: View {95 enum Tab: String, CaseIterable, Identifiable {96 case templates, presets97 var id: String { rawValue }98 var title: String { self == .templates ? "Templates" : "Presets" }99 }100 @Environment(AppModel.self) private var app101 /// Pushes the editor of a template that was just created.102 let onOpen: (String) -> Void103 @State private var tab: Tab = .templates104 @State private var templates: [PromptTemplateRecord]?105 @State private var presets: [PresetRecord]?106 @State private var error: String?107 @State private var naming = false108 @State private var newName = ""109 @State private var presetDraft: PresetRecord?110 @State private var deletingTemplate: PromptTemplateRecord?111 @State private var deletingPreset: PresetRecord?112113 var body: some View {114 LabPage(title: "Prompt studio") {115 Picker("Section", selection: $tab) { ForEach(Tab.allCases) { Text($0.title).tag($0) } }116 .pickerStyle(.segmented).accessibilityIdentifier("prompt-studio-tab")117 if let error { NoticeCard(.error, title: "The prompt studio could not be read", message: error, actionTitle: "Try again") { Task { await load() } } }118 switch tab {119 case .templates: templatesList120 case .presets: presetsList121 }122 }123 .toolbar {124 ToolbarItem(placement: .topBarTrailing) {125 Button {126 if tab == .templates { newName = ""; naming = true } else { presetDraft = PresetRecord(name: "") }127 } label: { Label(tab == .templates ? "New template" : "New preset", systemImage: "plus") }128 .accessibilityIdentifier("prompt-studio-add")129 }130 }131 .task { for await _ in app.store.changes(in: AstraTable.promptStudio) { await load() } }132 .alert("New template", isPresented: $naming) {133 TextField("Name", text: $newName)134 Button("Create") { create() }135 Button("Cancel", role: .cancel) {}136 } message: { Text("Give it a name. You can write the prompt next.") }137 .sheet(item: $presetDraft) { PresetEditorSheet(preset: $0) }138 .confirmationDialog("Delete this template?", isPresented: Binding(get: { deletingTemplate != nil }, set: { if !$0 { deletingTemplate = nil } }), titleVisibility: .visible) {139 Button("Delete with its history", role: .destructive) { if let t = deletingTemplate { remove(template: t) } }140 Button("Cancel", role: .cancel) {}141 } message: { Text("Every saved version of “\(deletingTemplate?.name ?? "")” is removed.") }142 .confirmationDialog("Delete this preset?", isPresented: Binding(get: { deletingPreset != nil }, set: { if !$0 { deletingPreset = nil } }), titleVisibility: .visible) {143 Button("Delete", role: .destructive) { if let p = deletingPreset { remove(preset: p) } }144 Button("Cancel", role: .cancel) {}145 } message: { Text("Conversations that already used it keep their own copy of the instructions.") }146 }147148 @ViewBuilder private var templatesList: some View {149 if let templates {150 if templates.isEmpty {151 EmptyStateView(symbol: "text.badge.star", title: "No template yet",152 message: "A template is a prompt with {{variables}} you fill in each time. Every save keeps a version you can return to.") {153 Button("Create a template") { newName = ""; naming = true }.buttonStyle(AstraPrimaryButtonStyle()).accessibilityIdentifier("prompt-studio-create")154 }155 .frame(maxWidth: .infinity)156 } else {157 ForEach(templates) { template in158 NavigationLink(value: LabRoute.template(template.id)) {159 AstraCard {160 VStack(alignment: .leading, spacing: AstraSpace.sm) {161 HStack(alignment: .firstTextBaseline) {162 Text(template.name.isEmpty ? "Untitled template" : template.name).font(AstraFont.headline).foregroundStyle(AstraColor.textPrimary).lineLimit(2)163 Spacer(minLength: AstraSpace.sm)164 AstraBadge("v\(template.currentVersion)", symbol: "clock.arrow.circlepath")165 }166 Text(template.userTemplate.isEmpty ? "No prompt written yet." : template.userTemplate)167 .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).lineLimit(3).multilineTextAlignment(.leading)168 if !template.variables.isEmpty {169 FlowLayout(spacing: AstraSpace.xs) { ForEach(template.variables, id: \.self) { AstraBadge("{{\($0)}}", tone: .accent) } }170 }171 Text("Edited \(LabFormat.dateTime(template.updatedAt))").font(AstraFont.micro).foregroundStyle(AstraColor.textTertiary)172 }173 }174 }175 .buttonStyle(.plain)176 .contextMenu { Button(role: .destructive) { deletingTemplate = template } label: { Label("Delete", systemImage: "trash") } }177 .accessibilityIdentifier("template-row")178 }179 }180 } else if error == nil { LabLoading() }181 }182183 @ViewBuilder private var presetsList: some View {184 if let presets {185 if presets.isEmpty {186 EmptyStateView(symbol: "slider.horizontal.3", title: "No preset yet",187 message: "A preset is a set of system instructions with generation parameters. Saved presets are offered in every conversation's settings.") {188 Button("Create a preset") { presetDraft = PresetRecord(name: "") }.buttonStyle(AstraPrimaryButtonStyle()).accessibilityIdentifier("preset-create")189 }190 .frame(maxWidth: .infinity)191 } else {192 ForEach(presets) { preset in193 AstraCard(padding: 0) {194 HStack(alignment: .top, spacing: 0) {195 Button { presetDraft = preset } label: {196 VStack(alignment: .leading, spacing: AstraSpace.xs) {197 Text(preset.name.isEmpty ? "Untitled preset" : preset.name).font(AstraFont.headline).foregroundStyle(AstraColor.textPrimary)198 Text(preset.system.isEmpty ? "No instructions." : preset.system).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).lineLimit(3).multilineTextAlignment(.leading)199 FlowLayout(spacing: AstraSpace.xs) {200 if let t = preset.parameters.temperature { AstraBadge(String(format: "Temperature %.2f", t)) }201 if let m = preset.parameters.maxOutputTokens { AstraBadge("Max \(m) tokens") }202 if let r = preset.parameters.reasoning { AstraBadge("Reasoning \(r.title.lowercased())") }203 }204 }205 .padding(AstraSpace.lg).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())206 }207 .buttonStyle(.plain)208 .accessibilityHint("Edits the preset")209 IconButton("trash", label: "Delete preset \(preset.name)", tint: AstraColor.textTertiary) { deletingPreset = preset }210 .padding(.top, AstraSpace.xs).padding(.trailing, AstraSpace.xs)211 }212 }213 }214 }215 } else if error == nil { LabLoading() }216 }217218 private func load() async {219 do { templates = try await app.store.templates(); presets = try await app.store.presets(); error = nil }220 catch { self.error = AstraError.wrap(error).message }221 }222223 private func create() {224 let name = newName.trimmingCharacters(in: .whitespacesAndNewlines)225 let store = app.store226 Task {227 do { onOpen(try await store.saveTemplate(name: name.isEmpty ? "Untitled template" : name, system: "", userTemplate: "", note: "Created").id) }228 catch { app.show(AstraError.wrap(error).message, .error) }229 }230 }231232 private func remove(template: PromptTemplateRecord) {233 let store = app.store234 Task {235 do { try await store.deleteTemplate(id: template.id); app.show("Template deleted", .success) }236 catch { app.show(AstraError.wrap(error).message, .error) }237 }238 }239240 private func remove(preset: PresetRecord) {241 let store = app.store242 Task {243 do { try await store.deletePreset(id: preset.id); app.show("Preset deleted", .success) }244 catch { app.show(AstraError.wrap(error).message, .error) }245 }246 }247}248249// MARK: - Template editor250251/// Edits one template, shows its history, and runs it against a model with the variables filled in.252struct TemplateEditorView: View {253 @Environment(AppModel.self) private var app254 @Environment(\.dismiss) private var dismiss255 let templateID: String256257 @State private var record: PromptTemplateRecord?258 @State private var missing = false259 @State private var name = ""260 @State private var system = ""261 @State private var user = ""262 @State private var parameters = GenerationParameters()263 @State private var note = ""264 @State private var isSaving = false265 @State private var values: [String: String] = [:]266 @State private var model: ModelRef?267 @State private var showPicker = false268 @State private var showVersions = false269 @State private var presetNaming = false270 @State private var presetName = ""271 @State private var confirmDelete = false272 @State private var run: LabRunController?273274 private var variables: [String] { PromptRenderer.variables(in: system + "\n" + user) }275 private var isDirty: Bool {276 guard let record else { return false }277 return record.name != name || record.system != system || record.userTemplate != user || record.parameters != parameters278 }279 private var renderedSystem: PromptRenderer.Result { PromptRenderer.render(system, values: values) }280 private var renderedUser: PromptRenderer.Result { PromptRenderer.render(user, values: values) }281282 var body: some View {283 LabPage(title: name.isEmpty ? "Template" : name) {284 if missing {285 EmptyStateView(symbol: "doc.questionmark", title: "This template no longer exists", message: "It may have been deleted.").frame(maxWidth: .infinity)286 } else if record == nil {287 LabLoading()288 } else {289 editor290 runSection291 manage292 }293 }294 .keyboardDoneButton()295 .toolbar {296 ToolbarItem(placement: .topBarTrailing) {297 Button { showVersions = true } label: { Label("Version history", systemImage: "clock.arrow.circlepath") }298 .disabled(record == nil).accessibilityIdentifier("template-versions")299 }300 }301 .task { await load() }302 .sheet(isPresented: $showPicker) {303 ModelPickerSheet(selected: model) { ref in304 model = ref305 let store = app.store306 Task { try? await store.setSetting("lab.promptStudio.model", ref.id) }307 }308 }309 .sheet(isPresented: $showVersions) {310 TemplateVersionsSheet(templateID: templateID, current: record?.currentVersion ?? 0) { restored in apply(restored) }311 }312 .alert("Save as preset", isPresented: $presetNaming) {313 TextField("Preset name", text: $presetName)314 Button("Save") { savePreset() }315 Button("Cancel", role: .cancel) {}316 } message: { Text("The system instructions and the parameters of this template become a preset you can apply in any conversation.") }317 .confirmationDialog("Delete this template?", isPresented: $confirmDelete, titleVisibility: .visible) {318 Button("Delete with its history", role: .destructive) { delete() }319 Button("Cancel", role: .cancel) {}320 }321 }322323 private var editor: some View {324 VStack(alignment: .leading, spacing: AstraSpace.md) {325 SectionTitle("Template", detail: record.map { "Version \($0.currentVersion)" })326 AstraCard {327 VStack(alignment: .leading, spacing: AstraSpace.md) {328 Text("Name").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)329 TextField("Name", text: $name)330 .font(AstraFont.body).padding(.horizontal, AstraSpace.md).frame(minHeight: AstraSpace.hit)331 .background(AstraColor.surfaceSunken, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))332 .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))333 .accessibilityIdentifier("template-name")334 Text("System instructions").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)335 LabTextArea(label: "System instructions", text: $system, placeholder: "Optional. You are a {{role}}…", minHeight: 80)336 .accessibilityIdentifier("template-system")337 Text("User prompt").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)338 LabTextArea(label: "User prompt template", text: $user, placeholder: "Summarize {{text}} in {{count}} bullet points.", minHeight: 130)339 .accessibilityIdentifier("template-user")340 if variables.isEmpty {341 Text("Write {{name}} anywhere to create a variable.").font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary)342 } else {343 FlowLayout(spacing: AstraSpace.xs) { ForEach(variables, id: \.self) { AstraBadge("{{\($0)}}", tone: .accent) } }344 .accessibilityElement(children: .ignore).accessibilityLabel("Variables").accessibilityValue(variables.joined(separator: ", "))345 }346 LabDivider()347 ParameterEditor(parameters: $parameters)348 if isDirty {349 LabDivider()350 TextField("What changed? (optional)", text: $note)351 .font(AstraFont.callout).padding(.horizontal, AstraSpace.md).frame(minHeight: AstraSpace.hit)352 .background(AstraColor.surfaceSunken, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))353 .accessibilityLabel("Note for this version")354 Button { save() } label: {355 HStack(spacing: AstraSpace.sm) { if isSaving { ProgressView().tint(AstraColor.onAccent) }; Text("Save as version \((record?.currentVersion ?? 0) + 1)") }356 }357 .buttonStyle(AstraPrimaryButtonStyle()).disabled(isSaving).accessibilityIdentifier("template-save")358 }359 }360 }361 }362 }363364 private var runSection: some View {365 VStack(alignment: .leading, spacing: AstraSpace.md) {366 SectionTitle("Try it", detail: isDirty ? "Uses the unsaved text" : nil)367 AstraCard {368 VStack(alignment: .leading, spacing: AstraSpace.md) {369 ModelChoiceRow(ref: model) { showPicker = true }.accessibilityIdentifier("template-model")370 if !variables.isEmpty {371 LabDivider()372 ForEach(variables, id: \.self) { variable in373 VStack(alignment: .leading, spacing: AstraSpace.xs) {374 Text(variable).font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)375 LabTextArea(label: "Value of \(variable)", text: Binding(get: { values[variable] ?? "" }, set: { values[variable] = $0.isEmpty ? nil : $0 }),376 placeholder: "Value", minHeight: 48)377 }378 }379 }380 let unfilled = Array(Set(renderedSystem.missing + renderedUser.missing)).sorted()381 if !unfilled.isEmpty {382 Label("Not filled: " + unfilled.map { "{{\($0)}}" }.joined(separator: ", ") + ". They are sent as written.", systemImage: "exclamationmark.triangle.fill")383 .font(AstraFont.caption).foregroundStyle(AstraColor.warning).fixedSize(horizontal: false, vertical: true)384 }385 if let run, run.isRunning {386 Button { run.stop() } label: { Label("Stop", systemImage: "stop.fill") }387 .buttonStyle(AstraSecondaryButtonStyle()).accessibilityIdentifier("template-stop")388 } else {389 Button { start() } label: { Label("Run", systemImage: "play.fill") }390 .buttonStyle(AstraPrimaryButtonStyle())391 .disabled(model == nil || user.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)392 .accessibilityIdentifier("template-run")393 if model == nil { Text("Choose a model to run the prompt.").font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary) }394 }395 if let run, run.phase != .idle {396 LabDivider()397 LabRunResultView(run: run)398 }399 }400 }401 }402 }403404 private var manage: some View {405 AstraCard(padding: 0) {406 VStack(spacing: 0) {407 Button { presetName = name; presetNaming = true } label: {408 LabActionRow(title: "Save as preset", detail: "Instructions and parameters, reusable in any chat", symbol: "slider.horizontal.3", showsChevron: false)409 .padding(.horizontal, AstraSpace.lg).padding(.vertical, AstraSpace.sm)410 }411 .buttonStyle(.plain).accessibilityIdentifier("template-save-preset")412 LabDivider()413 Button { confirmDelete = true } label: {414 LabActionRow(title: "Delete template", symbol: "trash", tint: AstraColor.danger, showsChevron: false)415 .padding(.horizontal, AstraSpace.lg).padding(.vertical, AstraSpace.sm)416 }417 .buttonStyle(.plain).accessibilityIdentifier("template-delete")418 }419 }420 }421422 private func apply(_ template: PromptTemplateRecord) {423 record = template; name = template.name; system = template.system; user = template.userTemplate; parameters = template.parameters; note = ""424 }425426 private func load() async {427 guard record == nil else { return }428 do {429 if let found = try await app.store.template(id: templateID) { apply(found) } else { missing = true }430 } catch { missing = true }431 if model == nil {432 let stored: String? = try? await app.store.setting("lab.promptStudio.model")433 if let ref = stored.flatMap({ ModelRef(id: $0) }), app.library.availability(of: ref) == nil, app.library.info(for: ref) != nil { model = ref }434 else { model = app.library.defaultModel() }435 }436 }437438 private func save() {439 guard !isSaving else { return }440 isSaving = true441 let store = app.store, id = templateID, name = name.trimmingCharacters(in: .whitespacesAndNewlines), system = system, user = user, parameters = parameters442 let note = note.trimmingCharacters(in: .whitespacesAndNewlines)443 Task {444 defer { isSaving = false }445 do {446 apply(try await store.saveTemplate(id: id, name: name.isEmpty ? "Untitled template" : name, system: system, userTemplate: user, parameters: parameters, note: note.isEmpty ? nil : note))447 AstraHaptics.success(); app.show("Saved as version \(record?.currentVersion ?? 0)", .success)448 } catch { app.show(AstraError.wrap(error).message, .error) }449 }450 }451452 private func start() {453 guard let model else { return }454 LabKeyboard.dismiss()455 let controller = run ?? LabRunController(store: app.store, library: app.library, orchestrator: app.orchestrator)456 run = controller457 AstraHaptics.send()458 controller.run(model: model, system: renderedSystem.text, prompt: renderedUser.text, parameters: parameters, origin: .promptStudio)459 }460461 private func savePreset() {462 let preset = PresetRecord(name: presetName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? name : presetName.trimmingCharacters(in: .whitespacesAndNewlines),463 system: renderedSystem.text, parameters: parameters)464 let store = app.store465 Task {466 do { try await store.savePreset(preset); app.show("Preset saved", .success) }467 catch { app.show(AstraError.wrap(error).message, .error) }468 }469 }470471 private func delete() {472 let store = app.store, id = templateID473 run?.stop()474 Task {475 do { try await store.deleteTemplate(id: id); app.show("Template deleted", .success); dismiss() }476 catch { app.show(AstraError.wrap(error).message, .error) }477 }478 }479}480481// MARK: - Versions482483struct TemplateVersionsSheet: View {484 @Environment(AppModel.self) private var app485 @Environment(\.dismiss) private var dismiss486 let templateID: String487 let current: Int488 let onRestore: (PromptTemplateRecord) -> Void489490 @State private var versions: [PromptTemplateVersionRecord]?491 @State private var error: String?492 @State private var open: String?493 @State private var restoring = false494495 var body: some View {496 NavigationStack {497 ScrollView {498 VStack(alignment: .leading, spacing: AstraSpace.md) {499 if let versions {500 Text("Every save is kept. Restoring an old version saves it again as the newest one, so nothing is ever overwritten.")501 .font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary).fixedSize(horizontal: false, vertical: true)502 ForEach(versions) { version in card(version) }503 } else if let error {504 NoticeCard(.error, title: "The history could not be read", message: error, actionTitle: "Try again") { Task { await load() } }505 } else { LabLoading() }506 }507 .padding(AstraSpace.page)508 }509 .background(AstraColor.background)510 .navigationTitle("Version history").navigationBarTitleDisplayMode(.inline)511 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }512 .task { await load() }513 }514 .presentationDetents([.large])515 }516517 private func card(_ version: PromptTemplateVersionRecord) -> some View {518 let isOpen = open == version.id519 let isCurrent = version.version == current520 return AstraCard {521 VStack(alignment: .leading, spacing: AstraSpace.sm) {522 Button { open = isOpen ? nil : version.id } label: {523 HStack(alignment: .firstTextBaseline, spacing: AstraSpace.sm) {524 VStack(alignment: .leading, spacing: AstraSpace.xxs) {525 HStack(spacing: AstraSpace.sm) {526 Text("Version \(version.version)").font(AstraFont.headline).foregroundStyle(AstraColor.textPrimary)527 if isCurrent { AstraBadge("Current", symbol: "checkmark", tone: .success) }528 }529 Text(LabFormat.dateTime(version.createdAt) + (version.note.map { " · " + $0 } ?? "")).font(AstraFont.caption).foregroundStyle(AstraColor.textSecondary)530 .multilineTextAlignment(.leading)531 }532 Spacer(minLength: AstraSpace.sm)533 Image(systemName: "chevron.right").font(.caption.weight(.semibold)).foregroundStyle(AstraColor.textTertiary).rotationEffect(.degrees(isOpen ? 90 : 0))534 }535 .frame(minHeight: AstraSpace.hit).contentShape(Rectangle())536 }537 .buttonStyle(.plain)538 .accessibilityValue(isOpen ? "expanded" : "collapsed")539 if isOpen {540 if !version.system.isEmpty {541 Text("System instructions").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)542 Text(version.system).font(AstraFont.monoSmall).foregroundStyle(AstraColor.textPrimary).textSelection(.enabled)543 }544 Text("User prompt").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)545 Text(version.userTemplate.isEmpty ? "Empty" : version.userTemplate).font(AstraFont.monoSmall).foregroundStyle(AstraColor.textPrimary).textSelection(.enabled)546 if !isCurrent {547 Button { restore(version) } label: { Label("Restore this version", systemImage: "arrow.uturn.backward") }548 .buttonStyle(AstraSecondaryButtonStyle()).disabled(restoring).accessibilityIdentifier("template-restore")549 }550 }551 }552 }553 }554555 private func load() async {556 error = nil557 do { versions = try await app.store.templateVersions(templateID: templateID) } catch { self.error = AstraError.wrap(error).message }558 }559560 private func restore(_ version: PromptTemplateVersionRecord) {561 restoring = true562 let store = app.store, id = templateID563 Task {564 defer { restoring = false }565 do {566 let restored = try await store.restoreTemplateVersion(templateID: id, version: version.version)567 onRestore(restored); app.show("Version \(version.version) restored as version \(restored.currentVersion)", .success); dismiss()568 } catch { app.show(AstraError.wrap(error).message, .error) }569 }570 }571}572573// MARK: - Preset editor574575struct PresetEditorSheet: View {576 @Environment(AppModel.self) private var app577 @Environment(\.dismiss) private var dismiss578 @State var preset: PresetRecord579 @State private var isSaving = false580581 var body: some View {582 NavigationStack {583 ScrollView {584 VStack(alignment: .leading, spacing: AstraSpace.md) {585 Text("Name").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)586 TextField("Name", text: $preset.name)587 .font(AstraFont.body).padding(.horizontal, AstraSpace.md).frame(minHeight: AstraSpace.hit)588 .background(AstraColor.surfaceSunken, in: RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous))589 .overlay(RoundedRectangle(cornerRadius: AstraRadius.md, style: .continuous).strokeBorder(AstraColor.stroke, lineWidth: 1))590 .accessibilityIdentifier("preset-name")591 Text("System instructions").font(AstraFont.captionEmphasis).foregroundStyle(AstraColor.textSecondary)592 LabTextArea(label: "System instructions", text: $preset.system, placeholder: "How the model should behave.", minHeight: 140)593 .accessibilityIdentifier("preset-system")594 AstraCard { ParameterEditor(parameters: $preset.parameters) }595 Text("A switched-off parameter uses the provider's default. Parameters a model cannot accept are dropped when the preset is used, and you are told.")596 .font(AstraFont.caption).foregroundStyle(AstraColor.textTertiary).fixedSize(horizontal: false, vertical: true)597 }598 .padding(AstraSpace.page)599 }600 .scrollDismissesKeyboard(.interactively)601 .background(AstraColor.background)602 .navigationTitle("Preset").navigationBarTitleDisplayMode(.inline)603 .toolbar {604 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }605 ToolbarItem(placement: .confirmationAction) {606 Button("Save") { save() }607 .disabled(isSaving || preset.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)608 .accessibilityIdentifier("preset-save")609 }610 }611 }612 .presentationDetents([.large])613 }614615 private func save() {616 isSaving = true617 var record = preset618 record.name = preset.name.trimmingCharacters(in: .whitespacesAndNewlines)619 let saved = record620 let store = app.store621 Task {622 defer { isSaving = false }623 do { try await store.savePreset(saved); app.show("Preset saved", .success); dismiss() }624 catch { app.show(AstraError.wrap(error).message, .error) }625 }626 }627}628