Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FeatureComposerDraftStore.swift

497 lines20.4 KB

1import Foundation
2​
3public struct FeatureComposerDraft: Sendable, Equatable {
4 public var context: OrchestrationMessageContext?
5 public var text: String
6 public var attachments: [FeatureDraftAttachment]
7 public var selection: FeatureSelection?
8 public var workspace: FeatureComposerWorkspaceDraft?
9​
10 public init(
11 text: String = "",
12 attachments: [FeatureDraftAttachment] = [],
13 selection: FeatureSelection? = nil,
14 workspace: FeatureComposerWorkspaceDraft? = nil,
15 context: OrchestrationMessageContext? = nil
16 ) {
17 self.text = text
18 self.attachments = attachments
19 self.selection = selection
20 self.workspace = workspace
21 self.context = context
22 }
23​
24 public var isEmpty: Bool {
25 text.isEmpty && attachments.isEmpty && selection == nil && workspace == nil
26 }
28​
29public struct FeatureComposerWorkspaceDraft: Sendable, Equatable {
30 public var mode: FeatureWorkspaceMode
31 public var branch: String?
32 public var worktreePath: String?
33 public var startFromOrigin: Bool
34​
35 public init(
36 mode: FeatureWorkspaceMode,
37 branch: String?,
38 worktreePath: String?,
39 startFromOrigin: Bool
40 ) {
41 self.mode = mode
42 self.branch = branch
43 self.worktreePath = worktreePath
44 self.startFromOrigin = startFromOrigin
45 }
47​
48enum FeatureQuestionAttachmentDraft {
49 static func key(inputID: String) -> String { "question-attachments:\(inputID)" }
50​
51 static func encode(_ attachments: [String: [FeatureDraftAttachment]]) throws -> FeatureComposerDraft {
52 let nonempty = attachments.filter { !$0.value.isEmpty }
53 guard !nonempty.isEmpty else { return FeatureComposerDraft() }
54 let data = try JSONEncoder().encode(nonempty.mapValues { $0.map(\.id) })
55 return FeatureComposerDraft(
56 text: String(decoding: data, as: UTF8.self),
57 attachments: nonempty.keys.sorted().flatMap { nonempty[$0] ?? [] }
58 )
59 }
60​
61 static func decode(_ draft: FeatureComposerDraft?) throws -> [String: [FeatureDraftAttachment]] {
62 guard let draft, !draft.isEmpty else { return [:] }
63 let ids = try JSONDecoder().decode([String: [UUID]].self, from: Data(draft.text.utf8))
64 let byID = Dictionary(draft.attachments.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
65 return ids.mapValues { $0.compactMap { byID[$0] } }
66 }
68​
69public enum FeatureComposerDraftImportError: LocalizedError, Equatable, Sendable {
70 case attachmentLimitExceeded(available: Int)
71​
72 public var errorDescription: String? {
73 switch self {
74 case let .attachmentLimitExceeded(available):
75 available == 0
76 ? "This draft already has eight attachments. Remove one before importing the share."
77 : "This share needs more attachment slots. The current draft has room for \(available)."
78 }
79 }
81​
82/// Persists composer state independently of view navigation. Draft writes are
83/// atomic, and callers debounce high-frequency text changes before reaching
84/// this actor so image data is not repeatedly encoded for every keystroke.
85public actor FeatureComposerDraftStore {
86 public static let shared = FeatureComposerDraftStore()
87 private static let documentVersion = 2
88​
89 private struct Document: Codable {
90 let version: Int
91 var drafts: [String: PersistedDraft]
92 }
93​
94 private struct PersistedDraft: Codable {
95 var context: OrchestrationMessageContext?
96 var text: String
97 var attachments: [PersistedAttachment]
98 var selection: FeatureSelection?
99 var workspace: PersistedWorkspace?
100 var importedShareIDs: [String]?
101​
102 init(_ draft: FeatureComposerDraft) {
103 text = draft.text
104 context = draft.context
105 attachments = draft.attachments.map(PersistedAttachment.init)
106 selection = draft.selection
107 workspace = draft.workspace.map(PersistedWorkspace.init)
108 importedShareIDs = nil
109 }
110​
111 func featureValue(fileStore: ManagedAttachmentFileStore) -> FeatureComposerDraft {
112 FeatureComposerDraft(
113 text: text,
114 attachments: attachments.compactMap { $0.featureValue(fileStore: fileStore) },
115 selection: selection,
116 workspace: workspace?.featureValue,
117 context: context
118 )
119 }
120 }
121​
122 private struct PersistedWorkspace: Codable {
123 var mode: FeatureWorkspaceMode
124 var branch: String?
125 var worktreePath: String?
126 var startFromOrigin: Bool
127​
128 init(_ workspace: FeatureComposerWorkspaceDraft) {
129 mode = workspace.mode
130 branch = workspace.branch
131 worktreePath = workspace.worktreePath
132 startFromOrigin = workspace.startFromOrigin
133 }
134​
135 var featureValue: FeatureComposerWorkspaceDraft {
136 FeatureComposerWorkspaceDraft(
137 mode: mode,
138 branch: branch,
139 worktreePath: worktreePath,
140 startFromOrigin: startFromOrigin
141 )
142 }
143 }
144​
145 private struct PersistedAttachment: Codable {
146 var source: PastedTextAttachmentSource?
147 var id: UUID
148 var data: Data?
149 var ownedFileName: String?
150 var byteCount: Int?
151 var thumbnailData: Data?
152 var filename: String
153 var mimeType: String
154 var uploadedReference: FeatureUploadedAttachmentReference?
155​
156 init(_ attachment: FeatureDraftAttachment) {
157 id = attachment.id
158 source = attachment.source
159 data = attachment.ownedFile == nil ? attachment.data : nil
160 ownedFileName = attachment.ownedFile?.fileName
161 byteCount = attachment.byteCount
162 thumbnailData = attachment.thumbnailData
163 filename = attachment.filename
164 mimeType = attachment.mimeType
165 uploadedReference = attachment.uploadedReference
166 }
167​
168 func featureValue(fileStore: ManagedAttachmentFileStore) -> FeatureDraftAttachment? {
169 if let ownedFileName,
170 let ownedFile = try? fileStore.resolvedFile(
171 fileName: ownedFileName,
172 byteCount: byteCount ?? 0
173 ) {
174 return FeatureDraftAttachment(
175 id: id,
176 ownedFile: ownedFile,
177 thumbnailData: thumbnailData,
178 filename: filename,
179 mimeType: mimeType,
180 uploadedReference: uploadedReference,
181 source: source
182 )
183 }
184 guard let data else { return nil }
185 return FeatureDraftAttachment(
186 id: id,
187 data: data,
188 thumbnailData: thumbnailData,
189 filename: filename,
190 mimeType: mimeType,
191 uploadedReference: uploadedReference,
192 source: source
193 )
194 }
195​
196 func hasSameContent(as attachment: FeatureDraftAttachment) -> Bool {
197 guard id == attachment.id,
198 filename == attachment.filename,
199 mimeType == attachment.mimeType,
200 source == attachment.source,
201 (byteCount ?? data?.count ?? 0) == attachment.byteCount else { return false }
202 if let ownedFileName {
203 return ownedFileName == attachment.ownedFile?.fileName
204 }
205 return attachment.ownedFile == nil && data == attachment.data
206 }
207 }
208​
209 public let fileURL: URL
210 public let attachmentFileStore: ManagedAttachmentFileStore
211 private var loadedDrafts: [String: PersistedDraft]?
212​
213 public init(fileURL: URL? = nil, attachmentStorageRootURL: URL? = nil) {
214 attachmentFileStore = ManagedAttachmentFileStore(rootURL: attachmentStorageRootURL)
215 if let fileURL {
216 self.fileURL = fileURL
217 } else {
218 let root = FileManager.default.urls(
219 for: .applicationSupportDirectory,
220 in: .userDomainMask
221 ).first!
222 self.fileURL = root
223 .appendingPathComponent("T3CodeSwift", isDirectory: true)
224 .appendingPathComponent("composer-drafts.json", isDirectory: false)
225 }
226 }
227​
228 public func draft(for key: String) throws -> FeatureComposerDraft? {
229 guard let draft = try loadIfNeeded()[key]?.featureValue(fileStore: attachmentFileStore),
230 !draft.isEmpty else { return nil }
231 return draft
232 }
233​
234 public func clipboardAttachment(environmentID: String, attachmentID: String) throws -> FeatureDraftAttachment? {
235 for (key, draft) in try loadIfNeeded() {
236 for attachment in draft.attachments {
237 // Logical-project drafts move between environments. Their local UUID identifies
238 // the bytes. Server attachment IDs still require the matching upload environment.
239 let localMatch = (key.hasPrefix("environment:\(environmentID):")
240 || key.hasPrefix(Self.rewindRecoveryKey(for: "environment:\(environmentID):"))
241 || key.hasPrefix("logical-project:"))
242 && attachment.id.uuidString.caseInsensitiveCompare(attachmentID) == .orderedSame
243 let uploadedMatch = attachment.uploadedReference?.environmentID == environmentID
244 && attachment.uploadedReference?.attachmentID == attachmentID
245 if localMatch || uploadedMatch { return attachment.featureValue(fileStore: attachmentFileStore) }
246 }
247 }
248 return nil
249 }
250​
251 public func setDraft(_ draft: FeatureComposerDraft, for key: String) throws {
252 var drafts = try loadIfNeeded()
253 let existingReferences = Dictionary(
254 uniqueKeysWithValues: (drafts[key]?.attachments ?? []).compactMap { attachment in
255 attachment.uploadedReference.map { (attachment.id, (attachment, $0)) }
256 }
257 )
258 var mergedDraft = draft
259 for index in mergedDraft.attachments.indices
260 where mergedDraft.attachments[index].uploadedReference == nil {
261 let incoming = mergedDraft.attachments[index]
262 if let (persisted, reference) = existingReferences[incoming.id],
263 persisted.hasSameContent(as: incoming) {
264 mergedDraft.attachments[index].uploadedReference = reference
265 }
266 }
267 if mergedDraft.isEmpty {
268 if let importedShareIDs = drafts[key]?.importedShareIDs,
269 !importedShareIDs.isEmpty {
270 var persisted = PersistedDraft(mergedDraft)
271 persisted.importedShareIDs = importedShareIDs
272 drafts[key] = persisted
273 } else {
274 drafts.removeValue(forKey: key)
275 }
276 } else {
277 var persisted = PersistedDraft(mergedDraft)
278 // Preserve the crash-replay ledger while the composer performs its
279 // ordinary debounced saves after opening an imported share.
280 persisted.importedShareIDs = drafts[key]?.importedShareIDs
281 drafts[key] = persisted
282 }
283 try persist(drafts)
284 loadedDrafts = drafts
285 }
286​
287 /// Saves an upload result only if the attachment still exists with the
288 /// same immutable content. Text, selection, and workspace stay unchanged.
289 @discardableResult
290 public func setUploadedReference(
291 _ reference: FeatureUploadedAttachmentReference,
292 attachment: FeatureDraftAttachment,
293 for key: String
294 ) throws -> Bool {
295 var drafts = try loadIfNeeded()
296 guard var draft = drafts[key],
297 let index = draft.attachments.firstIndex(where: { $0.id == attachment.id }),
298 draft.attachments[index].hasSameContent(as: attachment) else { return false }
299 draft.attachments[index].uploadedReference = reference
300 drafts[key] = draft
301 try persist(drafts)
302 loadedDrafts = drafts
303 return true
304 }
305​
306 /// Atomically imports one share-extension envelope into the latest stored
307 /// draft. The share ID is committed with the content, so a host crash after
308 /// this write but before inbox cleanup cannot duplicate the import.
309 @discardableResult
310 public func importSharedContent(
311 shareID: String,
312 text: String,
313 attachments: [FeatureDraftAttachment],
314 for key: String,
315 maximumAttachmentCount: Int = 8
316 ) throws -> FeatureComposerDraft {
317 var drafts = try loadIfNeeded()
318 var persisted = drafts[key] ?? PersistedDraft(FeatureComposerDraft())
319 var importedIDs = persisted.importedShareIDs ?? []
320 guard !importedIDs.contains(shareID) else {
321 return persisted.featureValue(fileStore: attachmentFileStore)
322 }
323​
324 let existingIDs = Set(persisted.attachments.map(\.id))
325 let uniqueAttachments = attachments.filter { !existingIDs.contains($0.id) }
326 let availableCount = max(0, maximumAttachmentCount - persisted.attachments.count)
327 guard uniqueAttachments.count <= availableCount else {
328 throw FeatureComposerDraftImportError.attachmentLimitExceeded(
329 available: availableCount
330 )
331 }
332​
333 let incomingText = text.trimmingCharacters(in: .whitespacesAndNewlines)
334 if !incomingText.isEmpty {
335 persisted.text = persisted.text.trimmingCharacters(in: .whitespacesAndNewlines)
336 persisted.text = persisted.text.isEmpty
337 ? incomingText
338 : "\(persisted.text)\n\n\(incomingText)"
339 }
340​
341 persisted.attachments.append(contentsOf: uniqueAttachments.map(PersistedAttachment.init))
342 importedIDs.append(shareID)
343 persisted.importedShareIDs = Array(importedIDs.suffix(32))
344 drafts[key] = persisted
345 try persist(drafts)
346 loadedDrafts = drafts
347 return persisted.featureValue(fileStore: attachmentFileStore)
348 }
349​
350 public func removeDraft(for key: String) throws {
351 var drafts = try loadIfNeeded()
352 guard drafts.removeValue(forKey: key) != nil else { return }
353 try persist(drafts)
354 loadedDrafts = drafts
355 }
356​
357 public static func rewindRecoveryKey(for threadKey: String) -> String {
358 "rewind-recovery:" + threadKey
359 }
360​
361 public func hasRewindRecovery(for threadKey: String) throws -> Bool {
362 try loadIfNeeded()[Self.rewindRecoveryKey(for: threadKey)] != nil
363 }
364​
365 /// Moving recovery into the composer is one disk write. A crash cannot
366 /// leave the same recovered message available to append a second time.
367 public func consumeRewindRecovery(for threadKey: String) throws -> FeatureComposerDraft? {
368 var drafts = try loadIfNeeded()
369 let recoveryKey = Self.rewindRecoveryKey(for: threadKey)
370 guard let savedRecovery = drafts[recoveryKey] else { return nil }
371 let recovery = savedRecovery.featureValue(fileStore: attachmentFileStore)
372 let current = drafts[threadKey]?.featureValue(fileStore: attachmentFileStore) ?? FeatureComposerDraft()
373 let files = (recovery.attachments + current.attachments).compactMap(\.ownedFile)
374 let filesAreReadable = files.allSatisfy { file in
375 guard FileManager.default.isReadableFile(atPath: file.url.path),
376 let attributes = try? file.url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) else {
377 return false
378 }
379 return attributes.isRegularFile == true && attributes.fileSize == file.byteCount
380 }
381 guard recovery.attachments.count == savedRecovery.attachments.count,
382 current.attachments.count == (drafts[threadKey]?.attachments.count ?? 0),
383 filesAreReadable else {
384 throw FeatureConversationRewindError(message: "Some saved attachments could not be read. The recovery copy is kept.")
385 }
386 guard current.attachments.count + recovery.attachments.count <= 8 else {
387 throw FeatureConversationRewindError(message: "Make room for the saved prompt's attachments before recovering it.")
388 }
389 let recovered = try FeatureConversationRewind.merge(recovery: recovery, into: current)
390 var persisted = PersistedDraft(recovered)
391 persisted.importedShareIDs = drafts[threadKey]?.importedShareIDs
392 drafts[threadKey] = persisted
393 drafts.removeValue(forKey: recoveryKey)
394 try persist(drafts)
395 loadedDrafts = drafts
396 return recovered
397 }
398​
399 /// Call only when the command was rejected or never sent. Recovery copies
400 /// have fresh IDs and are not shared with the outbox or existing drafts.
401 public func discardRewindRecovery(for threadKey: String) throws {
402 let recoveryKey = Self.rewindRecoveryKey(for: threadKey)
403 let attachments = try loadIfNeeded()[recoveryKey]?.attachments ?? []
404 try removeDraft(for: recoveryKey)
405 for attachment in attachments {
406 if let fileName = attachment.ownedFileName {
407 try? attachmentFileStore.removeOwnedFile(fileName: fileName)
408 }
409 }
410 }
411​
412 public func removeDrafts(
413 environmentID: String,
414 logicalProjectIDs: Set<String> = []
415 ) throws {
416 var drafts = try loadIfNeeded()
417 let environmentPrefix = "environment:\(environmentID):"
418 let rewindPrefix = Self.rewindRecoveryKey(for: environmentPrefix)
419 let questionPrefix = FeatureQuestionAttachmentDraft.key(
420 inputID: FeatureScopedID.input(environmentID: environmentID, wireID: "")
421 )
422 let logicalKeys = Set(logicalProjectIDs.map(Self.newTaskKey(logicalProjectID:)))
423 drafts = drafts.filter {
424 !$0.key.hasPrefix(environmentPrefix) && !$0.key.hasPrefix(rewindPrefix)
425 && !$0.key.hasPrefix(questionPrefix)
426 && !logicalKeys.contains($0.key)
427 }
428 try persist(drafts)
429 loadedDrafts = drafts
430 }
431​
432 public static func threadKey(_ thread: FeatureThread) -> String {
433 let environment = thread.environmentID ?? "active"
434 let threadID = thread.wireID ?? thread.id
435 return "environment:\(environment):thread:\(threadID)"
436 }
437​
438 public static func newTaskKey(project: FeatureProject) -> String {
439 let projectID = project.wireID ?? project.id
440 return "environment:\(project.environmentID):new-task:\(projectID)"
441 }
442​
443 static func newTaskKey(project: FeatureProject, in snapshot: FeatureSnapshot) -> String {
444 guard project.repositoryIdentity != nil else {
445 return newTaskKey(project: project)
446 }
447 return newTaskKey(
448 logicalProjectID: DailyUXCreationContext.logicalProjectID(
449 for: project,
450 in: snapshot
451 )
452 )
453 }
454​
455 public static func newTaskKey(logicalProjectID: String) -> String {
456 "logical-project:\(logicalProjectID):new-task"
457 }
458​
459 private func loadIfNeeded() throws -> [String: PersistedDraft] {
460 if let loadedDrafts { return loadedDrafts }
461 guard FileManager.default.fileExists(atPath: fileURL.path) else {
462 let drafts: [String: PersistedDraft] = [:]
463 loadedDrafts = drafts
464 return drafts
465 }
466 let data = try Data(contentsOf: fileURL)
467 let document = try JSONDecoder.t3.decode(Document.self, from: data)
468 guard document.version == 1 || document.version == Self.documentVersion else {
469 throw CocoaError(.fileReadCorruptFile)
470 }
471 var drafts = document.drafts
472 if document.version == 1 {
473 // Version 1 wrote resolved project/environment defaults into every
474 // new-task draft. They were not necessarily user choices, so drop
475 // only those derived fields while preserving text and attachments.
476 for key in Array(drafts.keys) where key.contains(":new-task:") {
477 drafts[key]?.selection = nil
478 drafts[key]?.workspace = nil
479 }
480 drafts = drafts.filter {
481 !$0.value.featureValue(fileStore: attachmentFileStore).isEmpty
482 }
483 try persist(drafts)
484 }
485 loadedDrafts = drafts
486 return drafts
487 }
488​
489 private func persist(_ drafts: [String: PersistedDraft]) throws {
490 try FileManager.default.createDirectory(
491 at: fileURL.deletingLastPathComponent(),
492 withIntermediateDirectories: true
493 )
494 let document = Document(version: Self.documentVersion, drafts: drafts)
495 try JSONEncoder.t3.encode(document).write(to: fileURL, options: .atomic)
496 }