Fix duplicate chat messages and image reloads on reconnect
Deploy with Docker Compose / deploy (push) Successful in 1m7s
Deploy with Docker Compose / deploy (push) Successful in 1m7s
The chat store bound its handlers to the shared socket ref, so when Chat.vue reconnected after auth resolved (isAdmin flipping), the old socket's onclose fired after the new socket existed, nulled it, and scheduled another reconnect. Two live sockets then pushed every broadcast, showing each sent message or upload twice. Handlers now check they belong to the current socket. History is sent as a single batch event so the message list is replaced in place instead of being emptied and refilled, which kept unmounting and reloading every image and jumping the scroll position. Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
@@ -62,6 +62,14 @@ type wsDeleteEvent struct {
|
||||
ID uint `json:"id"`
|
||||
}
|
||||
|
||||
// wsHistoryEvent is sent once on connect with the recent messages the client
|
||||
// may see. Sending it as a single batch lets the client replace its list
|
||||
// atomically, so a reconnect does not blank the chat and reload every image.
|
||||
type wsHistoryEvent struct {
|
||||
Action string `json:"action"`
|
||||
Messages []models.Message `json:"messages"`
|
||||
}
|
||||
|
||||
func InitWebSocket(database *gorm.DB, domain string) {
|
||||
wsDB = database
|
||||
allowedDomain = domain
|
||||
@@ -77,18 +85,17 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
|
||||
nextAuthorID++
|
||||
authorID := nextAuthorID
|
||||
|
||||
var history []models.Message
|
||||
history := make([]models.Message, 0, maxMessages)
|
||||
historyQuery := wsDB.Order("created_at ASC").Limit(maxMessages)
|
||||
if !isAdmin {
|
||||
historyQuery = historyQuery.Where("private = ?", false)
|
||||
}
|
||||
historyQuery.Find(&history)
|
||||
|
||||
for _, msg := range history {
|
||||
if err := conn.WriteJSON(msg); err != nil {
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
if err := conn.WriteJSON(wsHistoryEvent{Action: "history", Messages: history}); err != nil {
|
||||
delete(clients, conn)
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
|
||||
@@ -19,36 +19,53 @@ export const useMessagesStore = defineStore("messages", () => {
|
||||
const messagesCount = computed(() => messages.value.length);
|
||||
|
||||
function connect() {
|
||||
if (socket.value && isConnected.value) return;
|
||||
if (socket.value) return;
|
||||
intentionalClose = false;
|
||||
clearTimeout(reconnectTimer);
|
||||
|
||||
socket.value = new WebSocket(getWebSocketURL());
|
||||
// Every handler checks it still belongs to the current socket. A socket
|
||||
// closed by disconnect() can fire onclose after connect() has already
|
||||
// opened a replacement; without this guard it would null the new socket
|
||||
// and schedule a second reconnect, leaving two live sockets that each
|
||||
// push every broadcast (duplicate messages).
|
||||
const ws = new WebSocket(getWebSocketURL());
|
||||
socket.value = ws;
|
||||
|
||||
socket.value.onopen = () => {
|
||||
ws.onopen = () => {
|
||||
if (socket.value !== ws) return;
|
||||
isConnected.value = true;
|
||||
lastError.value = null;
|
||||
reconnectDelay = 1000;
|
||||
messages.value = [];
|
||||
};
|
||||
|
||||
socket.value.onmessage = (event) => {
|
||||
ws.onmessage = (event) => {
|
||||
if (socket.value !== ws) return;
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
if (data.action === "history") {
|
||||
// Replace in one go so keyed rows (and their images) are patched in
|
||||
// place rather than unmounted and recreated.
|
||||
messages.value = data.messages || [];
|
||||
return;
|
||||
}
|
||||
if (data.action === "delete") {
|
||||
messages.value = messages.value.filter((m) => m.id !== data.id);
|
||||
return;
|
||||
}
|
||||
if (data.id && messages.value.some((m) => m.id === data.id)) return;
|
||||
messages.value.push(data);
|
||||
} catch {
|
||||
messages.value.push({ text: event.data });
|
||||
}
|
||||
};
|
||||
|
||||
socket.value.onerror = (error) => {
|
||||
ws.onerror = (error) => {
|
||||
if (socket.value !== ws) return;
|
||||
lastError.value = error;
|
||||
};
|
||||
|
||||
socket.value.onclose = () => {
|
||||
ws.onclose = () => {
|
||||
if (socket.value !== ws) return;
|
||||
isConnected.value = false;
|
||||
socket.value = null;
|
||||
if (!intentionalClose) {
|
||||
@@ -64,9 +81,10 @@ export const useMessagesStore = defineStore("messages", () => {
|
||||
intentionalClose = true;
|
||||
clearTimeout(reconnectTimer);
|
||||
if (!socket.value) return;
|
||||
socket.value.close();
|
||||
const ws = socket.value;
|
||||
socket.value = null;
|
||||
isConnected.value = false;
|
||||
ws.close();
|
||||
}
|
||||
|
||||
function sendMessage(text, isPrivate = false) {
|
||||
|
||||
Reference in New Issue
Block a user