@allbluecn/admin-app 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/package.json +1 -2
  2. package/src/components/data-table/__tests__/data-table-virtual.test.tsx +111 -0
  3. package/src/components/data-table/data-table.tsx +11 -3
  4. package/src/components/devtools/devtools-panel.tsx +56 -0
  5. package/src/lib/__tests__/history-search-restore.test.tsx +53 -0
  6. package/src/lib/__tests__/query-defaults.test.ts +168 -0
  7. package/src/lib/__tests__/query-global-error.test.ts +257 -0
  8. package/src/lib/query-defaults.ts +8 -0
  9. package/src/lib/query-global-error.ts +182 -0
  10. package/src/paraglide/README.md +1 -1
  11. package/src/paraglide/messages/_index.js +1 -0
  12. package/src/paraglide/messages/common_error_generic.js +29 -0
  13. package/src/providers/index.tsx +2 -0
  14. package/src/router.tsx +24 -2
  15. package/src/routes/_nav/monitoring/route.lazy.tsx +9 -9
  16. package/src/server/__tests__/admin-billing.test.ts +33 -1
  17. package/src/server/__tests__/audit.test.ts +33 -1
  18. package/src/server/__tests__/compliance.test.ts +33 -1
  19. package/src/server/__tests__/invitations.test.ts +33 -1
  20. package/src/server/__tests__/permissions.test.ts +33 -1
  21. package/src/server/knowledge/public/kp-factory.ts +14 -15
  22. package/src/server/middlewares/__tests__/auth-context.test.ts +166 -0
  23. package/src/server/middlewares/auth-context.ts +58 -0
  24. package/src/server/serverFns/admin-billing.ts +4 -4
  25. package/src/server/serverFns/ai-memory/clear.ts +2 -2
  26. package/src/server/serverFns/ai-memory/delete.ts +2 -2
  27. package/src/server/serverFns/ai-memory/list-users.ts +2 -2
  28. package/src/server/serverFns/ai-memory/list.ts +2 -2
  29. package/src/server/serverFns/ai-prompts/activate.ts +4 -4
  30. package/src/server/serverFns/ai-prompts/get.ts +2 -2
  31. package/src/server/serverFns/ai-prompts/list.ts +2 -2
  32. package/src/server/serverFns/ai-prompts/preview.ts +2 -2
  33. package/src/server/serverFns/ai-prompts/rollback.ts +4 -4
  34. package/src/server/serverFns/ai-prompts/save.ts +4 -4
  35. package/src/server/serverFns/ai-provider/create.ts +2 -2
  36. package/src/server/serverFns/ai-provider/delete.ts +2 -2
  37. package/src/server/serverFns/ai-provider/get.ts +2 -2
  38. package/src/server/serverFns/ai-provider/list.ts +2 -2
  39. package/src/server/serverFns/ai-provider/seed-from-seed.ts +2 -2
  40. package/src/server/serverFns/ai-provider/update.ts +2 -2
  41. package/src/server/serverFns/anyhub/market.ts +4 -4
  42. package/src/server/serverFns/audit.ts +2 -2
  43. package/src/server/serverFns/compliance.ts +6 -6
  44. package/src/server/serverFns/components/import.ts +3 -3
  45. package/src/server/serverFns/components/list.ts +2 -2
  46. package/src/server/serverFns/components/mutations.ts +4 -4
  47. package/src/server/serverFns/dependency/list.ts +2 -2
  48. package/src/server/serverFns/dependency/sync.ts +3 -3
  49. package/src/server/serverFns/dependency/update.ts +2 -2
  50. package/src/server/serverFns/developer-log-auto-generate.ts +3 -3
  51. package/src/server/serverFns/developer-logs.ts +5 -5
  52. package/src/server/serverFns/invitations.ts +9 -9
  53. package/src/server/serverFns/knowledge/public/bookmarks/create.ts +2 -0
  54. package/src/server/serverFns/knowledge/public/bookmarks/delete.ts +2 -0
  55. package/src/server/serverFns/knowledge/public/bookmarks/detail.ts +2 -0
  56. package/src/server/serverFns/knowledge/public/bookmarks/list.ts +2 -0
  57. package/src/server/serverFns/knowledge/public/bookmarks/sync-all-github.ts +2 -2
  58. package/src/server/serverFns/knowledge/public/bookmarks/update.ts +2 -0
  59. package/src/server/serverFns/knowledge/public/compliance/create.ts +2 -0
  60. package/src/server/serverFns/knowledge/public/compliance/delete.ts +2 -0
  61. package/src/server/serverFns/knowledge/public/compliance/detail.ts +2 -0
  62. package/src/server/serverFns/knowledge/public/compliance/list.ts +2 -0
  63. package/src/server/serverFns/knowledge/public/compliance/update.ts +2 -0
  64. package/src/server/serverFns/knowledge/public/legal/create.ts +2 -0
  65. package/src/server/serverFns/knowledge/public/legal/delete.ts +2 -0
  66. package/src/server/serverFns/knowledge/public/legal/detail.ts +2 -0
  67. package/src/server/serverFns/knowledge/public/legal/list.ts +2 -0
  68. package/src/server/serverFns/knowledge/public/legal/update.ts +2 -0
  69. package/src/server/serverFns/licenses.ts +5 -5
  70. package/src/server/serverFns/monitoring/check-ai-alerts.ts +2 -2
  71. package/src/server/serverFns/monitoring/get-ai-usage-overview.ts +2 -2
  72. package/src/server/serverFns/monitoring/get-errors.ts +2 -2
  73. package/src/server/serverFns/monitoring/get-health-settings.ts +3 -3
  74. package/src/server/serverFns/monitoring/get-health.ts +2 -2
  75. package/src/server/serverFns/monitoring/get-metrics.ts +2 -2
  76. package/src/server/serverFns/monitoring/get-request-logs.ts +2 -2
  77. package/src/server/serverFns/monitoring/report-error.ts +2 -2
  78. package/src/server/serverFns/monitoring/reset.ts +2 -2
  79. package/src/server/serverFns/oauth-providers.ts +5 -5
  80. package/src/server/serverFns/permissions.ts +8 -8
  81. package/src/server/serverFns/sentry/config.ts +4 -4
  82. package/src/server/serverFns/sso-config.ts +5 -5
  83. package/src/server/serverFns/user/create.ts +4 -4
  84. package/src/server/serverFns/user/deactivate.ts +5 -5
  85. package/src/server/serverFns/user/detail.ts +2 -2
  86. package/src/server/serverFns/user/list.ts +2 -2
  87. package/src/server/serverFns/user/reset-password.ts +2 -2
  88. package/src/server/serverFns/user/update-role.ts +4 -4
  89. package/src/server/serverFns/user/update-status.ts +5 -5
  90. package/src/server/serverfn-public-allowlist.ts +28 -0
