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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { createPinia, setActivePinia } from 'pinia'
import { computed, ref } from 'vue'
import type {
  EntitiesContact,
  EntitiesMessageThread,
} from '../../shared/types/api'
import { useThreadsStore } from './threads'

function thread(id: string, unreadCount: number): EntitiesMessageThread {
  return {
    id,
    unread_count: unreadCount,
    owner: '+18005550199',
    contact: '+18005550100',
    color: 'indigo',
    is_archived: false,
    last_message_content: 'Hello',
    last_message_id: 'message-id',
    status: 'received',
    created_at: '2026-10-27T10:00:00Z',
    updated_at: '2026-10-27T10:00:00Z',
    order_timestamp: '2026-10-27T10:00:00Z',
    user_id: 'user-id',
  }
}

function setupStore() {
  const calls: { path: string; params?: Record<string, unknown> }[] = []
  let responseThreads = [thread('unread', 2), thread('read', 0)]
  const individualThreads = new Map<string, EntitiesMessageThread>()
  let nextLookup: Promise<{ data: EntitiesMessageThread }> | undefined
  let nextResponse: Promise<{ data: EntitiesMessageThread[] }> | undefined
  const phones = {
    owner: '+18005550199',
    phones: [],
    getHeartbeat: async () => [],
  }
  Object.assign(globalThis, {
    ref,
    computed,
    useApi: () => ({
      apiFetch: async (
        path: string,
        options: {
          params?: Record<string, unknown>
          method?: string
        } = {},
      ) => {
        calls.push({ path, params: options.params })
        if (options.method === 'PUT') {
          responseThreads = responseThreads.map((item) =>
            item.id === 'unread' ? { ...item, unread_count: 0 } : item,
          )
          return { data: thread('unread', 0) }
        }
        if (path === '/v1/messages') return { data: [] }
        if (
          (!options.method || options.method === 'GET') &&
          path.startsWith('/v1/message-threads/')
        ) {
          if (nextLookup) {
            const pending = nextLookup
            nextLookup = undefined
            return pending
          }
          const item = individualThreads.get(path.split('/').at(-1) ?? '')
          if (!item)
            throw Object.assign(new Error('Thread not found'), { status: 404 })
          return { data: item }
        }
        const pending = nextResponse
        nextResponse = undefined
        if (pending) return pending
        const skip = Number(options.params?.skip ?? 0)
        const limit = Number(options.params?.limit ?? 20)
        return {
          data: responseThreads.slice(skip, skip + limit),
        }
      },
    }),
    usePhonesStore: () => phones,
    useNotificationsStore: () => ({ addNotification: () => {} }),
  })
  setActivePinia(createPinia())
  return {
    store: useThreadsStore(),
    phones,
    calls,
    respondWith: (threads: EntitiesMessageThread[]) => {
      responseThreads = threads
    },
    respondToLookup: (item: EntitiesMessageThread) => {
      individualThreads.set(item.id, item)
    },
    deferLookup: (response: Promise<{ data: EntitiesMessageThread }>) => {
      nextLookup = response
    },
    deferNextLoad: (response: Promise<{ data: EntitiesMessageThread[] }>) => {
      nextResponse = response
    },
  }
}

function contact(
  name: string,
  phoneNumbers = ['+18005550100'],
): EntitiesContact {
  return {
    id: 'contact-id',
    name,
    phone_numbers: phoneNumbers,
    emails: [],
    properties: {},
    user_id: 'user-id',
    created_at: '2026-10-27T10:00:00Z',
    updated_at: '2026-10-27T11:00:00Z',
  }
}

async function setupReadConversationHistory() {
  const fixture = setupStore()
  const other = { ...thread('other', 1), contact: '+18005550101' }
  fixture.respondWith([thread('unread', 1), other])
  await fixture.store.loadThreads()
  fixture.store.setThreadId('unread')
  fixture.store.unreadOnly = true
  await fixture.store.resetThreadUnreadCount('unread')
  fixture.respondWith([other])
  await fixture.store.loadThreads()
  await fixture.store.loadThreadMessages('other')
  return fixture
}

test('Unread requests server-side filtering within the API limit', async () => {
  const { store, calls } = setupStore()
  store.unreadOnly = true
  store.archivedThreads = true

  await store.loadThreads()

  assert.equal(calls[0]?.params?.unread_only, true)
  assert.equal(calls[0]?.params?.is_archived, true)
  assert.equal(calls[0]?.params?.owner, '+18005550199')
  assert.equal(calls[0]?.params?.limit, 20)
})

