Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ui/src/api/types/system-role.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export type RoleType = (typeof ROLE_TYPE)[keyof typeof ROLE_TYPE]
export interface RoleInfo {
role_id: string
role_name: string
role_type?: RoleType
}

export interface RoleItem {
Expand Down
19 changes: 19 additions & 0 deletions ui/src/utils/workspace-selection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/** 工作空间选择。 */
import type { WorkspaceItem } from '@/api/types'
import { ROLE_TYPE } from '@/api/enums'

function hasWorkspaceManagerRole(workspace: WorkspaceItem) {
return workspace.role_info?.some(({ role_type }) => role_type === ROLE_TYPE.WORKSPACE_MANAGE) ?? false
}

/** 优先使用当前用户具有空间管理员角色的缓存工作空间,否则选择第一个可管理的工作空间。 */
export function getInitialWorkspaceId(cachedWorkspaceId: string | null, workspaceList?: WorkspaceItem[]): string {
if (cachedWorkspaceId) {
const cachedWorkspace = workspaceList?.find(({ id }) => id === cachedWorkspaceId)
if (cachedWorkspace && hasWorkspaceManagerRole(cachedWorkspace)) {
return cachedWorkspaceId
}
}

return workspaceList?.find((workspace) => workspace.id && hasWorkspaceManagerRole(workspace))?.id ?? 'default'
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall, the logic is sound and there are no obvious syntax/type errors. Potential issues and suggestions:

  1. Magic fallback 'default'

    • It may not be a real workspace ID. If no workspace is found, callers may receive an invalid ID.
    • Prefer a named constant, and consider returning null/undefined if the caller should handle “no workspace” explicitly.
    • If 'default' is guaranteed to exist, document that assumption.
  2. workspaceList may be undefined while loading

    • The function returns 'default' even when the list has not loaded yet. This can cause an incorrect initial workspace request.
    • Consider distinguishing “not loaded yet” from “no valid workspace found”.
  3. Cached ID validation

    • if (cachedWorkspaceId) accepts whitespace-only strings. If the value comes from storage, consider trimming/validating it first.
    • The parameter type could be string | null | undefined if callers may pass undefined.
  4. Predicate readability

    • workspace.id && hasWorkspaceManagerRole(workspace) works, but the predicate returns string | boolean.
    • Prefer Boolean(workspace.id) && hasWorkspaceManagerRole(workspace) or workspace.id !== '' && ... for clarity.
  5. Role check semantics

    • hasWorkspaceManagerRole only checks role_type. Confirm whether disabled/deleted workspaces or role status also need filtering.
    • Also confirm role_info represents the current user’s roles, not all users’ roles.
  6. Return type assumption

    • The function returns string, so WorkspaceItem.id must be a non-optional string. Verify the type definition.
  7. Minor optimization

    • The two find calls are O(n) each, but this is negligible for typical workspace lists. No change needed unless the list is very large.

Optional refactor:

const DEFAULT_WORKSPACE_ID = 'default'

export function getInitialWorkspaceId(
  cachedWorkspaceId: string | null | undefined,
  workspaceList?: WorkspaceItem[],
): string {
  const normalizedCachedId = cachedWorkspaceId?.trim()

  if (normalizedCachedId) {
    const cachedWorkspace = workspaceList?.find(({ id }) => id === normalizedCachedId)

    if (cachedWorkspace && hasWorkspaceManagerRole(cachedWorkspace)) {
      return cachedWorkspace.id
    }
  }

  return (
    workspaceList?.find(
      (workspace) => Boolean(workspace.id) && hasWorkspaceManagerRole(workspace),
    )?.id ?? DEFAULT_WORKSPACE_ID
  )
}

5 changes: 4 additions & 1 deletion ui/src/views/system/identity/groups/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ import { ADMIN_STORAGE_KEY } from '@/constants/storage-key'
import { useStore } from '@/stores'
import { MsgConfirm, MsgSuccess } from '@/utils/message'
import { getRoleName } from '@/utils/role-name'
import { getInitialWorkspaceId } from '@/utils/workspace-selection'
import perm from '@/permission/index.ts'
const { auth, user } = useStore()
const { t } = useI18n({ useScope: 'global' })

/* 选择工作空间列表 */
const selectedWorkspaceId = ref(localStorage.getItem(ADMIN_STORAGE_KEY.WORKSPACE_ID) || user.userInfo?.workspace_list?.[0]?.id || 'default')
const selectedWorkspaceId = ref(
getInitialWorkspaceId(localStorage.getItem(ADMIN_STORAGE_KEY.WORKSPACE_ID), user.userInfo?.workspace_list),
)
const workspaceOptions = ref<WorkspaceItem[]>([])
const loadingView = ref(false)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The change is reasonable—it centralizes workspace-ID initialization—but the main risk is the contract of getInitialWorkspaceId. I cannot fully validate it without seeing that helper, so verify the following.

Potential issues

  1. Fallback chain must be preserved
    The original logic was:

    storedId || firstWorkspaceId || 'default'

    Ensure getInitialWorkspaceId preserves exactly:

    • valid stored ID → stored ID
    • otherwise first workspace ID
    • otherwise 'default'

    If the helper can return undefined/null, selectedWorkspaceId may become invalid.

  2. String vs number ID comparison
    localStorage.getItem() always returns string | null, but workspace_list[].id may be a number. If the helper uses strict comparison:

    workspace.id === storedId

    a stored "1" will not match workspace ID 1. Normalize with String(workspace.id) === storedId, or define a consistent ID type.

  3. Premature validation when workspace list is not loaded
    At setup time, user.userInfo?.workspace_list may still be undefined. If the helper treats that as “empty list” and returns 'default', a valid stored workspace ID is discarded. The original code preserved the stored ID regardless of whether the list had loaded. Consider distinguishing:

    • workspaces == null → list not loaded, preserve stored ID if present
    • workspaces.length === 0 → loaded but empty, fall back to 'default'
  4. Empty-string stored value
    The original || treated '' as missing. If the helper uses ?? or only checks null, an empty string may be treated as a valid ID. Trim and treat empty string as missing.

  5. 'default' sentinel
    Ensure 'default' is accepted even if it is not present in workspace_list.

  6. Type safety of ref
    Check the inferred type of:

    const selectedWorkspaceId = ref(...)

    If the helper returns string | undefined, or if workspace IDs can be numbers, add an explicit type such as ref<string>(...) or a consistent WorkspaceId union.

  7. Reactivity / initialization timing
    This is a one-time initialization. If user.userInfo loads asynchronously after setup, selectedWorkspaceId will not automatically update. That was also true before, but the new helper may validate against an incomplete list. Make sure the helper does not incorrectly invalidate a stored ID before the list is available.

  8. localStorage access safety
    localStorage.getItem can throw in some environments. This was already present before, but if you are refactoring, consider a safe storage utility.

Suggested helper shape

export function getInitialWorkspaceId(
  storedId: string | null,
  workspaces?: WorkspaceItem[] | null,
): string {
  const stored = storedId?.trim()

  if (stored === 'default') return stored

  // List not loaded yet: preserve stored ID instead of falling back.
  if (workspaces == null) {
    return stored || 'default'
  }

  if (stored && workspaces.some(w => String(w.id) === stored)) {
    return stored
  }

  const firstId = workspaces[0]?.id
  return firstId != null ? String(firstId) : 'default'
}

If your workspace IDs are numbers and downstream APIs expect numbers, do not blindly convert everything to string; instead define and enforce a consistent WorkspaceId type.

Minor suggestions

  • Add tests for: valid stored ID, invalid stored ID, empty string, null, workspace_list undefined, empty workspace_list, numeric IDs, and 'default'.
  • If the project enforces import ordering, check the new import placement against lint rules.
  • Consider making the workspace-ID storage/parsing logic fully encapsulated so components do not call localStorage directly.

Overall, the diff is fine structurally; the critical review point is whether getInitialWorkspaceId correctly handles missing workspace data, type mismatches, and the 'default' fallback.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { RESOURCE_AUTHORIZATION_LABELS } from './constants'
import { ADMIN_STORAGE_KEY } from '@/constants/storage-key'
import { useStore } from '@/stores'
import { MsgSuccess } from '@/utils/message'
import { getInitialWorkspaceId } from '@/utils/workspace-selection'
import { perm } from '@/permission'

const { auth, user } = useStore()
Expand Down Expand Up @@ -53,7 +54,9 @@ const resourceTypeOptions = computed<OptionItem<ResourceAuthorizationType>[]>(()

/* 选择工作空间列表 */
const loadingView = ref(false)
const selectedWorkspaceId = ref(localStorage.getItem(ADMIN_STORAGE_KEY.WORKSPACE_ID) || user.userInfo?.workspace_list?.[0]?.id || 'default')
const selectedWorkspaceId = ref(
getInitialWorkspaceId(localStorage.getItem(ADMIN_STORAGE_KEY.WORKSPACE_ID), user.userInfo?.workspace_list),
)
const workspaceOptions = ref<WorkspaceItem[]>([])

function handleWorkspaceSelect(workspace: WorkspaceItem) {
Expand Down
73 changes: 73 additions & 0 deletions ui/tests/workspace-selection.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { test } from 'node:test'
import { compileFunction } from 'node:vm'
import ts from 'typescript'

function loadWorkspaceSelection() {
const { outputText } = ts.transpileModule(readFileSync(new URL('../src/utils/workspace-selection.ts', import.meta.url), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
})
const exports = {}
compileFunction(outputText, ['require', 'exports'])((id) => {
assert.equal(id, '@/api/enums')
return {
ROLE_TYPE: {
ADMIN: 'ADMIN',
USER: 'USER',
WORKSPACE_MANAGE: 'WORKSPACE_MANAGE',
},
}
}, exports)
return exports
}

const workspaceManagerRole = {
role_id: 'workspace-manager-role',
role_name: '空间管理员',
role_type: 'WORKSPACE_MANAGE',
}

const userRole = {
role_id: 'user-role',
role_name: '普通成员',
role_type: 'USER',
}

test('缓存工作空间包含空间管理员角色时沿用缓存 ID', () => {
const { getInitialWorkspaceId } = loadWorkspaceSelection()
const workspaces = [
{ id: 'workspace-a', name: '空间 A', role_info: [userRole] },
{ id: 'workspace-b', name: '空间 B', role_info: [workspaceManagerRole] },
]

assert.equal(getInitialWorkspaceId('workspace-b', workspaces), 'workspace-b')
})

test('缓存工作空间不是管理员空间时选择第一个管理员空间', () => {
const { getInitialWorkspaceId } = loadWorkspaceSelection()
const workspaces = [
{ id: 'workspace-a', name: '空间 A', role_info: [userRole] },
{ id: 'workspace-b', name: '空间 B', role_info: [workspaceManagerRole] },
]

assert.equal(getInitialWorkspaceId('workspace-a', workspaces), 'workspace-b')
})

test('缓存工作空间不在列表中时选择第一个管理员空间', () => {
const { getInitialWorkspaceId } = loadWorkspaceSelection()
const workspaces = [
{ id: 'workspace-a', name: '空间 A', role_info: [userRole] },
{ id: 'workspace-b', name: '空间 B', role_info: [userRole, workspaceManagerRole] },
]

assert.equal(getInitialWorkspaceId('missing-workspace', workspaces), 'workspace-b')
})

test('没有管理员空间时回退到 default', () => {
const { getInitialWorkspaceId } = loadWorkspaceSelection()
const workspaces = [{ id: 'workspace-a', name: '空间 A', role_info: [userRole] }]

assert.equal(getInitialWorkspaceId('workspace-a', workspaces), 'default')
assert.equal(getInitialWorkspaceId(null, undefined), 'default')
})

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's a review of the diff:

Potential Issues

  1. Fragile module stubbing via compileFunction + hard-coded assert.equal(id, ...)

    • The mock resolver asserts that every require() call receives exactly '@/api/enums'. If workspace-selection.ts ever imports anything else (even a built-in or an additional utility), all tests break with a confusing assertion failure inside the loader rather than at the actual test site.
    • Better: use a lookup map and throw a descriptive error for unknown ids:
      const modules = { '@/api/enums': { ROLE_TYPE: {...} } }
      compileFunction(outputText, ['require', 'exports'])((id) => {
        if (!modules[id]) throw new Error(`Unexpected require: ${id}`)
        return modules[id]
      }, exports)
  2. transpileModule doesn't type-check or resolve imports

    • It only transpiles syntax. Any type errors in workspace-selection.ts are silently ignored by tests. Fine for a runtime unit test, but be aware it won't catch TS mistakes. Consider running tsc --noEmit separately.
  3. Loader runs per-test, re-reading and transpiling the file each time

    • Minor perf issue (4 tests × readFileSync + transpile). Extract loadWorkspaceSelection() once at module scope, or cache the result:
      let cached
      function loadWorkspaceSelection() {
        return cached ??= (/* ...actual work... */)
      }
    • The unused .ts extension import path also means this relies on import.meta.url resolution—fine, but worth noting.
  4. Hard-coded Chinese strings in test(...) names — fine if project convention, but the role names (空间管理员) don't affect logic; keep only what's asserted.

  5. Magic value 'default' — the fallback ID is duplicated as a literal in tests. If workspace-selection.ts exports/references a constant (e.g. DEFAULT_WORKSPACE_ID), assert against that instead to avoid drift.

  6. Missing coverage cases

    • Empty array [].
    • Cached ID valid AND is admin space but appears after a non-admin admin-space earlier (ordering).
    • Workspace whose role_info is undefined / missing.
    • Multiple roles where WORKSPACE_MANAGE is not first in role_info (the third test partially covers, good).
    • Duplicate cached IDs.
    • The getInitialWorkspaceId(null, undefined) case is covered — good.
  7. role_type values duplicated between test fixtures and mock

    • The stub defines ROLE_TYPE, but fixtures use raw strings ('WORKSPACE_MANAGE', 'USER'). If source compares against ROLE_TYPE.X, using the same enum in fixtures would make the intent clearer and catch mismatches.
  8. Mock object shape

    • Returned exports starts as {}; if the compiled module assigns to module.exports directly (not just exports.foo), the destructure const { getInitialWorkspaceId } will be undefined. Currently works because the source presumably uses named exports, but it's brittle. Passing module isn't done here — confirm the source uses ESM-style named exports transpiled to exports.x = ....

Optimization Suggestions

  • Move loadWorkspaceSelection() to module top-level (or memoize) to transpile once.
  • Hoist shared fixtures (workspaceManagerRole, userRole, the workspace arrays) to reduce repetition.
  • Use t.before / node:test hooks if setup grows.
  • Consider testing against the real TS build output (compiled JS) instead of ad-hoc transpile+mock, which would remove the custom loader entirely.

Summary

Logic looks reasonable and the scenarios are sensible. Main risks: the over-strict single-module mock, re-transpiling per test, the duplicated 'default' literal, and slightly thin edge-case coverage. None are blockers, but addressing #1, #3, #5, and adding a couple of edge tests would improve resilience.

Loading