@@ -0,0 +1,257 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import { MutationCache, QueryCache, QueryClient } from '@tanstack/react-query'
3
+ import { m } from '@/paraglide/messages.js'
4
+ import { toast } from '@/components/ui/toast'
5
+ import {
6
+ handleGlobalMutationError,
7
+ handleGlobalQueryError,
8
+ } from '../query-global-error'
9
+
10
+ vi.mock('@/components/ui/toast', () => ({
11
+ toast: { error: vi.fn() },
12
+ }))
13
+
14
+ function makeRouter() {
15
+ const navigate = vi.fn()
16
+ // 结构桩仅含 handler 实际消费的字段,与既有 anonymous-safe.test.ts 同口径 as never
17
+ const router = {
18
+ state: { location: { pathname: '/users', searchStr: '?tab=active' } },
19
+ navigate,
20
+ } as never
21
+ return { router, navigate }
22
+ }
23
+
24
+ /** 构建一个直接失败的 query 并触发其 fetch(retry: false 免去重试延迟) */
25
+ async function fetchFailingQuery(
26
+ queryCache: QueryCache,
27
+ client: QueryClient,
28
+ options: { error: unknown; meta?: Record<string, unknown> },
29
+ ) {
30
+ const query = queryCache.build(client, {
31
+ queryKey: ['test-global-error'],
32
+ queryFn: () => Promise.reject(options.error),
33
+ retry: false,
34
+ meta: options.meta,
35
+ })
36
+ await query.fetch().catch(() => undefined)
37
+ }
38
+
39
+ /** 构建并执行一个直接失败的 mutation */
40
+ async function executeFailingMutation(
41
+ mutationCache: MutationCache,
42
+ client: QueryClient,
43
+ options: { error: unknown; meta?: Record<string, unknown> },
44
+ ) {
45
+ const mutation = mutationCache.build(client, {
46
+ mutationFn: () => Promise.reject(options.error),
47
+ meta: options.meta,
48
+ })
49
+ await mutation.execute(undefined as never).catch(() => undefined)
50
+ }
51
+
52
+ beforeEach(() => {
53
+ vi.mocked(toast.error).mockClear()
54
+ })
55
+
56
+ describe('QueryCache 全局 onError(admin 全新兜底)', () => {
57
+ it('401 查询错误跳登录(带回跳)且不 toast', async () => {
58
+ const { router, navigate } = makeRouter()
59
+ const queryCache = new QueryCache({
60
+ onError: (error, query) => handleGlobalQueryError(error, query, router),
61
+ })
62
+ const client = new QueryClient({ queryCache })
63
+ await fetchFailingQuery(queryCache, client, {
64
+ error: new Error('UNAUTHORIZED'),
65
+ })
66
+ expect(navigate).toHaveBeenCalledWith({
67
+ to: '/login',
68
+ search: { redirect: '/users?tab=active' },
69
+ })
70
+ expect(toast.error).not.toHaveBeenCalled()
71
+ })
72
+
73
+ it('识别 name 为 UnauthorizedError 的错误形态(serverFn requireAdmin 直抛)', async () => {
74
+ const { router, navigate } = makeRouter()
75
+ const queryCache = new QueryCache({
76
+ onError: (error, query) => handleGlobalQueryError(error, query, router),
77
+ })
78
+ const client = new QueryClient({ queryCache })
79
+ const e = new Error('别的消息')
80
+ e.name = 'UnauthorizedError'
81
+ await fetchFailingQuery(queryCache, client, { error: e })
82
+ expect(navigate).toHaveBeenCalledWith({
83
+ to: '/login',
84
+ search: { redirect: '/users?tab=active' },
85
+ })
86
+ expect(toast.error).not.toHaveBeenCalled()
87
+ })
88
+
89
+ it('4xx(非 401)toast 展示错误详情', async () => {
90
+ const { router, navigate } = makeRouter()
91
+ const queryCache = new QueryCache({
92
+ onError: (error, query) => handleGlobalQueryError(error, query, router),
93
+ })
94
+ const client = new QueryClient({ queryCache })
95
+ await fetchFailingQuery(queryCache, client, {
96
+ error: Object.assign(new Error('权限不足'), { status: 403 }),
97
+ })
98
+ expect(toast.error).toHaveBeenCalledWith('权限不足')
99
+ expect(navigate).not.toHaveBeenCalled()
100
+ })
101
+
102
+ it('5xx toast 通用文案(不透出服务端错误详情)', async () => {
103
+ const { router } = makeRouter()
104
+ const queryCache = new QueryCache({
105
+ onError: (error, query) => handleGlobalQueryError(error, query, router),
106
+ })
107
+ const client = new QueryClient({ queryCache })
108
+ await fetchFailingQuery(queryCache, client, {
109
+ error: Object.assign(new Error('Internal Server Error'), {
110
+ statusCode: 500,
111
+ }),
112
+ })
113
+ expect(toast.error).toHaveBeenCalledWith(m.common_error_generic())
114
+ })
115
+
116
+ it('网络错误(无 status)toast 通用文案', async () => {
117
+ const { router } = makeRouter()
118
+ const queryCache = new QueryCache({
119
+ onError: (error, query) => handleGlobalQueryError(error, query, router),
120
+ })
121
+ const client = new QueryClient({ queryCache })
122
+ await fetchFailingQuery(queryCache, client, {
123
+ error: new TypeError('Failed to fetch'),
124
+ })
125
+ expect(toast.error).toHaveBeenCalledWith(m.common_error_generic())
126
+ })
127
+
128
+ it('query meta.suppressGlobalToast=true 时全局 onError 不出手(防双 toast)', async () => {
129
+ const { router, navigate } = makeRouter()
130
+ const queryCache = new QueryCache({
131
+ onError: (error, query) => handleGlobalQueryError(error, query, router),
132
+ })
133
+ const client = new QueryClient({ queryCache })
134
+ await fetchFailingQuery(queryCache, client, {
135
+ error: Object.assign(new Error('权限不足'), { status: 403 }),
136
+ meta: { suppressGlobalToast: true },
137
+ })
138
+ expect(toast.error).not.toHaveBeenCalled()
139
+ expect(navigate).not.toHaveBeenCalled()
140
+ })
141
+
142
+ it('查询取消(CancelledError)不 toast 不跳转', async () => {
143
+ const { router, navigate } = makeRouter()
144
+ const queryCache = new QueryCache({
145
+ onError: (error, query) => handleGlobalQueryError(error, query, router),
146
+ })
147
+ const client = new QueryClient({ queryCache })
148
+ await fetchFailingQuery(queryCache, client, {
149
+ error: new Error('CancelledError'),
150
+ })
151
+ expect(toast.error).not.toHaveBeenCalled()
152
+ expect(navigate).not.toHaveBeenCalled()
153
+ })
154
+
155
+ it('SSR(window 缺失)不跳转不 toast', async () => {
156
+ vi.stubGlobal('window', undefined)
157
+ try {
158
+ const { router, navigate } = makeRouter()
159
+ const queryCache = new QueryCache({
160
+ onError: (error, query) => handleGlobalQueryError(error, query, router),
161
+ })
162
+ const client = new QueryClient({ queryCache })
163
+ await fetchFailingQuery(queryCache, client, {
164
+ error: new Error('UNAUTHORIZED'),
165
+ })
166
+ await fetchFailingQuery(queryCache, client, {
167
+ error: Object.assign(new Error('权限不足'), { status: 403 }),
168
+ })
169
+ expect(navigate).not.toHaveBeenCalled()
170
+ expect(toast.error).not.toHaveBeenCalled()
171
+ } finally {
172
+ vi.unstubAllGlobals()
173
+ }
174
+ })
175
+ })
176
+
177
+ describe('MutationCache 全局 onError(admin 全新兜底)', () => {
178
+ it('401 变更错误跳登录(带回跳)', async () => {
179
+ const { router, navigate } = makeRouter()
180
+ const mutationCache = new MutationCache({
181
+ onError: (error, _variables, _onMutateResult, mutation) =>
182
+ handleGlobalMutationError(error, mutation, router),
183
+ })
184
+ const client = new QueryClient({ mutationCache })
185
+ await executeFailingMutation(mutationCache, client, {
186
+ error: new Error('UNAUTHORIZED'),
187
+ })
188
+ expect(navigate).toHaveBeenCalledWith({
189
+ to: '/login',
190
+ search: { redirect: '/users?tab=active' },
191
+ })
192
+ expect(toast.error).not.toHaveBeenCalled()
193
+ })
194
+
195
+ it('非 401 变更错误 toast 详情(403)', async () => {
196
+ const { router, navigate } = makeRouter()
197
+ const mutationCache = new MutationCache({
198
+ onError: (error, _variables, _onMutateResult, mutation) =>
199
+ handleGlobalMutationError(error, mutation, router),
200
+ })
201
+ const client = new QueryClient({ mutationCache })
202
+ await executeFailingMutation(mutationCache, client, {
203
+ error: Object.assign(new Error('配额不足'), { status: 403 }),
204
+ })
205
+ expect(toast.error).toHaveBeenCalledWith('配额不足')
206
+ expect(navigate).not.toHaveBeenCalled()
207
+ })
208
+
209
+ it('5xx 变更错误 toast 通用文案', async () => {
210
+ const { router } = makeRouter()
211
+ const mutationCache = new MutationCache({
212
+ onError: (error, _variables, _onMutateResult, mutation) =>
213
+ handleGlobalMutationError(error, mutation, router),
214
+ })
215
+ const client = new QueryClient({ mutationCache })
216
+ await executeFailingMutation(mutationCache, client, {
217
+ error: Object.assign(new Error('Bad Gateway'), { status: 502 }),
218
+ })
219
+ expect(toast.error).toHaveBeenCalledWith(m.common_error_generic())
220
+ })
221
+
222
+ it('mutation options.meta.suppressGlobalToast=true 时全局 onError 不出手', async () => {
223
+ const { router } = makeRouter()
224
+ const mutationCache = new MutationCache({
225
+ onError: (error, _variables, _onMutateResult, mutation) =>
226
+ handleGlobalMutationError(error, mutation, router),
227
+ })
228
+ const client = new QueryClient({ mutationCache })
229
+ await executeFailingMutation(mutationCache, client, {
230
+ error: Object.assign(new Error('配额不足'), { status: 403 }),
231
+ meta: { suppressGlobalToast: true },
232
+ })
233
+ expect(toast.error).not.toHaveBeenCalled()
234
+ })
235
+
236
+ it('SSR(window 缺失)不跳转不 toast', async () => {
237
+ vi.stubGlobal('window', undefined)
238
+ try {
239
+ const { router, navigate } = makeRouter()
240
+ const mutationCache = new MutationCache({
241
+ onError: (error, _variables, _onMutateResult, mutation) =>
242
+ handleGlobalMutationError(error, mutation, router),
243
+ })
244
+ const client = new QueryClient({ mutationCache })
245
+ await executeFailingMutation(mutationCache, client, {
246
+ error: new Error('UNAUTHORIZED'),
247
+ })
248
+ await executeFailingMutation(mutationCache, client, {
249
+ error: Object.assign(new Error('配额不足'), { status: 403 }),
250
+ })
251
+ expect(navigate).not.toHaveBeenCalled()
252
+ expect(toast.error).not.toHaveBeenCalled()
253
+ } finally {
254
+ vi.unstubAllGlobals()
255
+ }
256
+ })
257
+ })
@@ -0,0 +1,8 @@
1
+ // 全局查询默认 staleTime:30 秒(毫秒常量)。与 apps/web/src/lib/query-defaults.ts 同口径。
2
+ // - 30s 内纯导航:loader 的 ensureQueryData / useQuery 命中缓存不重跑
3
+ // - mutation 后 invalidateQueries 不受 staleTime 阻断:显式失效把 fresh 数据
4
+ // 标记为 stale,active 查询立即 refetch、非 active 查询在下次访问时重拉
5
+ // - SSR:水合数据携带服务端 dataUpdatedAt,30s 窗口内客户端不重复请求(期望行为)
6
+ // 单一来源:router.tsx 的 defaultOptions 与协同测试
7
+ // (lib/__tests__/query-defaults.test.ts)共同引用本常量。
8
+ export const QUERY_STALE_TIME_MS = 30_000
@@ -0,0 +1,182 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // This program is free software: you can redistribute it and/or modify
6
+ // it under the terms of the GNU Affero General Public License as published by
7
+ // the Free Software Foundation, either version 3 of the License, or
8
+ // (at your option) any later version.
9
+ //
10
+ // This program is distributed in the hope that it will be useful,
11
+ // but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ // GNU Affero General Public License for more details.
14
+ //
15
+ // You should have received a copy of the GNU Affero General Public License
16
+ // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+
18
+ import { toast } from '@/components/ui/toast'
19
+ import { m } from '@/paraglide/messages.js'
20
+ import type { Mutation, Query } from '@tanstack/react-query'
21
+ import type { AnyRouter } from '@tanstack/react-router'
22
+
23
+ /**
24
+ * QueryCache / MutationCache 全局 onError 兜底(router.tsx 的 QueryClient 构造期注入,
25
+ * admin 此前双 Cache 均为空白)。
26
+ *
27
+ * meta 约定(防双 toast):query / mutation 的 options.meta 传
28
+ * `{ suppressGlobalToast: true }` 表示该次请求的错误由组件层自管提示
29
+ * (如 useMutation 的 onError 已 toast 详情),全局兜底不再重复出手;
30
+ * 错误对象自身携带 `meta.suppressGlobalToast`(包装重抛场景)时同样抑制。
31
+ * 401 跳登录不受该 meta 影响——会话过期重定向不是 toast,必须始终生效。
32
+ * (meta 类型按 unknown 读取:Register.queryMeta 可能被其他包声明收窄,
33
+ * 此处不做二次收窄,按鸭子类型读取 suppressGlobalToast。)
34
+ *
35
+ * 错误分级:401 → 跳登录(与 page-gate 同目标路径:/login + redirect 回跳,
36
+ * 识别形态对齐 server 端 requireAdmin 直抛的 UnauthorizedError);4xx(非 401)→
37
+ * toast 错误详情(业务语义错误,空消息回落通用文案);5xx / 网络中断 / 未知
38
+ * 形态 → toast 通用文案(不透出服务端内部详情)。
39
+ *
40
+ * SSR 硬约束:缓存 onError 在服务端 loader 查询失败时同样触发,
41
+ * 跳登录 / toast 必须守卫 `typeof window !== 'undefined'`,且整体
42
+ * try/catch 兜底——全局兜底自身绝不抛出(jsdom/SSR 环境守卫穿透教训)。
43
+ */
44
+
45
+ type RouterLike = Pick<AnyRouter, 'state' | 'navigate'>
46
+
47
+ const UNAUTHORIZED_NAME = 'UnauthorizedError'
48
+ const UNAUTHORIZED_STATUS = 401
49
+ /** TanStack query-core CancelledError 的 message(取消非故障,不提示) */
50
+ const CANCELLED_ERROR_MESSAGE = 'CancelledError'
51
+
52
+ /** QueryCache 全局 onError:签名 (error, query),见 query-core QueryCacheConfig */
53
+ export function handleGlobalQueryError(
54
+ error: unknown,
55
+ query: Query<unknown, unknown, unknown>,
56
+ router: RouterLike,
57
+ ): void {
58
+ handleGlobalError(error, query.meta, router)
59
+ }
60
+
61
+ /** MutationCache 全局 onError:签名 (error, variables, onMutateResult, mutation, context),见 MutationCacheConfig */
62
+ export function handleGlobalMutationError(
63
+ error: unknown,
64
+ mutation: Mutation<unknown, unknown, unknown>,
65
+ router: RouterLike,
66
+ ): void {
67
+ handleGlobalError(error, mutation.options?.meta, router)
68
+ }
69
+
70
+ function handleGlobalError(
71
+ error: unknown,
72
+ meta: unknown,
73
+ router: RouterLike,
74
+ ): void {
75
+ try {
76
+ if (isCancelledErrorShape(error)) return
77
+ if (isUnauthorizedError(error)) {
78
+ // 客户端跳登录;SSR 侧交由路由 loader/beforeLoad(requireAdminPage)重定向
79
+ if (typeof window !== 'undefined') {
80
+ navigateToLoginOnUnauthorized(error, router)
81
+ }
82
+ return
83
+ }
84
+ if (isGlobalToastSuppressed(error, meta)) return
85
+ // toast 仅浏览器端有渲染通道,SSR 静默
86
+ if (typeof window === 'undefined') return
87
+ if (isClientErrorStatus(extractErrorStatus(error))) {
88
+ // 4xx(非 401):业务语义错误,展示详情;空消息回落通用文案
89
+ toast.error(pickErrorMessage(error, new WeakSet()) ?? m.common_error_generic())
90
+ return
91
+ }
92
+ // 5xx / 网络中断 / 未知形态:通用文案
93
+ toast.error(m.common_error_generic())
94
+ } catch {
95
+ // 全局兜底自身绝不抛出,避免把缓存层回调放大为未捕获异常
96
+ }
97
+ }
98
+
99
+ function isCancelledErrorShape(error: unknown): boolean {
100
+ return error instanceof Error && error.message === CANCELLED_ERROR_MESSAGE
101
+ }
102
+
103
+ function isGlobalToastSuppressed(error: unknown, meta: unknown): boolean {
104
+ const carried = (error as { meta?: unknown } | null)?.meta
105
+ if (isSuppressFlag(carried)) return true
106
+ return isSuppressFlag(meta)
107
+ }
108
+
109
+ function isSuppressFlag(meta: unknown): boolean {
110
+ return (
111
+ (meta as { suppressGlobalToast?: unknown } | null | undefined)
112
+ ?.suppressGlobalToast === true
113
+ )
114
+ }
115
+
116
+ function isClientErrorStatus(status: number | undefined): boolean {
117
+ return typeof status === 'number' && status >= 400 && status < 500
118
+ }
119
+
120
+ function isUnauthorizedMessage(msg: unknown): boolean {
121
+ return typeof msg === 'string' && msg.toLowerCase() === 'unauthorized'
122
+ }
123
+
124
+ /**
125
+ * 401 识别(对齐 server/auth-helpers 的 UnauthorizedError 直抛形态与
126
+ * serverFn RPC 序列化的 message 形态,兼容 status/statusCode/包裹形态),WeakSet 防环
127
+ */
128
+ function isUnauthorizedError(
129
+ error: unknown,
130
+ seen: WeakSet<object> = new WeakSet(),
131
+ ): boolean {
132
+ if (!error || typeof error !== 'object' || seen.has(error)) return false
133
+ seen.add(error)
134
+ const e = error as {
135
+ message?: unknown
136
+ name?: unknown
137
+ status?: unknown
138
+ statusCode?: unknown
139
+ error?: unknown
140
+ }
141
+ return (
142
+ isUnauthorizedMessage(e.message) ||
143
+ e.name === UNAUTHORIZED_NAME ||
144
+ e.status === UNAUTHORIZED_STATUS ||
145
+ e.statusCode === UNAUTHORIZED_STATUS ||
146
+ isUnauthorizedError(e.error, seen)
147
+ )
148
+ }
149
+
150
+ /** 401 跳登录(带当前页回跳),目标路径与 page-gate 的 redirect 约定一致 */
151
+ function navigateToLoginOnUnauthorized(error: unknown, router: RouterLike): void {
152
+ const loc = router.state.location
153
+ router.navigate({
154
+ to: '/login',
155
+ search: { redirect: loc.pathname + loc.searchStr },
156
+ })
157
+ }
158
+
159
+ /**
160
+ * 提取 HTTP status(status / statusCode 字段),兼容包裹形态
161
+ * (error.error 为原始错误),WeakSet 防环
162
+ */
163
+ function extractErrorStatus(
164
+ error: unknown,
165
+ seen: WeakSet<object> = new WeakSet(),
166
+ ): number | undefined {
167
+ if (!error || typeof error !== 'object' || seen.has(error)) return undefined
168
+ seen.add(error)
169
+ const e = error as { status?: unknown; statusCode?: unknown; error?: unknown }
170
+ if (typeof e.status === 'number') return e.status
171
+ if (typeof e.statusCode === 'number') return e.statusCode
172
+ return extractErrorStatus(e.error, seen)
173
+ }
174
+
175
+ /** 取链路中第一个带非空 message 的 Error 文案(普通错误即自身 message) */
176
+ function pickErrorMessage(error: unknown, seen: WeakSet<object>): string | undefined {
177
+ if (!error || typeof error !== 'object' || seen.has(error)) return undefined
178
+ seen.add(error)
179
+ const e = error as { message?: unknown; error?: unknown }
180
+ if (typeof e.message === 'string' && e.message) return e.message
181
+ return pickErrorMessage(e.error, seen)
182
+ }
@@ -2,7 +2,7 @@
2
2
 