test('marking a thread read hides it from Unread without closing it', async () => {
  const { store, calls, respondWith } = setupStore()
  await store.loadThreads()
  store.setThreadId('unread')
  store.unreadOnly = true

  await store.resetThreadUnreadCount('unread')

  assert.ok(store.visibleThreads)
  assert.deepEqual(store.visibleThreads, [])
  assert.equal(store.currentThread?.id, 'unread')
  assert.equal(store.currentThread.unread_count, 0)

  respondWith([])
  await store.loadThreads()
  assert.equal(store.currentThread?.id, 'unread')
  await store.loadThreadMessages('unread')
  assert.equal(calls.at(-1)?.path, '/v1/messages')
})

test('switching back to All restores read conversations', async () => {
  const { store } = setupStore()
  await store.loadThreads()
  store.unreadOnly = true

  assert.ok(store.visibleThreads)
  assert.deepEqual(
    store.visibleThreads.map((item) => item.id),
    ['unread'],
  )

  store.unreadOnly = false
  await store.loadThreads()
  assert.deepEqual(
    store.visibleThreads.map((item) => item.id),
    ['unread', 'read'],
  )
})

test('resetting the store clears the filter and retained conversation', async () => {
  const { store, respondWith } = setupStore()
  await store.loadThreads()
  store.setThreadId('unread')
  store.unreadOnly = true
  respondWith([])
  await store.loadThreads()

  store.resetState()

  assert.equal(store.unreadOnly, false)
  assert.equal(store.currentThread, null)
  assert.deepEqual(store.threads, [])
})

test('an older polling response cannot overwrite a newer unread-filter load', async () => {
  const { store, respondWith, deferNextLoad } = setupStore()
  const pending = Promise.withResolvers<{ data: EntitiesMessageThread[] }>()
  deferNextLoad(pending.promise)
  const oldLoad = store.loadThreads()
  store.unreadOnly = true
  respondWith([thread('unread', 2)])
  await store.loadThreads()

  pending.resolve({ data: [thread('read', 0)] })
  await oldLoad

  assert.deepEqual(
    store.threads.map((item) => item.id),
    ['unread'],
  )
})

test('All does not retain a conversation removed from the server list', async () => {
  const { store, respondWith } = setupStore()
  await store.loadThreads()
  store.setThreadId('unread')
  respondWith([])

  await store.loadThreads()

  assert.equal(store.currentThread, null)
})

for (const scenario of [
  {
    name: 'adding a contact refreshes a retained read conversation',
    existing: undefined,
    saved: contact('New contact'),
    expectedName: 'New contact',
  },
  {
    name: 'editing a contact refreshes a retained read conversation',
    existing: contact('Old name'),
    saved: contact('Updated name'),
    expectedName: 'Updated name',
  },
  {
    name: 'removing the conversation number clears its retained contact',
    existing: contact('Old name'),
    saved: contact('Updated name', ['+18005550101']),
    expectedName: undefined,
  },
]) {
  test(scenario.name, async () => {
    const { store, respondWith } = setupStore()
    respondWith([
      { ...thread('unread', 1), contact_details: scenario.existing },
    ])
    await store.loadThreads()
    store.setThreadId('unread')
    store.unreadOnly = true
    await store.resetThreadUnreadCount('unread')
    respondWith([])
    await store.loadThreads()

    await store.loadThreads([scenario.saved])

    assert.equal(store.currentThread?.id, 'unread')
    assert.equal(
      store.currentThread.contact_details?.name,
      scenario.expectedName,
    )
    assert.deepEqual(store.visibleThreads, [])
  })
}

test('a late poll cannot restore unread counts after mark-read succeeds', async () => {
  const { store, deferNextLoad } = setupStore()
  await store.loadThreads()
  store.setThreadId('unread')
  store.unreadOnly = true
  const pending = Promise.withResolvers<{ data: EntitiesMessageThread[] }>()
  deferNextLoad(pending.promise)
  store.loadingThreads = true
  const poll = store.loadThreads()

  await store.resetThreadUnreadCount('unread')
  pending.resolve({ data: [thread('unread', 2)] })
  await poll

  assert.equal(store.currentThread?.unread_count, 0)
  assert.deepEqual(store.visibleThreads, [])
  assert.equal(store.loadingThreads, false)
})

test('refreshing an overlapping read preserves messages received after the read', async () => {
  const { store, deferNextLoad, respondWith } = setupStore()
  await store.loadThreads()
  store.setThreadId('unread')
  store.unreadOnly = true
  const pending = Promise.withResolvers<{ data: EntitiesMessageThread[] }>()
  deferNextLoad(pending.promise)
  const poll = store.loadThreads()

  await store.resetThreadUnreadCount('unread')
  respondWith([
    {
      ...thread('unread', 1),
      last_message_id: 'new-inbound-message',
      last_message_content: 'Received after mark-read',
    },
  ])
  pending.resolve({ data: [thread('unread', 2)] })
  await poll

  assert.equal(store.currentThread?.unread_count, 1)
  assert.equal(store.currentThread.last_message_id, 'new-inbound-message')
  assert.equal(store.visibleThreads.length, 1)
  assert.equal(store.loadingThreads, false)
})

