File size: 26,804 Bytes
b8370f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
import Foundation
import OpenClawKit
import Testing
@testable import OpenClawChatUI

private actor UnreadTestTransportState {
    var historyCalls = 0
    var listCalls = 0
    var unreadPatchAttempts: [(String, Bool)] = []
    var unreadPatchStarts = 0
    var sessionOverride: [OpenClawChatSessionEntry]?
    var historyFailuresRemaining: Int
    var patchFailuresRemaining: Int

    init(historyFailures: Int, patchFailures: Int) {
        self.historyFailuresRemaining = historyFailures
        self.patchFailuresRemaining = patchFailures
    }
}

private actor UnreadMutationRecorder {
    private(set) var events: [String] = []

    func append(_ event: String) {
        self.events.append(event)
    }
}

private actor UnreadPatchGate {
    private var continuation: CheckedContinuation<Void, Never>?
    private var released = false

    func wait() async {
        guard !self.released else { return }
        await withCheckedContinuation { continuation in
            if self.released {
                continuation.resume()
            } else {
                self.continuation = continuation
            }
        }
    }

    func release() {
        self.released = true
        self.continuation?.resume()
        self.continuation = nil
    }
}

private final class UnreadTestTransport: @unchecked Sendable, OpenClawChatTransport {
    private let state: UnreadTestTransportState
    private let sessions: [OpenClawChatSessionEntry]
    private let respectsListLimit: Bool
    private let patchDelay: Duration?
    private let patchGate: UnreadPatchGate?

    init(
        sessions: [OpenClawChatSessionEntry],
        historyFailures: Int = 0,
        patchFailures: Int = 0,
        respectsListLimit: Bool = false,
        patchDelay: Duration? = nil,
        patchGate: UnreadPatchGate? = nil)
    {
        self.sessions = sessions
        self.respectsListLimit = respectsListLimit
        self.patchDelay = patchDelay
        self.patchGate = patchGate
        self.state = UnreadTestTransportState(
            historyFailures: historyFailures,
            patchFailures: patchFailures)
    }

    func requestHistory(sessionKey: String) async throws -> OpenClawChatHistoryPayload {
        await self.state.recordHistoryCall()
        if await self.state.consumeHistoryFailure() {
            throw NSError(domain: "UnreadTestTransport", code: 1)
        }
        return OpenClawChatHistoryPayload(
            sessionKey: sessionKey,
            sessionId: "session-\(sessionKey)",
            messages: [],
            thinkingLevel: "off")
    }

    func sendMessage(
        sessionKey _: String,
        message _: String,
        thinking _: String,
        idempotencyKey _: String,
        attachments _: [OpenClawChatAttachmentPayload]) async throws -> OpenClawChatSendResponse
    {
        throw NSError(domain: "UnreadTestTransport", code: 3)
    }

    func listSessions(
        limit: Int?,
        search _: String?,
        archived _: Bool) async throws -> OpenClawChatSessionsListResponse
    {
        await self.state.recordListCall()
        let sessions = await self.state.sessionOverride ?? self.sessions
        let listed = if self.respectsListLimit, let limit {
            Array(sessions.prefix(limit))
        } else {
            sessions
        }
        return OpenClawChatSessionsListResponse(
            ts: nil,
            path: nil,
            count: listed.count,
            defaults: nil,
            sessions: listed)
    }

    func patchSession(
        key: String,
        expectedSessionID _: String?,
        label _: String??,
        category _: String??,
        color _: String?? = nil,
        pinned _: Bool?,
        archived _: Bool?,
        unread: Bool?) async throws
    {
        guard let unread else { return }
        await self.state.recordUnreadPatchStart()
        if let patchGate {
            await patchGate.wait()
        } else if let patchDelay {
            try await Task.sleep(for: patchDelay)
        }
        await self.state.recordUnreadPatch(key: key, unread: unread)
        if await self.state.consumePatchFailure() {
            throw NSError(domain: "UnreadTestTransport", code: 2)
        }
    }