3
3
  > Auto-generated i18n message functions. Import `messages.js` to use translated strings.
4
4
 
5
- Compiled from: `/Users/urmynami/HelloAI/AllBlue-Workspace/AllBlue/apps/admin/project.inlang`
5
+ Compiled from: `/Users/urmynami/HelloAI/AllBlue-Workspace/AllBlue/.worktrees/feat-tanstack-optimization/apps/admin/project.inlang`
6
6
 
7
7
 
8
8
  ## What is this folder?
@@ -757,6 +757,7 @@ export * from './common_errorpage_errormessage2.js'
757
757
  export * from './common_errorpage_genericdescription2.js'
758
758
  export * from './common_errorpage_gologin2.js'
759
759
  export * from './common_errorpage_notfound2.js'
760
+ export * from './common_error_generic.js'
760
761
  export * from './common_knowledgepublic_bookmarks_columns_category1.js'
761
762
  export * from './common_knowledgepublic_bookmarks_columns_createdat2.js'
762
763
  export * from './common_knowledgepublic_bookmarks_columns_tags1.js'
@@ -0,0 +1,29 @@
1
+ /* eslint-disable */
2
+ import { getLocale, experimentalStaticLocale } from '../runtime.js';
3
+
4
+ /** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
5
+
6
+ /** @typedef {{}} Common_Error_GenericInputs */
7
+
8
+ const zh_common_error_generic = /** @type {(inputs: Common_Error_GenericInputs) => LocalizedString} */ () => {
9
+ return /** @type {LocalizedString} */ (`请求失败,请稍后重试`)
10
+ };
11
+
12
+ const en_common_error_generic = /** @type {(inputs: Common_Error_GenericInputs) => LocalizedString} */ () => {
13
+ return /** @type {LocalizedString} */ (`Request failed. Please try again later`)
14
+ };
15
+
16
+ /**
17
+ * | output |
18
+ * | --- |
19
+ * | "Request failed. Please try again later" |
20
+ *
21
+ * @param {Common_Error_GenericInputs} inputs
22
+ * @param {{ locale?: "zh" | "en" }} options
23
+ * @returns {LocalizedString}
24
+ */
25
+ export const common_error_generic = /** @type {((inputs?: Common_Error_GenericInputs, options?: { locale?: "zh" | "en" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Common_Error_GenericInputs, { locale?: "zh" | "en" }, {}>} */ ((inputs = {}, options = {}) => {
26
+ const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
27
+ if (locale === "en") return en_common_error_generic(inputs)
28
+ return zh_common_error_generic(inputs)
29
+ });
@@ -19,6 +19,7 @@
19
19
  import { ThemeProvider } from "next-themes";
