@@ -212,31 +212,64 @@ extension GaryxMobileModel {
212212
213213 func persistTranscriptCacheWindowInBackground( _ window: GaryxCachedTranscript ) {
214214 let store = transcriptCacheStore
215+ let generation = nextTranscriptCachePersistenceGeneration ( for: window. threadId)
215216 Task . detached ( priority: . utility) {
216- await GaryxTranscriptCachePersistenceQueue . shared. save ( window, store: store)
217+ await GaryxTranscriptCachePersistenceQueue . shared. save (
218+ window,
219+ generation: generation,
220+ store: store
221+ )
217222 }
218223 }
219224
220225 func removeTranscriptCacheInBackground( threadId: String ) {
221226 let store = transcriptCacheStore
227+ let generation = nextTranscriptCachePersistenceGeneration ( for: threadId)
222228 Task . detached ( priority: . utility) {
223- await GaryxTranscriptCachePersistenceQueue . shared. remove ( threadId: threadId, store: store)
229+ await GaryxTranscriptCachePersistenceQueue . shared. remove (
230+ threadId: threadId,
231+ generation: generation,
232+ store: store
233+ )
224234 }
225235 }
236+
237+ private func nextTranscriptCachePersistenceGeneration( for threadId: String ) -> UInt64 {
238+ let next = ( transcriptCachePersistenceGenerations [ threadId] ?? 0 ) &+ 1
239+ transcriptCachePersistenceGenerations [ threadId] = next
240+ return next
241+ }
226242}
227243
228244private actor GaryxTranscriptCachePersistenceQueue {
229245 static let shared = GaryxTranscriptCachePersistenceQueue ( )
230246
247+ private var latestGenerationByThread : [ String : UInt64 ] = [ : ]
248+
231249 func load( threadId: String , store: GaryxTranscriptCacheStore ) -> GaryxCachedTranscript ? {
232250 store. load ( threadId: threadId)
233251 }
234252
235- func save( _ snapshot: GaryxCachedTranscript , store: GaryxTranscriptCacheStore ) {
253+ func save(
254+ _ snapshot: GaryxCachedTranscript ,
255+ generation: UInt64 ,
256+ store: GaryxTranscriptCacheStore
257+ ) {
258+ guard acceptGeneration ( generation, threadId: snapshot. threadId) else { return }
236259 store. save ( snapshot)
237260 }
238261
239- func remove( threadId: String , store: GaryxTranscriptCacheStore ) {
262+ func remove( threadId: String , generation: UInt64 , store: GaryxTranscriptCacheStore ) {
263+ guard acceptGeneration ( generation, threadId: threadId) else { return }
240264 store. remove ( threadId: threadId)
241265 }
266+
267+ private func acceptGeneration( _ generation: UInt64 , threadId: String ) -> Bool {
268+ let latest = latestGenerationByThread [ threadId] ?? 0
269+ guard generation >= latest else {
270+ return false
271+ }
272+ latestGenerationByThread [ threadId] = generation
273+ return true
274+ }
242275}
0 commit comments