Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(web): show and clear all local query cache (#834)
Gener1f7996ac9753
diff --git a/src/web/src/components/community/settings/advanced-settings.dom.test.tsx b/src/web/src/components/community/settings/advanced-settings.dom.test.tsxnew file mode 100644index 000000000..14812bc16--- /dev/null+++ b/src/web/src/components/community/settings/advanced-settings.dom.test.tsx@@ -0,0 +1,84 @@+import { render, screen, setupUser, waitFor } from "@/test/react-dom-harness"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { tid } from "@/lib/community/testids"+import { AdvancedSettings } from "./user-settings"++const cache = vi.hoisted(() => ({+ clearAll: vi.fn(),+ size: vi.fn(),+}))++vi.mock("@/lib/query-persister", () => ({+ clearAllPersistedCaches: cache.clearAll,+ getPersistedCacheSizeBytes: cache.size,+ formatBytes: (bytes: number) => bytes === 1536 ? "1.5 KB" : `${bytes} B`,+}))++vi.mock("@/components/ui/confirm-dialog", () => ({+ ConfirmDialog: ({ open, onConfirm }: { open: boolean; onConfirm: () => Promise<void> }) => (+ open ? <button onClick={() => { void onConfirm() }}>Confirm clear cache</button> : null+ ),+}))++describe("AdvancedSettings cache size", () => {+ beforeEach(() => {+ cache.clearAll.mockReset()+ cache.size.mockReset()+ })++ afterEach(() => {+ vi.unstubAllGlobals()+ })++ it("shows loading before the all-account cache total resolves", async () => {+ let resolveSize!: (bytes: number) => void+ cache.size.mockReturnValue(new Promise<number>((resolve) => { resolveSize = resolve }))++ render(<AdvancedSettings />)++ expect(screen.getByTestId(tid.settingsCacheSize)).toHaveTextContent("Calculating…")+ resolveSize(1536)+ await waitFor(() => {+ expect(screen.getByTestId(tid.settingsCacheSize)).toHaveTextContent("1.5 KB")+ })+ })++ it("shows an empty cache as 0 B", async () => {+ cache.size.mockResolvedValue(0)++ render(<AdvancedSettings />)++ await waitFor(() => {+ expect(screen.getByTestId(tid.settingsCacheSize)).toHaveTextContent("0 B")+ })+ })++ it("shows unavailable when IndexedDB cannot be read", async () => {+ cache.size.mockRejectedValue(new Error("IndexedDB unavailable"))++ render(<AdvancedSettings />)++ await waitFor(() => {+ expect(screen.getByTestId(tid.settingsCacheSize)).toHaveTextContent("Unavailable")+ })+ })++ it("shows 0 B after clearing and before the reload frame", async () => {+ const user = setupUser()+ cache.size.mockResolvedValue(2048)+ cache.clearAll.mockResolvedValue(undefined)+ vi.stubGlobal("requestAnimationFrame", vi.fn(() => 1))+ render(<AdvancedSettings />)+ await waitFor(() => {+ expect(screen.getByTestId(tid.settingsCacheSize)).toHaveTextContent("2048 B")+ })++ await user.click(screen.getByRole("button", { name: "Clear local cache" }))+ await user.click(screen.getByRole("button", { name: "Confirm clear cache" }))++ await waitFor(() => {+ expect(cache.clearAll).toHaveBeenCalledOnce()+ expect(screen.getByTestId(tid.settingsCacheSize)).toHaveTextContent("0 B")+ })+ })+})diff --git a/src/web/src/components/community/settings/user-settings.tsx b/src/web/src/components/community/settings/user-settings.tsxindex 9a57525b7..073adf889 100644--- a/src/web/src/components/community/settings/user-settings.tsx+++ b/src/web/src/components/community/settings/user-settings.tsx@@ -9,7 +9,11 @@ import { Button } from "@/components/ui/button"import { AutoResizeTextarea } from "@/components/ui/auto-resize-textarea"import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { PrivacyPolicyContent } from "@/components/privacy/privacy-policy-content"-import { clearPersistedCache } from "@/lib/query-persister"+import {+ clearAllPersistedCaches,+ formatBytes,+ getPersistedCacheSizeBytes,+} from "@/lib/query-persister"import { tid } from "@/lib/community/testids"import { Avatar } from "../avatar"import { Field } from "./field"@@ -73,31 +77,46 @@ function AppearanceSettings() {)}-// Advanced settings — currently just a "Clear local cache" affordance. Local-// cache = the IndexedDB-persisted TanStack Query blob (message pages +-// read-state snapshots). Rare to need in normal use; useful when a bad build-// leaves the persisted state inconsistent (see 2026-07-09 fetchOlder pollution).-function AdvancedSettings({ userId }: { userId: string | null }) {+type CacheSizeState = number | "loading" | "unavailable"++export function AdvancedSettings() {const [confirmOpen, setConfirmOpen] = useState(false)const [clearing, setClearing] = useState(false)+ const [cacheSize, setCacheSize] = useState<CacheSizeState>("loading")const webVersion = process.env.NEXT_PUBLIC_APP_VERSION++ useEffect(() => {+ let active = true+ void getPersistedCacheSizeBytes().then(+ (bytes) => { if (active) setCacheSize(bytes) },+ () => { if (active) setCacheSize("unavailable") },+ )+ return () => { active = false }+ }, [])+return (<><ConfirmDialogopen={confirmOpen}onOpenChange={(o) => { if (!o) setConfirmOpen(false) }}title="Clear local cache?"- description="This removes the locally persisted messages and read-state for your account. The next channel or DM you open will refetch from the server. Your unread state on the server is unaffected."+ description="This removes locally persisted messages for every account used on this device. The next channel or DM you open will refetch from the server. Nothing on the server is deleted."confirmLabel="Clear cache"loadingLabel="Clearing..."loading={clearing}onConfirm={async () => {setClearing(true)try {- await clearPersistedCache(userId)+ await clearAllPersistedCaches()+ setCacheSize(0)+ setClearing(false)+ setConfirmOpen(false)toast("Local cache cleared — reloading")- // Hard reload so the QueryClient starts fresh without racing an- // in-flight persister write.+ await new Promise<void>((resolve) => {+ window.requestAnimationFrame(() => {+ window.requestAnimationFrame(() => resolve())+ })+ })window.location.reload()} catch (e) {toastApiError(e, "Failed to clear cache")@@ -109,10 +128,23 @@ function AdvancedSettings({ userId }: { userId: string | null }) {<div className="mx-auto flex min-h-full w-full max-w-md flex-col"><section className="space-y-2"><h2 className="text-base font-medium tracking-tight">Clear local cache</h2>+ <p className="flex items-baseline justify-between gap-4 text-sm">+ <span className="text-muted-foreground">Cached messages</span>+ <span+ data-testid={tid.settingsCacheSize}+ className="font-mono tabular-nums text-foreground"+ >+ {cacheSize === "loading"+ ? "Calculating…"+ : cacheSize === "unavailable"+ ? "Unavailable"+ : formatBytes(cacheSize)}+ </span>+ </p><p className="max-w-[65ch] text-sm leading-6 text-muted-foreground">- Removes the locally persisted message history and read-state stored- in this browser. The next channel or DM you open will refetch from- the server. Nothing on the server is deleted.+ Removes locally persisted messages for every account used on this+ device. The next channel or DM you open will refetch from the server.+ Nothing on the server is deleted.</p><Buttonvariant="destructive"@@ -294,7 +326,7 @@ export function UserSettings({ initialTab = "profile", billingReturn = null, onC<AppearanceSettings /></SettingsShellPanel><SettingsShellPanel value="advanced" className="h-full">- <AdvancedSettings userId={userId} />+ <AdvancedSettings /></SettingsShellPanel><SettingsShellPanel value="privacy"><div className="mx-auto w-full max-w-2xl pb-8">diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex ca3706116..d0973c359 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -37,6 +37,7 @@ export const tid = {settingsClose: "community-settings-close",settingsLabel: "community-settings-label",settingsWebVersion: "community-settings-web-version",+ settingsCacheSize: "community-settings-cache-size",analyticsConsentBanner: "analytics-consent-banner",analyticsPreferenceControl: "analytics-preference-control",analyticsConsentNecessary: "analytics-consent-necessary",diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.tsindex e3b4c685c..06427cfc0 100644--- a/src/web/src/lib/query-persister.test.ts+++ b/src/web/src/lib/query-persister.test.ts@@ -1,12 +1,15 @@import "fake-indexeddb/auto"import { describe, expect, it, beforeEach } from "vitest"-import { get, set } from "idb-keyval"+import { del, get, set } from "idb-keyval"import { QueryClient } from "@tanstack/react-query"import type { PersistedClient } from "@tanstack/react-query-persist-client"import { communityKeys } from "@/lib/query-keys"import {clearPersistedCache,+ clearAllPersistedCaches,createIdbPersister,+ formatBytes,+ getPersistedCacheSizeBytes,MAX_PERSISTED_MESSAGES_PER_SCOPE,MAX_PERSISTED_MESSAGE_SCOPES,shouldPersistQuery,@@ -700,3 +703,71 @@ describe("createIdbPersister — user scoping", () => {expect(await get(`alook:qc:v2:u_alice:client`)).toBeUndefined()})})++describe("all-account persisted cache management", () => {+ beforeEach(async () => {+ await clearAllPersistedCaches()+ await del("unrelated")+ await del("alook:qc:v2:u_alice:metadata")+ await del("alook:qc:v2:extra:segment:client")+ })++ it("sums serialized UTF-8 bytes across account and cache versions", async () => {+ await set("alook:qc:v1:u_alice:client", "abc")+ await set("alook:qc:v2:u_bob:client", "你好")+ await set("alook:qc:v99:u_future:client", "!")++ expect(await getPersistedCacheSizeBytes()).toBe(10)+ })++ it("ignores unrelated shapes and non-string values", async () => {+ await set("alook:qc:v2:u_alice:client", "cache")+ await set("unrelated", "outside")+ await set("alook:qc:v2:u_alice:metadata", "outside")+ await set("alook:qc:v2:extra:segment:client", "outside")+ await set("alook:qc:v2:u_binary:client", new Uint8Array([1, 2, 3]))++ expect(await getPersistedCacheSizeBytes()).toBe(5)+ })++ it("clears every current account blob and preserves unrelated keys", async () => {+ const stale = createIdbPersister("u_alice")+ await set("alook:qc:v1:u_legacy:client", "legacy")+ await set("alook:qc:v2:u_alice:client", "alice")+ await set("alook:qc:v2:u_bob:client", "bob")+ await set("alook:qc:v99:u_future:client", "future")+ await set("unrelated", "keep")+ await set("alook:qc:v2:extra:segment:client", "keep")++ await clearAllPersistedCaches()+ await stale.persistClient({+ timestamp: 3,+ buster: "v2",+ clientState: { mutations: [], queries: [] },+ })++ expect(await get("alook:qc:v1:u_legacy:client")).toBeUndefined()+ expect(await get("alook:qc:v2:u_alice:client")).toBeUndefined()+ expect(await get("alook:qc:v2:u_bob:client")).toBeUndefined()+ expect(await get("alook:qc:v99:u_future:client")).toBeUndefined()+ expect(await get("unrelated")).toBe("keep")+ expect(await get("alook:qc:v2:extra:segment:client")).toBe("keep")+ })++ it("reports an empty cache as zero bytes", async () => {+ expect(await getPersistedCacheSizeBytes()).toBe(0)+ })+})++describe("formatBytes", () => {+ it.each([+ [0, "0 B"],+ [1023, "1023 B"],+ [1024, "1 KB"],+ [1536, "1.5 KB"],+ [1024 * 1024, "1 MB"],+ [Math.round(12.4 * 1024 * 1024), "12.4 MB"],+ ])("formats %i bytes as %s", (bytes, expected) => {+ expect(formatBytes(bytes)).toBe(expected)+ })+})diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.tsindex 6a2f6d4c2..d3be66ea7 100644--- a/src/web/src/lib/query-persister.ts+++ b/src/web/src/lib/query-persister.ts@@ -3,7 +3,7 @@ import type {PersistedClient,Persister,} from "@tanstack/react-query-persist-client"-import { del, get, set } from "idb-keyval"+import { del, get, keys, set } from "idb-keyval"import {communityCollectionSchemas,type CommunityCollectionName,@@ -244,6 +244,22 @@ function blobKeyFor(userId: string | null): string {return `${namespaceFor(userId)}:client`}+function isPersistedCacheBlobKey(key: IDBValidKey): key is string {+ return typeof key === "string" && /^alook:qc:[^:]+:[^:]+:client$/.test(key)+}++export function formatBytes(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`+ const units = ["KB", "MB", "GB"] as const+ let value = bytes / 1024+ let unitIndex = 0+ while (value >= 1024 && unitIndex < units.length - 1) {+ value /= 1024+ unitIndex += 1+ }+ return `${Number(value.toFixed(1))} ${units[unitIndex]}`+}+type PersistCoordination = {generations: Map<string, number>operations: Map<string, Promise<void>>@@ -336,3 +352,27 @@ export async function clearPersistedCache(userId: string | null): Promise<void>persistGenerations.set(key, (persistGenerations.get(key) ?? 0) + 1)await runPersistOperation(key, async () => del(key))}++export async function getPersistedCacheSizeBytes(): Promise<number> {+ const cacheKeys = (await keys()).filter(isPersistedCacheBlobKey)+ const values = await Promise.all(cacheKeys.map((key) => (+ runPersistOperation(key, () => get<unknown>(key))+ )))+ const encoder = new TextEncoder()+ return values.reduce<number>((total, value) => (+ typeof value === "string" ? total + encoder.encode(value).byteLength : total+ ), 0)+}++export async function clearAllPersistedCaches(): Promise<void> {+ const storedKeys = (await keys()).filter(isPersistedCacheBlobKey)+ const coordinatedKeys = [...persistGenerations.keys()].filter(isPersistedCacheBlobKey)+ const cacheKeys = [...new Set([...storedKeys, ...coordinatedKeys])]++ for (const key of cacheKeys) {+ persistGenerations.set(key, (persistGenerations.get(key) ?? 0) + 1)+ }+ await Promise.all(cacheKeys.map((key) => (+ runPersistOperation(key, async () => del(key))+ )))+}