World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Returning to a page does not refetch what the stream keeps fresh (#533)
WaylandYangacc4afd8e431
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 12d3cc2c..9b5f4dce 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -109,5 +109,7 @@ jobs:cache-dependency-path: web/pnpm-lock.yaml- name: Installrun: pnpm install --frozen-lockfile+ - name: Test+ run: pnpm test- name: Build (含类型检查)run: pnpm builddiff --git a/web/package.json b/web/package.jsonindex 89fa8bed..feb9020e 100644--- a/web/package.json+++ b/web/package.json@@ -8,6 +8,7 @@"dev": "vite","build": "node scripts/style-guard.mjs && tsc --noEmit && vite build","typecheck": "tsc --noEmit",+ "test": "vitest run","preview": "vite preview","guard": "node scripts/style-guard.mjs"},@@ -40,6 +41,7 @@"@vitejs/plugin-react": "^4.3.4","tailwindcss": "^4.0.0","typescript": "^5.7.2",- "vite": "^6.0.0"+ "vite": "^6.0.0",+ "vitest": "5.0.0"}}diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yamlindex 935940b3..48061e3f 100644--- a/web/pnpm-lock.yaml+++ b/web/pnpm-lock.yaml@@ -90,6 +90,9 @@ importers:vite:specifier: ^6.0.0+ vitest:+ specifier: 5.0.0+ version: 5.0.0(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected]))packages:@@ -1341,9 +1344,15 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==}+ '@types/[email protected]':+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}+'@types/[email protected]':resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}+'@types/[email protected]':resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}@@ -1388,10 +1397,28 @@ packages:peerDependencies:vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0+ '@vitest/[email protected]':+ resolution: {integrity: sha512-66PGTMIiVJP3t4a5yxU9qPtf7MdTBs8jmToMvy+HVflB3Yy13WJZTtPePdvU+wjRV02SKK5doLbSA6o9pwOmiA==}+ peerDependencies:+ msw: ^2.4.9+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0+ peerDependenciesMeta:+ msw:+ optional: true+ vite:+ optional: true++ '@vitest/[email protected]':+ resolution: {integrity: sha512-uy+luWBAPw9XfthoHi5AkfHUnuPYEESjl0p/r+meoBnU8bxg5GDQ3Ey8MjcJ6sqahkL4PFyrvfMJJBw7LbU06g==}+resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}engines: {node: '>=10'}+ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}@@ -1411,6 +1438,10 @@ packages:resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}+ resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}@@ -1473,6 +1504,9 @@ packages:resolution: {integrity: sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==}engines: {node: '>=10.13.0'}+ resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==}+resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==}engines: {node: '>=18'}@@ -1489,10 +1523,17 @@ packages:resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==}+ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}+resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}engines: {node: '>=0.8.x'}+ resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}+ engines: {node: '>=12.0.0'}+resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}@@ -1694,6 +1735,9 @@ packages:resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}+ resolution: {integrity: sha512-Bpb0W2TbLKOZ7vJnOUnVRGq3WL2p+ISV29M6hYPL1AFCpyKZpdr5ytiXoTSSxRVhg8YW7f65+6gbG8WG6PCa/g==}+resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}@@ -1844,6 +1888,10 @@ packages:resolution: {integrity: sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw==}+ resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==}+ engines: {node: '>=12.20.0'}+resolution: {integrity: sha512-wRqjisUyiUfXowgm7MFH2rwJzKIr20rca5FsHXCMNm1W5YPP1hCtrZfgmQ62kP7OZ7Xt+cR858aB28lu5NX55g==}@@ -1970,6 +2018,9 @@ packages:resolution: {integrity: sha512-LErWMNS2RRFdu2RMA5u/PA59/IWs0XsikyEXGQ2/36iEWFrdG0ABmg17E17cikrv76891kOAMq3TkTFXpwAHXw==}engines: {node: '>=10'}+ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}+resolution: {integrity: sha512-5H0zFlx6/NTQpqBg4Rm569ZOpnBOXMaS25UQThIWMU3XyzI5AhmorK/gnl87BvJBLhQd0tW4C0LIp3enWzMoNw==}@@ -1980,6 +2031,12 @@ packages:resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==}+ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}++ resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==}+resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}@@ -2001,6 +2058,14 @@ packages:peerDependencies:react: '>=18.0.0'+ resolution: {integrity: sha512-9APumHG7r4yOk4X4WlkmE71aZcv1gvin1czO3OQ1U9iJcFA5Ja/ygyb0vPOVHTthFozUYs8CLoLUlM8grb2lTQ==}+ engines: {node: '>=20.0.0'}++ resolution: {integrity: sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}engines: {node: '>=12.0.0'}@@ -2123,6 +2188,52 @@ packages:yaml:optional: true+ resolution: {integrity: sha512-gpsMNoRhMjMktVxPtstOH4/PJuPyovVaMDr4oDilXaGH1EcqM2OE96SoHT2VIQ6fTGtTjqmHDrEu2X9RQiXf8Q==}+ engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0}+ hasBin: true+ peerDependencies:+ '@edge-runtime/vm': '*'+ '@opentelemetry/api': ^1.9.0+ '@types/node': ^22.0.0 || >=24.0.0+ '@vitest/browser-playwright': 5.0.0+ '@vitest/browser-preview': 5.0.0+ '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0+ '@vitest/coverage-istanbul': 5.0.0+ '@vitest/coverage-v8': 5.0.0+ '@vitest/ui': 5.0.0+ happy-dom: '*'+ jsdom: '*'+ vite: ^6.4.0 || ^7.0.0 || ^8.0.0+ peerDependenciesMeta:+ '@edge-runtime/vm':+ optional: true+ '@opentelemetry/api':+ optional: true+ '@types/node':+ optional: true+ '@vitest/browser-playwright':+ optional: true+ '@vitest/browser-preview':+ optional: true+ '@vitest/browser-webdriverio':+ optional: true+ '@vitest/coverage-istanbul':+ optional: true+ '@vitest/coverage-v8':+ optional: true+ '@vitest/ui':+ optional: true+ happy-dom:+ optional: true+ jsdom:+ optional: true++ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}+ engines: {node: '>=8'}+ hasBin: true+resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}@@ -3324,10 +3435,17 @@ snapshots:dependencies:'@babel/types': 7.29.8+ '@types/[email protected]':+ dependencies:+ '@types/deep-eql': 4.0.2+ assertion-error: 2.0.1+'@types/[email protected]':dependencies:'@types/ms': 2.1.0+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@types/estree': 1.0.9@@ -3377,10 +3495,23 @@ snapshots:transitivePeerDependencies:- supports-color+ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))':+ dependencies:+ '@jridgewell/trace-mapping': 0.3.31+ '@vitest/spy': 5.0.0+ estree-walker: 3.0.3+ magic-string: 1.2.3+ optionalDependencies:++ '@vitest/[email protected]': {}+dependencies:tslib: 2.8.1+ [email protected]: {}+@@ -3397,6 +3528,8 @@ snapshots:+ [email protected]: {}+@@ -3440,6 +3573,8 @@ snapshots:graceful-fs: 4.2.11tapable: 2.3.3+ [email protected]: {}+optionalDependencies:'@esbuild/aix-ppc64': 0.25.12@@ -3475,8 +3610,14 @@ snapshots:+ dependencies:+ '@types/estree': 1.0.9++ [email protected]: {}+@@ -3651,6 +3792,10 @@ snapshots:dependencies:'@jridgewell/sourcemap-codec': 1.5.5+ dependencies:+ '@jridgewell/sourcemap-codec': 1.5.5+@@ -4009,6 +4154,8 @@ snapshots:+ [email protected]: {}+dependencies:mnemonist: 0.39.8@@ -4248,6 +4395,8 @@ snapshots:+ [email protected]: {}+dependencies:events: 3.3.0@@ -4259,6 +4408,10 @@ snapshots:+ [email protected]: {}++ [email protected]: {}+dependencies:character-entities-html4: 2.1.0@@ -4280,6 +4433,10 @@ snapshots:dependencies:react: 18.3.1+ [email protected]: {}++ [email protected]: {}+dependencies:fdir: 6.5.0([email protected])@@ -4384,6 +4541,32 @@ snapshots:jiti: 2.7.0lightningcss: 1.32.0+ [email protected](@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])):+ dependencies:+ '@types/chai': 5.2.3+ '@vitest/mocker': 5.0.0([email protected](@types/[email protected])([email protected])([email protected]))+ chai: 6.2.2+ es-module-lexer: 2.3.2+ expect-type: 1.4.0+ magic-string: 1.2.3+ obug: 2.2.1+ picomatch: 4.0.7+ std-env: 4.2.0+ tinybench: 6.1.4+ tinyexec: 1.3.0+ tinyglobby: 0.2.17+ why-is-node-running: 2.3.0+ optionalDependencies:+ '@types/node': 26.3.0+ transitivePeerDependencies:+ - msw++ dependencies:+ siginfo: 2.0.0+ stackback: 0.0.2+diff --git a/web/src/kb.tsx b/web/src/kb.tsxindex 9a858e24..fa560480 100644--- a/web/src/kb.tsx+++ b/web/src/kb.tsx@@ -2,6 +2,7 @@import { useCallback, useSyncExternalStore } from "react";import { useLocation, useNavigate, useParams } from "@tanstack/react-router";import { useQuery, useQueryClient } from "@tanstack/react-query";+import { STREAM_KEYS } from "./queryDefaults";import { api, DEFAULT_ONTOLOGY_PACKS, type Kb, type Workspace } from "./api";import { kbStore, wsStore } from "./wsStore";@@ -99,11 +100,17 @@ export function useKb(): {const setKb = useCallback((id: string) => {kbStore.set(id);+ // 事件流只订当前库,目标库在没人订的这段时间里的变化没人失效过;这些键又不再+ // 一挂载就重拉(queryDefaults.ts),所以切过去时主动失效一次。代价就是今天+ // 切库本来就有的那一轮请求+ for (const head of STREAM_KEYS) {+ queryClient.invalidateQueries({ queryKey: [head, id] });+ }if (currentKbId && currentKbId !== id) {navigate({ to: samePageInKb(pathname, currentKbId, id), replace: false });}},- [navigate, pathname, currentKbId],+ [navigate, pathname, currentKbId, queryClient],);return {diff --git a/web/src/main.tsx b/web/src/main.tsxindex 3a56b467..3986e24a 100644--- a/web/src/main.tsx+++ b/web/src/main.tsx@@ -4,13 +4,20 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { RouterProvider } from "@tanstack/react-router";import { router } from "./router";import { ToastHost } from "./toast";+import { DEFAULT_STALE_MS, applyQueryDefaults } from "./queryDefaults";import "./styles.css";+// staleTime 按键分档,表在 queryDefaults.ts;这里只给全局默认(#518)const queryClient = new QueryClient({defaultOptions: {- queries: { retry: false, refetchOnWindowFocus: false },+ queries: {+ retry: false,+ refetchOnWindowFocus: false,+ staleTime: DEFAULT_STALE_MS,+ },},});+applyQueryDefaults(queryClient);createRoot(document.getElementById("root")!).render(<StrictMode>diff --git a/web/src/pages/AccountShell.tsx b/web/src/pages/AccountShell.tsxindex 48c0b18f..e6c0f61d 100644--- a/web/src/pages/AccountShell.tsx+++ b/web/src/pages/AccountShell.tsx@@ -26,7 +26,7 @@ export function AccountShell() {const onAdmin = loc.pathname === "/admin";const adminTab = (loc.search as { tab?: string }).tab ?? "models";const me = useQuery({ queryKey: ["me"], queryFn: api.me });- const health = useQuery({ queryKey: ["health"], queryFn: api.health, staleTime: Infinity });+ const health = useQuery({ queryKey: ["health"], queryFn: api.health });// 标题:`Utopia | Persona`——账户区整体一个名字,不逐页细分usePageTitle(S.app.name, S.account.titleTag);diff --git a/web/src/pages/Docs.tsx b/web/src/pages/Docs.tsxindex 6c861541..d3a288a7 100644--- a/web/src/pages/Docs.tsx+++ b/web/src/pages/Docs.tsx@@ -118,7 +118,7 @@ export function DocsPage() {usePageTitle(S.app.name, doc.title);// 公开页也感知登录态:已登录给用户菜单,未登录给 Sign inconst me = useQuery({ queryKey: ["me"], queryFn: api.me, retry: false });- const health = useQuery({ queryKey: ["health"], queryFn: api.health, staleTime: Infinity });+ const health = useQuery({ queryKey: ["health"], queryFn: api.health });// 滚动跟随:视口上沿之上最近的标题为当前小节;// 滚到底强制激活最后一节(短末节永远越不过判定线)diff --git a/web/src/pages/Login.tsx b/web/src/pages/Login.tsxindex a6e6caf0..6ee9cc09 100644--- a/web/src/pages/Login.tsx+++ b/web/src/pages/Login.tsx@@ -1,5 +1,5 @@import { useState } from "react";-import { useMutation } from "@tanstack/react-query";+import { useMutation, useQueryClient } from "@tanstack/react-query";import { Link, useNavigate } from "@tanstack/react-router";/* lucide 已移除品牌图标,GitHub mark 内联(官方 mark 路径,fill=currentColor) */@@ -35,6 +35,7 @@ export function Login() {const [password, setPassword] = useState("");const [displayName, setDisplayName] = useState("");const [leaving, setLeaving] = useState(false);+ const queryClient = useQueryClient();const mutation = useMutation({mutationFn: async () => {@@ -42,6 +43,9 @@ export function Login() {return api.register(email, password, displayName);},onSuccess: () => {+ // 换人先清缓存:`me`、`workspaces` 这些一次会话内不过期(queryDefaults.ts),+ // 会话过期后同一标签页登另一个账号,不清就看见上一个人的名字和库+ queryClient.clear();// 谢幕:卡片上浮淡出、巨构放大穿越,再进入图谱首页setLeaving(true);window.setTimeout(() => navigate({ to: "/" }), 650);diff --git a/web/src/pages/Shell.tsx b/web/src/pages/Shell.tsxindex 5ff2d602..c8dedf6f 100644--- a/web/src/pages/Shell.tsx+++ b/web/src/pages/Shell.tsx@@ -49,7 +49,6 @@ export function Shell() {const health = useQuery({queryKey: ["health"],queryFn: api.health,- staleTime: Infinity,});const { kb, kbs, setKb } = useKb();// 标题跟随当前 tab:`Graph · Utopia`;文档查看页归入 Librarydiff --git a/web/src/queryDefaults.test.ts b/web/src/queryDefaults.test.tsnew file mode 100644index 00000000..e0d3240d--- /dev/null+++ b/web/src/queryDefaults.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";+import { QueryClient } from "@tanstack/react-query";+import {+ DEFAULT_STALE_MS,+ STREAM_STALE_MS,+ applyQueryDefaults,+ staleTimeFor,+} from "./queryDefaults";++describe("stale time by key", () => {+ it("a session key never goes stale on its own", () => {+ for (const key of [["me"], ["health"], ["deployment"]]) {+ expect(staleTimeFor(key)).toBe(Infinity);+ }+ });++ it("a key the event stream keeps fresh stays fresh for the stream window", () => {+ expect(staleTimeFor(["graph", "kb-1", "focus", 200])).toBe(STREAM_STALE_MS);+ expect(staleTimeFor(["documents", "kb-1"])).toBe(STREAM_STALE_MS);+ });++ it("a key with nothing behind it goes stale within the short default", () => {+ expect(staleTimeFor(["tokens"])).toBe(DEFAULT_STALE_MS);+ // 前缀匹配是按元素比的:reviewSummary 不是 review+ expect(staleTimeFor(["reviewSummary", "kb-1"])).toBe(DEFAULT_STALE_MS);+ expect(staleTimeFor([42])).toBe(DEFAULT_STALE_MS);+ });++ it("the table is what the client actually applies", () => {+ const client = new QueryClient({+ defaultOptions: { queries: { staleTime: DEFAULT_STALE_MS } },+ });+ applyQueryDefaults(client);+ expect(client.getQueryDefaults(["me"]).staleTime).toBe(Infinity);+ expect(client.getQueryDefaults(["review", "kb-1", "queue", 2]).staleTime).toBe(+ STREAM_STALE_MS,+ );+ expect(client.getQueryDefaults(["reviewSummary", "kb-1"]).staleTime).toBeUndefined();+ expect(client.getDefaultOptions().queries?.staleTime).toBe(DEFAULT_STALE_MS);+ });+});diff --git a/web/src/queryDefaults.ts b/web/src/queryDefaults.tsnew file mode 100644index 00000000..cbc8cbf1--- /dev/null+++ b/web/src/queryDefaults.ts@@ -0,0 +1,57 @@+// 服务端数据在缓存里算多久新鲜(#518)。+//+// 从前默认项只有 retry 与 refetchOnWindowFocus,staleTime 是 0:每个查询一落地就算过期,+// 每次导航回到一页都重拉一遍。而新鲜度早已经是推的、不是拉的——`useKbEvents` 订着当前库的+// 事件流,该刷的键它会失效,失效不看 staleTime。于是挂载时那次重拉对流覆盖的键是重复的,+// 对其余键多半是浪费:79 处 useQuery 只有 4 处各自设了 staleTime,`me` 在 12 处查同一个人,+// 六处 `placeholderData: (prev) => prev` 是在下游遮这个重拉带来的闪烁。+//+// 按键头分三档,写在这一处:+//+// - **一次会话内不变的**:me、health、deployment。Infinity。换人不靠过期,靠登录+// (`Login` 成功时)与登出(`UserMenu`)清空整个缓存——会话过期后同一标签页登另一个账号+// 是唯一会露馅的路,所以登录那一清不能省。deployment 由设置页的 mutation 自己失效。+// - **事件流覆盖的**:documents、graph、review、pending、sources、mappings。当前库即时;+// 可流只订**当前**库,切库回来、EventSource 断线重连期间都没人失效,所以不是 Infinity:+// 30 秒内自愈,且 `setKb` 切库时按 `STREAM_KEYS` 主动失效目标库。+// - **其余**:15 秒的全局默认。来回导航不重拉;别的会话或后台任务改了,15 秒内看见。+// 要更短的键(readiness 10 秒)在自己那处写,只有比这里短的才值得单独写。+//+// `setQueryDefaults` 按键前缀匹配:`["graph"]` 管到 `["graph", kbId, …]`。+import type { QueryClient } from "@tanstack/react-query";++/** 其余键的默认新鲜期 */+export const DEFAULT_STALE_MS = 15_000;+/** 事件流覆盖的键:切库与断线的漏洞在这个窗口内自愈 */+export const STREAM_STALE_MS = 30_000;++/** 事件流会失效的键头(见 `useKbEvents`);切库时也按这张表失效目标库 */+export const STREAM_KEYS = [+ "documents",+ "graph",+ "review",+ "pending",+ "sources",+ "mappings",+] as const;+/** 一次会话内不变的键头;换人靠清空缓存 */+export const SESSION_KEYS = ["me", "health", "deployment"] as const;++const STALE_BY_HEAD: ReadonlyMap<string, number> = new Map<string, number>([+ ...SESSION_KEYS.map((head): [string, number] => [head, Infinity]),+ ...STREAM_KEYS.map((head): [string, number] => [head, STREAM_STALE_MS]),+]);++/** 一个键该用的新鲜期。测试用它对表;运行时由 `applyQueryDefaults` 装进 QueryClient */+export function staleTimeFor(queryKey: readonly unknown[]): number {+ const head = queryKey[0];+ if (typeof head !== "string") return DEFAULT_STALE_MS;+ return STALE_BY_HEAD.get(head) ?? DEFAULT_STALE_MS;+}++/** 把上面那张表装进 QueryClient;全局默认在 `main.tsx` 建客户端时给 */+export function applyQueryDefaults(client: QueryClient): void {+ for (const [head, staleTime] of STALE_BY_HEAD) {+ client.setQueryDefaults([head], { staleTime });+ }+}diff --git a/web/src/useKbEvents.test.ts b/web/src/useKbEvents.test.tsnew file mode 100644index 00000000..d2188efb--- /dev/null+++ b/web/src/useKbEvents.test.ts@@ -0,0 +1,48 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createInvalidationCoalescer } from "./useKbEvents";++describe("a burst of events buys one refetch", () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ it("the same key pushed many times inside the settle window invalidates once", () => {+ const seen: unknown[] = [];+ const { push } = createInvalidationCoalescer((key) => seen.push(key), 300);+ for (let i = 0; i < 12; i++) push(["graph"]);+ expect(seen).toEqual([]);+ vi.advanceTimersByTime(299);+ expect(seen).toEqual([]);+ vi.advanceTimersByTime(1);+ expect(seen).toEqual([["graph"]]);+ });++ it("different keys in one burst each invalidate once, in arrival order", () => {+ const seen: unknown[] = [];+ const { push } = createInvalidationCoalescer((key) => seen.push(key), 300);+ push(["documents", "kb"], ["graph"]);+ push(["graph"]);+ push(["review", "kb"]);+ vi.advanceTimersByTime(300);+ expect(seen).toEqual([["documents", "kb"], ["graph"], ["review", "kb"]]);+ });++ it("a burst after the window is a new burst", () => {+ const seen: unknown[] = [];+ const { push } = createInvalidationCoalescer((key) => seen.push(key), 300);+ push(["graph"]);+ vi.advanceTimersByTime(300);+ push(["graph"]);+ vi.advanceTimersByTime(300);+ expect(seen).toEqual([["graph"], ["graph"]]);+ });++ it("flushing on unmount delivers what was pending instead of dropping it", () => {+ const seen: unknown[] = [];+ const { push, flush } = createInvalidationCoalescer((key) => seen.push(key), 300);+ push(["pending", "kb"]);+ flush();+ expect(seen).toEqual([["pending", "kb"]]);+ vi.advanceTimersByTime(300);+ expect(seen).toEqual([["pending", "kb"]]);+ });+});diff --git a/web/src/useKbEvents.ts b/web/src/useKbEvents.tsindex 29d2469d..8026f3bb 100644--- a/web/src/useKbEvents.ts+++ b/web/src/useKbEvents.ts@@ -6,45 +6,64 @@// 每次都是同一张图,最后一次才算数。所以事件只把 key 记下来,停顿一小会// 再一次性失效:一阵事件只换来一次重取,最后那次一定包含之前所有的变化。// 幂等性没变,只是把「每条都刷」变成「刷最后一条」。+//+// 失效不看 staleTime:这里失效的键在 queryDefaults.ts 里放到了 30 秒,靠的就是+// 这一层把当前库的变化即时推到页面上。import { useEffect } from "react";import { useQueryClient, type QueryKey } from "@tanstack/react-query";/** 一阵事件之间的静默期。抽取落事实的间隔远小于它,人眼看不出这点延迟 */-const SETTLE_MS = 300;+export const SETTLE_MS = 300;++/**+ * 把一阵失效合并成一次:`push` 只记键,静默 `settleMs` 后一起交给 `invalidate`,+ * 同一个键记多少次都只失效一次;`flush` 给卸载用,攒着的刷掉而不是丢掉。+ * 抽成纯函数是为了能测;订阅那层只是把事件名映射到键。+ */+export function createInvalidationCoalescer(+ invalidate: (key: QueryKey) => void,+ settleMs: number,+) {+ const pending = new Map<string, QueryKey>();+ let timer: ReturnType<typeof setTimeout> | null = null;+ const flush = () => {+ if (timer !== null) {+ clearTimeout(timer);+ timer = null;+ }+ const keys = [...pending.values()];+ pending.clear();+ for (const key of keys) invalidate(key);+ };+ const push = (...keys: QueryKey[]) => {+ for (const key of keys) pending.set(JSON.stringify(key), key);+ if (timer === null) timer = setTimeout(flush, settleMs);+ };+ return { push, flush };+}export function useKbEvents(kbId: string | undefined) {const queryClient = useQueryClient();useEffect(() => {if (!kbId) return;- const pending = new Map<string, QueryKey>();- let timer: ReturnType<typeof setTimeout> | null = null;- const flush = () => {- timer = null;- const keys = [...pending.values()];- pending.clear();- for (const key of keys) queryClient.invalidateQueries({ queryKey: key });- };- const invalidate = (...keys: QueryKey[]) => {- for (const key of keys) pending.set(JSON.stringify(key), key);- if (timer === null) timer = setTimeout(flush, SETTLE_MS);- };+ const { push, flush } = createInvalidationCoalescer(+ (key) => queryClient.invalidateQueries({ queryKey: key }),+ SETTLE_MS,+ );const es = new EventSource(`/api/v1/kbs/${kbId}/events`);- es.addEventListener("document", () => invalidate(["documents", kbId], ["graph"]));- es.addEventListener("graph", () => invalidate(["graph"]));+ es.addEventListener("document", () => push(["documents", kbId], ["graph"]));+ es.addEventListener("graph", () => push(["graph"]));// 映射探索跑完发的也是 review:Pending 那一栏得跟着刷新- es.addEventListener("review", () => invalidate(["review", kbId], ["mappings", kbId]));+ es.addEventListener("review", () => push(["review", kbId], ["mappings", kbId]));// 一句记忆抽出了等人点头的事实(0015):对话里那张确认卡跟着长出来- es.addEventListener("pending", () => invalidate(["pending", kbId], ["review", kbId]));- es.addEventListener("source", () => invalidate(["sources", kbId], ["documents", kbId]));+ es.addEventListener("pending", () => push(["pending", kbId], ["review", kbId]));+ es.addEventListener("source", () => push(["sources", kbId], ["documents", kbId]));return () => {es.close();// 卸载时把攒着的刷掉而不是丢掉:换页回来看到的必须是新数据- if (timer !== null) {- clearTimeout(timer);- flush();- }+ flush();};}, [kbId, queryClient]);}diff --git a/web/vite.config.ts b/web/vite.config.tsindex 97c5dbb2..40696d42 100644--- a/web/vite.config.ts+++ b/web/vite.config.ts@@ -1,4 +1,4 @@-import { defineConfig } from "vite";+import { defineConfig } from "vitest/config";import react from "@vitejs/plugin-react";import tailwindcss from "@tailwindcss/vite";@@ -12,4 +12,9 @@ export default defineConfig({"/api": process.env.UTOPIA_DEV_API ?? "http://127.0.0.1:1516",},},+ test: {+ // 纯逻辑单测,不起 DOM:queryDefaults 那张表、事件失效的合并+ include: ["src/**/*.test.ts"],+ environment: "node",+ },});