Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(chat): collapse chat-done flicker via inline cache write (#2509)

Naiyuan Qinge8c2855746ea
diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.ts
new file mode 100644
index 0000000000..1afb3873f3
--- /dev/null
+++ b/packages/core/realtime/use-realtime-sync.test.ts
@@ -0,0 +1,117 @@
+import { QueryClient } from "@tanstack/react-query";
+import { describe, expect, it, vi } from "vitest";
+import { chatKeys } from "../chat/queries";
+import type { ChatDonePayload, ChatMessage, ChatPendingTask } from "../types";
+import { applyChatDoneToCache } from "./use-realtime-sync";
+
+const sessionId = "session-1";
+const taskId = "task-1";
+const messagesKey = chatKeys.messages(sessionId);
+const pendingKey = chatKeys.pendingTask(sessionId);
+
+function createQueryClient() {
+ return new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ },
+ });
+}
+
+function userMessage(): ChatMessage {
+ return {
+ id: "msg-user",
+ chat_session_id: sessionId,
+ role: "user",
+ content: "hello",
+ task_id: null,
+ created_at: "2026-05-13T05:00:00Z",
+ };
+}
+
+function donePayload(overrides: Partial<ChatDonePayload> = {}): ChatDonePayload {
+ return {
+ chat_session_id: sessionId,
+ task_id: taskId,
+ message_id: "msg-assistant",
+ content: "done",
+ elapsed_ms: 1234,
+ created_at: "2026-05-13T05:00:02Z",
+ ...overrides,
+ };
+}
+
+describe("applyChatDoneToCache", () => {
+ it("writes the assistant message before clearing pending task", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage()]);
+ qc.setQueryData<ChatPendingTask>(pendingKey, {
+ task_id: taskId,
+ status: "running",
+ });
+
+ const setQueryData = vi.spyOn(qc, "setQueryData");
+
+ applyChatDoneToCache(qc, donePayload());
+
+ expect(setQueryData.mock.calls[0]?.[0]).toEqual(messagesKey);
+ expect(setQueryData.mock.calls[1]?.[0]).toEqual(pendingKey);
+ expect(qc.getQueryData<ChatPendingTask>(pendingKey)).toEqual({});
+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)).toEqual([
+ userMessage(),
+ {
+ id: "msg-assistant",
+ chat_session_id: sessionId,
+ role: "assistant",
+ content: "done",
+ task_id: taskId,
+ created_at: "2026-05-13T05:00:02Z",
+ elapsed_ms: 1234,
+ },
+ ]);
+ });
+
+ it("does not duplicate a replayed chat done event", () => {
+ const qc = createQueryClient();
+ const assistant: ChatMessage = {
+ id: "msg-assistant",
+ chat_session_id: sessionId,
+ role: "assistant",
+ content: "done",
+ task_id: taskId,
+ created_at: "2026-05-13T05:00:02Z",
+ elapsed_ms: 1234,
+ };
+ qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage(), assistant]);
+ qc.setQueryData<ChatPendingTask>(pendingKey, {
+ task_id: taskId,
+ status: "running",
+ });
+
+ applyChatDoneToCache(qc, donePayload());
+
+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)).toEqual([
+ userMessage(),
+ assistant,
+ ]);
+ expect(qc.getQueryData<ChatPendingTask>(pendingKey)).toEqual({});
+ });
+
+ it("falls back to invalidation-only when older servers omit message fields", () => {
+ const qc = createQueryClient();
+ qc.setQueryData<ChatMessage[]>(messagesKey, [userMessage()]);
+ qc.setQueryData<ChatPendingTask>(pendingKey, {
+ task_id: taskId,
+ status: "running",
+ });
+
+ applyChatDoneToCache(
+ qc,
+ donePayload({ message_id: undefined, content: undefined }),
+ );
+
+ expect(qc.getQueryData<ChatMessage[]>(messagesKey)).toEqual([
+ userMessage(),
+ ]);
+ expect(qc.getQueryData<ChatPendingTask>(pendingKey)).toEqual({});
+ });
+});
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index b0d7914d79..9893be4409 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useRef } from "react";
-import { useQueryClient } from "@tanstack/react-query";
+import { useQueryClient, type QueryClient } from "@tanstack/react-query";
import type { WSClient } from "../api/ws-client";
import type { StoreApi, UseBoundStore } from "zustand";
import type { AuthState } from "../auth/store";
@@ -62,6 +62,7 @@ import type {
TaskFailedPayload,
TaskCancelledPayload,
ChatDonePayload,
+ ChatMessage,
ChatPendingTask,
InvitationCreatedPayload,
} from "../types";
@@ -70,6 +71,42 @@ const chatWsLogger = createLogger("chat.ws");
const logger = createLogger("realtime-sync");
+export function applyChatDoneToCache(
+ qc: QueryClient,
+ payload: ChatDonePayload,
+) {
+ const sessionId = payload.chat_session_id;
+ const taskId = payload.task_id;
+ const messageId = payload.message_id;
+ const content = payload.content;
+ if (messageId && content !== undefined) {
+ qc.setQueryData<ChatMessage[] | undefined>(
+ chatKeys.messages(sessionId),
+ (old) => {
+ if (!old) return old; // first fetch will pick it up
+ // Idempotent against reconnect replay.
+ if (old.some((m) => m.id === messageId)) return old;
+ const assistant: ChatMessage = {
+ id: messageId,
+ chat_session_id: sessionId,
+ role: "assistant",
+ content,
+ task_id: taskId,
+ created_at: payload.created_at ?? new Date().toISOString(),
+ elapsed_ms: payload.elapsed_ms ?? null,
+ };
+ return [...old, assistant];
+ },
+ );
+ }
+ // Replacement is in the messages list now; safe to drop pending.
+ qc.setQueryData(chatKeys.pendingTask(sessionId), {});
+ // Authoritative refetch reconciles redaction / migrations / clients
+ // that took the fallback branch above.
+ qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
+}
+
export interface RealtimeSyncStores {
authStore: UseBoundStore<StoreApi<AuthState>>;
}
@@ -568,13 +605,21 @@ export function useRealtimeSync(
chatWsLogger.info("chat:done (global)", {
task_id: payload.task_id,
chat_session_id: payload.chat_session_id,
+ has_message: !!payload.message_id,
});
- // Assistant message was just written and task flipped out of 'running'.
- // Clear pending-task cache immediately so the live-timeline-vs-assistant
- // race window collapses to zero — the subsequent refetch will confirm.
- qc.setQueryData(chatKeys.pendingTask(payload.chat_session_id), {});
- qc.invalidateQueries({ queryKey: chatKeys.messages(payload.chat_session_id) });
- qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
+ // Inline-insert the assistant message into the messages cache BEFORE
+ // clearing pending-task. Both writes land in the same React render
+ // tick, so ChatMessageList sees `pendingAlreadyPersisted === true`
+ // and the live TimelineView unmounts only after AssistantMessage has
+ // mounted — no flicker window. This applies TkDodo's "combine
+ // setQueryData (active query) + invalidateQueries (others)" pattern
+ // (https://tkdodo.eu/blog/using-web-sockets-with-react-query).
+ //
+ // Falls back to invalidate-only when the server omits the message
+ // payload (older builds). Older clients hitting a newer server also
+ // work: they ignore the extra fields and rely on the invalidate
+ // below, which keeps the old behavior alive.
+ applyChatDoneToCache(qc, payload);
invalidatePendingAggregate();
// Assistant message just landed → has_unread may have flipped to true.
invalidateSessionLists();
@@ -645,9 +690,12 @@ export function useRealtimeSync(
task_id: payload.task_id,
chat_session_id: payload.chat_session_id,
});
- qc.setQueryData(chatKeys.pendingTask(payload.chat_session_id), {});
- qc.invalidateQueries({ queryKey: chatKeys.messages(payload.chat_session_id) });
- qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
+ // `chat:done` (broadcast immediately before this event in CompleteTask)
+ // already wrote the assistant message into the messages cache and
+ // cleared `chatKeys.pendingTask`. This event is now only responsible
+ // for refreshing the per-user cross-session aggregate that drives the
+ // FAB indicator — `chat:done` is per-session and doesn't carry that
+ // information.
invalidatePendingAggregate();
});
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 932a846f76..7f09e3b4f7 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -289,7 +289,16 @@ export interface ChatMessageEventPayload {
export interface ChatDonePayload {
chat_session_id: string;
task_id: string;
+ /**
+ * Server populates these from the freshly-persisted assistant ChatMessage
+ * row so the WS handler can write it into the messages cache inline. Older
+ * servers (pre-#2123) only sent chat_session_id + task_id; treat every field
+ * below as optional and fall back to a refetch when absent.
+ */
+ message_id?: string;
content?: string;
+ elapsed_ms?: number;
+ created_at?: string;
}
export interface ChatSessionReadPayload {
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 747d3e99e6..b333923891 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -991,21 +991,24 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
// For chat tasks, save assistant reply and broadcast chat:done. The
// resume pointer was already persisted inside the transaction above.
if task.ChatSessionID.Valid {
+ var assistantMsg *db.ChatMessage
var payload protocol.TaskCompletedPayload
if err := json.Unmarshal(result, &payload); err == nil && payload.Output != "" {
// Same unescape as the issue-comment path above: literal `\n` from
// agent stdout becomes a real newline so the chat panel renders
// paragraph breaks instead of one wall of prose.
body := util.UnescapeBackslashEscapes(payload.Output)
- if _, err := s.Queries.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ row, err := s.Queries.CreateChatMessage(ctx, db.CreateChatMessageParams{
ChatSessionID: task.ChatSessionID,
Role: "assistant",
Content: redact.Text(body),
TaskID: task.ID,
ElapsedMs: computeChatElapsedMs(task),
- }); err != nil {
+ })
+ if err != nil {
slog.Error("failed to save assistant chat message", "task_id", util.UUIDToString(task.ID), "error", err)
} else {
+ assistantMsg = &row
// Event-driven unread: stamp unread_since on the first unread
// assistant message. No-op if the session already has unread.
// If the user is actively viewing the session, the frontend's
@@ -1015,7 +1018,7 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
}
}
}
- s.broadcastChatDone(ctx, task)
+ s.broadcastChatDone(ctx, task, assistantMsg)
}
// Reconcile agent status
@@ -1630,21 +1633,32 @@ func (s *TaskService) ResolveTaskWorkspaceID(ctx context.Context, task db.AgentT
return ""
}
-func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQueue) {
+func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQueue, msg *db.ChatMessage) {
workspaceID := s.ResolveTaskWorkspaceID(ctx, task)
if workspaceID == "" {
return
}
+ payload := protocol.ChatDonePayload{
+ ChatSessionID: util.UUIDToString(task.ChatSessionID),
+ TaskID: util.UUIDToString(task.ID),
+ }
+ if msg != nil {
+ payload.MessageID = util.UUIDToString(msg.ID)
+ payload.Content = msg.Content
+ if msg.CreatedAt.Valid {
+ payload.CreatedAt = msg.CreatedAt.Time.UTC().Format(time.RFC3339Nano)
+ }
+ if msg.ElapsedMs.Valid {
+ payload.ElapsedMs = msg.ElapsedMs.Int64
+ }
+ }
s.Bus.Publish(events.Event{
Type: protocol.EventChatDone,
WorkspaceID: workspaceID,
ActorType: "system",
ActorID: "",
ChatSessionID: util.UUIDToString(task.ChatSessionID),
- Payload: protocol.ChatDonePayload{
- ChatSessionID: util.UUIDToString(task.ChatSessionID),
- TaskID: util.UUIDToString(task.ID),
- },
+ Payload: payload,
})
}
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index fd49e70ebc..616f6edec2 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -74,11 +74,18 @@ type ChatMessagePayload struct {
CreatedAt string `json:"created_at"`
}
-// ChatDonePayload is broadcast when an agent finishes responding to a chat message.
+// ChatDonePayload is broadcast when an agent finishes responding to a chat
+// message. Carries the freshly-persisted assistant ChatMessage so the client
+// can write it into the messages cache inline — avoids a refetch round-trip
+// during the live-timeline → AssistantMessage handoff that previously caused
+// a visible flicker (#2123).
type ChatDonePayload struct {
ChatSessionID string `json:"chat_session_id"`
TaskID string `json:"task_id"`
- Content string `json:"content"`
+ MessageID string `json:"message_id,omitempty"`
+ Content string `json:"content,omitempty"`
+ ElapsedMs int64 `json:"elapsed_ms,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
}
// ChatSessionReadPayload is broadcast when the creator marks a session as read.