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

NativeConversationRewind.swift

93 lines4.9 KB

1import Foundation
2​
3enum NativeConversationRewind {
4 /// Use checkpoint counts, not visible message indexes. Pages and steering messages
5 /// do not each represent one completed provider turn.
6 static func turnCount(before messageID: String, in thread: OrchestrationThread) -> Int? {
7 guard let index = thread.messages.firstIndex(where: { $0.id == messageID }),
8 thread.messages[index].role == "user" else { return nil }
9 let checkpoints = Dictionary(
10 thread.checkpoints.compactMap { checkpoint in
11 checkpoint.assistantMessageId.map { ($0, checkpoint.checkpointTurnCount) }
12 },
13 uniquingKeysWith: max
14 )
15 for message in thread.messages.dropFirst(index + 1) {
16 if message.role == "user" { return nil }
17 if let count = checkpoints[message.id] { return max(0, count - 1) }
18 }
19 return nil
20 }
21​
22 static func isComplete(_ thread: OrchestrationThread, messageID: String, turnCount: Int) -> Bool {
23 !thread.messages.contains(where: { $0.id == messageID })
24 && thread.checkpoints.allSatisfy { $0.checkpointTurnCount <= turnCount }
25 && (turnCount == 0
26 ? thread.latestTurn == nil
27 : thread.checkpoints.contains { $0.turnId == thread.latestTurn?.turnId })
28 }
29​
30 /// Command acceptance precedes provider rollback. Wait for its completion event
31 /// or an authoritative replacement snapshot, including while another thread is open.
32 static func waitForCompletion(
33 batches: AsyncThrowingStream<[ThreadStreamItem], Error>,
34 threadID: String,
35 messageID: String,
36 turnCount: Int,
37 afterSequence: Int,
38 previousFailureIDs: Set<String>,
39 timeout: Duration = .seconds(120)
40 ) async throws -> Int {
41 try await withThrowingTaskGroup(of: Int.self) { group in
42 group.addTask {
43 for try await batch in batches {
44 for item in batch {
45 switch item {
46 case .synchronized:
47 continue
48 case let .snapshot(snapshot):
49 guard snapshot.thread.id == threadID,
50 snapshot.snapshotSequence > afterSequence else { continue }
51 if isComplete(snapshot.thread, messageID: messageID, turnCount: turnCount) {
52 return snapshot.snapshotSequence
53 }
54 if let failure = snapshot.thread.activities.last(where: {
55 $0.kind == "checkpoint.revert.failed" && !previousFailureIDs.contains($0.id)
56 && $0.payload["turnCount"] == .number(Double(turnCount))
57 }) {
58 throw FeatureConversationRewindError(
59 message: failure.payload["detail"]?.stringValue ?? failure.summary,
60 didNotRevert: true
61 )
62 }
63 case let .event(event):
64 guard event["payload"]?["threadId"]?.stringValue == threadID,
65 case let .number(sequence)? = event["sequence"],
66 sequence > Double(afterSequence) else { continue }
67 if event["type"]?.stringValue == "thread.activity-appended",
68 let activity = event["payload"]?["activity"],
69 activity["kind"]?.stringValue == "checkpoint.revert.failed",
70 activity["payload"]?["turnCount"] == .number(Double(turnCount)) {
71 throw FeatureConversationRewindError(
72 message: activity["payload"]?["detail"]?.stringValue
73 ?? activity["summary"]?.stringValue ?? "Conversation rewind failed.",
74 didNotRevert: true
75 )
76 }
77 if event["type"]?.stringValue == "thread.reverted",
78 event["payload"]?["turnCount"] == .number(Double(turnCount)) { return Int(sequence) }
79 }
80 }
81 }
82 throw FeatureConversationRewindError(message: "The connection closed before rewind finished. Reload the thread before trying again.")
83 }
84 group.addTask {
85 try await Task.sleep(for: timeout)
86 throw FeatureConversationRewindError(message: "Timed out waiting for rewind. Reload the thread before trying again.")
87 }
88 defer { group.cancelAll() }
89 guard let sequence = try await group.next() else { throw CancellationError() }
90 return sequence
91 }
92 }