import test from 'node:test'; import assert from 'node:assert/strict'; import { createStore } from '../src/store.js'; import { createNetworkSynchronizer, validateMessageCursor } from '../src/network-sync.js'; import { createAiService } from '../src/ai-service.js'; const tid = '11111111-1111-1111-1111-111111111111', oid = '22222222-2222-2222-2222-222222222222'; const bearer = tenant => `Bearer header.${Buffer.from(JSON.stringify({ tid: tenant, oid, exp: 2200000000 })).toString('base64url')}.signature`; const url = id => `https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/conversations/${encodeURIComponent(id)}/messages?pageSize=200`; function payload(chatId, ids = ['m1']) { return { tenantId: tid, messages: ids.map(id => ({ id, conversationid: chatId, conversationLink: url(chatId).split('/messages')[0], type: 'Message', messagetype: 'RichText/Html', content: `

Message ${id}

`, version: '1788850000000', imdisplayname: 'Test author', originalarrivaltime: '2026-09-08T01:00:00Z' })), _metadata: { lastCompleteSegmentStartTime: 1788850000000, lastCompleteSegmentEndTime: 1788850000000, syncState: url(chatId) + '&syncState=opaque-next&startTime=1788850000000' } }; } const entry = (chatId, tenant = tid) => ({ request: { method: 'GET', url: url(chatId), headers: [{ name: 'Authorization', value: bearer(tenant) }] }, response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(payload(chatId)) } } }); const har = (...entries) => ({ log: { entries } }); test('canonical participant names resolve locally for emoji and self messages even when the optional name API rejects credentials', async () => { const store=createStore(':memory:'), peer='33333333-3333-3333-3333-333333333333'; const accountId=`web-api:${tid}:${oid}`, chat=`19:${oid}_${peer}@unq.gbl.spaces`; const body=payload(chat,['peer-emoji','self-message']); for(const [index,id] of [peer,oid].entries()) { body.messages[index].from=`https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/contacts/${encodeURIComponent(`8:orgid:${id}`)}`; body.messages[index].imdisplayname=index?'Fictional self':'Fictional colleague'; body.messages[index].content=index?'

My reply

':'🔥'; } const capture=entry(chat); capture.response.content.text=JSON.stringify(body); const sync=createNetworkSynchronizer({har:har(capture),store,fetch:async raw=>new URL(raw).pathname.endsWith('/messages')?Response.json(body):new Response('',{status:401})}); try { const first=await sync.runOnce(); assert.equal(first.ok,true); assert.equal(first.chatMetadata.errors[0].status,401); const messages=store.listRecords({kind:'message',accountId}).items; assert.equal(messages.length,2); assert.ok(messages.every(item=>item.chatTitle==='Fictional colleague')); assert.equal(messages.find(item=>item.raw.messageId==='peer-emoji').text,'🔥'); const baseline=messages.map(item=>({id:item.id,hash:store.getRecordByIdentity(item).hash,raw:item.raw,versions:store.getRecord(item.id).versions})); const query=createAiService({store}), found=query.searchMessages({q:'Fictional colleague',accountId,chatId:chat,from:'2026-09-08T00:00:00Z',to:'2026-09-09T00:00:00Z'}); assert.equal(found.items.length,2); assert.ok(found.items.every(item=>item.title==='Fictional colleague'&&item.isDirect===null)); assert.equal(found.items.find(item=>item.author==='Fictional self').text,'My reply'); assert.equal((await sync.runOnce()).changed,0); for(const before of baseline) { const after=store.getRecord(before.id); assert.equal(store.getRecordByIdentity(after).hash,before.hash); assert.deepEqual(after.raw,before.raw); assert.deepEqual(after.versions,before.versions); } } finally {store.close();} }); test('observed conversation details enrich an existing message and MCP name search without rewriting message history', async () => { const store = createStore(':memory:'), chat = '19:fictional-group@thread.v2', requests = []; const captured = har(entry(chat)); let metadataCalls = 0; const sync = createNetworkSynchronizer({ har: captured, store, fetch: async raw => { requests.push(raw); if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(chat)); metadataCalls++; return Response.json({ type: 'Conversation', id: chat, version: 1788850000000, properties: { ignoredPrivate: 'do-not-save' }, threadProperties: { topic: 'Fictional delivery group', threadType: 'chat', version: '1788850000000' }, lastMessage: { content: 'do-not-copy-this-body' }, messages: url(chat) }); } }); try { const first = await sync.runOnce(); assert.equal(first.ok, true); assert.equal(first.coverage.chatListRequests, 0); assert.equal(first.chatMetadata.changed, 1); assert.equal(metadataCalls, 1); const saved = store.listRecords({ kind: 'message' }).items[0], before = store.getRecordByIdentity(saved); assert.equal(saved.title, '聊天消息'); assert.equal(saved.chatTitle, 'Fictional delivery group'); assert.equal(saved.senderName, 'Test author'); assert.equal(store.getRecord(saved.id).versions.length, 1); const query = createAiService({ store }), search = query.searchMessages({ q: 'Fictional delivery group' }); assert.equal(search.items.length, 1); assert.equal(search.items[0].title, 'Fictional delivery group'); const chatRecord = store.listRecords({ kind: 'chat' }).items[0]; assert.doesNotMatch(JSON.stringify(chatRecord), /do-not-save|do-not-copy-this-body/); await sync.runOnce(); assert.equal(metadataCalls, 1); assert.equal(store.getRecordByIdentity(saved).hash, before.hash); assert.equal(store.getRecord(saved.id).versions.length, 1); assert.equal(store.getRecord(saved.id).versions[0].title, '聊天消息'); assert.equal(store.getRecord(chatRecord.id).versions.length, 1); assert.ok(requests.every(request => new URL(request).origin === 'https://teams.cloud.microsoft')); } finally { store.close(); } }); test('metadata failures and limited metadata slots preserve message polling and its total request budget', async () => { const store = createStore(':memory:'), chats = ['19:first@thread.v2', '19:second@thread.v2', '19:third@thread.v2']; const requests = []; const sync = createNetworkSynchronizer({ har: har(...chats.map(chat => entry(chat))), store, maxRequests: 2, fetch: async raw => { requests.push(raw); const path = new URL(raw).pathname; if (!path.endsWith('/messages')) return new Response('', { status: 403 }); const chat = decodeURIComponent(path.split('/conversations/')[1].split('/messages')[0]); return Response.json(payload(chat)); } }); try { const first = await sync.runOnce(); assert.equal(first.ok, true); assert.equal(first.requests, 2); assert.equal(first.records, 1); assert.equal(first.chatMetadata.requests, 1); assert.equal(first.chatMetadata.errors[0].status, 403); assert.equal(store.listRecords({ kind: 'message' }).total, 1); const second = await sync.runOnce(); assert.equal(second.ok, true); assert.ok(second.requests <= 2); assert.equal(store.listRecords({ kind: 'message' }).total, 2); assert.equal(requests.filter(raw => !new URL(raw).pathname.endsWith('/messages')).length, 2); } finally { store.close(); } }); test('earlier captured pages supply metadata links after an empty increment while the latest credentials and polling template remain in use', async () => { const store = createStore(':memory:'), chat = '19:captured-before-empty@thread.v2'; const earlier = entry(chat), latest = entry(chat), requests = []; const renewed = `Bearer header.${Buffer.from(JSON.stringify({ tid, oid, exp: 2200000100 })).toString('base64url')}.renewed-signature`; latest.request.url += '&startTime=1788850000001'; latest.request.headers = [{ name: 'Authorization', value: renewed }]; latest.response.content.text = JSON.stringify(payload(chat, [])); const sync = createNetworkSynchronizer({ har: har(earlier, latest), store, maxRequests: 2, fetch: async (raw, options) => { requests.push({ url: raw, authorization: options.headers.Authorization }); if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(chat, [])); return Response.json({ type: 'Conversation', id: chat, version: 1788850000000, threadProperties: { topic: 'Fictional captured group', threadType: 'chat', version: '1788850000000' } }); } }); try { assert.equal(sync.coverage().messages, 1); assert.equal(sync.coverage().chatMetadata.discovered, 1); const first = await sync.runOnce(); assert.equal(first.ok, true); assert.equal(first.records, 0); assert.equal(first.chatMetadata.changed, 1); assert.equal(requests.filter(item => new URL(item.url).pathname.endsWith('/messages')).length, 1); assert.equal(requests[0].url, latest.request.url); assert.ok(requests.every(item => item.authorization === renewed)); assert.equal(store.listRecords({ kind: 'message' }).total, 0); assert.equal(store.listRecords({ kind: 'chat' }).items[0].title, 'Fictional captured group'); } finally { store.close(); } }); test('failed, mismatched, or differently originated earlier pages cannot seed metadata for an empty latest capture', async () => { const chat = '19:captured-isolation@thread.v2', other = '19:another-conversation@thread.v2'; for (const alter of [ earlier => { earlier.response.status = 500; }, earlier => { earlier.response.content.text = JSON.stringify(payload(other)); }, earlier => { const body = payload(chat); body.messages[0].conversationLink = url(other).split('/messages')[0]; earlier.response.content.text = JSON.stringify(body); }, earlier => { earlier.request.url = earlier.request.url.replace('teams.cloud.microsoft', 'teams.microsoft.com'); }, ]) { const store = createStore(':memory:'), earlier = entry(chat), latest = entry(chat), requests = []; alter(earlier); latest.response.content.text = JSON.stringify(payload(chat, [])); const sync = createNetworkSynchronizer({ har: har(earlier, latest), store, fetch: async raw => { requests.push(raw); return Response.json(payload(chat, [])); } }); try { assert.equal(sync.coverage().messages, 1); assert.equal(sync.coverage().chatMetadata.discovered, 0); const result = await sync.runOnce(); assert.equal(result.ok, true); assert.equal(result.chatMetadata.requests, 0); assert.equal(requests.length, 1); assert.equal(store.listRecords({ kind: 'chat' }).total, 0); } finally { store.close(); } } }); test('captured metadata links for the same conversation stay within their authenticated account', async () => { const store = createStore(':memory:'), chat = '19:account-scoped-capture@thread.v2', otherTenant = '33333333-3333-3333-3333-333333333333'; const other = entry(chat, otherTenant), latest = entry(chat), metadataCredentials = []; latest.response.content.text = JSON.stringify(payload(chat, [])); const sync = createNetworkSynchronizer({ har: har(other, latest), store, fetch: async (raw, options) => { if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(chat, [])); metadataCredentials.push(options.headers.Authorization); return Response.json({ type: 'Conversation', id: chat, version: 1788850000000, threadProperties: { topic: 'Fictional separate account', threadType: 'chat', version: '1788850000000' } }); } }); try { const result = await sync.runOnce(); assert.equal(result.ok, true); assert.equal(result.chatMetadata.changed, 1); assert.deepEqual(metadataCredentials, [bearer(otherTenant)]); assert.equal(store.listRecords({ kind: 'chat', accountId: `web-api:${tid}:${oid}` }).total, 0); assert.equal(store.listRecords({ kind: 'chat', accountId: `web-api:${otherTenant}:${oid}` }).total, 1); } finally { store.close(); } }); test('verified history observations can supply metadata after empty captured and live message responses', async () => { const store = createStore(':memory:'), chat = '19:history-metadata@thread.v2', capture = entry(chat); capture.response.content.text = JSON.stringify(payload(chat, [])); const sync = createNetworkSynchronizer({ har: har(capture), store, fetch: async raw => { if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(chat, [])); return Response.json({ type: 'Conversation', id: chat, version: 1788850000000, threadProperties: { topic: 'Fictional history group', threadType: 'chat', version: '1788850000000' } }); } }); try { assert.equal(sync.coverage().chatMetadata.discovered, 0); assert.equal(sync.observeChatMetadata({ accountId: `web-api:${tid}:${oid}`, chatId: chat, requestUrl: url(chat) + '&startTime=0', headers: { Authorization: bearer(tid) } }, payload(chat)), true); const result = await sync.runOnce(); assert.equal(result.ok, true); assert.equal(result.chatMetadata.changed, 1); assert.equal(store.listRecords({ kind: 'chat' }).items[0].title, 'Fictional history group'); assert.equal(store.listRecords({ kind: 'message' }).total, 0); } finally { store.close(); } }); test('history metadata observations cannot replace current credentials or borrow them for another request scope', async () => { const store = createStore(':memory:'), chat = '19:history-renewed-credentials@thread.v2', latest = entry(chat), requests = []; const renewed = `Bearer header.${Buffer.from(JSON.stringify({ tid, oid, exp: 2200000100 })).toString('base64url')}.renewed-signature`; latest.request.headers = [{ name: 'Authorization', value: renewed }]; latest.response.content.text = JSON.stringify(payload(chat, [])); const observation = { accountId: `web-api:${tid}:${oid}`, chatId: chat, requestUrl: url(chat) + '&startTime=0', headers: { Authorization: bearer(tid) } }; const sync = createNetworkSynchronizer({ har: har(latest), store, fetch: async (raw, options) => { requests.push({ url: raw, authorization: options.headers.Authorization }); if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(chat, [])); return Response.json({ type: 'Conversation', id: chat, version: 1788850000000, threadProperties: { topic: 'Fictional renewed group', threadType: 'chat', version: '1788850000000' } }); } }); try { for (const requestUrl of [observation.requestUrl.replace('teams.cloud.microsoft', 'teams.microsoft.com'), observation.requestUrl.replace('/apac/', '/emea/'), url('19:other-history-chat@thread.v2') + '&startTime=0']) { assert.equal(sync.observeChatMetadata({ ...observation, requestUrl }, payload(chat)), false); assert.equal(sync.coverage().chatMetadata.discovered, 0); } assert.equal(sync.observeChatMetadata(observation, payload(chat)), true); const result = await sync.runOnce(); assert.equal(result.chatMetadata.changed, 1); assert.equal(requests.length, 2); assert.ok(requests.every(item => item.authorization === renewed)); assert.equal(store.listRecords({ kind: 'chat' }).items[0].title, 'Fictional renewed group'); } finally { store.close(); } }); test('a verified history-only conversation can supply its own bound metadata observation', async () => { const store = createStore(':memory:'), liveChat = '19:live-scope@thread.v2', historyChat = '19:history-only-scope@thread.v2', latest = entry(liveChat); latest.response.content.text = JSON.stringify(payload(liveChat, [])); const sync = createNetworkSynchronizer({ har: har(latest), store, fetch: async raw => { if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(liveChat, [])); assert.equal(raw, url(historyChat).split('/messages')[0]); return Response.json({ type: 'Conversation', id: historyChat, version: 1788850000000, threadProperties: { topic: 'Fictional history-only group', threadType: 'chat', version: '1788850000000' } }); } }); try { assert.equal(sync.observeChatMetadata({ accountId: `web-api:${tid}:${oid}`, chatId: historyChat, requestUrl: url(historyChat) + '&startTime=0', headers: { Authorization: bearer(tid) } }, payload(historyChat)), true); const result = await sync.runOnce(); assert.equal(result.chatMetadata.changed, 1); assert.equal(sync.coverage().messages, 1); assert.equal(store.listRecords({ kind: 'chat' }).items[0].externalId, historyChat); } finally { store.close(); } }); test('API polling writes chat-scoped records and commits validated cursors; subsequent zero-change polls do not duplicate', async () => { const store = createStore(':memory:'); let round = 0; const requested = []; try { const sync = createNetworkSynchronizer({ har: har(entry('chat-a'), entry('chat-b')), store, fetch: async (raw, options) => { requested.push(raw); assert.equal(options.redirect, 'manual'); const chat = decodeURIComponent(new URL(raw).pathname.split('/conversations/')[1].split('/messages')[0]); return Response.json(payload(chat, round ? [] : ['m1'])); } }); const first = await sync.runOnce(); assert.equal(first.ok, true); assert.equal(first.changed, 2); assert.equal(store.listRecords({ source: 'web-api', kind: 'message' }).total, 2); assert.equal(store.stats().versions, 2); round++; const second = await sync.runOnce(); assert.equal(second.ok, true); assert.equal(second.changed, 0); assert.ok(requested.slice(2).every(raw => raw.includes('syncState=opaque-next'))); assert.doesNotMatch(JSON.stringify(second), /signature|opaque-next|Message m1/); } finally { store.close(); } }); test('failed normalization and cross-origin continuations do not write records or advance cursors', async () => { const store = createStore(':memory:'); const requested = []; let invalid = true; try { const sync = createNetworkSynchronizer({ har: har(entry('chat-a')), store, fetch: async raw => { requested.push(raw); const body = payload('chat-a'); if (invalid) body._metadata.syncState = 'https://example.com/private'; return Response.json(body); } }); assert.equal((await sync.runOnce()).ok, false); assert.equal(store.stats().total, 0); invalid = false; assert.equal((await sync.runOnce()).changed, 1); assert.equal(requested[0], requested[1]); } finally { store.close(); } assert.throws(() => validateMessageCursor(url('chat-b'), url('chat-a'))); assert.throws(() => validateMessageCursor(url('chat-a') + '&access_token=secret', url('chat-a'))); }); test('the observed 48 activity stream is excluded from chat monitoring and persistence', async () => { const store = createStore(':memory:'), requested = []; try { const sync = createNetworkSynchronizer({ har: har(entry('48:notifications'), entry('chat-a')), store, fetch: async raw => { requested.push(raw); return Response.json(payload('chat-a')); } }); const result = await sync.runOnce(); assert.equal(result.ok, true); assert.equal(result.coverage.messages, 1); assert.equal(result.coverage.skipped.activityStream, 1); assert.equal(requested.length, 1); assert.ok(requested[0].includes('chat-a')); } finally { store.close(); } }); test('authentication failure pauses requests; federated chat tenant differs from the signed-in user without changing local ownership', async () => { const store = createStore(':memory:'); let calls = 0; try { const sync = createNetworkSynchronizer({ har: har(entry('chat-a'), entry('chat-b')), store, fetch: async () => { calls++; return new Response('', { status: 401 }); } }); const failed = await sync.runOnce(); assert.equal(failed.authRequired, true); assert.equal(failed.noUsableRequests, true); assert.equal(calls, 2); assert.equal(store.stats().total, 0); const mismatch = createNetworkSynchronizer({ har: har(entry('chat-a')), store, fetch: async () => Response.json({ ...payload('chat-a'), tenantId: 'wrong-tenant' }) }); assert.equal((await mismatch.runOnce()).ok, true); assert.equal(store.stats().total, 1); assert.equal(store.listRecords({ kind: 'message' }).items[0].accountId, `web-api:${tid}:${oid}`); } finally { store.close(); } }); test('calendar summary updates preserve previously collected details and repeated snapshots remain stable', async () => { const store = createStore(':memory:'); let summary = false; const calendar = { value: [{ id: 'event-a', subject: 'Meeting', body: { contentType: 'text', content: 'Detailed agenda' }, lastModifiedDateTime: '2026-09-07T05:00:00Z', start: { dateTime: '2026-09-08T01:00:00', timeZone: 'UTC' }, end: { dateTime: '2026-09-08T02:00:00', timeZone: 'UTC' } }] }; const capture = { request: { method: 'GET', url: 'https://graph.microsoft.com/v1.0/me/events', headers: [{ name: 'Authorization', value: bearer(tid) }] }, response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(calendar) } } }; try { const sync = createNetworkSynchronizer({ har: har(capture), store, fetch: async () => { const body = structuredClone(calendar); if (summary) { delete body.value[0].body; delete body.value[0].lastModifiedDateTime; } return Response.json(body); } }); assert.equal((await sync.runOnce()).changed, 1); summary = true; await sync.runOnce(); let record = store.listRecords({ kind: 'event' }).items[0]; assert.equal(record.text, 'Detailed agenda'); assert.equal(record.raw.detailLevel, 'detail'); assert.equal(record.updatedAt, '2026-09-07T05:00:00.000Z'); assert.equal((await sync.runOnce()).changed, 0); summary = false; assert.equal((await sync.runOnce()).changed, 0); } finally { store.close(); } }); test('per-round limits rotate among captured chats and overlapping calls share a single pass', async () => { const store = createStore(':memory:'); const requested = []; let release; try { const sync = createNetworkSynchronizer({ har: har(entry('chat-a'), entry('chat-b')), store, maxRequests: 1, fetch: async raw => { requested.push(raw); if (!release) await new Promise(resolve => { release = resolve; }); const id = raw.includes('chat-a') ? 'chat-a' : 'chat-b'; return Response.json(payload(id)); } }); const first = sync.runOnce(), concurrent = sync.runOnce(); await new Promise(resolve => setImmediate(resolve)); release(); await Promise.all([first, concurrent]); assert.equal(requested.length, 1); await sync.runOnce(); assert.equal(requested.length, 2); assert.notEqual(requested[0], requested[1]); } finally { store.close(); } }); function listEntry(tenant = tid) { const envelope = { chats: [], teams: [], users: [], channels: [], conversationFolders: {}, metadata: { syncToken: 'list-cursor', isPartialData: false, hasMoreChats: false } }; return { request: { method: 'GET', url: 'https://teams.cloud.microsoft/api/csa/apac/api/v3/teams/users/me/updates', headers: [{ name: 'Authorization', value: bearer(tenant) }] }, response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(envelope) } } }; } test('missing roster names use the same-account peer and never replace the chat title with the sender or stale placeholder', async () => { const store=createStore(':memory:'), accountId=`web-api:${tid}:${oid}`, peer='33333333-3333-3333-3333-333333333333'; try { store.upsertRecord({source:'web-api',accountId,kind:'chat',externalId:'chat-a',title:'聊天',raw:{isOneOnOne:true,titleSource:'placeholder'}}); store.upsertRecord({source:'web-api',accountId,kind:'message',externalId:'fictional-local-peer',parentId:'chat-a',title:'聊天',text:'Fictional earlier message', occurredAt:'2026-09-08T00:00:00Z',raw:{senderId:peer,author:'Fictional peer'}},{ingestion:'history'}); const sync=createNetworkSynchronizer({har:har(entry('chat-a'),listEntry()),store,fetch:async raw=>{ if(raw.includes('/updates')) { const body=JSON.parse(listEntry().response.content.text); body.chats=[{id:'chat-a',title:'',threadType:'chat',isOneOnOne:true,members:[{objectId:oid},{objectId:peer}]}]; return Response.json(body); } const body=payload('chat-a'); body.messages[0].from=`https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/contacts/${encodeURIComponent(`8:orgid:${oid}`)}`; body.messages[0].imdisplayname='Fictional self';return Response.json(body); }}); assert.equal((await sync.runOnce()).ok,true); const named=store.getRecordByIdentity({source:'web-api',accountId,kind:'chat',externalId:'chat-a'}); assert.equal(named.title,'Fictional peer');assert.equal(named.raw.titleSource,'message-author'); const saved=store.listRecords({kind:'message'}).items.find(record=>record.raw.messageId==='m1'); assert.equal(saved.title,'Fictional peer');assert.equal(saved.raw.author,'Fictional self'); const versions=store.stats().versions; assert.equal((await sync.runOnce()).changed,0);assert.equal(store.stats().versions,versions); assert.equal(store.getRecord(named.id).title,'Fictional peer'); } finally {store.close();} }); test('discovered chat identities and committed cursors survive restart even when the next list response has no changes', async () => { const store = createStore(':memory:'); let initial = true; const requested = []; const captured = har(entry('chat-a'), listEntry()); const fetch = async raw => { if (raw.includes('/updates')) { const body = JSON.parse(listEntry().response.content.text); if (initial) body.chats = [{ id: 'chat-b', title: 'Chat b', threadType: 'chat' }]; return Response.json(body); } requested.push(raw); const chatId = decodeURIComponent(new URL(raw).pathname.split('/conversations/')[1].split('/messages')[0]); return Response.json(payload(chatId)); }; try { assert.equal((await createNetworkSynchronizer({ har: captured, store, fetch }).runOnce()).ok, true); initial = false; requested.length = 0; const restarted = createNetworkSynchronizer({ har: captured, store, fetch }); assert.equal(restarted.coverage().messages, 2); assert.equal((await restarted.runOnce()).ok, true); assert.ok(requested.find(raw => raw.includes('chat-b')).includes('syncState=opaque-next')); } finally { store.close(); } }); test('separate list cursor rotates across accounts even when every message plan fits in one pass', async () => { const store = createStore(':memory:'), other = '33333333-3333-3333-3333-333333333333', lists = []; try { const sync = createNetworkSynchronizer({ har: har(entry('chat-a'), entry('chat-b', other), listEntry(), listEntry(other)), store, fetch: async (raw, options) => { if (raw.includes('/updates')) { lists.push(new Headers(options.headers).get('authorization')); return Response.json(JSON.parse(listEntry().response.content.text)); } return Response.json(payload(raw.includes('chat-a') ? 'chat-a' : 'chat-b')); } }); await sync.runOnce(); await sync.runOnce(); assert.deepEqual(lists, [bearer(tid), bearer(other)]); } finally { store.close(); } }); test('one expired resource pauses only that request while still-valid captured requests continue', async () => { const store = createStore(':memory:'); let expiredCalls = 0, validCalls = 0; try { const sync = createNetworkSynchronizer({ har: har(entry('chat-a'), entry('chat-b')), store, fetch: async raw => { if (raw.includes('chat-a')) { expiredCalls++; return new Response('', { status: 401 }); } validCalls++; return Response.json(payload('chat-b')); } }); const first = await sync.runOnce(); assert.equal(first.authRequired, true); assert.equal(first.noUsableRequests, false); assert.equal(first.successful, 1); await sync.runOnce(); assert.equal(expiredCalls, 1); assert.equal(validCalls, 2); assert.equal(store.listRecords({ kind: 'message' }).total, 1); } finally { store.close(); } });