Updated the notification system to utilize the `tm` function for template resolution, ensuring that placeholders like `{name}` and `{role}` remain intact for proper rendering. This change improves the display of workspace and role information in login and tenant switch notifications, allowing for better localization and visual consistency across the application. Adjustments were made in `App.vue`, `Login.vue`, and related utility functions to accommodate the new template handling.
The login-success and tenant-switch toasts previously showed the
workspace name and role inline as bracketed plain text, which read
flat and made the two key data points hard to scan at a glance.
Render them through a shared `renderWorkspaceNotifyContent` helper
that produces a NotifyPlugin VNode with:
* a neutral rounded chip for the workspace name (with a generic
workspace icon), and
* a role-coloured chip for the role (with the existing per-role icon
from useRoleLabel), so owner / admin / contributor / viewer each
get a distinct visual identity that matches the role badges used
elsewhere in the product.
The i18n templates lose the surrounding 「」 / "" / «» quote marks
because the chip itself now provides the visual delineation; double
emphasis looked off. Translators control the surrounding wording via
`{name}` and `{role}` placeholders and the renderer splits on those
markers to interleave plain text and chips in the original order.
The PendingTenantSwitchToast payload (sessionStorage-stashed for the
hard-reload survival trick) grows a `roleEnum` field so the post-
reload toast can colour the chip — without that, the switch toast
would fall back to a neutral chip while the login toast got the
colour treatment.
Note on icon resolution: the chip renderer imports TDesign's `Icon`
component directly rather than referencing it by string tag in `h()`
— Vue's render function does not auto-resolve component names the
way templates do, so `h('t-icon', ...)` would silently render an
unknown HTML element.
Replace the plain "Login successful" toast with a TDesign Notify card
that surfaces the workspace the user just landed in and their role
there, so users immediately see which space they're working in —
especially useful now that login can drop them into a remembered
non-home tenant.
A small shared helper (utils/loginNotify.ts) handles both the password
login path (views/auth/Login.vue) and the OIDC callback path
(App.vue handleGlobalOIDCCallback), so the two flows stay consistent.
Role label goes through the same useRoleLabel composable used by the
rest of the role-aware UI, so locale + future role-name tweaks live in
one place. The membership lookup falls back gracefully (no role line)
when the active tenant isn't in the response's memberships list — e.g.
the auto-setup path that synthesises a single owner row.
The legacy auth.loginSuccess key is left in place; nothing else
references it, so a future cleanup PR can drop it safely.
Until now a fresh login (new device, expired refresh token, cleared
browser) always dropped the user into their home tenant, even if they
spend most of their time in a peer workspace. The session-local
X-Tenant-ID override in localStorage gave a "same browser sticky"
effect, but never crossed devices or new sessions.
This adds a small server-side preference, `users.preferences.
last_active_tenant_id`, persisted in the existing jsonb column (no
new migration), and threads it through:
* Backend
* `UserPreferences` gains `LastActiveTenantID *uint64` with sentinel
semantics (`*0` from the PATCH endpoint = clear preference).
* `resolveLoginTenantID` validates the stored id (tenant still
exists + active membership, or CanAccessAllTenants) and falls
back to home on any failure, best-effort clearing the stale
preference so subsequent logins don't pay for it again.
* `Login` and `LoginWithOIDC` resolve once and use the result for
both the JWT `tenant_id` claim and the returned `active_tenant`,
keeping the two in sync. `RefreshToken` rides through
`GenerateTokens` so refresh rotations also land the user back in
their preferred tenant instead of bouncing to home.
* `UpdateUserPreferences` learns to merge the new key.
* `PUT /auth/me/preferences` accepts the new field.
* Frontend
* `Login.vue` now writes the user's HOME tenant id into
`user.tenant_id` (matching the field's documented semantics) and
expresses any active-vs-home divergence via `setSelectedTenant`,
so `useHomeTenant` and the "current"/"home" badges stay correct
after the backend honours a remembered preference. `App.vue`'s
OIDC sync does the same reconciliation.
* `TenantSelector`, `UserMenu` and the post-tenant-create handlers
fire `persistLastActiveTenantPreference` after every successful
user-initiated switch (switching to home sends `0` to clear).
The call is raced against the existing reload-grace window so
most writes finish before the page tears down; lost writes are
recoverable on the next switch.
No new UI. Users will simply notice that, after re-logging in on
another device, they land back in the workspace they were last
using rather than always in their home tenant.
Note: `make docs` is unrelated-broken on `main` (audit_log.go
references `errors.AppError` which swag can't resolve), so the
Swagger artifacts under docs/ are intentionally not regenerated
in this PR. The handler code is the source of truth.
Wrap the role icon in a small colored circular chip and reuse the same
chip inline inside the role tags in the members and invitations
tables, so the permission-matrix popover, the members grid and the
invitations grid all share the same visual language for each role.
The chip color is keyed by role, making role recognition faster at a
glance without depending on the tag's surrounding text.
Replace the lightweight "switch success" message with a richer
NotifyPlugin notification that reports the new workspace name and the
user's role in it. Because the post-switch flow does a hard reload,
the notification is stashed in sessionStorage before navigation and
consumed by App.vue on the next mount, so the toast actually appears
on the destination page with its full 6s duration instead of being
torn down a frame after it is shown.
For the cross-tenant superuser path (TenantSelector), the role line is
omitted when the user has no membership row in the target tenant,
avoiding a misleading empty/raw role value. Role labels are formatted
through the shared useRoleLabel composable so any future role text
change still lives in one place.
i18n keys updated across zh-CN, en-US, ko-KR, ru-RU.
Replace the default t-dropdown on knowledge document cards with a
custom t-popup-based list that matches the existing card-more popup
styling (rounded corners, blur, dark mode). Selected entries show a
brand-colored check icon.
Also fix the empty placeholder issue: when a document has no tag,
render a dashed "+ category" affordance only for users with edit
permission, instead of an empty tag chip. A "clear category" action
appears at the bottom of the popup only when a tag is already set,
avoiding ambiguity with user-defined tags named the same as the
generic "uncategorized" label.
Adds the knowledgeBase.tagClearAction i18n key in zh-CN, en-US,
ko-KR and ru-RU.
Updated the tenant switch logic to consistently redirect users to the platform's knowledge base list after a tenant switch, simplifying the navigation experience. Removed the previous handling of tenant-scoped routes, ensuring a more predictable behavior during tenant transitions. This change enhances user experience by avoiding potential empty states on reload.
Refs: #1303
Enhanced localization files for English, Korean, Russian, and Chinese by adding the "Shared by me" label to improve clarity in shared resource sections. This update ensures a more intuitive user experience when navigating shared content across different languages.
Refs: #1303
Enhanced English, Korean, Russian, and Chinese localization files by adding new section labels such as "Built-in," "Created by me," and "Other members" to improve user understanding. Adjusted existing labels for better clarity and consistency across languages. This update ensures a more intuitive user experience in navigating shared and personal resources.
Refs: #1303
Refactored the pinning mechanism for knowledge bases to be user-specific, allowing any user with read access to pin knowledge bases independently. This change includes the introduction of a new `user_kb_pins` table to manage pin states, replacing the previous tenant-wide pinning system. Updated relevant API endpoints and service logic to support this new functionality, ensuring that the UI reflects the user's personal pin status.
Additionally, adjusted the knowledge base listing to sort by user-specific pin status, enhancing the user experience by prioritizing pinned items.
Refs: #1303
Refactored the assignment of enableMemoryOverride in the sendMsg function to remove explicit type declaration, enhancing code clarity. This change maintains the existing functionality while streamlining the code structure.
Updated the memory management logic to utilize a server-side per-user preference for enabling memory. The `enable_memory` field is now conditionally set based on user preferences, allowing for better control in both normal and embedded contexts. Adjusted relevant API handlers and request structures to support this change, ensuring backward compatibility with existing clients.
Refs: #1303
Added functionality for managing user preferences, including the ability to update preferences via a new API endpoint. The preferences are now stored server-side, allowing for synchronization across devices. Updated relevant components to handle user preferences, including the UserMenu and settings views. Enhanced internationalization support for error messages related to preference updates.
Introduced a new QuickNav menu item for 'members' in the UserMenu component, allowing users with the appropriate role to access member-related functionalities. Updated the role alignment for QuickNav entries to ensure consistency with the Settings component. This enhancement improves navigation for users based on their permissions.
Refs: #1303
Updated the tenant information API to allow editing of both name and description fields, improving user experience in managing tenant details. Introduced a new GlobalInvitationBell component to display pending invitations in the UI, ensuring users can easily access their invitations without navigating away from their current context. Additionally, updated internationalization files to support new description-related messages.
Refs: #1303
Refactored the Input-field.vue component to enhance the clarity and maintainability of computed properties related to selected items. Improved the logic for handling agent configurations and user-selected files, ensuring a more streamlined approach to displaying knowledge bases and files. Additionally, adjusted the handling of disabled agents to ensure proper fallback selection when necessary.
Refs: #1303
Introduced a new optional field, creator_name, in both CustomAgent and KnowledgeBase types to allow the front end to display the creator's name. This enhancement enables better differentiation between resources created by the current user and those created by other members of the same tenant. Updated relevant API handlers to populate this field during list operations, ensuring accurate representation in the UI. Additionally, modified the ResourceOriginBadge component to utilize the creator_name for improved context in resource listings.
Refs: #1303
Consolidated the template structure in GlobalCommandPalette.vue to enhance code clarity and maintainability. Adjusted the layout of various elements for better alignment without altering existing functionality. This refactor aims to improve the overall readability of the component for future development.
Refs: #1303
Added functionality for managing pending invitations, including a polling mechanism to update the invitation count in real-time. Introduced a new dialog component for users to view and respond to their invitations without navigating away from their current context. Updated API endpoints for fetching and managing invitations, and enhanced the user interface with relevant internationalization support.
Refs: #1303
Introduced a new "leave workspace" feature with corresponding titles, descriptions, and buttons in English, Korean, Russian, and Chinese. This enhancement improves user experience and clarity in workspace management, allowing users to easily understand the implications of leaving a workspace.
Refs: #1303
Modified chat titles in multiple languages to enhance user engagement. Introduced a new "leave workspace" feature with corresponding titles, descriptions, and buttons in English, Korean, Russian, and Chinese, improving user experience and clarity in workspace management.
Refs: #1303
Implemented a new function to clear tenant-specific data from localStorage when a user switches tenants. This prevents issues with stale data being used in the new tenant context, which could lead to backend errors. The function is called during the tenant selection process to ensure a clean state for the new tenant.
Refs: #1303
Modified padding values in menu.vue and UserMenu.vue to enhance the visual consistency of the components. Reduced padding in various elements and adjusted avatar sizes for a more cohesive design. These changes aim to improve the overall user interface without altering functionality.
Refs: #1303
Introduced a new API client for managing user favorites, allowing users to list, add, and remove starred resources. Enhanced the sidebar to display favorites and recents, improving user navigation. Updated internationalization files to include relevant labels and tooltips for the new features across multiple languages.
Refs: #1303
Consolidated and formatted the template structure in ListSpaceSidebar.vue to enhance code clarity and maintainability. Adjusted the layout of various elements for better alignment without altering existing functionality. This refactor aims to improve the overall readability of the component for future development.
Refs: #1303
Updated the CreateTenantDialog component to improve the header layout by adding an icon and title for better visual clarity. Introduced new CSS styles for the header to enhance the overall user experience. Additionally, adjusted font sizes in UserMenu.vue for consistency across the application.
Refs: #1303
Consolidated template elements in menu.vue to enhance code clarity and maintainability. Adjusted formatting for better alignment and readability without altering existing functionality. This refactor aims to streamline the component's structure for future development.
Refs: #1303
Refactored the CreateTenantDialog component to enhance the user experience by improving the layout and adding a subtitle for clarity. Updated the internationalization files to reflect changes in terminology from "tenant" to "workspace" across multiple languages, ensuring consistency in user messaging. This includes adjustments to prompts and labels related to workspace creation.
Refs: #1303
Added a new configuration option to limit the number of tenants a non-superuser can create via self-service. Introduced a new error type for handling cases where users exceed this limit, returning a 429 status code. Updated the tenant creation and update handlers to enforce this limit and provide appropriate feedback to users. Additionally, refactored the tenant update request structure to ensure only mutable fields are allowed.
Refs: #1303
Added a new API endpoint for creating tenants, allowing any logged-in user to create their own workspace. The backend automatically assigns the creator as the Owner of the new tenant. A new CreateTenantDialog component was introduced in the frontend, enabling users to input the workspace name and an optional description. Internationalization files were updated to include relevant messages for this feature across multiple languages.
Refs: #1303
Refactored the UserMenu.vue component by consolidating template elements and removing unnecessary line breaks. This change enhances the overall readability of the code while maintaining the existing functionality of the user menu.
No functional changes were made; the focus was solely on code clarity.
Refs: #1303
Updated the inline editing input in TenantInfo.vue to ensure proper event handling by consolidating the input attributes. This change enhances the user experience during tenant name editing by maintaining consistent functionality for saving and canceling edits.
Refs: #1303
Implemented a new API endpoint for updating tenant names, allowing owners to edit tenant information directly within the UI. The frontend now supports inline editing with success and error notifications. Additionally, internationalization files have been updated to include relevant messages for the new functionality across English, Korean, Russian, and Chinese languages, ensuring a consistent user experience.
Refs: #1303
Updated internationalization files for English, Korean, Russian, and Chinese to include new messages related to editing tenant names and updating tenant information. This includes prompts for user actions such as saving or canceling changes, as well as success and failure notifications. The changes ensure a consistent user experience across all supported languages regarding tenant management functionalities.
Refs: #1303
Updated the organization membership model to operate at the tenant level, aligning with Plan 3. This change introduces new interfaces and modifies existing ones to accommodate tenant-centric operations, including the `InviteMemberRequest` and `TenantInviteCandidate`. The search functionality for inviting members has been updated to reflect this shift, allowing for tenant-based searches instead of user-based. Additionally, internationalization files have been updated to ensure consistent messaging across languages regarding tenant membership and roles.
Refs: #1303
Enhanced internationalization support by adding RBAC-related messages across multiple language files. These messages inform users about the necessary tenant admin role for actions such as creating, joining, and managing shared spaces. Updated English, Korean, Russian, and Chinese translations to ensure consistent user experience regarding role-based access control.
Refs: #1303
Plan 3 (#1303) lifted Org membership from per-user to per-tenant, and
40fdb978 pinned the org's owner tenant in DB as organizations.owner_tenant_id.
The OrganizationSettingsModal members list, however, still decided
"which row is the owner" by comparing member.user_id against
orgInfo.owner_id. After Plan 3 the members list is keyed on tenant_id,
so the user-id check is structurally wrong: the representative user of
the owner tenant happens to be the owner today, but if that user is
moved to another tenant — or a different user of the owner tenant
becomes the representative — the modal would either lose the "(owner)"
tag, or re-tag a non-owner row, and would offer the role-select /
remove-button affordances on what is in fact the owner tenant row.
This change:
- Adds OwnerTenantID to OrganizationResponse and populates it in
toOrgResponse from the persisted column. IsOwner now compares the
caller's current tenant against owner_tenant_id (with a user-id
fallback for legacy rows where owner_tenant_id == 0).
- Adds owner_tenant_id to the frontend Organization type and a small
isOwnerMember(member) helper in OrganizationSettingsModal, which
tenant-matches by default and falls back to user-id only on
pre-000046 rows. The role <select>, role tag suffix, and the
delete button on member rows now all use the helper.
The "is-me" CSS class and the me-tag in the member name still match
on user_id — that one really is a per-user marker ("this row's user is
me, the signed-in user").
Before this change, the `organization_members` table keyed on user_id —
joining an org as a Viewer in tenant T meant only that one user got
visibility on shared KBs/agents, while the rest of T (including its
Owner) saw nothing. The mismatch surfaced as confusing UX bugs:
"my colleague shared this with us, why can't I see it?"
This change replaces `organization_members` with
`organization_tenant_members`. Membership and Org-RBAC role now key on
(org_id, tenant_id); `representative_user_id` stays as a display-only
label of the user who first brought the tenant in.
Permission resolution gains a 3-D cap so tenant-RBAC stays honest under
cross-tenant sharing:
effective = min(share.Permission, tenant_org_role, tenant_role_cap)
where tenant_role_cap pins tenant Viewers to OrgRoleViewer regardless
of the org-level grant. A Viewer in their own tenant cannot edit a
shared KB even if the org granted Editor — preserves the
"Viewer = read-only everywhere" promise.
Migration 000045 backfills `organization_tenant_members` from the old
table by collapsing each (org, tenant) group to its max role, then
renames the old table to `organization_members_pre_plan3` for safe
rollback. Sqlite mirror (Lite mode) is fresh-bootstrap: the init
schema replaces the old table directly.
Routes: member-management URLs change from `:user_id` to `:tenant_id`.
Org create / join / leave now require Admin+ in the caller's tenant —
joining an Org affects everyone in T, so the decision can't sit with
a Viewer.
Frontend: OrganizationSettingsModal + store update to address members
by tenant_id.
- Updated the logic in selectedAgent computed property to prioritize shared agents when a source tenant is set, ensuring correct agent resolution across tenants.
- Adjusted hasAgentConfig and currentAgentConfig computed properties to handle shared agent configurations properly, preventing conflicts with local built-in agents.
- Added comments for clarity on the handling of shared agents and built-in agents to enhance maintainability.
- Updated visibility conditions for various UI elements based on user roles, ensuring that only users with appropriate permissions (Admin, Contributor, or KB creator) can access certain actions.
- Introduced computed properties to manage permissions for sharing knowledge bases, managing data sources, and executing graph extraction.
- Adjusted the AgentList and KnowledgeBase components to reflect these changes, improving user experience by preventing unauthorized actions from being displayed.
- Ensured that the backend routes are aligned with the updated frontend role checks, enhancing security and clarity in user interactions.
Polish the role-aware UI surfaces wired up in #1303 so role / tenant
context is discoverable from the main shell rather than buried in a
hover-only switcher or the settings drawer.
UserMenu sidebar trigger:
- Replace username + email with `tenant name / username · role-icon
role-name` so the active tenant + current role are always visible at
the bottom of the sidebar; long usernames elide before the role label.
- Single-tenant users keep the old username + email layout.
UserMenu dropdown:
- Promote the tenant switcher to a clickable header row at the top of
the dropdown (tenant name + swap icon, role caption underneath).
- Drop the standalone "Switch tenant" submenu entry — the header row
hosts the same hover panel.
- Switcher panel rows now lead the role label with a role icon
(owner / admin / contributor / viewer) and surface the home tenant
via a small home dot on the avatar instead of a separate badge, so
the right-edge "current" badge column lines up across rows.
Settings:
- Add SECTION_MIN_ROLE so settings nav entries are gated by the same
role matrix the backend enforces (chathistory + ollama + websearch +
vectorstore + parser + storage + mcp → admin; api → owner; rest →
viewer). UserMenu quickNav uses the same map.
- Render a role-denied empty state when a user deep-links into a
section their role can't reach.
- Split account info (id / username / email / created_at) out of the
owner-only API Info page into a new viewer-accessible UserProfile
section.
Composable:
- New useRoleLabel composable centralises role → label and role → icon
mapping (consumed by UserMenu trigger / dropdown / switcher panel).
- useHomeTenant derives the home tenant id from `user.tenant_id` (the
immutable signup-time field), not `tenant.id` which now reflects the
active tenant after a switch.
Lists:
- KnowledgeBaseList / AgentList default the sidebar selection to "all"
for viewers (who typically own nothing) so the empty "Mine" state no
longer hides the shared content they actually have access to;
contributor+ keeps "Mine" as the default.
i18n:
- Tenant role labels: 拥有者/贡献者/查看者 → 所有者/编辑/访客 (all four
locales updated, plus new userProfile / roleDenied / homeBadge keys).
The org-vs-tenant scope question raised during review is intentionally
out of scope here — that needs an RFC before any UI/backend changes.
Recent searches were persisted under a single global localStorage
key (weknora_cmdk_recent), so:
- Multiple users sharing the same browser saw each other's
queries.
- Switching tenants inside the same session also leaked queries
across tenants.
Keys are now scoped as 'weknora_cmdk_recent:<userId>:<tenantId>'
with 'anon' / 'none' fallbacks for the pre-login window. A watch
on (user.id, effectiveTenantId) reloads from the right namespace
on login / logout / tenant switch. The auth store is resolved
lazily inside actions / watcher (not at setup-time) to dodge any
pinia init-order surprises — same pattern stores/menu.ts already
uses.
Old global key entries become orphans (~100 bytes); no migration
since that data is the leak we're fixing.
Switching the active tenant triggers window.location.reload() to
re-key every cached store / open SSE stream / in-flight request.
The catch: when the user is currently sitting on a route whose URL
embeds a tenant-scoped resource id, the new tenant lands on a
404/403 and the user sees a blank screen.
Three risky route shapes today:
/platform/knowledge-bases/:kbId
/platform/knowledge-bases/:kbId/creatChat
/platform/chat/:chatid
Add a tiny tenantSwitch utility (navigateAfterTenantSwitch) that
matches the current path against this list and redirects to
/platform/knowledge-bases — the platform default landing, always
renderable regardless of role. Anything else (settings, agent
list, KB list, etc.) continues to reload its current path because
those views handle empty/forbidden data gracefully.
Both tenant-switch call sites (TenantSelector and UserMenu) use
the helper so the matrix lives in one place; future tenant-scoped
routes only need to add a regex to the list.
Several mutation entry points stayed visible to users who lacked the
backend-required role, so Viewers (and non-creator Contributors) hit
403 on click instead of seeing the disabled state. Surgical fixes,
all matching the existing backend matrix:
- KnowledgeBaseList: gate the entire 3-dot popup (both the 'all'
and 'mine' tabs) behind canManageKBCard. Pin/unpin used to be
unguarded; settings/delete were per-item gated but the trigger
still showed. Now non-managers don't see the popup at all.
- AgentList: the popup trigger now requires at least one menu item
to be visible (edit OR copy OR disable OR delete), via a compound
v-if on the popup itself. Disable/enable on own custom agents
and shared agents both gain a hasRole('admin') guard to match
POST /shared-agents/disabled, which writes a tenant-level
preference and is Admin-gated.
- AgentEditorModal: new readOnly prop hides the '确定' (save)
button and replaces 'Cancel' with 'Close'. AgentList passes
readOnly when the user can't manage the agent (built-in agents
and others' custom agents for Viewers). Form-input disabling is
intentionally NOT wired here yet — the modal has 3000+ lines of
inputs and the only mutation surface that 403s is the save
button. Hiding it removes the broken path without rewiring the
whole form.
- doc-content: generated-question delete button gated by a new
canEditKB prop driven by KnowledgeBase.vue's existing canEdit
computed (KB creator OR Admin OR org-share-edit). Defaults to
Admin-only when the prop is missing — fail-closed since the
backend matrix is now stricter (see follow-up commit).
The server still enforces the same matrix on every mutation; these
gates only stop the user from staring at a 'failed' toast.
The Tenant.ConversationConfig field was marked deprecated when
CustomAgent (builtin-quick-answer) replaced the per-tenant defaults
path, but the JSONB column, GET/PUT KV handlers, write helpers and
read fall-throughs all stayed wired. This had two concrete failure
modes:
- Input-field.vue silently PUT-ed per-user model picks back into
/tenants/kv/conversation-config, which requires Admin+ — Viewers
and Contributors got a 403 every time they switched chat models.
- The same write also overwrote the tenant-shared default for every
other user, turning a per-user UX into a per-tenant footgun.
Remove the field, the struct, the validate helper, the PUT case and
the two dead Summary helpers in session/helpers.go. KnowledgeSearch
loses its tenant-conversation fallback (one chunk-tool reader); the
global config + hardcoded defaults still cover it. session_agent_qa
already required agents to declare their own rerank_model_id, so no
behaviour change there.
Frontend follows:
- Input-field.vue: per-user 'last selected chat model' moves to
localStorage, no API call.
- AgentEditorModal: defaults for builtin-quick-answer creation now
come from prompt-templates (system/context/rewrite/fallback) and
retrieval-config (top_k / threshold), the two endpoints that
actually own those settings now.
- AgentSettings.vue: orphan settings page with no router/import
referencing it; deleted.
- api/system: getConversationConfig / updateConversationConfig and
the ConversationConfig interface go away.
Net: 137 insertions, 2761 deletions.
The settings sidebar grew to 13 entries — flat scroll made related
settings (e.g. model + parser + storage) hard to find. Group them by
intent (basic / AI / data / workspace / system) with section titles
above each cluster, mirroring how popular SaaS settings pages are
organised. Behaviour and routing unchanged.
The previous PR removed the
"selectedTenantId === weknora_tenant.id → skip header" short-circuit
from the axios interceptor, but the same copy-pasted logic lived in
three more places that bypass axios:
- `api/chat/streame.ts` — `fetchEventSource` for the streaming chat
endpoint. Without this fix the chat reply would 404 with
"流式连接失败:HTTP 404" on the first message after switching to
a non-home tenant: the SSE call landed on the home tenant where
the freshly-created session did not exist.
- `api/initialization/index.ts` — native `fetch` for multimodal
test (FormData) requests. Misroutes the test to the home tenant.
- `utils/security.ts` — `getProtectedFileRequestHeaders` used by the
Markdown image proxy. Authenticated file fetches landed on the
home tenant, breaking image rendering after a tenant switch.
All three now mirror the simplified rule: if `weknora_selected_tenant_id`
is set, attach `X-Tenant-ID` unconditionally. The server's
`IsTenantAccessible` already accepts a header pointing at the user's
home tenant, so always attaching is safe.
Same root cause as the axios fix: any code path that writes the
active tenant into `weknora_tenant` (UserMenu's `loadUserInfo`, OIDC
sync, router hydrate) made the two values equal, after which these
non-axios paths silently dropped the header and re-routed to home.
When an Owner of tenant A invited user B as a Viewer, B could log in,
switch the active tenant from B's home to A via the user menu, and
still see every write button — Create KB, Upload Document, Edit/Delete
agent — because the role-gate plumbing on the client was wired to the
wrong tenant. The server's RBAC enforcement (PR 2 / PR 5) still blocked
the actual mutations with 403, so no data leaked, but the UI presented
authority the user did not have, which is a confusing and embarrassing
defect.
Five distinct root causes, all on the client / server boundary:
1. `currentTenantRole` (frontend/src/stores/auth.ts) read
`tenant.value.id` — the user's *home* tenant — instead of the active
tenant id. After switching to A, the helper still returned B's home
role (Owner), so every `hasRole(...)` gate in the codebase silently
short-circuited. Fix: read `selectedTenantId` first, fall back to
`tenant.id`.
2. `setMemberships` was only called once, on /auth/login. Hard reloads
(which the tenant switcher triggers) re-ran `getCurrentUser()` via
`App.vue` and `router/index.ts`, but those callers discarded the
`memberships` field of the response, so the auth store kept the
login-time snapshot forever. Role changes between sessions stayed
invisible. Fix: extract memberships in both /auth/me consumers and
feed them into `setMemberships`.
3. `KnowledgeBase.vue`'s `isOwner` compared `kb.tenant_id` to the
active tenant id, so any KB inside the current tenant was treated
as "owned by the caller" — bypassing every role gate below. Fix:
compare against `kb.creator_id` (the field PR 5 introduced) and
require an actual creator match. `canEdit` / `canManage` now layer
`hasRole('admin')` on top so a non-creator with sufficient role can
still manage.
4. `KnowledgeBaseList.vue` and `AgentList.vue` rendered the per-card
more-menu (Settings, Delete, Edit) unconditionally. With the
ownership column from PR 5 this is straightforward to gate on the
client: Settings/Delete now require creator-match or `hasRole('admin')`
per the server's `OwnedKBOrAdmin` / `OwnedAgentOrAdmin` matrix.
5. The axios interceptor (frontend/src/utils/request.ts) had a
"selectedTenantId === defaultTenantId → don't attach X-Tenant-ID"
short-circuit. Any code that wrote the active tenant into
`weknora_tenant` (UserMenu's loadUserInfo, OIDC sync, router
hydrate) made the two values equal, after which the header silently
stopped attaching and subsequent navigation requests landed on the
home tenant. Fix: drop the short-circuit; always attach when
selectedTenantId is set.
Server-side, /auth/me read `user.TenantID` (the immutable home tenant
id stamped at signup) when fetching the tenant for the response, so
the `tenant` field always pointed at home even after the auth
middleware had already resolved an active tenant from X-Tenant-ID.
The frontend then re-keyed `authStore.tenant` to the home tenant on
every refresh, undoing the switch. Fix: read the active tenant id from
context (`types.TenantIDFromContext(ctx)`) and only fall back to
user.TenantID when context is unset.
The server-side enforcement was correct throughout — every fix here is
purely about not lying to the user with the rendered UI.