forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatProvider.swift
More file actions
7331 lines (6814 loc) · 289 KB
/
Copy pathChatProvider.swift
File metadata and controls
7331 lines (6814 loc) · 289 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
import Combine
import CoreGraphics
import CryptoKit
@preconcurrency import GRDB
import OmiSupport
import SwiftUI
import UniformTypeIdentifiers
/// Boxes a value so it can cross a `@Sendable` boundary without itself
/// conforming to `Sendable`. Safe here because the captured JSON payloads are
/// read straight through and never mutated after boxing.
private struct ChatProviderSendableBox<Value>: @unchecked Sendable {
let value: Value
}
/// Mutable timing/usage accumulator shared between a turn's @Sendable tool
/// callbacks and the @MainActor turn body. All access is funneled through the
/// MainActor (callbacks run via ChatTurnCallbackQueue), matching the existing
/// responseMetrics/pendingToolTraceInputs accumulators, so unchecked Sendable
/// conformance is safe.
private final class ChatToolTimingState: @unchecked Sendable {
var toolNames: [String] = []
var toolStartTimes: [String: Date] = [:]
}
struct ChatLegacyCompatibilityMetadata: Equatable {
static let owner = "desktop-main-chat"
static let removalCondition =
"all supported desktop versions have checkpointed backend chat history into the kernel journal"
static let removeBy = "2026-10-01"
static let pageSize = 100
}
enum ChatLegacyPageCollector {
static func all<Element>(
fetchPage: @Sendable (_ limit: Int, _ offset: Int) async throws -> [Element]
) async throws -> [Element] {
var rows: [Element] = []
var offset = 0
while true {
let page = try await fetchPage(ChatLegacyCompatibilityMetadata.pageSize, offset)
rows.append(contentsOf: page)
offset += page.count
if page.count < ChatLegacyCompatibilityMetadata.pageSize { return rows }
}
}
}
enum ChatLegacyImportChronology {
struct Entry<Row> {
let row: Row
let createdAtMs: Int
}
/// Converts a backend page into a strict immutable chronology before the
/// rows cross the one-at-a-time runtime import protocol.
static func plan<Row>(
_ rows: [Row],
createdAt: (Row) -> Date,
role: (Row) -> String
) -> [Entry<Row>] {
let ordered = rows.enumerated().sorted { lhs, rhs in
let lhsDate = createdAt(lhs.element)
let rhsDate = createdAt(rhs.element)
if lhsDate != rhsDate { return lhsDate < rhsDate }
let lhsRank = role(lhs.element) == "human" ? 0 : 1
let rhsRank = role(rhs.element) == "human" ? 0 : 1
if lhsRank != rhsRank { return lhsRank < rhsRank }
return lhs.offset < rhs.offset
}
var previousCreatedAtMs: Int?
return ordered.map { item in
let raw = Int(createdAt(item.element).timeIntervalSince1970 * 1_000)
let normalized = max(raw, (previousCreatedAtMs ?? (raw - 1)) + 1)
previousCreatedAtMs = normalized
return Entry(row: item.element, createdAtMs: normalized)
}
}
}
struct ChatRunAccountingPolicy: Equatable {
let usesOmiAccountQuota: Bool
let recordsPersonalProviderUsage: Bool
init(pinnedAdapterID: String) {
usesOmiAccountQuota = pinnedAdapterID == AgentAdapterId.piMono.rawValue
recordsPersonalProviderUsage = pinnedAdapterID == AgentAdapterId.acp.rawValue
}
}
struct OwnerIsolationKernelProbeReceipt: Equatable {
let ownerID: String
let conversationID: String
let sessionID: String
let turns: [KernelJournalTurn]
}
/// Non-production owner-isolation probes need kernel ownership evidence even
/// when their synthetic owner intentionally has no Firebase credential. This
/// seam admits only an owner handshake, one canonical surface mapping, and one
/// journal exchange; it never opens a managed-model execution lane.
@MainActor
enum OwnerIsolationKernelProbe {
static func run(
ownerID: String,
query: String,
response: String,
registerControlOnlyRuntime: @MainActor () async throws -> Void,
synchronizeOwner: @MainActor () async -> Bool,
resolveSurface: @MainActor () async throws -> (conversationID: String, sessionID: String),
recordExchange: @MainActor ([KernelJournalTurnWrite]) async throws -> [KernelJournalTurn]
) async throws -> OwnerIsolationKernelProbeReceipt {
try await registerControlOnlyRuntime()
guard await synchronizeOwner() else { throw BridgeError.authMissing }
let surface = try await resolveSurface()
let now = Int(Date().timeIntervalSince1970 * 1000)
let continuityID = UUID().uuidString
let turns = [
KernelJournalTurnWrite(
turnId: continuityID,
role: "user",
origin: "typed_chat",
status: .completed,
content: query,
contentBlocksJSON: "[]",
resourcesJSON: "[]",
metadataJSON: #"{"harness":"owner_isolation_probe"}"#,
createdAtMs: now
),
KernelJournalTurnWrite(
turnId: "\(continuityID)-assistant",
role: "assistant",
origin: "typed_chat",
status: .completed,
content: response,
contentBlocksJSON: "[]",
resourcesJSON: "[]",
metadataJSON: #"{"harness":"owner_isolation_probe"}"#,
createdAtMs: now
),
]
let recorded = try await recordExchange(turns)
return OwnerIsolationKernelProbeReceipt(
ownerID: ownerID,
conversationID: surface.conversationID,
sessionID: surface.sessionID,
turns: recorded
)
}
}
private struct ChatJournalTerminalTarget {
let surface: AgentSurfaceReference
let assistantMessageId: String
let ownerID: String
let onFinalized: (@MainActor (Bool) -> Void)?
}
// MARK: - UserDefaults Extension for KVO
extension UserDefaults {
@objc dynamic var multiChatEnabled: Bool {
return bool(forKey: "multiChatEnabled")
}
@objc dynamic var playwrightUseExtension: Bool {
return bool(forKey: "playwrightUseExtension")
}
}
// MARK: - Chat Session Model
/// A chat session that groups related messages
struct ChatSession: Identifiable, Codable, Equatable {
let id: String
var title: String
var preview: String?
let createdAt: Date
var updatedAt: Date
let appId: String?
var messageCount: Int
var starred: Bool
enum CodingKeys: String, CodingKey {
case id, title, preview, starred
case createdAt = "created_at"
case updatedAt = "updated_at"
case appId = "app_id"
case messageCount = "message_count"
}
init(
id: String = UUID().uuidString, title: String = "New Chat", preview: String? = nil,
createdAt: Date = Date(), updatedAt: Date = Date(), appId: String? = nil,
messageCount: Int = 0, starred: Bool = false
) {
self.id = id
self.title = title
self.preview = preview
self.createdAt = createdAt
self.updatedAt = updatedAt
self.appId = appId
self.messageCount = messageCount
self.starred = starred
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
title = try container.decodeIfPresent(String.self, forKey: .title) ?? "New Chat"
preview = try container.decodeIfPresent(String.self, forKey: .preview)
createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) ?? Date()
updatedAt = try container.decodeIfPresent(Date.self, forKey: .updatedAt) ?? Date()
appId = try container.decodeIfPresent(String.self, forKey: .appId)
messageCount = try container.decodeIfPresent(Int.self, forKey: .messageCount) ?? 0
starred = try container.decodeIfPresent(Bool.self, forKey: .starred) ?? false
}
}
// MARK: - Content Block Model
/// Structured tool input for inline display
struct ToolCallInput: Equatable {
/// Short summary for inline display (e.g., file path, command)
let summary: String
/// Full JSON details for expanded view
let details: String?
}
/// A block of content within an AI message (text or tool call indicator)
/// Stable identity for opening a background agent from the chat timeline.
/// Prefer `sessionId` / `runId` for kernel hydrate; `pillId` is the UI cache key.
struct AgentTimelineRef: Equatable {
var pillId: UUID?
var sessionId: String?
var runId: String?
var hasIdentity: Bool {
pillId != nil
|| !(sessionId?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true)
|| !(runId?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true)
}
/// Kernel lookup prefers run, then session, then pill externalRefId.
var hydratePreference: AgentTimelineHydratePreference {
AgentTimelineHydratePreference.make(pillId: pillId, sessionId: sessionId, runId: runId)
}
}
/// Pure ordering for open-by-id hydrate (unit-testable without kernel I/O).
struct AgentTimelineHydratePreference: Equatable {
enum Key: Equatable {
case runId(String)
case sessionId(String)
case pillId(UUID)
}
let keys: [Key]
static func make(pillId: UUID?, sessionId: String?, runId: String?) -> AgentTimelineHydratePreference {
var keys: [Key] = []
if let runId = sessionIdOrNil(runId) {
keys.append(.runId(runId))
}
if let sessionId = sessionIdOrNil(sessionId) {
keys.append(.sessionId(sessionId))
}
if let pillId {
keys.append(.pillId(pillId))
}
return AgentTimelineHydratePreference(keys: keys)
}
/// First preference key that matches the provided lookups (run → session → pill).
func firstMatchingKey(
runIdMatches: (String) -> Bool,
sessionIdMatches: (String) -> Bool,
pillIdMatches: (UUID) -> Bool
) -> Key? {
for key in keys {
switch key {
case .runId(let runId) where runIdMatches(runId):
return key
case .sessionId(let sessionId) where sessionIdMatches(sessionId):
return key
case .pillId(let pillId) where pillIdMatches(pillId):
return key
default:
continue
}
}
return nil
}
private static func sessionIdOrNil(_ value: String?) -> String? {
guard let value else { return nil }
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
}
/// Applies timeline open result to card unavailable UI (unit-testable).
enum AgentTimelineOpenFeedback {
/// Returns whether the card should show the unavailable message after an open attempt.
static func shouldShowUnavailable(succeeded: Bool) -> Bool {
!succeeded
}
/// Link-out opens a resolvable agent; hide it when open failed / unavailable / no callback / no id.
static func shouldShowLinkOut(
hasResolvableAgent: Bool,
hasOpenAction: Bool,
showUnavailable: Bool
) -> Bool {
hasResolvableAgent && hasOpenAction && !showUnavailable
}
}
struct ConversationLinkActionItem: Equatable {
let description: String
let taskID: String?
}
enum ChatContentBlock: Identifiable {
case text(id: String, text: String)
case toolCall(
id: String, name: String, status: ToolCallStatus,
toolUseId: String? = nil,
input: ToolCallInput? = nil,
output: String? = nil)
case thinking(id: String, text: String)
/// Collapsible card showing a summary with expandable full text (used for AI profile/discovery)
case discoveryCard(id: String, title: String, summary: String, fullText: String)
case questionCard(
id: String,
questionId: String,
text: String,
subjectKind: String,
subjectId: String,
options: [[String: Any]],
selectedOptionId: String? = nil
)
case taskCard(id: String, taskId: String)
case goalLink(id: String, goalId: String, summary: String)
case captureLink(id: String, conversationId: String, momentTimestampMs: Int?, summary: String)
case conversationLink(
id: String,
conversationId: String,
summary: String,
recommendedActionItems: [ConversationLinkActionItem]
)
case memoryLink(id: String, memoryId: String, summary: String)
/// The memories one day actually produced, each row correctable in place.
/// Review state is deliberately absent: it is read live from the memory, so a vote on the phone
/// shows on the Mac and the block never becomes a second copy of the verdict.
case memoryReviewCard(id: String, summaryId: String, date: String, items: [MemoryReviewItem])
/// Answer-level provenance. Unlike a rich link card, this is rendered at the matching inline
/// numeric marker and is otherwise invisible in the transcript.
case citation(id: String, reference: ChatCitationReference)
/// One grounded next question, rendered as a tappable chip under the answer.
/// Tapping it sends the question as a new user turn in the same lane.
case followUp(id: String, text: String)
case agentSpawn(
id: String,
pillId: UUID?,
sessionId: String,
runId: String,
title: String,
objective: String,
provider: AgentHarnessMode? = nil
)
case agentCompletion(
id: String,
pillId: UUID?,
sessionId: String?,
runId: String?,
title: String,
promptSnippet: String,
output: String,
status: String
)
var id: String {
switch self {
case .text(let id, _): return id
case .toolCall(let id, _, _, _, _, _): return id
case .thinking(let id, _): return id
case .discoveryCard(let id, _, _, _): return id
case .questionCard(let id, _, _, _, _, _, _): return id
case .taskCard(let id, _): return id
case .goalLink(let id, _, _): return id
case .captureLink(let id, _, _, _): return id
case .conversationLink(let id, _, _, _): return id
case .memoryLink(let id, _, _): return id
case .memoryReviewCard(let id, _, _, _): return id
case .citation(let id, _): return id
case .followUp(let id, _): return id
case .agentSpawn(let id, _, _, _, _, _, _): return id
case .agentCompletion(let id, _, _, _, _, _, _, _): return id
}
}
var agentTimelineRef: AgentTimelineRef? {
switch self {
case .agentSpawn(_, let pillId, let sessionId, let runId, _, _, _):
return AgentTimelineRef(pillId: pillId, sessionId: sessionId, runId: runId)
case .agentCompletion(_, let pillId, let sessionId, let runId, _, _, _, _):
return AgentTimelineRef(pillId: pillId, sessionId: sessionId, runId: runId)
default:
return nil
}
}
/// Human-friendly display name for a tool
static func displayName(for toolName: String) -> String {
// Strip MCP prefix (e.g., "mcp__omi-tools__execute_sql" → "execute_sql")
let cleanName: String
if toolName.hasPrefix("mcp__") {
cleanName = String(toolName.split(separator: "__").last ?? Substring(toolName))
} else {
cleanName = toolName
}
// Handle tool names with embedded details (e.g. "WebSearch: \"query\"")
if cleanName.hasPrefix("WebSearch:") {
let query = String(cleanName.dropFirst("WebSearch: ".count))
.trimmingCharacters(in: CharacterSet(charactersIn: "\""))
return query.isEmpty ? "Searching the web" : "Searching: \(query)"
}
if cleanName.hasPrefix("WebFetch:") {
return "Fetching page"
}
if cleanName.lowercased().hasPrefix("read:") {
return "Reading file"
}
if cleanName.lowercased().hasPrefix("write:") {
return "Writing file"
}
if cleanName.lowercased().hasPrefix("edit:") {
return "Editing file"
}
if cleanName.lowercased().hasPrefix("bash:") {
return "Running command"
}
switch cleanName {
case "execute_sql": return "Querying database"
case "semantic_search": return "Searching conversations"
case "spawn_agent": return "Starting agent"
case "run_agent_and_wait": return "Running agent"
case "search_tasks": return "Searching tasks"
case "Read": return "Reading file"
case "Write": return "Writing file"
case "Edit": return "Editing file"
case "Bash": return "Running command"
case "Grep": return "Searching code"
case "Glob": return "Finding files"
case "WebSearch": return "Searching the web"
case "WebFetch": return "Fetching page"
default: return "Using \(cleanName)"
}
}
/// Tools whose runs are legitimately long — shell commands, file
/// generation/edits, web fetches, database queries, and delegated
/// agents. The stall banner ("This is taking longer than usual") is
/// suppressed for these so normal long work doesn't read as stuck.
static func isSlowExpectedTool(_ toolName: String) -> Bool {
let cleaned: String
if toolName.hasPrefix("mcp__") {
cleaned = String(toolName.split(separator: "__").last ?? Substring(toolName))
} else {
cleaned = toolName
}
// Any MCP tool is an out-of-process call we don't time-bound.
if toolName.hasPrefix("mcp__") { return true }
let lower = cleaned.lowercased()
let slowPrefixes = ["bash", "write", "edit", "multiedit", "webfetch", "websearch", "task", "notebookedit"]
if slowPrefixes.contains(where: { lower.hasPrefix($0) }) { return true }
let slowExact: Set<String> = [
"execute_sql", "semantic_search", "spawn_agent",
"search_tasks", "run_attempt", "run_agent_and_wait", "send_agent_message",
]
// Strip any embedded summary suffix ("Bash: cmd" style) before matching.
let head = lower.split(separator: ":").first.map(String.init) ?? lower
return slowExact.contains(head.trimmingCharacters(in: .whitespaces))
}
/// Extracts a short summary from tool input for inline display
static func toolInputSummary(for toolName: String, input: [String: Any]) -> ToolCallInput? {
let cleanName: String
if toolName.hasPrefix("mcp__") {
cleanName = String(toolName.split(separator: "__").last ?? Substring(toolName))
} else {
cleanName = toolName
}
let summary: String?
switch cleanName {
case "Read":
summary = input["file_path"] as? String
case "Write", "Edit":
summary = input["file_path"] as? String
case "Bash":
if let cmd = input["command"] as? String {
summary = cmd.count > 80 ? String(cmd.prefix(80)) + "…" : cmd
} else {
summary = nil
}
case "Grep":
let pattern = input["pattern"] as? String ?? ""
let path = input["path"] as? String
summary = path != nil ? "\(pattern) in \(path!)" : pattern
case "Glob":
summary = input["pattern"] as? String
case "WebSearch":
summary = input["query"] as? String
case "WebFetch":
summary = input["url"] as? String
case "execute_sql":
if let query = input["query"] as? String {
summary = query.count > 100 ? String(query.prefix(100)) + "…" : query
} else {
summary = nil
}
case "semantic_search":
summary = input["query"] as? String
case "spawn_agent":
summary = (input["objective"] ?? input["brief"] ?? input["query"]) as? String
case "run_agent_and_wait":
summary = input["objective"] as? String
case "search_tasks":
summary = input["query"] as? String
case "request_permission":
summary = input["type"] as? String
case "ask_followup":
summary = input["question"] as? String
default:
// Try common key names
summary = (input["file_path"] ?? input["path"] ?? input["query"] ?? input["command"]) as? String
}
guard let summary = summary, !summary.isEmpty else { return nil }
// Build full details JSON
let details: String?
if let data = try? JSONSerialization.data(withJSONObject: input, options: [.prettyPrinted, .sortedKeys]),
let str = String(data: data, encoding: .utf8)
{
details = str
} else {
details = nil
}
return ToolCallInput(summary: summary, details: details)
}
}
enum ToolCallStatus: CaseIterable {
case running
/// Promoted by `StallDetector` after the per-tool / inter-event
/// timer crosses `StallThresholds.slowGapMs`. Still in flight.
case slow
/// Promoted after `StallThresholds.stalledGapMs`. Still in flight,
/// but eligible for the message-level Cancel banner.
case stalled
case completed
/// Terminal failure (timeout, interrupt, bridge error).
case failed
/// True for any state where the tool is still working. Pattern
/// matches throughout the UI should use this instead of `== .running`
/// so `.slow` and `.stalled` don't accidentally look complete.
var isInFlight: Bool {
switch self {
case .running, .slow, .stalled:
return true
case .completed, .failed:
return false
}
}
static func fromBridgeStatus(_ status: String) -> ToolCallStatus {
switch status {
case "started", "progress":
return .running
case "failed", "cancelled", "interrupted":
return .failed
default:
return .completed
}
}
}
final class ChatResponseMetrics: @unchecked Sendable {
struct Snapshot {
let sqlRowsReturned: Int
let sqlQueryCount: Int
let screenContext: ScreenContextChatCycleSnapshot
}
private let lock = NSLock()
private var isFirstResponse = true
private var isGenerating = false
private var sqlRowsReturned = 0
private var sqlQueryCount = 0
private let screenContextMetrics = ScreenContextChatCycleMetrics()
func markFirstOutputIfNeeded() -> Bool {
lock.lock()
defer { lock.unlock() }
guard isFirstResponse else { return false }
isFirstResponse = false
return true
}
func markGenerationStartedIfNeeded() -> Bool {
lock.lock()
defer { lock.unlock() }
guard !isGenerating else { return false }
isGenerating = true
return true
}
func recordToolResult(name: String, result: String) {
screenContextMetrics.recordToolResult(name: name, output: result)
guard name == "execute_sql" else { return }
let rowsReturned = Self.sqlRowsReturned(in: result)
lock.lock()
sqlQueryCount += 1
sqlRowsReturned += rowsReturned
lock.unlock()
}
func recordToolRequested(name: String) {
screenContextMetrics.recordToolRequested(name)
}
func snapshot() -> Snapshot {
lock.lock()
defer { lock.unlock() }
return Snapshot(
sqlRowsReturned: sqlRowsReturned,
sqlQueryCount: sqlQueryCount,
screenContext: screenContextMetrics.snapshot()
)
}
private static func sqlRowsReturned(in result: String) -> Int {
guard let match = result.range(of: #"(\d+) row\(s\)"#, options: .regularExpression) else {
return 0
}
let numStr = result[match].components(separatedBy: " ").first ?? "0"
return Int(numStr) ?? 0
}
}
final class ChatToolTraceInputStore: @unchecked Sendable {
struct Entry {
let inputJson: String
let started: ContinuousClock.Instant
}
private let lock = NSLock()
private var entries: [String: Entry] = [:]
func record(id: String, inputJson: String, started: ContinuousClock.Instant = .now) {
lock.lock()
entries[id] = Entry(inputJson: inputJson, started: started)
lock.unlock()
}
func take(id: String) -> Entry? {
lock.lock()
defer { lock.unlock() }
return entries.removeValue(forKey: id)
}
}
// MARK: - Chat Message Model
/// A single chat message
struct ChatMessage: Identifiable {
var id: String // Mutable to sync with server-generated ID
let clientTurnId: String?
var text: String
let createdAt: Date
let sender: ChatSender
var isStreaming: Bool
/// Rating: 1 = thumbs up, -1 = thumbs down, nil = no rating
var rating: Int?
/// Whether the message has been synced with the backend (has valid server ID)
var isSynced: Bool
/// Citations extracted from the AI response
var citations: [Citation]
/// Structured content blocks for AI messages (text interspersed with tool calls)
var contentBlocks: [ChatContentBlock]
/// Metadata about context used to generate this response (AI messages only)
var metadata: MessageMetadata?
/// Context text for proactive notification messages (not shown to user, sent to Claude)
var notificationContext: String?
/// Screenshot JPEG data captured when a proactive notification was generated
var notificationScreenshot: Data?
/// User-attached files (screenshots, images, documents) — populated for user messages.
var attachments: [ChatAttachment]
/// Surface-neutral resources associated with this message. Assistant messages
/// use this for generated artifacts; user messages derive resources from
/// `attachments` for backwards compatibility.
var resources: [ChatResource]
/// Which surface produced this turn. This is only an ownership label for
/// interruption/cancellation policy; chat history is canonical and renders
/// every Omi turn in every full chat timeline.
var turnOwner: ChatTurnOwner?
/// Kernel journal lifecycle when this message was projected from a journal
/// row. Failed turns get a light visual treatment so they don't look completed.
var journalStatus: KernelJournalTurnStatus?
/// A journal-first continuation can reserve its assistant row before the
/// query begins. It stays out of the transcript until real output arrives.
var hidesEmptyStreamingPlaceholder: Bool
init(
id: String = UUID().uuidString, clientTurnId: String? = nil, text: String, createdAt: Date = Date(),
sender: ChatSender, isStreaming: Bool = false, rating: Int? = nil, isSynced: Bool = false,
citations: [Citation] = [], contentBlocks: [ChatContentBlock] = [], metadata: MessageMetadata? = nil,
notificationContext: String? = nil, notificationScreenshot: Data? = nil, attachments: [ChatAttachment] = [],
resources: [ChatResource] = [], turnOwner: ChatTurnOwner? = nil, journalStatus: KernelJournalTurnStatus? = nil,
hidesEmptyStreamingPlaceholder: Bool = false
) {
self.id = id
self.turnOwner = turnOwner
self.clientTurnId = clientTurnId
self.text = text
self.createdAt = createdAt
self.sender = sender
self.isStreaming = isStreaming
self.rating = rating
self.isSynced = isSynced
self.citations = citations
self.contentBlocks = contentBlocks
self.metadata = metadata
self.notificationContext = notificationContext
self.notificationScreenshot = notificationScreenshot
self.attachments = attachments
self.resources = resources
self.journalStatus = journalStatus
self.hidesEmptyStreamingPlaceholder = hidesEmptyStreamingPlaceholder
}
}
/// IDs are the only caller-provided inputs for a suggestion selection. The
/// kernel derives all visible reply content transactionally.
struct ChatQuestionCardSelection: Sendable {
let questionID: String
let optionID: String
}
/// Receipt for resuming an already-admitted question reply after an app crash.
struct ChatQuestionCardContinuation: Sendable {
let continuityKey: String
let preparedAnswer: String
let userTurnID: String
let assistantTurnID: String
init?(continuityKey: String, preparedAnswer: String, userTurnID: String, assistantTurnID: String) {
guard !continuityKey.isEmpty, !preparedAnswer.isEmpty, !userTurnID.isEmpty, !assistantTurnID.isEmpty else {
return nil
}
self.continuityKey = continuityKey
self.preparedAnswer = preparedAnswer
self.userTurnID = userTurnID
self.assistantTurnID = assistantTurnID
}
init?(receipt: AgentRuntimeProcess.QuestionInteractionReply) {
self.init(
continuityKey: receipt.continuityKey,
preparedAnswer: receipt.userTurn.content,
userTurnID: receipt.userTurn.turnId,
assistantTurnID: receipt.assistantTurn.turnId
)
}
static func tailResumeCandidate(from messages: [ChatMessage]) -> ChatQuestionCardContinuation? {
guard let assistant = messages.last,
assistant.sender == .ai,
assistant.isStreaming,
assistant.hidesEmptyStreamingPlaceholder,
assistant.text.isEmpty,
assistant.contentBlocks.isEmpty,
let continuityKey = assistant.clientTurnId,
continuityKey.hasPrefix("qri_"),
messages.count >= 2
else { return nil }
let user = messages[messages.count - 2]
guard user.sender == .user, user.clientTurnId == continuityKey else { return nil }
return ChatQuestionCardContinuation(
continuityKey: continuityKey,
preparedAnswer: user.text,
userTurnID: user.id,
assistantTurnID: assistant.id
)
}
}
extension ChatMessage {
/// User-visible answer, excluding pre-tool commentary the model streamed before tools.
var visibleAnswerText: String {
ChatAssistantAnswerText.visible(
contentBlocks: contentBlocks,
fallback: text,
isStreaming: isStreaming
)
}
var copyableText: String {
visibleAnswerText
}
/// `!copyableText.isEmpty` without deriving the text.
var hasCopyableText: Bool {
ChatAssistantAnswerText.hasVisible(
contentBlocks: contentBlocks,
fallback: text,
isStreaming: isStreaming
)
}
var displayResources: [ChatResource] {
if !resources.isEmpty {
return resources
}
return attachments.map(ChatResource.attachment)
}
}
extension ChatContentBlock {
var copyableText: String? {
switch self {
case .text(_, let text):
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
case .thinking(_, let text):
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : "Thinking:\n\(trimmed)"
case .discoveryCard(_, let title, _, let fullText):
let trimmed = fullText.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? title : "\(title)\n\(trimmed)"
case .questionCard(_, _, let text, _, _, _, _):
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
case .taskCard:
return nil
case .goalLink(_, _, let summary), .captureLink(_, _, _, let summary),
.conversationLink(_, _, let summary, _), .memoryLink(_, _, let summary):
let trimmed = summary.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
case .citation:
return nil
// A copied answer is what Omi said, not the control offering the next turn.
case .followUp:
return nil
// Same rule for the review card: it is three controls over memories that already exist, not
// prose the reader would expect to find in a copied answer.
case .memoryReviewCard:
return nil
case .agentSpawn(_, _, _, _, let title, let objective, _):
let trimmed = objective.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? title : "\(title)\n\(trimmed)"
case .agentCompletion(_, _, _, _, let title, let promptSnippet, let output, _):
let body = [promptSnippet, output]
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
.joined(separator: "\n")
return body.isEmpty ? title : "\(title)\n\(body)"
case .toolCall:
return nil
}
}
}
enum ChatSender: Equatable {
case user
case ai
}
enum ChatTurnOwner: Equatable {
case mainChat
case floatingDefault
case floatingVoice
case taskChat(String)
case agentPill(UUID)
/// Per-turn reasoning-effort lane relayed to the desktop gateway.
/// Typed chat runs "adaptive": the model decides how much to think per
/// question (including explicit "think properly / take 5 minutes" asks).
/// PTT/voice runs "fast": thinking off, low effort, latency-optimized.
/// Background surfaces (task chat, agent pills) keep the legacy behavior.
var reasoningEffort: String? {
switch self {
case .floatingVoice: return "fast"
case .mainChat, .floatingDefault: return "adaptive"
case .taskChat, .agentPill: return nil
}
}
func canInterrupt(_ activeOwner: ChatTurnOwner) -> Bool {
switch (self, activeOwner) {
case (.floatingDefault, .floatingDefault),
(.floatingDefault, .floatingVoice),
(.floatingVoice, .floatingDefault),
(.floatingVoice, .floatingVoice):
return true
case (.taskChat(let lhs), .taskChat(let rhs)):
return lhs == rhs
case (.agentPill(let lhs), .agentPill(let rhs)):
return lhs == rhs
default:
return self == activeOwner
}
}
}
extension ChatMessage {
/// Convert a backend message to a local ChatMessage
init(from db: ChatMessageDB) {
let resources = ChatResource.decodeResourcesFromMessageMetadata(db.metadata)
let contentBlocks =
db.contentBlocksJSON.flatMap(ChatContentBlockCodec.decode)
?? ChatContentBlockCodec.decodeFromMessageMetadata(db.metadata)
self.init(
id: db.id,
text: db.text,
createdAt: db.createdAt,
sender: db.sender == "human" ? .user : .ai,
isStreaming: false,
rating: db.rating,
isSynced: true,
contentBlocks: contentBlocks,
attachments: ChatMessage.decodeAttachments(from: db.metadata),
resources: resources
)
}
/// Parse the `attachments` array from a message's persisted metadata JSON.
/// Format (mirrors `MessageMetadata.attachmentsJSON()` on send):
/// `{ "attachments": [ { "id": "...", "name": "...", "mime_type": "...", "thumbnail": "..." } ] }`
static func decodeAttachments(from metadataJSON: String?) -> [ChatAttachment] {
guard let json = metadataJSON, let data = json.data(using: .utf8),
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let raw = root["attachments"] as? [[String: Any]]
else { return [] }
return raw.compactMap { item -> ChatAttachment? in
guard let id = item["id"] as? String else { return nil }
let name = (item["name"] as? String) ?? "file"
let mime = (item["mime_type"] as? String) ?? "application/octet-stream"
let thumb = item["thumbnail"] as? String
return ChatAttachment(
id: id,
fileName: name,
mimeType: mime,
data: nil,
serverId: id,
thumbnailURL: thumb,
state: .uploaded
)
}
}
}
// MARK: - Citation Model
/// A citation referencing a source conversation or memory
struct Citation: Identifiable {
let id: String
let sourceType: CitationSourceType
let title: String
let preview: String
let emoji: String?
let createdAt: Date?
enum CitationSourceType {
case conversation
case memory
}
}
// MARK: - Chat Mode
/// Controls whether the AI agent can perform write actions (Act) or is restricted to read-only (Ask)
enum ChatMode: String, CaseIterable {
case ask
case act
}
enum ChatSystemPromptStyle {
case main
case floating
}
enum RealtimeChatLaneError: Error {