Skip to content

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

Go

Revert "fix(mobile): refresh active chat when realtime stalls (#6325)" (#6374)

Naiyuan Qing11e2906feec6
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
index f1cbf24752..474c3424bf 100644
--- a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
@@ -33,7 +33,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Alert,
- AppState,
KeyboardAvoidingView,
Platform,
View,
@@ -58,11 +57,6 @@ import {
pendingChatTaskOptions,
taskMessagesOptions,
} from "@/data/queries/chat";
-import {
- ACTIVE_CHAT_POLL_INTERVAL_MS,
- refetchActiveChat,
- shouldPollActiveChat,
-} from "@/data/queries/chat-polling";
import {
useCreateChatSession,
useDeleteChatSession,
@@ -98,19 +92,6 @@ 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
@@ -213,43 +194,6 @@ 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-
@@ -259,6 +203,7 @@ 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.ts
deleted file mode 100644
index a4864dfe17..0000000000
--- a/apps/mobile/data/queries/chat-polling.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-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.ts
deleted file mode 100644
index 94e3c485ae..0000000000
--- a/apps/mobile/data/queries/chat-polling.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 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.ts
index ea87c1024f..6b8e2e1b4f 100644
--- a/apps/mobile/data/queries/chat.ts
+++ b/apps/mobile/data/queries/chat.ts
@@ -10,18 +10,14 @@
* 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).
*
- * 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.
+ * `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).
*/
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) =>
@@ -65,7 +61,7 @@ export const chatMessagesOptions = (sessionId: string | null) =>
queryKey: chatKeys.messages(sessionId ?? ""),
queryFn: ({ signal }) => api.listChatMessages(sessionId!, { signal }),
enabled: !!sessionId,
- staleTime: CHAT_CACHE_STALE_MS,
+ staleTime: Infinity,
});
export const pendingChatTaskOptions = (sessionId: string | null) =>
@@ -73,7 +69,7 @@ export const pendingChatTaskOptions = (sessionId: string | null) =>
queryKey: chatKeys.pendingTask(sessionId ?? ""),
queryFn: ({ signal }) => api.getPendingChatTask(sessionId!, { signal }),
enabled: !!sessionId,
- staleTime: CHAT_CACHE_STALE_MS,
+ staleTime: Infinity,
});
export const taskMessagesOptions = (taskId: string | null | undefined) =>