    func requestHealth(timeoutMs _: Int) async throws -> Bool {
        true
    }

    func listModels(agentID _: String?) async throws -> [OpenClawChatModelChoice] {
        []
    }

    func events() -> AsyncStream<OpenClawChatTransportEvent> {
        AsyncStream { $0.finish() }
    }

    func unreadPatchAttempts() async -> [(String, Bool)] {
        await self.state.unreadPatchAttempts
    }

    func historyCallCount() async -> Int {
        await self.state.historyCalls
    }

    func unreadPatchStartCount() async -> Int {
        await self.state.unreadPatchStarts
    }

    func listCallCount() async -> Int {
        await self.state.listCalls
    }

    func setSessions(_ sessions: [OpenClawChatSessionEntry]) async {
        await self.state.setSessions(sessions)
    }
}

extension UnreadTestTransportState {
    fileprivate func recordHistoryCall() {
        self.historyCalls += 1
    }

    fileprivate func recordListCall() {
        self.listCalls += 1
    }

    fileprivate func recordUnreadPatch(key: String, unread: Bool) {
        self.unreadPatchAttempts.append((key, unread))
    }

    fileprivate func recordUnreadPatchStart() {
        self.unreadPatchStarts += 1
    }

    fileprivate func consumeHistoryFailure() -> Bool {
        guard self.historyFailuresRemaining > 0 else { return false }
        self.historyFailuresRemaining -= 1
        return true
    }

    fileprivate func consumePatchFailure() -> Bool {
        guard self.patchFailuresRemaining > 0 else { return false }
        self.patchFailuresRemaining -= 1
        return true
    }

    fileprivate func setSessions(_ sessions: [OpenClawChatSessionEntry]) {
        self.sessionOverride = sessions
    }
}

@Suite(.serialized)
@MainActor
struct ChatViewModelUnreadTests {
    @Test func `successful activation clears unread once`() async throws {
        let transport = UnreadTestTransport(sessions: [self.entry(key: "a", unread: true)])
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)

