Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(mobile): refresh active chat when realtime stalls (#6325)
LiaoyuanNing@TTC08abec1873f0
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsxindex 474c3424bf..f1cbf24752 100644--- a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx@@ -33,6 +33,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {Alert,+ AppState,KeyboardAvoidingView,Platform,View,@@ -57,6 +58,11 @@ import {pendingChatTaskOptions,taskMessagesOptions,} from "@/data/queries/chat";+import {+ ACTIVE_CHAT_POLL_INTERVAL_MS,+ refetchActiveChat,+ shouldPollActiveChat,+} from "@/data/queries/chat-polling";import {useCreateChatSession,useDeleteChatSession,@@ -92,6 +98,19 @@ export default function ChatTab() {const [activeSessionId, setActiveSessionId] = useState<string | null>(null);const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);const [agentPickerOpen, setAgentPickerOpen] = useState(false);+ const [isAppActive, setIsAppActive] = useState(+ () => AppState.currentState === "active",+ );++ // React Navigation tracks tab focus, not whether iOS has backgrounded the+ // app. Keep the pull fallback strictly foreground-only so it never turns+ // into background polling when timers happen to survive a transition.+ useEffect(() => {+ const sub = AppState.addEventListener("change", (nextState) => {+ setIsAppActive(nextState === "active");+ });+ return () => sub.remove();+ }, []);// Bridge to the chat-sessions formSheet route. Mirror local// activeSessionId into the store so the picker can render the current@@ -194,6 +213,43 @@ export default function ChatTab() {setActiveSessionId(null);});+ const isFocused = useIsFocused();++ // A chat that becomes visible must not depend on a reconnect or a fresh WS+ // event to catch up. This also recovers a session after a tab/app switch.+ useFocusEffect(+ useCallback(() => {+ if (isAppActive && activeSessionId) {+ void refetchActiveChat(qc, activeSessionId);+ }+ }, [activeSessionId, isAppActive, qc]),+ );++ // WebSocket is the fast path, not the sole source of truth. While an active+ // task is visible, pull its messages, task pointer, and persisted progress+ // every four seconds. Stop immediately if the tab loses focus or the task+ // completes, so idle/background chats consume no polling traffic.+ useEffect(() => {+ if (+ !activeSessionId ||+ !shouldPollActiveChat(+ isFocused,+ isAppActive,+ activeSessionId,+ pendingTask?.task_id,+ )+ ) {+ return;+ }+ const sessionId = activeSessionId;+ const refresh = () => {+ void refetchActiveChat(qc, sessionId, pendingTask?.task_id);+ };+ refresh();+ const timer = setInterval(refresh, ACTIVE_CHAT_POLL_INTERVAL_MS);+ return () => clearInterval(timer);+ }, [activeSessionId, isAppActive, isFocused, pendingTask?.task_id, qc]);+// Exit text-selection mode whenever the chat tab loses focus. Expo// Router bottom tabs stay mounted across tab switches, so a plain// useEffect cleanup wouldn't fire — useFocusEffect is the navigation-@@ -203,7 +259,6 @@ export default function ChatTab() {);// ── Auto markRead while viewing a session with unread state ──────────- const isFocused = useIsFocused();const markRead = useMarkChatSessionRead();useEffect(() => {if (!isFocused) return;diff --git a/apps/mobile/data/queries/chat-polling.test.ts b/apps/mobile/data/queries/chat-polling.test.tsnew file mode 100644index 0000000000..a4864dfe17--- /dev/null+++ b/apps/mobile/data/queries/chat-polling.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it, vi } from "vitest";+import { QueryClient } from "@tanstack/react-query";++vi.mock("@/data/api", () => ({ api: {} }));++import {+ refetchActiveChat,+ shouldPollActiveChat,+} from "./chat-polling";+import { chatKeys } from "./chat";++const SESSION = "session-1";+const TASK = "11111111-1111-4111-8111-111111111111";++describe("shouldPollActiveChat", () => {+ it.each([+ [true, true, SESSION, TASK, true],+ [false, true, SESSION, TASK, false],+ [true, false, SESSION, TASK, false],+ [true, true, null, TASK, false],+ [true, true, SESSION, null, false],+ ])("gates polling to a foreground focused session with a pending task", (tabFocused, appActive, sessionId, taskId, expected) => {+ expect(shouldPollActiveChat(tabFocused, appActive, sessionId, taskId)).toBe(expected);+ });+});++describe("refetchActiveChat", () => {+ it("refetches messages, pending state, and the server task timeline", async () => {+ const qc = new QueryClient();+ const refetch = vi.spyOn(qc, "refetchQueries").mockResolvedValue();++ await refetchActiveChat(qc, SESSION, TASK);++ expect(refetch).toHaveBeenCalledWith({ queryKey: chatKeys.messages(SESSION) });+ expect(refetch).toHaveBeenCalledWith({ queryKey: chatKeys.pendingTask(SESSION) });+ expect(refetch).toHaveBeenCalledWith({ queryKey: chatKeys.taskMessages(TASK) });+ });++ it("never requests task messages for an optimistic task id", async () => {+ const qc = new QueryClient();+ const refetch = vi.spyOn(qc, "refetchQueries").mockResolvedValue();++ await refetchActiveChat(qc, SESSION, "optimistic-123");++ expect(refetch).toHaveBeenCalledTimes(2);+ expect(refetch).not.toHaveBeenCalledWith({+ queryKey: chatKeys.taskMessages("optimistic-123"),+ });+ });+});diff --git a/apps/mobile/data/queries/chat-polling.ts b/apps/mobile/data/queries/chat-polling.tsnew file mode 100644index 0000000000..94e3c485ae--- /dev/null+++ b/apps/mobile/data/queries/chat-polling.ts@@ -0,0 +1,41 @@+/**+ * Pull fallback for an active mobile chat task.+ *+ * WebSocket events remain the fast path. This helper only refetches the three+ * caches whose freshness is visible in an open conversation, so a missed+ * event, reconnect race, or temporarily lost subscription heals without an+ * app restart. Callers must gate it to a focused chat tab with a pending task.+ */+import type { QueryClient } from "@tanstack/react-query";+import { chatKeys, isTaskMessageTaskId } from "./chat";++export const ACTIVE_CHAT_POLL_INTERVAL_MS = 4_000;++export function shouldPollActiveChat(+ isTabFocused: boolean,+ isAppActive: boolean,+ sessionId: string | null,+ taskId: string | null | undefined,+) {+ return isTabFocused && isAppActive && !!sessionId && !!taskId;+}++/** Refetch the authoritative rows and current task pointer. The timeline is+ * added only for a server-issued task UUID; optimistic ids must never reach+ * the task-messages endpoint. */+export async function refetchActiveChat(+ qc: QueryClient,+ sessionId: string,+ taskId?: string | null,+) {+ const refetches = [+ qc.refetchQueries({ queryKey: chatKeys.messages(sessionId) }),+ qc.refetchQueries({ queryKey: chatKeys.pendingTask(sessionId) }),+ ];+ if (isTaskMessageTaskId(taskId)) {+ refetches.push(+ qc.refetchQueries({ queryKey: chatKeys.taskMessages(taskId) }),+ );+ }+ await Promise.all(refetches);+}diff --git a/apps/mobile/data/queries/chat.ts b/apps/mobile/data/queries/chat.tsindex 6b8e2e1b4f..ea87c1024f 100644--- a/apps/mobile/data/queries/chat.ts+++ b/apps/mobile/data/queries/chat.ts@@ -10,14 +10,18 @@* Same shape as web's `chatKeys` in packages/core/chat/queries.ts (mobile* owns its own copy per the "mirror, don't import" rule in apps/mobile/CLAUDE.md).*- * `staleTime: Infinity` everywhere — caches are kept fresh by WS event- * handlers, not by background refetch. Foreground / reconnect invalidates- * are scoped to each owning hook (see use-chat-sessions-realtime.ts and- * use-chat-session-realtime.ts).+ * Sessions stay event-driven, but messages and a pending task use a bounded+ * stale time. A dropped realtime event must not leave an open conversation+ * permanently stuck until the app is killed; the chat tab adds a focused,+ * task-only pull fallback on top of these options.*/import { queryOptions } from "@tanstack/react-query";import { api } from "@/data/api";+/** Idle chat data may be up to this old before a normal focus refetch. Active+ * tasks are refreshed much faster by the focused polling fallback. */+export const CHAT_CACHE_STALE_MS = 30_000;+export const chatKeys = {all: (wsId: string | null) => ["chat", wsId] as const,sessions: (wsId: string | null) =>@@ -61,7 +65,7 @@ export const chatMessagesOptions = (sessionId: string | null) =>queryKey: chatKeys.messages(sessionId ?? ""),queryFn: ({ signal }) => api.listChatMessages(sessionId!, { signal }),enabled: !!sessionId,- staleTime: Infinity,+ staleTime: CHAT_CACHE_STALE_MS,});export const pendingChatTaskOptions = (sessionId: string | null) =>@@ -69,7 +73,7 @@ export const pendingChatTaskOptions = (sessionId: string | null) =>queryKey: chatKeys.pendingTask(sessionId ?? ""),queryFn: ({ signal }) => api.getPendingChatTask(sessionId!, { signal }),enabled: !!sessionId,- staleTime: Infinity,+ staleTime: CHAT_CACHE_STALE_MS,});export const taskMessagesOptions = (taskId: string | null | undefined) =>