import test from 'node:test';
import assert from 'node:assert/strict';
import { createStore } from '../src/store.js';
import { currentChatTitle, normalizeChatName, preserveChatName, refreshChatNames } from '../src/chat-names.js';
const tenant = '11111111-1111-1111-1111-111111111111', self = '22222222-2222-2222-2222-222222222222';
const peer = '33333333-3333-3333-3333-333333333333', third = '44444444-4444-4444-4444-444444444444';
const accountId = `web-api:${tenant}:${self}`;
const chat = (overrides = {}) => ({ source: 'web-api', accountId, kind: 'chat', externalId: 'fictional-chat', title: '聊天',
raw: { isOneOnOne: true, titleSource: 'placeholder' }, ...overrides });
const message = (id, senderId, author, overrides = {}) => ({ source: 'web-api', accountId, kind: 'message', externalId: id,
parentId: 'fictional-chat', title: '聊天', text: 'Fictional message', occurredAt: '2026-09-08T10:00:00Z', raw: { senderId, selfUserId: self, author }, ...overrides });
test('member naming excludes self, validates identities and preserves explicitly named generic titles', () => {
const item = { title: '', isOneOnOne: true, members: [
{ objectId: self, mri: `8:orgid:${self}`, friendlyName: 'Fictional self' },
{ objectId: peer, mri: `8:orgid:${peer}`, friendlyName: 'Fictional peer', authorization: 'secret-marker' },
] };
const named = normalizeChatName(item, accountId);
assert.equal(named.title, 'Fictional peer'); assert.equal(named.raw.titleSource, 'members'); assert.equal(named.raw.peerId, peer);
assert.equal(named.raw.members.length, 2); assert.doesNotMatch(JSON.stringify(named), /secret-marker|8:orgid/);
assert.equal(normalizeChatName({ ...item, title: '聊天' }, accountId).raw.titleSource, 'explicit');
assert.equal(normalizeChatName(item, 'unknown-account').title, '聊天');
assert.equal(normalizeChatName({ ...item, members: [{ objectId: peer, mri: `8:orgid:${third}`, friendlyName: 'Unverified' }] }, accountId).title, '聊天');
assert.equal(normalizeChatName({ ...item, members: [{ friendlyName: 'Unidentified' }] }, accountId).title, '聊天');
});
test('a self-authored message cannot name the peer; the most recent other-author name can', () => {
const store = createStore(':memory:');
try {
store.upsertRecord(chat());
store.upsertRecord(message('old-peer', peer, 'Fictional former peer name'), { ingestion: 'history' });
store.upsertRecord(message('new-peer', peer, 'Fictional current peer name', { occurredAt: '2026-09-08T11:00:00Z' }), { ingestion: 'history' });
store.upsertRecord(message('my-message', self, 'Fictional self name', { occurredAt: '2026-09-08T12:00:00Z' }), { ingestion: 'history' });
const snapshot = () => ({ records: store.readRows("SELECT * FROM records WHERE kind='message' ORDER BY id"),
versions: store.readRows("SELECT v.* FROM versions v JOIN records r ON v.recordId=r.id WHERE r.kind='message' ORDER BY v.id") });
const before = snapshot();
assert.equal(refreshChatNames(store), 1);
const resolved = store.getRecordByIdentity(chat());
assert.equal(resolved.title, 'Fictional current peer name'); assert.equal(resolved.raw.titleSource, 'message-author'); assert.equal(resolved.raw.peerId, peer);
assert.deepEqual(snapshot(), before);
assert.equal(store.readOne('SELECT ingestion FROM change_log ORDER BY seq DESC LIMIT 1').ingestion, 'import');
const originalUpsert = store.upsertRecord;
store.upsertRecord = () => assert.fail('An unchanged derived title must not refresh lastSeenAt');
assert.equal(refreshChatNames(store), 0);
store.upsertRecord = originalUpsert;
store.upsertRecord(message('same-peer-name', peer, 'Fictional current peer name', { occurredAt: '2026-09-08T13:00:00Z' }));
store.upsertRecord = () => assert.fail('A newer message with the same name must not rewrite the chat');
assert.equal(refreshChatNames(store), 0);
} finally { store.close(); }
});
test('verified member names take precedence and a stored derived name tracks a new peer display name', () => {
const store = createStore(':memory:');
try {
store.upsertRecord(chat({ raw: { isOneOnOne: true, titleSource: 'placeholder', membersComplete: true,
members: [{ userId: self, displayName: 'Fictional self' }, { userId: peer, displayName: 'Fictional roster peer' }] } }));
store.upsertRecord(message('peer', peer, 'Fictional historical author'));
assert.equal(refreshChatNames(store), 1);
assert.equal(store.getRecordByIdentity(chat()).title, 'Fictional roster peer');
store.upsertRecord(chat({ title: 'Old peer name', raw: { isOneOnOne: true, titleSource: 'message-author', peerId: peer } }));
assert.equal(refreshChatNames(store), 1);
assert.equal(store.getRecordByIdentity(chat()).title, 'Fictional historical author');
} finally { store.close(); }
});
test('group, unknown, ambiguous, masked and explicitly named chats are not guessed', () => {
for (const overrides of [
{ raw: { isOneOnOne: false, titleSource: 'placeholder' } }, { raw: { titleSource: 'placeholder' } },
{ title: '聊天', raw: { isOneOnOne: true, titleSource: 'explicit' } },
{ title: 'Explicit fictional title', raw: { isOneOnOne: true } },
{ raw: { isOneOnOne: true, titleSource: 'placeholder', members: [{ userId: peer, isIdentityMasked: true }] } },
{ raw: { isOneOnOne: true, titleSource: 'placeholder', membersComplete: false, members: [{ userId: peer }] } },
{ raw: { isOneOnOne: true, titleSource: 'placeholder', members: [{ userId: peer }, { userId: third }] } },
]) {
const store = createStore(':memory:');
try { store.upsertRecord(chat(overrides)); store.upsertRecord(message('peer', peer, 'Fictional peer')); assert.equal(refreshChatNames(store), 0); }
finally { store.close(); }
}
const store = createStore(':memory:');
try {
store.upsertRecord(chat()); store.upsertRecord(message('peer', peer, 'Fictional peer')); store.upsertRecord(message('third', third, 'Fictional third'));
assert.equal(refreshChatNames(store), 0);
} finally { store.close(); }
});
test('peer author lookups remain in the same account, source and conversation', () => {
const store = createStore(':memory:');
try {
store.upsertRecord(chat());
store.upsertRecord(message('other-account', peer, 'Wrong account', { accountId: 'another-account' }));
store.upsertRecord(message('other-source', peer, 'Wrong source', { source: 'browser' }));
store.upsertRecord(message('other-chat', peer, 'Wrong chat', { parentId: 'another-chat' }));
store.upsertRecord(message('self', self, 'Fictional self'));
assert.equal(refreshChatNames(store), 0);
store.upsertRecord(message('correct', peer, 'Correct fictional peer'));
assert.equal(refreshChatNames(store, { accountId, chatId: 'fictional-chat' }), 1);
} finally { store.close(); }
});
test('missing list names preserve useful titles, while an explicit replacement or changed peer wins', () => {
const previous = chat({ title: 'Fictional peer', raw: { isOneOnOne: true, titleSource: 'message-author', peerId: peer } });
assert.equal(preserveChatName(chat(), previous).title, 'Fictional peer');
assert.equal(preserveChatName(chat({ title: '聊天', raw: { isOneOnOne: true, titleSource: 'explicit' } }), previous).title, '聊天');
assert.equal(preserveChatName(chat({ raw: { isOneOnOne: true, titleSource: 'placeholder', members: [{ userId: third }] } }), previous).title, '聊天');
const store = createStore(':memory:');
try {
store.upsertRecord(previous);
assert.equal(currentChatTitle(store, accountId, 'fictional-chat', '聊天'), 'Fictional peer');
assert.equal(currentChatTitle(store, 'another-account', 'fictional-chat', 'Other fallback'), 'Other fallback');
} finally { store.close(); }
});
test('derived names are not retained when the new roster contradicts private-chat or visible-identity evidence', () => {
for (const titleSource of ['members', 'message-author']) {
const previous = chat({ title: 'Fictional peer', raw: { isOneOnOne: true, titleSource, peerId: peer } });
for (const evidence of [
{ chatType: 'group' }, { chatType: 'meeting' }, { threadType: 'meeting' },
{ membersComplete: false }, { members: [{ userId: peer, isIdentityMasked: true }] },
]) {
const incoming = chat({ raw: { isOneOnOne: true, titleSource: 'placeholder', ...evidence } });
assert.equal(preserveChatName(incoming, previous).title, '聊天');
assert.equal(preserveChatName(incoming, previous).raw.titleSource, 'placeholder');
}
assert.equal(preserveChatName(chat(), previous).title, 'Fictional peer');
}
});
const participantChatId = `19:${self}_${peer}@unq.gbl.spaces`;
const participantChatRecord = (overrides = {}) => chat({ externalId: participantChatId, raw: { titleSource: 'placeholder' }, ...overrides });
const participantMessage = (id, senderId, author, overrides = {}) => message(id, senderId, author, { parentId: participantChatId, ...overrides });
const messageSnapshot = store => ({ records: store.readRows("SELECT * FROM records WHERE kind='message' ORDER BY id"),
versions: store.readRows("SELECT v.* FROM versions v JOIN records r ON v.recordId=r.id WHERE r.kind='message' ORDER BY v.id") });
test('canonical participant IDs and a local peer author name an uncatalogued emoji conversation without classification', () => {
const store = createStore(':memory:');
try {
store.upsertRecord(participantMessage('emoji', peer, 'Fictional peer', { text: '🔥' }), { ingestion: 'history' });
store.upsertRecord(participantMessage('own', self, 'Fictional self', { occurredAt: '2026-09-08T12:00:00Z' }));
const before = messageSnapshot(store);
assert.equal(refreshChatNames(store, { accountId, chatId: participantChatId }), 1);
const resolved = store.getRecordByIdentity(participantChatRecord());
assert.equal(resolved.title, 'Fictional peer');
assert.deepEqual(resolved.raw, { chatId: participantChatId, titleSource: 'conversation-peer', peerId: peer, nameEvidence: 'unq-participant-ids' });
assert.equal(store.getRecord(store.getRecordByIdentity(participantMessage('emoji')).id).displayTitle, 'Fictional peer');
assert.equal(store.getRecord(store.getRecordByIdentity(participantMessage('own')).id).displayTitle, 'Fictional peer');
assert.deepEqual(messageSnapshot(store), before);
assert.equal(store.readOne('SELECT ingestion FROM change_log ORDER BY seq DESC LIMIT 1').ingestion, 'import');
const records = store.readRows('SELECT * FROM records ORDER BY id'), versions = store.readRows('SELECT * FROM versions ORDER BY id');
store.upsertRecord = () => assert.fail('An unchanged peer name must not write metadata or versions');
assert.equal(refreshChatNames(store), 0);
assert.deepEqual(store.readRows('SELECT * FROM records ORDER BY id'), records);
assert.deepEqual(store.readRows('SELECT * FROM versions ORDER BY id'), versions);
} finally { store.close(); }
});
test('the same participant conversation resolves the opposite peer independently for each account', () => {
const store = createStore(':memory:'), otherAccount = `web-api:${tenant}:${peer}`;
try {
store.upsertRecord(participantMessage('for-first', peer, 'Fictional second person'));
store.upsertRecord(participantMessage('for-second', self, 'Fictional first person', {
accountId: otherAccount, raw: { senderId: self, selfUserId: peer, author: 'Fictional first person' } }));
assert.equal(refreshChatNames(store, { accountId }), 1);
assert.equal(store.getRecordByIdentity(participantChatRecord({ accountId: otherAccount })), null);
assert.equal(refreshChatNames(store), 1);
assert.equal(currentChatTitle(store, accountId, participantChatId), 'Fictional second person');
assert.equal(currentChatTitle(store, otherAccount, participantChatId), 'Fictional first person');
assert.equal(store.getRecordByIdentity(participantChatRecord({ accountId: otherAccount })).raw.peerId, self);
} finally { store.close(); }
});
test('participant fallback rejects incomplete identifiers and missing local peer evidence', () => {
const cases = [
{ label: 'fake UUID', parentId: `19:${self}_fake@unq.gbl.spaces` },
{ label: 'repeated self', parentId: `19:${self}_${self}@unq.gbl.spaces` },
{ label: 'account absent from pair', parentId: `19:${third}_${peer}@unq.gbl.spaces` },
{ label: 'thread suffix only', parentId: `19:${self}_${peer}@thread.v2` },
{ label: 'encoded IDs', parentId: `19%3A${self}_${peer}%40unq.gbl.spaces` },
{ label: 'trailing content', parentId: `${participantChatId}:extra` },
{ label: 'invalid account tenant', accountId: `web-api:tenant:${self}` },
{ label: 'invalid self identity', accountId: `web-api:${tenant}:self` },
{ label: 'another source', source: 'browser' },
{ label: 'only own message', raw: { senderId: self, selfUserId: self, author: 'Fictional self' } },
{ label: 'deleted peer', deleted: true },
{ label: 'unknown sender', raw: { senderId: 'not-a-uuid', selfUserId: self, author: 'Unknown person' } },
{ label: 'empty author', raw: { senderId: peer, selfUserId: self, author: '' } },
{ label: 'wrong self claim', raw: { senderId: peer, selfUserId: third, author: 'Fictional peer' } },
];
for (const { label, ...overrides } of cases) {
const store = createStore(':memory:');
try {
store.upsertRecord(participantMessage('candidate', peer, 'Fictional peer', overrides));
assert.equal(refreshChatNames(store), 0, label);
assert.equal(store.readOne("SELECT COUNT(*) n FROM records WHERE kind='chat'").n, 0, label);
} finally { store.close(); }
}
});
test('peer name discovery rejects contradictory senders, identity claims and conversation metadata', () => {
const cases = [
{ label: 'third sender', extra: participantMessage('third', third, 'Third person') },
{ label: 'wrong self claim on another message', extra: participantMessage('wrong-self', self, 'Fictional self',
{ raw: { senderId: self, selfUserId: third, author: 'Fictional self' } }) },
...[{ isOneOnOne: false }, { chatType: 'group' }, { chatType: 'meeting' }, { threadType: 'meeting' },
{ isIdentityMasked: true }, { membersComplete: false },
{ membersComplete: true, members: [{ userId: self }, { userId: peer, isIdentityMasked: true }] },
{ membersComplete: true, members: [{ userId: self }, { userId: third }] },
{ members: 'invalid' }].map(evidence => ({ label: `message evidence ${JSON.stringify(evidence)}`,
extra: participantMessage('message-evidence', self, 'Fictional self',
{ raw: { senderId: self, selfUserId: self, author: 'Fictional self', ...evidence } }) })),
...[
{ isOneOnOne: false }, { chatType: 'group' }, { chatType: 'meeting' }, { threadType: 'group' }, { threadType: 'meeting' },
{ membersComplete: false }, { isIdentityMasked: true }, { selfUserId: third }, { peerId: third },
{ members: [{ userId: self }, { userId: peer }] },
{ membersComplete: true, members: [{ userId: peer }] },
{ membersComplete: true, members: [{ userId: self }, { userId: third }] },
{ membersComplete: true, members: [{ userId: self }, { userId: peer, isIdentityMasked: true }] },
{ membersComplete: true, members: [{ userId: self }, { userId: self }] },
{ membersComplete: true, members: [{ userId: self }, { userId: 'invalid' }] },
{ membersComplete: true, members: 'invalid' },
].map(raw => ({ label: JSON.stringify(raw), chat: participantChatRecord({ raw: { titleSource: 'placeholder', ...raw } }) })),
{ label: 'deleted conversation', chat: participantChatRecord({ deleted: true }) },
];
for (const { label, extra, chat: existing } of cases) {
const store = createStore(':memory:');
try {
if (existing) store.upsertRecord(existing);
store.upsertRecord(participantMessage('candidate', peer, 'Fictional peer'));
if (extra) store.upsertRecord(extra);
const before = store.readRows('SELECT * FROM records ORDER BY id');
assert.equal(refreshChatNames(store), 0, label);
assert.deepEqual(store.readRows('SELECT * FROM records ORDER BY id'), before, label);
} finally { store.close(); }
}
});
test('participant discovery uses only the requested source, account and conversation', () => {
const store = createStore(':memory:'), otherChat = `19:${self}_${third}@unq.gbl.spaces`;
try {
store.upsertRecord(participantMessage('other-account', peer, 'Wrong account', { accountId: `web-api:${third}:${self}` }));
store.upsertRecord(participantMessage('other-source', peer, 'Wrong source', { source: 'browser' }));
store.upsertRecord(participantMessage('other-chat', peer, 'Wrong conversation', { parentId: otherChat }));
store.upsertRecord(participantMessage('self-only', self, 'Fictional self'));
assert.equal(refreshChatNames(store, { accountId, chatId: participantChatId }), 0);
assert.equal(store.readOne("SELECT COUNT(*) n FROM records WHERE kind='chat'").n, 0);
store.upsertRecord(participantMessage('right-peer', peer, 'Correct fictional peer'));
assert.equal(refreshChatNames(store, { accountId, chatId: participantChatId }), 1);
assert.equal(store.readOne("SELECT COUNT(*) n FROM records WHERE kind='chat'").n, 1);
assert.equal(currentChatTitle(store, accountId, participantChatId), 'Correct fictional peer');
} finally { store.close(); }
});
test('explicit and useful unknown titles take precedence over participant author fallback', () => {
for (const existing of [
participantChatRecord({ title: '聊天', raw: { titleSource: 'explicit' } }),
participantChatRecord({ title: 'Fictional server topic', raw: { titleSource: 'conversation-details' } }),
participantChatRecord({ title: 'Fictional named chat', raw: {} }),
participantChatRecord({ title: 'Fictional named chat', raw: { titleSource: 'future-source' } }),
participantChatRecord({ title: 'Fictional roster name', raw: { titleSource: 'members', peerId: peer } }),
]) {
const store = createStore(':memory:');
try {
store.upsertRecord(existing); store.upsertRecord(participantMessage('peer', peer, 'Fictional peer'));
assert.equal(refreshChatNames(store), 0);
assert.equal(store.getRecordByIdentity(existing).title, existing.title);
} finally { store.close(); }
}
});
test('a canonical participant chat keeps verified member names ahead of historical author names', () => {
const store = createStore(':memory:');
try {
store.upsertRecord(participantChatRecord({ raw: { titleSource: 'placeholder', isOneOnOne: true, membersComplete: true,
members: [{ userId: self, displayName: 'Fictional self' }, { userId: peer, displayName: 'Fictional roster name' }] } }));
store.upsertRecord(participantMessage('peer', peer, 'Fictional historic author'));
assert.equal(refreshChatNames(store), 1);
const resolved = store.getRecordByIdentity(participantChatRecord());
assert.equal(resolved.title, 'Fictional roster name'); assert.equal(resolved.raw.titleSource, 'members');
assert.equal(resolved.raw.isOneOnOne, true); assert.equal(resolved.raw.nameEvidence, undefined);
assert.equal(refreshChatNames(store), 0);
} finally { store.close(); }
});
test('participant fallback follows valid peer name changes while preserving existing metadata and message history', () => {
const store = createStore(':memory:');
try {
store.upsertRecord(participantChatRecord({ raw: { titleSource: 'placeholder', isOneOnOne: true, membersComplete: true,
members: [{ userId: self }, { userId: peer }], originalEvidence: 'retained' } }));
store.upsertRecord(participantMessage('old', peer, 'Fictional old name'));
assert.equal(refreshChatNames(store), 1);
store.upsertRecord(participantMessage('new', peer, 'Fictional new name', { occurredAt: '2026-09-08T07:00:00-04:00' }));
store.upsertRecord(participantMessage('blank', peer, '', { occurredAt: '2026-09-08T12:00:00Z' }));
store.upsertRecord(participantMessage('self', self, 'Latest self name', { occurredAt: '2026-09-08T13:00:00Z' }));
const before = messageSnapshot(store);
assert.equal(refreshChatNames(store), 1);
const updated = store.getRecordByIdentity(participantChatRecord());
assert.equal(updated.title, 'Fictional new name'); assert.equal(updated.raw.originalEvidence, 'retained');
assert.equal(updated.raw.isOneOnOne, true); assert.equal(updated.raw.members.length, 2);
assert.deepEqual(messageSnapshot(store), before);
assert.equal(refreshChatNames(store), 0);
assert.equal(store.readOne('SELECT COUNT(*) n FROM versions WHERE recordId=?', [updated.id]).n, 3);
} finally { store.close(); }
});
test('incremental placeholder names retain participant evidence only while the account, peer and roster agree', () => {
const previous = participantChatRecord({ title: 'Fictional peer', raw: { titleSource: 'conversation-peer', peerId: peer,
chatId: participantChatId, nameEvidence: 'unq-participant-ids' } });
const preserved = preserveChatName(participantChatRecord(), previous);
assert.equal(preserved.title, 'Fictional peer'); assert.equal(preserved.raw.nameEvidence, 'unq-participant-ids');
assert.equal(preserved.raw.isOneOnOne, undefined); assert.equal(preserved.raw.chatType, undefined);
for (const evidence of [
{ isOneOnOne: false }, { chatType: 'group' }, { threadType: 'meeting' }, { peerId: third }, { selfUserId: third },
{ membersComplete: false }, { membersComplete: true, members: [{ userId: self }, { userId: third }] },
{ membersComplete: true, members: [{ userId: self }, { userId: peer, isIdentityMasked: true }] },
]) {
const incoming = participantChatRecord({ raw: { titleSource: 'placeholder', ...evidence } });
assert.deepEqual(preserveChatName(incoming, previous), incoming);
}
for (const incoming of [
participantChatRecord({ accountId: `web-api:${tenant}:${peer}` }),
participantChatRecord({ externalId: `19:${self}_${third}@unq.gbl.spaces` }),
participantChatRecord({ source: 'browser' }),
participantChatRecord({ title: 'New topic', raw: { titleSource: 'explicit' } }),
]) assert.deepEqual(preserveChatName(incoming, previous), incoming);
});
test('new conflicting evidence withdraws only locally derived peer names without rewriting messages', () => {
const cases = [
store => store.upsertRecord(participantMessage('third', third, 'Fictional third')),
store => store.upsertRecord(participantMessage('wrong-self', self, 'Fictional self',
{ raw: { senderId: self, selfUserId: third, author: 'Fictional self' } })),
store => store.upsertRecord(participantMessage('peer', peer, 'Fictional peer', { deleted: true })),
...[{ isOneOnOne: false }, { chatType: 'meeting' }, { membersComplete: false },
{ membersComplete: true, members: [{ userId: self }, { userId: peer, isIdentityMasked: true }] }]
.map(evidence => store => {
const current = store.getRecordByIdentity(participantChatRecord());
store.upsertRecord({ ...current, raw: { ...current.raw, ...evidence } });
}),
];
for (const conflict of cases) {
const store = createStore(':memory:');
try {
store.upsertRecord(participantMessage('peer', peer, 'Fictional peer'));
assert.equal(refreshChatNames(store), 1);
conflict(store);
const before = messageSnapshot(store);
assert.equal(refreshChatNames(store), 1);
const current = store.getRecordByIdentity(participantChatRecord());
assert.equal(current.title, '聊天'); assert.equal(current.raw.titleSource, 'placeholder');
assert.equal(current.raw.peerId, undefined); assert.equal(current.raw.nameEvidence, undefined);
assert.deepEqual(messageSnapshot(store), before);
assert.equal(refreshChatNames(store), 0);
} finally { store.close(); }
}
});