forked from osaurus-ai/osaurus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentDBTabViews.swift
More file actions
2397 lines (2248 loc) · 89.4 KB
/
Copy pathAgentDBTabViews.swift
File metadata and controls
2397 lines (2248 loc) · 89.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// AgentDBTabViews.swift
// osaurus
//
// Tabs that surface the Agent DB feature (spec §5.5 / §7) in the
// agent detail view: a read-only Schema view, a Data grid (filled in
// by `DataTabView`/`AgentDataTableRepresentable`), and an Activity
// log that joins `agent_runs` with `_changelog`.
//
// The tabs are gated by `Agent.settings.dbEnabled` in
// `AgentsView.DetailTab.allTabsForAgent(_:)`. They open the agent's
// encrypted DB lazily on first display via `LocalAgentBridge.shared`
// — if the DB has never been written to, the schema is just the
// reserved system tables and the tab renders an empty-state nudge.
//
import Foundation
import SwiftUI
// MARK: - Schema Tab
/// Read-only listing of every table, column, index, and view the agent
/// has materialized in its private DB. The system tables (`_tables_meta`,
/// `_changelog`, `_views`) sit at the top under a dimmed header so the
/// user can audit reserved-name conflicts; user tables follow in
/// creation order.
public struct SchemaTabView: View {
@Environment(\.theme) private var theme
let agentId: UUID
@State private var schema: AgentDatabaseSchema?
@State private var loadError: String?
@State private var isLoading = true
public init(agentId: UUID) {
self.agentId = agentId
}
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
if isLoading {
loadingState
} else if let error = loadError {
errorState(error)
} else if let schema, schema.tables.isEmpty && schema.views.isEmpty {
emptyState
} else if let schema {
schemaContent(schema)
}
}
.padding(24)
.frame(maxWidth: .infinity, alignment: .leading)
}
.background(theme.primaryBackground)
.task { await reload() }
.onChange(of: agentId) { _, _ in Task { await reload() } }
}
@MainActor
private func reload() async {
isLoading = true
loadError = nil
do {
let snapshot = try LocalAgentBridge.shared.schema(agentId: agentId)
self.schema = snapshot
self.isLoading = false
} catch {
self.loadError = error.localizedDescription
self.isLoading = false
}
}
@ViewBuilder
private var loadingState: some View {
HStack {
ProgressView()
Text("Loading schema…", bundle: .module)
.font(.system(size: 12))
.foregroundColor(theme.tertiaryText)
}
}
@ViewBuilder
private func errorState(_ message: String) -> some View {
VStack(alignment: .leading, spacing: 8) {
Label(localized: "Couldn't open the database", systemImage: "exclamationmark.triangle")
.font(.system(size: 13, weight: .semibold))
.foregroundColor(.red)
Text(message)
.font(.system(size: 11, design: .monospaced))
.foregroundColor(theme.tertiaryText)
}
}
@ViewBuilder
private var emptyState: some View {
VStack(alignment: .leading, spacing: 6) {
Text("No tables yet", bundle: .module)
.font(.system(size: 13, weight: .semibold))
.foregroundColor(theme.primaryText)
Text(
"Once the agent creates a table with the `db_create_table` tool, it will show up here.",
bundle: .module
)
.font(.system(size: 12))
.foregroundColor(theme.tertiaryText)
}
}
@ViewBuilder
private func schemaContent(_ schema: AgentDatabaseSchema) -> some View {
VStack(alignment: .leading, spacing: 18) {
HStack(spacing: 8) {
StorageQuotaBadge(agentId: agentId, theme: theme)
MutationsInFlightIndicator(agentId: agentId, theme: theme)
Spacer(minLength: 0)
}
ForEach(userTables(schema), id: \.name) { table in
tableCard(table, isSystem: false)
}
if !schema.views.isEmpty {
VStack(alignment: .leading, spacing: 8) {
sectionHeader("Saved Views")
ForEach(schema.views, id: \.name) { view in
viewCard(view)
}
}
}
let systemTables = schema.tables.filter { isSystemTable($0.name) }
if !systemTables.isEmpty {
VStack(alignment: .leading, spacing: 8) {
sectionHeader("System (reserved)")
ForEach(systemTables, id: \.name) { table in
tableCard(table, isSystem: true)
}
}
}
}
}
private func userTables(_ schema: AgentDatabaseSchema) -> [AgentTableSchema] {
schema.tables.filter { !isSystemTable($0.name) }
}
private func isSystemTable(_ name: String) -> Bool {
name.hasPrefix("_")
}
@ViewBuilder
private func sectionHeader(_ text: LocalizedStringKey) -> some View {
Text(text, bundle: .module)
.font(.system(size: 11, weight: .bold))
.foregroundColor(theme.tertiaryText)
.tracking(0.5)
}
@ViewBuilder
private func tableCard(_ table: AgentTableSchema, isSystem: Bool) -> some View {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 8) {
Image(systemName: "tablecells")
.foregroundColor(isSystem ? theme.tertiaryText : theme.accentColor)
Text(table.name)
.font(.system(size: 13, weight: .semibold, design: .monospaced))
.foregroundColor(theme.primaryText)
if !table.purpose.isEmpty {
Text("— \(table.purpose)")
.font(.system(size: 11))
.foregroundColor(theme.tertiaryText)
.lineLimit(1)
}
Spacer()
// Quick-jump into the Data tab for this row. System
// tables (`_changelog`, `_views`) are read-only so the
// Browse affordance still works on them — the user
// just lands on a non-editable grid. Posting through
// the same notification the Schema/Notify deep-link
// routes use keeps the entire focus pipeline single-
// sourced.
Button {
NotificationCenter.default.post(
name: .agentDetailDeeplink,
object: nil,
userInfo: [
"agentId": agentId,
"tab": "data",
"tableRef": table.name,
]
)
} label: {
Label(localized: "Browse", systemImage: "arrow.right.square")
.font(.system(size: 10, weight: .medium))
.labelStyle(.titleAndIcon)
}
.buttonStyle(.borderless)
.localizedHelp("Open this table in the Data tab")
}
ForEach(table.columns, id: \.name) { column in
HStack(spacing: 8) {
Text(column.name)
.font(.system(size: 11, design: .monospaced))
.foregroundColor(theme.primaryText)
Text(column.type)
.font(.system(size: 11, design: .monospaced))
.foregroundColor(theme.tertiaryText)
if column.primaryKey {
Text(localized: "PK").font(.system(size: 9, weight: .bold))
.foregroundColor(theme.accentColor)
}
if !column.nullable {
Text(localized: "NOT NULL").font(.system(size: 9))
.foregroundColor(theme.tertiaryText)
}
Spacer()
}
.padding(.leading, 18)
}
if !table.indexes.isEmpty {
ForEach(table.indexes, id: \.name) { index in
HStack(spacing: 8) {
Image(systemName: "list.bullet.indent")
.foregroundColor(theme.tertiaryText)
Text(index.name)
.font(.system(size: 10, weight: .medium, design: .monospaced))
.foregroundColor(theme.tertiaryText)
Text("(\(index.columns.joined(separator: ", ")))")
.font(.system(size: 10, design: .monospaced))
.foregroundColor(theme.tertiaryText)
if index.unique {
Text(localized: "UNIQUE").font(.system(size: 9, weight: .bold))
.foregroundColor(theme.tertiaryText)
}
Spacer()
}
.padding(.leading, 18)
}
}
}
.padding(12)
.background(
RoundedRectangle(cornerRadius: 8).fill(theme.inputBackground)
)
.overlay(
RoundedRectangle(cornerRadius: 8).stroke(theme.inputBorder, lineWidth: 1)
)
.opacity(isSystem ? 0.6 : 1)
}
@ViewBuilder
private func viewCard(_ view: AgentSavedView) -> some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 8) {
Image(systemName: "eye")
.foregroundColor(theme.accentColor)
Text(view.name)
.font(.system(size: 13, weight: .semibold, design: .monospaced))
.foregroundColor(theme.primaryText)
Spacer()
}
if let description = view.description, !description.isEmpty {
Text(description)
.font(.system(size: 11))
.foregroundColor(theme.tertiaryText)
}
Text(view.sql)
.font(.system(size: 10, design: .monospaced))
.foregroundColor(theme.tertiaryText)
.padding(8)
.frame(maxWidth: .infinity, alignment: .leading)
.background(theme.tertiaryBackground)
.cornerRadius(4)
}
.padding(12)
.background(
RoundedRectangle(cornerRadius: 8).fill(theme.inputBackground)
)
.overlay(
RoundedRectangle(cornerRadius: 8).stroke(theme.inputBorder, lineWidth: 1)
)
}
}
// MARK: - Data Tab
/// Soft-delete filter modes for the data grid. The spec calls out
/// "soft-delete view" (§7) — the data grid shows live rows by default
/// and an audit-style read-only view of `_deleted_at IS NOT NULL`
/// rows on demand.
fileprivate enum DataFilterMode: String, CaseIterable, Identifiable {
case live
case deleted
case all
var id: String { rawValue }
/// User-facing label. `.live` reads as "Active" since users
/// don't think of un-deleted rows as "live" — the term came from
/// the soft-delete SQL pattern and was confusing in the UI.
var label: LocalizedStringKey {
switch self {
case .live: return "Active"
case .deleted: return "Deleted"
case .all: return "All"
}
}
/// One-line description shown in the filter help popover.
var helpDescription: LocalizedStringKey {
switch self {
case .live: return "Rows the agent is currently using."
case .deleted: return "Soft-deleted rows the agent can still restore."
case .all: return "Everything in the table, including soft-deleted rows."
}
}
}
/// Browse, inspect, and edit the rows the agent has accumulated. Uses
/// a parameterised `db_query` (via `LocalAgentBridge`) so all reads
/// stay encrypted and audit-visible. Edits flow through
/// `LocalAgentBridge.update` and `softDelete` so the `_changelog`
/// gets stamped correctly and the per-agent serial queue holds the
/// write order.
public struct DataTabView: View {
@Environment(\.theme) private var theme
let agentId: UUID
/// Optional table name to pre-select on first load. Used by the
/// "Browse" deeplink from `SchemaTabView` and by the notification
/// deeplink so the user lands directly on the table they tapped.
/// Honoured once on `task`; afterwards the user's selection
/// drives the dropdown.
let initialSelectedTable: String?
@State private var tables: [AgentTableSchema] = []
@State private var selectedTable: String? = nil
@State private var filterMode: DataFilterMode = .live
@State private var rows: [[AgentSQLValue]] = []
@State private var columns: [AgentColumnInfo] = []
@State private var idColumnIndex: Int? = nil
@State private var totalRowCount: Int = 0
@State private var truncated: Bool = false
@State private var isLoading: Bool = false
@State private var loadError: String? = nil
@State private var editingRow: EditingRow? = nil
@State private var hasAppliedInitialSelection = false
/// Display-string ids (`displayString(for: idValue)`) of every
/// row currently checked in the grid. Driven from the bulk-
/// delete checkbox column on `AgentDataTableRepresentable`; we
/// key on the string because `AgentSQLValue` is `Equatable` but
/// not `Hashable` (it carries `Data` blobs).
@State private var selectedRowIds: Set<String> = []
@State private var showBulkDeleteConfirm: Bool = false
/// Toggles the small `?` popover next to the filter segments
/// that explains what `Active / Deleted / All` mean.
@State private var showFilterHelp: Bool = false
/// First-load tip caption surfaced above the grid. Dismissed
/// once the user clicks the inline `x`. Persisted across
/// sessions so power users don't keep seeing it.
@AppStorage("agentDataTipDismissed") private var dataTipDismissed: Bool = false
public init(agentId: UUID, initialSelectedTable: String? = nil) {
self.agentId = agentId
self.initialSelectedTable = initialSelectedTable
}
public var body: some View {
VStack(alignment: .leading, spacing: 0) {
controlBar
.padding(.horizontal, 16)
.padding(.vertical, 10)
Divider().foregroundColor(theme.primaryBorder)
content
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(theme.primaryBackground)
.task { await loadTables() }
.onChange(of: agentId) { _, _ in
Task { await loadTables() }
}
.onChange(of: selectedTable) { _, _ in
selectedRowIds.removeAll()
Task { await reloadRows() }
}
.onChange(of: filterMode) { _, _ in
selectedRowIds.removeAll()
Task { await reloadRows() }
}
.sheet(item: $editingRow) { row in
RowEditorSheet(
row: row,
onSave: { updates in
Task { await applyUpdate(rowId: row.rowId, updates: updates) }
},
onSoftDelete: {
Task { await applySoftDelete(rowId: row.rowId) }
},
onRestore: {
Task { await applyRestore(rowId: row.rowId) }
},
onCancel: { editingRow = nil }
)
}
}
// MARK: - Controls
@ViewBuilder
private var controlBar: some View {
HStack(spacing: 16) {
controlBarSelectorZone
Spacer()
controlBarActionsZone
}
.confirmationDialog(
"Delete \(selectedRowIds.count) rows?",
isPresented: $showBulkDeleteConfirm,
titleVisibility: .visible
) {
Button(localized: "Soft-Delete \(selectedRowIds.count) Rows", role: .destructive) {
Task { await bulkSoftDelete() }
}
Button(localized: "Cancel", role: .cancel) {}
} message: {
Text(
"These rows will be soft-deleted (their `_deleted_at` "
+ "stamp set), not permanently removed. Switch the "
+ "filter to \"Deleted\" to restore them later."
)
}
}
/// Left side of the toolbar — what the user is LOOKING AT. Holds
/// the table picker and the filter segments (with a help popover
/// explaining what `Active / Deleted / All` mean). Labels use
/// `verbatim:` so they render regardless of the resolved bundle
/// localisation table, and each label-group is `.fixedSize`'d so
/// SwiftUI doesn't squeeze "Show" into a vertical S/h/o/w stack
/// when the action zone competes for horizontal space.
@ViewBuilder
private var controlBarSelectorZone: some View {
HStack(spacing: 14) {
HStack(spacing: 6) {
Text(verbatim: "Table")
.font(.system(size: 11, weight: .semibold))
.foregroundColor(theme.secondaryText)
.fixedSize()
tablePicker
}
.fixedSize(horizontal: true, vertical: false)
HStack(spacing: 6) {
Text(verbatim: "Show")
.font(.system(size: 11, weight: .semibold))
.foregroundColor(theme.secondaryText)
.fixedSize()
Picker("", selection: $filterMode) {
ForEach(DataFilterMode.allCases) { mode in
Text(mode.label, bundle: .module).tag(mode)
}
}
.pickerStyle(.segmented)
.fixedSize()
.labelsHidden()
filterHelpButton
}
.fixedSize(horizontal: true, vertical: false)
}
}
/// Right side of the toolbar — STATUS + ACTIONS. Storage / mutation
/// status sit closest to the spacer; bulk delete + truncated +
/// export are the verbs the user invokes.
@ViewBuilder
private var controlBarActionsZone: some View {
HStack(spacing: 10) {
StorageQuotaBadge(agentId: agentId, theme: theme)
MutationsInFlightIndicator(agentId: agentId, theme: theme)
if !selectedRowIds.isEmpty {
Button(role: .destructive) {
showBulkDeleteConfirm = true
} label: {
Label(localized: "Delete \(selectedRowIds.count)", systemImage: "trash")
.font(.system(size: 11, weight: .medium))
}
.buttonStyle(.bordered)
.controlSize(.small)
.tint(.red)
}
if truncated {
Label(localized: "Truncated", systemImage: "scissors")
.font(.system(size: 11))
.foregroundColor(theme.tertiaryText)
.localizedHelp("The result was capped at 500 rows.")
}
Button {
exportCSV()
} label: {
Label(localized: "Export CSV", systemImage: "square.and.arrow.up")
.font(.system(size: 11, weight: .medium))
}
.buttonStyle(.bordered)
.controlSize(.small)
.disabled(rows.isEmpty)
}
}
/// `?` button next to the filter picker. Opens a small popover
/// listing the meaning of each filter mode — without it,
/// "Active / Deleted / All" is opaque to first-time users.
@ViewBuilder
private var filterHelpButton: some View {
Button {
showFilterHelp.toggle()
} label: {
Image(systemName: "questionmark.circle")
.font(.system(size: 12))
.foregroundColor(theme.tertiaryText)
}
.buttonStyle(.plain)
.localizedHelp("What do these filters mean?")
.popover(isPresented: $showFilterHelp, arrowEdge: .bottom) {
VStack(alignment: .leading, spacing: 10) {
Text(localized: "Filters")
.font(.system(size: 12, weight: .semibold))
.foregroundColor(theme.primaryText)
ForEach(DataFilterMode.allCases) { mode in
VStack(alignment: .leading, spacing: 2) {
Text(mode.label, bundle: .module)
.font(.system(size: 11, weight: .semibold))
.foregroundColor(theme.primaryText)
Text(mode.helpDescription, bundle: .module)
.font(.system(size: 11))
.foregroundColor(theme.secondaryText)
.fixedSize(horizontal: false, vertical: true)
}
}
}
.padding(14)
.frame(width: 260)
}
}
@ViewBuilder
private var tablePicker: some View {
Picker(
"",
selection: Binding(
get: { selectedTable ?? "" },
set: { selectedTable = $0.isEmpty ? nil : $0 }
)
) {
if tables.isEmpty {
Text(localized: "No tables").tag("")
} else {
ForEach(userVisibleTables, id: \.name) { table in
Text(table.name).tag(table.name)
}
}
}
.pickerStyle(.menu)
.labelsHidden()
.frame(minWidth: 140, idealWidth: 180, maxWidth: 240)
}
private var userVisibleTables: [AgentTableSchema] {
tables.filter { !$0.name.hasPrefix("_") }
}
// MARK: - Body Content
@ViewBuilder
private var content: some View {
if let error = loadError {
VStack(alignment: .leading, spacing: 6) {
Label(localized: "Couldn't load rows", systemImage: "exclamationmark.triangle")
.font(.system(size: 13, weight: .semibold))
.foregroundColor(.red)
Text(error)
.font(.system(size: 11, design: .monospaced))
.foregroundColor(theme.tertiaryText)
}
.padding(24)
} else if userVisibleTables.isEmpty {
noTablesEmptyState
} else if selectedTable == nil {
noTableSelectedEmptyState
} else if isLoading {
HStack {
ProgressView()
Text("Loading rows…", bundle: .module)
.font(.system(size: 12))
.foregroundColor(theme.tertiaryText)
}
.padding(24)
} else if rows.isEmpty {
noRowsEmptyState
} else {
VStack(alignment: .leading, spacing: 0) {
if !dataTipDismissed {
dataTipCaption
}
grid
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
}
/// Structured "no tables yet" onboarding card. Replaces the flat
/// `empty(message:)` for the case where the agent hasn't called
/// `db_create_table` yet — surfaces what's expected and gives a
/// one-click path into the Schema tab so users have somewhere to
/// go besides "wait."
@ViewBuilder
private var noTablesEmptyState: some View {
DataEmptyState(
systemImage: "tablecells.badge.ellipsis",
title: "This agent has no memory tables yet.",
subtitle:
"Ask the agent in chat to remember something — it will call `db_create_table` to build the schema it needs. You can browse what it creates here.",
actionTitle: "Open Schema tab",
actionSystemImage: "tablecells",
action: { openSchemaTab() },
theme: theme
)
}
/// Shown when there ARE user-visible tables but none picked yet.
/// Less aggressive than the "no tables" state — the user just
/// needs a nudge toward the dropdown.
@ViewBuilder
private var noTableSelectedEmptyState: some View {
DataEmptyState(
systemImage: "arrow.up.left",
title: "Pick a table to see its rows.",
subtitle: "Use the Table dropdown above to choose which of this agent's tables you want to browse.",
actionTitle: nil,
actionSystemImage: nil,
action: nil,
theme: theme
)
}
/// Shown when the selected table exists but the current filter
/// returns nothing. Copy varies with the filter so the user knows
/// whether to switch to a different filter or wait for the agent.
@ViewBuilder
private var noRowsEmptyState: some View {
let tableLabel = selectedTable ?? "this table"
switch filterMode {
case .deleted:
DataEmptyState(
systemImage: "trash.slash",
title: "No deleted rows in `\(tableLabel)`.",
subtitle: "Soft-deleted rows the agent could restore would appear here.",
actionTitle: nil,
actionSystemImage: nil,
action: nil,
theme: theme
)
case .live, .all:
DataEmptyState(
systemImage: "tray",
title: "No rows in `\(tableLabel)`.",
subtitle:
"The agent adds rows with `db_insert` / `db_upsert` when it has something to remember. You can also ask it directly in chat.",
actionTitle: nil,
actionSystemImage: nil,
action: nil,
theme: theme
)
}
}
/// One-line dismissable caption that teaches the affordances on
/// the grid (Open button, checkbox selection, dimmed soft-deleted
/// rows). Hidden permanently once the user dismisses it; the flag
/// lives in `@AppStorage` so power users don't keep seeing it.
@ViewBuilder
private var dataTipCaption: some View {
HStack(spacing: 8) {
Image(systemName: "lightbulb")
.font(.system(size: 10))
.foregroundColor(theme.tertiaryText)
Text(
"Click ↗ on a row to open it · check rows for bulk delete · soft-deleted rows are dimmed.",
bundle: .module
)
.font(.system(size: 11))
.foregroundColor(theme.tertiaryText)
Spacer(minLength: 0)
Button {
dataTipDismissed = true
} label: {
Image(systemName: "xmark")
.font(.system(size: 9, weight: .semibold))
.foregroundColor(theme.tertiaryText)
}
.buttonStyle(.plain)
.localizedHelp("Hide this tip")
}
.padding(.horizontal, 16)
.padding(.vertical, 6)
.background(theme.secondaryBackground.opacity(0.5))
}
/// Posts the standard `.agentDetailDeeplink` notification to flip
/// the parent `AgentDetailView` to the Schema tab. Reuses the same
/// channel that `SchemaTabView`'s `Browse` button uses, in the
/// opposite direction.
private func openSchemaTab() {
NotificationCenter.default.post(
name: .agentDetailDeeplink,
object: nil,
userInfo: [
"agentId": agentId,
"tab": "schema",
]
)
}
@ViewBuilder
private var grid: some View {
AgentDataTableRepresentable(
columns: columns,
rows: rows,
idColumnIndex: idColumnIndex,
deletedColumnIndex: deletedColumnIndex,
// Only reserve a leading status column when soft-deleted
// rows can actually appear in the current filter — keeps the
// default Active view from showing a permanently-empty
// 76px column that looks broken.
showsStatusColumn: filterMode != .live && deletedColumnIndex != nil,
selectedRowIds: $selectedRowIds,
theme: theme,
onRowOpen: { rowIndex in
openEditor(for: rowIndex)
}
)
}
/// Column index of `_deleted_at` if present — used by the grid
/// to dim soft-deleted rows in `.all` filter mode.
private var deletedColumnIndex: Int? {
columns.firstIndex(where: { $0.name == "_deleted_at" })
}
// MARK: - Loading
@MainActor
private func loadTables() async {
loadError = nil
do {
let snapshot = try LocalAgentBridge.shared.schema(agentId: agentId)
tables = snapshot.tables
if !hasAppliedInitialSelection,
let pin = initialSelectedTable,
userVisibleTables.contains(where: { $0.name == pin })
{
hasAppliedInitialSelection = true
selectedTable = pin
} else if let current = selectedTable,
userVisibleTables.contains(where: { $0.name == current })
{
// Keep current.
} else {
selectedTable = userVisibleTables.first?.name
}
await reloadRows()
} catch {
loadError = error.localizedDescription
}
}
@MainActor
private func reloadRows() async {
guard let tableName = selectedTable,
let table = tables.first(where: { $0.name == tableName })
else {
rows = []
columns = []
idColumnIndex = nil
return
}
isLoading = true
defer { isLoading = false }
loadError = nil
let whereSQL: String = {
switch filterMode {
case .live: return "WHERE _deleted_at IS NULL"
case .deleted: return "WHERE _deleted_at IS NOT NULL"
case .all: return ""
}
}()
let sql =
"SELECT * FROM \"\(tableName)\" \(whereSQL) "
+ "ORDER BY _updated_at DESC LIMIT 500"
do {
let result = try LocalAgentBridge.shared.query(
agentId: agentId,
sql: sql,
params: []
)
columns = table.columns
rows = result.rows
truncated = result.truncated
totalRowCount = result.rows.count
idColumnIndex = result.columns.firstIndex(of: "id")
} catch {
loadError = error.localizedDescription
rows = []
columns = []
idColumnIndex = nil
}
}
// MARK: - Edit
private func openEditor(for rowIndex: Int) {
guard rowIndex >= 0, rowIndex < rows.count else { return }
let row = rows[rowIndex]
guard let idIdx = idColumnIndex, idIdx < row.count else { return }
// The default `id` column is `INTEGER PRIMARY KEY AUTOINCREMENT`,
// but agents can declare their own TEXT/INTEGER PKs, so we
// round-trip the value through `AgentSQLValue` rather than
// committing to one type at this layer.
editingRow = EditingRow(
rowId: row[idIdx],
tableName: selectedTable ?? "",
columns: columns,
values: row,
isDeleted: filterMode == .deleted
|| rowValue(row, forColumnNamed: "_deleted_at").isNotNull
)
}
@MainActor
private func applyUpdate(rowId: AgentSQLValue, updates: [String: AgentSQLValue]) async {
guard let table = selectedTable else { return }
// Stamp _changelog with `actor=user` for UI-driven writes
// (spec §6). `LocalAgentBridge.currentActor()` falls back to
// `agent` when the task-local is `nil`, which would mislabel
// every inline edit. Binding here keeps the read path on the
// serial queue inside the bridge intact — matches the pattern
// `BackgroundTaskManager.dispatchChat` uses for `agent` stamping.
do {
_ = try ChatExecutionContext.$currentRunActor.withValue("user") {
try LocalAgentBridge.shared.update(
agentId: agentId,
table: table,
set: updates,
whereClause: ["id": rowId],
includeDeleted: filterMode != .live
)
}
editingRow = nil
await reloadRows()
} catch {
loadError = error.localizedDescription
}
}
@MainActor
private func applySoftDelete(rowId: AgentSQLValue) async {
guard let table = selectedTable else { return }
do {
_ = try ChatExecutionContext.$currentRunActor.withValue("user") {
try LocalAgentBridge.shared.softDelete(
agentId: agentId,
table: table,
whereClause: ["id": rowId]
)
}
editingRow = nil
await reloadRows()
} catch {
loadError = error.localizedDescription
}
}
/// Soft-delete every row currently checked in the grid, in one
/// `actor=user` task-local scope so the audit trail shows the
/// edit came from the UI. Clears the selection on success.
@MainActor
private func bulkSoftDelete() async {
guard let table = selectedTable else { return }
guard let idIdx = idColumnIndex else { return }
// Map the display-string selection back to the matching row's
// PK value. Doing the lookup once up-front means even if
// `reloadRows()` mutates the row order mid-loop, we still
// delete the right things.
let targets: [AgentSQLValue] = rows.compactMap { row in
guard idIdx < row.count else { return nil }
let value = row[idIdx]
return selectedRowIds.contains(displayString(for: value)) ? value : nil
}
guard !targets.isEmpty else {
selectedRowIds.removeAll()
return
}
do {
try ChatExecutionContext.$currentRunActor.withValue("user") {
for rowId in targets {
_ = try LocalAgentBridge.shared.softDelete(
agentId: agentId,
table: table,
whereClause: ["id": rowId]
)
}
}
selectedRowIds.removeAll()
await reloadRows()
} catch {
loadError = error.localizedDescription
}
}
@MainActor
private func applyRestore(rowId: AgentSQLValue) async {
guard let table = selectedTable else { return }
do {
_ = try ChatExecutionContext.$currentRunActor.withValue("user") {
try LocalAgentBridge.shared.restore(
agentId: agentId,
table: table,
whereClause: ["id": rowId]
)
}
editingRow = nil
await reloadRows()
} catch {
loadError = error.localizedDescription
}
}
private func rowValue(_ row: [AgentSQLValue], forColumnNamed name: String) -> AgentSQLValue {
guard let idx = columns.firstIndex(where: { $0.name == name }), idx < row.count
else { return .null }
return row[idx]
}
// MARK: - CSV Export
private func exportCSV() {
guard !rows.isEmpty else { return }
let panel = NSSavePanel()
panel.allowedContentTypes = [.commaSeparatedText]
panel.nameFieldStringValue = "\(selectedTable ?? "rows").csv"
Task { @MainActor in
guard await panel.beginModal() == .OK, let url = panel.url else { return }
let csv = renderCSV(columns: columns.map(\.name), rows: rows)
do {
try csv.write(to: url, atomically: true, encoding: .utf8)
} catch {
loadError = "CSV write failed: \(error.localizedDescription)"
}
}
}
private func renderCSV(columns: [String], rows: [[AgentSQLValue]]) -> String {
var lines: [String] = []
lines.append(columns.map(csvEscape).joined(separator: ","))
for row in rows {
let cells = row.map { csvEscape(displayString(for: $0)) }
lines.append(cells.joined(separator: ","))
}
return lines.joined(separator: "\n") + "\n"
}
private func csvEscape(_ value: String) -> String {
if value.contains(",") || value.contains("\"") || value.contains("\n") {
let escaped = value.replacingOccurrences(of: "\"", with: "\"\"")
return "\"\(escaped)\""
}
return value
}
}
// MARK: - Editing Row
fileprivate struct EditingRow: Identifiable {
/// Stable display-form id so SwiftUI's `sheet(item:)` machinery
/// can drive presentation. The actual PK lives in `rowId` and
/// is the value we pass back to `LocalAgentBridge.update /
/// softDelete / restore`.
var id: String { displayString(for: rowId) }
let rowId: AgentSQLValue
let tableName: String
let columns: [AgentColumnInfo]
let values: [AgentSQLValue]
let isDeleted: Bool
}
// MARK: - Row Editor Sheet
fileprivate struct RowEditorSheet: View {
@Environment(\.theme) private var theme