-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatThreadEntity.swift
More file actions
202 lines (158 loc) · 6.42 KB
/
Copy pathChatThreadEntity.swift
File metadata and controls
202 lines (158 loc) · 6.42 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
//
// ChatThreadEntity.swift
// Slices Chat
//
// AppEntity for ChatThread with search integration
// Created by Williamson Quintero on 1/9/26.
//
import AppIntents
import Foundation
import SwiftData
/// AppEntity representing a chat thread for search and App Intents integration
struct ChatThreadEntity: AppEntity {
// MARK: - AppEntity Requirements
static var typeDisplayRepresentation = TypeDisplayRepresentation(
name: "Chat Thread",
numericFormat: "\(placeholder: .int) threads"
)
static var defaultQuery = ChatThreadQuery()
// MARK: - Entity Properties
var id: String
@Property(title: "Title")
var title: String
@Property(title: "Last Message Preview")
var lastMessagePreview: String?
@Property(title: "Updated")
var updatedAt: Date
// MARK: - Display Representation
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(
title: "\(title)",
subtitle: lastMessagePreview.map { "\($0)" },
image: .init(systemName: "bubble.left.and.bubble.right")
)
}
// MARK: - Initialization
init(id: String, title: String, lastMessagePreview: String?, updatedAt: Date) {
self.id = id
self.title = title
self.lastMessagePreview = lastMessagePreview
self.updatedAt = updatedAt
}
/// Create entity from SwiftData ChatThread
init(from thread: ChatThread) {
self.id = (thread.id ?? UUID()).uuidString
self.title = thread.safeTitle
self.lastMessagePreview = thread.lastMessageText
self.updatedAt = thread.safeUpdatedAt
}
}
// MARK: - Entity Query
struct ChatThreadQuery: EntityQuery, EntityStringQuery {
/// Search threads by string query
func entities(for identifiers: [String]) async throws -> [ChatThreadEntity] {
return try await fetchThreads(with: identifiers)
}
/// Suggested entities (recent or pinned threads)
func suggestedEntities() async throws -> [ChatThreadEntity] {
return try await fetchRecentThreads(limit: 5)
}
/// Search by string (required by EntityStringQuery)
func entities(matching string: String) async throws -> [ChatThreadEntity] {
let searchTerm = string.lowercased()
return try await searchThreads(by: [searchTerm])
}
// MARK: - Private Helpers
@MainActor
private func searchThreads(by terms: [String]) async throws -> [ChatThreadEntity] {
// Get the model context from the app
guard let modelContext = await getModelContext() else {
return []
}
// Fetch all threads (you could optimize with predicates)
let descriptor = FetchDescriptor<ChatThread>(
sortBy: [SortDescriptor(\.updatedAt, order: .reverse)]
)
let allThreads = try modelContext.fetch(descriptor)
// Filter threads that match any of the search terms
let matchedThreads = allThreads.filter { thread in
let title = thread.safeTitle.lowercased()
let lastMessage = (thread.lastMessageText ?? "").lowercased()
let systemPrompt = (thread.systemPrompt ?? "").lowercased()
// Check if any term matches title, last message, or system prompt
return terms.contains { term in
title.contains(term) ||
lastMessage.contains(term) ||
systemPrompt.contains(term)
}
}
// Limit results to be responsive
let limitedThreads = Array(matchedThreads.prefix(10))
return limitedThreads.map { ChatThreadEntity(from: $0) }
}
@MainActor
private func fetchThreads(with ids: [String]) async throws -> [ChatThreadEntity] {
guard let modelContext = await getModelContext() else {
return []
}
let descriptor = FetchDescriptor<ChatThread>()
let allThreads = try modelContext.fetch(descriptor)
let matchedThreads = allThreads.filter { thread in
guard let threadId = thread.id else { return false }
return ids.contains(threadId.uuidString)
}
return matchedThreads.map { ChatThreadEntity(from: $0) }
}
@MainActor
private func fetchRecentThreads(limit: Int) async throws -> [ChatThreadEntity] {
guard let modelContext = await getModelContext() else {
return []
}
let descriptor = FetchDescriptor<ChatThread>(
sortBy: [SortDescriptor(\.updatedAt, order: .reverse)]
)
let threads = try modelContext.fetch(descriptor)
let recentThreads = Array(threads.prefix(limit))
return recentThreads.map { ChatThreadEntity(from: $0) }
}
@MainActor
private func getModelContext() async -> ModelContext? {
// Access the shared model container from your app
return await PurpleChatApp.shared?.modelContainer.mainContext
}
}
// MARK: - Transferable Conformance
/// Makes ChatThreadEntity available to Siri and system integrations
/// Provides plain text and JSON representations
extension ChatThreadEntity: Transferable {
static var transferRepresentation: some TransferRepresentation {
// Plain text representation for simple sharing
DataRepresentation(exportedContentType: .plainText) { entity in
let text = """
Chat Thread: \(entity.title)
Last Updated: \(entity.updatedAt.formatted())
\(entity.lastMessagePreview.map { "Preview: \($0)" } ?? "")
"""
return text.data(using: .utf8) ?? Data()
}
// JSON representation for structured data
DataRepresentation(exportedContentType: .json) { entity in
let json: [String: Any] = [
"id": entity.id,
"title": entity.title,
"lastMessagePreview": entity.lastMessagePreview ?? "",
"updatedAt": entity.updatedAt.timeIntervalSince1970
]
return try JSONSerialization.data(withJSONObject: json)
}
}
}
// MARK: - Hashable Conformance
extension ChatThreadEntity: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: ChatThreadEntity, rhs: ChatThreadEntity) -> Bool {
lhs.id == rhs.id
}
}