Open History to see the last commit
1import Foundation
2
3/// Stable wire identities make an outbox retry idempotent across app launches,
4/// including the ambiguous case where the server committed a command but its
5/// response never reached the phone.
6public struct FeatureSubmissionIdentity: Sendable, Equatable, Hashable, Codable {
7 public var threadID: String
8 public var commandID: String
9 public var messageID: String
10 public var createdAt: Date
11
12 public init(
13 threadID: String = UUID().uuidString,
14 commandID: String = UUID().uuidString,
15 messageID: String = UUID().uuidString,
16 createdAt: Date = .now
17 ) {
18 self.threadID = threadID
19 self.commandID = commandID
20 self.messageID = messageID
21 self.createdAt = createdAt
22 }
23}
24
25public struct FeatureQueuedAttachment: Sendable, Equatable, Codable {
26 public var source: PastedTextAttachmentSource?
27 public var id: UUID
28 public var data: Data?
29 public var ownedFileName: String?
30 public var byteCount: Int?
31 public var name: String
32 public var mimeType: String
33 public var uploadedReference: FeatureUploadedAttachmentReference?
34 private var resolvedOwnedFile: FeatureOwnedAttachmentFile?
35
36 public init(
37 id: UUID = UUID(),
38 data: Data,
39 name: String,
40 mimeType: String,
41 uploadedReference: FeatureUploadedAttachmentReference? = nil,
42 source: PastedTextAttachmentSource? = nil
43 ) {
44 self.id = id
45 self.data = data
46 ownedFileName = nil
47 byteCount = data.count
48 self.name = name
49 self.mimeType = mimeType
50 self.uploadedReference = uploadedReference
51 self.source = source
52 resolvedOwnedFile = nil
53 }
54
55 init(_ attachment: FeatureUploadAttachment) {
56 id = attachment.id
57 source = attachment.source
58 data = attachment.ownedFile == nil ? attachment.data : nil
59 ownedFileName = attachment.ownedFile?.fileName
60 byteCount = attachment.byteCount
61 name = attachment.name
62 mimeType = attachment.mimeType
63 uploadedReference = attachment.uploadedReference
64 resolvedOwnedFile = attachment.ownedFile
65 }
66
67 private enum CodingKeys: String, CodingKey {
68 case id, data, ownedFileName, byteCount, name, mimeType, uploadedReference
69 case source
70 }
71
72 public init(from decoder: any Decoder) throws {
73 let container = try decoder.container(keyedBy: CodingKeys.self)
74 id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
75 data = try container.decodeIfPresent(Data.self, forKey: .data)
76 ownedFileName = try container.decodeIfPresent(String.self, forKey: .ownedFileName)
77 byteCount = try container.decodeIfPresent(Int.self, forKey: .byteCount) ?? data?.count
78 name = try container.decode(String.self, forKey: .name)
79 mimeType = try container.decode(String.self, forKey: .mimeType)
80 source = try container.decodeIfPresent(PastedTextAttachmentSource.self, forKey: .source)
81 uploadedReference = try container.decodeIfPresent(
82 FeatureUploadedAttachmentReference.self,
83 forKey: .uploadedReference
84 )
85 resolvedOwnedFile = nil
86 }
87
88 public func encode(to encoder: any Encoder) throws {
89 var container = encoder.container(keyedBy: CodingKeys.self)
90 try container.encode(id, forKey: .id)
91 try container.encodeIfPresent(data, forKey: .data)
92 try container.encodeIfPresent(ownedFileName, forKey: .ownedFileName)
93 try container.encodeIfPresent(byteCount, forKey: .byteCount)
94 try container.encode(name, forKey: .name)
95 try container.encode(mimeType, forKey: .mimeType)
96 try container.encodeIfPresent(source, forKey: .source)
97 try container.encodeIfPresent(uploadedReference, forKey: .uploadedReference)
98 }
99
100 mutating func resolveOwnedFile(using fileStore: ManagedAttachmentFileStore) {
101 guard let ownedFileName else { return }
102 resolvedOwnedFile = try? fileStore.resolvedFile(
103 fileName: ownedFileName,
104 byteCount: byteCount ?? 0
105 )
106 }
107
108 var upload: FeatureUploadAttachment? {
109 if let resolvedOwnedFile {
110 return FeatureUploadAttachment(
111 id: id,
112 ownedFile: resolvedOwnedFile,
113 name: name,
114 mimeType: mimeType,
115 uploadedReference: uploadedReference,
116 source: source
117 )
118 }
119 guard let data else { return nil }
120 return FeatureUploadAttachment(
121 id: id,
122 data: data,
123 name: name,
124 mimeType: mimeType,
125 uploadedReference: uploadedReference,
126 source: source
127 )
128 }
129}
130
131public struct FeatureQueuedCreation: Sendable, Equatable, Codable {
132 public var projectID: String
133 public var projectName: String
134 public var workspaceMode: FeatureWorkspaceMode
135 public var branch: String?
136 public var worktreePath: String?
137 public var startFromOrigin: Bool
138
139 public init(
140 projectID: String,
141 projectName: String,
142 workspaceMode: FeatureWorkspaceMode,
143 branch: String?,
144 worktreePath: String?,
145 startFromOrigin: Bool
146 ) {
147 self.projectID = projectID
148 self.projectName = projectName
149 self.workspaceMode = workspaceMode
150 self.branch = branch
151 self.worktreePath = worktreePath
152 self.startFromOrigin = startFromOrigin
153 }
154}
155
156public struct FeatureQueuedSubmission: Identifiable, Sendable, Equatable, Codable {
157 public var context: OrchestrationMessageContext?
158 public let id: String
159 public var environmentID: String
160 public var identity: FeatureSubmissionIdentity
161 public var threadID: String
162 public var text: String
163 public var selection: FeatureSelection?
164 public var runtimeMode: FeatureRuntimeMode
165 public var interactionMode: FeatureInteractionMode
166 public var attachments: [FeatureQueuedAttachment]
167 public var creation: FeatureQueuedCreation?
168
169 public init(
170 id: String? = nil,
171 environmentID: String,
172 identity: FeatureSubmissionIdentity,
173 threadID: String,
174 text: String,
175 selection: FeatureSelection?,
176 runtimeMode: FeatureRuntimeMode,
177 interactionMode: FeatureInteractionMode,
178 attachments: [FeatureUploadAttachment],
179 creation: FeatureQueuedCreation? = nil,
180 context: OrchestrationMessageContext? = nil
181 ) {
182 self.id = id ?? identity.messageID
183 self.environmentID = environmentID
184 self.identity = identity
185 self.threadID = threadID
186 self.text = text
187 self.selection = selection
188 self.runtimeMode = runtimeMode
189 self.interactionMode = interactionMode.mobileNormalized
190 self.attachments = attachments.map(FeatureQueuedAttachment.init)
191 self.creation = creation
192 self.context = context
193 }
194
195 public var uploads: [FeatureUploadAttachment] {
196 attachments.compactMap(\.upload)
197 }
198}
199
200public enum FeatureOutboxDeliveryDecision: Equatable {
201 case discard
202 case wait
203 case send
204}
205
206public enum FeatureOutboxPolicy {
207 /// Delivery waits for the owning environment. Existing threads accept
208 /// follow-up messages while a turn is running, matching the web queue.
209 /// A created thread does not prove that its first message was accepted.
210 /// Retry its stable command identity until the message itself is confirmed.
211 public static func decision(
212 for submission: FeatureQueuedSubmission,
213 snapshot: FeatureSnapshot,
214 pendingCreationThreadIDs: Set<String> = []
215 ) -> FeatureOutboxDeliveryDecision {
216 let environment = snapshot.environments.first { $0.id == submission.environmentID }
217 let isConnected = environment?.isEnabled == true
218 && environment?.connectionState == .connected
219 let thread = snapshot.threads.first { $0.id == submission.threadID }
220
221 if submission.creation != nil {
222 if thread != nil { return isConnected ? .send : .wait }
223 let projectExists = snapshot.projects.contains {
224 $0.id == submission.creation?.projectID
225 && $0.environmentID == submission.environmentID
226 }
227 if isConnected, !projectExists { return .discard }
228 return isConnected ? .send : .wait
229 }
230
231 if pendingCreationThreadIDs.contains(submission.threadID) {
232 return .wait
233 }
234 guard thread != nil else {
235 // A fully synchronized environment proves the thread was deleted.
236 return isConnected ? .discard : .wait
237 }
238 guard isConnected else { return .wait }
239 return .send
240 }
241}
242
243public actor FeatureOutboxStore {
244 private struct Document: Codable {
245 var version = 1
246 var submissions: [FeatureQueuedSubmission]
247 }
248
249 public static let shared = FeatureOutboxStore()
250
251 public let fileURL: URL
252 public let attachmentFileStore: ManagedAttachmentFileStore
253 private var cached: [FeatureQueuedSubmission]?
254
255 public init(fileURL: URL? = nil, attachmentStorageRootURL: URL? = nil) {
256 attachmentFileStore = ManagedAttachmentFileStore(rootURL: attachmentStorageRootURL)
257 if let fileURL {
258 self.fileURL = fileURL
259 } else {
260 let root = FileManager.default.urls(
261 for: .applicationSupportDirectory,
262 in: .userDomainMask
263 ).first!
264 self.fileURL = root
265 .appendingPathComponent("T3CodeSwift", isDirectory: true)
266 .appendingPathComponent("outbox.json", isDirectory: false)
267 }
268 }
269
270 public func submissions() throws -> [FeatureQueuedSubmission] {
271 if let cached { return cached }
272 guard FileManager.default.fileExists(atPath: fileURL.path) else {
273 cached = []
274 return []
275 }
276 // Keep failed reads uncached so later writes cannot replace unreadable messages.
277 let document = try JSONDecoder.t3.decode(
278 Document.self,
279 from: Data(contentsOf: fileURL)
280 )
281 cached = document.submissions.map { submission in
282 var submission = submission
283 submission.interactionMode = submission.interactionMode.mobileNormalized
284 for index in submission.attachments.indices {
285 submission.attachments[index].resolveOwnedFile(using: attachmentFileStore)
286 }
287 return submission
288 }.sorted {
289 $0.identity.createdAt < $1.identity.createdAt
290 }
291 return cached ?? []
292 }
293
294 public func enqueue(_ submission: FeatureQueuedSubmission) throws {
295 var values = try submissions()
296 values.removeAll { $0.id == submission.id }
297 values.append(submission)
298 values.sort { $0.identity.createdAt < $1.identity.createdAt }
299 try save(values)
300 }
301
302 public func remove(id: String) throws {
303 var values = try submissions()
304 values.removeAll { $0.id == id }
305 try save(values)
306 }
307
308 public func removeAll(environmentID: String) throws {
309 var values = try submissions()
310 values.removeAll { $0.environmentID == environmentID }
311 try save(values)
312 }
313
314 private func save(_ submissions: [FeatureQueuedSubmission]) throws {
315 try FileManager.default.createDirectory(
316 at: fileURL.deletingLastPathComponent(),
317 withIntermediateDirectories: true
318 )
319 let data = try JSONEncoder.t3.encode(Document(submissions: submissions))
320 try data.write(to: fileURL, options: .atomic)
321 cached = submissions
322 }
323}