Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(favorites): implement user favorites and recents functionality

wizardchen8332a0dab669
diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts
index c2cda726f..9a7836934 100644
--- a/frontend/src/api/agent/index.ts
+++ b/frontend/src/api/agent/index.ts
@@ -135,8 +135,17 @@ export const BUILTIN_AGENT_AGENT_ID = BUILTIN_SMART_REASONING_ID;
// 获取智能体列表(包括内置智能体)
// disabled_own_agent_ids: 当前租户在对话下拉中停用的「我的」智能体 ID,仅影响本租户
-export function listAgents() {
- return get<{ data: CustomAgent[]; disabled_own_agent_ids?: string[] }>('/api/v1/agents');
+export function listAgents(params?: {
+ /**
+ * Optional creator filter; mirrors listKnowledgeBases. Built-in agents
+ * (is_builtin=true) are always returned regardless of this filter so
+ * the conversation dropdown never silently loses quick-answer /
+ * smart-reasoning when a user picks "Created by me".
+ */
+ creator?: 'all' | 'mine' | 'others';
+}) {
+ const qs = params?.creator && params.creator !== 'all' ? `?creator=${params.creator}` : '';
+ return get<{ data: CustomAgent[]; disabled_own_agent_ids?: string[] }>(`/api/v1/agents${qs}`);
}
// 获取智能体详情
diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts
index 61b6bb381..dfed05904 100644
--- a/frontend/src/api/knowledge-base/index.ts
+++ b/frontend/src/api/knowledge-base/index.ts
@@ -1,9 +1,21 @@
import { get, post, put, del, postUpload, getDown } from "../../utils/request";
// 知识库管理 API(列表、创建、获取、更新、删除、复制)
-export function listKnowledgeBases(params?: { agent_id?: string }) {
+export function listKnowledgeBases(params?: {
+ agent_id?: string;
+ /**
+ * Optional creator filter. Server-side semantics:
+ * - "mine" → only KBs whose creator_id matches the caller
+ * - "others" → only KBs created by someone else in this tenant
+ * - omitted/"all" → no filter
+ * KBs predating the RBAC backfill (creator_id="") never match
+ * mine/others — they fall out of both views by design.
+ */
+ creator?: 'all' | 'mine' | 'others';
+}) {
const query = new URLSearchParams();
if (params?.agent_id) query.set('agent_id', params.agent_id);
+ if (params?.creator && params.creator !== 'all') query.set('creator', params.creator);
const qs = query.toString();
return get(qs ? `/api/v1/knowledge-bases?${qs}` : '/api/v1/knowledge-bases');
}
diff --git a/frontend/src/api/user-favorites.ts b/frontend/src/api/user-favorites.ts
new file mode 100644
index 000000000..8de318e46
--- /dev/null
+++ b/frontend/src/api/user-favorites.ts
@@ -0,0 +1,34 @@
+// API client for per-user starred resources (DB-backed; see migration
+// 000047 and internal/handler/user_resource_favorite.go).
+//
+// The backend authoritatively scopes favorites to the active (user, tenant)
+// pair from the auth context — these helpers therefore never pass user_id
+// or tenant_id, and a tenant switch automatically points reads at the
+// right namespace.
+
+import { get, post, del } from '@/utils/request'
+
+export type FavoriteResourceType = 'kb' | 'agent'
+
+export interface FavoriteEntry {
+ user_id: string
+ tenant_id: number
+ resource_type: FavoriteResourceType
+ resource_id: string
+ /** ISO timestamp from the server (created_at column). */
+ created_at: string
+}
+
+export function listFavorites(type: FavoriteResourceType) {
+ return get<{ success: boolean; data: FavoriteEntry[] }>(
+ `/api/v1/user/favorites?type=${encodeURIComponent(type)}`
+ )
+}
+
+export function addFavorite(type: FavoriteResourceType, id: string) {
+ return post('/api/v1/user/favorites', { type, id })
+}
+
+export function removeFavorite(type: FavoriteResourceType, id: string) {
+ return del(`/api/v1/user/favorites/${encodeURIComponent(type)}/${encodeURIComponent(id)}`)
+}
diff --git a/frontend/src/components/ListSpaceSidebar.vue b/frontend/src/components/ListSpaceSidebar.vue
index 132c7481e..bffa8b3d6 100644
--- a/frontend/src/components/ListSpaceSidebar.vue
+++ b/frontend/src/components/ListSpaceSidebar.vue
@@ -11,19 +11,32 @@
<span class="icon-label">{{ $t('listSpaceSidebar.all') }}</span>
</div>
</t-tooltip>
- <t-tooltip :content="tooltipText($t('listSpaceSidebar.mine'), countMine)" placement="right" :show-arrow="false">
- <div class="icon-item-labeled" :class="{ active: selected === 'mine' }" @click="select('mine')">
- <t-icon name="user" size="16px" />
- <span class="icon-label">{{ $t('listSpaceSidebar.mine') }}</span>
+ <t-tooltip v-if="showFavorites" :content="tooltipText($t('listSpaceSidebar.favorites'), countFavorites)"
+ placement="right" :show-arrow="false">
+ <div class="icon-item-labeled" :class="{ active: selected === 'favorites' }" @click="select('favorites')">
+ <t-icon name="star" size="16px" />
+ <span class="icon-label">{{ $t('listSpaceSidebar.favorites') }}</span>
</div>
</t-tooltip>
- <t-tooltip v-if="!hideShared" :content="tooltipText($t('listSpaceSidebar.sharedToMe'), countShared)"
+ <t-tooltip v-if="showRecents" :content="tooltipText($t('listSpaceSidebar.recents'), countRecents)"
placement="right" :show-arrow="false">
- <div class="icon-item-labeled" :class="{ active: selected === 'shared' }" @click="select('shared')">
- <t-icon name="share" size="16px" />
- <span class="icon-label">{{ $t('listSpaceSidebar.sharedToMe') }}</span>
+ <div class="icon-item-labeled" :class="{ active: selected === 'recents' }" @click="select('recents')">
+ <t-icon name="history" size="16px" />
+ <span class="icon-label">{{ $t('listSpaceSidebar.recents') }}</span>
+ </div>
+ </t-tooltip>
+ <t-tooltip :content="tooltipText(workspaceLabel, countMine)" placement="right" :show-arrow="false">
+ <div class="icon-item-labeled workspace-item" :class="{ active: selected === 'mine' }"
+ @click="select('mine')">
+ <t-icon name="system-sum" size="16px" />
+ <span class="icon-label">{{ workspaceLabel }}</span>
</div>
</t-tooltip>
+ <!-- Shared spaces group: per-org/space entries only. We dropped
+ the aggregate "协作" / shared-with-me entry — its meaning
+ oscillated between "everything shared to me" and "things I
+ can edit", and either reading duplicated information already
+ visible on the per-space entries below. -->
<template v-if="organizationsWithCount.length">
<div class="icon-strip-divider" />
<t-tooltip v-for="org in organizationsWithCount" :key="org.id"
@@ -71,21 +84,32 @@
</div>
<template v-if="mode === 'resource'">
- <div class="sidebar-item" :class="{ active: selected === 'mine' }" @click="select('mine')">
+ <div v-if="showFavorites" class="sidebar-item" :class="{ active: selected === 'favorites' }"
+ @click="select('favorites')">
<div class="item-left">
- <t-icon name="user" class="item-icon" />
- <span class="item-label">{{ $t('listSpaceSidebar.mine') }}</span>
+ <t-icon name="star" class="item-icon" />
+ <span class="item-label">{{ $t('listSpaceSidebar.favorites') }}</span>
</div>
- <span v-if="countMine !== undefined" class="item-count">{{ countMine }}</span>
+ <span v-if="countFavorites > 0" class="item-count">{{ countFavorites }}</span>
+ </div>
+ <div v-if="showRecents" class="sidebar-item" :class="{ active: selected === 'recents' }"
+ @click="select('recents')">
+ <div class="item-left">
+ <t-icon name="history" class="item-icon" />
+ <span class="item-label">{{ $t('listSpaceSidebar.recents') }}</span>
+ </div>
+ <span v-if="countRecents > 0" class="item-count">{{ countRecents }}</span>
</div>
- <div v-if="!hideShared" class="sidebar-item" :class="{ active: selected === 'shared' }"
- @click="select('shared')">
+ <div v-if="(showFavorites || showRecents)" class="sidebar-divider" />
+ <div class="sidebar-item" :class="{ active: selected === 'mine' }" @click="select('mine')">
<div class="item-left">
- <t-icon name="share" class="item-icon" />
- <span class="item-label">{{ $t('listSpaceSidebar.sharedToMe') }}</span>
+ <t-icon name="system-sum" class="item-icon" />
+ <span class="item-label">{{ workspaceLabel }}</span>
</div>
- <span v-if="countShared !== undefined && countShared > 0" class="item-count">{{ countShared }}</span>
+ <span v-if="countMine !== undefined" class="item-count">{{ countMine }}</span>
</div>
+ <!-- Shared spaces group — per-org entries only; the aggregate
+ entry was removed (see collapsed strip for rationale). -->
<template v-if="organizationsWithCount.length">
<div class="sidebar-section">
<span class="section-title">{{ $t('listSpaceSidebar.spaces') }}</span>
@@ -128,6 +152,7 @@
<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
+import { useI18n } from 'vue-i18n'
import { Icon as TIcon } from 'tdesign-vue-next'
import SpaceAvatar from './SpaceAvatar.vue'
import { useOrganizationStore } from '@/stores/organization'
@@ -143,14 +168,31 @@ const props = withDefaults(
collapsedKey?: string
countAll?: number
countMine?: number
- countShared?: number
countByOrg?: Record<string, number>
countCreated?: number
countJoined?: number
hideAll?: boolean
- hideShared?: boolean
+ /** Favorites entry. Only meaningful in resource mode. */
+ countFavorites?: number
+ showFavorites?: boolean
+ /** Recents entry. Only meaningful in resource mode. */
+ countRecents?: number
+ showRecents?: boolean
}>(),
- { mode: 'resource', collapsedKey: 'sidebar-collapsed-list', countAll: undefined, countMine: undefined, countShared: undefined, countByOrg: () => ({}), countCreated: undefined, countJoined: undefined, hideAll: false, hideShared: false }
+ {
+ mode: 'resource',
+ collapsedKey: 'sidebar-collapsed-list',
+ countAll: undefined,
+ countMine: undefined,
+ countByOrg: () => ({}),
+ countCreated: undefined,
+ countJoined: undefined,
+ hideAll: false,
+ countFavorites: 0,
+ showFavorites: true,
+ countRecents: 0,
+ showRecents: true,
+ }
)
const storageKey = props.collapsedKey + '-expanded'
@@ -196,8 +238,12 @@ function tooltipText(name: string, count?: number): string {
return count !== undefined ? `${name} (${count})` : name
}
+// truncateLabel keeps the collapsed-strip label visually balanced (~44px
+// wide). 4 CJK chars fits; ASCII can stretch further. Callers that want
+// the full label should pass it as :title= on the same element for hover.
function truncateLabel(text: string, max = 4): string {
- return text.length > max ? text.slice(0, max) : text
+ if (!text) return ''
+ return text.length > max ? text.slice(0, max) + '…' : text
}
const emit = defineEmits<{
@@ -205,11 +251,21 @@ const emit = defineEmits<{
}>()
const orgStore = useOrganizationStore()
+const { t } = useI18n()
const selected = computed({
get: () => props.modelValue,
set: (v: string) => emit('update:modelValue', v)
})
+// workspaceLabel is the unified label for the tenant-owned bucket.
+// Earlier iterations rendered the active tenant's display name here, but
+// long names (e.g. "wizardlab Test Team") got truncated to unreadable
+// stubs ("wiza…") in the collapsed strip and competed visually with the
+// org/space entries below. A constant i18n label sidesteps both issues;
+// the tenant identity is already conveyed by the dedicated TenantSelector
+// in the global header, so we don't lose information.
+const workspaceLabel = computed(() => t('listSpaceSidebar.workspace'))
+
const organizations = computed(() => orgStore.organizations || [])
const organizationsWithCount = computed(() => {
@@ -346,10 +402,10 @@ onBeforeUnmount(() => {
}
.icon-label {
- font-size: 10px;
- line-height: 1.2;
+ font-size: 11px;
+ line-height: 1.25;
color: var(--td-text-color-secondary);
- max-width: 44px;
+ max-width: 52px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -357,6 +413,7 @@ onBeforeUnmount(() => {
transition: color 0.15s ease;
}
+
.icon-strip-divider {
width: 24px;
height: 1px;
@@ -478,6 +535,12 @@ onBeforeUnmount(() => {
}
}
+.sidebar-divider {
+ height: 1px;
+ margin: 6px 4px;
+ background: var(--td-component-stroke);
+}
+
.sidebar-section {
padding: 8px 6px 2px;
margin-top: 2px;
diff --git a/frontend/src/components/ResourceOriginBadge.vue b/frontend/src/components/ResourceOriginBadge.vue
new file mode 100644
index 000000000..0e52080ac
--- /dev/null
+++ b/frontend/src/components/ResourceOriginBadge.vue
@@ -0,0 +1,149 @@
+<template>
+ <span class="resource-origin-badge" :class="variantClass" :title="tooltipText">
+ <t-icon :name="iconName" size="12px" class="badge-icon" />
+ <span class="badge-text">{{ displayText }}</span>
+ </span>
+</template>
+
+<script setup lang="ts">
+import { computed } from 'vue'
+import { Icon as TIcon } from 'tdesign-vue-next'
+import { useI18n } from 'vue-i18n'
+import { useAuthStore } from '@/stores/auth'
+
+/**
+ * ResourceOriginBadge – a unified, compact label that explains *where* a
+ * KB or Agent comes from. Replaces the ad-hoc "我的" / "shared-by-me-badge"
+ * / org_name pills scattered across KnowledgeBaseList and AgentList. The
+ * variants below cover the four origin shapes the list views actually
+ * surface; future origins (e.g. "system" / "imported") should add a new
+ * variant rather than re-using one of these.
+ *
+ * Variants:
+ * - mine : created by the current user in the current tenant
+ * - tenant : owned by the current tenant but created by someone else
+ * - space : reached through a cross-tenant space (organization)
+ * - shared : cross-tenant share without a useful org name to show
+ *
+ * Pass `creatorName` to surface "by 张三" in the tooltip for the `tenant`
+ * variant; omit it for the `mine` / `space` / `shared` variants where the
+ * subject is implicit.
+ */
+const props = withDefaults(
+ defineProps<{
+ variant: 'mine' | 'tenant' | 'space' | 'shared'
+ /** Used in `space` variant — the organization (space) display name. */
+ spaceName?: string
+ /** Optional creator display name, surfaces in tooltip for `tenant` variant. */
+ creatorName?: string
+ /** Optional source tenant name, surfaces in tooltip for cross-tenant. */
+ sourceTenantName?: string
+ }>(),
+ { spaceName: '', creatorName: '', sourceTenantName: '' }
+)
+
+const { t } = useI18n()
+const authStore = useAuthStore()
+
+const iconName = computed(() => {
+ switch (props.variant) {
+ case 'mine':
+ return 'user'
+ case 'tenant':
+ return 'usergroup'
+ case 'space':
+ return 'building'
+ case 'shared':
+ return 'share'
+ default:
+ return 'usergroup'
+ }
+})
+
+const variantClass = computed(() => `origin-${props.variant}`)
+
+const displayText = computed(() => {
+ switch (props.variant) {
+ case 'mine':
+ return t('resourceOrigin.mine')
+ case 'tenant':
+ // Prefer the tenant name when known so the badge says where the
+ // resource lives, not a vague "tenant" label. Falls back to i18n.
+ return authStore.currentTenantName || t('resourceOrigin.tenant')
+ case 'space':
+ return props.spaceName || t('resourceOrigin.space')
+ case 'shared':
+ return props.sourceTenantName || t('resourceOrigin.shared')
+ default:
+ return ''
+ }
+})
+
+const tooltipText = computed(() => {
+ switch (props.variant) {
+ case 'mine':
+ return t('resourceOrigin.mineTooltip')
+ case 'tenant':
+ if (props.creatorName) {
+ return t('resourceOrigin.tenantTooltipWithCreator', { creator: props.creatorName })
+ }
+ return t('resourceOrigin.tenantTooltip')
+ case 'space':
+ if (props.sourceTenantName) {
+ return t('resourceOrigin.spaceTooltipWithTenant', {
+ space: props.spaceName,
+ tenant: props.sourceTenantName,
+ })
+ }
+ return t('resourceOrigin.spaceTooltip', { space: props.spaceName })
+ case 'shared':
+ return t('resourceOrigin.sharedTooltip')
+ default:
+ return ''
+ }
+})
+</script>
+
+<style scoped lang="less">
+.resource-origin-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ padding: 1px 6px;
+ border-radius: 8px;
+ font-size: 11px;
+ line-height: 1.4;
+ font-weight: 500;
+ max-width: 140px;
+
+ .badge-icon {
+ flex-shrink: 0;
+ }
+
+ .badge-text {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &.origin-mine {
+ color: var(--td-brand-color);
+ background: var(--td-success-color-light);
+ }
+
+ &.origin-tenant {
+ color: var(--td-text-color-secondary);
+ background: var(--td-bg-color-secondarycontainer);
+ }
+
+ &.origin-space {
+ color: var(--td-warning-color-7, #b86e02);
+ background: var(--td-warning-color-1, #fff7e6);
+ }
+
+ &.origin-shared {
+ color: var(--td-text-color-secondary);
+ background: var(--td-bg-color-secondarycontainer);
+ }
+}
+</style>
diff --git a/frontend/src/composables/useListUrlState.ts b/frontend/src/composables/useListUrlState.ts
new file mode 100644
index 000000000..c4cccd965
--- /dev/null
+++ b/frontend/src/composables/useListUrlState.ts
@@ -0,0 +1,111 @@
+// useListUrlState keeps a list view's filter state (sidebar scope, creator
+// filter, free-text query) reflected in the route's query string so the
+// URL is shareable, bookmarkable and survives a browser back/forward.
+//
+// Why a composable instead of inlining: KnowledgeBaseList and AgentList
+// share the same three filters and the same URL-encoding rules. Centralising
+// here means changing the schema (e.g. renaming `scope` -> `view`) is a
+// one-line change for both pages.
+//
+// Schema:
+// ?scope=<all|mine|shared|orgId>
+// ?creator=<all|mine|others>
+// ?q=<text>
+//
+// Defaults are omitted from the URL to keep it terse and to avoid producing
+// a no-op history entry on first mount. We use router.replace (not push)
+// for state changes so the back button still leaves the list view, rather
+// than cycling through filter changes the user didn't think of as
+// navigation.
+
+import { ref, watch, type Ref } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+
+export type CreatorFilter = 'all' | 'mine' | 'others'
+
+export interface ListUrlState {
+ scope: Ref<string>
+ creator: Ref<CreatorFilter>
+ query: Ref<string>
+}
+
+export interface ListUrlStateOptions {
+ /** Default scope when no `?scope=` is present. Usually role-derived. */
+ defaultScope: string
+ /** Default creator filter when no `?creator=` is present. */
+ defaultCreator?: CreatorFilter
+}
+
+export function useListUrlState(opts: ListUrlStateOptions): ListUrlState {
+ const route = useRoute()
+ const router = useRouter()
+
+ const initScope = typeof route.query.scope === 'string' && route.query.scope
+ ? route.query.scope
+ : opts.defaultScope
+
+ const initCreator: CreatorFilter =
+ route.query.creator === 'mine' || route.query.creator === 'others' || route.query.creator === 'all'
+ ? (route.query.creator as CreatorFilter)
+ : (opts.defaultCreator ?? 'all')
+
+ const initQuery = typeof route.query.q === 'string' ? route.query.q : ''
+
+ const scope = ref<string>(initScope)
+ const creator = ref<CreatorFilter>(initCreator)
+ const query = ref<string>(initQuery)
+
+ // Push URL when any filter changes. We diff against current route.query
+ // to avoid a redundant router.replace when nothing actually changed (the
+ // route guard would still fire and cause unnecessary watcher churn).
+ const sync = () => {
+ const next: Record<string, string> = { ...(route.query as Record<string, string>) }
+ if (scope.value && scope.value !== opts.defaultScope) {
+ next.scope = scope.value
+ } else {
+ delete next.scope
+ }
+ const cdef = opts.defaultCreator ?? 'all'
+ if (creator.value && creator.value !== cdef) {
+ next.creator = creator.value
+ } else {
+ delete next.creator
+ }
+ if (query.value) {
+ next.q = query.value
+ } else {
+ delete next.q
+ }
+ const changed =
+ next.scope !== route.query.scope ||
+ next.creator !== route.query.creator ||
+ next.q !== route.query.q
+ if (!changed) return
+ router.replace({ path: route.path, query: next }).catch(() => {
+ // navigation duplication errors are harmless here; vue-router throws
+ // when the user clicks the same scope twice in rapid succession.
+ })
+ }
+
+ watch([scope, creator, query], sync)
+
+ // When the route changes from elsewhere (e.g. user pastes a link or hits
+ // back), pull the new values back into our refs. Guards against re-emit
+ // by only updating when the parsed value differs.
+ watch(
+ () => route.query,
+ (q) => {
+ const ns = (typeof q.scope === 'string' && q.scope) ? q.scope : opts.defaultScope
+ const nc: CreatorFilter =
+ q.creator === 'mine' || q.creator === 'others' || q.creator === 'all'
+ ? (q.creator as CreatorFilter)
+ : (opts.defaultCreator ?? 'all')
+ const nq = typeof q.q === 'string' ? q.q : ''
+ if (scope.value !== ns) scope.value = ns
+ if (creator.value !== nc) creator.value = nc
+ if (query.value !== nq) query.value = nq
+ }
+ )
+
+ return { scope, creator, query }
+}
diff --git a/frontend/src/composables/useResourcePins.ts b/frontend/src/composables/useResourcePins.ts
new file mode 100644
index 000000000..1a2724a5b
--- /dev/null
+++ b/frontend/src/composables/useResourcePins.ts
@@ -0,0 +1,260 @@
+// useResourcePins – per-(user, tenant) favorites + per-user recents for
+// KBs and custom agents.
+//
+// Favorites are DB-backed (see migration 000047) so they sync across
+// devices and survive a logout. They are scoped per (user, tenant) on
+// the server, which means switching tenants automatically re-points the
+// reads — see `refresh()` and the tenant-change watcher inside the
+// composable.
+//
+// Recents stay in localStorage. They're a personal navigation aid, not a
+// shareable resource; round-tripping every card click through the
+// network would add latency for marginal value. If the product later
+// needs cross-device recents we can promote them to a server-side
+// audit-log derivation, which is a much smaller migration than starting
+// from scratch.
+
+import { ref, computed, watch, type ComputedRef, type Ref } from 'vue'
+import {
+ listFavorites,
+ addFavorite,
+ removeFavorite,
+ type FavoriteResourceType,
+} from '@/api/user-favorites'
+import { safeGetItem, safeSetItem, readUserId } from './preferenceStorage'
+import { useAuthStore } from '@/stores/auth'
+
+export type ResourceType = FavoriteResourceType
+
+export interface PinEntry {
+ type: ResourceType
+ id: string
+ /** Unix ms when the pin was created (favorite) or last accessed (recent). */
+ ts: number
+}
+
+const RECENTS_SUFFIX = 'resource_recents'
+const RECENTS_CAP = 30
+
+// Recents are scoped by (user, tenant) — same rationale as favorites. The
+// hydration step in the list views joins recent entries against the
+// current tenant's KB/Agent index, so a recent from tenant A would
+// silently drop out of the rendered list but still count in the sidebar
+// badge ("最近 (2)" but empty body). Keying the storage by tenant
+// prevents that mismatch entirely.
+//
+// `tenantSegmentForKey` returns "" when no tenant is resolvable (e.g.
+// during the very first render before auth state hydrates); the resulting
+// key is still per-user, so we never accidentally read another user's
+// recents. Once the tenant id resolves, the tenant watcher below bumps
+// the revision so views pick up the right namespace.
+function tenantSegmentForKey(): string {
+ try {
+ const authStore = useAuthStore()
+ const tid = authStore.effectiveTenantId
+ return tid ? `t${tid}_` : ''
+ } catch {
+ return ''
+ }
+}
+
+function recentsKey(): string {
+ return `WeKnora_${readUserId()}_${tenantSegmentForKey()}${RECENTS_SUFFIX}`
+}
+
+function readRecents(): PinEntry[] {
+ const raw = safeGetItem(recentsKey())
+ if (!raw) return []
+ try {
+ const parsed = JSON.parse(raw)
+ if (!Array.isArray(parsed)) return []
+ return parsed.filter(
+ (e: unknown): e is PinEntry =>
+ !!e &&
+ typeof (e as PinEntry).type === 'string' &&
+ ((e as PinEntry).type === 'kb' || (e as PinEntry).type === 'agent') &&
+ typeof (e as PinEntry).id === 'string' &&
+ typeof (e as PinEntry).ts === 'number'
+ )
+ } catch {
+ return []
+ }
+}
+
+function writeRecents(list: PinEntry[]): void {
+ safeSetItem(recentsKey(), JSON.stringify(list))
+}
+
+// Module-level shared state: a single source of truth for the whole tab
+// so all list views stay in sync after a star toggle, and so two list
+// views don't double-fetch the same data.
+const favoritesByType: Record<ResourceType, Ref<PinEntry[]>> = {
+ kb: ref<PinEntry[]>([]),
+ agent: ref<PinEntry[]>([]),
+}
+const loaded: Record<ResourceType, boolean> = { kb: false, agent: false }
+const inFlight: Record<ResourceType, Promise<void> | null> = { kb: null, agent: null }
+
+// recents revision counter — same bump-to-invalidate pattern as before.
+const recentsRevision = ref(0)
+function bumpRecents() {
+ recentsRevision.value++
+}
+
+if (typeof window !== 'undefined') {
+ // Cross-tab sync for recents (localStorage event); favorites changes from
+ // another tab are not propagated because the server is the source of
+ // truth and a manual refresh / next mutation will pull fresh state.
+ window.addEventListener('storage', (e) => {
+ if (e.key?.endsWith(`_${RECENTS_SUFFIX}`)) bumpRecents()
+ })
+}
+
+async function fetchFavorites(type: ResourceType): Promise<void> {
+ // Single-flight guard: list views mount in parallel and would otherwise
+ // each fire a request. Reuse the in-flight promise instead.
+ if (inFlight[type]) return inFlight[type]!
+ inFlight[type] = (async () => {
+ try {
+ const res = (await listFavorites(type)) as unknown as { success: boolean; data?: any[] }
+ const data = res?.data || []
+ favoritesByType[type].value = data.map((e: any) => ({
+ type: e.resource_type as ResourceType,
+ id: e.resource_id as string,
+ ts: e.created_at ? new Date(e.created_at).getTime() : Date.now(),
+ }))
+ loaded[type] = true
+ } catch (err) {
+ console.warn(`[useResourcePins] failed to load ${type} favorites:`, err)
+ favoritesByType[type].value = []
+ } finally {
+ inFlight[type] = null
+ }
+ })()
+ return inFlight[type]!
+}
+
+// Invalidate caches when the active tenant changes — favorites are
+// (user, tenant)-scoped on the server, so a tenant switch means the
+// currently loaded list belongs to the *previous* tenant. We trigger one
+// watcher at module load so any later switch refetches automatically.
+let tenantWatcherInstalled = false
+function installTenantWatcher(): void {
+ if (tenantWatcherInstalled) return
+ tenantWatcherInstalled = true
+ const authStore = useAuthStore()
+ watch(
+ () => authStore.effectiveTenantId,
+ () => {
+ loaded.kb = false
+ loaded.agent = false
+ favoritesByType.kb.value = []
+ favoritesByType.agent.value = []
+ // Eagerly refetch both types so any already-mounted list view sees
+ // fresh data without a manual refresh.
+ void fetchFavorites('kb')
+ void fetchFavorites('agent')
+ // Recents are keyed on the tenant id (see `recentsKey`); bump the
+ // revision so any active computed re-reads against the new key.
+ bumpRecents()
+ }
+ )
+}
+
+export interface UseResourcePinsResult {
+ favorites: ComputedRef<PinEntry[]>
+ recents: ComputedRef<PinEntry[]>
+ isFavorite: (type: ResourceType, id: string) => boolean
+ toggleFavorite: (type: ResourceType, id: string) => Promise<boolean>
+ touchRecent: (type: ResourceType, id: string) => void
+ removeRecent: (type: ResourceType, id: string) => void
+ /** Force a refetch (e.g. after a debug-y state mismatch). */
+ refresh: () => Promise<void>
+}
+
+export function useResourcePins(): UseResourcePinsResult {
+ installTenantWatcher()
+
+ // Lazy first load. Calling the composable always kicks off (or reuses)
+ // the in-flight fetch for both types; the templates render with empty
+ // arrays until data lands, which is fine because the counts default to
+ // 0 and no view depends on a synchronous read.
+ if (!loaded.kb) void fetchFavorites('kb')
+ if (!loaded.agent) void fetchFavorites('agent')
+
+ const favorites = computed<PinEntry[]>(() => {
+ // Merge both type lists and sort by ts desc.
+ return [...favoritesByType.kb.value, ...favoritesByType.agent.value].sort(
+ (a, b) => b.ts - a.ts
+ )
+ })
+
+ const recents = computed<PinEntry[]>(() => {
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const _ = recentsRevision.value
+ return readRecents().sort((a, b) => b.ts - a.ts)
+ })
+
+ const isFavorite = (type: ResourceType, id: string): boolean => {
+ return favoritesByType[type].value.some((e) => e.id === id)
+ }
+
+ const toggleFavorite = async (type: ResourceType, id: string): Promise<boolean> => {
+ const list = favoritesByType[type].value
+ const idx = list.findIndex((e) => e.id === id)
+ // Optimistic update first so the star animation feels instant; on
+ // network failure we roll back to the previous state. Errors are
+ // swallowed here (logged + rollback) because callers wire this to a
+ // click handler that can't surface a useful message — the rolled-back
+ // UI itself is the error indication.
+ if (idx >= 0) {
+ const removed = list[idx]
+ favoritesByType[type].value = list.filter((_, i) => i !== idx)
+ try {
+ await removeFavorite(type, id)
+ return false
+ } catch (err) {
+ favoritesByType[type].value = [removed, ...favoritesByType[type].value]
+ console.warn('[useResourcePins] removeFavorite failed; reverted:', err)
+ return true
+ }
+ }
+ const optimistic: PinEntry = { type, id, ts: Date.now() }
+ favoritesByType[type].value = [optimistic, ...list]
+ try {
+ await addFavorite(type, id)
+ return true
+ } catch (err) {
+ favoritesByType[type].value = favoritesByType[type].value.filter((e) => e.id !== id)
+ console.warn('[useResourcePins] addFavorite failed; reverted:', err)
+ return false
+ }
+ }
+
+ const touchRecent = (type: ResourceType, id: string): void => {
+ const list = readRecents()
+ const idx = list.findIndex((e) => e.type === type && e.id === id)
+ if (idx >= 0) list.splice(idx, 1)
+ list.unshift({ type, id, ts: Date.now() })
+ if (list.length > RECENTS_CAP) list.length = RECENTS_CAP
+ writeRecents(list)
+ bumpRecents()
+ }
+
+ const removeRecent = (type: ResourceType, id: string): void => {
+ const list = readRecents()
+ const next = list.filter((e) => !(e.type === type && e.id === id))
+ if (next.length !== list.length) {
+ writeRecents(next)
+ bumpRecents()
+ }
+ }
+
+ const refresh = async (): Promise<void> => {
+ loaded.kb = false
+ loaded.agent = false
+ await Promise.all([fetchFavorites('kb'), fetchFavorites('agent')])
+ }
+
+ return { favorites, recents, isFavorite, toggleFavorite, touchRecent, removeRecent, refresh }
+}
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 670510baf..25fb00175 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -43,9 +43,29 @@ export default {
listSpaceSidebar: {
title: 'Filter',
all: 'All',
+ workspace: 'Workspace',
mine: 'Mine',
- sharedToMe: 'Collaborative',
- spaces: 'Spaces'
+ spaces: 'Shared with me',
+ favorites: 'Starred',
+ recents: 'Recent'
+ },
+ listFilter: {
+ creator: 'Creator',
+ allCreators: 'All',
+ createdByMe: 'Created by me',
+ createdByOthers: 'Created by others'
+ },
+ resourceOrigin: {
+ mine: 'Mine',
+ mineTooltip: 'Created by you',
+ tenant: 'Workspace',
+ tenantTooltip: 'Created by another member of this workspace',
+ tenantTooltipWithCreator: 'Created by {creator}',
+ space: 'Space',
+ spaceTooltip: 'Shared via space "{space}"',
+ spaceTooltipWithTenant: 'Shared via space "{space}" · from {tenant}',
+ shared: 'External',
+ sharedTooltip: 'Accessed from an external tenant via a shared space'
},
knowledgeBase: {
title: 'Knowledge Base',
@@ -410,6 +430,10 @@ export default {
description: 'Click the button in the top right to create your first agent',
sharedTitle: 'No shared agents yet',
sharedDescription: 'You can join a space or ask others to share agents with you',
+ favoritesTitle: 'No favorites yet',
+ favoritesDescription: 'Star an agent from its card to add it here',
+ recentsTitle: 'Nothing here yet',
+ recentsDescription: 'Agents you recently used will show up here',
},
detail: {
title: 'Agent Details',
@@ -636,11 +660,11 @@ export default {
tenantInfo: 'Tenant Info',
apiInfo: 'API Info',
navGroups: {
- basic: 'Basic',
- ai: 'AI Capabilities',
- data: 'Data & Engines',
- workspace: 'Workspace & Access',
- system: 'System Info',
+ workspaceAccount: 'Workspace',
+ modelsRuntime: 'Models',
+ integrations: 'Extensions',
+ knowledgeInfra: 'Engines',
+ platform: 'Platform',
},
roleDenied: {
title: 'Insufficient permissions',
@@ -1570,7 +1594,11 @@ export default {
title: 'No knowledge bases yet',
description: 'Click "Create Knowledge Base" in the top-right corner to add your first one.',
sharedTitle: 'No shared knowledge bases',
- sharedDescription: 'You can join a shared space or request others to share knowledge bases with you'
+ sharedDescription: 'You can join a shared space or request others to share knowledge bases with you',
+ favoritesTitle: 'No favorites yet',
+ favoritesDescription: 'Star a knowledge base from its card to add it here',
+ recentsTitle: 'Nothing here yet',
+ recentsDescription: 'Knowledge bases you recently opened will show up here',
},
delete: {
confirmTitle: 'Delete Confirmation',
@@ -3283,7 +3311,7 @@ export default {
},
organization: {
title: 'Shared Spaces',
- subtitle: 'Create or join shared spaces to share knowledge bases and agents with your team',
+ subtitle: 'Create or join shared spaces so multiple workspaces can collaborate and share knowledge bases and agents',
createOrg: 'Create Space',
createOrgShort: 'New',
joinOrg: 'Join Space',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 3bec2e1ae..77d0e3b48 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -43,9 +43,29 @@ export default {
listSpaceSidebar: {
title: "필터",
all: "모두",
+ workspace: "워크스페이스",
mine: "소유",
- sharedToMe: "공유",
- spaces: "스페이스",
+ spaces: "나와 공유됨",
+ favorites: "즐겨찾기",
+ recents: "최근",
+ },
+ listFilter: {
+ creator: "생성자",
+ allCreators: "전체",
+ createdByMe: "내가 생성",
+ createdByOthers: "다른 사람 생성",
+ },
+ resourceOrigin: {
+ mine: "내 생성",
+ mineTooltip: "현재 사용자가 생성",
+ tenant: "워크스페이스",
+ tenantTooltip: "워크스페이스의 다른 멤버가 생성",
+ tenantTooltipWithCreator: "{creator}님이 생성",
+ space: "스페이스",
+ spaceTooltip: "공유 스페이스 「{space}」에서 가져옴",
+ spaceTooltipWithTenant: "공유 스페이스 「{space}」 · 출처 {tenant}",
+ shared: "외부 공유",
+ sharedTooltip: "공유 스페이스를 통해 외부 테넌트에서 접근",
},
knowledgeBase: {
title: "지식베이스",
@@ -512,11 +532,11 @@ export default {
tenantInfo: "테넌트 정보",
apiInfo: "API 정보",
navGroups: {
- basic: "기본",
- ai: "AI 기능",
- data: "데이터 및 엔진",
- workspace: "공간 및 권한",
- system: "시스템 정보",
+ workspaceAccount: "공간 및 계정",
+ modelsRuntime: "모델",
+ integrations: "확장",
+ knowledgeInfra: "엔진",
+ platform: "플랫폼",
},
roleDenied: {
title: "권한 없음",
@@ -1303,6 +1323,10 @@ export default {
sharedTitle: "아직 공유 에이전트가 없습니다.",
sharedDescription:
"스페이스에 참여하거나 다른 사람에게 에이전트를 공유하도록 요청할 수 있습니다.",
+ favoritesTitle: "즐겨찾기 없음",
+ favoritesDescription: "카드의 별표 아이콘을 눌러 즐겨찾기에 추가하세요",
+ recentsTitle: "최근 항목 없음",
+ recentsDescription: "최근에 사용한 에이전트가 여기에 표시됩니다",
},
detail: {
title: "에이전트 세부정보",
@@ -2224,6 +2248,10 @@ export default {
sharedTitle: "아직 공유 지식베이스가 없습니다.",
sharedDescription:
"공유 스페이스에 참여하거나 다른 사람에게 지식베이스를 공유해 달라고 요청할 수 있습니다.",
+ favoritesTitle: "즐겨찾기 없음",
+ favoritesDescription: "카드의 별표 아이콘을 눌러 즐겨찾기에 추가하세요",
+ recentsTitle: "최근 항목 없음",
+ recentsDescription: "최근에 연 지식베이스가 여기에 표시됩니다",
},
delete: {
confirmTitle: "삭제 확인",
@@ -3326,7 +3354,7 @@ export default {
organization: {
title: "공유 스페이스",
subtitle:
- "지식베이스와 에이전트를 팀 구성원과 공유하기 위해 공유 스페이스를 만들거나 참여하세요.",
+ "공유 스페이스를 만들거나 참여하여 여러 스페이스가 함께 협업하고 지식베이스와 에이전트를 공유하세요.",
createOrg: "스페이스 생성",
createOrgShort: "새로 만들기",
joinOrg: "스페이스에 참여하기",
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 63d4540ec..dc2877263 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -521,7 +521,11 @@ export default {
title: 'No Custom Agents',
description: 'Click the button in the top right to create your first agent',
sharedTitle: 'No shared agents yet',
- sharedDescription: 'You can join a space or ask others to share agents with you'
+ sharedDescription: 'You can join a space or ask others to share agents with you',
+ favoritesTitle: 'No favorites yet',
+ favoritesDescription: 'Star an agent from its card to add it here',
+ recentsTitle: 'Nothing here yet',
+ recentsDescription: 'Agents you recently used will show up here'
},
detail: {
title: 'Agent Details',
@@ -621,11 +625,11 @@ export default {
tenantInfo: 'Информация о арендаторе',
apiInfo: 'Информация API',
navGroups: {
- basic: 'Основное',
- ai: 'AI-возможности',
- data: 'Данные и движки',
- workspace: 'Пространство и доступ',
- system: 'Сведения о системе',
+ workspaceAccount: 'Пространство и аккаунт',
+ modelsRuntime: 'Модели',
+ integrations: 'Расширения',
+ knowledgeInfra: 'Движки',
+ platform: 'Платформа',
},
roleDenied: {
title: 'Недостаточно прав',
@@ -1821,7 +1825,11 @@ export default {
title: 'Базы знаний отсутствуют',
description: 'Нажмите «Создать базу знаний» в левом быстром действии, чтобы добавить первую базу.',
sharedTitle: 'No shared knowledge bases',
- sharedDescription: 'You can join a shared space or request others to share knowledge bases with you'
+ sharedDescription: 'You can join a shared space or request others to share knowledge bases with you',
+ favoritesTitle: 'No favorites yet',
+ favoritesDescription: 'Star a knowledge base from its card to add it here',
+ recentsTitle: 'Nothing here yet',
+ recentsDescription: 'Knowledge bases you recently opened will show up here'
},
delete: {
confirmTitle: 'Подтверждение удаления',
@@ -3794,9 +3802,29 @@ export default {
listSpaceSidebar: {
title: 'Фильтр',
all: 'Все',
+ workspace: 'Рабочая область',
+ mine: 'Мои',
+ spaces: 'Доступно мне',
+ favorites: 'Избранное',
+ recents: 'Недавние'
+ },
+ listFilter: {
+ creator: 'Автор',
+ allCreators: 'Все',
+ createdByMe: 'Созданные мной',
+ createdByOthers: 'Созданные другими'
+ },
+ resourceOrigin: {
mine: 'Мои',
- sharedToMe: 'Совместные',
- spaces: 'Пространства'
+ mineTooltip: 'Создано вами',
+ tenant: 'Рабочая область',
+ tenantTooltip: 'Создано другим участником рабочей области',
+ tenantTooltipWithCreator: 'Создано {creator}',
+ space: 'Пространство',
+ spaceTooltip: 'Через пространство "{space}"',
+ spaceTooltipWithTenant: 'Через пространство "{space}" · от {tenant}',
+ shared: 'Внешнее',
+ sharedTooltip: 'Доступ из внешнего арендатора через общее пространство'
},
promptTemplate: {
noTemplates: 'No templates available',
@@ -3809,7 +3837,7 @@ export default {
},
organization: {
title: 'Shared Spaces',
- subtitle: 'Create or join shared spaces to share knowledge bases and agents with your team',
+ subtitle: 'Create or join shared spaces so multiple workspaces can collaborate and share knowledge bases and agents',
createOrg: 'Create Space',
createOrgShort: 'New',
joinOrg: 'Join Space',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index ba8f11142..359cb7805 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -43,9 +43,29 @@ export default {
listSpaceSidebar: {
title: "筛选",
all: "全部",
+ workspace: "本空间",
mine: "我的",
- sharedToMe: "协作",
- spaces: "空间",
+ spaces: "共享给我",
+ favorites: "收藏",
+ recents: "最近",
+ },
+ listFilter: {
+ creator: "创建者",
+ allCreators: "全部",
+ createdByMe: "我创建的",
+ createdByOthers: "他人创建的",
+ },
+ resourceOrigin: {
+ mine: "我创建",
+ mineTooltip: "由当前用户创建",
+ tenant: "本空间",
+ tenantTooltip: "本空间其他成员创建",
+ tenantTooltipWithCreator: "由 {creator} 创建",
+ space: "共享空间",
+ spaceTooltip: "来自共享空间「{space}」",
+ spaceTooltipWithTenant: "来自共享空间「{space}」· 源空间 {tenant}",
+ shared: "外部共享",
+ sharedTooltip: "通过共享空间从其他空间访问",
},
knowledgeBase: {
title: "知识库",
@@ -506,18 +526,18 @@ export default {
storageEngine: "存储引擎",
mcpService: "MCP服务",
systemSettings: "系统设置",
- tenantInfo: "租户信息",
+ tenantInfo: "空间信息",
apiInfo: "API信息",
navGroups: {
- basic: "基础",
- ai: "AI 能力",
- data: "数据与引擎",
- workspace: "空间与权限",
- system: "系统信息",
+ workspaceAccount: "空间与账户",
+ modelsRuntime: "模型",
+ integrations: "扩展",
+ knowledgeInfra: "引擎",
+ platform: "平台",
},
roleDenied: {
title: "权限不足",
- desc: "你当前的角色无权访问此设置项。请联系本租户的管理员获取所需角色。",
+ desc: "你当前的角色无权访问此设置项。请联系本空间的管理员获取所需角色。",
}, weknoraCloud: {
title: "WeKnora Cloud",
description: "配置 WeKnora Cloud 的 APPID 和 APPSECRET 凭证。凭证用于模型服务和文档解析引擎。",
@@ -1128,10 +1148,10 @@ export default {
noAccount: "还没有账户?",
backToLogin: "返回登录",
registerNow: "立即注册",
- registerSuccess: "注册成功!系统已为您创建专属租户,请登录",
+ registerSuccess: "注册成功!系统已为您创建专属空间,请登录",
registerFailed: "注册失败",
subtitle: "基于大模型的文档理解和语义搜索框架",
- registerSubtitle: "注册后系统将为您创建专属租户",
+ registerSubtitle: "注册后系统将为您创建专属空间",
emailPlaceholder: "输入邮箱地址",
passwordPlaceholder: "输入密码(8-32个字符,包含字母和数字)",
confirmPasswordPlaceholder: "再次输入密码",
@@ -1157,7 +1177,7 @@ export default {
authStore: {
errors: {
parseUserFailed: "解析用户信息失败",
- parseTenantFailed: "解析租户信息失败",
+ parseTenantFailed: "解析空间信息失败",
parseKnowledgeBasesFailed: "解析知识库列表失败",
parseCurrentKnowledgeBaseFailed: "解析当前知识库失败",
},
@@ -1296,6 +1316,10 @@ export default {
description: "点击右上角按钮创建您的第一个智能体",
sharedTitle: "暂无共享智能体",
sharedDescription: "您可以加入空间或请求他人将智能体共享给您",
+ favoritesTitle: "暂无收藏",
+ favoritesDescription: "在智能体卡片右上角点击星标即可收藏",
+ recentsTitle: "暂无最近访问",
+ recentsDescription: "最近使用过的智能体会出现在这里",
},
detail: {
title: "智能体详情",
@@ -1514,23 +1538,23 @@ export default {
selectFile: "选择文件",
},
tenant: {
- title: "租户信息",
- currentTenant: "当前租户",
- switchTenant: "切换工作区",
+ title: "空间信息",
+ currentTenant: "当前空间",
+ switchTenant: "切换空间",
switcher: {
- menuLabel: "切换工作区",
+ menuLabel: "切换空间",
currentBadge: "当前",
homeBadge: "我的",
- homeTooltip: "我的工作区",
- empty: "你目前只属于这一个工作区",
+ homeTooltip: "我的空间",
+ empty: "你目前只属于这一个空间",
},
currentChip: {
- home: "我的租户",
+ home: "我的空间",
},
- sectionDescription: "查看租户的详细配置信息",
+ sectionDescription: "查看空间的详细配置信息",
apiDocument: "API文档",
- name: "租户名称",
- id: "租户ID",
+ name: "空间名称",
+ id: "空间 ID",
createdAt: "创建时间",
updatedAt: "更新时间",
status: "状态",
@@ -1545,9 +1569,9 @@ export default {
userId: "用户ID",
username: "用户名",
email: "邮箱",
- tenantInfo: "租户信息",
- tenantId: "租户ID",
- tenantName: "租户名称",
+ tenantInfo: "空间信息",
+ tenantId: "空间 ID",
+ tenantName: "空间名称",
description: "描述",
business: "业务",
noDescription: "无描述",
@@ -1572,58 +1596,58 @@ export default {
apiKeyCopied: "API密钥已复制到剪贴板",
unknown: "未知",
formatError: "格式错误",
- searchPlaceholder: "搜索租户名称或输入租户ID...",
- searchHint: "支持按名称搜索或直接输入租户ID",
- noMatch: "未找到匹配的租户",
- switchSuccess: "租户切换成功",
- loadTenantsFailed: "加载租户列表失败",
+ searchPlaceholder: "搜索空间名称或输入空间 ID...",
+ searchHint: "支持按名称搜索或直接输入空间 ID",
+ noMatch: "未找到匹配的空间",
+ switchSuccess: "空间切换成功",
+ loadTenantsFailed: "加载空间列表失败",
loading: "加载中...",
loadMore: "加载更多",
create: {
- action: "创建新工作区",
- dialogTitle: "创建新工作区",
- dialogSubtitle: "工作区拥有独立的知识库与成员,你将自动成为新工作区的所有者。",
- nameLabel: "工作区名称",
+ action: "创建新空间",
+ dialogTitle: "创建新空间",
+ dialogSubtitle: "空间拥有独立的知识库与成员,你将自动成为新空间的所有者。",
+ nameLabel: "空间名称",
namePlaceholder: "例如:我的新项目",
- nameRequired: "请输入工作区名称",
+ nameRequired: "请输入空间名称",
descriptionLabel: "描述(可选)",
- descriptionPlaceholder: "简单描述一下这个工作区的用途",
+ descriptionPlaceholder: "简单描述一下这个空间的用途",
submit: "创建",
cancel: "取消",
- success: "工作区创建成功",
- failed: "工作区创建失败",
+ success: "空间创建成功",
+ failed: "空间创建失败",
},
details: {
- idLabel: "租户 ID",
- idDescription: "您所属租户的唯一标识",
- nameLabel: "租户名称",
- nameDescription: "您所属的租户名称",
- descriptionLabel: "租户描述",
- descriptionDescription: "租户的详细描述信息",
- businessLabel: "租户业务",
- businessDescription: "租户所属的业务类型",
- statusLabel: "租户状态",
- statusDescription: "租户当前的运行状态",
- createdAtLabel: "租户创建时间",
- createdAtDescription: "租户创建的时间",
+ idLabel: "空间 ID",
+ idDescription: "您所属空间的唯一标识",
+ nameLabel: "空间名称",
+ nameDescription: "您所属的空间名称",
+ descriptionLabel: "空间描述",
+ descriptionDescription: "空间的详细描述信息",
+ businessLabel: "空间业务",
+ businessDescription: "空间所属的业务类型",
+ statusLabel: "空间状态",
+ statusDescription: "空间当前的运行状态",
+ createdAtLabel: "空间创建时间",
+ createdAtDescription: "空间创建的时间",
editName: "修改名称",
- editNamePlaceholder: "请输入新的租户名称",
+ editNamePlaceholder: "请输入新的空间名称",
editNameConfirm: "保存",
editNameCancel: "取消",
- editNameRequired: "租户名称不能为空",
- editNameSuccess: "租户名称已更新",
- editNameFailed: "更新租户名称失败",
+ editNameRequired: "空间名称不能为空",
+ editNameSuccess: "空间名称已更新",
+ editNameFailed: "更新空间名称失败",
},
storage: {
quotaLabel: "存储配额",
- quotaDescription: "租户的总存储空间配额",
+ quotaDescription: "空间的总存储空间配额",
usedLabel: "已使用存储",
usedDescription: "已经使用的存储空间",
usageLabel: "存储使用率",
usageDescription: "存储空间的使用百分比",
},
messages: {
- fetchFailed: "获取租户信息失败",
+ fetchFailed: "获取空间信息失败",
networkError: "网络错误,请稍后重试",
},
api: {
@@ -1750,7 +1774,7 @@ export default {
loginFailed: "登录失败",
registerFailed: "注册失败",
getUserFailed: "获取用户信息失败",
- getTenantFailed: "获取租户信息失败",
+ getTenantFailed: "获取空间信息失败",
refreshTokenFailed: "刷新Token失败",
logoutFailed: "登出失败",
validateTokenFailed: "Token验证失败",
@@ -1762,10 +1786,10 @@ export default {
deleteFailed: "删除模型失败",
},
tenant: {
- listFailed: "获取租户列表失败",
- searchFailed: "搜索租户失败",
+ listFailed: "获取空间列表失败",
+ searchFailed: "搜索空间失败",
resetApiKeyFailed: "重置 API Key 失败",
- updateFailed: "更新租户信息失败",
+ updateFailed: "更新空间信息失败",
},
initialization: {
checkFailed: "检查失败",
@@ -2200,6 +2224,10 @@ export default {
description: '点击左侧快捷操作"新建知识库"按钮创建第一个知识库',
sharedTitle: "暂无共享知识库",
sharedDescription: "您可以加入共享空间或请求他人共享知识库给您",
+ favoritesTitle: "暂无收藏",
+ favoritesDescription: "在知识库卡片右上角点击星标即可收藏",
+ recentsTitle: "暂无最近访问",
+ recentsDescription: "最近打开过的知识库会出现在这里",
},
delete: {
confirmTitle: "删除确认",
@@ -3278,7 +3306,7 @@ export default {
},
organization: {
title: "共享空间",
- subtitle: "创建或加入共享空间,与团队成员共享知识库与智能体",
+ subtitle: "创建或加入共享空间,让多个空间互相协作,共享知识库与智能体",
createOrg: "创建空间",
createOrgShort: "新建",
joinOrg: "加入空间",
@@ -3303,11 +3331,11 @@ export default {
inviteCodeRefreshed: "邀请码已刷新",
inviteCodeRefreshFailed: "刷新邀请码失败",
rbac: {
- needTenantAdmin: "需要租户管理员权限",
- needTenantAdminTip: "此操作需要当前租户的 admin 或更高角色,请联系租户 Owner 调整权限。",
- cannotCreate: "当前租户角色不足,无法创建共享空间",
- cannotJoin: "当前租户角色不足,无法加入或申请加入共享空间",
- cannotManage: "当前租户角色不足,无法管理共享空间",
+ needTenantAdmin: "需要空间管理员权限",
+ needTenantAdminTip: "此操作需要当前空间的 admin 或更高角色,请联系空间 Owner 调整权限。",
+ cannotCreate: "当前空间角色不足,无法创建共享空间",
+ cannotJoin: "当前空间角色不足,无法加入或申请加入共享空间",
+ cannotManage: "当前空间角色不足,无法管理共享空间",
},
join: {
title: "加入空间",
@@ -3415,7 +3443,7 @@ export default {
editTitle: "空间设置",
detailTitle: "空间详情",
myRoleDesc: "您在此空间中的角色决定了您的权限范围",
- membersDesc: "查看和管理空间成员、调整成员角色。每个成员对应一个租户,同一租户下的所有用户共享该空间的访问权限。",
+ membersDesc: "查看和管理共享空间成员、调整成员角色。成员的最小单位是空间——加入后该空间下的所有用户都将获得访问权限。",
sharedDesc: "查看共享到此空间的所有知识库",
noSharedKB: "暂无共享的知识库",
noSharedKBTip: "知识库拥有者可以在知识库设置中将其共享到此空间",
@@ -3518,13 +3546,13 @@ export default {
button: "添加成员",
dialogTitle: "添加成员",
tip: "添加的用户将立即成为空间成员,可以访问空间内共享的知识库。",
- tipTenant: "空间成员的最小单位是租户:选定一个租户后,其下全部用户都将共享该空间的访问权限。下方搜索结果按租户去重。",
+ tipTenant: "共享空间的成员单位是空间:选定一个空间后,其下全部用户都将获得访问权限。下方搜索结果按空间去重。",
searchUser: "选择用户",
- searchTenant: "选择租户",
+ searchTenant: "选择空间",
searchPlaceholder: "输入用户名或邮箱搜索...",
- searchTenantPlaceholder: "输入租户名、用户名或邮箱搜索...",
- searchHint: "输入至少2个字符开始搜索",
- searchTenantHint: "输入至少2个字符开始搜索,按租户去重并自动过滤已加入的租户",
+ searchTenantPlaceholder: "输入空间名、用户名或邮箱搜索...",
+ searchHint: "输入至少 2 个字符开始搜索",
+ searchTenantHint: "输入至少 2 个字符开始搜索,按空间去重并自动过滤已加入的空间",
selectRole: "分配角色",
confirmBtn: "添加",
success: "成员添加成功",
@@ -4312,9 +4340,9 @@ export default {
imOverview: {
menuTitle: "已接入的 IM",
pageTitle: "已接入的 IM",
- subtitle: "当前租户下所有智能体已接入的 IM 渠道,可快速启停或跳转到对应智能体",
+ subtitle: "当前空间下所有智能体已接入的 IM 渠道,可快速启停或跳转到对应智能体",
totalCount: "共 {count} 个",
- empty: "当前租户还没有配置 IM 机器人",
+ empty: "当前空间还没有配置 IM 机器人",
loadFailed: "加载 IM 机器人列表失败",
builtinAgent: "内置智能体",
liveIndicator: "有已启用的 IM 渠道正在运行",
@@ -4355,7 +4383,7 @@ export default {
},
tenantMember: {
title: "成员管理",
- sectionDescription: "邀请伙伴加入当前租户并分配角色。只有 Owner 可以新增或移除成员。",
+ sectionDescription: "邀请伙伴加入当前空间并分配角色。只有 Owner 可以新增或移除成员。",
totalCount: "共 {n} 位成员",
loading: "正在加载成员…",
retry: "重试",
@@ -4364,13 +4392,13 @@ export default {
searchPlaceholder: "按姓名或邮箱搜索",
permissions: {
title: "角色权限说明",
- desc: "每个角色在当前租户内能做的事情。服务端强制执行,UI 控件仅作展示。",
+ desc: "每个角色在当前空间内能做的事情。服务端强制执行,UI 控件仅作展示。",
iconHint: "悬停查看角色权限说明",
manageMembers: "管理成员",
- manageTenantConfig: "修改租户配置",
+ manageTenantConfig: "修改空间配置",
manageInfra: "配置模型 / 向量库 / IM 通道",
createOwnKB: "创建并编辑自己的知识库和智能体",
- readAll: "查看租户内容",
+ readAll: "查看空间内容",
},
columns: {
member: "姓名与邮箱",
@@ -4398,16 +4426,16 @@ export default {
remove: {
button: "移除",
confirmTitle: "确认移除?",
- confirmBody: "确定要将 {name} 从当前租户中移除吗?该用户会立即失去访问权限。",
+ confirmBody: "确定要将 {name} 从当前空间中移除吗?该用户会立即失去访问权限。",
confirm: "移除",
success: "已移除成员",
},
leave: {
- button: "退出租户",
- confirmTitle: "确认退出当前租户?",
- confirmBody: "退出后您将无法访问当前租户内的所有知识库和智能体。后续可被再次邀请加入。",
+ button: "退出空间",
+ confirmTitle: "确认退出当前空间?",
+ confirmBody: "退出后您将无法访问当前空间内的所有知识库和智能体。后续可被再次邀请加入。",
confirm: "退出",
- success: "已退出当前租户",
+ success: "已退出当前空间",
},
roleChange: {
success: "角色已更新",
@@ -4417,10 +4445,10 @@ export default {
emailFormat: "邮箱格式不正确",
roleRequired: "请选择角色",
userNotFound: "该邮箱尚未注册,请先邀请对方注册账号。",
- alreadyMember: "该用户已经是当前租户的成员。",
+ alreadyMember: "该用户已经是当前空间的成员。",
lastOwner: "无法降级、移除或退出最后一位 Owner,请先把其他成员提升为 Owner。",
notFound: "未找到对应的成员。",
- noTenant: "当前没有可操作的租户。",
+ noTenant: "当前没有可操作的空间。",
invalidRole: "角色必须是 owner / admin / contributor / viewer 之一。",
generic: "操作失败,请稍后重试。",
},
@@ -4431,7 +4459,7 @@ export default {
audit: {
tabLabel: "审计日志",
description:
- "记录当前租户的成员变更与访问拒绝事件,按时间倒序展示。一分钟内的重复拒绝会自动去重。",
+ "记录当前空间的成员变更与访问拒绝事件,按时间倒序展示。一分钟内的重复拒绝会自动去重。",
refresh: "刷新",
loadMore: "加载更多",
end: "已经到底了。",
diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts
index bed7c37d3..484900007 100644
--- a/frontend/src/stores/auth.ts
+++ b/frontend/src/stores/auth.ts
@@ -47,6 +47,30 @@ export const useAuthStore = defineStore('auth', () => {
return tenant.value?.id || ''
})
+ // currentTenantName resolves the active tenant's display name across the
+ // app (sidebar, breadcrumbs, headers). It MUST follow the same active-
+ // tenant rule as currentTenantRole / effectiveTenantId: the user's
+ // selected override takes precedence over their home tenant. Reading
+ // tenant.value.name alone would render the home tenant's name even after
+ // the user switched, which is the bug TenantSelector already worked
+ // around inline; this computed centralises that fallback ladder.
+ const currentTenantName = computed(() => {
+ const tid =
+ selectedTenantId.value !== null && selectedTenantId.value !== undefined
+ ? String(selectedTenantId.value)
+ : tenant.value?.id
+ ? String(tenant.value.id)
+ : ''
+ if (!tid) return ''
+ if (selectedTenantId.value && selectedTenantName.value) {
+ return selectedTenantName.value
+ }
+ const fromMembership = memberships.value.find((m) => String(m.tenant_id) === tid)
+ if (fromMembership?.tenant_name) return fromMembership.tenant_name
+ if (tenant.value && String(tenant.value.id) === tid) return tenant.value.name || ''
+ return ''
+ })
+
const currentUserId = computed(() => {
return user.value?.id || ''
})
@@ -322,6 +346,7 @@ export const useAuthStore = defineStore('auth', () => {
isLoggedIn,
hasValidTenant,
currentTenantId,
+ currentTenantName,
currentUserId,
canAccessAllTenants,
currentTenantRole,
diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vue
index e40f8a3b2..3d1ed05d1 100644
--- a/frontend/src/views/agent/AgentList.vue
+++ b/frontend/src/views/agent/AgentList.vue
@@ -1,7 +1,8 @@
<template>
<div class="agent-list-container">
<ListSpaceSidebar v-if="!authStore.isLiteMode" v-model="spaceSelection" :count-all="allAgentsCount"
- :count-mine="agents.length" :count-by-org="effectiveSharedCountByOrg" hide-all hide-shared />
+ :count-mine="agents.length" :count-by-org="effectiveSharedCountByOrg" :count-favorites="agentFavoritesCount"
+ :count-recents="agentRecentsCount" hide-all />
<div class="agent-list-content">
<div class="header" style="--wails-draggable: drag">
<div class="header-title" style="--wails-draggable: drag">
@@ -36,6 +37,9 @@
</div>
</div>
<div class="agent-list-main">
+ <!-- creator filter removed; see KnowledgeBaseList for rationale.
+ Card-level creator display + URL-state field are retained. -->
+
<!-- 骨架屏占位 -->
<div v-if="loading && agents.length === 0" class="agent-card-wrap">
<div v-for="n in 6" :key="'skel-' + n" class="agent-card agent-card-skeleton">
@@ -56,8 +60,10 @@
</div>
</div>
- <!-- 全部:我的 + 共享 -->
- <div v-if="spaceSelection === 'all' && filteredAgents.length > 0" class="agent-card-wrap">
+ <!-- 全部 / 收藏 / 最近:共用同一份卡片模板 -->
+ <div
+ v-if="(spaceSelection === 'all' || spaceSelection === 'favorites' || spaceSelection === 'recents') && filteredAgents.length > 0"
+ class="agent-card-wrap">
<div v-for="agent in filteredAgents" :key="agent.isMine ? agent.id : `shared-${agent.share_id}`"
class="agent-card" :class="{
'is-builtin': agent.is_builtin,
@@ -65,6 +71,11 @@
'agent-mode-agent': agent.config?.agent_mode === 'smart-reasoning',
'shared-agent-card': !agent.isMine
}" @click="handleCardClick(agent)">
+ <!-- 收藏按钮 -->
+ <button type="button" class="agent-favorite-star" :class="{ 'is-favorited': isAgentFavorited(agent.id) }"
+ @click.stop="toggleFavoriteAgent(agent.id, $event)">
+ <t-icon :name="isAgentFavorited(agent.id) ? 'star-filled' : 'star'" size="14px" />
+ </button>
<!-- 装饰星星 -->
<div class="card-decoration">
<svg class="star-icon" width="24" height="24" viewBox="0 0 20 20" fill="none"
@@ -212,6 +223,11 @@
'agent-mode-normal': agent.config?.agent_mode === 'quick-answer',
'agent-mode-agent': agent.config?.agent_mode === 'smart-reasoning'
}" @click="handleCardClick(agent)">
+ <!-- 收藏按钮 -->
+ <button type="button" class="agent-favorite-star" :class="{ 'is-favorited': isAgentFavorited(agent.id) }"
+ @click.stop="toggleFavoriteAgent(agent.id, $event)">
+ <t-icon :name="isAgentFavorited(agent.id) ? 'star-filled' : 'star'" size="14px" />
+ </button>
<!-- 装饰星星 -->
<div class="card-decoration">
<svg class="star-icon" width="24" height="24" viewBox="0 0 20 20" fill="none"
@@ -446,7 +462,7 @@
</div>
</div>
- <!-- 空状态:全部 -->
+ <!-- 空状态:全部(保留创建 CTA) -->
<div v-if="spaceSelection === 'all' && filteredAgents.length === 0 && !loading" class="empty-state">
<img class="empty-img" src="@/assets/img/upload.svg" alt="">
<span class="empty-txt">{{ $t('agent.empty.title') }}</span>
@@ -475,6 +491,18 @@
<span>{{ $t('agent.createAgent') }}</span>
</t-button>
</div>
+
+ <!-- 空状态:收藏 / 最近 — 不放创建按钮,参见 KnowledgeBaseList 的同处理由 -->
+ <div v-if="spaceSelection === 'favorites' && filteredAgents.length === 0 && !loading" class="empty-state">
+ <t-icon name="star" size="48px" class="empty-icon" />
+ <span class="empty-txt">{{ $t('agent.empty.favoritesTitle') }}</span>
+ <span class="empty-desc">{{ $t('agent.empty.favoritesDescription') }}</span>
+ </div>
+ <div v-if="spaceSelection === 'recents' && filteredAgents.length === 0 && !loading" class="empty-state">
+ <t-icon name="history" size="48px" class="empty-icon" />
+ <span class="empty-txt">{{ $t('agent.empty.recentsTitle') }}</span>
+ <span class="empty-desc">{{ $t('agent.empty.recentsDescription') }}</span>
+ </div>
<!-- 空状态:我的 -->
<div v-if="spaceSelection === 'mine' && agents.length === 0 && !loading" class="empty-state">
<img class="empty-img" src="@/assets/img/upload.svg" alt="">
@@ -622,6 +650,8 @@ import AgentEditorModal from './AgentEditorModal.vue'
import AgentAvatar from '@/components/AgentAvatar.vue'
import ListSpaceSidebar from '@/components/ListSpaceSidebar.vue'
import { useAuthStore } from '@/stores/auth'
+import { useListUrlState } from '@/composables/useListUrlState'
+import { useResourcePins } from '@/composables/useResourcePins'
const { t } = useI18n()
const route = useRoute()
@@ -641,16 +671,35 @@ type DisplayAgent = (AgentWithUI & { isMine: true }) | (CustomAgent & { isMine:
// 左侧空间选择:默认根据当前角色决定。
// 与 KnowledgeBaseList 同款逻辑:Viewer 在当前租户里通常没有自建智能体,
// 默认落到 "all" 才能看到内置 + 共享给我的;Contributor 以上仍默认 "mine"。
-const initialSpaceSelection = (): 'all' | 'mine' =>
- authStore.hasRole('contributor') ? 'mine' : 'all'
-const spaceSelection = ref<'all' | 'mine' | string>(initialSpaceSelection())
+// State synced to `?scope=` so links are shareable. The "mine" value is
+// retained for back-compat with existing links; its display label is
+// rebranded to the active tenant name inside ListSpaceSidebar.
+const defaultScope: 'all' | 'mine' = authStore.hasRole('contributor') ? 'mine' : 'all'
+const { scope: spaceSelection, creator: creatorFilter } = useListUrlState({
+ defaultScope,
+ defaultCreator: 'all',
+})
+
+// Per-user favorites + recents (localStorage-backed). See useResourcePins.
+const pins = useResourcePins()
+const agentFavoritesCount = computed(
+ () => pins.favorites.value.filter((e) => e.type === 'agent').length
+)
+const agentRecentsCount = computed(
+ () => pins.recents.value.filter((e) => e.type === 'agent').length
+)
const agents = ref<AgentWithUI[]>([])
const sharedAgents = computed<SharedAgentInfo[]>(() => orgStore.sharedAgents || [])
const allAgentsCount = computed(() => agents.value.length + sharedAgents.value.length)
+// Same gotcha as KnowledgeBaseList: keep the reserved-scope set in sync
+// with ListSpaceSidebar's pseudo-scopes (favorites / recents / shared /
+// mine / all). Anything not in here is treated as an org/space id, which
+// is what triggers the per-space fetch + "no shared agents" empty state.
+const RESERVED_SCOPES = new Set(['all', 'mine', 'shared', 'favorites', 'recents'])
const spaceSelectionOrgId = computed(() => {
const s = spaceSelection.value
- return s !== 'all' && s !== 'mine' && !!s
+ return !!s && !RESERVED_SCOPES.has(s)
})
const sharedAgentsByOrg = computed(() => {
@@ -686,7 +735,61 @@ const effectiveSharedCountByOrg = computed<Record<string, number>>(() => {
return merged
})
+// Favorites / Recents view: hydrate pinned ids against own + shared agents.
+const agentResourceIndex = computed(() => {
+ const map = new Map<string, { agent: any; isMine: boolean; shared?: SharedAgentInfo }>()
+ for (const a of agents.value) map.set(a.id, { agent: a, isMine: true })
+ for (const s of sharedAgents.value) {
+ if (s.agent && !map.has(s.agent.id)) map.set(s.agent.id, { agent: s.agent, isMine: false, shared: s })
+ }
+ return map
+})
+
+const favoritesAgentList = computed<DisplayAgent[]>(() => {
+ return pins.favorites.value
+ .filter((e) => e.type === 'agent')
+ .map((e) => {
+ const entry = agentResourceIndex.value.get(e.id)
+ if (!entry) return null
+ if (entry.isMine) return { ...entry.agent, isMine: true as const, showMore: false }
+ const s = entry.shared!
+ return {
+ ...entry.agent,
+ isMine: false as const,
+ org_name: s.org_name,
+ source_tenant_id: s.source_tenant_id,
+ share_id: s.share_id,
+ disabled_by_me: s.disabled_by_me,
+ showMore: false,
+ } as DisplayAgent
+ })
+ .filter((x): x is DisplayAgent => x !== null)
+})
+
+const recentsAgentList = computed<DisplayAgent[]>(() => {
+ return pins.recents.value
+ .filter((e) => e.type === 'agent')
+ .map((e) => {
+ const entry = agentResourceIndex.value.get(e.id)
+ if (!entry) return null
+ if (entry.isMine) return { ...entry.agent, isMine: true as const, showMore: false }
+ const s = entry.shared!
+ return {
+ ...entry.agent,
+ isMine: false as const,
+ org_name: s.org_name,
+ source_tenant_id: s.source_tenant_id,
+ share_id: s.share_id,
+ disabled_by_me: s.disabled_by_me,
+ showMore: false,
+ } as DisplayAgent
+ })
+ .filter((x): x is DisplayAgent => x !== null)
+})
+
const filteredAgents = computed<DisplayAgent[]>(() => {
+ if (spaceSelection.value === 'favorites') return favoritesAgentList.value
+ if (spaceSelection.value === 'recents') return recentsAgentList.value
if (spaceSelection.value === 'mine') {
return agents.value.map(a => ({ ...a, isMine: true as const }))
}
@@ -741,7 +844,7 @@ const openMoreAgentId = ref<string | null>(null)
const fetchList = () => {
loading.value = true
return Promise.all([
- listAgents().then((res: any) => {
+ listAgents({ creator: creatorFilter.value }).then((res: any) => {
const data = res.data || []
const disabledOwnIds = res.disabled_own_agent_ids || []
agents.value = data.map((agent: CustomAgent) => ({
@@ -772,8 +875,10 @@ const checkAndOpenEditModal = () => {
editorInitialSection.value = section || 'basic'
editorVisible.value = true
}
- // 清除 URL 中的参数
- router.replace({ path: route.path, query: {} })
+ // Drop the transient edit/section params but preserve other filter
+ // state (scope / creator / q) so refreshing doesn't reset the view.
+ const { edit: _e, section: _s, ...rest } = route.query
+ router.replace({ path: route.path, query: rest })
}
}
@@ -816,6 +921,13 @@ watch(spaceSelection, (val) => {
})
}, { immediate: true })
+// Refetch when the creator filter flips so the server applies the
+// predicate uniformly (also keeps built-in agents always present, see
+// the matching block in custom_agent.go).
+watch(creatorFilter, () => {
+ fetchList()
+})
+
onMounted(() => {
fetchList()
window.addEventListener('openAgentEditor', handleOpenAgentEditor as EventListener)
@@ -838,6 +950,9 @@ const toggleMore = (e: Event, agentId: string) => {
const handleCardClick = (agent: DisplayAgent | AgentWithUI) => {
if (openMoreAgentId.value === agent.id) return
+ // Track recency before any branch — Recents should reflect what the
+ // user *looked at*, not only what they edited.
+ pins.touchRecent('agent', agent.id)
if ('isMine' in agent && !agent.isMine) {
const shared = sharedAgents.value.find(s => s.agent?.id === agent.id && s.source_tenant_id === agent.source_tenant_id)
if (shared) openSharedAgentDetail(shared)
@@ -846,6 +961,12 @@ const handleCardClick = (agent: DisplayAgent | AgentWithUI) => {
handleEdit(agent as AgentWithUI)
}
+const toggleFavoriteAgent = (agentId: string, evt?: Event) => {
+ evt?.stopPropagation()
+ pins.toggleFavorite('agent', agentId)
+}
+const isAgentFavorited = (agentId: string) => pins.isFavorite('agent', agentId)
+
function openSharedAgentDetail(shared: SharedAgentInfo) {
currentSharedAgent.value = shared
sharedDetailVisible.value = true
@@ -1354,6 +1475,39 @@ defineExpose({
box-shadow: 0 4px 12px rgba(7, 192, 95, 0.12);
}
+ .agent-favorite-star {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ z-index: 3;
+ width: 24px;
+ height: 24px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: none;
+ border-radius: 6px;
+ color: var(--td-text-color-secondary);
+ cursor: pointer;
+ opacity: 0;
+ transition: opacity 0.15s ease, background 0.15s ease, color 0.15s ease;
+
+ &:hover {
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-warning-color, #e37318);
+ }
+
+ &.is-favorited {
+ opacity: 1;
+ color: var(--td-warning-color, #e37318);
+ }
+ }
+
+ &:hover .agent-favorite-star {
+ opacity: 1;
+ }
+
// 普通模式样式
&.agent-mode-normal {
background: linear-gradient(135deg, var(--td-bg-color-container) 0%, rgba(7, 192, 95, 0.04) 100%);
diff --git a/frontend/src/views/knowledge/KnowledgeBaseList.vue b/frontend/src/views/knowledge/KnowledgeBaseList.vue
index 641e2f924..0a9940c9a 100644
--- a/frontend/src/views/knowledge/KnowledgeBaseList.vue
+++ b/frontend/src/views/knowledge/KnowledgeBaseList.vue
@@ -1,7 +1,8 @@
<template>
<div class="kb-list-container">
<ListSpaceSidebar v-if="!authStore.isLiteMode" v-model="spaceSelection" :count-all="allKnowledgeBases"
- :count-mine="kbs.length" :count-shared="sharedKbs.length" :count-by-org="effectiveSharedCountByOrg" />
+ :count-mine="kbs.length" :count-by-org="effectiveSharedCountByOrg" :count-favorites="kbFavoritesCount"
+ :count-recents="kbRecentsCount" />
<div class="kb-list-content">
<div class="header" style="--wails-draggable: drag">
<div class="header-title" style="--wails-draggable: drag">
@@ -18,6 +19,14 @@
</div>
</div>
<div class="kb-list-main">
+ <!-- creator filter intentionally removed from chrome: every card
+ already shows its creator via ResourceOriginBadge / avatar, so
+ a dedicated horizontal switch added more noise than signal.
+ The backend `?creator=mine|others` param and the URL-state
+ field are kept so a future "filter by member" entry point
+ (e.g. clicking an avatar) can deep-link without re-plumbing. -->
+
+
<!-- 未初始化知识库提示 -->
<div v-if="hasUninitializedKbs" class="warning-banner">
<t-icon name="info-circle" size="16px" />
@@ -79,8 +88,11 @@
</div>
</div>
- <!-- 卡片网格:全部 -->
- <div v-if="spaceSelection === 'all' && filteredKnowledgeBases.length > 0" class="kb-card-wrap">
+ <!-- 卡片网格:全部 / 收藏 / 最近 — 共用同一份卡片模板,
+ 仅依赖 filteredKnowledgeBases 切片即可切换视图 -->
+ <div
+ v-if="(spaceSelection === 'all' || spaceSelection === 'favorites' || spaceSelection === 'recents') && filteredKnowledgeBases.length > 0"
+ class="kb-card-wrap">
<!-- 置顶分组标题 -->
<div
v-if="filteredKnowledgeBases[0] && filteredKnowledgeBases[0].isMine && filteredKnowledgeBases[0].is_pinned"
@@ -110,6 +122,11 @@
<div v-if="kb.is_pinned" class="pin-indicator">
<t-icon name="pin-filled" size="14px" />
</div>
+ <!-- 收藏按钮:右上角浮动 -->
+ <button type="button" class="kb-favorite-star" :class="{ 'is-favorited': isKbFavorited(kb.id) }"
+ @click.stop="toggleFavoriteKb(kb.id, $event)">
+ <t-icon :name="isKbFavorited(kb.id) ? 'star-filled' : 'star'" size="14px" />
+ </button>
<!-- 卡片头部 -->
<div class="card-header">
<span class="card-title" :title="kb.name">{{ kb.name }}</span>
@@ -199,6 +216,11 @@
'kb-type-document': (kb.type || 'document') === 'document',
'kb-type-faq': kb.type === 'faq'
}" @click="handleSharedKbClickFromAll(kb)">
+ <!-- 收藏按钮 -->
+ <button type="button" class="kb-favorite-star" :class="{ 'is-favorited': isKbFavorited(kb.id) }"
+ @click.stop="toggleFavoriteKb(kb.id, $event)">
+ <t-icon :name="isKbFavorited(kb.id) ? 'star-filled' : 'star'" size="14px" />
+ </button>
<!-- 卡片头部 -->
<div class="card-header">
<span class="card-title" :title="kb.name">{{ kb.name }}</span>
@@ -229,7 +251,7 @@
<t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" size="14px" />
<span class="badge-count">{{ kb.type === 'faq' ? (kb.chunk_count || '-') : (kb.knowledge_count
|| '-')
- }}</span>
+ }}</span>
</div>
</t-tooltip>
<t-tooltip v-if="kb.extract_config?.enabled" :content="$t('knowledgeList.features.knowledgeGraph')"
@@ -291,6 +313,11 @@
<div v-if="kb.is_pinned" class="pin-indicator">
<t-icon name="pin-filled" size="14px" />
</div>
+ <!-- 收藏按钮 -->
+ <button type="button" class="kb-favorite-star" :class="{ 'is-favorited': isKbFavorited(kb.id) }"
+ @click.stop="toggleFavoriteKb(kb.id, $event)">
+ <t-icon :name="isKbFavorited(kb.id) ? 'star-filled' : 'star'" size="14px" />
+ </button>
<!-- 卡片头部 -->
<div class="card-header">
<span class="card-title" :title="kb.name">{{ kb.name }}</span>
@@ -380,60 +407,7 @@
</template>
</div>
- <!-- 卡片网格:共享给我 -->
- <div v-if="spaceSelection === 'shared' && sharedKbs.length > 0" class="kb-card-wrap">
- <div v-for="shared in sharedKbs" :key="'shared-' + shared.share_id" class="kb-card shared-kb-card" :class="{
- 'kb-type-document': (shared.knowledge_base.type || 'document') === 'document',
- 'kb-type-faq': shared.knowledge_base.type === 'faq'
- }" @click="handleSharedKbClickFromAll(shared.knowledge_base)">
- <div class="card-header">
- <span class="card-title" :title="shared.knowledge_base.name">{{ shared.knowledge_base.name }}</span>
- <t-tooltip :content="$t('knowledgeList.menu.viewDetails')" placement="top">
- <button type="button" class="shared-detail-trigger" @click.stop="openSharedDetail(shared)"
- :aria-label="$t('knowledgeList.menu.viewDetails')">
- <t-icon name="info-circle" size="16px" />
- </button>
- </t-tooltip>
- </div>
- <div class="card-content">
- <div class="card-description">
- {{ shared.knowledge_base.description || $t('knowledgeBase.noDescription') }}
- </div>
- </div>
- <div class="card-bottom">
- <div class="bottom-left">
- <div class="feature-badges">
- <t-tooltip
- :content="shared.knowledge_base.type === 'faq' ? $t('knowledgeEditor.basic.typeFAQ') : $t('knowledgeEditor.basic.typeDocument')"
- placement="top">
- <div class="feature-badge"
- :class="{ 'type-document': (shared.knowledge_base.type || 'document') === 'document', 'type-faq': shared.knowledge_base.type === 'faq' }">
- <t-icon :name="shared.knowledge_base.type === 'faq' ? 'chat-bubble-help' : 'folder'"
- size="14px" />
- <span class="badge-count">{{ shared.knowledge_base.type === 'faq' ?
- (shared.knowledge_base.chunk_count ||
- '-') : (shared.knowledge_base.knowledge_count || '-') }}</span>
- </div>
- </t-tooltip>
- </div>
- </div>
- <div class="bottom-right">
- <t-tooltip :content="shared.org_name" placement="top">
- <div class="org-source">
- <img src="@/assets/img/organization-green.svg" class="org-source-icon" alt="" aria-hidden="true" />
- <span>{{ shared.org_name }}</span>
- </div>
- </t-tooltip>
- </div>
- </div>
- </div>
- </div>
-
- <!-- 共享给我空状态 -->
- <div v-if="spaceSelection === 'shared' && sharedKbs.length === 0 && !loading" class="empty-state">
- <t-icon name="share" size="48px" class="empty-icon" />
- <p>{{ $t('knowledgeList.emptyShared') }}</p>
- </div>
+ <!-- 协作 / 共享给我 聚合视图已移除:共享 KB 走「全部」或具体空间下展示 -->
<!-- 按空间筛选:该空间内全部知识库(含我共享的) -->
<div v-if="spaceSelectionOrgId && spaceKbsLoading" class="kb-list-main-loading">
@@ -497,7 +471,7 @@
</div>
</div>
- <!-- 全部空状态 -->
+ <!-- 全部空状态:保留「新建知识库」CTA,因为是租户没有任何 KB 的真空场景 -->
<div v-if="spaceSelection === 'all' && filteredKnowledgeBases.length === 0 && !loading" class="empty-state">
<img class="empty-img" src="@/assets/img/upload.svg" alt="">
<span class="empty-txt">{{ $t('knowledgeList.empty.title') }}</span>
@@ -509,6 +483,22 @@
</t-button>
</div>
+ <!-- 收藏空状态:不放创建按钮——「没有收藏」 ≠ 「没有知识库」,
+ 正确引导是「去星标一下」,不是「再建一个」。 -->
+ <div v-if="spaceSelection === 'favorites' && filteredKnowledgeBases.length === 0 && !loading"
+ class="empty-state">
+ <t-icon name="star" size="48px" class="empty-icon" />
+ <span class="empty-txt">{{ $t('knowledgeList.empty.favoritesTitle') }}</span>
+ <span class="empty-desc">{{ $t('knowledgeList.empty.favoritesDescription') }}</span>
+ </div>
+
+ <!-- 最近空状态:同理,引导是「去打开一个」。 -->
+ <div v-if="spaceSelection === 'recents' && filteredKnowledgeBases.length === 0 && !loading" class="empty-state">
+ <t-icon name="history" size="48px" class="empty-icon" />
+ <span class="empty-txt">{{ $t('knowledgeList.empty.recentsTitle') }}</span>
+ <span class="empty-desc">{{ $t('knowledgeList.empty.recentsDescription') }}</span>
+ </div>
+
<!-- 我的知识库空状态 -->
<div v-if="spaceSelection === 'mine' && kbs.length === 0 && !loading" class="empty-state">
<img class="empty-img" src="@/assets/img/upload.svg" alt="">
@@ -544,7 +534,7 @@
<div class="circle-btn">
<span class="circle-btn-txt" @click="deleteVisible = false">{{ $t('common.cancel') }}</span>
<span class="circle-btn-txt confirm" @click="confirmDelete">{{ $t('knowledgeList.delete.confirmButton')
- }}</span>
+ }}</span>
</div>
</div>
</t-dialog>
@@ -603,7 +593,7 @@
<div class="shared-detail-row">
<span class="shared-detail-label">{{ $t('knowledgeList.detail.sharedAt') }}</span>
<span class="shared-detail-value">{{ formatStringDate(new Date(currentSharedKbForDetail.shared_at))
- }}</span>
+ }}</span>
</div>
<div class="shared-detail-row">
<span class="shared-detail-label">{{ $t('knowledgeList.detail.myPermission') }}</span>
@@ -615,7 +605,7 @@
</div>
<div class="shared-detail-drawer-footer">
<t-button theme="default" variant="outline" @click="closeSharedDetailPanel">{{ $t('common.close')
- }}</t-button>
+ }}</t-button>
<t-button theme="primary" class="go-to-kb-btn" @click="goToSharedKbFromPanel">
<t-icon name="browse" />
{{ $t('knowledgeList.detail.goToKb') }}
@@ -643,6 +633,8 @@ import KnowledgeBaseEditorModal from './KnowledgeBaseEditorModal.vue'
import ShareKnowledgeBaseDialog from '@/components/ShareKnowledgeBaseDialog.vue'
import ListSpaceSidebar from '@/components/ListSpaceSidebar.vue'
import { useI18n } from 'vue-i18n'
+import { useListUrlState } from '@/composables/useListUrlState'
+import { useResourcePins } from '@/composables/useResourcePins'
const router = useRouter()
const route = useRoute()
@@ -655,9 +647,27 @@ const { t } = useI18n()
// Viewer 在该租户里通常 0 KB owned,"我的"会显示空状态、又把共享 KB 藏起来,
// 体验非常误导;所以 Viewer 默认落到 "all"(我的 + 共享给我都显示)。
// Contributor 及以上一进来主要管理自己创建的 KB,仍默认 "mine"。
-const initialSpaceSelection = (): 'all' | 'mine' =>
- authStore.hasRole('contributor') ? 'mine' : 'all'
-const spaceSelection = ref<'all' | 'mine' | 'shared' | string>(initialSpaceSelection())
+//
+// State lives in `?scope=` so links are shareable/bookmarkable; the
+// composable handles two-way sync with the URL. We keep "mine" as the
+// stored value (not "workspace") for back-compat with any external link
+// that might point at the old query — its display label is rebranded
+// via ListSpaceSidebar's workspaceLabel computed.
+const defaultScope: 'all' | 'mine' = authStore.hasRole('contributor') ? 'mine' : 'all'
+const { scope: spaceSelection, creator: creatorFilter } = useListUrlState({
+ defaultScope,
+ defaultCreator: 'all',
+})
+
+// Per-user favorites + recents (localStorage-backed). isFavorite & touchRecent
+// are wired into card render and click handlers below.
+const pins = useResourcePins()
+const kbFavoritesCount = computed(
+ () => pins.favorites.value.filter((e) => e.type === 'kb').length
+)
+const kbRecentsCount = computed(
+ () => pins.recents.value.filter((e) => e.type === 'kb').length
+)
interface KB {
id: string;
@@ -702,16 +712,23 @@ const shareDialogVisible = ref(false)
const sharingKbId = ref('')
const sharingKbName = ref('')
-// Shared knowledge bases
+// Shared knowledge bases (everything cross-tenant shared to me, including
+// viewer-only). Used by the per-space views and the "all" aggregate so
+// readers still see read-only shares — those are valid resources, just
+// not editable.
const sharedKbs = computed<SharedKnowledgeBase[]>(() => orgStore.sharedKnowledgeBases || [])
-// All knowledge bases (mine + shared to me)
const allKnowledgeBases = computed(() => kbs.value.length + sharedKbs.value.length)
-// 当前选中的是空间 ID(非全部、非我的)
+// 当前选中的是空间 ID(非全部、非我的、非收藏/最近这类伪 scope)
+// NB: keep the reserved-scope list in sync with ListSpaceSidebar's
+// non-org buckets — otherwise a new pseudo-scope (e.g. "favorites")
+// falls through here and triggers the per-space code paths, which
+// renders an extra "no shared KB" empty state on top of the real view.
+const RESERVED_SCOPES = new Set(['all', 'mine', 'favorites', 'recents'])
const spaceSelectionOrgId = computed(() => {
const s = spaceSelection.value
- return s !== 'all' && s !== 'mine' && s !== 'shared' && !!s
+ return !!s && !RESERVED_SCOPES.has(s)
})
// 当前空间下共享给我的知识库(旧:仅他人共享;保留用于兼容)
@@ -748,8 +765,88 @@ const effectiveSharedCountByOrg = computed<Record<string, number>>(() => {
return merged
})
+// Favorites / Recents views: hydrate pin entries by id against every KB
+// the user can already see in this page (own + cross-tenant shared). KBs
+// the user no longer has access to (deleted / share revoked) are dropped
+// silently — the pin survives until the next mutation, which keeps the
+// composable simple at the cost of harmless ghost entries.
+//
+// Order:
+// - favorites: most recently starred first (PinEntry.ts desc)
+// - recents: most recently opened first (also ts desc, already sorted)
+const kbResourceIndex = computed(() => {
+ const map = new Map<string, { kb: any; isMine: boolean; shared?: SharedKnowledgeBase }>()
+ for (const kb of kbs.value) {
+ map.set(kb.id, { kb, isMine: true })
+ }
+ for (const shared of sharedKbs.value) {
+ if (!shared.knowledge_base) continue
+ if (!map.has(shared.knowledge_base.id)) {
+ map.set(shared.knowledge_base.id, { kb: shared.knowledge_base, isMine: false, shared })
+ }
+ }
+ return map
+})
+
+const favoritesList = computed(() => {
+ return pins.favorites.value
+ .filter((e) => e.type === 'kb')
+ .map((e) => {
+ const entry = kbResourceIndex.value.get(e.id)
+ if (!entry) return null
+ if (entry.isMine) {
+ return { ...entry.kb, isMine: true as const, _pinTs: e.ts }
+ }
+ const s = entry.shared!
+ return {
+ ...entry.kb,
+ isMine: false as const,
+ permission: s.permission,
+ shared_at: s.shared_at,
+ share_id: s.share_id,
+ org_name: s.org_name,
+ _pinTs: e.ts,
+ } as any
+ })
+ .filter((x): x is NonNullable<typeof x> => x !== null)
+})
+
+const recentsList = computed(() => {
+ return pins.recents.value
+ .filter((e) => e.type === 'kb')
+ .map((e) => {
+ const entry = kbResourceIndex.value.get(e.id)
+ if (!entry) return null
+ if (entry.isMine) {
+ return { ...entry.kb, isMine: true as const, _pinTs: e.ts }
+ }
+ const s = entry.shared!
+ return {
+ ...entry.kb,
+ isMine: false as const,
+ permission: s.permission,
+ shared_at: s.shared_at,
+ share_id: s.share_id,
+ org_name: s.org_name,
+ _pinTs: e.ts,
+ } as any
+ })
+ .filter((x): x is NonNullable<typeof x> => x !== null)
+})
+
// Filtered knowledge bases: 全部 = 我的 + 全部共享;我的 = 仅我的
+//
+// Favorites / Recents reuse the same render path as `all` — they're just
+// pre-filtered, pre-ordered slices, so the existing kb-card / shared
+// kb-card templates render them with zero extra markup. Order is
+// preserved via the upstream array (pins order is ts-desc).
const filteredKnowledgeBases = computed(() => {
+ if (spaceSelection.value === 'favorites') {
+ return favoritesList.value
+ }
+ if (spaceSelection.value === 'recents') {
+ return recentsList.value
+ }
if (spaceSelection.value === 'mine') {
return kbs.value.map(kb => ({ ...kb, isMine: true as const }))
}
@@ -797,8 +894,12 @@ interface UploadSummary {
const fetchList = () => {
loading.value = true
+ // The creator filter only applies to the caller's own tenant KBs (the
+ // first call). Shared KBs are inherently "not mine" so we don't filter
+ // them server-side; the segmented control is also hidden whenever the
+ // user is browsing the shared / per-space scopes.
return Promise.all([
- listKnowledgeBases().then((res: any) => {
+ listKnowledgeBases({ creator: creatorFilter.value }).then((res: any) => {
const data = res.data || []
// 格式化时间,并初始化 showMore 状态
// is_processing 字段由后端返回
@@ -821,7 +922,15 @@ const fetchList = () => {
// 选中空间时请求该空间内全部知识库(含我共享的)
watch(spaceSelection, (val) => {
- if (val === 'all' || val === 'mine' || val === 'shared' || !val) {
+ // Stale URL guard: an older "协作" view used scope=shared; that view
+ // was removed, so normalize back to "all" instead of letting the
+ // value fall through to the per-space fetch branch (which would 404
+ // on the string "shared").
+ if (val === 'shared') {
+ spaceSelection.value = 'all'
+ return
+ }
+ if (val === 'all' || val === 'mine' || val === 'favorites' || val === 'recents' || !val) {
spaceKbsList.value = []
return
}
@@ -838,14 +947,23 @@ watch(spaceSelection, (val) => {
})
}, { immediate: true })
+// Refetch when the creator filter flips. We re-pull the whole list rather
+// than filtering in-memory so the server stays the single source of truth
+// (and we don't need to worry about stale share_count or pagination later).
+watch(creatorFilter, () => {
+ fetchList()
+})
+
onMounted(() => {
fetchList().then(() => {
// 检查路由参数中是否有需要高亮的知识库ID
const highlightKbId = route.query.highlightKbId as string
if (highlightKbId) {
triggerHighlightFlash(highlightKbId)
- // 清除 URL 中的查询参数
- router.replace({ query: {} })
+ // Drop the transient highlight param but preserve other state
+ // (scope / creator / q) so refreshing doesn't reset the user's view.
+ const { highlightKbId: _drop, ...rest } = route.query
+ router.replace({ query: rest })
}
})
@@ -873,7 +991,8 @@ onUnmounted(() => {
watch(() => route.query.highlightKbId, (newKbId) => {
if (newKbId && typeof newKbId === 'string' && kbs.value.length > 0) {
triggerHighlightFlash(newKbId)
- router.replace({ query: {} })
+ const { highlightKbId: _drop, ...rest } = route.query
+ router.replace({ query: rest })
}
})
@@ -968,12 +1087,14 @@ const handleShareSuccess = () => {
}
const handleSharedKbClick = (sharedKb: SharedKnowledgeBase) => {
+ pins.touchRecent('kb', sharedKb.knowledge_base.id)
// 跳转到共享知识库详情页
router.push(`/platform/knowledge-bases/${sharedKb.knowledge_base.id}`)
}
// 处理"全部"Tab 中的共享知识库卡片点击(直接进入知识库)
const handleSharedKbClickFromAll = (kb: any) => {
+ pins.touchRecent('kb', kb.id)
router.push(`/platform/knowledge-bases/${kb.id}`)
}
@@ -1152,6 +1273,9 @@ const ensureUploadTaskEntry = (detail?: UploadEventDetail) => {
}
const handleCardClick = (kb: KB) => {
+ // Track this open in the per-user "recent" list before navigating —
+ // matches the user mental model "this is what I last worked on".
+ pins.touchRecent('kb', kb.id)
if (isInitialized(kb)) {
goDetail(kb.id)
} else {
@@ -1159,6 +1283,15 @@ const handleCardClick = (kb: KB) => {
}
}
+// toggleFavoriteKb is the click handler for the star icon rendered on
+// each card. Stops propagation so it doesn't bubble into the card's
+// own @click which would open the KB.
+const toggleFavoriteKb = (kbId: string, evt?: Event) => {
+ evt?.stopPropagation()
+ pins.toggleFavorite('kb', kbId)
+}
+const isKbFavorited = (kbId: string) => pins.isFavorite('kb', kbId)
+
const goDetail = (id: string) => {
router.push(`/platform/knowledge-bases/${id}`)
}
@@ -1180,8 +1313,8 @@ const handleKBEditorSuccess = (kbId: string) => {
// 如果是从路由参数中获取的高亮ID,触发闪烁效果
if (route.query.highlightKbId === kbId) {
triggerHighlightFlash(kbId)
- // 清除 URL 中的查询参数
- router.replace({ query: {} })
+ const { highlightKbId: _drop, ...rest } = route.query
+ router.replace({ query: rest })
}
})
}
@@ -1553,6 +1686,7 @@ const handleUploadFinishedEvent = (event: Event) => {
}
}
+
.warning-banner {
display: flex;
align-items: center;
@@ -1780,6 +1914,40 @@ const handleUploadFinishedEvent = (event: Event) => {
opacity: 0.7;
}
+ .kb-favorite-star {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ z-index: 2;
+ width: 24px;
+ height: 24px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: none;
+ border-radius: 6px;
+ color: var(--td-text-color-secondary);
+ cursor: pointer;
+ opacity: 0;
+ transition: opacity 0.15s ease, background 0.15s ease, color 0.15s ease;
+
+ &:hover {
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-warning-color, #e37318);
+ }
+
+ &.is-favorited {
+ opacity: 1;
+ color: var(--td-warning-color, #e37318);
+ }
+ }
+
+ // Reveal the star on card hover; favorited state forces it visible.
+ &:hover .kb-favorite-star {
+ opacity: 1;
+ }
+
// 确保内容在装饰之上
.card-header,
.card-content,
diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vue
index dea2c7c70..fed5efbf0 100644
--- a/frontend/src/views/settings/Settings.vue
+++ b/frontend/src/views/settings/Settings.vue
@@ -26,7 +26,7 @@
'expanded': expandedMenus.includes(item.key)
}]" @click="handleNavClick(item)">
<!-- 网络搜索使用自定义 SVG 图标 -->
- <svg v-if="item.key === 'websearch'" width="18" height="18" viewBox="0 0 18 18" fill="none"
+ <svg v-if="item.key === 'websearch'" width="17" height="17" viewBox="0 0 18 18" fill="none"
xmlns="http://www.w3.org/2000/svg" class="nav-icon">
<circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="1.2" fill="none" />
<path d="M 9 2 A 3.5 7 0 0 0 9 16" stroke="currentColor" stroke-width="1.2" fill="none" />
@@ -37,7 +37,7 @@
stroke-linecap="round" />
</svg>
<!-- WeKnora Cloud 使用自定义 W 图标 -->
- <svg v-else-if="item.key === 'weknoracloud'" width="18" height="18" viewBox="0 0 18 18"
+ <svg v-else-if="item.key === 'weknoracloud'" width="17" height="17" viewBox="0 0 18 18"
fill="none" xmlns="http://www.w3.org/2000/svg" class="nav-icon">
<rect x="1.5" y="1.5" width="15" height="15" rx="3.5" stroke="currentColor" stroke-width="1.2"
fill="none" />
@@ -285,12 +285,33 @@ const navItems = computed(() => {
const navGroups = computed<NavGroup[]>(() => {
const itemMap = new Map(navItems.value.map((item) => [item.key, item]))
const pickItems = (keys: string[]) => keys.map((key) => itemMap.get(key)).filter(Boolean) as NavItem[]
+ // 分组:空间与账户 → 模型 → 扩展 → 引擎 → 平台(文案见 i18n settings.navGroups)
return [
- { key: 'basic', label: t('settings.navGroups.basic'), items: pickItems(['general']) },
- { key: 'ai', label: t('settings.navGroups.ai'), items: pickItems(['models', 'ollama', 'weknoracloud', 'websearch', 'mcp']) },
- { key: 'data', label: t('settings.navGroups.data'), items: pickItems(['vectorstore', 'parser', 'storage']) },
- { key: 'workspace', label: t('settings.navGroups.workspace'), items: pickItems(['userprofile', 'tenant', 'members']) },
- { key: 'system', label: t('settings.navGroups.system'), items: pickItems(['chathistory', 'system', 'api']) },
+ {
+ key: 'workspace_account',
+ label: t('settings.navGroups.workspaceAccount'),
+ items: pickItems(['general', 'userprofile', 'tenant', 'members']),
+ },
+ {
+ key: 'models_runtime',
+ label: t('settings.navGroups.modelsRuntime'),
+ items: pickItems(['models', 'ollama', 'weknoracloud']),
+ },
+ {
+ key: 'integrations',
+ label: t('settings.navGroups.integrations'),
+ items: pickItems(['websearch', 'mcp']),
+ },
+ {
+ key: 'knowledge_infra',
+ label: t('settings.navGroups.knowledgeInfra'),
+ items: pickItems(['vectorstore', 'parser', 'storage']),
+ },
+ {
+ key: 'platform',
+ label: t('settings.navGroups.platform'),
+ items: pickItems(['chathistory', 'system', 'api']),
+ },
].filter((group) => group.items.length > 0)
})
@@ -468,9 +489,9 @@ onUnmounted(() => {
overflow: hidden;
}
-/* 左侧导航栏 */
+/* 左侧导航栏:略紧凑于最初版,字号与留白适中 */
.settings-sidebar {
- width: 220px;
+ width: 208px;
background-color: var(--td-bg-color-settings-modal);
border-right: 1px solid var(--td-component-stroke);
flex-shrink: 0;
@@ -480,24 +501,24 @@ onUnmounted(() => {
}
.sidebar-header {
- padding: 24px 16px 16px;
+ padding: 18px 14px 14px;
border-bottom: 1px solid var(--td-component-stroke);
}
.sidebar-title {
- font-size: 18px;
+ font-size: 17px;
font-weight: 600;
color: var(--td-text-color-primary);
margin: 0;
}
.settings-nav {
- padding: 12px 8px 16px;
+ padding: 10px 8px 14px;
flex: 1;
}
.nav-group-title {
- padding: 12px 16px 6px;
+ padding: 10px 14px 5px;
color: var(--td-text-color-placeholder);
font-size: 12px;
font-weight: 600;
@@ -507,11 +528,11 @@ onUnmounted(() => {
.nav-item {
display: flex;
align-items: center;
- padding: 8px 16px;
+ padding: 7px 12px;
margin-bottom: 2px;
border-radius: 6px;
cursor: pointer;
- color: var(--td-text-color-secondary);
+ color: var(--td-text-color-primary);
font-size: 14px;
transition: all 0.2s ease;
user-select: none;
@@ -529,8 +550,8 @@ onUnmounted(() => {
}
.nav-icon {
- margin-right: 12px;
- font-size: 18px;
+ margin-right: 10px;
+ font-size: 17px;
display: flex;
align-items: center;
justify-content: center;
@@ -550,17 +571,17 @@ onUnmounted(() => {
/* 子菜单 */
.submenu {
- margin-left: 32px;
- margin-bottom: 4px;
+ margin-left: 28px;
+ margin-bottom: 3px;
overflow: hidden;
}
.submenu-item {
- padding: 8px 16px;
+ padding: 6px 12px;
margin-bottom: 2px;
border-radius: 4px;
cursor: pointer;
- color: var(--td-text-color-secondary);
+ color: var(--td-text-color-primary);
font-size: 13px;
transition: all 0.2s ease;
user-select: none;
diff --git a/internal/application/repository/user_resource_favorite.go b/internal/application/repository/user_resource_favorite.go
new file mode 100644
index 000000000..a2ee49290
--- /dev/null
+++ b/internal/application/repository/user_resource_favorite.go
@@ -0,0 +1,80 @@
+package repository
+
+import (
+ "context"
+ "errors"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "gorm.io/gorm"
+)
+
+type userResourceFavoriteRepository struct {
+ db *gorm.DB
+}
+
+// NewUserResourceFavoriteRepository constructs the GORM-backed implementation.
+func NewUserResourceFavoriteRepository(db *gorm.DB) interfaces.UserResourceFavoriteRepository {
+ return &userResourceFavoriteRepository{db: db}
+}
+
+func (r *userResourceFavoriteRepository) List(
+ ctx context.Context, userID string, tenantID uint64, resourceType string,
+) ([]*types.UserResourceFavorite, error) {
+ var list []*types.UserResourceFavorite
+ err := r.db.WithContext(ctx).
+ Where("user_id = ? AND tenant_id = ? AND resource_type = ?", userID, tenantID, resourceType).
+ Order("created_at DESC").
+ Find(&list).Error
+ return list, err
+}
+
+// Add upserts the favorite. We rely on the composite primary key + GORM's
+// FirstOrCreate to make the insertion idempotent — concurrent double-clicks
+// from the same user collapse into one row with no error path needed.
+// `created` reflects whether the row was newly inserted vs already present.
+func (r *userResourceFavoriteRepository) Add(
+ ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string,
+) (bool, error) {
+ rec := &types.UserResourceFavorite{
+ UserID: userID,
+ TenantID: tenantID,
+ ResourceType: resourceType,
+ ResourceID: resourceID,
+ }
+ res := r.db.WithContext(ctx).Where(rec).FirstOrCreate(rec)
+ if res.Error != nil {
+ return false, res.Error
+ }
+ return res.RowsAffected > 0, nil
+}
+
+func (r *userResourceFavoriteRepository) Remove(
+ ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string,
+) (bool, error) {
+ res := r.db.WithContext(ctx).
+ Where("user_id = ? AND tenant_id = ? AND resource_type = ? AND resource_id = ?",
+ userID, tenantID, resourceType, resourceID).
+ Delete(&types.UserResourceFavorite{})
+ if res.Error != nil {
+ return false, res.Error
+ }
+ return res.RowsAffected > 0, nil
+}
+
+func (r *userResourceFavoriteRepository) IsFavorite(
+ ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string,
+) (bool, error) {
+ var rec types.UserResourceFavorite
+ err := r.db.WithContext(ctx).
+ Where("user_id = ? AND tenant_id = ? AND resource_type = ? AND resource_id = ?",
+ userID, tenantID, resourceType, resourceID).
+ First(&rec).Error
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return false, nil
+ }
+ return false, err
+ }
+ return true, nil
+}
diff --git a/internal/application/service/user_resource_favorite.go b/internal/application/service/user_resource_favorite.go
new file mode 100644
index 000000000..8dda07826
--- /dev/null
+++ b/internal/application/service/user_resource_favorite.go
@@ -0,0 +1,64 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// Sentinel errors so the handler can map cleanly to HTTP status codes
+// without leaking GORM internals.
+var (
+ ErrFavoriteInvalidType = errors.New("invalid favorite resource type")
+ ErrFavoriteEmptyID = errors.New("favorite resource id is required")
+)
+
+type userResourceFavoriteService struct {
+ repo interfaces.UserResourceFavoriteRepository
+}
+
+// NewUserResourceFavoriteService wraps the repository with input
+// validation (allowlist of resource types, non-empty resource id).
+// We keep service thin on purpose — favoriting is a non-business action
+// that doesn't need audit logging or cross-aggregate side effects.
+func NewUserResourceFavoriteService(repo interfaces.UserResourceFavoriteRepository) interfaces.UserResourceFavoriteService {
+ return &userResourceFavoriteService{repo: repo}
+}
+
+func (s *userResourceFavoriteService) List(
+ ctx context.Context, userID string, tenantID uint64, resourceType string,
+) ([]*types.UserResourceFavorite, error) {
+ if !types.IsValidFavoriteResourceType(resourceType) {
+ return nil, ErrFavoriteInvalidType
+ }
+ return s.repo.List(ctx, userID, tenantID, resourceType)
+}
+
+func (s *userResourceFavoriteService) Add(
+ ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string,
+) error {
+ if !types.IsValidFavoriteResourceType(resourceType) {
+ return ErrFavoriteInvalidType
+ }
+ if strings.TrimSpace(resourceID) == "" {
+ return ErrFavoriteEmptyID
+ }
+ _, err := s.repo.Add(ctx, userID, tenantID, resourceType, resourceID)
+ return err
+}
+
+func (s *userResourceFavoriteService) Remove(
+ ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string,
+) error {
+ if !types.IsValidFavoriteResourceType(resourceType) {
+ return ErrFavoriteInvalidType
+ }
+ if strings.TrimSpace(resourceID) == "" {
+ return ErrFavoriteEmptyID
+ }
+ _, err := s.repo.Remove(ctx, userID, tenantID, resourceType, resourceID)
+ return err
+}
diff --git a/internal/container/container.go b/internal/container/container.go
index 64aed70e1..f6a99b7f3 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -155,6 +155,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(repository.NewKBShareRepository))
must(container.Provide(repository.NewAgentShareRepository))
must(container.Provide(repository.NewTenantDisabledSharedAgentRepository))
+ must(container.Provide(repository.NewUserResourceFavoriteRepository))
must(container.Provide(service.NewWebSearchStateService))
must(container.Provide(repository.NewDataSourceRepository))
must(container.Provide(repository.NewSyncLogRepository))
@@ -197,6 +198,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewMCPServiceService))
must(container.Provide(service.NewMCPToolApprovalService))
must(container.Provide(service.NewCustomAgentService))
+ must(container.Provide(service.NewUserResourceFavoriteService))
must(container.Provide(memoryService.NewMemoryService))
must(container.Provide(service.NewWikiPageService))
must(container.Provide(service.NewWikiLogEntryService))
@@ -310,6 +312,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewWebSearchProviderHandler))
must(container.Provide(handler.NewVectorStoreHandler))
must(container.Provide(handler.NewCustomAgentHandler))
+ must(container.Provide(handler.NewUserResourceFavoriteHandler))
must(container.Provide(service.NewSkillService))
must(container.Provide(handler.NewSkillHandler))
must(container.Provide(handler.NewOrganizationHandler))
diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go
index 136bc047c..18ffc329a 100644
--- a/internal/handler/custom_agent.go
+++ b/internal/handler/custom_agent.go
@@ -165,6 +165,34 @@ func (h *CustomAgentHandler) ListAgents(c *gin.Context) {
return
}
+ // Optional creator filter — see the matching block in
+ // KnowledgeBaseHandler.ListKnowledgeBases for rationale. Built-in
+ // agents (IsBuiltin=true, CreatedBy="") are tenant-level fixtures
+ // rather than user creations; we always keep them regardless of the
+ // filter so the conversation dropdown never silently loses
+ // quick-answer / smart-reasoning when a user picks "Created by me".
+ creatorFilter := strings.ToLower(strings.TrimSpace(c.Query("creator")))
+ if creatorFilter == "mine" || creatorFilter == "others" {
+ callerUserID, _ := c.Get(types.UserIDContextKey.String())
+ callerUserIDStr, _ := callerUserID.(string)
+ filtered := make([]*types.CustomAgent, 0, len(agents))
+ for _, ag := range agents {
+ if ag.IsBuiltin {
+ filtered = append(filtered, ag)
+ continue
+ }
+ if ag.CreatedBy == "" {
+ continue
+ }
+ if creatorFilter == "mine" && ag.CreatedBy == callerUserIDStr {
+ filtered = append(filtered, ag)
+ } else if creatorFilter == "others" && ag.CreatedBy != callerUserIDStr {
+ filtered = append(filtered, ag)
+ }
+ }
+ agents = filtered
+ }
+
// Per-tenant "disabled by me" for own agents (only affects this tenant's conversation dropdown)
tenantIDVal, exists := c.Get(types.TenantIDContextKey.String())
if !exists {
diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.go
index 08717c537..5b4462081 100644
--- a/internal/handler/knowledgebase.go
+++ b/internal/handler/knowledgebase.go
@@ -503,6 +503,32 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
return
}
+ // Optional creator filter — drives the [All | Mine | Others] segmented
+ // control on the list page. We filter in-process rather than pushing
+ // down into SQL because the tenant-bounded KB list is small (typically
+ // <100 rows) and adding a creator predicate to ListKnowledgeBases would
+ // ripple through every other caller (chat pipeline, agent editor, …).
+ // Rows with empty CreatorID predate the RBAC migration (PR 5); we treat
+ // them as "not anyone in particular" so they never appear under "mine"
+ // or "others" — they fall out of both filters cleanly.
+ creatorFilter := strings.ToLower(strings.TrimSpace(c.Query("creator")))
+ if creatorFilter == "mine" || creatorFilter == "others" {
+ callerUserID, _ := c.Get(types.UserIDContextKey.String())
+ callerUserIDStr, _ := callerUserID.(string)
+ filtered := make([]*types.KnowledgeBase, 0, len(kbs))
+ for _, kb := range kbs {
+ if kb.CreatorID == "" {
+ continue
+ }
+ if creatorFilter == "mine" && kb.CreatorID == callerUserIDStr {
+ filtered = append(filtered, kb)
+ } else if creatorFilter == "others" && kb.CreatorID != callerUserIDStr {
+ filtered = append(filtered, kb)
+ }
+ }
+ kbs = filtered
+ }
+
// Get share counts for all knowledge bases
if len(kbs) > 0 && h.kbShareService != nil {
kbIDs := make([]string, len(kbs))
diff --git a/internal/handler/user_resource_favorite.go b/internal/handler/user_resource_favorite.go
new file mode 100644
index 000000000..d76baef5b
--- /dev/null
+++ b/internal/handler/user_resource_favorite.go
@@ -0,0 +1,144 @@
+package handler
+
+import (
+ stderrors "errors"
+ "net/http"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+)
+
+// UserResourceFavoriteHandler exposes the per-user starred-resource API.
+//
+// Authorization model: a user can only manipulate *their own* favorites in
+// the tenant they're currently scoped into (TenantIDContextKey from the
+// auth middleware). Cross-user or cross-tenant access is not allowed —
+// callers cannot pass a user_id or tenant_id query param. This matches
+// the data-model rationale: favorites are personal navigation aids, not
+// shareable resources, so there's no value in admin-style listing.
+type UserResourceFavoriteHandler struct {
+ service interfaces.UserResourceFavoriteService
+}
+
+func NewUserResourceFavoriteHandler(svc interfaces.UserResourceFavoriteService) *UserResourceFavoriteHandler {
+ return &UserResourceFavoriteHandler{service: svc}
+}
+
+// favoriteContext resolves the (userID, tenantID) pair the handler will
+// scope all queries to. Centralised so the three endpoints stay short
+// and consistent in their error shape.
+func favoriteContext(c *gin.Context) (string, uint64, bool) {
+ uidVal, ok := c.Get(types.UserIDContextKey.String())
+ if !ok {
+ c.Error(apperrors.NewUnauthorizedError("user ID not found"))
+ return "", 0, false
+ }
+ userID, _ := uidVal.(string)
+ if userID == "" {
+ c.Error(apperrors.NewUnauthorizedError("user ID not found"))
+ return "", 0, false
+ }
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ if tenantID == 0 {
+ c.Error(apperrors.NewUnauthorizedError("tenant ID not found"))
+ return "", 0, false
+ }
+ return userID, tenantID, true
+}
+
+// ListFavorites godoc
+// @Summary List my favorites
+// @Description Lists this user's starred resources in the current tenant for a given type
+// @Tags User
+// @Param type query string true "Resource type (kb | agent)"
+// @Success 200 {object} map[string]interface{}
+// @Router /user/favorites [get]
+func (h *UserResourceFavoriteHandler) ListFavorites(c *gin.Context) {
+ ctx := c.Request.Context()
+ userID, tenantID, ok := favoriteContext(c)
+ if !ok {
+ return
+ }
+ resourceType := c.Query("type")
+
+ list, err := h.service.List(ctx, userID, tenantID, resourceType)
+ if err != nil {
+ if stderrors.Is(err, service.ErrFavoriteInvalidType) {
+ c.Error(apperrors.NewBadRequestError(err.Error()))
+ return
+ }
+ logger.ErrorWithFields(ctx, err, nil)
+ c.Error(apperrors.NewInternalServerError(err.Error()))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": list})
+}
+
+// AddFavoriteRequest is the body for POST /user/favorites — kept symmetric
+// with the DELETE path parameters so the frontend can build a single API
+// helper that switches verb on toggle.
+type AddFavoriteRequest struct {
+ ResourceType string `json:"type"`
+ ResourceID string `json:"id"`
+}
+
+// AddFavorite godoc
+// @Summary Star a resource
+// @Tags User
+// @Param body body AddFavoriteRequest true "Type + id"
+// @Success 200 {object} map[string]interface{}
+// @Router /user/favorites [post]
+func (h *UserResourceFavoriteHandler) AddFavorite(c *gin.Context) {
+ ctx := c.Request.Context()
+ userID, tenantID, ok := favoriteContext(c)
+ if !ok {
+ return
+ }
+ var req AddFavoriteRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.Error(apperrors.NewBadRequestError("invalid request body").WithDetails(err.Error()))
+ return
+ }
+ if err := h.service.Add(ctx, userID, tenantID, req.ResourceType, req.ResourceID); err != nil {
+ if stderrors.Is(err, service.ErrFavoriteInvalidType) || stderrors.Is(err, service.ErrFavoriteEmptyID) {
+ c.Error(apperrors.NewBadRequestError(err.Error()))
+ return
+ }
+ logger.ErrorWithFields(ctx, err, nil)
+ c.Error(apperrors.NewInternalServerError(err.Error()))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
+
+// RemoveFavorite godoc
+// @Summary Unstar a resource
+// @Tags User
+// @Param type path string true "Resource type"
+// @Param id path string true "Resource id"
+// @Success 200 {object} map[string]interface{}
+// @Router /user/favorites/{type}/{id} [delete]
+func (h *UserResourceFavoriteHandler) RemoveFavorite(c *gin.Context) {
+ ctx := c.Request.Context()
+ userID, tenantID, ok := favoriteContext(c)
+ if !ok {
+ return
+ }
+ resourceType := c.Param("type")
+ resourceID := c.Param("id")
+
+ if err := h.service.Remove(ctx, userID, tenantID, resourceType, resourceID); err != nil {
+ if stderrors.Is(err, service.ErrFavoriteInvalidType) || stderrors.Is(err, service.ErrFavoriteEmptyID) {
+ c.Error(apperrors.NewBadRequestError(err.Error()))
+ return
+ }
+ logger.ErrorWithFields(ctx, err, nil)
+ c.Error(apperrors.NewInternalServerError(err.Error()))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
diff --git a/internal/router/router.go b/internal/router/router.go
index d448ce5fa..3b6041f55 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -72,6 +72,7 @@ type RouterParams struct {
FAQHandler *handler.FAQHandler
TagHandler *handler.TagHandler
CustomAgentHandler *handler.CustomAgentHandler
+ UserFavoriteHandler *handler.UserResourceFavoriteHandler
SkillHandler *handler.SkillHandler
OrganizationHandler *handler.OrganizationHandler
IMHandler *handler.IMHandler
@@ -191,6 +192,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterWebSearchProviderRoutes(v1, params.WebSearchProviderHandler, params.WebSearchCredentialsHandler, rbacGuards)
RegisterVectorStoreRoutes(v1, params.VectorStoreHandler, rbacGuards)
RegisterCustomAgentRoutes(v1, params.CustomAgentHandler, rbacGuards)
+ RegisterUserFavoriteRoutes(v1, params.UserFavoriteHandler, rbacGuards)
RegisterSkillRoutes(v1, params.SkillHandler, rbacGuards)
RegisterOrganizationRoutes(v1, params.OrganizationHandler, rbacGuards)
RegisterIMChannelRoutes(v1, params.IMHandler, rbacGuards)
@@ -804,6 +806,22 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA
r.GET("/agents/:id/suggested-questions", g.Viewer(), agentHandler.GetSuggestedQuestions)
}
+// RegisterUserFavoriteRoutes wires the per-user starred-resource endpoints.
+//
+// Authorization: the handler always derives (user_id, tenant_id) from the
+// auth context — there is no admin-style "see another user's favorites"
+// path — so a Viewer floor is the right gate. The endpoints intentionally
+// don't follow the OwnedXOrAdmin pattern: favorites aren't owned by the
+// resource's creator, they're owned by the user *doing* the starring.
+func RegisterUserFavoriteRoutes(r *gin.RouterGroup, h *handler.UserResourceFavoriteHandler, g *rbacGuards) {
+ favs := r.Group("/user/favorites")
+ {
+ favs.GET("", g.Viewer(), h.ListFavorites)
+ favs.POST("", g.Viewer(), h.AddFavorite)
+ favs.DELETE("/:type/:id", g.Viewer(), h.RemoveFavorite)
+ }
+}
+
// RegisterSkillRoutes registers skill routes.
//
// PR 2 currently only exposes a read-only `ListSkills`; gated to
diff --git a/internal/types/interfaces/user_resource_favorite.go b/internal/types/interfaces/user_resource_favorite.go
new file mode 100644
index 000000000..a4bba8b18
--- /dev/null
+++ b/internal/types/interfaces/user_resource_favorite.go
@@ -0,0 +1,33 @@
+package interfaces
+
+import (
+ "context"
+
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// UserResourceFavoriteRepository is the storage contract for per-user
+// favorited resources. Implementations are expected to be tenant-aware
+// (queries always include tenant_id) so a user switching tenants sees
+// only that tenant's favorites — matches the PK shape in migration 000047.
+type UserResourceFavoriteRepository interface {
+ // List returns favorites for (userID, tenantID, resourceType), newest first.
+ List(ctx context.Context, userID string, tenantID uint64, resourceType string) ([]*types.UserResourceFavorite, error)
+ // Add upserts a favorite (no-op if already present). Returns whether
+ // a new row was actually inserted so the service layer can decide
+ // whether to emit an audit event.
+ Add(ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string) (created bool, err error)
+ // Remove deletes a favorite; returns whether anything was deleted.
+ Remove(ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string) (removed bool, err error)
+ // IsFavorite exists for the rare RPC where the caller wants a single
+ // boolean rather than the full list (e.g. a future GET-by-id endpoint).
+ IsFavorite(ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string) (bool, error)
+}
+
+// UserResourceFavoriteService wraps the repository with input validation
+// (resource type allowlist, non-empty id) so the handler stays thin.
+type UserResourceFavoriteService interface {
+ List(ctx context.Context, userID string, tenantID uint64, resourceType string) ([]*types.UserResourceFavorite, error)
+ Add(ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string) error
+ Remove(ctx context.Context, userID string, tenantID uint64, resourceType, resourceID string) error
+}
diff --git a/internal/types/user_resource_favorite.go b/internal/types/user_resource_favorite.go
new file mode 100644
index 000000000..a0d5ee6a7
--- /dev/null
+++ b/internal/types/user_resource_favorite.go
@@ -0,0 +1,41 @@
+package types
+
+import "time"
+
+// Resource type constants for UserResourceFavorite. Extensible — adding a
+// new favoritable resource is just a new constant string + a frontend hook,
+// no schema change required.
+const (
+ ResourceTypeKB = "kb"
+ ResourceTypeAgent = "agent"
+)
+
+// UserResourceFavorite is a per-(user, tenant) star on a single resource.
+// See migration 000047 for the schema rationale (composite key, no FK,
+// tenant-scoped on purpose).
+type UserResourceFavorite struct {
+ UserID string `json:"user_id" gorm:"type:varchar(36);primaryKey"`
+ TenantID uint64 `json:"tenant_id" gorm:"primaryKey"`
+ ResourceType string `json:"resource_type" gorm:"type:varchar(16);primaryKey"`
+ ResourceID string `json:"resource_id" gorm:"type:varchar(64);primaryKey"`
+ CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
+}
+
+// TableName pins the table to the migration's exact name so GORM's
+// pluraliser doesn't drift if we ever rename the struct.
+func (UserResourceFavorite) TableName() string {
+ return "user_resource_favorites"
+}
+
+// IsValidFavoriteResourceType returns true for resource types this product
+// currently supports favoriting. The handler validates against this list
+// to keep clients from inserting arbitrary strings (which would balloon
+// the table and break the frontend's segmented view).
+func IsValidFavoriteResourceType(t string) bool {
+ switch t {
+ case ResourceTypeKB, ResourceTypeAgent:
+ return true
+ default:
+ return false
+ }
+}
diff --git a/migrations/sqlite/000000_init.down.sql b/migrations/sqlite/000000_init.down.sql
index b503a722c..72ea402cf 100644
--- a/migrations/sqlite/000000_init.down.sql
+++ b/migrations/sqlite/000000_init.down.sql
@@ -1,3 +1,4 @@
+DROP TABLE IF EXISTS user_resource_favorites;
DROP TABLE IF EXISTS tenant_disabled_shared_agents;
DROP TABLE IF EXISTS agent_shares;
DROP TABLE IF EXISTS organization_join_requests;
diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql
index f95ca3b7d..1e37a80e4 100644
--- a/migrations/sqlite/000000_init.up.sql
+++ b/migrations/sqlite/000000_init.up.sql
@@ -299,6 +299,22 @@ CREATE INDEX IF NOT EXISTS idx_audit_logs_tenant_action
CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at
ON audit_logs(created_at);
+-- user_resource_favorites — sqlite mirror of migration 000047. Same
+-- composite PK (user_id, tenant_id, resource_type, resource_id) so the
+-- GORM model and FirstOrCreate idempotency carry over.
+CREATE TABLE IF NOT EXISTS user_resource_favorites (
+ user_id VARCHAR(36) NOT NULL,
+ tenant_id INTEGER NOT NULL,
+ resource_type VARCHAR(16) NOT NULL,
+ resource_id VARCHAR(64) NOT NULL,
+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (user_id, tenant_id, resource_type, resource_id)
+);
+CREATE INDEX IF NOT EXISTS idx_user_resource_favorites_user_tenant_type_created_at
+ ON user_resource_favorites(user_id, tenant_id, resource_type, created_at DESC);
+CREATE INDEX IF NOT EXISTS idx_user_resource_favorites_tenant_id
+ ON user_resource_favorites(tenant_id);
+
CREATE TABLE IF NOT EXISTS knowledge_tags (
id VARCHAR(36) PRIMARY KEY,
tenant_id INTEGER NOT NULL,
diff --git a/migrations/versioned/000047_user_resource_favorites.down.sql b/migrations/versioned/000047_user_resource_favorites.down.sql
new file mode 100644
index 000000000..48f4482d4
--- /dev/null
+++ b/migrations/versioned/000047_user_resource_favorites.down.sql
@@ -0,0 +1,8 @@
+-- Reverse of 000047_user_resource_favorites.
+DO $$ BEGIN RAISE NOTICE '[Migration 000047] Dropping table: user_resource_favorites'; END $$;
+
+DROP INDEX IF EXISTS idx_user_resource_favorites_tenant_id;
+DROP INDEX IF EXISTS idx_user_resource_favorites_user_tenant_type_created_at;
+DROP TABLE IF EXISTS user_resource_favorites;
+
+DO $$ BEGIN RAISE NOTICE '[Migration 000047] user_resource_favorites table dropped'; END $$;
diff --git a/migrations/versioned/000047_user_resource_favorites.up.sql b/migrations/versioned/000047_user_resource_favorites.up.sql
new file mode 100644
index 000000000..d26411499
--- /dev/null
+++ b/migrations/versioned/000047_user_resource_favorites.up.sql
@@ -0,0 +1,43 @@
+-- Migration: 000047_user_resource_favorites
+-- Per-(user, tenant) starred resources (knowledge bases and custom agents).
+--
+-- Why (user_id, tenant_id) instead of (user_id) alone:
+-- A user can be a member of multiple tenants with very different
+-- resource sets; a KB called "design specs" in tenant A is not the
+-- same thing as "design specs" in tenant B and the user almost
+-- certainly wants to star them independently. Scoping by tenant also
+-- simplifies cleanup: drop a tenant -> drop its favorites cleanly via
+-- the (tenant_id) index without orphaning rows.
+--
+-- Why a single table instead of one per resource_type:
+-- Adding "favorite a mcp tool" or "favorite a wiki page" later is a
+-- new constant string, not a new schema migration. The PK includes
+-- resource_type so different types with colliding ids can coexist.
+--
+-- No FK to knowledge_bases / custom_agents:
+-- Favorites survive across share revocations / re-grants and across
+-- the eventual soft-delete -> hard-delete window. Hydrating with a
+-- LEFT JOIN at read time is cheap (<= ~30 rows per user) and lets us
+-- silently drop entries for resources the user can no longer see.
+DO $$ BEGIN RAISE NOTICE '[Migration 000047] Creating table: user_resource_favorites'; END $$;
+
+CREATE TABLE IF NOT EXISTS user_resource_favorites (
+ user_id VARCHAR(36) NOT NULL,
+ tenant_id BIGINT NOT NULL,
+ resource_type VARCHAR(16) NOT NULL, -- 'kb' | 'agent' (extensible)
+ resource_id VARCHAR(64) NOT NULL,
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (user_id, tenant_id, resource_type, resource_id)
+);
+
+-- Primary read path: "list this user's favorites of this type in this
+-- tenant, newest first". The PK already covers (user_id, tenant_id, …)
+-- equality, but we want created_at DESC ordering without a sort step.
+CREATE INDEX IF NOT EXISTS idx_user_resource_favorites_user_tenant_type_created_at
+ ON user_resource_favorites (user_id, tenant_id, resource_type, created_at DESC);
+
+-- Cleanup path when a tenant is deleted: bulk DELETE WHERE tenant_id = ?
+CREATE INDEX IF NOT EXISTS idx_user_resource_favorites_tenant_id
+ ON user_resource_favorites (tenant_id);
+
+DO $$ BEGIN RAISE NOTICE '[Migration 000047] user_resource_favorites table ready'; END $$;