test('Back navigation restores an earlier read conversation in Unread', async () => {
  const { store, calls } = await setupReadConversationHistory()

  store.setThreadId('unread')

  assert.equal(store.currentThread?.id, 'unread')
  assert.equal(store.currentThread.unread_count, 0)
  await store.loadThreadMessages('unread')
  assert.equal(calls.at(-1)?.params?.contact, '+18005550100')
  assert.deepEqual(
    store.visibleThreads.map((item) => item.id),
    ['other'],
  )
})

test('saved contacts refresh previously opened read conversations too', async () => {
  const { store } = await setupReadConversationHistory()
  await store.loadThreads([contact('Alice')])

  store.setThreadId('unread')

  assert.equal(store.currentThread?.contact_details?.name, 'Alice')
})

for (const action of ['reset', 'delete', 'archive', 'owner', 'view']) {
  test(`navigation cache does not restore conversations after ${action}`, async () => {
    const { store, phones, respondWith } = await setupReadConversationHistory()
    if (action === 'reset') store.resetState()
    if (action === 'delete') await store.deleteThread('unread')
    if (action === 'archive') {
      await store.updateThread({ threadId: 'unread', isArchived: true })
    }
    if (action === 'owner' || action === 'view') {
      if (action === 'owner') phones.owner = '+18005550198'
      if (action === 'view') store.archivedThreads = true
      respondWith([])
      await store.loadThreads()
    }

    store.setThreadId('unread')

    assert.equal(store.currentThread, null)
    assert.equal(store.hasThreadId('unread'), false)
  })
}

function manyThreads(count: number) {
  return Array.from({ length: count }, (_, index) => ({
    ...thread(`page-${index}`, 1),
    contact: `+1800555${String(index).padStart(4, '0')}`,
  }))
}

for (const count of [0, 19, 20, 21]) {
  test(`Load More is available when the last page is full (${count})`, async () => {
    const { store, respondWith } = setupStore()
    respondWith(manyThreads(count))

    await store.loadThreads()

    assert.equal(store.threads.length, Math.min(count, 20))
    assert.equal(store.hasMoreThreads, count >= 20)
  })
}

test('Load More expands the loaded list and disappears on the final page', async () => {
  const { store, respondWith, calls } = setupStore()
  respondWith(manyThreads(45))
  await store.loadThreads()

  await store.loadMoreThreads()
  assert.equal(store.threads.length, 40)
  assert.equal(store.hasMoreThreads, true)
  await store.loadMoreThreads()
  assert.equal(store.threads.length, 45)
  assert.equal(new Set(store.threads.map((item) => item.id)).size, 45)
  assert.equal(store.hasMoreThreads, false)
  assert.equal(store.loadingMoreThreads, false)
  const completedCalls = calls.length
  await store.loadMoreThreads()
  assert.equal(calls.length, completedCalls)
})

for (const count of [20, 40]) {
  test(`an empty final page hides Load More without losing ${count} loaded threads`, async () => {
    const { store, respondWith } = setupStore()
    respondWith(manyThreads(count))
    await store.loadThreads()
    if (count === 40) await store.loadMoreThreads()
    assert.equal(store.threads.length, count)
    assert.equal(store.hasMoreThreads, true)

    await store.loadMoreThreads()

    assert.equal(store.threads.length, count)
    assert.equal(store.hasMoreThreads, false)
    assert.equal(store.loadingMoreThreads, false)
  })
}

test('polling preserves loaded pages and changing filters resets them', async () => {
  const { store, respondWith } = setupStore()
  respondWith(manyThreads(45))
  await store.loadThreads()
  await store.loadMoreThreads()

  await store.loadThreads()
  assert.equal(store.threads.length, 40)

  store.unreadOnly = true
  await store.loadThreads()
  assert.equal(store.threads.length, 20)
  await store.loadMoreThreads()
  store.archivedThreads = true
  await store.loadThreads()
  assert.equal(store.threads.length, 20)
})

test('switching phones resets loaded pages', async () => {
  const { store, respondWith, phones } = setupStore()
  respondWith(manyThreads(45))
  await store.loadThreads()
  await store.loadMoreThreads()

  phones.owner = '+18005550198'
  await store.loadThreads()

  assert.equal(store.threads.length, 20)
})

