From 15b5e8d3319f86530bbd7106076765695ca88df8 Mon Sep 17 00:00:00 2001 From: GuoQing Zhang Date: Tue, 17 Nov 2026 16:55:36 +0800 Subject: [PATCH 1/8] fix(department): reset directory after mounting child tenant --- .../tenant-mount-refresh-fix-20261117.md | 57 ++++++ .../SystemPage/components/Departments.tsx | 29 ++- .../systemDepartmentsTenantMount.test.tsx | 184 ++++++++++++++++++ 3 files changed, 266 insertions(+), 4 deletions(-) create mode 100644 docs/reviews/tenant-mount-refresh-fix-20261117.md create mode 100644 src/frontend/platform/src/test/systemDepartmentsTenantMount.test.tsx diff --git a/docs/reviews/tenant-mount-refresh-fix-20261117.md b/docs/reviews/tenant-mount-refresh-fix-20261117.md new file mode 100644 index 0000000000..81f4aee5c5 --- /dev/null +++ b/docs/reviews/tenant-mount-refresh-fix-20261117.md @@ -0,0 +1,57 @@ +# 子租户挂载后的部门页面刷新修复 + +- 日期:2026-11-17 +- 目标分支:`feat/3.1.0-beta1` +- 基线:`19a79c8130` +- 流程:SDD Guide §1 Hotfix;不修改 API、租户归属或权限契约。 + +## 问题与修复 + +`MountTenantDialog` 成功后调用组织页的 `handleTreeChange()`。这个通用刷新流程会重新请求所有已加载的树层级,再通过 `reveal(selectedDept.id)` 定位原选中部门。 + +挂载后,子租户根及其后代已不属于 Root 组织视图。`DirectoryRepository.scope()` 排除这些子树,`require_department()` 对跨越该边界的请求返回 21009。继续刷新旧子树和选中节点会让挂载成功后再弹出权限错误。 + +本次只调整成功后的页面状态衔接: + +- 删除组织树正常/含归档两种模式的查询缓存;删除缓存不会主动刷新旧层级。 +- 重新挂载组织目录内容,清除原选中部门、快照、搜索、展开节点、成员定位和弹窗。 +- 从当前管理视图的根层级重新加载,自动选择新目录中的首个根节点。 +- 取消或挂载失败不触发该流程;真实的目录刷新失败继续交由统一错误处理展示。 + +后端的租户边界校验保持原样。解绑和普通编辑继续使用原有刷新流程。 + +## 验证 + +`systemDepartmentsTenantMount.test.tsx` 使用真实 `useLazyDepartmentTree` 和 React Query,只替换视觉组件、弹窗完成事件及网络边界,覆盖: + +1. Root → 部门 95 → 部门 96 已加载并展开,选中 95 后挂载成功:不再读取 95/96 的子层级、不再定位 95、不刷新其成员;清除含归档模式旧缓存;转到 Root。 +2. 取消挂载保留原部门,不刷新目录。 +3. 新目录为空时清除旧选中项,不展示旧成员。 +4. 新目录加载失败正常报错,不恢复旧部门数据。 + +验证结果: + +- 未修复基线运行新增测试:3 失败、1 通过,重现旧子树刷新触发 21009。 +- 修复后新增 4 项及现有归档/删除 3 项回归:7/7 通过。 +- `pnpm lint`、`pnpm typecheck`、`pnpm check-i18n` 通过。 +- 变更文件 ESLint suppression prune、架构守卫、`git diff --check` 通过;未新增 suppression。 + +## 七维审查 + +| 维度 | 结论 | 依据 | +| --- | --- | --- | +| 边界条件 | PASS | 覆盖空目录、取消操作、真实刷新失败;不保留过期选中快照。 | +| 权限与认证 | PASS | 保持后端管理域校验,前端只读取新目录;不增加跨租户绕过。 | +| 并发安全 | PASS | React Query 删除旧树查询并重新挂载其消费者;不执行旧 `refreshAll` 或 `reveal`。 | +| 信息泄漏 | PASS | 清除旧树与成员界面;无新增返回字段、日志或错误展示策略。 | +| 测试覆盖 | PASS | 新增回归在旧代码失败,在修复后通过;保留归档/删除回归。 | +| 代码风格 | PASS | 一个文件的逻辑变更;使用既有 React Query 和统一错误处理,无新增文案或依赖。 | +| 文档同步 | PASS | 热修复问题、实现、验证和部署边界记录于本文。 | + +Overall: PASS + +## 部署与验证边界 + +未在 116 部署;此前提供的 SSH 登录凭据本次未通过认证,未获取这次截图对应请求的现场日志。以上是代码调用链和组件回归证据,不等同于现场验收。 + +部署后应由 Root 管理员将一个含下级部门的部门挂载为子租户,确认只出现挂载成功提示、页面返回 Root 可见目录;再切换到新子租户管理视图验证部门和成员可正常加载。本次不操作现场租户或部门数据。 diff --git a/src/frontend/platform/src/pages/SystemPage/components/Departments.tsx b/src/frontend/platform/src/pages/SystemPage/components/Departments.tsx index 9adb9414f6..b7e27e35e7 100644 --- a/src/frontend/platform/src/pages/SystemPage/components/Departments.tsx +++ b/src/frontend/platform/src/pages/SystemPage/components/Departments.tsx @@ -1,4 +1,5 @@ import { useCallback, useContext, useEffect, useRef, useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; import { Button, Checkbox, Tooltip, toast } from "@bisheng/ui"; import { Outlined } from "bisheng-icons"; import { useTranslation } from "react-i18next"; @@ -27,6 +28,29 @@ import { OrganizationSearchPanel } from "@/pages/DepartmentPage/components/Organ import type { DepartmentTreeNode } from "@/types/api/department"; export default function Departments() { + const queryClient = useQueryClient(); + const [directoryRevision, setDirectoryRevision] = useState(0); + const handleTenantMounted = () => { + // Mounting changes the business boundary. Drop both browse caches and all + // local selection/search state before loading the directory in its new scope. + queryClient.removeQueries(["dept:false"]); + queryClient.removeQueries(["dept:true"]); + setDirectoryRevision((revision) => revision + 1); + }; + + return ( + + ); +} + +interface DepartmentDirectoryProps { + onTenantMounted: () => void; +} + +function DepartmentDirectory({ onTenantMounted }: DepartmentDirectoryProps) { const { t } = useTranslation(); const createDepartmentLabel = t("bs:department.create"); const createChildDepartmentLabel = t("bs:organization.createChildDepartment"); @@ -370,10 +394,7 @@ export default function Departments() { deptId={mountTarget.id} deptName={mountTarget.name} onClose={() => setMountTarget(null)} - onMounted={() => { - setMountTarget(null); - void handleTreeChange().catch(showApiError); - }} + onMounted={onTenantMounted} /> )} diff --git a/src/frontend/platform/src/test/systemDepartmentsTenantMount.test.tsx b/src/frontend/platform/src/test/systemDepartmentsTenantMount.test.tsx new file mode 100644 index 0000000000..d8c786de80 --- /dev/null +++ b/src/frontend/platform/src/test/systemDepartmentsTenantMount.test.tsx @@ -0,0 +1,184 @@ +import { useEffect, type ReactNode } from "react"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import Departments from "@/pages/SystemPage/components/Departments"; +import { + getDepartmentChildrenApi, + getDepartmentPathTreeApi, +} from "@/controllers/API/department"; +import { showApiError } from "@/controllers/request"; +import type { DepartmentTreeNode } from "@/types/api/department"; +import type { LazyDepartmentTree } from "@/components/bs-comp/department/useLazyDepartmentTree"; + +vi.mock("@/contexts/locationContext", async () => { + const { createContext } = await import("react"); + return { locationContext: createContext({ appConfig: { multiTenantEnabled: true } }) }; +}); +vi.mock("@/contexts/userContext", async () => { + const { createContext } = await import("react"); + return { userContext: createContext({ user: { role: "admin", is_global_super: true } }) }; +}); +vi.mock("@/controllers/API/department", () => ({ + getDepartmentChildrenApi: vi.fn(), + getDepartmentPathTreeApi: vi.fn(), + searchDepartmentsApi: vi.fn(), +})); +vi.mock("@/controllers/request", () => ({ showApiError: vi.fn() })); +vi.mock("@/pages/DepartmentPage/components/CreateDepartmentDialog", () => ({ + CreateDepartmentDialog: () => null, +})); +vi.mock("@/pages/DepartmentPage/components/OrganizationSearchPanel", () => ({ + OrganizationSearchPanel: ({ children }: { children: ReactNode }) => children, +})); + +// Keep the real lazy-tree controller so cached and expanded branches participate +// in the success callback. Only replace its visual presentation. +vi.mock("@/components/bs-comp/department", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + LazyDepartmentTree: ({ controller, onSelect }: { + controller: LazyDepartmentTree; + onSelect: (node: DepartmentTreeNode) => void; + }) => ( +
+ {[1, 95, 96].map((id) => { + const node = controller.getNode(id); + return node && ( +
+ + +
+ ); + })} +
+ ), + }; +}); + +const state = vi.hoisted(() => ({ + mounted: false, + rootUnavailable: false, + empty: false, + memberReads: vi.fn(), +})); +vi.mock("@/pages/DepartmentPage/components/MemberTable", () => ({ + MemberTable: ({ deptId, membersRefreshSignal, toolbarActions }: { + deptId: string; + membersRefreshSignal: number; + toolbarActions: ReactNode; + }) => { + useEffect(() => { + state.memberReads(deptId, state.mounted); + }, [deptId, membersRefreshSignal]); + return
{deptId}{toolbarActions}
; + }, +})); +vi.mock("@/pages/DepartmentPage/components/DepartmentSettingsDialog", () => ({ + DepartmentSettingsDialog: ({ dept, onMarkAsTenant }: { + dept: DepartmentTreeNode; + onMarkAsTenant: (id: number, name: string) => void; + }) => , +})); +vi.mock("@/pages/DepartmentPage/components/MountTenantDialog", () => ({ + MountTenantDialog: ({ onMounted, onClose }: { onMounted: () => void; onClose: () => void }) => ( +
+ + +
+ ), +})); + +function department(id: number, parentId: number | null, hasChildren: boolean): DepartmentTreeNode { + return { + id, dept_id: `BS@${id}`, name: `Department ${id}`, parent_id: parentId, + path: id === 1 ? "/1/" : id === 95 ? "/1/95/" : "/1/95/96/", + sort_order: 0, source: "local", status: "active", is_tenant_root: false, + mounted_tenant_id: null, has_children: hasChildren, children: [], + }; +} +const root = department(1, null, true); +const child = department(95, 1, true); +const descendant = department(96, 95, true); + +async function openMountDialog() { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + // A previously opened archived view must not retain the now out-of-scope branch. + queryClient.setQueryData(["dept:true", "children", 95], [descendant]); + render(); + fireEvent.click(await screen.findByRole("button", { name: "expand 95" })); + fireEvent.click(await screen.findByRole("button", { name: "expand 96" })); + await waitFor(() => expect(getDepartmentChildrenApi).toHaveBeenCalledWith(96, false)); + fireEvent.click(screen.getByRole("button", { name: "select 95" })); + await waitFor(() => expect(screen.getByTestId("members")).toHaveTextContent("BS@95")); + fireEvent.click(screen.getByRole("button", { name: "bs:department.settings" })); + fireEvent.click(screen.getByRole("button", { name: "mark tenant" })); + return queryClient; +} + +describe("System department tenant mount refresh", () => { + beforeEach(() => { + vi.clearAllMocks(); + state.mounted = false; + state.rootUnavailable = false; + state.empty = false; + vi.mocked(getDepartmentChildrenApi).mockImplementation(async (parentId) => { + if (state.mounted && (parentId === 95 || parentId === 96)) { + throw new Error("21009: outside Root directory"); + } + if (state.mounted && state.rootUnavailable) throw new Error("directory unavailable"); + if (state.mounted && state.empty) return []; + if (parentId == null) return [root]; + if (parentId === 1) return state.mounted ? [] : [child]; + if (parentId === 95) return [descendant]; + return []; + }); + vi.mocked(getDepartmentPathTreeApi).mockRejectedValue(new Error("21009: stale selection")); + }); + + it("reloads the Root view without reading the mounted department or its descendants", async () => { + const queryClient = await openMountDialog(); + vi.mocked(getDepartmentChildrenApi).mockClear(); + fireEvent.click(screen.getByRole("button", { name: "mount success" })); + + await waitFor(() => expect(screen.getByTestId("members")).toHaveTextContent("BS@1")); + await waitFor(() => expect(getDepartmentChildrenApi).toHaveBeenCalledWith(1, false)); + expect(getDepartmentChildrenApi).toHaveBeenCalledWith(null, false); + expect(getDepartmentChildrenApi).not.toHaveBeenCalledWith(95, false); + expect(getDepartmentChildrenApi).not.toHaveBeenCalledWith(96, false); + expect(getDepartmentPathTreeApi).not.toHaveBeenCalled(); + expect(state.memberReads).not.toHaveBeenCalledWith("BS@95", true); + expect(screen.queryByRole("button", { name: "select 95" })).not.toBeInTheDocument(); + expect(queryClient.getQueryData(["dept:true", "children", 95])).toBeUndefined(); + expect(showApiError).not.toHaveBeenCalled(); + }); + + it("keeps the current department when mounting is cancelled", async () => { + await openMountDialog(); + vi.mocked(getDepartmentChildrenApi).mockClear(); + fireEvent.click(screen.getByRole("button", { name: "cancel mount" })); + expect(screen.getByTestId("members")).toHaveTextContent("BS@95"); + expect(getDepartmentChildrenApi).not.toHaveBeenCalled(); + expect(showApiError).not.toHaveBeenCalled(); + }); + + it("clears the stale selection when the refreshed directory is empty", async () => { + await openMountDialog(); + state.empty = true; + fireEvent.click(screen.getByRole("button", { name: "mount success" })); + await screen.findByText("bs:department.selectDept"); + expect(screen.queryByTestId("members")).not.toBeInTheDocument(); + expect(getDepartmentPathTreeApi).not.toHaveBeenCalled(); + expect(showApiError).not.toHaveBeenCalled(); + }); + + it("surfaces a real directory refresh failure without restoring stale department data", async () => { + await openMountDialog(); + state.rootUnavailable = true; + fireEvent.click(screen.getByRole("button", { name: "mount success" })); + await waitFor(() => expect(showApiError).toHaveBeenCalledWith(new Error("directory unavailable"))); + expect(screen.queryByTestId("members")).not.toBeInTheDocument(); + expect(getDepartmentPathTreeApi).not.toHaveBeenCalled(); + }); +}); From ecc39676683ef26741aeb832dd380fa3d90ff8f3 Mon Sep 17 00:00:00 2001 From: codesstar <825323057@qq.com> Date: Tue, 17 Nov 2026 17:11:41 +0800 Subject: [PATCH 2/8] fix(F016): name the provider in the base model picker Relays often carry the same model name (two "deepseek-v4.1-flash" from different providers), and the base model picker listed only the name, so an administrator could not tell which one they were choosing. Each option now reads "model (provider)", which also shows in the trigger once chosen. --- .../platform/public/locales/en-US/bs.json | 1 + .../platform/public/locales/ja/bs.json | 1 + .../platform/public/locales/zh-Hans/bs.json | 1 + .../manage/dsh/BaseModelPicker.test.tsx | 23 +++++++++++++++---- .../ModelPage/manage/dsh/BaseModelPicker.tsx | 8 ++++--- 5 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/frontend/platform/public/locales/en-US/bs.json b/src/frontend/platform/public/locales/en-US/bs.json index df6648f7ad..fcef2071cd 100644 --- a/src/frontend/platform/public/locales/en-US/bs.json +++ b/src/frontend/platform/public/locales/en-US/bs.json @@ -4515,6 +4515,7 @@ "baseModel": "Base model", "baseModelHelp": "The model whose credit ratio is 1.00x. It only affects the ratio shown, not what is charged.", "baseModelDefault": "Daily chat default model", + "baseModelOption": "{{model}} ({{provider}})", "baseUnavailable": "The base model is unavailable (deleted, offline, unpriced or free), so credit ratios are hidden.", "settings": "Credit conversion", "settingsHelp": "Set how much one credit is worth. Changes apply to calls that start afterwards.", diff --git a/src/frontend/platform/public/locales/ja/bs.json b/src/frontend/platform/public/locales/ja/bs.json index 4d3689adf4..83d52c4a50 100644 --- a/src/frontend/platform/public/locales/ja/bs.json +++ b/src/frontend/platform/public/locales/ja/bs.json @@ -4460,6 +4460,7 @@ "baseModel": "基準モデル", "baseModelHelp": "クレジット倍率が 1.00x になるモデルです。倍率の表示だけに影響し、消費量には影響しません。", "baseModelDefault": "日常チャットの既定モデル", + "baseModelOption": "{{model}}({{provider}})", "baseUnavailable": "基準モデルが利用できない(削除・オフライン・価格なし・無料)ため、クレジット倍率を表示していません。", "settings": "クレジット換算", "settingsHelp": "1 クレジットの金額を設定します。変更はその後に開始する呼び出しから適用されます。", diff --git a/src/frontend/platform/public/locales/zh-Hans/bs.json b/src/frontend/platform/public/locales/zh-Hans/bs.json index 8cd497f8f4..155473118e 100644 --- a/src/frontend/platform/public/locales/zh-Hans/bs.json +++ b/src/frontend/platform/public/locales/zh-Hans/bs.json @@ -4460,6 +4460,7 @@ "baseModel": "基准模型", "baseModelHelp": "积分倍率为 1.00x 的模型,只影响倍率显示,不影响扣费。", "baseModelDefault": "日常对话默认模型", + "baseModelOption": "{{model}}({{provider}})", "baseUnavailable": "基准模型不可用(已删除、已下线、没有价格或免费),暂不显示积分倍率。", "settings": "积分换算", "settingsHelp": "设置 1 积分对应多少钱。修改只影响之后开始的调用。", diff --git a/src/frontend/platform/src/pages/ModelPage/manage/dsh/BaseModelPicker.test.tsx b/src/frontend/platform/src/pages/ModelPage/manage/dsh/BaseModelPicker.test.tsx index 1dd3b2ea1a..da8e869982 100644 --- a/src/frontend/platform/src/pages/ModelPage/manage/dsh/BaseModelPicker.test.tsx +++ b/src/frontend/platform/src/pages/ModelPage/manage/dsh/BaseModelPicker.test.tsx @@ -5,7 +5,11 @@ import { } from '@/controllers/API/modelPricing' import { BaseModelPicker } from './BaseModelPicker' -vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) })) +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (key: string, args?: Record) => key === 'dsh.pricing.baseModelOption' ? `${args?.model} (${args?.provider})` : key, + }), +})) vi.mock('@/controllers/API/modelPricing', () => ({ getCreditSettings: vi.fn(), saveCreditSettings: vi.fn(), @@ -18,7 +22,7 @@ const SAVED: CreditSettings = { const row = (model_id: number, hint: ModelPricingRow['hint'], missing = false): ModelPricingRow => ({ model_id, pricing: null, effective: null, edited: false, missing, hint, }) -const models = [{ id: 46, label: 'Chat default' }, { id: 47, label: 'Local model' }] +const models = [{ id: 46, label: 'Chat default', provider: 'DeepSeek' }, { id: 47, label: 'Local model', provider: 'Ollama' }] beforeEach(() => { vi.resetAllMocks() @@ -31,7 +35,7 @@ it('saves the chosen base model with the loaded version', async () => { render() await waitFor(() => expect(getCreditSettings).toHaveBeenCalled()) expect(screen.queryByText('dsh.pricing.baseUnavailable')).toBeNull() - await selectOption('dsh.pricing.baseModel', 'Local model') + await selectOption('dsh.pricing.baseModel', 'Local model (Ollama)') await waitFor(() => expect(saveCreditSettings).toHaveBeenCalledWith(expect.objectContaining({ version: 3, base_model_id: 47 }))) expect(await screen.findByLabelText('dsh.pricing.saved')).toBeInTheDocument() }) @@ -46,6 +50,17 @@ it('shows a conflict without changing the selection', async () => { vi.mocked(saveCreditSettings).mockRejectedValue({ status_code: 26130 }) render() await waitFor(() => expect(getCreditSettings).toHaveBeenCalled()) - await selectOption('dsh.pricing.baseModel', 'Local model') + await selectOption('dsh.pricing.baseModel', 'Local model (Ollama)') expect(await screen.findByRole('alert')).toHaveTextContent('dsh.pricing.conflict') }) + +it('tells same-named models apart by their provider', async () => { + const relays = [ + { id: 935, label: 'deepseek-v4.1-flash', provider: 'Qwen' }, + { id: 1143, label: 'deepseek-v4.1-flash', provider: 'Bailian relay' }, + ] + render() + await waitFor(() => expect(getCreditSettings).toHaveBeenCalled()) + await selectOption('dsh.pricing.baseModel', 'deepseek-v4.1-flash (Bailian relay)') + await waitFor(() => expect(saveCreditSettings).toHaveBeenCalledWith(expect.objectContaining({ base_model_id: 1143 }))) +}) diff --git a/src/frontend/platform/src/pages/ModelPage/manage/dsh/BaseModelPicker.tsx b/src/frontend/platform/src/pages/ModelPage/manage/dsh/BaseModelPicker.tsx index 188b346561..9d530738dd 100644 --- a/src/frontend/platform/src/pages/ModelPage/manage/dsh/BaseModelPicker.tsx +++ b/src/frontend/platform/src/pages/ModelPage/manage/dsh/BaseModelPicker.tsx @@ -10,7 +10,7 @@ import { creditPricingErrorKey, useCreditSettings } from './useCreditPricing' const DEFAULT_BASE = 'default' interface BaseModelPickerProps { - models: { id: number; label: string }[] + models: { id: number; label: string; provider: string }[] rows?: Map } @@ -47,13 +47,15 @@ export function BaseModelPicker({ models, rows }: BaseModelPickerProps) { return
{t('dsh.pricing.baseModel')} -