        viewModel.load()
        try await self.waitForUnreadState("initial activation unread patch") {
            await transport.unreadPatchAttempts().count == 1
        }
        viewModel.refresh()
        try await self.waitForUnreadState("refresh bootstrap settled") {
            await transport.listCallCount() >= 2 && !viewModel.isLoading
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.map(\.0) == ["a"])
        #expect(attempts.map(\.1) == [false])
    }

    @Test func `main alias refresh does not rearm unread clearing`() async throws {
        let transport = UnreadTestTransport(
            sessions: [self.entry(key: "agent:alpha:main", unread: true)])
        let viewModel = self.viewModel(
            sessionKey: "main",
            activeAgentID: "alpha",
            transport: transport)

        viewModel.load()
        try await self.waitForUnreadState("main alias activation unread patch") {
            await transport.unreadPatchAttempts().count == 1
        }
        viewModel.refresh()
        try await self.waitForUnreadState("main alias refresh settled") {
            await transport.historyCallCount() >= 2 && !viewModel.isLoading
        }

        #expect(await transport.unreadPatchAttempts().count == 1)
    }

    @Test func `cold main alias mark unread shares canonical activation identity`() async throws {
        let transport = UnreadTestTransport(
            sessions: [self.entry(key: "agent:alpha:main", unread: true)],
            patchDelay: .milliseconds(50))
        let viewModel = self.viewModel(
            sessionKey: "main",
            activeAgentID: "alpha",
            transport: transport)

        viewModel.setSessionUnread(key: "main", unread: true)
        viewModel.load()
        try await self.waitForUnreadState("cold main alias unread mutation settled") {
            await transport.unreadPatchAttempts().count == 1 && !viewModel.isLoading
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.map(\.0) == ["main"])
        #expect(attempts.map(\.1) == [true])
    }

    @Test func `failed history does not clear unread`() async throws {
        let transport = UnreadTestTransport(
            sessions: [self.entry(key: "a", unread: true)],
            historyFailures: 1)
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)

        viewModel.load()
        try await self.waitForUnreadState("failed history surfaced") {
            !viewModel.isLoading && viewModel.errorText != nil
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.isEmpty)
    }

    @Test func `failed unread patch retries on next activation`() async throws {
        let transport = UnreadTestTransport(
            sessions: [
                self.entry(key: "a", unread: true),
                self.entry(key: "b", unread: false),
            ],
            patchFailures: 1)
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)

        viewModel.load()
        try await self.waitForUnreadState("first failed unread patch recorded") {
            await transport.unreadPatchAttempts().count == 1
        }
        viewModel.switchSession(to: "b")
        try await self.waitForUnreadState("switched to session b") {
            viewModel.sessionId == "session-b"
        }
        viewModel.switchSession(to: "a")
        try await self.waitForUnreadState("retry unread patch recorded") {
            await transport.unreadPatchAttempts().count == 2
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.map(\.0) == ["a", "a"])
        #expect(attempts.allSatisfy { !$0.1 })
    }

    @Test func `failed intermediate activation still rearms unread clearing`() async throws {
        let transport = UnreadTestTransport(
            sessions: [
                self.entry(key: "a", unread: false),
                self.entry(key: "b", unread: false),
            ],
            historyFailures: 1)
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)
        viewModel.refreshSessions()
        try await self.waitForUnreadState("initial session list loaded") {
            viewModel.sessions.count == 2
        }

        viewModel.setSessionUnread(key: "a", unread: true)
        try await self.waitForUnreadState("explicit unread mutation recorded") {
            await transport.unreadPatchAttempts().count == 1
        }
        await transport.setSessions([
            self.entry(key: "a", unread: true),
            self.entry(key: "b", unread: false),
        ])
        viewModel.switchSession(to: "b")
        try await self.waitForUnreadState("failed intermediate activation surfaced") {
            viewModel.errorText != nil
        }
        viewModel.switchSession(to: "a")
        try await self.waitForUnreadState("reactivated unread patch recorded") {
            await transport.unreadPatchAttempts().count == 2
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.map(\.0) == ["a", "a"])
        #expect(attempts.map(\.1) == [true, false])
    }

    @Test func `explicit mark unread rearms automatic clearing`() async throws {
        let transport = UnreadTestTransport(sessions: [
            self.entry(key: "a", unread: true),
            self.entry(key: "b", unread: false),
        ])
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)

        viewModel.load()
        try await self.waitForUnreadState("initial activation read recorded") {
            await transport.unreadPatchAttempts().count == 1
        }
        viewModel.setSessionUnread(key: "a", unread: true)
        try await self.waitForUnreadState("explicit unread mutation recorded") {
            await transport.unreadPatchAttempts().count == 2
        }
        viewModel.switchSession(to: "b")
        try await self.waitForUnreadState("switched to session b") {
            viewModel.sessionId == "session-b"
        }
        viewModel.switchSession(to: "a")
        try await self.waitForUnreadState("reactivated unread patch recorded") {
            await transport.unreadPatchAttempts().count == 3
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.map(\.1) == [false, true, false])
    }

    @Test func `marking background session unread does not consume its activation`() async throws {
        let transport = UnreadTestTransport(sessions: [
            self.entry(key: "a", unread: false),
            self.entry(key: "b", unread: false),
        ])
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)
        viewModel.refreshSessions()
        try await self.waitForUnreadState("background session list loaded") {
            viewModel.sessions.count == 2
        }

        viewModel.setSessionUnread(key: "b", unread: true)
        try await self.waitForUnreadState("background unread mutation recorded") {
            await transport.unreadPatchAttempts().count == 1
        }
        await transport.setSessions([
            self.entry(key: "a", unread: false),
            self.entry(key: "b", unread: true),
        ])
        viewModel.switchSession(to: "b")
        try await self.waitForUnreadState("background activation read recorded") {
            await transport.unreadPatchAttempts().count == 2
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.map(\.0) == ["b", "b"])
        #expect(attempts.map(\.1) == [true, false])
    }

    @Test func `manual unread from another client survives refresh until reactivation`() async throws {
        let transport = UnreadTestTransport(sessions: [
            self.entry(key: "a", unread: false),
            self.entry(key: "b", unread: false),
        ])
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)

        viewModel.load()
        try await self.waitForUnreadState("initial read session loaded") {
            !viewModel.isLoading && viewModel.sessionId == "session-a"
        }
        await transport.setSessions([
            self.entry(key: "a", unread: true, markedUnreadAt: 100),
            self.entry(key: "b", unread: false),
        ])
        viewModel.refresh()
        try await self.waitForUnreadState("manual unread refresh settled") {
            await transport.historyCallCount() >= 2 && !viewModel.isLoading
        }
        #expect(await transport.unreadPatchAttempts().isEmpty)

        viewModel.switchSession(to: "b")
        try await self.waitForUnreadState("other session activated") {
            viewModel.sessionId == "session-b"
        }
        viewModel.switchSession(to: "a")
        try await self.waitForUnreadState("manual unread acknowledged on reactivation") {
            await transport.unreadPatchAttempts().count == 1
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.map(\.0) == ["a"])
        #expect(attempts.map(\.1) == [false])
    }

    @Test func `newer manual unread remains visible when activation acknowledgement loses race`() async throws {
        let patchGate = UnreadPatchGate()
        let transport = UnreadTestTransport(
            sessions: [self.entry(key: "a", unread: true, markedUnreadAt: 100)],
            patchGate: patchGate)
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)

        viewModel.load()
        try await self.waitForUnreadState("activation acknowledgement started") {
            await transport.unreadPatchStartCount() == 1
        }
        await transport.setSessions([
            self.entry(key: "a", unread: true, markedUnreadAt: 101),
        ])
        await patchGate.release()
        try await self.waitForUnreadState("authoritative unread refresh applied") {
            await transport.listCallCount() >= 2 &&
                viewModel.sessions.first(where: { $0.key == "a" })?.markedUnreadAt == 101
        }

        let session = try #require(viewModel.sessions.first(where: { $0.key == "a" }))
        #expect(session.unread == true)
        #expect(session.markedUnreadAt == 101)
    }

    @Test func `successful off-list mark read records read confirmation`() async throws {
        let transport = UnreadTestTransport(sessions: [])
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)

        viewModel.setSessionUnread(key: "hidden", unread: false)
        try await self.waitForUnreadState("off-list read confirmation recorded") {
            viewModel.unreadPatchGuard.confirmedUnread(key: "hidden") == false
        }

        #expect(viewModel.unreadPatchGuard.confirmedUnread(key: "hidden") == false)
    }

    @Test func `failed route lease preserves mutation queue ordering`() async throws {
        let recorder = UnreadMutationRecorder()
        let queue = ChatSessionUnreadMutationQueue()
        let firstLease = OpenClawChatSessionMutationRouteLease { _, _, _, _, _, _, _, _, _ in
            await recorder.append("first-start")
            try await Task.sleep(for: .milliseconds(100))
            await recorder.append("first-end")
        }
        let thirdLease = OpenClawChatSessionMutationRouteLease { _, _, _, _, _, _, _, _, _ in
            await recorder.append("third")
        }

        let first = queue.reserve(
            routeLease: Task<OpenClawChatSessionMutationRouteLease?, Never> { firstLease },
            queueKey: "a",
            routeKey: "a",
            unread: false)
        let second = queue.reserve(
            routeLease: Task<OpenClawChatSessionMutationRouteLease?, Never> { nil },
            queueKey: "a",
            routeKey: "a",
            unread: true)
        let third = queue.reserve(
            routeLease: Task<OpenClawChatSessionMutationRouteLease?, Never> { thirdLease },
            queueKey: "a",
            routeKey: "a",
            unread: false)

        try await first.value
        await #expect(throws: OpenClawChatTransportSendError.self) {
            try await second.value
        }
        try await third.value
        #expect(await recorder.events == ["first-start", "first-end", "third"])
    }

    @Test func `activation clears selected session outside refresh page`() async throws {
        let recent = (0..<50).map { index in
            self.entry(key: "recent-\(index)", unread: false, updatedAt: Double(100 - index))
        }
        let selected = self.entry(key: "old", unread: true, updatedAt: 1)
        let transport = UnreadTestTransport(
            sessions: recent + [selected],
            respectsListLimit: true)
        let viewModel = self.viewModel(sessionKey: "old", transport: transport)

        viewModel.refreshSessions(limit: 200)
        try await self.waitForUnreadState("selected off-page session loaded") {
            viewModel.sessions.contains { $0.key == "old" }
        }
        viewModel.load()
        try await self.waitForUnreadState("off-page activation read recorded") {
            await transport.unreadPatchAttempts().count == 1
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.map(\.0) == ["old"])
        #expect(attempts.map(\.1) == [false])
    }

    @Test func `failed unread patch refreshes authoritative session state`() async throws {
        let transport = UnreadTestTransport(
            sessions: [
                self.entry(key: "a", unread: true),
                self.entry(key: "b", unread: false),
            ],
            patchFailures: 1,
            patchDelay: .milliseconds(50))
        let viewModel = self.viewModel(sessionKey: "b", transport: transport)
        viewModel.refreshSessions()
        try await self.waitForUnreadState("authoritative session list loaded") {
            viewModel.sessions.count == 2
        }
        await transport.setSessions([
            self.entry(key: "a", unread: true),
            self.entry(key: "b", unread: false, pinned: true),
        ])

        viewModel.setSessionUnread(key: "a", unread: false)
        let otherIndex = try #require(viewModel.sessions.firstIndex(where: { $0.key == "b" }))
        viewModel.sessions[otherIndex].pinned = true
        try await self.waitForUnreadState("unread mutation failure surfaced") {
            viewModel.errorText != nil
        }
        try await self.waitForUnreadState("failure refresh completed") {
            await transport.listCallCount() >= 2
        }

        #expect(viewModel.sessions.first(where: { $0.key == "a" })?.unread == true)
        #expect(viewModel.sessions.first(where: { $0.key == "b" })?.pinned == true)
    }

    @Test func `mark unread wins over an older activation read`() async throws {
        let transport = UnreadTestTransport(
            sessions: [self.entry(key: "a", unread: true)],
            patchDelay: .milliseconds(50))
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)

        viewModel.load()
        try await self.waitForUnreadState("activation read started") {
            await transport.unreadPatchStartCount() == 1
        }
        viewModel.setSessionUnread(key: "a", unread: true)
        try await self.waitForUnreadState("explicit unread mutation completed") {
            await transport.unreadPatchAttempts().count == 2
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.map(\.1) == [false, true])
        #expect(viewModel.sessions.first(where: { $0.key == "a" })?.unread == true)
    }

    @Test func `stale list does not undo pending explicit unread`() async throws {
        let transport = UnreadTestTransport(
            sessions: [self.entry(key: "a", unread: false)],
            patchDelay: .milliseconds(50))
        let viewModel = self.viewModel(sessionKey: "a", transport: transport)
        viewModel.refreshSessions()
        try await self.waitForUnreadState("initial session list loaded") {
            viewModel.sessions.count == 1
        }

        viewModel.setSessionUnread(key: "a", unread: true)
        viewModel.refreshSessions()
        try await self.waitForUnreadState("explicit unread mutation completed") {
            await transport.unreadPatchAttempts().count == 1
        }
        await transport.setSessions([self.entry(key: "a", unread: true)])
        viewModel.load()
        try await self.waitForUnreadState("reactivated session loaded") {
            !viewModel.isLoading && viewModel.sessionId == "session-a"
        }

        let attempts = await transport.unreadPatchAttempts()
        #expect(attempts.map(\.1) == [true])
    }

    @Test func `pending explicit unread overlays stale list until fresh observation`() async throws {
        let patchGate = UnreadPatchGate()
        let transport = UnreadTestTransport(
            sessions: [
                self.entry(key: "a", unread: false),
                self.entry(key: "b", unread: false),
            ],
            patchGate: patchGate)
        let viewModel = self.viewModel(sessionKey: "b", transport: transport)
        viewModel.refreshSessions()
        try await self.waitForUnreadState("pending unread session list loaded") {
            viewModel.sessions.count == 2
        }

        viewModel.setSessionUnread(key: "a", unread: true)
        try await self.waitForUnreadState("unread patch started") {
            await transport.unreadPatchStartCount() == 1
        }
        viewModel.refreshSessions()
        try await self.waitForUnreadState("stale list refresh completed") {
            await transport.listCallCount() >= 2
        }

        #expect(viewModel.sessions.first(where: { $0.key == "a" })?.unread == true)
        #expect(viewModel.unreadPatchGuard.localUnreadOverride(key: "a") == true)

        await patchGate.release()
        await transport.setSessions([
            self.entry(key: "a", unread: true),
            self.entry(key: "b", unread: false),
        ])
        let listCallCount = await transport.listCallCount()
        try await self.waitForUnreadState("unread patch completed") {
            await transport.unreadPatchAttempts().count == 1
        }
        try await self.waitForUnreadState("fresh unread observation applied") {
            await transport.listCallCount() > listCallCount &&
                viewModel.unreadPatchGuard.localUnreadOverride(key: "a") == nil
        }

        #expect(viewModel.unreadPatchGuard.localUnreadOverride(key: "a") == nil)
        #expect(viewModel.unreadPatchGuard.confirmedUnread(key: "a") == true)
        #expect(viewModel.sessions.first(where: { $0.key == "a" })?.unread == true)
    }

    private func viewModel(
        sessionKey: String,
        activeAgentID: String? = nil,
        transport: UnreadTestTransport) -> OpenClawChatViewModel
    {
        let defaults = UserDefaults(suiteName: "ChatViewModelUnreadTests.\(UUID().uuidString)") ?? .standard
        return OpenClawChatViewModel(
            sessionKey: sessionKey,
            transport: transport,
            activeAgentId: activeAgentID,
            modelPickerStore: ChatModelPickerStore(defaults: defaults))
    }

    private func entry(
        key: String,
        unread: Bool,
        updatedAt: Double = 1,
        markedUnreadAt: Double? = nil,
        lastInteractionAt: Double? = nil,
        lastActivityAt: Double? = nil,
        pinned: Bool? = nil) -> OpenClawChatSessionEntry
    {
        OpenClawChatSessionEntry(
            key: key,
            kind: nil,
            displayName: nil,
            surface: nil,
            subject: nil,
            room: nil,
            space: nil,
            updatedAt: updatedAt,
            sessionId: nil,
            systemSent: nil,
            abortedLastRun: nil,
            thinkingLevel: nil,
            verboseLevel: nil,
            inputTokens: nil,
            outputTokens: nil,
            totalTokens: nil,
            modelProvider: nil,
            model: nil,
            contextTokens: nil,
            pinned: pinned,
            unread: unread,
            markedUnreadAt: markedUnreadAt,
            lastInteractionAt: lastInteractionAt,
            lastActivityAt: lastActivityAt)
    }

    private func waitForUnreadState(
        _ label: String,
        condition: @escaping @MainActor @Sendable () async -> Bool) async throws
    {
        try await waitUntil(label) {
            await condition()
        }
    }
}