network-sync.test.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import test from 'node:test';
  2. import assert from 'node:assert/strict';
  3. import { createStore } from '../src/store.js';
  4. import { createNetworkSynchronizer, validateMessageCursor } from '../src/network-sync.js';
  5. import { createAiService } from '../src/ai-service.js';
  6. const tid = '11111111-1111-1111-1111-111111111111', oid = '22222222-2222-2222-2222-222222222222';
  7. const bearer = tenant => `Bearer header.${Buffer.from(JSON.stringify({ tid: tenant, oid, exp: 2200000000 })).toString('base64url')}.signature`;
  8. const url = id => `https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/conversations/${encodeURIComponent(id)}/messages?pageSize=200`;
  9. function payload(chatId, ids = ['m1']) {
  10. return { tenantId: tid, messages: ids.map(id => ({ id, conversationid: chatId,
  11. conversationLink: url(chatId).split('/messages')[0], type: 'Message', messagetype: 'RichText/Html',
  12. content: `<p>Message ${id}</p>`, version: '1788850000000', imdisplayname: 'Test author',
  13. originalarrivaltime: '2026-09-08T01:00:00Z' })),
  14. _metadata: { lastCompleteSegmentStartTime: 1788850000000, lastCompleteSegmentEndTime: 1788850000000,
  15. syncState: url(chatId) + '&syncState=opaque-next&startTime=1788850000000' } };
  16. }
  17. const entry = (chatId, tenant = tid) => ({ request: { method: 'GET', url: url(chatId), headers: [{ name: 'Authorization', value: bearer(tenant) }] },
  18. response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(payload(chatId)) } } });
  19. const har = (...entries) => ({ log: { entries } });
  20. test('canonical participant names resolve locally for emoji and self messages even when the optional name API rejects credentials', async () => {
  21. const store=createStore(':memory:'), peer='33333333-3333-3333-3333-333333333333';
  22. const accountId=`web-api:${tid}:${oid}`, chat=`19:${oid}_${peer}@unq.gbl.spaces`;
  23. const body=payload(chat,['peer-emoji','self-message']);
  24. for(const [index,id] of [peer,oid].entries()) {
  25. body.messages[index].from=`https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/contacts/${encodeURIComponent(`8:orgid:${id}`)}`;
  26. body.messages[index].imdisplayname=index?'Fictional self':'Fictional colleague';
  27. body.messages[index].content=index?'<p>My reply</p>':'<img alt="🔥">';
  28. }
  29. const capture=entry(chat); capture.response.content.text=JSON.stringify(body);
  30. const sync=createNetworkSynchronizer({har:har(capture),store,fetch:async raw=>new URL(raw).pathname.endsWith('/messages')?Response.json(body):new Response('',{status:401})});
  31. try {
  32. const first=await sync.runOnce();
  33. assert.equal(first.ok,true); assert.equal(first.chatMetadata.errors[0].status,401);
  34. const messages=store.listRecords({kind:'message',accountId}).items;
  35. assert.equal(messages.length,2); assert.ok(messages.every(item=>item.chatTitle==='Fictional colleague'));
  36. assert.equal(messages.find(item=>item.raw.messageId==='peer-emoji').text,'🔥');
  37. const baseline=messages.map(item=>({id:item.id,hash:store.getRecordByIdentity(item).hash,raw:item.raw,versions:store.getRecord(item.id).versions}));
  38. 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'});
  39. assert.equal(found.items.length,2); assert.ok(found.items.every(item=>item.title==='Fictional colleague'&&item.isDirect===null));
  40. assert.equal(found.items.find(item=>item.author==='Fictional self').text,'My reply');
  41. assert.equal((await sync.runOnce()).changed,0);
  42. for(const before of baseline) {
  43. const after=store.getRecord(before.id);
  44. assert.equal(store.getRecordByIdentity(after).hash,before.hash); assert.deepEqual(after.raw,before.raw); assert.deepEqual(after.versions,before.versions);
  45. }
  46. } finally {store.close();}
  47. });
  48. test('observed conversation details enrich an existing message and MCP name search without rewriting message history', async () => {
  49. const store = createStore(':memory:'), chat = '19:fictional-group@thread.v2', requests = [];
  50. const captured = har(entry(chat)); let metadataCalls = 0;
  51. const sync = createNetworkSynchronizer({ har: captured, store, fetch: async raw => {
  52. requests.push(raw);
  53. if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(chat));
  54. metadataCalls++;
  55. return Response.json({ type: 'Conversation', id: chat, version: 1788850000000,
  56. properties: { ignoredPrivate: 'do-not-save' }, threadProperties: { topic: 'Fictional delivery group', threadType: 'chat', version: '1788850000000' },
  57. lastMessage: { content: 'do-not-copy-this-body' }, messages: url(chat) });
  58. } });
  59. try {
  60. const first = await sync.runOnce(); assert.equal(first.ok, true); assert.equal(first.coverage.chatListRequests, 0);
  61. assert.equal(first.chatMetadata.changed, 1); assert.equal(metadataCalls, 1);
  62. const saved = store.listRecords({ kind: 'message' }).items[0], before = store.getRecordByIdentity(saved);
  63. assert.equal(saved.title, '聊天消息'); assert.equal(saved.chatTitle, 'Fictional delivery group');
  64. assert.equal(saved.senderName, 'Test author'); assert.equal(store.getRecord(saved.id).versions.length, 1);
  65. const query = createAiService({ store }), search = query.searchMessages({ q: 'Fictional delivery group' });
  66. assert.equal(search.items.length, 1); assert.equal(search.items[0].title, 'Fictional delivery group');
  67. const chatRecord = store.listRecords({ kind: 'chat' }).items[0];
  68. assert.doesNotMatch(JSON.stringify(chatRecord), /do-not-save|do-not-copy-this-body/);
  69. await sync.runOnce(); assert.equal(metadataCalls, 1);
  70. assert.equal(store.getRecordByIdentity(saved).hash, before.hash); assert.equal(store.getRecord(saved.id).versions.length, 1);
  71. assert.equal(store.getRecord(saved.id).versions[0].title, '聊天消息');
  72. assert.equal(store.getRecord(chatRecord.id).versions.length, 1);
  73. assert.ok(requests.every(request => new URL(request).origin === 'https://teams.cloud.microsoft'));
  74. } finally { store.close(); }
  75. });
  76. test('metadata failures and limited metadata slots preserve message polling and its total request budget', async () => {
  77. const store = createStore(':memory:'), chats = ['19:first@thread.v2', '19:second@thread.v2', '19:third@thread.v2'];
  78. const requests = [];
  79. const sync = createNetworkSynchronizer({ har: har(...chats.map(chat => entry(chat))), store, maxRequests: 2, fetch: async raw => {
  80. requests.push(raw); const path = new URL(raw).pathname;
  81. if (!path.endsWith('/messages')) return new Response('', { status: 403 });
  82. const chat = decodeURIComponent(path.split('/conversations/')[1].split('/messages')[0]); return Response.json(payload(chat));
  83. } });
  84. try {
  85. const first = await sync.runOnce();
  86. assert.equal(first.ok, true); assert.equal(first.requests, 2); assert.equal(first.records, 1);
  87. assert.equal(first.chatMetadata.requests, 1); assert.equal(first.chatMetadata.errors[0].status, 403);
  88. assert.equal(store.listRecords({ kind: 'message' }).total, 1);
  89. const second = await sync.runOnce(); assert.equal(second.ok, true); assert.ok(second.requests <= 2);
  90. assert.equal(store.listRecords({ kind: 'message' }).total, 2);
  91. assert.equal(requests.filter(raw => !new URL(raw).pathname.endsWith('/messages')).length, 2);
  92. } finally { store.close(); }
  93. });
  94. test('earlier captured pages supply metadata links after an empty increment while the latest credentials and polling template remain in use', async () => {
  95. const store = createStore(':memory:'), chat = '19:captured-before-empty@thread.v2';
  96. const earlier = entry(chat), latest = entry(chat), requests = [];
  97. const renewed = `Bearer header.${Buffer.from(JSON.stringify({ tid, oid, exp: 2200000100 })).toString('base64url')}.renewed-signature`;
  98. latest.request.url += '&startTime=1788850000001';
  99. latest.request.headers = [{ name: 'Authorization', value: renewed }];
  100. latest.response.content.text = JSON.stringify(payload(chat, []));
  101. const sync = createNetworkSynchronizer({ har: har(earlier, latest), store, maxRequests: 2, fetch: async (raw, options) => {
  102. requests.push({ url: raw, authorization: options.headers.Authorization });
  103. if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(chat, []));
  104. return Response.json({ type: 'Conversation', id: chat, version: 1788850000000,
  105. threadProperties: { topic: 'Fictional captured group', threadType: 'chat', version: '1788850000000' } });
  106. } });
  107. try {
  108. assert.equal(sync.coverage().messages, 1); assert.equal(sync.coverage().chatMetadata.discovered, 1);
  109. const first = await sync.runOnce();
  110. assert.equal(first.ok, true); assert.equal(first.records, 0); assert.equal(first.chatMetadata.changed, 1);
  111. assert.equal(requests.filter(item => new URL(item.url).pathname.endsWith('/messages')).length, 1);
  112. assert.equal(requests[0].url, latest.request.url);
  113. assert.ok(requests.every(item => item.authorization === renewed));
  114. assert.equal(store.listRecords({ kind: 'message' }).total, 0);
  115. assert.equal(store.listRecords({ kind: 'chat' }).items[0].title, 'Fictional captured group');
  116. } finally { store.close(); }
  117. });
  118. test('failed, mismatched, or differently originated earlier pages cannot seed metadata for an empty latest capture', async () => {
  119. const chat = '19:captured-isolation@thread.v2', other = '19:another-conversation@thread.v2';
  120. for (const alter of [
  121. earlier => { earlier.response.status = 500; },
  122. earlier => { earlier.response.content.text = JSON.stringify(payload(other)); },
  123. earlier => { const body = payload(chat); body.messages[0].conversationLink = url(other).split('/messages')[0]; earlier.response.content.text = JSON.stringify(body); },
  124. earlier => { earlier.request.url = earlier.request.url.replace('teams.cloud.microsoft', 'teams.microsoft.com'); },
  125. ]) {
  126. const store = createStore(':memory:'), earlier = entry(chat), latest = entry(chat), requests = [];
  127. alter(earlier); latest.response.content.text = JSON.stringify(payload(chat, []));
  128. const sync = createNetworkSynchronizer({ har: har(earlier, latest), store, fetch: async raw => {
  129. requests.push(raw); return Response.json(payload(chat, []));
  130. } });
  131. try {
  132. assert.equal(sync.coverage().messages, 1); assert.equal(sync.coverage().chatMetadata.discovered, 0);
  133. const result = await sync.runOnce(); assert.equal(result.ok, true); assert.equal(result.chatMetadata.requests, 0);
  134. assert.equal(requests.length, 1); assert.equal(store.listRecords({ kind: 'chat' }).total, 0);
  135. } finally { store.close(); }
  136. }
  137. });
  138. test('captured metadata links for the same conversation stay within their authenticated account', async () => {
  139. const store = createStore(':memory:'), chat = '19:account-scoped-capture@thread.v2', otherTenant = '33333333-3333-3333-3333-333333333333';
  140. const other = entry(chat, otherTenant), latest = entry(chat), metadataCredentials = [];
  141. latest.response.content.text = JSON.stringify(payload(chat, []));
  142. const sync = createNetworkSynchronizer({ har: har(other, latest), store, fetch: async (raw, options) => {
  143. if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(chat, []));
  144. metadataCredentials.push(options.headers.Authorization);
  145. return Response.json({ type: 'Conversation', id: chat, version: 1788850000000,
  146. threadProperties: { topic: 'Fictional separate account', threadType: 'chat', version: '1788850000000' } });
  147. } });
  148. try {
  149. const result = await sync.runOnce(); assert.equal(result.ok, true); assert.equal(result.chatMetadata.changed, 1);
  150. assert.deepEqual(metadataCredentials, [bearer(otherTenant)]);
  151. assert.equal(store.listRecords({ kind: 'chat', accountId: `web-api:${tid}:${oid}` }).total, 0);
  152. assert.equal(store.listRecords({ kind: 'chat', accountId: `web-api:${otherTenant}:${oid}` }).total, 1);
  153. } finally { store.close(); }
  154. });
  155. test('verified history observations can supply metadata after empty captured and live message responses', async () => {
  156. const store = createStore(':memory:'), chat = '19:history-metadata@thread.v2', capture = entry(chat);
  157. capture.response.content.text = JSON.stringify(payload(chat, []));
  158. const sync = createNetworkSynchronizer({ har: har(capture), store, fetch: async raw => {
  159. if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(chat, []));
  160. return Response.json({ type: 'Conversation', id: chat, version: 1788850000000,
  161. threadProperties: { topic: 'Fictional history group', threadType: 'chat', version: '1788850000000' } });
  162. } });
  163. try {
  164. assert.equal(sync.coverage().chatMetadata.discovered, 0);
  165. assert.equal(sync.observeChatMetadata({ accountId: `web-api:${tid}:${oid}`, chatId: chat,
  166. requestUrl: url(chat) + '&startTime=0', headers: { Authorization: bearer(tid) } }, payload(chat)), true);
  167. const result = await sync.runOnce(); assert.equal(result.ok, true); assert.equal(result.chatMetadata.changed, 1);
  168. assert.equal(store.listRecords({ kind: 'chat' }).items[0].title, 'Fictional history group');
  169. assert.equal(store.listRecords({ kind: 'message' }).total, 0);
  170. } finally { store.close(); }
  171. });
  172. test('history metadata observations cannot replace current credentials or borrow them for another request scope', async () => {
  173. const store = createStore(':memory:'), chat = '19:history-renewed-credentials@thread.v2', latest = entry(chat), requests = [];
  174. const renewed = `Bearer header.${Buffer.from(JSON.stringify({ tid, oid, exp: 2200000100 })).toString('base64url')}.renewed-signature`;
  175. latest.request.headers = [{ name: 'Authorization', value: renewed }];
  176. latest.response.content.text = JSON.stringify(payload(chat, []));
  177. const observation = { accountId: `web-api:${tid}:${oid}`, chatId: chat, requestUrl: url(chat) + '&startTime=0',
  178. headers: { Authorization: bearer(tid) } };
  179. const sync = createNetworkSynchronizer({ har: har(latest), store, fetch: async (raw, options) => {
  180. requests.push({ url: raw, authorization: options.headers.Authorization });
  181. if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(chat, []));
  182. return Response.json({ type: 'Conversation', id: chat, version: 1788850000000,
  183. threadProperties: { topic: 'Fictional renewed group', threadType: 'chat', version: '1788850000000' } });
  184. } });
  185. try {
  186. for (const requestUrl of [observation.requestUrl.replace('teams.cloud.microsoft', 'teams.microsoft.com'),
  187. observation.requestUrl.replace('/apac/', '/emea/'), url('19:other-history-chat@thread.v2') + '&startTime=0']) {
  188. assert.equal(sync.observeChatMetadata({ ...observation, requestUrl }, payload(chat)), false);
  189. assert.equal(sync.coverage().chatMetadata.discovered, 0);
  190. }
  191. assert.equal(sync.observeChatMetadata(observation, payload(chat)), true);
  192. const result = await sync.runOnce(); assert.equal(result.chatMetadata.changed, 1);
  193. assert.equal(requests.length, 2); assert.ok(requests.every(item => item.authorization === renewed));
  194. assert.equal(store.listRecords({ kind: 'chat' }).items[0].title, 'Fictional renewed group');
  195. } finally { store.close(); }
  196. });
  197. test('a verified history-only conversation can supply its own bound metadata observation', async () => {
  198. const store = createStore(':memory:'), liveChat = '19:live-scope@thread.v2', historyChat = '19:history-only-scope@thread.v2', latest = entry(liveChat);
  199. latest.response.content.text = JSON.stringify(payload(liveChat, []));
  200. const sync = createNetworkSynchronizer({ har: har(latest), store, fetch: async raw => {
  201. if (new URL(raw).pathname.endsWith('/messages')) return Response.json(payload(liveChat, []));
  202. assert.equal(raw, url(historyChat).split('/messages')[0]);
  203. return Response.json({ type: 'Conversation', id: historyChat, version: 1788850000000,
  204. threadProperties: { topic: 'Fictional history-only group', threadType: 'chat', version: '1788850000000' } });
  205. } });
  206. try {
  207. assert.equal(sync.observeChatMetadata({ accountId: `web-api:${tid}:${oid}`, chatId: historyChat,
  208. requestUrl: url(historyChat) + '&startTime=0', headers: { Authorization: bearer(tid) } }, payload(historyChat)), true);
  209. const result = await sync.runOnce(); assert.equal(result.chatMetadata.changed, 1);
  210. assert.equal(sync.coverage().messages, 1);
  211. assert.equal(store.listRecords({ kind: 'chat' }).items[0].externalId, historyChat);
  212. } finally { store.close(); }
  213. });
  214. test('API polling writes chat-scoped records and commits validated cursors; subsequent zero-change polls do not duplicate', async () => {
  215. const store = createStore(':memory:'); let round = 0; const requested = [];
  216. try {
  217. const sync = createNetworkSynchronizer({ har: har(entry('chat-a'), entry('chat-b')), store,
  218. fetch: async (raw, options) => {
  219. requested.push(raw); assert.equal(options.redirect, 'manual');
  220. const chat = decodeURIComponent(new URL(raw).pathname.split('/conversations/')[1].split('/messages')[0]);
  221. return Response.json(payload(chat, round ? [] : ['m1']));
  222. } });
  223. const first = await sync.runOnce(); assert.equal(first.ok, true); assert.equal(first.changed, 2);
  224. assert.equal(store.listRecords({ source: 'web-api', kind: 'message' }).total, 2); assert.equal(store.stats().versions, 2);
  225. round++; const second = await sync.runOnce(); assert.equal(second.ok, true); assert.equal(second.changed, 0);
  226. assert.ok(requested.slice(2).every(raw => raw.includes('syncState=opaque-next')));
  227. assert.doesNotMatch(JSON.stringify(second), /signature|opaque-next|Message m1/);
  228. } finally { store.close(); }
  229. });
  230. test('failed normalization and cross-origin continuations do not write records or advance cursors', async () => {
  231. const store = createStore(':memory:'); const requested = []; let invalid = true;
  232. try {
  233. const sync = createNetworkSynchronizer({ har: har(entry('chat-a')), store, fetch: async raw => {
  234. requested.push(raw); const body = payload('chat-a'); if (invalid) body._metadata.syncState = 'https://example.com/private'; return Response.json(body);
  235. } });
  236. assert.equal((await sync.runOnce()).ok, false); assert.equal(store.stats().total, 0);
  237. invalid = false; assert.equal((await sync.runOnce()).changed, 1); assert.equal(requested[0], requested[1]);
  238. } finally { store.close(); }
  239. assert.throws(() => validateMessageCursor(url('chat-b'), url('chat-a')));
  240. assert.throws(() => validateMessageCursor(url('chat-a') + '&access_token=secret', url('chat-a')));
  241. });
  242. test('the observed 48 activity stream is excluded from chat monitoring and persistence', async () => {
  243. const store = createStore(':memory:'), requested = [];
  244. try {
  245. const sync = createNetworkSynchronizer({ har: har(entry('48:notifications'), entry('chat-a')), store, fetch: async raw => {
  246. requested.push(raw); return Response.json(payload('chat-a'));
  247. } });
  248. const result = await sync.runOnce(); assert.equal(result.ok, true);
  249. assert.equal(result.coverage.messages, 1); assert.equal(result.coverage.skipped.activityStream, 1);
  250. assert.equal(requested.length, 1); assert.ok(requested[0].includes('chat-a'));
  251. } finally { store.close(); }
  252. });
  253. test('authentication failure pauses requests; federated chat tenant differs from the signed-in user without changing local ownership', async () => {
  254. const store = createStore(':memory:'); let calls = 0;
  255. try {
  256. const sync = createNetworkSynchronizer({ har: har(entry('chat-a'), entry('chat-b')), store, fetch: async () => { calls++; return new Response('', { status: 401 }); } });
  257. 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);
  258. const mismatch = createNetworkSynchronizer({ har: har(entry('chat-a')), store, fetch: async () => Response.json({ ...payload('chat-a'), tenantId: 'wrong-tenant' }) });
  259. assert.equal((await mismatch.runOnce()).ok, true); assert.equal(store.stats().total, 1);
  260. assert.equal(store.listRecords({ kind: 'message' }).items[0].accountId, `web-api:${tid}:${oid}`);
  261. } finally { store.close(); }
  262. });
  263. test('calendar summary updates preserve previously collected details and repeated snapshots remain stable', async () => {
  264. const store = createStore(':memory:'); let summary = false;
  265. const calendar = { value: [{ id: 'event-a', subject: 'Meeting', body: { contentType: 'text', content: 'Detailed agenda' }, lastModifiedDateTime: '2026-09-07T05:00:00Z',
  266. start: { dateTime: '2026-09-08T01:00:00', timeZone: 'UTC' }, end: { dateTime: '2026-09-08T02:00:00', timeZone: 'UTC' } }] };
  267. const capture = { request: { method: 'GET', url: 'https://graph.microsoft.com/v1.0/me/events', headers: [{ name: 'Authorization', value: bearer(tid) }] },
  268. response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(calendar) } } };
  269. try {
  270. const sync = createNetworkSynchronizer({ har: har(capture), store, fetch: async () => {
  271. const body = structuredClone(calendar); if (summary) { delete body.value[0].body; delete body.value[0].lastModifiedDateTime; } return Response.json(body);
  272. } });
  273. assert.equal((await sync.runOnce()).changed, 1);
  274. summary = true; await sync.runOnce();
  275. let record = store.listRecords({ kind: 'event' }).items[0]; assert.equal(record.text, 'Detailed agenda'); assert.equal(record.raw.detailLevel, 'detail');
  276. assert.equal(record.updatedAt, '2026-09-07T05:00:00.000Z');
  277. assert.equal((await sync.runOnce()).changed, 0);
  278. summary = false; assert.equal((await sync.runOnce()).changed, 0);
  279. } finally { store.close(); }
  280. });
  281. test('per-round limits rotate among captured chats and overlapping calls share a single pass', async () => {
  282. const store = createStore(':memory:'); const requested = []; let release;
  283. try {
  284. const sync = createNetworkSynchronizer({ har: har(entry('chat-a'), entry('chat-b')), store, maxRequests: 1,
  285. 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)); } });
  286. const first = sync.runOnce(), concurrent = sync.runOnce(); await new Promise(resolve => setImmediate(resolve)); release();
  287. await Promise.all([first, concurrent]); assert.equal(requested.length, 1);
  288. await sync.runOnce(); assert.equal(requested.length, 2); assert.notEqual(requested[0], requested[1]);
  289. } finally { store.close(); }
  290. });
  291. function listEntry(tenant = tid) {
  292. const envelope = { chats: [], teams: [], users: [], channels: [], conversationFolders: {}, metadata: { syncToken: 'list-cursor', isPartialData: false, hasMoreChats: false } };
  293. return { request: { method: 'GET', url: 'https://teams.cloud.microsoft/api/csa/apac/api/v3/teams/users/me/updates', headers: [{ name: 'Authorization', value: bearer(tenant) }] },
  294. response: { status: 200, content: { mimeType: 'application/json', text: JSON.stringify(envelope) } } };
  295. }
  296. test('missing roster names use the same-account peer and never replace the chat title with the sender or stale placeholder', async () => {
  297. const store=createStore(':memory:'), accountId=`web-api:${tid}:${oid}`, peer='33333333-3333-3333-3333-333333333333';
  298. try {
  299. store.upsertRecord({source:'web-api',accountId,kind:'chat',externalId:'chat-a',title:'聊天',raw:{isOneOnOne:true,titleSource:'placeholder'}});
  300. store.upsertRecord({source:'web-api',accountId,kind:'message',externalId:'fictional-local-peer',parentId:'chat-a',title:'聊天',text:'Fictional earlier message',
  301. occurredAt:'2026-09-08T00:00:00Z',raw:{senderId:peer,author:'Fictional peer'}},{ingestion:'history'});
  302. const sync=createNetworkSynchronizer({har:har(entry('chat-a'),listEntry()),store,fetch:async raw=>{
  303. if(raw.includes('/updates')) {
  304. const body=JSON.parse(listEntry().response.content.text);
  305. body.chats=[{id:'chat-a',title:'',threadType:'chat',isOneOnOne:true,members:[{objectId:oid},{objectId:peer}]}];
  306. return Response.json(body);
  307. }
  308. const body=payload('chat-a');
  309. body.messages[0].from=`https://teams.cloud.microsoft/api/chatsvc/apac/v1/users/ME/contacts/${encodeURIComponent(`8:orgid:${oid}`)}`;
  310. body.messages[0].imdisplayname='Fictional self';return Response.json(body);
  311. }});
  312. assert.equal((await sync.runOnce()).ok,true);
  313. const named=store.getRecordByIdentity({source:'web-api',accountId,kind:'chat',externalId:'chat-a'});
  314. assert.equal(named.title,'Fictional peer');assert.equal(named.raw.titleSource,'message-author');
  315. const saved=store.listRecords({kind:'message'}).items.find(record=>record.raw.messageId==='m1');
  316. assert.equal(saved.title,'Fictional peer');assert.equal(saved.raw.author,'Fictional self');
  317. const versions=store.stats().versions;
  318. assert.equal((await sync.runOnce()).changed,0);assert.equal(store.stats().versions,versions);
  319. assert.equal(store.getRecord(named.id).title,'Fictional peer');
  320. } finally {store.close();}
  321. });
  322. test('discovered chat identities and committed cursors survive restart even when the next list response has no changes', async () => {
  323. const store = createStore(':memory:'); let initial = true; const requested = [];
  324. const captured = har(entry('chat-a'), listEntry());
  325. const fetch = async raw => {
  326. if (raw.includes('/updates')) {
  327. const body = JSON.parse(listEntry().response.content.text);
  328. if (initial) body.chats = [{ id: 'chat-b', title: 'Chat b', threadType: 'chat' }];
  329. return Response.json(body);
  330. }
  331. requested.push(raw); const chatId = decodeURIComponent(new URL(raw).pathname.split('/conversations/')[1].split('/messages')[0]);
  332. return Response.json(payload(chatId));
  333. };
  334. try {
  335. assert.equal((await createNetworkSynchronizer({ har: captured, store, fetch }).runOnce()).ok, true);
  336. initial = false; requested.length = 0;
  337. const restarted = createNetworkSynchronizer({ har: captured, store, fetch });
  338. assert.equal(restarted.coverage().messages, 2);
  339. assert.equal((await restarted.runOnce()).ok, true);
  340. assert.ok(requested.find(raw => raw.includes('chat-b')).includes('syncState=opaque-next'));
  341. } finally { store.close(); }
  342. });
  343. test('separate list cursor rotates across accounts even when every message plan fits in one pass', async () => {
  344. const store = createStore(':memory:'), other = '33333333-3333-3333-3333-333333333333', lists = [];
  345. try {
  346. const sync = createNetworkSynchronizer({ har: har(entry('chat-a'), entry('chat-b', other), listEntry(), listEntry(other)), store,
  347. fetch: async (raw, options) => {
  348. if (raw.includes('/updates')) { lists.push(new Headers(options.headers).get('authorization')); return Response.json(JSON.parse(listEntry().response.content.text)); }
  349. return Response.json(payload(raw.includes('chat-a') ? 'chat-a' : 'chat-b'));
  350. } });
  351. await sync.runOnce(); await sync.runOnce();
  352. assert.deepEqual(lists, [bearer(tid), bearer(other)]);
  353. } finally { store.close(); }
  354. });
  355. test('one expired resource pauses only that request while still-valid captured requests continue', async () => {
  356. const store = createStore(':memory:'); let expiredCalls = 0, validCalls = 0;
  357. try {
  358. const sync = createNetworkSynchronizer({ har: har(entry('chat-a'), entry('chat-b')), store, fetch: async raw => {
  359. if (raw.includes('chat-a')) { expiredCalls++; return new Response('', { status: 401 }); }
  360. validCalls++; return Response.json(payload('chat-b'));
  361. } });
  362. const first = await sync.runOnce(); assert.equal(first.authRequired, true); assert.equal(first.noUsableRequests, false); assert.equal(first.successful, 1);
  363. await sync.runOnce(); assert.equal(expiredCalls, 1); assert.equal(validCalls, 2);
  364. assert.equal(store.listRecords({ kind: 'message' }).total, 1);
  365. } finally { store.close(); }
  366. });