fix: 聊天回复被周期同步清空(数据丢失)
- 根因: mergeJsonArrays 以服务端为基准, 同id跳过本机 -> 旧空会话覆盖新回复; doSyncNow applyLocal 写回清空, 且推送也带不上新回复 - 修复: 新增 mergeConvs() 不同id并集/同id取updatedAt更新方(并列取消息多者) - 兜底: 本机无该键也统一截断30条 测试5项: 本机新回复保住/服务端更新胜出/并集/墓碑生效/上限30 ✓ CHANGELOG记录
This commit is contained in:
1 parent
5301a8c840
commit
7d60ff1212
2 files changed
+48
-2
No files matched your search
@@ -121,6 +121,42 @@ function applyTombstones(data: Record<string, any>) {
|
||||
data['it-tools-ai-chat-convs'] = JSON.stringify(convs);
|
||||
}
|
||||
|
||||
/** 会话列表合并:不同 id 取并集;同 id 取 updatedAt 更新的一方。
|
||||
* 关键——不能以服务端为基准,否则服务端的旧(空)会话会覆盖本机刚发的回复。 */
|
||||
function mergeConvs(a: string, b: string): string {
|
||||
let arrA: any[], arrB: any[];
|
||||
try {
|
||||
arrA = JSON.parse(a);
|
||||
if (!Array.isArray(arrA)) arrA = [];
|
||||
}
|
||||
catch { arrA = []; }
|
||||
try {
|
||||
arrB = JSON.parse(b);
|
||||
if (!Array.isArray(arrB)) arrB = [];
|
||||
}
|
||||
catch { arrB = []; }
|
||||
const map = new Map<string, any>();
|
||||
for (const c of arrA) {
|
||||
if (c?.id) map.set(c.id, c);
|
||||
}
|
||||
for (const c of arrB) {
|
||||
if (!c?.id) continue;
|
||||
const exist = map.get(c.id);
|
||||
// 同 id:保留消息更新的一方(updatedAt 更大,或消息更多)
|
||||
if (!exist) {
|
||||
map.set(c.id, c);
|
||||
}
|
||||
else {
|
||||
const ea = exist.updatedAt ?? 0;
|
||||
const eb = c.updatedAt ?? 0;
|
||||
const la = Array.isArray(exist.messages) ? exist.messages.length : 0;
|
||||
const lb = Array.isArray(c.messages) ? c.messages.length : 0;
|
||||
if (eb > ea || (eb === ea && lb > la)) map.set(c.id, c);
|
||||
}
|
||||
}
|
||||
return trimConvs(JSON.stringify([...map.values()]));
|
||||
}
|
||||
|
||||
function mergeData(server: Record<string, any>, mine: Record<string, any>): Record<string, any> {
|
||||
const out: Record<string, any> = { ...server };
|
||||
for (const [k, v] of Object.entries(mine)) {
|
||||
@@ -136,8 +172,8 @@ function mergeData(server: Record<string, any>, mine: Record<string, any>): Reco
|
||||
out[k] = mergeJsonArrays(out[k], v, k === 'it-tools-recent-tools' ? 'path' : null);
|
||||
}
|
||||
else if (k === 'it-tools-ai-chat-convs') {
|
||||
// 对话列表按 id 合并(多设备各自的会话都保留),上限 30 条
|
||||
out[k] = trimConvs(mergeJsonArrays(out[k], v, 'id'));
|
||||
// 不同 id 并集;同 id 取更新一方(防服务端旧空会话覆盖本机新回复)
|
||||
out[k] = mergeConvs(out[k], v);
|
||||
}
|
||||
else if (k === 'it-tools-ai-chat-deleted') {
|
||||
out[k] = mergeTombstones(out[k], v);
|
||||
@@ -148,6 +184,10 @@ function mergeData(server: Record<string, any>, mine: Record<string, any>): Reco
|
||||
}
|
||||
}
|
||||
applyTombstones(out);
|
||||
// 兜底:即使本机没有该键,也统一截断到 30 条
|
||||
if (typeof out['it-tools-ai-chat-convs'] === 'string') {
|
||||
out['it-tools-ai-chat-convs'] = trimConvs(out['it-tools-ai-chat-convs']);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user