fix: drain initial message sync before polling

This commit is contained in:
2026-08-03 12:06:21 +08:00
parent 4d8db43be0
commit a76bbdeaee
+26 -2
View File
@@ -152,13 +152,37 @@ async function syncLoop(): Promise<void> {
polling = true;
while (session.active) {
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
// per request even when `more` is 0. Drain until it is empty before
// switching to the paced live-polling loop; otherwise a reopened chat
// with history needs minutes to reach the latest Agent response.
while (session.active) {
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 || "同步失败");
for (const message of body.messages ?? []) {
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 {
if (session.active) setPresence("同步中断,正在重试…");
}