20
20
  import { type ReactNode } from "react";
21
21
  import { TooltipProvider } from "@/components/ui/tooltip";
22
+ import { DevtoolsPanel } from "@/components/devtools/devtools-panel";
22
23
 
23
24
  export function Providers({
24
25
  children,
@@ -29,6 +30,7 @@ export function Providers({
29
30
  <ThemeProvider attribute="class" defaultTheme="light" enableSystem>
30
31
  <TooltipProvider>
31
32
  {children}
33
+ {import.meta.env.DEV && <DevtoolsPanel />}
32
34
  </TooltipProvider>
33
35
  </ThemeProvider>
34
36
  );
package/src/router.tsx CHANGED
@@ -18,14 +18,36 @@
18
18
  import * as Sentry from '@sentry/tanstackstart-react'
19
19
  import { createRouter as createTanstackRouter } from '@tanstack/react-router'
20
20
  import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query'
21
- import { QueryClient } from '@tanstack/react-query'
21
+ import { MutationCache, QueryCache, QueryClient } from '@tanstack/react-query'
22
+ import {
23
+ handleGlobalMutationError,
24
+ handleGlobalQueryError,
25
+ } from '@/lib/query-global-error'
26
+ import { QUERY_STALE_TIME_MS } from '@/lib/query-defaults'
22
27
  import { routeTree } from './routeTree.gen'
23
28
 
24
29
  export function getRouter() {
30
+ // QueryCache/MutationCache 必须在 QueryClient 构造期注入(该版本 Cache 实例无 onError 方法);
31
+ // onError 闭包引用下方才声明的 router——onError 只在 query/mutation 报错时触发,
32
+ // 必然晚于 getRouter 返回,运行时不会读到未初始化的 router。
33
+ // 全局兜底(401 跳登录 / 分级 toast / suppressGlobalToast meta 约定 / SSR 守卫)
34
+ // 见 @/lib/query-global-error
25
35
  const queryClient = new QueryClient({
26
36
  defaultOptions: {
27
- queries: { staleTime: 60 * 1000, refetchOnWindowFocus: false },
37
+ // 全局 staleTime 30s(见 @/lib/query-defaults 注释:纯导航窗口内命中缓存、
38
+ // invalidate 协同不阻断)
39
+ queries: { staleTime: QUERY_STALE_TIME_MS, refetchOnWindowFocus: false },
28
40
  },
41
+ queryCache: new QueryCache({
42
+ onError: (error, query) => {
43
+ handleGlobalQueryError(error, query, router)
44
+ },
45
+ }),
46
+ mutationCache: new MutationCache({
47
+ onError: (error, _variables, _onMutateResult, mutation) => {
48
+ handleGlobalMutationError(error, mutation, router)
49
+ },
50
+ }),
29
51
  })
30
52
 
31
53
  const router = createTanstackRouter({
@@ -15,7 +15,7 @@
15
15
  // You should have received a copy of the GNU Affero General Public License
16
16
  // along with this program. If not, see <https://www.gnu.org/licenses/>.
17
17
 
18
- import { createLazyFileRoute, Link, Outlet, useLocation } from '@tanstack/react-router'
18
+ import { createLazyFileRoute, Link, Outlet } from '@tanstack/react-router'
19
19
  import { m } from '@/paraglide/messages.js'
20
20
  import { SidebarTrigger } from '@/components/ui/sidebar'
21
21
  import { Separator } from '@/components/ui/separator'
@@ -25,8 +25,6 @@ export const Route = createLazyFileRoute('/_nav/monitoring')({
25
25
  })
26
26
 
27
27
  function MonitoringLayout() {
28
- const location = useLocation()
29
-
30
28
  const subNavItems = [
31
29
  { id: 'overview', label: m.common_monitoring_nav_overview(), path: '/monitoring/overview' },
32
30
  { id: 'logs', label: m.common_monitoring_nav_logs(), path: '/monitoring/logs' },
@@ -37,8 +35,6 @@ function MonitoringLayout() {
37
35
  { id: 'ai-usage', label: m.common_monitoring_nav_aiUsage(), path: '/monitoring/ai-usage' },
38
36
  ]
39
37
 
40
- const currentId = subNavItems.find((item) => location.pathname.startsWith(item.path))?.id || 'overview'
41
-
42
38
  return (
43
39
  <div className="flex flex-col min-h-0 h-full overflow-hidden">
44
40
  <header className="flex h-14 shrink-0 items-center gap-2 border-b px-4">
@@ -49,10 +45,14 @@ function MonitoringLayout() {
49
45
  <Link
50
46
  key={item.id}
51
47
  to={item.path}
52
- className={`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${currentId === item.id
53
- ? 'bg-accent text-accent-foreground'
54
- : 'text-muted-foreground hover:text-foreground hover:bg-accent/50'
55
- }`}
48
+ // 激活态由 Link 自身判定:默认模糊匹配 = 段边界前缀(等价原
49
+ // pathname.startsWith(item.path),七项互非段前缀、均为叶子路由,口径一致);
50
+ // includeSearch:false 保持纯 pathname 口径。差异:裸 /monitoring(无 index
51
+ // 子路由,仅手动输 URL 可达,应用内无入口)不再回落高亮 overview
52
+ className="px-3 py-1.5 rounded-md text-sm font-medium transition-colors"
53
+ activeProps={{ className: 'bg-accent text-accent-foreground' }}
54
+ inactiveProps={{ className: 'text-muted-foreground hover:text-foreground hover:bg-accent/50' }}
55
+ activeOptions={{ includeSearch: false }}
56
56
  >
57
57
  {item.label}
58
58
  </Link>
@@ -18,9 +18,17 @@
18
18
  import { describe, it, expect, vi, beforeEach } from 'vitest'
19
19
 
20
20
  vi.mock('@tanstack/react-start', () => ({
21
+ // 迁移后经 .middleware([adminAuthContextMiddleware]) 注入 context.admin:
22
+ // mock 依序执行 middleware 的 server 段(复现框架 executeMiddleware 的
23
+ // context 合并语义),真实鉴权链由被 mock 的 auth-helpers 承接
21
24
  createServerFn: (_config: unknown) => {
22
25
  const api: any = {
23
26
  _validator: undefined,
27
+ _middlewares: [] as any[],
28
+ middleware(mws: any[]) {
29
+ this._middlewares.push(...mws)
30
+ return this
31
+ },
24
32
  validator(schema: any) {
25
33
  this._validator = schema
26
34
  return this
@@ -31,13 +39,37 @@ vi.mock('@tanstack/react-start', () => ({
31
39
  if (this._validator && data !== undefined) {
32
40
  data = this._validator.parse ? this._validator.parse(data) : data
33
41
  }
34
- return fn({ data })
42
+ let context: any = {}
43
+ for (const mw of this._middlewares ?? []) {
44
+ const serverFn = mw?.options?.server
45
+ if (!serverFn) continue
46
+ const result = await serverFn({
47
+ data,
48
+ context,
49
+ method: 'GET',
50
+ serverFnMeta: {},
51
+ signal: new AbortController().signal,
52
+ next: async (inner: any) => ({ context: { ...context, ...(inner?.context ?? {}) } }),
53
+ })
54
+ context = result.context
55
+ }
56
+ return fn({ data, context })
35
57
  }
36
58
  return wrapped
37
59
  },
38
60
  }
39
61
  return api
40
62
  },
63
+ // adminAuthContextMiddleware 依赖 createMiddleware({ type: 'function' }).server(fn):
64
+ // mock 产出与真实 middleware 同构的 { options: { server } } 形状
65
+ createMiddleware: (opts: any) => {
66
+ const mw: any = { options: { type: opts?.type } }
67
+ mw.server = (fn: Function) => {
68
+ mw.options.server = fn
69
+ return mw
70
+ }
71
+ return mw
72
+ },
41
73
  }))
42
74
 
43
75
  vi.mock('@tanstack/react-start/server', () => ({