fix: drain initial message sync before polling

This commit is contained in:
2026-08-03 12:06:21 +08:00
parent 4d8db43be0
commit a76bbdeaee
+30 -6
View File
@@ -152,12 +152,36 @@ async function syncLoop(): Promise<void> {
polling = true; polling = true;
while (session.active) { while (session.active) {
try { try {
const response = await fetch(api("/messages/sync"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ channel_id: session.channelID, channel_type: session.channelType, login_uid: session.uid, start_message_seq: session.lastSeq === 0 ? 0 : session.lastSeq + 1, limit: 50 }) }); // WuKongIM's legacy sync endpoint can return a single retained message
const body = await response.json().catch(() => ({})) as { error?: string; messages?: SyncedMessage[] }; // per request even when `more` is 0. Drain until it is empty before
if (!response.ok) throw new Error(body.error || "同步失败"); // switching to the paced live-polling loop; otherwise a reopened chat
for (const message of body.messages ?? []) { // with history needs minutes to reach the latest Agent response.
session.lastSeq = Math.max(session.lastSeq, message.message_seq); while (session.active) {
if (message.from_uid !== session.uid) render(decodeConversationItem(decodeBase64(message.payload))); const startMessageSeq = session.lastSeq === 0 ? 0 : session.lastSeq + 1;
const response = await fetch(api("/messages/sync"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ channel_id: session.channelID, channel_type: session.channelType, login_uid: session.uid, start_message_seq: startMessageSeq, limit: 50 }) });
const body = await response.json().catch(() => ({})) as { error?: string; messages?: SyncedMessage[] };
if (!response.ok) throw new Error(body.error || "同步失败");
const synced = body.messages ?? [];
if (synced.length === 0) {
setPresence("已同步,等待消息");
break;
}
let advanced = false;
for (const message of synced) {
const previousSeq = session.lastSeq;
session.lastSeq = Math.max(session.lastSeq, message.message_seq);
advanced ||= session.lastSeq > previousSeq;
if (message.from_uid !== session.uid) render(decodeConversationItem(decodeBase64(message.payload)));
}
// Avoid a hot loop if an upstream response repeats a sequence that
// cannot advance the local cursor.
if (!advanced) {
setPresence("已同步,等待消息");
break;
}
} }
} catch { } catch {
if (session.active) setPresence("同步中断,正在重试…"); if (session.active) setPresence("同步中断,正在重试…");