Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): recover mobile websocket connections and message windows (#1066)

Generbef47b53db26
diff --git a/scripts/ci/native-oauth-desktop.test.ts b/scripts/ci/native-oauth-desktop.test.ts
index 0e7a3e508..563a4f058 100644
--- a/scripts/ci/native-oauth-desktop.test.ts
+++ b/scripts/ci/native-oauth-desktop.test.ts
@@ -3,20 +3,33 @@ import { resolve } from "node:path"
import { describe, expect, it } from "vitest"
const root = resolve(import.meta.dirname, "../../src/desktop/src-tauri")
const read = (file: string) => readFileSync(resolve(root, file), "utf8")
-type Capability = { identifier: string; local?: boolean; remote?: { urls: string[] }; windows: string[]; platforms?: string[]; permissions: (string | { identifier: string })[] }
+type Capability = { identifier: string; local?: boolean; remote?: { urls: string[] }; windows: string[]; webviews?: string[]; platforms?: string[]; permissions: (string | { identifier: string })[] }
type Config = { app: { security: { capabilities: (string | Capability)[] } }; build: { frontendDist: string }; plugins?: { "deep-link"?: unknown } }
const production: Config = JSON.parse(read("tauri.conf.json"))
const development: Config = JSON.parse(read("tauri.dev.conf.json"))
const capabilities = (config: Config): Capability[] => config.app.security.capabilities.map(c => typeof c === "string" ? JSON.parse(read(`capabilities/${c === "desktop-capability" ? "desktop" : c}.json`)) : c)
describe("desktop native OAuth security configuration", () => {
- it.each([production, development])("grants the app-local frontend only the scoped native OAuth capability", config => {
+ it.each([production, development])("keeps desktop raw IPC disabled and scopes mobile event listeners to the trusted main window", config => {
const merged = capabilities(config)
- for (const permission of merged.flatMap(c => c.permissions).map(p => typeof p === "string" ? p : p.identifier)) {
- expect(permission).not.toMatch(/^(?:core:default$|core:event:|deep-link:|store:)/)
+ const isProduction = config === production
+ const lifecycleIdentifier = isProduction ? "window-lifecycle-mobile" : "window-lifecycle-dev"
+ const lifecycle = merged.filter(c => c.identifier === lifecycleIdentifier)
+ expect(lifecycle).toHaveLength(1)
+ expect(lifecycle[0]).toMatchObject({
+ windows: ["main"],
+ platforms: ["android", "iOS"],
+ local: !isProduction,
+ remote: { urls: [isProduction ? "https://alook.ai" : "http://localhost:3000"] },
+ permissions: ["core:event:allow-listen", "core:event:allow-unlisten"],
+ })
+ expect(lifecycle[0]!.webviews ?? []).toEqual([])
+ for (const capability of merged.filter(c => c.identifier !== lifecycleIdentifier)) {
+ for (const permission of capability.permissions.map(p => typeof p === "string" ? p : p.identifier)) {
+ expect(permission).not.toMatch(/^(?:core:default$|core:event:|deep-link:|store:)/)
+ }
}
const oauth = merged.find(c => c.permissions.includes("native-oauth"))!
- const isProduction = config === production
expect(config.build.frontendDist).toBe(isProduction ? "alook-recovery://localhost/bootstrap" : "http://localhost:3000")
expect(oauth.windows).toEqual(["main"])
expect(oauth.platforms).toEqual(expect.arrayContaining(["linux", "macOS", "windows"]))
diff --git a/scripts/ci/workflow-contract.test.ts b/scripts/ci/workflow-contract.test.ts
index bcddee0c8..9eefe5aa0 100644
--- a/scripts/ci/workflow-contract.test.ts
+++ b/scripts/ci/workflow-contract.test.ts
@@ -1292,6 +1292,14 @@ describe("Desktop image clipboard", () => {
expect(desktopDevConfig.app.security.capabilities).toEqual([
"desktop-capability",
"external-links",
+ expect.objectContaining({
+ identifier: "window-lifecycle-dev",
+ local: true,
+ windows: ["main"],
+ platforms: ["android", "iOS"],
+ remote: { urls: ["http://localhost:3000"] },
+ permissions: ["core:event:allow-listen", "core:event:allow-unlisten"],
+ }),
expect.objectContaining({ identifier: "native-oauth-dev", local: true, remote: { urls: ["http://localhost:3000"] }, permissions: ["native-oauth"] }),
expect.objectContaining({
identifier: "mobile-share-image-dev",
diff --git a/src/desktop/src-tauri/capabilities/window-lifecycle-mobile.json b/src/desktop/src-tauri/capabilities/window-lifecycle-mobile.json
new file mode 100644
index 000000000..70d3498f9
--- /dev/null
+++ b/src/desktop/src-tauri/capabilities/window-lifecycle-mobile.json
@@ -0,0 +1,10 @@
+{
+ "$schema": "../gen/schemas/mobile-schema.json",
+ "identifier": "window-lifecycle-mobile",
+ "description": "Native window lifecycle listeners for the trusted main WebView",
+ "windows": ["main"],
+ "platforms": ["android", "iOS"],
+ "local": false,
+ "remote": { "urls": ["https://alook.ai"] },
+ "permissions": ["core:event:allow-listen", "core:event:allow-unlisten"]
+}
diff --git a/src/desktop/src-tauri/tauri.conf.json b/src/desktop/src-tauri/tauri.conf.json
index 2ff42e6ad..56ec52d6d 100644
--- a/src/desktop/src-tauri/tauri.conf.json
+++ b/src/desktop/src-tauri/tauri.conf.json
@@ -52,6 +52,7 @@
"mobile-share-image-mobile",
"mobile-system-notification-mobile",
"native-back-mobile",
+ "window-lifecycle-mobile",
"file-save"
]
}
diff --git a/src/desktop/src-tauri/tauri.dev.conf.json b/src/desktop/src-tauri/tauri.dev.conf.json
index d91c34afb..bd282cc85 100644
--- a/src/desktop/src-tauri/tauri.dev.conf.json
+++ b/src/desktop/src-tauri/tauri.dev.conf.json
@@ -5,6 +5,15 @@
"capabilities": [
"desktop-capability",
"external-links",
+ {
+ "identifier": "window-lifecycle-dev",
+ "description": "Native window lifecycle listeners for the trusted development WebView",
+ "windows": ["main"],
+ "platforms": ["android", "iOS"],
+ "local": true,
+ "remote": { "urls": ["http://localhost:3000"] },
+ "permissions": ["core:event:allow-listen", "core:event:allow-unlisten"]
+ },
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "native-oauth-dev",
diff --git a/src/web/blog/src/app/blog/observability.dom.test.tsx b/src/web/blog/src/app/blog/observability.dom.test.tsx
index c11948260..9c56dbaf9 100644
--- a/src/web/blog/src/app/blog/observability.dom.test.tsx
+++ b/src/web/blog/src/app/blog/observability.dom.test.tsx
@@ -37,10 +37,15 @@ beforeEach(() => {
installTelemetrySink(event => events.push(event));
vi.stubGlobal("matchMedia", vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })));
});
-afterEach(async () => {
- await act(async () => { retireTelemetry(); clearActions(); });
- vi.unstubAllGlobals();
-});
+async function cleanupObservabilityTest() {
+ try {
+ await act(async () => { retireTelemetry(); clearActions(); });
+ await vi.dynamicImportSettled();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+}
+afterEach(cleanupObservabilityTest);
it("executes the actual index loader and renders ordered featured/recent links before reporting committed content", async () => {
const navigation = beginNavigation("/blog")!;
@@ -156,3 +161,38 @@ it("renders a related article title before its summary and retains its destinati
related.title, "Decide whether I need an agent or a chatbot", related.readingTime,
]);
});
+
+it("keeps globals until cleanup finishes draining the real dynamic imports", async () => {
+ const originalDrain = vi.dynamicImportSettled.bind(vi);
+ let release!: () => void;
+ const pending = new Promise<void>(resolve => { release = resolve; });
+ const drain = vi.spyOn(vi, "dynamicImportSettled").mockImplementationOnce(async () => {
+ await originalDrain();
+ await pending;
+ });
+ const originalGlobal = globalThis.matchMedia;
+ let completed = false;
+ const cleanup = cleanupObservabilityTest().then(() => { completed = true; });
+ try {
+ await waitFor(() => expect(drain).toHaveBeenCalledOnce());
+ expect(completed).toBe(false);
+ expect(globalThis.matchMedia).toBe(originalGlobal);
+ } finally {
+ release();
+ try { await cleanup; } finally { drain.mockRestore(); }
+ }
+ expect(completed).toBe(true);
+ expect(globalThis.matchMedia).not.toBe(originalGlobal);
+});
+
+it("restores globals when cleanup rejects and preserves the original rejection", async () => {
+ const error = new Error("import drain rejected");
+ const originalGlobal = globalThis.matchMedia;
+ const drain = vi.spyOn(vi, "dynamicImportSettled").mockRejectedValueOnce(error);
+ try {
+ await expect(cleanupObservabilityTest()).rejects.toBe(error);
+ expect(globalThis.matchMedia).not.toBe(originalGlobal);
+ } finally {
+ drain.mockRestore();
+ }
+});
diff --git a/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts b/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts
index b0674c698..562b432b9 100644
--- a/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts
+++ b/src/web/src/components/community/shell/community-ws-reconnect-overlay.dom.test.ts
@@ -1,16 +1,22 @@
import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, fireEvent, render as renderDom, screen } from "@/test/react-dom-harness"
+import { act, fireEvent, render as renderDom, screen, setupUser, waitFor } from "@/test/react-dom-harness"
import { tid } from "@/lib/community/testids"
-import { QueryClient } from "@tanstack/react-query"
+import { QueryClient, QueryClientProvider, QueryObserver } from "@tanstack/react-query"
import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"
import { CommunityRuntimeProvider } from "@/stores/community/runtime"
let registry: CommunityDbRegistry
import { CommunityWsReconnectBoundary } from "./community-ws-reconnect-overlay"
+import { communityKeys } from "@/lib/query-keys"
+import { messageReconcileOptions } from "@/hooks/community/community-ws/reconnect-messages"
+import { ApiError } from "@/lib/errors"
+const apiFetchMock = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))
describe("CommunityWsReconnectBoundary", () => {
beforeEach(() => {
registry = createCommunityDbRegistry(new QueryClient(), "viewer")
+ apiFetchMock.mockReset()
vi.stubGlobal("matchMedia", vi.fn(() => ({matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn()})))
vi.stubGlobal("IntersectionObserver", class {
@@ -29,11 +35,11 @@ describe("CommunityWsReconnectBoundary", () => {
function render() {
const focus = vi.spyOn(HTMLElement.prototype, "focus")
- const renderer = renderDom(React.createElement(CommunityRuntimeProvider, { value: { runtime: registry.runtime } }, React.createElement(
+ const renderer = renderDom(React.createElement(QueryClientProvider, { client: registry.queryClient }, React.createElement(CommunityRuntimeProvider, { value: { runtime: registry.runtime } }, React.createElement(
CommunityWsReconnectBoundary,
null,
React.createElement("button", { type: "button" }, "Underlying action"),
- )))
+ ))))
return { renderer, focus }
}
@@ -78,4 +84,34 @@ describe("CommunityWsReconnectBoundary", () => {
expect(screen.queryByTestId(tid.wsReconnectOverlay)).not.toBeInTheDocument()
expect(renderer.container.querySelector(".contents")).not.toHaveAttribute("inert")
})
+
+ it("keeps healthy transport independent and retries the failed active message window by keyboard", async () => {
+ await registry.preload()
+ const key = communityKeys.channelMessages("repair-status")
+ registry.queryClient.setQueryData(key, {
+ pages: [{ messages: [{ id: "m_1", seq: 1 }], latestSeq: 1 }], pageParams: [{ mode: "newest" }],
+ })
+ const observer = new QueryObserver(registry.queryClient, { queryKey: key, queryFn: async () => undefined, staleTime: Infinity })
+ const unsubscribe = observer.subscribe(() => undefined)
+ const reconnect = vi.fn()
+ registry.runtime.ws.actions.bindReconnectNow(reconnect)
+ apiFetchMock.mockRejectedValue(new ApiError("unavailable", 503))
+ const { renderer } = render()
+ await act(async () => {
+ await registry.queryClient.query({ ...messageReconcileOptions(registry.queryClient, { kind: "channel", scopeId: "repair-status" }, key), retryDelay: 0 }).catch(() => undefined)
+ })
+ expect(screen.getByTestId(tid.messageRepairStatus)).toHaveTextContent("Messages could not refresh")
+ expect(screen.queryByTestId(tid.wsReconnectOverlay)).not.toBeInTheDocument()
+ expect(renderer.container.querySelector(".contents")).not.toHaveAttribute("inert")
+ expect(apiFetchMock).toHaveBeenCalledTimes(3)
+ apiFetchMock.mockResolvedValue({ messages: [{ id: "m_1", seq: 1, content: "recovered" }], latestSeq: 1 })
+ const retry = screen.getByTestId(tid.messageRepairRetry)
+ retry.focus()
+ await setupUser().keyboard("{Enter}")
+ await waitFor(() => expect(screen.queryByTestId(tid.messageRepairStatus)).not.toBeInTheDocument())
+ await waitFor(() => expect(registry.collections.messages.get("m_1")?.content).toBe("recovered"))
+ expect(reconnect).not.toHaveBeenCalled()
+ expect(apiFetchMock).toHaveBeenCalledTimes(4)
+ unsubscribe()
+ })
})
diff --git a/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx b/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx
index f2adde77e..39825a983 100644
--- a/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx
+++ b/src/web/src/components/community/shell/community-ws-reconnect-overlay.tsx
@@ -1,19 +1,48 @@
"use client"
-import type { ReactNode } from "react"
+import { useCallback, useSyncExternalStore, type ReactNode } from "react"
+import { useQueryClient } from "@tanstack/react-query"
import { WifiOff } from "lucide-react"
import { Button } from "@/components/ui/button"
import { tid } from "@/lib/community/testids"
import { useCommunityWsStore } from "@/stores/community/ws"
+import { isFailedMessageRepair, retryFailedMessageRepairs } from "@/hooks/community/community-ws/reconnect-messages"
export function CommunityWsReconnectBoundary({ children }: { children: ReactNode }) {
const connectionStatus = useCommunityWsStore((state) => state.connectionStatus)
const reconnectNow = useCommunityWsStore((state) => state.reconnectNow)
+ const queryClient = useQueryClient()
+ const subscribe = useCallback((notify: () => void) => queryClient.getQueryCache().subscribe(notify), [queryClient])
+ const snapshot = useCallback(() => queryClient.getQueryCache().getAll().some((query) => isFailedMessageRepair(queryClient, query)), [queryClient])
+ const repairFailed = useSyncExternalStore(subscribe, snapshot, () => false)
const failed = connectionStatus === "failed"
return (
<>
<div className="contents">{children}</div>
+ {!failed && repairFailed && (
+ <div
+ role="status"
+ aria-live="polite"
+ aria-atomic="true"
+ data-testid={tid.messageRepairStatus}
+ className="fixed bottom-4 right-4 z-50 flex max-w-xs items-center gap-3 rounded-lg border bg-popover p-3 text-popover-foreground shadow-(--e2)"
+ >
+ <div className="min-w-0 flex-1">
+ <p className="font-heading text-sm font-medium">Messages could not refresh</p>
+ <p className="text-xs text-muted-foreground">Cached content is still available.</p>
+ </div>
+ <Button
+ type="button"
+ variant="secondary"
+ data-testid={tid.messageRepairRetry}
+ onClick={() => { void retryFailedMessageRepairs(queryClient).catch(() => undefined) }}
+ className="h-11 shrink-0 sm:h-9"
+ >
+ Retry
+ </Button>
+ </div>
+ )}
{failed && (
<div
role="status"
diff --git a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
index 968718ff7..0114f0e88 100644
--- a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
@@ -44,7 +44,8 @@ import {
} from "./test-harness"
const scheduleGapRepairMock = vi.hoisted(() => vi.fn(() => null))
-vi.mock("@/hooks/community/community-ws/reconnect-messages", () => ({
+vi.mock("@/hooks/community/community-ws/reconnect-messages", async original => ({
+ ...await original<typeof import("@/hooks/community/community-ws/reconnect-messages")>(),
scheduleFocusedMessageGapRepair: (...args: unknown[]) => scheduleGapRepairMock(...args),
}))
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
index 14f1f4dbe..8579520f0 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
@@ -13,8 +13,15 @@ import {
import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
import { ApiError } from "@/lib/errors"
+import { CONVERSATION_READ_TIMEOUT_MS, ConversationReadTimeoutError } from "@/lib/community/conversation-read"
+import { messageWindowOptions } from "@/lib/community/message-window"
import {
+ cancelMessageRepairs,
+ isFailedMessageRepair,
+ messageReconcileOptions,
reconcileFocusedMessageQueries,
+ retryFailedMessageRepairs,
+ reconcileWindow,
scheduleFocusedMessageGapRepair,
} from "./reconnect-messages"
@@ -110,6 +117,156 @@ beforeEach(() => {
})
describe("focused message reconnect catch-up", () => {
+ it("rejects an inactive window without a live entry owner", async () => {
+ const { client } = await createCommunityQueryOwner("a")
+ const key = communityKeys.channelMessages("inactive")
+ const { unsubscribe } = seedActiveQuery(client, key)
+ unsubscribe()
+ const before = client.getQueryData(key)
+ await reconcileWindow(client, { kind: "channel", scopeId: "inactive" }, key)
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ expect(client.getQueryData(key)).toBe(before)
+ })
+
+ it("lets an active message observer retain shared work after its entry owner retires", async () => {
+ const { client, registry } = await createCommunityQueryOwner("a")
+ const key = communityKeys.channelMessages("handoff")
+ seedActiveQuery(client, key).unsubscribe()
+ const parentKey = ["entry-owner"]
+ client.setQueryData(parentKey, true)
+ const parent = new QueryObserver(client, { queryKey: parentKey, queryFn: async () => true, staleTime: Infinity })
+ const stopParent = parent.subscribe(() => undefined)
+ const controller = new AbortController()
+ let signal: AbortSignal | undefined
+ let release!: (value: unknown) => void
+ apiFetchMock.mockImplementation((_url: string, request: { signal: AbortSignal }) => {
+ signal = request.signal
+ return new Promise((resolve) => { release = resolve })
+ })
+ const repair = reconcileWindow(client, { kind: "channel", scopeId: "handoff" }, key, 0, undefined, {
+ query: client.getQueryCache().find({ queryKey: parentKey, exact: true })!, signal: controller.signal,
+ })
+ await vi.waitFor(() => expect(signal).toBeDefined())
+ const observer = new QueryObserver(client, { queryKey: key, queryFn: async () => undefined, staleTime: Infinity })
+ const stopWindow = observer.subscribe(() => undefined)
+ controller.abort()
+ stopParent()
+ expect(signal?.aborted).toBe(false)
+ release({ messages: [{ id: "m_2", seq: 2, content: "owned by window" }], latestSeq: 2 })
+ await repair
+ expect(registry.collections.messages.get("m_2")?.content).toBe("owned by window")
+ stopWindow()
+ })
+
+ it.each([0, 500, 502, 503, 504, "deadline"] as const)("retries transient %s through the existing Query and publishes canonical content", async (failure) => {
+ const { client, registry } = await createCommunityQueryOwner("a")
+ const key = communityKeys.channelMessages("retry")
+ const { unsubscribe } = seedActiveQuery(client, key)
+ apiFetchMock.mockRejectedValueOnce(failure === "deadline" ? new ConversationReadTimeoutError() : new ApiError("temporary", failure))
+ .mockResolvedValueOnce({ messages: [{ id: "m_2", seq: 2, content: "refreshed" }], latestSeq: 2 })
+ await client.query({ ...messageReconcileOptions(client, { kind: "channel", scopeId: "retry" }, key), retryDelay: 0 })
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ expect(registry.collections.messages.get("m_2")?.content).toBe("refreshed")
+ unsubscribe()
+ })
+
+ it("exhausts after two retries, keeps cached pages and lets the same repair entry recover", async () => {
+ const { client, registry } = await createCommunityQueryOwner("a")
+ const key = communityKeys.channelMessages("exhausted")
+ const { unsubscribe } = seedActiveQuery(client, key)
+ const before = client.getQueryData(key)
+ apiFetchMock.mockRejectedValue(new ApiError("unavailable", 503))
+ await expect(client.query({ ...messageReconcileOptions(client, { kind: "channel", scopeId: "exhausted" }, key), retryDelay: 0 })).rejects.toThrow("unavailable")
+ expect(apiFetchMock).toHaveBeenCalledTimes(3)
+ expect(client.getQueryData(key)).toBe(before)
+ const repair = client.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true })!
+ expect(isFailedMessageRepair(client, repair)).toBe(true)
+ apiFetchMock.mockResolvedValue({ messages: [{ id: "m_2", seq: 2, content: "recovered" }], latestSeq: 2 })
+ await retryFailedMessageRepairs(client)
+ expect(apiFetchMock).toHaveBeenCalledTimes(4)
+ expect(registry.collections.messages.get("m_2")?.content).toBe("recovered")
+ expect(isFailedMessageRepair(client, repair)).toBe(false)
+ unsubscribe()
+ })
+
+ it("keeps one-page repair cursors usable by the real subsequent newer-page fetch", async () => {
+ const { client, registry } = await createCommunityQueryOwner("a")
+ const key = communityKeys.channelMessages("scroll-newer")
+ const { unsubscribe } = seedActiveQuery(client, key)
+ apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "m_2", seq: 2 }], latestSeq: 100 })
+ .mockResolvedValueOnce({ messages: [{ id: "m_3", seq: 3, createdAt: "2026-08-15T00:00:03.000Z" }], latestSeq: 100, hasMoreNewer: true, newerCursor: "next-page" })
+ .mockResolvedValueOnce({ messages: [{ id: "m_4", seq: 4, content: "from scroll" }], latestSeq: 100, hasMoreNewer: true, newerCursor: "later-page" })
+ await reconcileFocusedMessageQueries(client, "channel", "scroll-newer")
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ const observer = new InfiniteQueryObserver(client, {
+ ...messageWindowOptions(client, "scroll-newer", { mode: "newest" }), queryKey: key, staleTime: Infinity,
+ })
+ const stop = observer.subscribe(() => undefined)
+ await observer.fetchPreviousPage()
+ expect(apiFetchMock).toHaveBeenCalledTimes(3)
+ expect(apiFetchMock.mock.calls[2][0]).toBe("/api/community/channels/scroll-newer/messages?since=next-page")
+ expect(registry.collections.messages.get("m_4")?.content).toBe("from scroll")
+ expect(client.getQueryData<{ pages: unknown[]; pageParams: unknown[] }>(key)?.pageParams).toEqual([
+ { mode: "newer", cursor: "next-page" }, { mode: "newest" }, { mode: "older", cursor: "older-2" },
+ ])
+ stop(); unsubscribe()
+ })
+
+ it.each([400, 401, 429, 501, "unknown", "abort"] as const)("does not automatically retry terminal %s", async (failure) => {
+ const { client } = await createCommunityQueryOwner("a")
+ const key = communityKeys.channelMessages("terminal")
+ const { unsubscribe } = seedActiveQuery(client, key)
+ const error = failure === "unknown" ? new Error("unknown") : failure === "abort" ? new DOMException("retired", "AbortError") : new ApiError("terminal", failure)
+ apiFetchMock.mockRejectedValue(error)
+ await expect(client.query({ ...messageReconcileOptions(client, { kind: "channel", scopeId: "terminal" }, key), retryDelay: 0 })).rejects.toBe(error)
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ unsubscribe()
+ })
+
+ it("bounds hung HTTP attempts with the existing deadline and aborts every request", async () => {
+ const { client } = await createCommunityQueryOwner("a")
+ const key = communityKeys.channelMessages("hung")
+ const { unsubscribe } = seedActiveQuery(client, key)
+ const before = client.getQueryData(key)
+ const signals: AbortSignal[] = []
+ apiFetchMock.mockImplementation((_url: string, options: { signal: AbortSignal }) => {
+ signals.push(options.signal)
+ return new Promise(() => undefined)
+ })
+ vi.useFakeTimers()
+ try {
+ const result = client.query({ ...messageReconcileOptions(client, { kind: "channel", scopeId: "hung" }, key), retryDelay: 0 }).catch((error: unknown) => error)
+ await vi.advanceTimersByTimeAsync(CONVERSATION_READ_TIMEOUT_MS * 3 + 10)
+ expect(await result).toBeInstanceOf(ConversationReadTimeoutError)
+ expect(signals).toHaveLength(3)
+ expect(signals.every((signal) => signal.aborted)).toBe(true)
+ expect(client.getQueryData(key)).toBe(before)
+ } finally { vi.useRealTimers(); unsubscribe() }
+ })
+
+ it.each(["background", "window"] as const)("cancels pending retry on %s retirement and starts a fresh repair later", async (reason) => {
+ const { client } = await createCommunityQueryOwner("a")
+ const key = communityKeys.channelMessages("cancelled")
+ const first = seedActiveQuery(client, key)
+ apiFetchMock.mockRejectedValue(new ApiError("offline", 0))
+ vi.useFakeTimers()
+ try {
+ const result = reconcileFocusedMessageQueries(client, "channel", "cancelled")
+ await vi.advanceTimersByTimeAsync(1)
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ if (reason === "window") first.unsubscribe()
+ await cancelMessageRepairs(client, reason === "window")
+ await result
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ const next = reason === "window" ? seedActiveQuery(client, key) : first
+ apiFetchMock.mockResolvedValue({ messages: [], latestSeq: 2 })
+ await reconcileFocusedMessageQueries(client, "channel", "cancelled")
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ next.unsubscribe()
+ } finally { vi.useRealTimers(); first.unsubscribe() }
+ })
+
it.each(["account", "parent", "replacement"] as const)("drops old reconnect data after %s changes", async (change) => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const key = communityKeys.channelMessages("child")
@@ -161,6 +318,35 @@ describe("focused message reconnect catch-up", () => {
client.clear()
})
+ it("propagates one shared non-cancellation failure to both callers and retains a usable retry", async () => {
+ const { client, registry } = await createCommunityQueryOwner("a")
+ const key = communityKeys.channelMessages("shared-failure")
+ const { unsubscribe } = seedActiveQuery(client, key)
+ const before = client.getQueryData(key)
+ const error = new Error("shared read failed")
+ let reject!: (reason: unknown) => void
+ apiFetchMock.mockReturnValueOnce(new Promise((_, rejectPromise) => { reject = rejectPromise }))
+ const first = reconcileWindow(client, { kind: "channel", scopeId: "shared-failure" }, key)
+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
+ const shared = reconcileWindow(client, { kind: "channel", scopeId: "shared-failure" }, key)
+ const settled = Promise.allSettled([first, shared])
+ reject(error)
+ for (const result of await settled) {
+ expect(result.status).toBe("rejected")
+ if (result.status === "rejected") expect(result.reason).toBe(error)
+ }
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ expect(client.getQueryData(key)).toBe(before)
+ const repair = client.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true })!
+ expect(isFailedMessageRepair(client, repair)).toBe(true)
+ apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "m_2", seq: 2, content: "retry recovered" }], latestSeq: 2 })
+ await retryFailedMessageRepairs(client)
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ expect(registry.collections.messages.get("m_2")?.content).toBe("retry recovered")
+ expect(isFailedMessageRepair(client, repair)).toBe(false)
+ unsubscribe()
+ })
+
it("refreshes a completed query variant when another variant still holds the scope owner", async () => {
const { client: client } = await createCommunityQueryOwner("a")
const key = communityKeys.channelMessages("variants")
@@ -489,7 +675,7 @@ describe("focused message reconnect catch-up", () => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const queryKey = communityKeys.channelMessages("ch_offline")
const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
- apiFetchMock.mockRejectedValueOnce(new ApiError("unavailable", 503))
+ apiFetchMock.mockRejectedValue(new ApiError("unavailable", 503))
await expect(
reconcileFocusedMessageQueries(queryClient, "channel", "ch_offline"),
@@ -644,7 +830,7 @@ describe("focused message reconnect catch-up", () => {
await vi.waitFor(() => expect(observer.getCurrentResult().isSuccess).toBe(true))
const pagination = observer.fetchNextPage()
await vi.waitFor(() => expect(olderCalls).toBe(1))
- apiFetchMock.mockResolvedValueOnce(newest).mockResolvedValueOnce({ ...newest, latestSeq: 5 }).mockResolvedValueOnce({
+ apiFetchMock.mockResolvedValueOnce(newest).mockResolvedValueOnce({
messages: [3, 4, 5].map((seq) => ({ id: `m_${seq}`, seq, createdAt: `2026-08-15T00:00:0${seq}.000Z` })), latestSeq: 5, hasMoreNewer: false,
})
const cancel = vi.spyOn(client, "cancelQueries")
@@ -655,7 +841,7 @@ describe("focused message reconnect catch-up", () => {
releaseReplay(older)
releaseStale(older)
await Promise.all([foreground, gap, pagination])
- expect(apiFetchMock).toHaveBeenCalledTimes(3)
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
expect(cancel).toHaveBeenCalledOnce()
expect(olderCalls).toBe(2)
expect(client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(key)?.pages.flatMap((entry) => entry.messages.map((row) => row.id))).toEqual(["m_2", "m_3", "m_4", "m_5", "m_1"])
@@ -760,11 +946,13 @@ describe("focused message reconnect catch-up", () => {
const { queryFn, unsubscribe } = seedEmptyActiveQuery(client, key)
apiFetchMock.mockResolvedValue({ messages: [], latestSeq: 0, hasMore: false })
await scheduleFocusedMessageGapRepair(client, { kind, scopeId }, 2)
- expect(apiFetchMock).toHaveBeenCalledTimes(8)
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
expect(client.getQueryData<{ pages: Array<{ messages: unknown[] }> }>(key)?.pages[0].messages).toEqual([])
- apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "m_later", seq: 1 }], latestSeq: 1, hasMore: false })
+ const repair = client.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true })!
+ expect(isFailedMessageRepair(client, repair)).toBe(true)
+ apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "m_later", seq: 2 }], latestSeq: 2, hasMore: false })
await reconcileFocusedMessageQueries(client, kind, scopeId)
- expect(apiFetchMock).toHaveBeenCalledTimes(9)
+ expect(apiFetchMock).toHaveBeenCalledTimes(3)
expect(client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(key)?.pages[0].messages.map((message) => message.id)).toEqual(["m_later"])
expect(queryFn).not.toHaveBeenCalled()
unsubscribe()
@@ -946,7 +1134,7 @@ describe("focused message reconnect catch-up", () => {
unsubscribe()
})
- it("walks only forward delta pages and preserves every cached history page", async () => {
+ it("prefetches one forward delta page and preserves every cached history page", async () => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const queryKey = communityKeys.channelMessages("ch_1")
const { queryFn, unsubscribe } = seedActiveQuery(queryClient, queryKey)
@@ -986,11 +1174,10 @@ describe("focused message reconnect catch-up", () => {
await reconcileFocusedMessageQueries(queryClient, "channel", "ch_1")
- expect(apiFetchMock).toHaveBeenCalledTimes(3)
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual([
"/api/community/channels/ch_1/messages",
"/api/community/channels/ch_1/messages?since=2026-08-15T00%3A00%3A02.000Z%7Cm_2",
- "/api/community/channels/ch_1/messages?since=2026-08-15T00%3A00%3A03.000Z%7Cm_3",
])
expect(queryFn).not.toHaveBeenCalled()
expect(queryClient.getQueryData<{
@@ -1005,11 +1192,11 @@ describe("focused message reconnect catch-up", () => {
}>(queryKey)).toMatchObject({
pages: [
{
- messages: [{ id: "m_2" }, { id: "m_3" }, { id: "m_4" }],
+ messages: [{ id: "m_2" }, { id: "m_3" }],
latestSeq: 4,
hasMore: true,
cursor: "older-2",
- hasMoreNewer: false,
+ hasMoreNewer: true,
},
{ messages: [{ id: "m_1" }] },
],
@@ -1021,7 +1208,7 @@ describe("focused message reconnect catch-up", () => {
unsubscribe()
})
- it("caps forward catch-up at eight pages and leaves the newer cursor resumable", async () => {
+ it("caps forward catch-up at one page and leaves the newer cursor resumable", async () => {
const { client: queryClient } = await createCommunityQueryOwner("a")
const queryKey = communityKeys.channelMessages("ch_bounded")
const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
@@ -1052,9 +1239,9 @@ describe("focused message reconnect catch-up", () => {
await reconcileFocusedMessageQueries(queryClient, "channel", "ch_bounded")
- expect(apiFetchMock).toHaveBeenCalledTimes(9)
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
expect(apiFetchMock.mock.calls.at(-1)?.[0]).toBe(
- "/api/community/channels/ch_bounded/messages?since=2026-08-15T00%3A00%3A09.000Z%7Cm_9",
+ "/api/community/channels/ch_bounded/messages?since=2026-08-15T00%3A00%3A02.000Z%7Cm_2",
)
expect(queryClient.getQueryData<{
pages: Array<{
@@ -1063,9 +1250,9 @@ describe("focused message reconnect catch-up", () => {
newerCursor?: string
}>
}>(queryKey)?.pages[0]).toMatchObject({
- messages: Array.from({ length: 9 }, (_, index) => ({ id: `m_${index + 2}` })),
+ messages: Array.from({ length: 2 }, (_, index) => ({ id: `m_${index + 2}` })),
hasMoreNewer: true,
- newerCursor: "2026-08-15T00:00:10.000Z|m_10",
+ newerCursor: "2026-08-15T00:00:03.000Z|m_3",
})
unsubscribe()
})
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
index 1db747c4a..a0007b4ae 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
@@ -1,8 +1,8 @@
-import { CancelledError, hashKey, queryOptions, type InfiniteData, type QueryClient, type QueryKey } from "@tanstack/react-query"
+import { CancelledError, hashKey, queryOptions, type InfiniteData, type Query, type QueryClient, type QueryKey } from "@tanstack/react-query"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityMessages, retireCommunityChannelReading } from "@/lib/community-db/sync"
-import { isConversationAnchorMissingError } from "@/lib/community/conversation-read"
+import { ConversationReadTimeoutError, withConversationReadDeadline, isConversationAnchorMissingError } from "@/lib/community/conversation-read"
import { ApiError, isAbortError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import { getCommunityRuntime } from "@/stores/community/runtime"
@@ -12,7 +12,6 @@ import { buildMessagesUrl, messageWindowIdentity } from "@/lib/community/message
type MessageCache = InfiniteData<MessagesWindowPage, MessagesPageParam>
type GapRepairScope = { kind: "channel" | "dm"; scopeId: string; serverId?: string }
-const MAX_CATCH_UP_PAGES = 8
function isMessageCache(value: unknown): value is MessageCache { return !!value && typeof value === "object" && Array.isArray((value as MessageCache).pages) && Array.isArray((value as MessageCache).pageParams) }
function messagesKey(scope: GapRepairScope) { return scope.kind === "channel" ? communityKeys.channelMessages(scope.scopeId) : communityKeys.dmMessages(scope.scopeId) }
function targetKey(key: QueryKey) { return [...key, "reconcile-target"] }
@@ -33,61 +32,134 @@ function mergeWindow(cache: MessageCache, refreshed: MessagesPage, catchUp: Mess
return { ...cache, pages }
}
-export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, landing?: { page: MessagesPage; param: MessagesPageParam }) {
+type MessageRepairOwner = { query: Query; signal: AbortSignal }
+type MessageRepairReceipt = {
+ token: ReturnType<typeof captureCommunityLiveSnapshotToken>
+ window: Query | undefined
+ scope: GapRepairScope
+ key: QueryKey
+ owner?: MessageRepairOwner
+}
+
+function repairReceipt(query: Query): MessageRepairReceipt | undefined {
+ return query.meta?.communityMessageRepair as MessageRepairReceipt | undefined
+}
+
+function assertRepairCurrent(queryClient: QueryClient, receipt: MessageRepairReceipt, signal?: AbortSignal) {
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, receipt.token, signal)
+ if (!receipt.window || queryClient.getQueryCache().find({ queryKey: receipt.key, exact: true }) !== receipt.window) {
+ throw new DOMException("Retired message window", "AbortError")
+ }
+ if (receipt.window.isActive()) return
+ const owner = receipt.owner
+ if (!owner || owner.signal.aborted || queryClient.getQueryCache().get(owner.query.queryHash) !== owner.query
+ || !owner.query.isActive() && owner.query.state.fetchStatus === "idle") {
+ throw new DOMException("Retired message repair owner", "AbortError")
+ }
+}
+
+export function isFailedMessageRepair(queryClient: QueryClient, query: Query): boolean {
+ const receipt = repairReceipt(query)
+ if (!receipt?.window?.isActive() || query.state.status !== "error" || query.state.fetchStatus !== "idle"
+ || isAbortError(query.state.error) || query.state.error instanceof CancelledError
+ || isConversationAnchorMissingError(query.state.error)) return false
+ try { assertRepairCurrent(queryClient, receipt); return true } catch { return false }
+}
+
+export function cancelMessageRepairs(queryClient: QueryClient, inactiveOnly = false) {
+ return queryClient.cancelQueries({ predicate: (query) => {
+ const receipt = repairReceipt(query)
+ if (!receipt || query.state.fetchStatus === "idle") return false
+ if (!inactiveOnly) return true
+ try { assertRepairCurrent(queryClient, receipt); return false } catch { return true }
+ } })
+}
+
+export function retryFailedMessageRepairs(queryClient: QueryClient) {
+ return Promise.all(queryClient.getQueryCache().getAll()
+ .filter((query) => isFailedMessageRepair(queryClient, query))
+ .map((query) => {
+ const receipt = repairReceipt(query)!
+ return reconcileWindow(queryClient, receipt.scope, receipt.key)
+ }))
+}
+
+export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, landing?: { page: MessagesPage; param: MessagesPageParam }, owner?: MessageRepairOwner) {
const scopeId = scope.scopeId
const token = captureCommunityLiveSnapshotToken(queryClient, scopeId), registry = getCommunityDbRegistry(queryClient)
const channel = registry?.collections.channels.get(scopeId)
const serverId = scope.kind === "dm" ? null : channel ? channel.serverId : scope.serverId
const originalQuery = queryClient.getQueryCache().find({ queryKey: key, exact: true })
- const receipt = { token, window: originalQuery }
+ const receipt: MessageRepairReceipt = { token, window: originalQuery, scope, key, owner }
+ const pendingDirection = originalQuery?.state.fetchStatus === "fetching" ? originalQuery.state.fetchMeta?.fetchMore?.direction : undefined
+ let paginationReplayed = false
+ let landingPage = landing
+ let prefetched: { param: MessagesPageParam; page: MessagesPage } | undefined
+ const repairKey: QueryKey = [...key, "reconcile"]
return queryOptions({
- queryKey: [...key, "reconcile"], staleTime: 0, retry: false,
+ queryKey: repairKey, staleTime: 0,
+ retry: (failureCount, error) => failureCount < 2 && (error instanceof ConversationReadTimeoutError
+ || (error instanceof ApiError && [0, 500, 502, 503, 504].includes(error.status))),
+ retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 4000) + Math.floor(Math.random() * 250),
+ networkMode: "online",
meta: { communityMessageRepair: receipt },
queryFn: async ({ signal }) => {
- const assert = () => { assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal); if (queryClient.getQueryCache().find({ queryKey: key, exact: true }) !== originalQuery) throw new DOMException("Retired message window", "AbortError") }
+ const assert = () => assertRepairCurrent(queryClient, receipt, signal)
await registry?.ready
assert()
const data = originalQuery?.state.data
if (!isMessageCache(data) || !data.pageParams[0]) return { latestSeq: 0 }
- const pendingDirection = originalQuery?.state.fetchStatus === "fetching" ? originalQuery.state.fetchMeta?.fetchMore?.direction : undefined
await queryClient.cancelQueries({ queryKey: key, exact: true }, { revert: true, silent: true })
assert()
const tag = messageWindowIdentity(key)?.tag ?? null
- const load = async (param: MessagesPageParam) => { assert(); const page = await apiFetchCommunity<MessagesPage>(url(scopeId, param, tag), { signal, assertActive: assert }, token); assert(); return page }
- let landingPage = landing
- let highWater = latest(data)
- let paginationReplayed = false
+ const load = async (param: MessagesPageParam) => {
+ assert()
+ const page = await withConversationReadDeadline(signal, (readSignal) => apiFetchCommunity<MessagesPage>(
+ url(scopeId, param, tag), { signal: readSignal, assertActive: assert }, token,
+ ))
+ assert()
+ return page
+ }
+ const target = () => queryClient.getQueryData<number>(targetKey(key)) ?? 0
+ const prefetch = async (current: MessageCache, refreshed: MessagesPage) => {
+ if (prefetched || Math.max(refreshed.latestSeq ?? 0, target()) <= latest(current, false)) return
+ const nextCursor = cursor(current)
+ if (!nextCursor && (refreshed.latestSeq ?? 0) >= target()) return
+ const param: MessagesPageParam = nextCursor ? { mode: "since", since: nextCursor } : current.pageParams[0]
+ prefetched = { param, page: await load(param) }
+ }
+ const publish = (refreshed: MessagesPage) => {
+ assert()
+ const catchUp = prefetched ? [prefetched.page] : []
+ publishCommunityMessages(queryClient, { channelId: scopeId, messages: [refreshed, ...catchUp].flatMap((page) => page.messages), proof: { token, signal } })
+ queryClient.setQueryData<MessageCache>(key, (cache) => isMessageCache(cache) ? mergeWindow(cache, refreshed, catchUp) : cache)
+ }
try {
- for (let pass = 0; pass < MAX_CATCH_UP_PAGES; pass++) {
- const target = () => queryClient.getQueryData<number>(targetKey(key)) ?? 0
- const current = originalQuery?.state.data
- if (!isMessageCache(current) || !current.pageParams[0]) return { latestSeq: highWater }
- const refreshed = landingPage && hashKey([landingPage.param]) === hashKey([current.pageParams[0]])
- ? landingPage.page : await load(current.pageParams[0])
- landingPage = undefined
- const catchUp: MessagesPage[] = []
- if (!isMessageCache(originalQuery?.state.data)) return { latestSeq: highWater }
- let nextCursor = cursor(current)
- highWater = Math.max(highWater, refreshed.latestSeq ?? 0)
- for (let pageIndex = 0; nextCursor && pageIndex < MAX_CATCH_UP_PAGES && (highWater > latest(current) || target() > highWater); pageIndex++) {
- const page = await load({ mode: "since", since: nextCursor })
- catchUp.push(page)
- highWater = Math.max(highWater, page.latestSeq ?? 0)
- if (!page.hasMoreNewer || !page.newerCursor) { if (highWater < target()) continue; break }
- nextCursor = page.newerCursor
- }
+ const current = originalQuery?.state.data
+ if (!isMessageCache(current) || !current.pageParams[0]) return { latestSeq: 0 }
+ if (!landingPage || hashKey([landingPage.param]) !== hashKey([current.pageParams[0]])) {
+ landingPage = { param: current.pageParams[0], page: await load(current.pageParams[0]) }
+ }
+ const refreshed = landingPage.page
+ if (!isMessageCache(originalQuery?.state.data)) return { latestSeq: 0 }
+ await prefetch(current, refreshed)
+ publish(refreshed)
+ if (pendingDirection && !paginationReplayed) {
+ paginationReplayed = true
+ await originalQuery?.fetch(undefined, { meta: { fetchMore: { direction: pendingDirection } } })
assert()
- publishCommunityMessages(queryClient, { channelId: scopeId, messages: [refreshed, ...catchUp].flatMap((page) => page.messages), proof: { token, signal } })
- queryClient.setQueryData<MessageCache>(key, (cache) => isMessageCache(cache) ? mergeWindow(cache, refreshed, catchUp) : cache)
- if (pendingDirection && !paginationReplayed) {
- paginationReplayed = true
- await originalQuery?.fetch(undefined, { meta: { fetchMore: { direction: pendingDirection } } })
- assert()
- }
- if (highWater >= (queryClient.getQueryData<number>(targetKey(key)) ?? 0)) break
+ }
+ const afterPagination = originalQuery?.state.data
+ if (!prefetched && isMessageCache(afterPagination) && target() > latest(afterPagination, false)) {
+ await prefetch(afterPagination, refreshed)
+ publish(refreshed)
}
assert()
- return { latestSeq: highWater }
+ const latestSeq = Math.max(refreshed.latestSeq ?? 0, prefetched?.page.latestSeq ?? 0)
+ if (latestSeq < target() && !(prefetched?.page.hasMoreNewer && prefetched.page.newerCursor)) {
+ throw new Error("Messages have not caught up yet")
+ }
+ return { latestSeq }
} catch (error) {
assert()
if (!(error instanceof ApiError) || (error.status !== 403 && error.status !== 404) || isConversationAnchorMissingError(error)) throw error
@@ -96,37 +168,53 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
preserveQuery: queryClient.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true }),
})
return { latestSeq: 0 }
- } finally {
- const repair = queryClient.getQueryCache().find({ queryKey: [...key, "reconcile"], exact: true })
- if (repair?.meta?.communityMessageRepair === receipt) queryClient.removeQueries({ queryKey: targetKey(key), exact: true })
}
},
})
}
-export function reconcileWindow(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, target = 0, landing?: { page: MessagesPage; param: MessagesPageParam }) {
+export function reconcileWindow(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, target = 0, landing?: { page: MessagesPage; param: MessagesPageParam }, owner?: MessageRepairOwner) {
const query = queryClient.getQueryCache().find({ queryKey: key, exact: true })
if (!query) return Promise.resolve()
queryClient.setQueryData<number>(targetKey(key), (current) => Math.max(current ?? 0, target))
if (!isMessageCache(query.state.data)) return query.fetch().then(() => undefined)
const repairKey = [...key, "reconcile"]
const repair = queryClient.getQueryCache().find({ queryKey: repairKey, exact: true })
- const receipt = repair?.meta?.communityMessageRepair as { token: ReturnType<typeof captureCommunityLiveSnapshotToken>; window: typeof query } | undefined
+ const receipt = repair && repairReceipt(repair)
if (receipt) {
let current = receipt.window === query
- try { assertCommunityLiveSnapshotTokenCurrent(queryClient, receipt.token, undefined) } catch { current = false }
+ try { assertRepairCurrent(queryClient, receipt) } catch { current = false }
if (!current) queryClient.removeQueries({ queryKey: repairKey, exact: true })
+ else if (repair.state.fetchStatus !== "idle" && repair.promise) {
+ return repair.promise.then(() => undefined).catch((error: unknown) => {
+ if (!isAbortError(error) && !(error instanceof CancelledError)) throw error
+ })
+ }
+ }
+ const options = messageReconcileOptions(queryClient, scope, key, landing, owner)
+ const cancelRetiredOwner = () => {
+ const current = queryClient.getQueryCache().find({ queryKey: repairKey, exact: true })
+ if (current?.meta?.communityMessageRepair === options.meta?.communityMessageRepair && !query.isActive()) {
+ void queryClient.cancelQueries({ queryKey: repairKey, exact: true })
+ }
}
- return queryClient.query({ ...messageReconcileOptions(queryClient, scope, key, landing), select: undefined }).then(() => undefined).catch((error: unknown) => {
+ owner?.signal.addEventListener("abort", cancelRetiredOwner, { once: true })
+ return queryClient.query({ ...options, select: undefined }).then(() => undefined).catch((error: unknown) => {
if (!isAbortError(error) && !(error instanceof CancelledError)) throw error
+ }).finally(() => {
+ owner?.signal.removeEventListener("abort", cancelRetiredOwner)
+ const current = queryClient.getQueryCache().find({ queryKey: repairKey, exact: true })
+ if (current?.meta?.communityMessageRepair === options.meta?.communityMessageRepair && current?.state.status !== "error") {
+ queryClient.removeQueries({ queryKey: targetKey(key), exact: true })
+ }
})
}
-export function reconcileConversationLanding(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, page: MessagesPage, param: MessagesPageParam) {
+export function reconcileConversationLanding(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, page: MessagesPage, param: MessagesPageParam, owner: MessageRepairOwner) {
const data = queryClient.getQueryData(key)
const highWater = page.latestSeq ?? 0
if (!isMessageCache(data) || highWater <= latest(data)) return Promise.resolve()
- return reconcileWindow(queryClient, scope, key, highWater, { page, param })
+ return reconcileWindow(queryClient, scope, key, highWater, { page, param }, owner)
}
function reconcile(queryClient: QueryClient, scope: GapRepairScope, target = 0) {
diff --git a/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts b/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts
index b88a1cd7d..748d63e5b 100644
--- a/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts
@@ -103,12 +103,11 @@ describe("community foreground message reconciliation", () => {
throw new Error(`unexpected fetch: ${String(path)}`)
})
const cancel = vi.spyOn(capturedQueryClient, "cancelQueries")
- const reads = vi.spyOn(capturedQueryClient, "query")
let foreground!: void | Promise<void>; act(() => { foreground = capturedUseUserWsOptions!.onForeground!() })
await vi.waitFor(() => expect(release).toBeTypeOf("function"))
let duplicate!: void | Promise<void>, reconnect!: void | Promise<void>
act(() => { duplicate = capturedUseUserWsOptions!.onForeground!(); reconnect = capturedOnReconnect!({ reconnectDurationMs: 1_000 }) })
- await vi.waitFor(() => expect(reads.mock.calls.filter(([options]) => options.queryKey.at(-1) === "reconcile")).toHaveLength(3))
+ expect(capturedQueryClient.getQueryState([...key, "reconcile"])?.fetchStatus).toBe("fetching")
const event = messageCreate("focused", "live")
event.message.seq = 3
await act(async () => { capturedOnMessage!(event) })
diff --git a/src/web/src/hooks/community/use-community-ws.dom.test.ts b/src/web/src/hooks/community/use-community-ws.dom.test.ts
index 8089cf9f8..4eb75622a 100644
--- a/src/web/src/hooks/community/use-community-ws.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.dom.test.ts
@@ -1,7 +1,10 @@
import { act, fireEvent } from "@/test/react-dom-harness"
import { ANALYTICS_CONSENT_CHANGE_EVENT } from "@/lib/analytics-consent"
import * as funnel from "@/lib/community/funnel-analytics"
-import { getCapturedRuntime } from "./community-ws/test-harness"
+import { getCapturedRuntime, getCommunityApiFetchMock } from "./community-ws/test-harness"
+import { QueryObserver } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import { reconcileFocusedMessageQueries } from "./community-ws/reconnect-messages"
/**
* Root Community WebSocket boundary and transport-ownership tests.
*/
@@ -65,6 +68,41 @@ describe("useCommunityWs — non-community events bail", () => {
})
describe("useCommunityWs — public helper contracts", () => {
+ it.each(["background", "window"] as const)("cancels the real message repair when the root sees %s retirement", async (reason) => {
+ await mountHook()
+ const key = communityKeys.channelMessages("root-repair")
+ capturedQueryClient.setQueryData(key, {
+ pages: [{ messages: [{ id: "kept", seq: 2 }], latestSeq: 2 }], pageParams: [{ mode: "newest" }],
+ })
+ const observer = new QueryObserver(capturedQueryClient, { queryKey: key, queryFn: async () => undefined, staleTime: Infinity })
+ const unsubscribe = observer.subscribe(() => undefined)
+ const before = capturedQueryClient.getQueryData(key)
+ const api = getCommunityApiFetchMock()
+ const original = api.getMockImplementation()!
+ let signal: AbortSignal | undefined
+ let release!: (value: unknown) => void
+ api.mockImplementation(async (...args: unknown[]) => {
+ if (String(args[0]).includes("/root-repair/messages")) {
+ signal = (args[1] as { signal: AbortSignal }).signal
+ return new Promise((resolve) => { release = resolve })
+ }
+ return original(...args)
+ })
+ try {
+ const result = reconcileFocusedMessageQueries(capturedQueryClient, "channel", "root-repair")
+ await vi.waitFor(() => expect(signal).toBeDefined())
+ await act(async () => {
+ if (reason === "background") capturedConnectionStateChange!("suspended")
+ else unsubscribe()
+ await result
+ })
+ expect(signal?.aborted).toBe(true)
+ release({ messages: [{ id: "late", seq: 3 }], latestSeq: 3 })
+ await act(async () => { await Promise.resolve() })
+ expect(capturedQueryClient.getQueryData(key)).toBe(before)
+ } finally { api.mockImplementation(original); unsubscribe() }
+ })
+
it("returns void after mounting the single root transport", async () => {
expect(await mountHook({ viewerUserId: "u_viewer" })).toBeUndefined()
})
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index b4fcedd11..7e30050d6 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -5,6 +5,7 @@ import { useCommunityRuntime, type CommunityRuntime } from "@/stores/community/r
import { useCallback, useEffect, useRef } from "react"
import { useQueryClient } from "@tanstack/react-query"
+import { cancelMessageRepairs } from "@/hooks/community/community-ws/reconnect-messages"
import {
useUserWs,
type UserWsConnectionPhase,
@@ -240,8 +241,15 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
return connectionControllerRef.current
}, [runtime.ws.actions.setConnectionStatus])
const handleConnectionStateChange = useCallback((phase: UserWsConnectionPhase) => {
+ if (phase === "suspended") void cancelMessageRepairs(queryClient)
getConnectionController().handlePhase(phase)
- }, [getConnectionController])
+ }, [getConnectionController, queryClient])
+ useEffect(() => {
+ const unsubscribe = queryClient.getQueryCache().subscribe(() => {
+ void cancelMessageRepairs(queryClient, true)
+ })
+ return () => { unsubscribe(); void cancelMessageRepairs(queryClient) }
+ }, [queryClient])
const viewerUserIdRef = useRef<string | null>(options?.viewerUserId ?? null)
const hasAuthenticatedRef = useRef(false)
const viewerUserId = options?.viewerUserId ?? null
diff --git a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
index c40630bb8..d9c3c6bb6 100644
--- a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
@@ -797,6 +797,7 @@ describe("native entry freshness with authoritative newer attention", () => {
if (explicitAnchor) packet.selection = { reason: "explicit_anchor", anchorMessageId: "m1" }
load.mockResolvedValueOnce(packet)
const original = await client.query(conversationEntryOptions(client, selectedTarget))
+ expect(client.getQueryCache().find({ queryKey: original.windowKey, exact: true })?.isActive()).toBe(false)
load.mockClear()
publishAccountAttentionSnapshot(client, {
snapshot: { scopes: [{ scopeId: packet.channelId, channelId: packet.channelId, serverId: packet.channel.serverId,
@@ -829,4 +830,41 @@ describe("native entry freshness with authoritative newer attention", () => {
expect(registry.collections.readStates.get(packet.channelId)?.lastReadSeq).toBe(1)
hook.unmount()
})
+
+ it.each(["cancel", "replacement", "account", "access"] as const)("retires an entry-owned repair before a message observer exists on %s", async (reason) => {
+ const { client, registry } = await setup()
+ const options = conversationEntryOptions(client, target)
+ load.mockResolvedValueOnce(fixture())
+ const original = await client.query(options)
+ const window = client.getQueryCache().find({ queryKey: original.windowKey, exact: true })!
+ expect(window.isActive()).toBe(false)
+ const before = client.getQueryData(original.windowKey)
+ const newer = fixture()
+ newer.page.latestSeq = 2
+ newer.page.hasMoreNewer = true
+ newer.page.newerCursor = "next"
+ const held = deferred<unknown>()
+ let signal: AbortSignal | undefined
+ load.mockImplementation((url: string, request: { signal: AbortSignal }) => {
+ if (url.includes("entry=1")) return Promise.resolve(newer)
+ signal = request.signal
+ return held.promise
+ })
+ const result = client.query({ ...options, staleTime: 0 }).catch((error: unknown) => error)
+ await waitFor(() => expect(signal).toBeDefined())
+ expect(window.isActive()).toBe(false)
+ await act(async () => {
+ if (reason === "cancel") await client.cancelQueries({ queryKey: options.queryKey, exact: true })
+ else if (reason === "replacement") client.removeQueries({ queryKey: options.queryKey, exact: true })
+ else if (reason === "account") registry.runtime.ws.actions.activateProfileAccount("other")
+ else registry.runtime.ws.actions.revokeChannelAccess("s1", "c1")
+ })
+ if (reason === "cancel" || reason === "replacement") expect(signal?.aborted).toBe(true)
+ await act(async () => {
+ held.resolve({ messages: [{ ...newer.messages[0], id: "m2", seq: 2 }], latestSeq: 2, hasMoreNewer: false })
+ await result
+ })
+ expect(client.getQueryData(original.windowKey)).toBe(before)
+ expect(registry.collections.messages.has("m2")).toBe(false)
+ })
})
diff --git a/src/web/src/hooks/community/use-conversation-entry.ts b/src/web/src/hooks/community/use-conversation-entry.ts
index 0f4c1c191..8b350fe37 100644
--- a/src/web/src/hooks/community/use-conversation-entry.ts
+++ b/src/web/src/hooks/community/use-conversation-entry.ts
@@ -113,7 +113,7 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {
? current : { path: expectedPath, intent: incomingIntent })
}, [active, expectedPath, incomingIntent, resuming])
const intent = (active && !resuming) || retainedIntent.path !== expectedPath ? incomingIntent : retainedIntent.intent
- const { client, cachedResource, input, query, canonical, resource, canRead, revoked, denied, anchorMissing, localPosition } = useConversationResource(target, intent, true)
+ const { client, cachedResource, input, options: entryOptions, query, canonical, resource, canRead, revoked, denied, anchorMissing, localPosition } = useConversationResource(target, intent, true)
const canonicalInput = useMemo(() => localPosition ? { ...input, anchorMessageId: null } : input, [input, localPosition])
const entry = useMemo(() => {
const pointer = cachedResource && isChannelMetadataTokenCurrent(cachedResource.proof) ? currentConversationReadState(client, input.channelId) : undefined
@@ -146,10 +146,13 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {
if (!canRead || !window || !resource || hashKey(window.key) === hashKey(resource.windowKey)) return
const landing = client.getQueryData<MessageWindowData>(resource.windowKey)
const target = Math.max(0, ...(landing?.pages.map(page => page.latestSeq ?? 0) ?? []))
+ const owner = client.getQueryCache().find({ queryKey: entryOptions.queryKey, exact: true })
+ const controller = new AbortController()
void reconcileWindow(client, {
kind: input.serverId === null ? "dm" : "channel", scopeId: input.channelId, serverId: input.serverId ?? undefined,
- }, window.key, target).catch(() => undefined)
- }, [canRead, client, input.channelId, input.serverId, resource, window])
+ }, window.key, target, undefined, owner ? { query: owner, signal: controller.signal } : undefined).catch(() => undefined)
+ return () => controller.abort()
+ }, [canRead, client, entryOptions.queryKey, input.channelId, input.serverId, resource, window])
const activeQuery = needsCanonicalWindow ? canonicalQuery : query
const refetch = activeQuery.refetch
const retry = useCallback(() => refetch({ cancelRefetch: false }), [refetch])
diff --git a/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx b/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx
index 2aef4a859..546bafb88 100644
--- a/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx
+++ b/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx
@@ -214,12 +214,16 @@ describe("returned entry and selected message window", () => {
it("retains its readable selected window and snapshot after a repair timeout", async () => {
const { hook, client, late, key } = await holdSelectedWindowRepair()
await act(async () => late.reject(new ConversationReadTimeoutError()))
- await waitFor(() => expect(client.getQueryState([...key, "reconcile"])?.status).toBe("error"))
+ expect(client.getQueryState([...key, "reconcile"])?.status).toBe("pending")
+ expect(client.getQueryState([...key, "reconcile"])?.fetchFailureCount).toBe(1)
+ expect(hook.result.current.messages.map(message => message.id)).toEqual(["m1"])
+ expect(hook.result.current.readSnapshot?.lastReadSeq).toBe(1)
+ await waitFor(() => expect(client.getQueryState([...key, "reconcile"])?.status).toBe("error"), { timeout: 6000 })
expect(hook.result.current.messages.map(message => message.id)).toEqual(["m1"])
expect(hook.result.current.readSnapshot?.lastReadSeq).toBe(1)
expect(hook.result.current.initialPositionKnown).toBe(true)
expect(hook.result.current.initialLoadError).toBeNull()
- expect(load.mock.calls.filter(([url]) => url === "/api/community/channels/c1/messages")).toHaveLength(1)
+ expect(load.mock.calls.filter(([url]) => url === "/api/community/channels/c1/messages")).toHaveLength(3)
hook.unmount()
})
})
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index bb6972a60..c65dea06a 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -2,7 +2,7 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
import { createStore, useSelector } from "@tanstack/react-store"
-import { hashKey, useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"
+import { hashKey, useInfiniteQuery, useQuery, useQueryClient, type QueryKey } from "@tanstack/react-query"
import type { ApiRequestOptions } from "@/lib/api/client"
import { currentPageObservation, navigationForHref } from "@/lib/observability/context"
import { channelHref } from "@/lib/community/community-route"
@@ -112,7 +112,12 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const options = messageWindowOptions(client, enabled ? channelId : "__none__", initial, tag, { observation })
const queryKey = selectedWindow?.key ?? options.queryKey
const query = useInfiniteQuery({ ...options, queryKey, enabled, subscribed: enabled })
- const reconciliation = useQuery({ ...messageReconcileOptions(client, { kind: serverId === null ? "dm" : "channel", scopeId: channelId ?? "__none__", serverId: serverId ?? undefined }, queryKey), enabled: false, subscribed: enabled })
+ const repairKey: QueryKey = [...queryKey, "reconcile"]
+ const repairOptions = client.getQueryCache().find<{ latestSeq: number }>({ queryKey: repairKey, exact: true })?.options
+ const reconciliation = useQuery({ ...(repairOptions?.queryFn ? repairOptions : messageReconcileOptions(client, {
+ kind: serverId === null ? "dm" : "channel", scopeId: channelId ?? "__none__", serverId: serverId ?? undefined,
+ }, queryKey)),
+ queryKey: repairKey, enabled: false, subscribed: enabled })
const originalQuery = client.getQueryCache().find({ queryKey, exact: true })
const owner = useMemo(() => ({ present, retries, query: originalQuery, enabled }), [present, retries, originalQuery, enabled])
const committed = useRef<typeof owner | null>(null)
diff --git a/src/web/src/lib/community/conversation-entry.ts b/src/web/src/lib/community/conversation-entry.ts
index 76e9ac60c..61738920c 100644
--- a/src/web/src/lib/community/conversation-entry.ts
+++ b/src/web/src/lib/community/conversation-entry.ts
@@ -198,7 +198,7 @@ export function conversationEntryOptions(client: QueryClient, target: Conversati
await reconcileConversationLanding(client, {
kind: target.serverId === null ? "dm" : "channel", scopeId: target.channelId,
serverId: target.serverId ?? undefined,
- }, resource.windowKey, { ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages }, initial)
+ }, resource.windowKey, { ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages }, initial, { query: original!, signal })
assert()
}
return resource
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 8edbf8e48..81542a295 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -16,6 +16,8 @@ export const tid = {
messageScroller: "community-message-scroller",
wsReconnectOverlay: "community-ws-reconnect-overlay",
wsRetry: "community-ws-retry",
+ messageRepairStatus: "community-message-repair-status",
+ messageRepairRetry: "community-message-repair-retry",
initialFrame: "community-initial-frame",
initialRailPending: "community-initial-rail-pending",
initialUserBarPending: "community-initial-user-bar-pending",
diff --git a/src/web/src/lib/native-window-lifecycle.test.ts b/src/web/src/lib/native-window-lifecycle.test.ts
new file mode 100644
index 000000000..7695dcce6
--- /dev/null
+++ b/src/web/src/lib/native-window-lifecycle.test.ts
@@ -0,0 +1,197 @@
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { listenNativeWindowLifecycle } from "./native-window-lifecycle"
+
+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() })
+
+describe("native window lifecycle", () => {
+ it("returns a usable cleanup when the native current window lookup throws", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined)
+ const handlers = { resumed: vi.fn(), suspended: vi.fn() }
+ vi.stubGlobal("window", { __TAURI__: { window: { getCurrentWindow: () => { throw new Error("window unavailable") } } } })
+ const dispose = listenNativeWindowLifecycle(handlers)
+ expect(() => { dispose(); dispose() }).not.toThrow()
+ expect(warn).toHaveBeenCalledExactlyOnceWith("[ws] native lifecycle window unavailable")
+ expect(handlers.resumed).not.toHaveBeenCalled()
+ expect(handlers.suspended).not.toHaveBeenCalled()
+ })
+
+ it.each(["sync", "async"] as const)("releases the sibling and retires callbacks when %s cleanup fails", async (failure) => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined)
+ const callbacks = new Map<string, () => void>()
+ const error = new Error("cleanup failed")
+ const failedRelease = vi.fn(() => { if (failure === "sync") throw error; return Promise.reject(error) })
+ const siblingRelease = vi.fn()
+ vi.stubGlobal("window", { __TAURI__: { window: { getCurrentWindow: () => ({
+ listen: async (event: string, callback: () => void) => {
+ callbacks.set(event, callback)
+ return event === "tauri://resumed" ? failedRelease : siblingRelease
+ },
+ }) } } })
+ const handlers = { resumed: vi.fn(), suspended: vi.fn() }
+ const dispose = listenNativeWindowLifecycle(handlers)
+ await Promise.resolve()
+ expect(() => { dispose(); dispose() }).not.toThrow()
+ await Promise.resolve()
+ expect(failedRelease).toHaveBeenCalledOnce()
+ expect(siblingRelease).toHaveBeenCalledOnce()
+ expect(warn).toHaveBeenCalledExactlyOnceWith("[ws] native lifecycle cleanup failed")
+ callbacks.get("tauri://resumed")!()
+ callbacks.get("tauri://suspended")!()
+ expect(handlers.resumed).not.toHaveBeenCalled()
+ expect(handlers.suspended).not.toHaveBeenCalled()
+ })
+
+ it("isolates a throwing callback while keeping the sibling and cleanup usable", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined)
+ const callbacks = new Map<string, () => void>()
+ const release = vi.fn()
+ vi.stubGlobal("window", { __TAURI__: { window: { getCurrentWindow: () => ({
+ listen: async (event: string, callback: () => void) => { callbacks.set(event, callback); return release },
+ }) } } })
+ const handlers = { resumed: vi.fn(() => { throw new Error("consumer failed") }), suspended: vi.fn() }
+ const dispose = listenNativeWindowLifecycle(handlers)
+ await Promise.resolve()
+ expect(() => callbacks.get("tauri://resumed")!()).not.toThrow()
+ callbacks.get("tauri://suspended")!()
+ expect(handlers.resumed).toHaveBeenCalledOnce()
+ expect(handlers.suspended).toHaveBeenCalledOnce()
+ expect(warn).toHaveBeenCalledExactlyOnceWith("[ws] native lifecycle callback failed", { event: "resumed" })
+ dispose()
+ expect(release).toHaveBeenCalledTimes(2)
+ })
+
+ it.each(["resumed", "suspended"] as const)("retires the group when %s registration throws synchronously", async (failed) => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined)
+ const callbacks = new Map<string, () => void>()
+ const releases: Array<(unlisten: () => void) => void> = []
+ const release = vi.fn()
+ const listen = vi.fn((event: string, callback: () => void) => {
+ if (event === `tauri://${failed}`) throw new Error("registration failed")
+ callbacks.set(event, callback)
+ return new Promise<() => void>((resolve) => releases.push(resolve))
+ })
+ vi.stubGlobal("window", { __TAURI__: { window: { getCurrentWindow: () => ({ listen }) } } })
+ const handlers = { resumed: vi.fn(), suspended: vi.fn() }
+ const dispose = listenNativeWindowLifecycle(handlers)
+ for (const resolve of releases) resolve(release)
+ await Promise.resolve()
+ for (const callback of callbacks.values()) callback()
+ dispose()
+ expect(listen).toHaveBeenCalledTimes(failed === "resumed" ? 1 : 2)
+ expect(release).toHaveBeenCalledTimes(failed === "resumed" ? 0 : 1)
+ expect(warn).toHaveBeenCalledExactlyOnceWith("[ws] native lifecycle listener unavailable", { event: failed })
+ expect(handlers.resumed).not.toHaveBeenCalled()
+ expect(handlers.suspended).not.toHaveBeenCalled()
+ })
+
+ it("uses the current window, retires handlers immediately and releases late registrations", async () => {
+ const listeners = new Map<string, () => void>()
+ const releases = [vi.fn(), vi.fn()]
+ const registrations: Array<(value: () => void) => void> = []
+ const listen = vi.fn((event: string, handler: () => void) => {
+ listeners.set(event, handler)
+ return new Promise<() => void>((resolve) => registrations.push(resolve))
+ })
+ const getCurrentWindow = vi.fn(() => ({ listen }))
+ vi.stubGlobal("window", { __TAURI__: { window: { getCurrentWindow } } })
+ const resumed = vi.fn(), suspended = vi.fn()
+ const dispose = listenNativeWindowLifecycle({ resumed, suspended })
+ expect(getCurrentWindow).toHaveBeenCalledOnce()
+ expect([...listeners.keys()]).toEqual(["tauri://resumed", "tauri://suspended"])
+ listeners.get("tauri://suspended")!()
+ listeners.get("tauri://resumed")!()
+ expect(resumed).not.toHaveBeenCalled()
+ expect(suspended).not.toHaveBeenCalled()
+ registrations[0](releases[0])
+ await Promise.resolve()
+ dispose()
+ registrations[1](releases[1])
+ await Promise.resolve()
+ listeners.get("tauri://resumed")!()
+ listeners.get("tauri://suspended")!()
+ expect(resumed).not.toHaveBeenCalled()
+ expect(suspended).not.toHaveBeenCalled()
+ for (const release of releases) expect(release).toHaveBeenCalledOnce()
+ })
+
+ it("keeps Web and failed native registrations usable without an unhandled rejection", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined)
+ const handlers = { resumed: vi.fn(), suspended: vi.fn() }
+ vi.stubGlobal("window", {})
+ listenNativeWindowLifecycle(handlers)()
+ vi.stubGlobal("window", { __TAURI__: { window: { getCurrentWindow: () => ({
+ listen: vi.fn().mockRejectedValue(new Error("permission denied")),
+ }) } } })
+ const dispose = listenNativeWindowLifecycle(handlers)
+ await Promise.resolve()
+ await Promise.resolve()
+ dispose()
+ expect(warn).toHaveBeenCalledOnce()
+ expect(handlers.resumed).not.toHaveBeenCalled()
+ })
+
+ it("activates both registrations together and delivers only the latest buffered state", async () => {
+ const callbacks = new Map<string, () => void>()
+ const registrations: Array<(value: () => void) => void> = []
+ const release = vi.fn()
+ vi.stubGlobal("window", { __TAURI__: { window: { getCurrentWindow: () => ({
+ listen: (event: string, callback: () => void) => {
+ callbacks.set(event, callback)
+ return new Promise<() => void>((resolve) => registrations.push(resolve))
+ },
+ }) } } })
+ const handlers = { resumed: vi.fn(), suspended: vi.fn() }
+ const dispose = listenNativeWindowLifecycle(handlers)
+ registrations[1](release)
+ await Promise.resolve()
+ callbacks.get("tauri://suspended")!()
+ callbacks.get("tauri://resumed")!()
+ expect(handlers.resumed).not.toHaveBeenCalled()
+ expect(handlers.suspended).not.toHaveBeenCalled()
+ registrations[0](release)
+ await Promise.resolve()
+ expect(handlers.resumed).toHaveBeenCalledOnce()
+ expect(handlers.suspended).not.toHaveBeenCalled()
+ callbacks.get("tauri://suspended")!()
+ expect(handlers.suspended).toHaveBeenCalledOnce()
+ dispose()
+ expect(release).toHaveBeenCalledTimes(2)
+ })
+ it.each([
+ ["resumed", "before"], ["resumed", "after"], ["suspended", "before"], ["suspended", "after"],
+ ] as const)("retires the whole group when %s fails with its sibling resolving %s failure", async (failed, order) => {
+ vi.spyOn(console, "warn").mockImplementation(() => undefined)
+ const callbacks = new Map<string, () => void>()
+ const registrations = new Map<string, { resolve: (value: () => void) => void; reject: (error: Error) => void }>()
+ const release = vi.fn()
+ vi.stubGlobal("window", { __TAURI__: { window: { getCurrentWindow: () => ({
+ listen: (name: string, callback: () => void) => {
+ callbacks.set(name, callback)
+ return new Promise<() => void>((resolve, reject) => { registrations.set(name, { resolve, reject }) })
+ },
+ }) } } })
+ const handlers = { resumed: vi.fn(), suspended: vi.fn() }
+ const dispose = listenNativeWindowLifecycle(handlers)
+ const sibling = failed === "resumed" ? "suspended" : "resumed"
+ if (order === "before") {
+ registrations.get(`tauri://${sibling}`)!.resolve(release)
+ await Promise.resolve()
+ }
+ callbacks.get("tauri://suspended")!()
+ expect(handlers.suspended).not.toHaveBeenCalled()
+ registrations.get(`tauri://${failed}`)!.reject(new Error("registration denied"))
+ await Promise.resolve()
+ await Promise.resolve()
+ if (order === "after") {
+ registrations.get(`tauri://${sibling}`)!.resolve(release)
+ await Promise.resolve()
+ }
+ callbacks.get("tauri://resumed")!()
+ callbacks.get("tauri://suspended")!()
+ dispose()
+ expect(handlers.resumed).not.toHaveBeenCalled()
+ expect(handlers.suspended).not.toHaveBeenCalled()
+ expect(release).toHaveBeenCalledOnce()
+ })
+
+})
diff --git a/src/web/src/lib/native-window-lifecycle.ts b/src/web/src/lib/native-window-lifecycle.ts
new file mode 100644
index 000000000..5c1cb17fb
--- /dev/null
+++ b/src/web/src/lib/native-window-lifecycle.ts
@@ -0,0 +1,65 @@
+type Unlisten = () => void | Promise<void>
+type NativeWindow = {
+ listen: (event: string, handler: () => void) => Promise<Unlisten>
+}
+type LifecycleWindow = Window & {
+ __TAURI__?: { window?: { getCurrentWindow?: () => NativeWindow } }
+}
+
+export function listenNativeWindowLifecycle(handlers: { resumed: () => void; suspended: () => void }): () => void {
+ if (typeof window === "undefined") return () => undefined
+ let current: NativeWindow | undefined
+ try { current = (window as LifecycleWindow).__TAURI__?.window?.getCurrentWindow?.() } catch {
+ console.warn("[ws] native lifecycle window unavailable")
+ }
+ if (!current) return () => undefined
+ let disposed = false
+ let active = false
+ let pending: keyof typeof handlers | null = null
+ const unlisteners: Unlisten[] = []
+ const release = (unlisten: Unlisten) => {
+ try {
+ void Promise.resolve(unlisten()).catch(() => console.warn("[ws] native lifecycle cleanup failed"))
+ } catch {
+ console.warn("[ws] native lifecycle cleanup failed")
+ }
+ }
+ const dispose = () => {
+ disposed = true
+ active = false
+ pending = null
+ for (const unlisten of unlisteners.splice(0)) release(unlisten)
+ }
+ const deliver = (name: keyof typeof handlers) => {
+ if (disposed) return
+ if (!active) { pending = name; return }
+ try { handlers[name]() } catch {
+ console.warn("[ws] native lifecycle callback failed", { event: name })
+ }
+ }
+ const fail = (name: keyof typeof handlers) => {
+ if (disposed) return
+ dispose()
+ console.warn("[ws] native lifecycle listener unavailable", { event: name })
+ }
+ for (const name of ["resumed", "suspended"] as const) {
+ if (disposed) break
+ try {
+ void current.listen(`tauri://${name}`, () => deliver(name)).then((unlisten) => {
+ if (disposed) release(unlisten)
+ else {
+ unlisteners.push(unlisten)
+ if (unlisteners.length === 2) {
+ active = true
+ const latest = pending
+ pending = null
+ if (latest) deliver(latest)
+ }
+ }
+ }, () => fail(name))
+ } catch {
+ fail(name)
+ }
+ }
+ return dispose
+}
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index a3176cd2d..d882a911f 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -286,6 +286,7 @@ function resetMockState() {
mockNavigator.onLine = true
mockDocument.reset()
mockWindow.reset()
+ Reflect.deleteProperty(mockWindow, "__TAURI__")
}
describe("useUserWs", () => {
@@ -1556,6 +1557,7 @@ describe("useUserWs", () => {
const [{ nonce }] = connectionPings(first)
await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS)
+ await vi.advanceTimersByTimeAsync(1_000)
await flushPromises()
expect(first.closed).toBe(true)
expect(onReconnect).not.toHaveBeenCalled()
@@ -1569,7 +1571,7 @@ describe("useUserWs", () => {
expect(onReconnect).toHaveBeenCalledOnce()
expect(onReconnect).toHaveBeenCalledWith({
- reconnectDurationMs: 1_000 + mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS,
+ reconnectDurationMs: 2_000 + mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS,
})
})
@@ -1695,6 +1697,37 @@ describe("useUserWs", () => {
expect(MockWebSocket.instances).toHaveLength(2)
})
+ it("defers heartbeat startup when the authentication callback hides the page and restores it after foreground validation", async () => {
+ setupTokenFetch()
+ const interval = vi.spyOn(globalThis, "setInterval")
+ try {
+ await mountHook(vi.fn(), {
+ requestDaemonStatusOnAuth: false,
+ onAuthenticated: () => {
+ mockDocument.visibilityState = "hidden"
+ mockDocument.dispatch("visibilitychange")
+ },
+ })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ interval.mockClear()
+ ws.simulateMessage({ type: "auth.ok" })
+ expect(interval.mock.calls.filter(([, delay]) => delay === 25_000 || delay === 5_000)).toHaveLength(0)
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(ws.sent).not.toContain("ping")
+ expect(ws.closed).toBe(false)
+ mockDocument.visibilityState = "visible"
+ mockDocument.dispatch("visibilitychange")
+ const [{ nonce }] = connectionPings(ws)
+ ws.simulateMessage({ type: "connection.pong", nonce })
+ await vi.advanceTimersByTimeAsync(25_000)
+ expect(ws.sent.filter(frame => frame === "ping")).toHaveLength(1)
+ expect(MockWebSocket.instances).toEqual([ws])
+ } finally {
+ interval.mockRestore()
+ }
+ })
+
it("parks an authenticated hidden socket without heartbeat or reconnect work", async () => {
setupTokenFetch()
const onConnectionStateChange = vi.fn()
@@ -1958,6 +1991,7 @@ describe("useUserWs", () => {
expect(connectionPings(first)).toEqual([{ type: "connection.ping", nonce }])
await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS)
+ await vi.advanceTimersByTimeAsync(1_000)
await flushPromises()
expect(first.closed).toBe(true)
@@ -2174,7 +2208,7 @@ describe("useUserWs", () => {
dispatchWindowFocus()
mockDocument.dispatch("resume")
dispatchPageShow(true)
- expect(onForeground).toHaveBeenCalledTimes(3)
+ expect(onForeground).toHaveBeenCalledOnce()
expect(connectionPings(ws)).toHaveLength(1)
const [{ nonce }] = connectionPings(ws)
@@ -2321,6 +2355,7 @@ describe("useUserWs", () => {
ws.simulateMessage({ type: "auth.ok" })
dispatchHiddenToVisible()
+ await vi.advanceTimersByTimeAsync(1_000)
await flushPromises()
expect(onDisconnect).toHaveBeenCalledOnce()
@@ -2355,6 +2390,7 @@ describe("useUserWs", () => {
expect(first.closed).toBe(false)
await vi.advanceTimersByTimeAsync(1)
+ await vi.advanceTimersByTimeAsync(1_000)
mockWindow.dispatch("pageshow")
await flushPromises()
@@ -2466,6 +2502,7 @@ describe("useUserWs", () => {
const [{ nonce }] = connectionPings(ws)
await vi.advanceTimersByTimeAsync(mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS)
+ await vi.advanceTimersByTimeAsync(1_000)
await flushPromises()
expect(ws.closed).toBe(true)
expect(MockWebSocket.instances).toHaveLength(2)
@@ -3001,4 +3038,135 @@ describe("useUserWs", () => {
ws.simulateMessage(generic)
expect(onMessage).toHaveBeenCalledWith(generic, undefined, 1)
})
+ it.each(["token", "authentication", "heartbeat"] as const)("keeps one retry deadline when a timed-out %s attempt later fails", async (kind) => {
+ const random = vi.spyOn(Math, "random").mockReturnValue(0.75)
+ try {
+ const tokenResponse = deferred<never>()
+ if (kind === "token") mockFetch.mockReturnValueOnce(tokenResponse.promise)
+ else setupTokenFetch()
+ const mod = await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })
+ const old = MockWebSocket.instances[0]
+ if (old) {
+ old.close = vi.fn(() => { old.readyState = MockWebSocket.CLOSING })
+ old.simulateOpen()
+ if (kind === "heartbeat") old.simulateMessage({ type: "auth.ok" })
+ }
+ const count = MockWebSocket.instances.length
+ await vi.advanceTimersByTimeAsync(kind === "heartbeat" ? 35_000 : mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS)
+ expect(mockTrackCommunityWsRetryScheduled).toHaveBeenCalledExactlyOnceWith({ attempt: 1, delayMs: 750, windowMs: 1000 })
+ if (kind === "token") tokenResponse.reject(new Error("late transport failure"))
+ else {
+ old!.simulateClose()
+ old!.simulateError()
+ old!.simulateMessage({ type: "auth.ok" })
+ }
+ await flushPromises()
+ expect(mockTrackCommunityWsRetryScheduled).toHaveBeenCalledOnce()
+ setupTokenFetch()
+ await vi.advanceTimersByTimeAsync(749)
+ expect(MockWebSocket.instances).toHaveLength(count)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(MockWebSocket.instances).toHaveLength(count + 1)
+ expect(mockTrackCommunityWsRetryScheduled).toHaveBeenCalledOnce()
+ } finally {
+ random.mockRestore()
+ }
+ })
+
+ it.each(["authentication", "heartbeat"] as const)("retires %s timeout without waiting for close and ignores every stale callback", async (kind) => {
+ setupTokenFetch()
+ const onDisconnect = vi.fn(), onReconnect = vi.fn(), onMessage = vi.fn(), onConnectionStateChange = vi.fn()
+ const mod = await mountHook(onMessage, { onDisconnect, onReconnect, onConnectionStateChange, requestDaemonStatusOnAuth: false })
+ const old = MockWebSocket.instances[0]!
+ old.close = vi.fn(() => { old.readyState = MockWebSocket.CLOSING })
+ old.simulateOpen()
+ if (kind === "heartbeat") old.simulateMessage({ type: "auth.ok" })
+ const deadline = kind === "authentication" ? mod.WS_CONNECTION_VALIDATION_TIMEOUT_MS : 35_000
+ await vi.advanceTimersByTimeAsync(deadline - 1)
+ expect(old.close).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1)
+ expect(old.close).toHaveBeenCalledOnce()
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("reconnecting")
+ expect(onDisconnect).toHaveBeenCalledTimes(kind === "heartbeat" ? 1 : 0)
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(MockWebSocket.instances).toHaveLength(2)
+ const replacement = MockWebSocket.instances[1]!
+ replacement.simulateOpen()
+ replacement.simulateMessage({ type: "auth.ok" })
+ old.simulateOpen()
+ old.simulateMessage({ type: "auth.ok" })
+ old.simulateMessage({ type: "task.updated" })
+ old.simulateClose()
+ old.simulateError()
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(onMessage).not.toHaveBeenCalled()
+ expect(MockWebSocket.instances).toHaveLength(2)
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("authenticated")
+ expect(onDisconnect).toHaveBeenCalledTimes(kind === "heartbeat" ? 1 : 0)
+ expect(onReconnect).toHaveBeenCalledTimes(kind === "heartbeat" ? 1 : 0)
+ })
+
+ it("parks on native suspend even with visible DOM and retains an early native resume until visible", async () => {
+ const listeners = new Map<string, () => void>()
+ const unlisten = vi.fn()
+ Object.assign(mockWindow, { __TAURI__: { window: { getCurrentWindow: () => ({
+ listen: async (event: string, handler: () => void) => { listeners.set(event, handler); return unlisten },
+ }) } } })
+ setupTokenFetch()
+ const onForeground = vi.fn(), onConnectionStateChange = vi.fn()
+ await mountHook(vi.fn(), { onForeground, onConnectionStateChange, requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ const sent = ws.sent.length
+ listeners.get("tauri://suspended")!()
+ dispatchWindowFocus()
+ await vi.advanceTimersByTimeAsync(40_000)
+ expect(ws.sent).toHaveLength(sent)
+ expect(ws.closed).toBe(false)
+ expect(onConnectionStateChange).toHaveBeenLastCalledWith("suspended")
+ mockDocument.visibilityState = "hidden"
+ listeners.get("tauri://resumed")!()
+ expect(onForeground).not.toHaveBeenCalled()
+ mockDocument.visibilityState = "visible"
+ mockDocument.dispatch("visibilitychange")
+ listeners.get("tauri://resumed")!()
+ mockDocument.dispatch("resume")
+ dispatchPageShow(true)
+ expect(onForeground).toHaveBeenCalledOnce()
+ expect(connectionPings(ws)).toHaveLength(1)
+ expect(MockWebSocket.instances).toHaveLength(1)
+ for (const effect of effectMemo.values()) effect.cleanup?.()
+ expect(unlisten).toHaveBeenCalledTimes(2)
+ listeners.get("tauri://resumed")!()
+ expect(onForeground).toHaveBeenCalledOnce()
+ })
+
+ it("keeps DOM recovery available when native resumed registration fails after suspended registered", async () => {
+ const callbacks = new Map<string, () => void>()
+ const resumed = deferred<() => void>()
+ const unlisten = vi.fn()
+ Object.assign(mockWindow, { __TAURI__: { window: { getCurrentWindow: () => ({
+ listen: (event: string, callback: () => void) => {
+ callbacks.set(event, callback)
+ return event === "tauri://resumed" ? resumed.promise : Promise.resolve(unlisten)
+ },
+ }) } } })
+ setupTokenFetch()
+ const onForeground = vi.fn(), onConnectionStateChange = vi.fn()
+ await mountHook(vi.fn(), { onForeground, onConnectionStateChange, requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]!
+ ws.simulateOpen()
+ ws.simulateMessage({ type: "auth.ok" })
+ callbacks.get("tauri://suspended")!()
+ resumed.reject(new Error("permission denied"))
+ await flushPromises()
+ dispatchHiddenToVisible()
+ callbacks.get("tauri://suspended")!()
+ expect(onForeground).toHaveBeenCalledOnce()
+ expect(connectionPings(ws)).toHaveLength(1)
+ expect(unlisten).toHaveBeenCalledOnce()
+ expect(MockWebSocket.instances).toEqual([ws])
+ })
+
})
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index ecf00f56e..c9ba084d7 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -34,6 +34,7 @@ import {
import { isLocalServiceEnvironment, WS_DO_PORT_DEFAULT } from "@/lib/utils"
import { websocketUrl } from "@/lib/websocket-url"
import { authClient } from "@/lib/auth-client"
+import { listenNativeWindowLifecycle } from "@/lib/native-window-lifecycle"
const useLocalServices = isLocalServiceEnvironment()
const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000
@@ -243,6 +244,8 @@ export function useUserWs(
const connectionValidationRef = useRef<PendingConnectionValidation | null>(null)
const connectionValidationNeededRef = useRef(isPageHidden())
const frozenRef = useRef(false)
+ const nativeSuspendedRef = useRef(false)
+ const isBackground = useCallback(() => isPageHidden() || nativeSuspendedRef.current, [])
const suspendedAtRef = useRef<number | null>(null)
const sentinelIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null)
const lastSentinelTickAtRef = useRef(0)
@@ -393,48 +396,23 @@ export function useUserWs(
if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }
}, [])
- const startHeartbeat = useCallback((ws: WebSocket, generation: number) => {
- stopHeartbeat()
- if (
- isPageHidden()
- || isOffline()
- || frozenRef.current
- || !ownsAuthenticatedConnection(ws, generation)
- ) return
- lastMessageAtRef.current = Date.now()
- pingIntervalRef.current = setInterval(() => {
- if (
- !isOffline()
- && !isPageHidden()
- && !frozenRef.current
- && ownsAuthenticatedConnection(ws, generation)
- ) ws.send("ping")
- }, 25_000)
- livenessIntervalRef.current = setInterval(() => {
- if (
- !isOffline()
- && ownsAuthenticatedConnection(ws, generation)
- && Date.now() - lastMessageAtRef.current > 30_000
- ) closeSocket(ws, "heartbeat-timeout")
- }, 5_000)
- }, [closeSocket, isOffline, ownsAuthenticatedConnection, stopHeartbeat])
-
const retireSocket = useCallback((
reportDisconnect: boolean,
initiator: CommunityWsCloseInitiator,
validationResult: CommunityWsLifecycleStageResult = "aborted",
) => {
const ws = wsRef.current
+ const disconnected = reportDisconnect && authenticatedGenerationRef.current !== null
wsRef.current = null
clearConnectionValidation(validationResult)
- if (reportDisconnect && authenticatedGenerationRef.current !== null) {
+ if (disconnected) {
authenticatedGenerationRef.current = null
disconnectedAtRef.current ??= Date.now()
- runLifecycleCallback("disconnect", onDisconnectRef.current)
}
stopHeartbeat()
if (connectTimeoutRef.current !== null) { clearTimeout(connectTimeoutRef.current); connectTimeoutRef.current = null }
if (ws) { finishPageOperation(observedSockets.current.get(ws)?.operation, "cancelled"); closeSocket(ws, initiator) }
+ if (disconnected) runLifecycleCallback("disconnect", onDisconnectRef.current)
}, [clearConnectionValidation, closeSocket, stopHeartbeat])
const stopCredentialRetry = useCallback(() => {
@@ -448,6 +426,70 @@ export function useUserWs(
})
}, [retireSocket, viewerUserId])
+ const scheduleReconnect = useCallback((generation: number) => {
+ if (generation !== connectionGenerationRef.current) return
+ if (credentialRetryRef.current.stopped || !isCurrentWsAccount(viewerUserId)) return
+ if (isBackground() || isOffline() || frozenRef.current) return
+ const windowMs = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)
+ const delayMs = Math.floor(Math.random() * windowMs)
+ const attempt = reconnectAttemptRef.current + 1
+ reconnectAttemptRef.current = attempt
+ reconnectDelay.current = Math.min(windowMs * 2, WS_RECONNECT_MAX)
+ emitTelemetry("ws.reconnect", { phase: "transport", attempt, duration_ms: delayMs, outcome: "observed" })
+ trackCommunityWsRetryScheduled({ attempt, delayMs, windowMs })
+ reconnectTimerRef.current = setTimeout(() => {
+ reconnectTimerRef.current = null
+ if (
+ generation !== connectionGenerationRef.current
+ || isBackground()
+ || isOffline()
+ || frozenRef.current
+ ) return
+ void connectRef.current?.()
+ }, delayMs)
+ }, [isBackground, isOffline, viewerUserId])
+
+ const recoverTimedOutConnection = useCallback((
+ ws: WebSocket,
+ generation: number,
+ initiator: CommunityWsCloseInitiator,
+ result: CommunityWsLifecycleStageResult = "timeout",
+ ) => {
+ if (!ownsConnection(ws, generation)) return
+ retireSocket(true, initiator, result)
+ if (generation !== connectionGenerationRef.current || !isCurrentWsAccount(viewerUserId)) return
+ publishConnectionPhase(isBackground() || frozenRef.current ? "suspended" : "reconnecting")
+ scheduleReconnect(generation)
+ }, [isBackground, ownsConnection, publishConnectionPhase, retireSocket, scheduleReconnect, viewerUserId])
+
+ const startHeartbeat = useCallback((ws: WebSocket, generation: number) => {
+ stopHeartbeat()
+ if (
+ isBackground()
+ || isOffline()
+ || frozenRef.current
+ || !ownsAuthenticatedConnection(ws, generation)
+ ) return
+ lastMessageAtRef.current = Date.now()
+ pingIntervalRef.current = setInterval(() => {
+ if (
+ !isOffline()
+ && !isBackground()
+ && !frozenRef.current
+ && ownsAuthenticatedConnection(ws, generation)
+ ) ws.send("ping")
+ }, 25_000)
+ livenessIntervalRef.current = setInterval(() => {
+ if (
+ !isOffline()
+ && !isBackground()
+ && !frozenRef.current
+ && ownsAuthenticatedConnection(ws, generation)
+ && Date.now() - lastMessageAtRef.current > 30_000
+ ) recoverTimedOutConnection(ws, generation, "heartbeat-timeout")
+ }, 5_000)
+ }, [isBackground, isOffline, ownsAuthenticatedConnection, recoverTimedOutConnection, stopHeartbeat])
+
const failConnectionValidation = useCallback((
ws: WebSocket,
generation: number,
@@ -464,19 +506,13 @@ export function useUserWs(
|| generation !== connectionGenerationRef.current
) return
const initiator = result === "timeout" ? "validation-timeout" : "validation-failure"
- clearConnectionValidation(result)
- retireSocket(true, initiator, result)
- if (generation !== connectionGenerationRef.current) return
- const parked = isPageHidden() || frozenRef.current
- publishConnectionPhase(parked ? "suspended" : "reconnecting")
- if (generation !== connectionGenerationRef.current) return
- if (!parked && !isOffline()) void connectRef.current?.()
- }, [clearConnectionValidation, isOffline, publishConnectionPhase, retireSocket])
+ recoverTimedOutConnection(ws, generation, initiator, result)
+ }, [recoverTimedOutConnection])
const validateCurrentConnection = useCallback((ws: WebSocket, generation: number) => {
if (
isOffline()
- || isPageHidden()
+ || isBackground()
|| frozenRef.current
|| !ownsAuthenticatedConnection(ws, generation)
) return
@@ -508,43 +544,17 @@ export function useUserWs(
}, [
clearConnectionValidation,
failConnectionValidation,
+ isBackground,
isOffline,
ownsAuthenticatedConnection,
stopHeartbeat,
])
- const scheduleReconnect = useCallback((generation: number) => {
- if (generation !== connectionGenerationRef.current) return
- if (credentialRetryRef.current.stopped || !isCurrentWsAccount(viewerUserId)) return
- if (isPageHidden() || isOffline() || frozenRef.current) return
- if (reconnectTimerRef.current !== null) {
- clearTimeout(reconnectTimerRef.current)
- reconnectTimerRef.current = null
- }
- const windowMs = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)
- const delayMs = Math.floor(Math.random() * windowMs)
- const attempt = reconnectAttemptRef.current + 1
- reconnectAttemptRef.current = attempt
- reconnectDelay.current = Math.min(windowMs * 2, WS_RECONNECT_MAX)
- emitTelemetry("ws.reconnect", { phase: "transport", attempt, duration_ms: delayMs, outcome: "observed" })
- trackCommunityWsRetryScheduled({ attempt, delayMs, windowMs })
- reconnectTimerRef.current = setTimeout(() => {
- reconnectTimerRef.current = null
- if (
- generation !== connectionGenerationRef.current
- || isPageHidden()
- || isOffline()
- || frozenRef.current
- ) return
- void connectRef.current?.()
- }, delayMs)
- }, [isOffline, viewerUserId])
-
const connect = useCallback(async () => {
if (credentialRetryRef.current.stopped || !isCurrentWsAccount(viewerUserId)) return
- if (isPageHidden() || isOffline() || frozenRef.current) {
+ if (isBackground() || isOffline() || frozenRef.current) {
publishConnectionPhase(
- isPageHidden() || frozenRef.current ? "suspended" : "reconnecting",
+ isBackground() || frozenRef.current ? "suspended" : "reconnecting",
)
return
}
@@ -554,7 +564,7 @@ export function useUserWs(
if (
pendingTokenRef.current
|| previousGeneration !== connectionGenerationRef.current
- || isPageHidden()
+ || isBackground()
|| isOffline()
|| frozenRef.current
|| !isCurrentWsAccount(viewerUserId)
@@ -733,7 +743,7 @@ export function useUserWs(
reportAuthStage("timeout")
reportAuthFailure("timeout")
}
- closeSocket(ws, "connect-timeout")
+ recoverTimedOutConnection(ws, generation, "connect-timeout")
}, WS_CONNECTION_VALIDATION_TIMEOUT_MS)
ws.onopen = () => {
@@ -949,10 +959,10 @@ export function useUserWs(
else stopCredentialRetry()
}
publishConnectionPhase(
- isPageHidden() || frozenRef.current ? "suspended" : "reconnecting",
+ isBackground() || frozenRef.current ? "suspended" : "reconnecting",
)
if (generation !== connectionGenerationRef.current) return
- if (failedValidation && !isPageHidden() && !isOffline() && !frozenRef.current) {
+ if (failedValidation && !isBackground() && !isOffline() && !frozenRef.current) {
void connectRef.current?.()
} else {
scheduleReconnect(generation)
@@ -961,6 +971,7 @@ export function useUserWs(
}, [
clearConnectionValidation,
closeSocket,
+ isBackground,
isOffline,
ownsAuthenticatedConnection,
ownsConnection,
@@ -968,6 +979,7 @@ export function useUserWs(
reportSocketClose,
reportTokenAttempt,
retireSocket,
+ recoverTimedOutConnection,
scheduleReconnect,
startHeartbeat,
stopCredentialRetry,
@@ -1028,11 +1040,12 @@ export function useUserWs(
connectionGenerationRef.current += 1
retireSocket(true, "offline")
}
- const parked = retainAuthenticatedSocket || isPageHidden() || frozenRef.current
+ const parked = retainAuthenticatedSocket || isBackground() || frozenRef.current
publishConnectionPhase(parked ? "suspended" : "reconnecting")
}, [
abortPendingToken,
clearConnectionValidation,
+ isBackground,
ownsAuthenticatedConnection,
publishConnectionPhase,
retireSocket,
@@ -1045,7 +1058,7 @@ export function useUserWs(
readyState: CommunityWsSocketReadyState,
now: number,
) => {
- if (isPageHidden() || isOffline() || frozenRef.current) return
+ if (isBackground() || isOffline() || frozenRef.current) return
trackCommunityWsLifecycleRecovery({
trigger,
strategy,
@@ -1053,7 +1066,7 @@ export function useUserWs(
suspensionDuration: suspensionDurationBucket(suspendedAtRef.current, now),
})
suspendedAtRef.current = null
- }, [isOffline])
+ }, [isBackground, isOffline])
const requestForegroundRecovery = useCallback((
trigger: CommunityWsLifecycleRecoveryTrigger,
@@ -1068,7 +1081,7 @@ export function useUserWs(
}
return
}
- if (isPageHidden()) {
+ if (isBackground()) {
suspendConnection(false)
return
}
@@ -1077,8 +1090,9 @@ export function useUserWs(
const recoveryNeeded = forceValidation || connectionValidationNeededRef.current
if (!recoveryNeeded) return
+ if (connectionValidationRef.current) return
if (trigger !== "focus" || connectionValidationNeededRef.current) runLifecycleCallback("foreground", onForegroundRef.current)
- if (isOffline() || isPageHidden()) return
+ if (isOffline() || isBackground()) return
if (pendingTokenRef.current) return
const ws = wsRef.current
@@ -1092,7 +1106,6 @@ export function useUserWs(
&& Date.now() - connectStartedAtRef.current <= WS_CONNECTION_VALIDATION_TIMEOUT_MS
if (authenticated && ws?.readyState === WebSocket.OPEN) {
connectionValidationNeededRef.current = false
- if (connectionValidationRef.current?.ws === ws) return
trackLifecycleRecovery(trigger, "validate", socketReadyState(ws), Date.now())
validateCurrentConnection(ws, generation)
return
@@ -1110,6 +1123,7 @@ export function useUserWs(
trackLifecycleRecovery(trigger, "replace", readyState, Date.now())
void connectRef.current?.()
}, [
+ isBackground,
isOffline,
ownsAuthenticatedConnection,
publishConnectionPhase,
@@ -1155,11 +1169,11 @@ export function useUserWs(
useEffect(() => {
const mountedAt = Date.now()
- if (isPageHidden() || isOffline()) suspendedAtRef.current = mountedAt
+ if (isBackground() || isOffline()) suspendedAtRef.current = mountedAt
lastSentinelTickAtRef.current = mountedAt
void connect()
const onVisibilityChange = () => {
- if (isPageHidden()) {
+ if (isBackground()) {
suspendConnection(false)
return
}
@@ -1185,6 +1199,16 @@ export function useUserWs(
requestForegroundRecovery("online", true)
}
const onOffline = () => suspendForOffline()
+ const unlistenNative = listenNativeWindowLifecycle({
+ suspended: () => {
+ nativeSuspendedRef.current = true
+ suspendConnection(false)
+ },
+ resumed: () => {
+ nativeSuspendedRef.current = false
+ requestForegroundRecovery("resume", true)
+ },
+ })
if (typeof document !== "undefined") {
document.addEventListener("visibilitychange", onVisibilityChange)
document.addEventListener("freeze", onFreeze)
@@ -1201,13 +1225,15 @@ export function useUserWs(
const elapsedMs = Math.max(0, now - lastSentinelTickAtRef.current)
lastSentinelTickAtRef.current = now
if (
- isPageHidden()
+ isBackground()
|| isOffline()
|| elapsedMs < WS_FOREGROUND_SUSPENSION_GAP_MS
) return
requestForegroundRecovery("sentinel", true)
}, WS_FOREGROUND_SENTINEL_INTERVAL_MS)
return () => {
+ unlistenNative()
+ nativeSuspendedRef.current = false
if (typeof document !== "undefined") {
document.removeEventListener("visibilitychange", onVisibilityChange)
document.removeEventListener("freeze", onFreeze)
@@ -1238,6 +1264,7 @@ export function useUserWs(
abortPendingToken,
clearConnectionValidation,
connect,
+ isBackground,
isOffline,
requestForegroundRecovery,
retireSocket,
@@ -1275,7 +1302,7 @@ export function useUserWs(
return
}
retireSocket(true, "manual-retry")
- if (isPageHidden() || frozenRef.current) {
+ if (isBackground() || frozenRef.current) {
connectionGenerationRef.current += 1
publishConnectionPhase("suspended")
return
@@ -1284,6 +1311,7 @@ export function useUserWs(
}, [
abortPendingToken,
clearConnectionValidation,
+ isBackground,
isOffline,
ownsAuthenticatedConnection,
publishConnectionPhase,