test('Load More failure preserves rows and permits a retry', async () => {
  const { store, respondWith, deferNextLoad } = setupStore()
  respondWith(manyThreads(45))
  await store.loadThreads()
  const pending = Promise.withResolvers<{ data: EntitiesMessageThread[] }>()
  deferNextLoad(pending.promise)

  const loading = store.loadMoreThreads()
  pending.reject(new Error('Network failed'))
  await assert.rejects(loading, /Network failed/)

  assert.equal(store.threads.length, 20)
  assert.equal(store.hasMoreThreads, true)
  assert.equal(store.loadingMoreThreads, false)
  await store.loadMoreThreads()
  assert.equal(store.threads.length, 40)
})

test('new activity does not close an open conversation pushed beyond the loaded page', async () => {
  const { store, respondWith } = setupStore()
  const existing = manyThreads(45)
  respondWith(existing)
  await store.loadThreads()
  store.setThreadId('page-19')
  respondWith([thread('newest', 1), ...existing])

  await store.loadThreads()

  assert.equal(store.currentThread?.id, 'page-19')
  await store.loadThreadMessages('page-19')
})

test('a second Load More click is ignored while the first is running', async () => {
  const { store, respondWith, deferNextLoad } = setupStore()
  const existing = manyThreads(65)
  respondWith(existing)
  await store.loadThreads()
  const pending = Promise.withResolvers<{ data: EntitiesMessageThread[] }>()
  deferNextLoad(pending.promise)

  const loading = store.loadMoreThreads()
  assert.equal(store.loadingMoreThreads, true)
  await store.loadMoreThreads()
  pending.resolve({ data: existing.slice(0, 20) })
  await loading

  assert.equal(store.threads.length, 40)
  assert.equal(store.loadingMoreThreads, false)
})

test('changing filters cancels an older Load More result', async () => {
  const { store, respondWith, deferNextLoad } = setupStore()
  const existing = manyThreads(45)
  respondWith(existing)
  await store.loadThreads()
  const pending = Promise.withResolvers<{ data: EntitiesMessageThread[] }>()
  deferNextLoad(pending.promise)

  const loading = store.loadMoreThreads()
  assert.equal(store.loadingMoreThreads, true)
  store.unreadOnly = true
  await store.loadThreads()
  pending.resolve({ data: existing.slice(0, 20) })
  await loading

  assert.equal(store.threads.length, 20)
  assert.equal(store.loadingMoreThreads, false)
  await store.loadMoreThreads()
  assert.equal(store.threads.length, 40)
})

test('a cold deep link resolves an older conversation independently of page one', async () => {
  const { store, respondWith, respondToLookup, calls } = setupStore()
  const rows = manyThreads(65)
  const requested = {
    ...thread('page-60', 0),
    contact: '+18005550060',
    contact_details: contact('Older contact', ['+18005550060']),
  }
  respondWith(rows)
  respondToLookup(requested)
  store.setThreadId(requested.id)

  await store.fetchThread(requested.id)
  await store.loadThreads()
  store.setThreadId(requested.id)

  assert.equal(store.threads.length, 20)
  assert.equal(store.currentThread?.id, requested.id)
  assert.equal(store.currentThread.contact_details?.name, 'Older contact')
  await store.loadThreadMessages(requested.id)
  assert.equal(calls.at(-1)?.params?.contact, requested.contact)
  assert.equal(
    calls.filter((call) => call.path === '/v1/message-threads').length,
    1,
  )
})

test('individual lookup preserves a real 404 instead of searching every page', async () => {
  const { store, calls } = setupStore()

  await assert.rejects(store.fetchThread('missing'), { status: 404 })

  assert.equal(calls.length, 1)
  assert.equal(calls[0]?.path, '/v1/message-threads/missing')
})

test('a successfully fetched conversation remains selectable independently of list metadata', async () => {
  const { store, respondWith, respondToLookup } = setupStore()
  respondWith(manyThreads(19))
  const requested = thread('directly-requested', 0)
  respondToLookup(requested)
  await store.loadThreads()
  assert.equal(store.hasMoreThreads, false)

  await store.fetchThread(requested.id)
  store.setThreadId(requested.id)

  assert.equal(store.currentThread?.id, requested.id)
  assert.equal(store.threads.length, 19)
})

test('resetting the session cancels an older individual lookup', async () => {
  const { store, deferLookup } = setupStore()
  const pending = Promise.withResolvers<{ data: EntitiesMessageThread }>()
  deferLookup(pending.promise)
  const loading = store.fetchThread('old-session')

  store.resetState()
  pending.resolve({ data: thread('old-session', 0) })

  await assert.rejects(loading, { name: 'AbortError' })
  store.unreadOnly = true
  store.setThreadId('old-session')
  assert.equal(store.currentThread, null)
})