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

FeatureConversationRewind.swift

57 lines2.4 KB

1import Foundation
2​
3public struct FeatureRevertedMessage: Sendable {
4 public let message: FeatureMessage
5 public let attachments: [FeatureDraftAttachment]
6​
7 public init(message: FeatureMessage, attachments: [FeatureDraftAttachment]) {
8 self.message = message
9 self.attachments = attachments
10 }
12​
13struct FeatureConversationRewindError: LocalizedError {
14 let message: String
15 var didNotRevert = false
16 var errorDescription: String? { message }
18​
19enum FeatureConversationRewind {
20 static func canStart(in detail: FeatureThreadDetail) -> Bool {
21 switch detail.thread.state {
22 case .idle, .completed, .failed:
23 detail.isCompacting != true && !detail.backgroundWorkIsActive
24 && detail.approvals.isEmpty && detail.userInputs.isEmpty
25 default:
26 false
27 }
28 }
29​
30 /// Append recovered input without changing the current model or workspace.
31 static func recover(_ reverted: FeatureRevertedMessage, draft: FeatureComposerDraft) throws -> FeatureComposerDraft {
32 let original = reverted.message.text
33 let prompt = !reverted.attachments.isEmpty
34 && original == "[User attached one or more files without additional text. Respond using the conversation context and the attached files.]"
35 ? "" : original
36 // Copies keep the original attachment order but receive fresh local IDs.
37 // Keep the context links stable and point their records at those copies.
38 let attachmentIDs = Dictionary(zip(reverted.message.attachments, reverted.attachments).map { original, copy in
39 (original.id, copy.id.uuidString)
40 }, uniquingKeysWith: { first, _ in first })
41 let context = ComposerContextReferences.rebind(reverted.message.context, attachmentIDs: attachmentIDs)
42 return try merge(
43 recovery: FeatureComposerDraft(text: prompt, attachments: reverted.attachments, context: context),
44 into: draft
45 )
46 }
47​
48 static func merge(recovery: FeatureComposerDraft, into draft: FeatureComposerDraft) throws -> FeatureComposerDraft {
49 var recovered = draft
50 if !recovery.text.isEmpty {
51 recovered.text = draft.text.isEmpty ? recovery.text : draft.text + "\n\n" + recovery.text
52 }
53 recovered.attachments.append(contentsOf: recovery.attachments)
54 recovered.context = try FeatureComposerContext.merge(draft.context, recovery.context)
55 return recovered
56 }