Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Agent/WorkspaceViews.swift3// Description: Agent (long-term memory, scheduled watches), Jobs (analyses and computations running on the server) and Documents (shared reports).4import SwiftUI5import VQuantCore67// MARK: - Agent: memory and watches89struct AgentView: View {10 let app: AppEnvironment11 let model: WindowModel12 @State private var newMemory = ""13 @State private var category = "profil"14 @State private var editingWatch: WatchDraft?1516 var body: some View {17 let ws = app.workspace.workspace18 VStack(spacing: 0) {19 if app.workspace.fromCache, let f = app.workspace.fetchedAt { NoticeBar(kind: .cached, text: "Offline: workspace received \(Fmt.relative(f)). Editing is disabled until the server is reachable.") }20 else if let e = app.workspace.error, ws == nil { NoticeBar(kind: .error, text: e) { Task { await app.workspace.refresh() } } }21 HSplitView {22 VStack(alignment: .leading, spacing: 8) {23 HStack { Text("Long-term memory").font(.headline); Spacer(); if let r = ws?.recall { Text("\(r.passages) passages from \(r.conversations) conversations in the searchable archive").font(.caption).foregroundStyle(.secondary) } }24 Text("What the agent remembers about you across conversations. It reads these before every analysis and can add to them itself.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)25 List {26 ForEach(Memory.categories, id: \.self) { cat in27 let items = (ws?.memories ?? []).filter { $0.category == cat }28 if !items.isEmpty {29 Section(Memory.categoryTitle(cat)) {30 ForEach(items) { m in31 HStack(alignment: .firstTextBaseline) {32 Text(m.content).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)33 Spacer()34 Text(Fmt.relative(m.created)).font(.caption2).foregroundStyle(.tertiary)35 Button { change { try await $0.deleteMemory(m.id) } } label: { Image(systemName: "trash") }.buttonStyle(.borderless).disabled(!app.workspace.canEdit).help("Forget this")36 }37 }38 }39 }40 }41 }42 .listStyle(.inset)43 .overlay { if (ws?.memories.isEmpty ?? false) { EmptyState(symbol: "brain", title: "Nothing remembered yet") } }44 HStack {45 Picker("", selection: $category) { ForEach(Memory.categories, id: \.self) { Text(Memory.categoryTitle($0)).tag($0) } }.labelsHidden().frame(width: 130)46 TextField("Something the agent should remember", text: $newMemory).textFieldStyle(.roundedBorder).onSubmit(addMemory)47 Button("Add", action: addMemory).disabled(newMemory.trimmingCharacters(in: .whitespaces).count < 3 || !app.workspace.canEdit)48 }49 }50 .padding(12).frame(minWidth: 380)5152 VStack(alignment: .leading, spacing: 8) {53 HStack { Text("Scheduled watches").font(.headline); Spacer(); Button { editingWatch = WatchDraft() } label: { Label("New Watch", systemImage: "plus") }.disabled(!app.workspace.canEdit) }54 Text("A watch runs a question on the server at a set time (New York time) and saves the answer as a conversation.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)55 List {56 ForEach(ws?.watches ?? []) { w in57 HStack(alignment: .top, spacing: 8) {58 Toggle("", isOn: Binding(get: { w.enabled }, set: { on in change { _ = try await $0.updateWatch(w.id, ["enabled": .bool(on)]) } })).labelsHidden().toggleStyle(.switch).controlSize(.small).disabled(!app.workspace.canEdit)59 VStack(alignment: .leading, spacing: 2) {60 Text(w.title).fontWeight(.medium)61 Text("\(w.time) ET · \(w.days == "daily" ? "every day" : "weekdays")\(w.deep ? " · deep research" : "") · \(ResearchModel.name(w.model))").font(.caption).foregroundStyle(.secondary)62 Text(w.prompt).font(.caption).foregroundStyle(.secondary).lineLimit(2)63 if let t = w.lastRun { Text("Last run \(Fmt.relative(t))\(w.lastStatus.map { " · \($0)" } ?? "")").font(.caption2).foregroundStyle(.tertiary) }64 }65 Spacer()66 Menu {67 Button("Run Now") { change { try await $0.runWatch(w.id) }; app.toasts.show("“\(w.title)” started on the server.") }68 if let sid = w.lastSessionId { Button("Open Last Answer") { model.openConversation(sid) } }69 Button("Edit…") { editingWatch = WatchDraft(w) }70 Divider()71 Button("Delete", role: .destructive) { change { try await $0.deleteWatch(w.id) } }72 } label: { Image(systemName: "ellipsis.circle") }.menuStyle(.borderlessButton).frame(width: 28).disabled(!app.workspace.canEdit)73 }74 .padding(.vertical, 2)75 }76 }77 .listStyle(.inset)78 .overlay { if (ws?.watches.isEmpty ?? false) { EmptyState(symbol: "clock.badge.checkmark", title: "No watch scheduled") } }79 }80 .padding(12).frame(minWidth: 360)81 }82 }83 .task { await app.workspace.refresh() }84 .sheet(item: $editingWatch) { d in WatchSheet(app: app, draft: d) }85 }8687 private func addMemory() {88 let text = newMemory.trimmingCharacters(in: .whitespaces)89 guard text.count >= 3 else { return }90 newMemory = ""91 change { _ = try await $0.addMemory(content: text, category: category) }92 }93 private func change(_ op: @escaping (VQuantAPI) async throws -> Void) { Task { do { try await app.workspace.perform(op) } catch { app.toasts.error(error) } } }94}9596struct WatchDraft: Identifiable {97 let id = UUID()98 var watchId: String?99 var title = "", prompt = "", time = "08:30", days = "weekdays", deep = false, model = ResearchModel.default100 init() {}101 init(_ w: Watch) { watchId = w.id; title = w.title; prompt = w.prompt; time = w.time; days = w.days; deep = w.deep; model = w.model }102}103104private struct WatchSheet: View {105 let app: AppEnvironment106 @State var draft: WatchDraft107 @State private var error: String?108 @Environment(\.dismiss) private var dismiss109110 var body: some View {111 VStack(alignment: .leading, spacing: 12) {112 Text(draft.watchId == nil ? "New Watch" : "Edit Watch").font(.headline)113 Form {114 TextField("Title", text: $draft.title)115 TextField("Question", text: $draft.prompt, axis: .vertical).lineLimit(3...8)116 TextField("Time (24 h, New York)", text: $draft.time)117 Picker("Days", selection: $draft.days) { Text("Weekdays").tag("weekdays"); Text("Every day").tag("daily") }118 Toggle("Deep research (longer and more expensive)", isOn: $draft.deep)119 if draft.watchId == nil { Picker("Model", selection: $draft.model) { ForEach(ResearchModel.all, id: \.id) { Text($0.name).tag($0.id) } } }120 }121 if let error { Text(error).font(.callout).foregroundStyle(Palette.red).fixedSize(horizontal: false, vertical: true) }122 HStack { Spacer(); Button("Cancel", role: .cancel) { dismiss() }; Button("Save") { save() }.keyboardShortcut(.defaultAction) }123 }124 .padding(18).frame(width: 480)125 }126127 private func save() {128 guard draft.time.range(of: "^([01][0-9]|2[0-3]):[0-5][0-9]$", options: .regularExpression) != nil else { error = "Use a 24-hour time such as 08:30."; return }129 guard !draft.title.trimmingCharacters(in: .whitespaces).isEmpty, !draft.prompt.trimmingCharacters(in: .whitespaces).isEmpty else { error = "A title and a question are required."; return }130 let d = draft131 Task {132 do {133 try await app.workspace.perform { api in134 if let id = d.watchId { _ = try await api.updateWatch(id, ["title": .string(d.title), "prompt": .string(d.prompt), "time": .string(d.time), "days": .string(d.days), "deep": .bool(d.deep)]) }135 else { _ = try await api.createWatch(title: d.title, prompt: d.prompt, time: d.time, days: d.days, deep: d.deep, model: d.model) }136 }137 dismiss()138 } catch { self.error = error.localizedDescription }139 }140 }141}142143// MARK: - Jobs144145struct JobsView: View {146 let app: AppEnvironment147 let model: WindowModel148149 var body: some View {150 VSplitView {151 VStack(alignment: .leading, spacing: 0) {152 header("Analyses", detail: "Research jobs of the last 24 hours. They run on the server and continue when no device is watching. A finished job can be replayed for 20 minutes; its answer stays in the conversation.", error: app.research.generationsError)153 Table(app.research.generations) {154 TableColumn("") { g in GenerationStatusIcon(status: g.status) }.width(22)155 TableColumn("Question") { g in Text(g.query).lineLimit(1).help(g.query) }156 TableColumn("Mode") { g in Text(ResearchMode(rawValue: g.mode)?.title ?? g.mode) }.width(min: 70, ideal: 100)157 TableColumn("Step") { g in Text(g.error ?? g.step).foregroundStyle(g.error == nil ? Color.secondary : Palette.red).lineLimit(1) }158 TableColumn("Tools") { g in Text("\(g.tools)").monospacedDigit() }.width(46)159 TableColumn("Started") { g in Text(Fmt.time(g.started)) }.width(min: 70, ideal: 84)160 TableColumn("Duration") { g in Text(Fmt.duration((g.finished ?? Date()).timeIntervalSince(g.started))).monospacedDigit() }.width(min: 70, ideal: 90)161 TableColumn("") { g in162 HStack(spacing: 6) {163 Button("Open") { if g.status == .running || g.replayable { app.research.attach(g) }; model.openConversation(g.sessionId) }164 if g.status == .running { Button("Stop", role: .destructive) { Task { await app.research.cancelGeneration(g.id) } } }165 }.controlSize(.small)166 }.width(110)167 }168 .overlay { if app.research.generations.isEmpty { EmptyState(symbol: "sparkles", title: "No analysis in the last 24 hours") } }169 }170 .frame(minHeight: 180)171 VStack(alignment: .leading, spacing: 0) {172 header("Computations", detail: "Quant Engine jobs. Results are stored on the server with their parameters and code.", error: app.quant.error)173 Table(app.quant.jobs) {174 TableColumn("") { j in JobStatusIcon(status: j.status) }.width(22)175 TableColumn("Engine") { j in Text(app.quant.tool(j.tool)?.title ?? j.tool) }.width(min: 120, ideal: 170)176 TableColumn("Subject") { j in Text(j.subject).font(.body.monospaced()).lineLimit(1) }.width(min: 90, ideal: 160)177 TableColumn("Parameters") { j in Text(j.paramSummary).font(.caption).foregroundStyle(.secondary).lineLimit(1).help(j.paramSummary) }178 TableColumn("Started") { j in Text(Fmt.dateTime(j.started)) }.width(min: 110, ideal: 140)179 TableColumn("Duration") { j in Text(j.status == .running ? Fmt.duration(Date().timeIntervalSince(j.started)) : Fmt.duration(j.duration)).monospacedDigit() }.width(min: 70, ideal: 90)180 TableColumn("") { j in Button("Open") { model.openQuantJob(j.id) }.controlSize(.small) }.width(60)181 }182 .overlay { if app.quant.jobs.isEmpty { EmptyState(symbol: "function", title: "No computation yet") } }183 }184 .frame(minHeight: 180)185 }186 .task { await app.research.refreshGenerations(); await app.quant.refresh() }187 }188189 private func header(_ title: String, detail: String, error: String?) -> some View {190 VStack(alignment: .leading, spacing: 2) {191 Text(title).font(.headline)192 Text(error ?? detail).font(.caption).foregroundStyle(error == nil ? Color.secondary : Palette.red)193 }194 .padding(.horizontal, 12).padding(.vertical, 8)195 }196}197198struct GenerationStatusIcon: View {199 let status: GenerationSummary.Status200 var body: some View {201 switch status {202 case .running: ProgressView().controlSize(.mini)203 case .done: Image(systemName: "checkmark.circle.fill").foregroundStyle(Palette.green)204 case .error: Image(systemName: "xmark.circle.fill").foregroundStyle(Palette.red)205 case .cancelled: Image(systemName: "stop.circle.fill").foregroundStyle(.secondary)206 }207 }208}209210// MARK: - Documents211212struct DocumentsView: View {213 let app: AppEnvironment214 let model: WindowModel215 @State private var reports: [SharedReportSummary] = []216 @State private var fromCache = false217 @State private var error: String?218 @State private var selection: String?219 @State private var report: SharedReport?220 @State private var filter = ""221 @State private var loading = false222223 var body: some View {224 HSplitView {225 VStack(spacing: 0) {226 TextField("Filter shared reports", text: $filter).textFieldStyle(.roundedBorder).padding(8)227 if fromCache { Text("Offline — list from this Mac's cache").font(.caption).foregroundStyle(.orange).padding(.bottom, 4) }228 List {229 ForEach(reports.filter { filter.isEmpty || $0.question.localizedCaseInsensitiveContains(filter) }) { r in230 SelectableRow(isSelected: selection == r.shareId) { selection = r.shareId } content: { VStack(alignment: .leading, spacing: 2) { Text(r.question).lineLimit(2); Text(Fmt.dateTime(ServerDate.parse(r.createdAt))).font(.caption2).foregroundStyle(.tertiary) } }231 }232 }233 .listStyle(.inset)234 .overlay { if reports.isEmpty { EmptyState(symbol: "doc.text", title: loading ? "Loading…" : "No shared report", detail: error ?? "A report is published here from Research with Export › Publish to Shared Reports.") } }235 }236 .frame(minWidth: 240, idealWidth: 300, maxWidth: 400)237 Group {238 if let report {239 ScrollView {240 VStack(alignment: .leading, spacing: 12) {241 HStack(alignment: .top) {242 Text(report.question).font(.title3.weight(.semibold)).textSelection(.enabled)243 Spacer()244 ReportActions(app: app, question: report.question, answer: report.answer, sources: report.sources, figures: [])245 }246 Text("Published \(Fmt.dateTime(ServerDate.parse(report.createdAt)))").font(.caption).foregroundStyle(.secondary)247 Divider()248 MarkdownView(app: app, source: report.answer)249 if !report.sources.isEmpty { SourcesView(sources: report.sources) }250 }251 .padding(.horizontal, 24).padding(.vertical, 18).frame(maxWidth: 980, alignment: .leading).frame(maxWidth: .infinity)252 }253 } else { EmptyState(symbol: "doc.text.magnifyingglass", title: "Shared reports", detail: "Reports published from a conversation, readable by every person of this VQuant instance. Exports to PDF, Word and slides are rendered by the server.") }254 }255 .frame(minWidth: 460, maxWidth: .infinity)256 }257 .task {258 loading = true; defer { loading = false }259 do { let r = try await app.cache.fetch("shared-reports") { [api = app.api] in try await api.sharedReports() }; reports = r.value; fromCache = r.fromCache; error = nil }260 catch { self.error = error.localizedDescription }261 }262 .task(id: selection) {263 guard let id = selection else { report = nil; return }264 report = (try? await app.cache.fetch("shared-report-\(id)") { [api = app.api] in try await api.sharedReport(id) })?.value265 }266 }267}268