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(api): enhance organization shared knowledge base and agent functionalities

wizardchen9a073d62bfe0
diff --git a/frontend/src/api/organization/index.ts b/frontend/src/api/organization/index.ts
index 41baf4e52..86ada70e6 100644
--- a/frontend/src/api/organization/index.ts
+++ b/frontend/src/api/organization/index.ts
@@ -74,6 +74,21 @@ export interface SharedKnowledgeBase {
shared_at: string
}
+/** When set, this KB is visible in the space via a shared agent (read-only, no direct KB share) */
+export interface SourceFromAgentInfo {
+ agent_id: string
+ agent_name: string
+ /** "all" | "selected" | "none" — for showing agent's KB strategy in the drawer */
+ kb_selection_mode?: string
+}
+
+/** Item from GET /organizations/:id/shared-knowledge-bases (space-scoped list including mine and agent-carried) */
+export type OrganizationSharedKnowledgeBaseItem = SharedKnowledgeBase & {
+ is_mine: boolean
+ /** Present when the KB is from a shared agent's config (not directly shared to the space) */
+ source_from_agent?: SourceFromAgentInfo
+}
+
export interface OrganizationPreview {
id: string
name: string
@@ -245,6 +260,9 @@ export interface SharedAgentInfo {
disabled_by_me?: boolean
}
+/** Item from GET /organizations/:id/shared-agents (space-scoped list including mine) */
+export type OrganizationSharedAgentItem = SharedAgentInfo & { is_mine: boolean }
+
export interface ListAgentSharesResponse {
shares: AgentShareResponse[]
total: number
@@ -554,6 +572,18 @@ export async function listSharedKnowledgeBases(): Promise<ApiResponse<SharedKnow
}
}
+/**
+ * List all knowledge bases in an organization (including those shared by current tenant), for list page when a space is selected.
+ */
+export async function listOrganizationSharedKnowledgeBases(orgId: string): Promise<ApiResponse<OrganizationSharedKnowledgeBaseItem[]>> {
+ try {
+ const response = await get(`/api/v1/organizations/${orgId}/shared-knowledge-bases`)
+ return response as unknown as ApiResponse<OrganizationSharedKnowledgeBaseItem[]>
+ } catch (error: any) {
+ return { success: false, message: error.message || 'Failed to list organization shared knowledge bases' }
+ }
+}
+
/**
* List knowledge bases shared to a specific organization
*/
@@ -612,6 +642,37 @@ export async function listSharedAgents(): Promise<ApiResponse<SharedAgentInfo[]>
}
}
+/** Response of GET /me/resource-counts: per-org counts for sidebar (one request instead of N). */
+export interface MeResourceCountsResponse {
+ knowledge_bases: { by_organization: Record<string, number> }
+ agents: { by_organization: Record<string, number> }
+}
+
+/**
+ * Get per-organization resource counts for list sidebar (one request).
+ * 全部 total is not included; frontend keeps 全部 = 我的 + 他人共享给我.
+ */
+export async function getMeResourceCounts(): Promise<ApiResponse<MeResourceCountsResponse>> {
+ try {
+ const response = await get('/api/v1/me/resource-counts')
+ return response as unknown as ApiResponse<MeResourceCountsResponse>
+ } catch (error: any) {
+ return { success: false, message: error.message || 'Failed to get resource counts' }
+ }
+}
+
+/**
+ * List all agents in an organization (including those shared by current tenant), for list page when a space is selected.
+ */
+export async function listOrganizationSharedAgents(orgId: string): Promise<ApiResponse<OrganizationSharedAgentItem[]>> {
+ try {
+ const response = await get(`/api/v1/organizations/${orgId}/shared-agents`)
+ return response as unknown as ApiResponse<OrganizationSharedAgentItem[]>
+ } catch (error: any) {
+ return { success: false, message: error.message || 'Failed to list organization shared agents' }
+ }
+}
+
/** 设置当前用户对某共享智能体的停用状态(仅影响本人对话下拉显示) */
export async function setSharedAgentDisabledByMe(
agentId: string,
diff --git a/frontend/src/components/AgentShareSettings.vue b/frontend/src/components/AgentShareSettings.vue
index 150c8db99..1094654b1 100644
--- a/frontend/src/components/AgentShareSettings.vue
+++ b/frontend/src/components/AgentShareSettings.vue
@@ -51,7 +51,7 @@
{{ org.share_count ?? 0 }}
</span>
<span class="org-meta-tag">
- <t-icon name="control-platform" class="org-meta-icon org-meta-icon-agent" />
+ <img src="@/assets/img/agent.svg" class="org-meta-icon org-meta-icon-agent" alt="" aria-hidden="true" />
{{ org.agent_share_count ?? 0 }}
</span>
</div>
@@ -107,7 +107,7 @@
</span>
<t-tooltip :content="$t('organization.share.spaceAgentShareCountTip')" placement="top">
<span class="org-meta-tag">
- <t-icon name="control-platform" class="org-meta-icon org-meta-icon-agent" />
+ <img src="@/assets/img/agent.svg" class="org-meta-icon org-meta-icon-agent" alt="" aria-hidden="true" />
{{ getOrgForShare(share.organization_id)?.agent_share_count ?? 0 }}
</span>
</t-tooltip>
@@ -378,7 +378,8 @@ defineExpose({ loadShares })
opacity: 0.75;
}
.org-meta-icon-agent {
- font-size: 12px;
+ width: 12px;
+ height: 12px;
opacity: 0.75;
}
}
@@ -491,7 +492,8 @@ defineExpose({ loadShares })
opacity: 0.75;
}
.org-meta-icon-agent {
- font-size: 12px;
+ width: 12px;
+ height: 12px;
opacity: 0.75;
}
}
diff --git a/frontend/src/components/ListSpaceSidebar.vue b/frontend/src/components/ListSpaceSidebar.vue
index cb88110d8..891feb3b6 100644
--- a/frontend/src/components/ListSpaceSidebar.vue
+++ b/frontend/src/components/ListSpaceSidebar.vue
@@ -7,8 +7,9 @@
</div>
</div>
<nav class="sidebar-nav">
- <!-- 全部 -->
+ <!-- 全部:仅组织模式显示;知识库/智能体列表不展示「全部」 -->
<div
+ v-if="mode !== 'resource'"
class="sidebar-item"
:class="{ active: selected === 'all' }"
@click="select('all')"
@@ -32,12 +33,12 @@
</div>
<span v-if="countMine !== undefined" class="item-count">{{ countMine }}</span>
</div>
- <template v-if="organizations.length">
+ <template v-if="organizationsWithCount.length">
<div class="sidebar-section">
<span class="section-title">{{ $t('listSpaceSidebar.spaces') }}</span>
</div>
<div
- v-for="org in organizations"
+ v-for="org in organizationsWithCount"
:key="org.id"
class="sidebar-item org-item"
:class="{ active: selected === org.id }"
@@ -117,6 +118,12 @@ const selected = computed({
const organizations = computed(() => orgStore.organizations || [])
+/** 资源模式下只展示数量大于 0 的空间 */
+const organizationsWithCount = computed(() => {
+ if (props.mode !== 'resource') return organizations.value
+ return organizations.value.filter((org) => (props.countByOrg?.[org.id] ?? 0) > 0)
+})
+
function select(value: string) {
selected.value = value
}
diff --git a/frontend/src/components/MentionSelector.vue b/frontend/src/components/MentionSelector.vue
index 0908a4d69..40a9086aa 100644
--- a/frontend/src/components/MentionSelector.vue
+++ b/frontend/src/components/MentionSelector.vue
@@ -61,6 +61,9 @@
{{ detailCache[item.id].data.org_name || item.orgName }}
</span>
</span>
+ <span v-if="agentIdForDetail && (detailCache[item.id].data.org_name || item.orgName)" class="detail-readonly-hint">
+ {{ $t('mentionDetail.readOnlyFromAgent') }}
+ </span>
</div>
</template>
</div>
@@ -509,6 +512,14 @@ const scrollToItem = (index: number) => {
gap: 6px;
align-items: flex-start;
}
+.mention-detail-content .detail-readonly-hint {
+ display: block;
+ margin-top: 6px;
+ font-size: var(--td-font-size-mark-small, 12px);
+ color: var(--td-text-color-placeholder, #999);
+ font-style: italic;
+}
+
.mention-detail-content .detail-org,
.mention-detail-content .detail-kb {
display: inline-flex;
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 19409fcb3..0b166eedf 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -917,6 +917,7 @@ export default {
noResult: 'No results',
},
mentionDetail: {
+ readOnlyFromAgent: 'Read-only in this conversation; not shown in Knowledge Base list',
faqCount: '{count} Q&A entries',
kbCount: '{count} documents',
belongsToKb: 'Knowledge base: ',
@@ -1115,6 +1116,8 @@ export default {
sharedToOrgs: 'Shared to {count} space(s)',
sharedLabel: 'Shared',
myLabel: 'Mine',
+ fromAgent: 'From agent {name}',
+ fromAgentShort: 'Agent: {name}',
tabs: {
all: 'All',
myKnowledgeBases: 'My Knowledge Bases',
@@ -1145,7 +1148,15 @@ export default {
overviewDesc: 'View knowledge base information and source',
permission: 'Permission',
permissionDesc: 'View your permissions for this knowledge base',
- sourceOrg: 'Source Space',
+ sourceType: 'Source',
+ sourceTypeKbShare: 'KB shared directly to this space',
+ sourceTypeAgent: 'Visible via shared agent',
+ sourceOrg: 'Space',
+ sourceFromAgent: 'Agent',
+ agentKbStrategy: 'Agent KB strategy',
+ agentKbStrategyAll: 'All knowledge bases',
+ agentKbStrategySelected: 'Selected knowledge bases',
+ agentKbStrategyNone: 'No knowledge bases',
sharedAt: 'Shared At',
myPermission: 'My Permission',
canEdit: 'Can edit knowledge base content',
@@ -2531,6 +2542,8 @@ export default {
sharedAgents: 'Shared Agents',
noSharedAgents: 'No shared agents yet',
sharedAgentsDesc: 'Agents shared to this space; members can use them in chat',
+ sharedAgentsKbHint: 'Knowledge bases linked to an agent are only available (read-only) when members use that agent in a conversation (via @). They do not appear in the Knowledge Base list. To let members see or edit a knowledge base in the list, share that knowledge base to this space separately.',
+ sharedAgentsKbHintShort: 'Agent-linked knowledge is read-only in chat; share the KB to this space if members should see or edit it in the list.',
noSharedAgentsTip: 'Admins can share agents to this space from agent settings',
sharePermissionLabel: 'Space permission',
myPermissionLabel: 'My actual permission',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 27d713d51..151fb8f1b 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -759,6 +759,7 @@ export default {
kbCount: "共 {count} 个文档",
belongsToKb: "所属知识库:",
belongsToOrg: "所属空间:",
+ readOnlyFromAgent: "仅在此对话中只读,不显示在知识库列表中",
},
agent: {
taskLabel: "任务:",
@@ -1507,6 +1508,8 @@ export default {
sharedToOrgs: "已共享给 {count} 个空间",
sharedLabel: "共享",
myLabel: "我的",
+ fromAgent: "来自智能体 {name}",
+ fromAgentShort: "智能体: {name}",
tabs: {
all: "全部",
myKnowledgeBases: "我的知识库",
@@ -1534,7 +1537,15 @@ export default {
overviewDesc: "查看知识库基本信息和来源",
permission: "权限",
permissionDesc: "查看您在此知识库的操作权限",
+ sourceType: "来源方式",
+ sourceTypeKbShare: "知识库直接共享到本空间",
+ sourceTypeAgent: "智能体可访问(通过共享智能体可见)",
sourceOrg: "来源空间",
+ sourceFromAgent: "智能体",
+ agentKbStrategy: "智能体知识库策略",
+ agentKbStrategyAll: "全部知识库",
+ agentKbStrategySelected: "指定知识库",
+ agentKbStrategyNone: "不使用知识库",
sharedAt: "共享时间",
myPermission: "我的权限",
canEdit: "可以编辑知识库内容",
@@ -2536,6 +2547,8 @@ export default {
sharedAgents: "共享智能体",
noSharedAgents: "暂无共享的智能体",
sharedAgentsDesc: "已共享到本空间的智能体,成员可在对话中使用",
+ sharedAgentsKbHint: "智能体绑定的知识库仅在成员使用该智能体对话时可 @ 使用(只读),不会出现在「知识库列表」中。若需成员在列表中看到或编辑知识库,请单独将知识库共享到本空间。",
+ sharedAgentsKbHintShort: "智能体绑定知识仅对话内只读;需在列表看到或编辑请单独共享知识库",
noSharedAgentsTip: "管理员可将智能体从智能体设置中共享到本空间",
sharePermissionLabel: "空间权限",
myPermissionLabel: "我的实际权限",
diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vue
index 2e03c1980..683c819de 100644
--- a/frontend/src/views/agent/AgentList.vue
+++ b/frontend/src/views/agent/AgentList.vue
@@ -14,7 +14,7 @@
v-model="spaceSelection"
:count-all="allAgentsCount"
:count-mine="agents.length"
- :count-by-org="sharedCountByOrg"
+ :count-by-org="effectiveSharedCountByOrg"
>
<template #actions>
<t-tooltip :content="$t('agent.createAgent')" placement="top">
@@ -304,17 +304,20 @@
</div>
</div>
- <!-- 按空间筛选:该空间下共享给我的智能体 -->
- <div v-if="spaceSelectionOrgId && sharedAgentsByOrg.length > 0" class="agent-card-wrap">
+ <!-- 按空间筛选:该空间内全部智能体(含我共享的) -->
+ <div v-if="spaceSelectionOrgId && spaceAgentsLoading" class="agent-list-main-loading">
+ <t-loading size="large" text="" />
+ </div>
+ <div v-else-if="spaceSelectionOrgId && spaceAgentsList.length > 0" class="agent-card-wrap">
<div
- v-for="shared in sharedAgentsByOrg"
+ v-for="shared in spaceAgentsList"
:key="'shared-' + shared.share_id"
class="agent-card shared-agent-card"
:class="{
'agent-mode-normal': shared.agent?.config?.agent_mode === 'quick-answer',
'agent-mode-agent': shared.agent?.config?.agent_mode === 'smart-reasoning'
}"
- @click="openSharedAgentDetail(shared)"
+ @click="handleSpaceAgentCardClick(shared)"
>
<div class="card-decoration">
<svg class="star-icon" width="24" height="24" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
@@ -329,8 +332,10 @@
<div v-if="shared.agent?.avatar" class="builtin-avatar agent-emoji">{{ shared.agent.avatar }}</div>
<AgentAvatar v-else :name="shared.agent?.name" size="small" />
<span class="card-title" :title="shared.agent?.name">{{ shared.agent?.name }}</span>
+ <span v-if="shared.is_mine" class="shared-by-me-badge">{{ $t('listSpaceSidebar.mine') }}</span>
</div>
<t-popup
+ v-if="!shared.is_mine"
:visible="openMoreAgentId === 'shared-tab-' + shared.share_id"
trigger="hover"
overlayClassName="card-more-popup"
@@ -422,8 +427,8 @@
<span>{{ $t('agent.createAgent') }}</span>
</t-button>
</div>
- <!-- 空状态:空间下共享给我 -->
- <div v-if="spaceSelectionOrgId && sharedAgentsByOrg.length === 0 && !loading" class="empty-state">
+ <!-- 空状态:空间下 -->
+ <div v-if="spaceSelectionOrgId && !spaceAgentsLoading && spaceAgentsList.length === 0" class="empty-state">
<img class="empty-img" src="@/assets/img/upload.svg" alt="">
<span class="empty-txt">{{ $t('agent.empty.sharedTitle') }}</span>
<span class="empty-desc">{{ $t('agent.empty.sharedDescription') }}</span>
@@ -527,7 +532,7 @@
</template>
<script setup lang="ts">
-import { computed, onMounted, onUnmounted, ref } from 'vue'
+import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'
import { listAgents, deleteAgent, copyAgent, type CustomAgent } from '@/api/agent'
@@ -535,10 +540,10 @@ import { formatStringDate } from '@/utils/index'
import { useI18n } from 'vue-i18n'
import { createSessions } from '@/api/chat/index'
import { useOrganizationStore } from '@/stores/organization'
-import { setSharedAgentDisabledByMe } from '@/api/organization'
+import { setSharedAgentDisabledByMe, listOrganizationSharedAgents, getMeResourceCounts } from '@/api/organization'
import { useSettingsStore } from '@/stores/settings'
import { useMenuStore } from '@/stores/menu'
-import type { SharedAgentInfo } from '@/api/organization'
+import type { SharedAgentInfo, OrganizationSharedAgentItem } from '@/api/organization'
import AgentEditorModal from './AgentEditorModal.vue'
import AgentAvatar from '@/components/AgentAvatar.vue'
import ListSpaceSidebar from '@/components/ListSpaceSidebar.vue'
@@ -557,7 +562,8 @@ interface AgentWithUI extends CustomAgent {
/** Merged agent for "all" tab: my agents (isMine: true) or shared (isMine: false, org_name, source_tenant_id, share_id, disabled_by_me?) */
type DisplayAgent = (AgentWithUI & { isMine: true }) | (CustomAgent & { isMine: false; org_name: string; source_tenant_id: number; share_id: string; showMore?: boolean; disabled_by_me?: boolean })
-const spaceSelection = ref<'all' | 'mine' | string>('all')
+// 左侧空间选择:我的 / 空间 ID(已去掉「全部」)
+const spaceSelection = ref<'all' | 'mine' | string>('mine')
const agents = ref<AgentWithUI[]>([])
const sharedAgents = computed<SharedAgentInfo[]>(() => orgStore.sharedAgents || [])
const allAgentsCount = computed(() => agents.value.length + sharedAgents.value.length)
@@ -573,7 +579,12 @@ const sharedAgentsByOrg = computed(() => {
return sharedAgents.value.filter(s => s.organization_id === orgId)
})
-// 各空间下的共享智能体数量(用于侧栏展示,含 0 的也显示)
+// 空间视角:该空间内全部智能体(含我共享的),选中空间时请求新接口
+const spaceAgentsList = ref<OrganizationSharedAgentItem[]>([])
+const spaceAgentsLoading = ref(false)
+const spaceAgentCountByOrg = ref<Record<string, number>>({})
+
+// 各空间下的共享智能体数量(用于侧栏展示):优先用接口返回的该空间总数
const sharedCountByOrg = computed<Record<string, number>>(() => {
const map: Record<string, number> = {}
sharedAgents.value.forEach(s => {
@@ -586,6 +597,14 @@ const sharedCountByOrg = computed<Record<string, number>>(() => {
})
return map
})
+const effectiveSharedCountByOrg = computed<Record<string, number>>(() => {
+ const base = sharedCountByOrg.value
+ const merged = { ...base }
+ Object.keys(spaceAgentCountByOrg.value).forEach(orgId => {
+ merged[orgId] = spaceAgentCountByOrg.value[orgId]
+ })
+ return merged
+})
const filteredAgents = computed<DisplayAgent[]>(() => {
if (spaceSelection.value === 'mine') {
@@ -652,8 +671,16 @@ const fetchList = () => {
}))
checkAndOpenEditModal()
}),
- orgStore.fetchSharedAgents()
- ]).finally(() => loading.value = false)
+ orgStore.fetchSharedAgents(),
+ orgStore.fetchOrganizations()
+ ]).finally(() => { loading.value = false }).then(() => {
+ // 一次请求拉取各空间内全部智能体数量(含我共享的),用于侧栏展示
+ getMeResourceCounts().then((res) => {
+ if (res.success && res.data?.agents?.by_organization) {
+ spaceAgentCountByOrg.value = { ...res.data.agents.by_organization }
+ }
+ })
+ })
}
// 检查 URL 参数并打开编辑模态框
@@ -680,6 +707,25 @@ const handleOpenAgentEditor = (event: CustomEvent) => {
}
}
+// 选中空间时请求该空间内全部智能体(含我共享的)
+watch(spaceSelection, (val) => {
+ if (val === 'all' || val === 'mine' || !val) {
+ spaceAgentsList.value = []
+ return
+ }
+ spaceAgentsLoading.value = true
+ listOrganizationSharedAgents(val).then((res) => {
+ if (res.success && res.data) {
+ spaceAgentsList.value = res.data
+ spaceAgentCountByOrg.value = { ...spaceAgentCountByOrg.value, [val]: res.data.length }
+ } else {
+ spaceAgentsList.value = []
+ }
+ }).finally(() => {
+ spaceAgentsLoading.value = false
+ })
+}, { immediate: true })
+
onMounted(() => {
fetchList()
window.addEventListener('openAgentEditor', handleOpenAgentEditor as EventListener)
@@ -715,6 +761,15 @@ function openSharedAgentDetail(shared: SharedAgentInfo) {
sharedDetailVisible.value = true
}
+/** 空间视角下点击卡片:我共享的进编辑,他人共享的打开详情抽屉 */
+function handleSpaceAgentCardClick(shared: OrganizationSharedAgentItem) {
+ if (shared.is_mine && shared.agent) {
+ handleEdit({ ...shared.agent, showMore: false, disabled_by_me: shared.disabled_by_me } as AgentWithUI)
+ } else {
+ openSharedAgentDetail(shared)
+ }
+}
+
function closeSharedAgentDetail() {
sharedDetailVisible.value = false
currentSharedAgent.value = null
@@ -907,6 +962,26 @@ defineExpose({
background: #fafbfc;
}
+.agent-list-main-loading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 200px;
+ padding: 12px;
+ background: #fafbfc;
+}
+
+.shared-by-me-badge {
+ display: inline-flex;
+ align-items: center;
+ padding: 2px 6px;
+ background: rgba(7, 192, 95, 0.1);
+ border-radius: 4px;
+ font-size: 12px;
+ color: #07c05f;
+ margin-left: 6px;
+}
+
.header {
display: flex;
align-items: center;
diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue
index cb351cd43..027c640ac 100644
--- a/frontend/src/views/knowledge/KnowledgeBase.vue
+++ b/frontend/src/views/knowledge/KnowledgeBase.vue
@@ -64,10 +64,13 @@ const currentSharedKb = computed(() =>
orgStore.sharedKnowledgeBases.find((s) => s.knowledge_base?.id === kbId.value) ?? null,
);
+// Effective permission: from direct org share list or from GET /knowledge-bases/:id (e.g. agent-visible KB)
+const effectiveKBPermission = computed(() => orgStore.getKBPermission(kbId.value) || kbInfo.value?.my_permission || '');
+
// Display role label: owner or org role (admin/editor/viewer)
const accessRoleLabel = computed(() => {
if (isOwner.value) return t('knowledgeBase.accessInfo.roleOwner');
- const perm = orgStore.getKBPermission(kbId.value);
+ const perm = effectiveKBPermission.value;
if (perm) return t(`organization.role.${perm}`);
return '--';
});
@@ -75,7 +78,7 @@ const accessRoleLabel = computed(() => {
// Permission summary text for current role
const accessPermissionSummary = computed(() => {
if (isOwner.value) return t('knowledgeBase.accessInfo.permissionOwner');
- const perm = orgStore.getKBPermission(kbId.value);
+ const perm = effectiveKBPermission.value;
if (perm === 'admin') return t('knowledgeBase.accessInfo.permissionAdmin');
if (perm === 'editor') return t('knowledgeBase.accessInfo.permissionEditor');
if (perm === 'viewer') return t('knowledgeBase.accessInfo.permissionViewer');
@@ -1190,7 +1193,7 @@ async function createNewSession(value: string): Promise<void> {
<div v-if="kbInfo" class="kb-access-meta">
<t-tooltip :content="accessPermissionSummary" placement="top">
<span class="kb-access-meta-inner">
- <t-tag size="small" :theme="isOwner ? 'success' : (currentSharedKb?.permission === 'admin' ? 'primary' : currentSharedKb?.permission === 'editor' ? 'warning' : 'default')" class="kb-access-role-tag">
+ <t-tag size="small" :theme="isOwner ? 'success' : (effectiveKBPermission === 'admin' ? 'primary' : effectiveKBPermission === 'editor' ? 'warning' : 'default')" class="kb-access-role-tag">
{{ accessRoleLabel }}
</t-tag>
<template v-if="currentSharedKb">
@@ -1200,6 +1203,10 @@ async function createNewSession(value: string): Promise<void> {
{{ $t('knowledgeBase.accessInfo.sharedAt') }} {{ formatStringDate(new Date(currentSharedKb.shared_at)) }}
</span>
</template>
+ <template v-else-if="effectiveKBPermission">
+ <span class="kb-access-meta-sep">·</span>
+ <span class="kb-access-meta-text">{{ $t('knowledgeList.detail.sourceTypeAgent') }}</span>
+ </template>
<template v-else-if="kbLastUpdated">
<span class="kb-access-meta-sep">·</span>
<span class="kb-access-meta-text">{{ $t('knowledgeBase.accessInfo.lastUpdated') }} {{ kbLastUpdated }}</span>
diff --git a/frontend/src/views/knowledge/KnowledgeBaseList.vue b/frontend/src/views/knowledge/KnowledgeBaseList.vue
index 949d1a40a..b6be08cd9 100644
--- a/frontend/src/views/knowledge/KnowledgeBaseList.vue
+++ b/frontend/src/views/knowledge/KnowledgeBaseList.vue
@@ -14,7 +14,7 @@
v-model="spaceSelection"
:count-all="allKnowledgeBases"
:count-mine="kbs.length"
- :count-by-org="sharedCountByOrg"
+ :count-by-org="effectiveSharedCountByOrg"
>
<template #actions>
<t-tooltip :content="$t('knowledgeList.create')" placement="top">
@@ -340,11 +340,14 @@
</div>
</div>
- <!-- 按空间筛选:该空间下共享给我的知识库 -->
- <div v-if="spaceSelectionOrgId && sharedKbsByOrg.length > 0" class="kb-card-wrap">
+ <!-- 按空间筛选:该空间内全部知识库(含我共享的) -->
+ <div v-if="spaceSelectionOrgId && spaceKbsLoading" class="kb-list-main-loading">
+ <t-loading size="large" text="" />
+ </div>
+ <div v-else-if="spaceSelectionOrgId && spaceKbsList.length > 0" class="kb-card-wrap">
<div
- v-for="shared in sharedKbsByOrg"
- :key="'shared-' + shared.share_id"
+ v-for="shared in spaceKbsList"
+ :key="'shared-' + (shared.share_id || `agent-${shared.knowledge_base?.id}-${shared.source_from_agent?.agent_id || ''}`)"
class="kb-card shared-kb-card"
:class="{
'kb-type-document': (shared.knowledge_base.type || 'document') === 'document',
@@ -355,7 +358,10 @@
<!-- 卡片头部 -->
<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">
+ <t-tooltip v-if="shared.is_mine" :content="$t('knowledgeList.myLabel')" placement="top">
+ <span class="shared-by-me-badge">{{ $t('knowledgeList.myLabel') }}</span>
+ </t-tooltip>
+ <t-tooltip v-if="!shared.is_mine" :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>
@@ -415,8 +421,8 @@
</t-button>
</div>
- <!-- 空间下共享知识库空状态 -->
- <div v-if="spaceSelectionOrgId && sharedKbsByOrg.length === 0 && !loading" class="empty-state">
+ <!-- 空间下知识库空状态 -->
+ <div v-if="spaceSelectionOrgId && !spaceKbsLoading && spaceKbsList.length === 0" class="empty-state">
<img class="empty-img" src="@/assets/img/upload.svg" alt="">
<span class="empty-txt">{{ $t('knowledgeList.empty.sharedTitle') || '暂无共享知识库' }}</span>
<span class="empty-desc">{{ $t('knowledgeList.empty.sharedDescription') || '您可以加入组织或请求他人共享知识库给您' }}</span>
@@ -482,10 +488,22 @@
<span class="shared-detail-value">{{ currentSharedKbForDetail.knowledge_base.name }}</span>
</div>
<div class="shared-detail-row">
- <span class="shared-detail-label">{{ $t('knowledgeList.detail.sourceOrg') }}</span>
+ <span class="shared-detail-label">{{ $t('knowledgeList.detail.sourceType') }}</span>
+ <span class="shared-detail-value shared-detail-source-type">
+ {{ currentSharedKbForDetail.source_from_agent ? $t('knowledgeList.detail.sourceTypeAgent') : $t('knowledgeList.detail.sourceTypeKbShare') }}
+ </span>
+ </div>
+ <div class="shared-detail-row">
+ <span class="shared-detail-label">{{ currentSharedKbForDetail.source_from_agent ? $t('knowledgeList.detail.sourceFromAgent') : $t('knowledgeList.detail.sourceOrg') }}</span>
<span class="shared-detail-value shared-detail-org">
<img src="@/assets/img/organization-green.svg" class="shared-detail-org-icon" alt="" aria-hidden="true" />
- {{ currentSharedKbForDetail.org_name }}
+ {{ currentSharedKbForDetail.source_from_agent ? currentSharedKbForDetail.source_from_agent.agent_name : currentSharedKbForDetail.org_name }}
+ </span>
+ </div>
+ <div v-if="currentSharedKbForDetail.source_from_agent" class="shared-detail-row">
+ <span class="shared-detail-label">{{ $t('knowledgeList.detail.agentKbStrategy') }}</span>
+ <span class="shared-detail-value">
+ {{ agentKbStrategyText(currentSharedKbForDetail.source_from_agent?.kb_selection_mode ?? '') }}
</span>
</div>
<div class="shared-detail-row">
@@ -522,7 +540,7 @@ import { listKnowledgeBases, deleteKnowledgeBase } from '@/api/knowledge-base'
import { formatStringDate } from '@/utils/index'
import { useUIStore } from '@/stores/ui'
import { useOrganizationStore } from '@/stores/organization'
-import type { SharedKnowledgeBase } from '@/api/organization'
+import { listOrganizationSharedKnowledgeBases, getMeResourceCounts, type SharedKnowledgeBase, type OrganizationSharedKnowledgeBaseItem, type SourceFromAgentInfo } from '@/api/organization'
import KnowledgeBaseEditorModal from './KnowledgeBaseEditorModal.vue'
import ShareKnowledgeBaseDialog from '@/components/ShareKnowledgeBaseDialog.vue'
import ListSpaceSidebar from '@/components/ListSpaceSidebar.vue'
@@ -534,8 +552,8 @@ const uiStore = useUIStore()
const orgStore = useOrganizationStore()
const { t } = useI18n()
-// 左侧空间选择:全部 / 我的 / 空间 ID
-const spaceSelection = ref<'all' | 'mine' | string>('all')
+// 左侧空间选择:我的 / 空间 ID(已去掉「全部」)
+const spaceSelection = ref<'all' | 'mine' | string>('mine')
interface KB {
id: string;
@@ -586,14 +604,19 @@ const spaceSelectionOrgId = computed(() => {
return s !== 'all' && s !== 'mine' && !!s
})
-// 当前空间下共享给我的知识库
+// 当前空间下共享给我的知识库(旧:仅他人共享;保留用于兼容)
const sharedKbsByOrg = computed(() => {
const orgId = spaceSelection.value
if (orgId === 'all' || orgId === 'mine') return []
return sharedKbs.value.filter(s => s.organization_id === orgId)
})
-// 各空间下的共享知识库数量(用于侧栏展示,含 0 的也显示)
+// 空间视角:该空间内全部知识库(含我共享的),选中空间时请求新接口
+const spaceKbsList = ref<OrganizationSharedKnowledgeBaseItem[]>([])
+const spaceKbsLoading = ref(false)
+const spaceCountByOrg = ref<Record<string, number>>({})
+
+// 各空间下的共享知识库数量(用于侧栏展示):优先用接口返回的该空间总数,否则用「共享给我」数量
const sharedCountByOrg = computed<Record<string, number>>(() => {
const map: Record<string, number> = {}
sharedKbs.value.forEach(s => {
@@ -606,6 +629,14 @@ const sharedCountByOrg = computed<Record<string, number>>(() => {
})
return map
})
+const effectiveSharedCountByOrg = computed<Record<string, number>>(() => {
+ const base = sharedCountByOrg.value
+ const merged = { ...base }
+ Object.keys(spaceCountByOrg.value).forEach(orgId => {
+ merged[orgId] = spaceCountByOrg.value[orgId]
+ })
+ return merged
+})
// Filtered knowledge bases: 全部 = 我的 + 全部共享;我的 = 仅我的
const filteredKnowledgeBases = computed(() => {
@@ -669,10 +700,37 @@ const fetchList = () => {
processing_count: kb.processing_count || 0
}))
}),
- orgStore.fetchSharedKnowledgeBases()
- ]).finally(() => loading.value = false)
+ orgStore.fetchSharedKnowledgeBases(),
+ orgStore.fetchOrganizations()
+ ]).finally(() => { loading.value = false }).then(() => {
+ // 一次请求拉取各空间内全部知识库数量(含我共享的),用于侧栏展示
+ getMeResourceCounts().then((res) => {
+ if (res.success && res.data?.knowledge_bases?.by_organization) {
+ spaceCountByOrg.value = { ...res.data.knowledge_bases.by_organization }
+ }
+ })
+ })
}
+// 选中空间时请求该空间内全部知识库(含我共享的)
+watch(spaceSelection, (val) => {
+ if (val === 'all' || val === 'mine' || !val) {
+ spaceKbsList.value = []
+ return
+ }
+ spaceKbsLoading.value = true
+ listOrganizationSharedKnowledgeBases(val).then((res) => {
+ if (res.success && res.data) {
+ spaceKbsList.value = res.data
+ spaceCountByOrg.value = { ...spaceCountByOrg.value, [val]: res.data.length }
+ } else {
+ spaceKbsList.value = []
+ }
+ }).finally(() => {
+ spaceKbsLoading.value = false
+ })
+}, { immediate: true })
+
onMounted(() => {
fetchList().then(() => {
// 检查路由参数中是否有需要高亮的知识库ID
@@ -768,9 +826,10 @@ const handleSharedKbClickFromAll = (kb: any) => {
router.push(`/platform/knowledge-bases/${kb.id}`)
}
-// 右侧详情面板:共享知识库详情
+// 右侧详情面板:共享知识库详情(含直接共享与来自智能体的)
+type SharedKbDetailItem = SharedKnowledgeBase & { is_mine?: boolean; source_from_agent?: SourceFromAgentInfo }
const sharedDetailPanelVisible = ref(false)
-const currentSharedKbForDetail = ref<SharedKnowledgeBase | null>(null)
+const currentSharedKbForDetail = ref<SharedKbDetailItem | null>(null)
const closeSharedDetailPanel = () => {
sharedDetailPanelVisible.value = false
@@ -786,12 +845,19 @@ const openSharedDetailFromAll = (kb: any) => {
}
}
-// 打开右侧详情面板(共享给我 Tab)
-const openSharedDetail = (sharedKb: SharedKnowledgeBase) => {
+// 打开右侧详情面板(空间 Tab:直接共享或来自智能体)
+const openSharedDetail = (sharedKb: SharedKbDetailItem) => {
currentSharedKbForDetail.value = sharedKb
sharedDetailPanelVisible.value = true
}
+// 智能体对知识库的策略文案(用于抽屉「来源方式」为智能体时)
+const agentKbStrategyText = (mode: string) => {
+ if (mode === 'all') return t('knowledgeList.detail.agentKbStrategyAll')
+ if (mode === 'selected') return t('knowledgeList.detail.agentKbStrategySelected')
+ return t('knowledgeList.detail.agentKbStrategyNone')
+}
+
// 从右侧面板进入知识库
const goToSharedKbFromPanel = () => {
if (currentSharedKbForDetail.value) {
@@ -1095,6 +1161,26 @@ const handleUploadFinishedEvent = (event: Event) => {
background: #fafbfc;
}
+.kb-list-main-loading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 200px;
+ padding: 12px;
+ background: #fafbfc;
+}
+
+.shared-by-me-badge {
+ display: inline-flex;
+ align-items: center;
+ padding: 2px 6px;
+ background: rgba(7, 192, 95, 0.1);
+ border-radius: 4px;
+ font-size: 12px;
+ color: #07c05f;
+ margin-left: 6px;
+}
+
.header-subtitle {
margin: 0;
color: #00000099;
@@ -2119,6 +2205,11 @@ const handleUploadFinishedEvent = (event: Event) => {
line-height: 1.5;
word-break: break-word;
+ &.shared-detail-source-type {
+ font-weight: 500;
+ color: #0d0d0d;
+ }
+
&.shared-detail-org {
display: inline-flex;
align-items: center;
diff --git a/frontend/src/views/knowledge/components/FAQEntryManager.vue b/frontend/src/views/knowledge/components/FAQEntryManager.vue
index bafe554f4..335d42138 100644
--- a/frontend/src/views/knowledge/components/FAQEntryManager.vue
+++ b/frontend/src/views/knowledge/components/FAQEntryManager.vue
@@ -43,7 +43,7 @@
<div v-if="kbInfo" class="faq-access-meta">
<t-tooltip :content="accessPermissionSummary" placement="top">
<span class="faq-access-meta-inner">
- <t-tag size="small" :theme="isOwner ? 'success' : (currentSharedKb?.permission === 'admin' ? 'primary' : currentSharedKb?.permission === 'editor' ? 'warning' : 'default')" class="faq-access-role-tag">
+ <t-tag size="small" :theme="isOwner ? 'success' : (effectiveKBPermission === 'admin' ? 'primary' : effectiveKBPermission === 'editor' ? 'warning' : 'default')" class="faq-access-role-tag">
{{ accessRoleLabel }}
</t-tag>
<template v-if="currentSharedKb">
@@ -53,6 +53,10 @@
{{ $t('knowledgeBase.accessInfo.sharedAt') }} {{ formatImportTime(currentSharedKb.shared_at) }}
</span>
</template>
+ <template v-else-if="effectiveKBPermission">
+ <span class="faq-access-meta-sep">·</span>
+ <span class="faq-access-meta-text">{{ $t('knowledgeList.detail.sourceTypeAgent') }}</span>
+ </template>
<template v-else-if="kbLastUpdated">
<span class="faq-access-meta-sep">·</span>
<span class="faq-access-meta-text">{{ $t('knowledgeBase.accessInfo.lastUpdated') }} {{ kbLastUpdated }}</span>
@@ -1304,10 +1308,13 @@ const currentSharedKb = computed(() =>
orgStore.sharedKnowledgeBases.find((s) => s.knowledge_base?.id === props.kbId) ?? null,
)
+// Effective permission: from direct org share list or from GET /knowledge-bases/:id (e.g. agent-visible KB)
+const effectiveKBPermission = computed(() => orgStore.getKBPermission(props.kbId) || kbInfo.value?.my_permission || '')
+
// Display role label: owner or org role (admin/editor/viewer)
const accessRoleLabel = computed(() => {
if (isOwner.value) return t('knowledgeBase.accessInfo.roleOwner')
- const perm = orgStore.getKBPermission(props.kbId)
+ const perm = effectiveKBPermission.value
if (perm) return t(`organization.role.${perm}`)
return '--'
})
@@ -1315,7 +1322,7 @@ const accessRoleLabel = computed(() => {
// Permission summary text for current role
const accessPermissionSummary = computed(() => {
if (isOwner.value) return t('knowledgeBase.accessInfo.permissionOwner')
- const perm = orgStore.getKBPermission(props.kbId)
+ const perm = effectiveKBPermission.value
if (perm === 'admin') return t('knowledgeBase.accessInfo.permissionAdmin')
if (perm === 'editor') return t('knowledgeBase.accessInfo.permissionEditor')
if (perm === 'viewer') return t('knowledgeBase.accessInfo.permissionViewer')
diff --git a/frontend/src/views/knowledge/settings/KBShareSettings.vue b/frontend/src/views/knowledge/settings/KBShareSettings.vue
index 2f3414a7d..ffb6cb1f1 100644
--- a/frontend/src/views/knowledge/settings/KBShareSettings.vue
+++ b/frontend/src/views/knowledge/settings/KBShareSettings.vue
@@ -47,7 +47,7 @@
{{ org.share_count ?? 0 }}
</span>
<span class="org-meta-tag">
- <t-icon name="control-platform" class="org-meta-icon org-meta-icon-agent" />
+ <img src="@/assets/img/agent.svg" class="org-meta-icon org-meta-icon-agent" alt="" aria-hidden="true" />
{{ org.agent_share_count ?? 0 }}
</span>
</div>
@@ -122,7 +122,7 @@
{{ getOrgForShare(share.organization_id)?.share_count ?? 0 }}
</span>
<span class="org-meta-tag">
- <t-icon name="control-platform" class="org-meta-icon org-meta-icon-agent" />
+ <img src="@/assets/img/agent.svg" class="org-meta-icon org-meta-icon-agent" alt="" aria-hidden="true" />
{{ getOrgForShare(share.organization_id)?.agent_share_count ?? 0 }}
</span>
</div>
@@ -504,7 +504,8 @@ onMounted(async () => {
opacity: 0.75;
}
.org-meta-icon-agent {
- font-size: 12px;
+ width: 12px;
+ height: 12px;
opacity: 0.75;
}
}
@@ -640,7 +641,8 @@ onMounted(async () => {
opacity: 0.75;
}
.org-meta-icon-agent {
- font-size: 12px;
+ width: 12px;
+ height: 12px;
opacity: 0.75;
}
}
diff --git a/frontend/src/views/organization/OrganizationSettingsModal.vue b/frontend/src/views/organization/OrganizationSettingsModal.vue
index 9834f3b70..60a913dd9 100644
--- a/frontend/src/views/organization/OrganizationSettingsModal.vue
+++ b/frontend/src/views/organization/OrganizationSettingsModal.vue
@@ -556,6 +556,14 @@
<div class="section-header">
<h2>{{ $t('organization.settings.sharedAgents') }}</h2>
<p class="section-description">{{ $t('organization.settings.sharedAgentsDesc') }}</p>
+ <p class="section-description permission-calc-hint">
+ <t-tooltip :content="$t('organization.settings.sharedAgentsKbHint')" placement="top" :show-delay="300">
+ <span class="hint-inner">
+ <t-icon name="info-circle" size="14px" />
+ {{ $t('organization.settings.sharedAgentsKbHintShort') }}
+ </span>
+ </t-tooltip>
+ </p>
</div>
<div class="settings-group">
<div v-if="sharedAgents.length === 0" class="empty-shared">
diff --git a/internal/application/repository/agent_share.go b/internal/application/repository/agent_share.go
index 487452709..973b10e45 100644
--- a/internal/application/repository/agent_share.go
+++ b/internal/application/repository/agent_share.go
@@ -108,6 +108,7 @@ func (r *agentShareRepository) ListByOrganization(ctx context.Context, orgID str
err := r.db.WithContext(ctx).
Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
Preload("Agent").
+ Preload("Organization").
Where("agent_shares.organization_id = ? AND agent_shares.deleted_at IS NULL", orgID).
Order("agent_shares.created_at DESC").
Find(&shares).Error
@@ -117,6 +118,35 @@ func (r *agentShareRepository) ListByOrganization(ctx context.Context, orgID str
return shares, nil
}
+// CountByOrganizations returns share counts per organization (only orgs in orgIDs). Excludes deleted agents.
+func (r *agentShareRepository) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
+ if len(orgIDs) == 0 {
+ return make(map[string]int64), nil
+ }
+ type row struct {
+ OrgID string `gorm:"column:organization_id"`
+ Count int64 `gorm:"column:count"`
+ }
+ var rows []row
+ err := r.db.WithContext(ctx).Model(&types.AgentShare{}).
+ Joins("JOIN custom_agents ON custom_agents.id = agent_shares.agent_id AND custom_agents.tenant_id = agent_shares.source_tenant_id AND custom_agents.deleted_at IS NULL").
+ Select("agent_shares.organization_id as organization_id, COUNT(*) as count").
+ Where("agent_shares.organization_id IN ? AND agent_shares.deleted_at IS NULL", orgIDs).
+ Group("agent_shares.organization_id").
+ Find(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ out := make(map[string]int64)
+ for _, o := range orgIDs {
+ out[o] = 0
+ }
+ for _, r := range rows {
+ out[r.OrgID] = r.Count
+ }
+ return out, nil
+}
+
// ListSharedAgentsForUser lists all agents shared to organizations that the user belongs to
func (r *agentShareRepository) ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error) {
var shares []*types.AgentShare
diff --git a/internal/application/repository/kbshare.go b/internal/application/repository/kbshare.go
index 4323fa735..a7dda4273 100644
--- a/internal/application/repository/kbshare.go
+++ b/internal/application/repository/kbshare.go
@@ -115,6 +115,7 @@ func (r *kbShareRepository) ListByOrganization(ctx context.Context, orgID string
err := r.db.WithContext(ctx).
Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
Preload("KnowledgeBase").
+ Preload("Organization").
Where("kb_shares.organization_id = ? AND kb_shares.deleted_at IS NULL", orgID).
Order("kb_shares.created_at DESC").
Find(&shares).Error
@@ -188,3 +189,32 @@ func (r *kbShareRepository) CountSharesByKnowledgeBaseIDs(ctx context.Context, k
}
return countMap, nil
}
+
+// CountByOrganizations returns share counts per organization (only orgs in orgIDs). Excludes deleted KBs.
+func (r *kbShareRepository) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
+ if len(orgIDs) == 0 {
+ return make(map[string]int64), nil
+ }
+ type row struct {
+ OrgID string `gorm:"column:organization_id"`
+ Count int64 `gorm:"column:count"`
+ }
+ var rows []row
+ err := r.db.WithContext(ctx).Model(&types.KnowledgeBaseShare{}).
+ Joins("JOIN knowledge_bases ON knowledge_bases.id = kb_shares.knowledge_base_id AND knowledge_bases.deleted_at IS NULL").
+ Select("kb_shares.organization_id as organization_id, COUNT(*) as count").
+ Where("kb_shares.organization_id IN ? AND kb_shares.deleted_at IS NULL", orgIDs).
+ Group("kb_shares.organization_id").
+ Find(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ out := make(map[string]int64)
+ for _, o := range orgIDs {
+ out[o] = 0
+ }
+ for _, r := range rows {
+ out[r.OrgID] = r.Count
+ }
+ return out, nil
+}
diff --git a/internal/application/service/agent_share.go b/internal/application/service/agent_share.go
index 84a116997..d55ed5896 100644
--- a/internal/application/service/agent_share.go
+++ b/internal/application/service/agent_share.go
@@ -224,6 +224,81 @@ func (s *agentShareService) ListSharedAgents(ctx context.Context, userID string,
return result, nil
}
+// ListSharedAgentsInOrganization returns all agents shared to the given organization (including those shared by the current tenant), for list-page display when a space is selected.
+func (s *agentShareService) ListSharedAgentsInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedAgentItem, error) {
+ member, err := s.orgRepo.GetMember(ctx, orgID, userID)
+ if err != nil {
+ if errors.Is(err, repository.ErrOrgMemberNotFound) {
+ return nil, ErrUserNotInOrg
+ }
+ return nil, err
+ }
+
+ shares, err := s.shareRepo.ListByOrganization(ctx, orgID)
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]*types.OrganizationSharedAgentItem, 0, len(shares))
+ for _, share := range shares {
+ if share.Agent == nil {
+ continue
+ }
+
+ effectivePermission := share.Permission
+ if !member.Role.HasPermission(share.Permission) {
+ effectivePermission = member.Role
+ }
+
+ orgName := ""
+ if share.Organization != nil {
+ orgName = share.Organization.Name
+ }
+ info := &types.SharedAgentInfo{
+ Agent: share.Agent,
+ ShareID: share.ID,
+ OrganizationID: share.OrganizationID,
+ OrgName: orgName,
+ Permission: effectivePermission,
+ SourceTenantID: share.SourceTenantID,
+ SharedAt: share.CreatedAt,
+ SharedByUserID: share.SharedByUserID,
+ }
+ if share.SharedByUserID != "" {
+ if u, err := s.userRepo.GetUserByID(ctx, share.SharedByUserID); err == nil && u != nil {
+ info.SharedByUsername = u.Username
+ }
+ }
+
+ item := &types.OrganizationSharedAgentItem{
+ SharedAgentInfo: *info,
+ IsMine: share.SourceTenantID == currentTenantID,
+ }
+ result = append(result, item)
+ }
+
+ // Set DisabledByMe for entries shared by others (mine entries stay false)
+ disabledList, err := s.disabledRepo.ListByTenantID(ctx, currentTenantID)
+ if err == nil {
+ disabledSet := make(map[string]bool)
+ for _, d := range disabledList {
+ disabledSet[fmt.Sprintf("%s_%d", d.AgentID, d.SourceTenantID)] = true
+ }
+ for _, item := range result {
+ if item.Agent != nil && !item.IsMine {
+ key := fmt.Sprintf("%s_%d", item.Agent.ID, item.SourceTenantID)
+ item.DisabledByMe = disabledSet[key]
+ }
+ }
+ }
+ return result, nil
+}
+
+// CountByOrganizations returns share counts per organization (for list sidebar); excludes deleted agents
+func (s *agentShareService) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
+ return s.shareRepo.CountByOrganizations(ctx, orgIDs)
+}
+
// SetSharedAgentDisabledByMe adds or removes (tenantID, agentID, sourceTenantID) from tenant_disabled_shared_agents.
func (s *agentShareService) SetSharedAgentDisabledByMe(ctx context.Context, tenantID uint64, agentID string, sourceTenantID uint64, disabled bool) error {
if disabled {
@@ -254,6 +329,41 @@ func (s *agentShareService) GetSharedAgentForUser(ctx context.Context, userID st
return agent, nil
}
+// UserCanAccessKBViaSomeSharedAgent returns true if the user has at least one shared agent that can access the given KB (used when opening KB detail from space list without agent_id).
+func (s *agentShareService) UserCanAccessKBViaSomeSharedAgent(ctx context.Context, userID string, currentTenantID uint64, kb *types.KnowledgeBase) (bool, error) {
+ if kb == nil || kb.ID == "" {
+ return false, nil
+ }
+ list, err := s.ListSharedAgents(ctx, userID, currentTenantID)
+ if err != nil || len(list) == 0 {
+ return false, err
+ }
+ for _, info := range list {
+ if info.Agent == nil {
+ continue
+ }
+ agent := info.Agent
+ if agent.TenantID != kb.TenantID {
+ continue
+ }
+ mode := agent.Config.KBSelectionMode
+ if mode == "none" {
+ continue
+ }
+ if mode == "all" {
+ return true, nil
+ }
+ if mode == "selected" {
+ for _, id := range agent.Config.KnowledgeBases {
+ if id == kb.ID {
+ return true, nil
+ }
+ }
+ }
+ }
+ return false, nil
+}
+
// GetShare gets an agent share by ID
func (s *agentShareService) GetShare(ctx context.Context, shareID string) (*types.AgentShare, error) {
share, err := s.shareRepo.GetByID(ctx, shareID)
diff --git a/internal/application/service/kbshare.go b/internal/application/service/kbshare.go
index 68aa4e0f4..abd567b3a 100644
--- a/internal/application/service/kbshare.go
+++ b/internal/application/service/kbshare.go
@@ -289,6 +289,65 @@ func (s *kbShareService) ListSharedKnowledgeBases(ctx context.Context, userID st
return result, nil
}
+// ListSharedKnowledgeBasesInOrganization returns all knowledge bases shared to the given organization (including those shared by the current tenant), for list-page display when a space is selected.
+func (s *kbShareService) ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) {
+ member, err := s.orgRepo.GetMember(ctx, orgID, userID)
+ if err != nil {
+ if errors.Is(err, repository.ErrOrgMemberNotFound) {
+ return nil, ErrUserNotInOrg
+ }
+ return nil, err
+ }
+
+ shares, err := s.shareRepo.ListByOrganization(ctx, orgID)
+ if err != nil {
+ return nil, err
+ }
+
+ result := make([]*types.OrganizationSharedKnowledgeBaseItem, 0, len(shares))
+ for _, share := range shares {
+ if share.KnowledgeBase == nil {
+ continue
+ }
+
+ effectivePermission := share.Permission
+ if !member.Role.HasPermission(share.Permission) {
+ effectivePermission = member.Role
+ }
+
+ kb := share.KnowledgeBase
+ switch kb.Type {
+ case types.KnowledgeBaseTypeDocument:
+ if count, err := s.kgRepo.CountKnowledgeByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID); err == nil {
+ kb.KnowledgeCount = count
+ }
+ case types.KnowledgeBaseTypeFAQ:
+ if count, err := s.chunkRepo.CountChunksByKnowledgeBaseID(ctx, share.SourceTenantID, kb.ID); err == nil {
+ kb.ChunkCount = count
+ }
+ }
+
+ orgName := ""
+ if share.Organization != nil {
+ orgName = share.Organization.Name
+ }
+ item := &types.OrganizationSharedKnowledgeBaseItem{
+ SharedKnowledgeBaseInfo: types.SharedKnowledgeBaseInfo{
+ KnowledgeBase: kb,
+ ShareID: share.ID,
+ OrganizationID: share.OrganizationID,
+ OrgName: orgName,
+ Permission: effectivePermission,
+ SourceTenantID: share.SourceTenantID,
+ SharedAt: share.CreatedAt,
+ },
+ IsMine: share.SourceTenantID == currentTenantID,
+ }
+ result = append(result, item)
+ }
+ return result, nil
+}
+
// GetShare gets a share by ID
func (s *kbShareService) GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error) {
share, err := s.shareRepo.GetByID(ctx, shareID)
@@ -388,3 +447,8 @@ func (s *kbShareService) GetKBSourceTenant(ctx context.Context, kbID string) (ui
func (s *kbShareService) CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error) {
return s.shareRepo.CountSharesByKnowledgeBaseIDs(ctx, kbIDs)
}
+
+// CountByOrganizations returns share counts per organization (for list sidebar); excludes deleted KBs
+func (s *kbShareService) CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error) {
+ return s.shareRepo.CountByOrganizations(ctx, orgIDs)
+}
diff --git a/internal/handler/chunk.go b/internal/handler/chunk.go
index c90020f45..551548e2d 100644
--- a/internal/handler/chunk.go
+++ b/internal/handler/chunk.go
@@ -15,14 +15,15 @@ import (
// ChunkHandler defines HTTP handlers for chunk operations
type ChunkHandler struct {
- service interfaces.ChunkService
- kgService interfaces.KnowledgeService
- kbShareService interfaces.KBShareService
+ service interfaces.ChunkService
+ kgService interfaces.KnowledgeService
+ kbShareService interfaces.KBShareService
+ agentShareService interfaces.AgentShareService
}
// NewChunkHandler creates a new chunk handler
-func NewChunkHandler(service interfaces.ChunkService, kgService interfaces.KnowledgeService, kbShareService interfaces.KBShareService) *ChunkHandler {
- return &ChunkHandler{service: service, kgService: kgService, kbShareService: kbShareService}
+func NewChunkHandler(service interfaces.ChunkService, kgService interfaces.KnowledgeService, kbShareService interfaces.KBShareService, agentShareService interfaces.AgentShareService) *ChunkHandler {
+ return &ChunkHandler{service: service, kgService: kgService, kbShareService: kbShareService, agentShareService: agentShareService}
}
// effectiveCtxForKnowledge resolves knowledge by ID, validates KB access (owner or shared with required role), and returns context with effectiveTenantID for downstream service calls.
@@ -41,17 +42,26 @@ func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID stri
if knowledge.TenantID == tenantID {
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
}
- if !userExists || h.kbShareService == nil {
+ if !userExists {
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
}
- permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string))
- if permErr != nil || !isShared {
- return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
+ if h.kbShareService != nil {
+ permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, knowledge.KnowledgeBaseID, userID.(string))
+ if permErr == nil && isShared {
+ if !permission.HasPermission(requiredPermission) {
+ return nil, errors.NewForbiddenError("Insufficient permission for this operation")
+ }
+ return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
+ }
}
- if !permission.HasPermission(requiredPermission) {
- return nil, errors.NewForbiddenError("Insufficient permission for this operation")
+ if requiredPermission == types.OrgRoleViewer && h.agentShareService != nil {
+ kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID}
+ can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kbRef)
+ if err == nil && can {
+ return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
+ }
}
- return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
+ return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
}
// GetChunkByIDOnly godoc
diff --git a/internal/handler/faq.go b/internal/handler/faq.go
index c1a7aa392..022fcaf31 100644
--- a/internal/handler/faq.go
+++ b/internal/handler/faq.go
@@ -1,6 +1,7 @@
package handler
import (
+ "context"
"net/http"
"strconv"
@@ -15,12 +16,67 @@ import (
// FAQHandler handles FAQ knowledge base operations.
type FAQHandler struct {
- knowledgeService interfaces.KnowledgeService
+ knowledgeService interfaces.KnowledgeService
+ kbService interfaces.KnowledgeBaseService
+ kbShareService interfaces.KBShareService
+ agentShareService interfaces.AgentShareService
}
// NewFAQHandler creates a new FAQ handler
-func NewFAQHandler(knowledgeService interfaces.KnowledgeService) *FAQHandler {
- return &FAQHandler{knowledgeService: knowledgeService}
+func NewFAQHandler(
+ knowledgeService interfaces.KnowledgeService,
+ kbService interfaces.KnowledgeBaseService,
+ kbShareService interfaces.KBShareService,
+ agentShareService interfaces.AgentShareService,
+) *FAQHandler {
+ return &FAQHandler{
+ knowledgeService: knowledgeService,
+ kbService: kbService,
+ kbShareService: kbShareService,
+ agentShareService: agentShareService,
+ }
+}
+
+// effectiveCtxForKB validates KB access (owner, shared, or via shared agent when requiredPermission is Viewer) and returns context with effectiveTenantID.
+func (h *FAQHandler) effectiveCtxForKB(c *gin.Context, kbID string, requiredPermission types.OrgMemberRole) (context.Context, error) {
+ ctx := c.Request.Context()
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ if tenantID == 0 {
+ return nil, errors.NewUnauthorizedError("Unauthorized")
+ }
+ userID, userExists := c.Get(types.UserIDContextKey.String())
+ kbID = secutils.SanitizeForLog(kbID)
+ if kbID == "" {
+ return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty")
+ }
+ kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, nil)
+ return nil, errors.NewInternalServerError(err.Error())
+ }
+ if kb.TenantID == tenantID {
+ return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
+ }
+ if userExists && h.kbShareService != nil {
+ permission, isShared, permErr := h.kbShareService.CheckUserKBPermission(ctx, kbID, userID.(string))
+ if permErr == nil && isShared && permission.HasPermission(requiredPermission) {
+ sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID)
+ if srcErr == nil {
+ logger.Infof(ctx, "User %s accessing shared KB %s with permission %s, source tenant: %d",
+ userID.(string), kbID, permission, sourceTenantID)
+ return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil
+ }
+ }
+ }
+ if requiredPermission == types.OrgRoleViewer && userExists && h.agentShareService != nil {
+ can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
+ if err == nil && can {
+ logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
+ return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil
+ }
+ }
+ logger.Warnf(ctx, "Permission denied to access KB %s", kbID)
+ return nil, errors.NewForbiddenError("Permission denied to access this knowledge base")
}
// ListEntries godoc
@@ -43,6 +99,12 @@ func NewFAQHandler(knowledgeService interfaces.KnowledgeService) *FAQHandler {
// @Router /knowledge-bases/{id}/faq/entries [get]
func (h *FAQHandler) ListEntries(c *gin.Context) {
ctx := c.Request.Context()
+ kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer)
+ if err != nil {
+ c.Error(err)
+ return
+ }
var page types.Pagination
if err := c.ShouldBindQuery(&page); err != nil {
logger.Error(ctx, "Failed to bind pagination query", err)
@@ -64,7 +126,7 @@ func (h *FAQHandler) ListEntries(c *gin.Context) {
searchField := secutils.SanitizeForLog(c.Query("search_field"))
sortOrder := secutils.SanitizeForLog(c.Query("sort_order"))
- result, err := h.knowledgeService.ListFAQEntries(ctx, secutils.SanitizeForLog(c.Param("id")), &page, tagSeqID, keyword, searchField, sortOrder)
+ result, err := h.knowledgeService.ListFAQEntries(effCtx, kbID, &page, tagSeqID, keyword, searchField, sortOrder)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
@@ -94,6 +156,12 @@ func (h *FAQHandler) ListEntries(c *gin.Context) {
// @Router /knowledge-bases/{id}/faq/entries [post]
func (h *FAQHandler) UpsertEntries(c *gin.Context) {
ctx := c.Request.Context()
+ kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
+ if err != nil {
+ c.Error(err)
+ return
+ }
var req types.FAQBatchUpsertPayload
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ upsert payload", err)
@@ -101,10 +169,8 @@ func (h *FAQHandler) UpsertEntries(c *gin.Context) {
return
}
- kbID := secutils.SanitizeForLog(c.Param("id"))
-
// 统一使用 UpsertFAQEntries,通过 DryRun 字段区分模式
- taskID, err := h.knowledgeService.UpsertFAQEntries(ctx, kbID, &req)
+ taskID, err := h.knowledgeService.UpsertFAQEntries(effCtx, kbID, &req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
@@ -134,6 +200,12 @@ func (h *FAQHandler) UpsertEntries(c *gin.Context) {
// @Router /knowledge-bases/{id}/faq/entry [post]
func (h *FAQHandler) CreateEntry(c *gin.Context) {
ctx := c.Request.Context()
+ kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
+ if err != nil {
+ c.Error(err)
+ return
+ }
var req types.FAQEntryPayload
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry payload", err)
@@ -141,7 +213,7 @@ func (h *FAQHandler) CreateEntry(c *gin.Context) {
return
}
- entry, err := h.knowledgeService.CreateFAQEntry(ctx, secutils.SanitizeForLog(c.Param("id")), &req)
+ entry, err := h.knowledgeService.CreateFAQEntry(effCtx, kbID, &req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
@@ -170,6 +242,12 @@ func (h *FAQHandler) CreateEntry(c *gin.Context) {
// @Router /knowledge-bases/{id}/faq/entries/{entry_id} [put]
func (h *FAQHandler) UpdateEntry(c *gin.Context) {
ctx := c.Request.Context()
+ kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
+ if err != nil {
+ c.Error(err)
+ return
+ }
var req types.FAQEntryPayload
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry payload", err)
@@ -183,8 +261,8 @@ func (h *FAQHandler) UpdateEntry(c *gin.Context) {
return
}
- entry, err := h.knowledgeService.UpdateFAQEntry(ctx,
- secutils.SanitizeForLog(c.Param("id")), entrySeqID, &req)
+ entry, err := h.knowledgeService.UpdateFAQEntry(effCtx,
+ kbID, entrySeqID, &req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
@@ -212,14 +290,20 @@ func (h *FAQHandler) UpdateEntry(c *gin.Context) {
// @Router /knowledge-bases/{id}/faq/entries/tags [put]
func (h *FAQHandler) UpdateEntryTagBatch(c *gin.Context) {
ctx := c.Request.Context()
+ kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
+ if err != nil {
+ c.Error(err)
+ return
+ }
var req faqEntryTagBatchRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry tag batch payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
- if err := h.knowledgeService.UpdateFAQEntryTagBatch(ctx,
- secutils.SanitizeForLog(c.Param("id")), req.Updates); err != nil {
+ if err := h.knowledgeService.UpdateFAQEntryTagBatch(effCtx,
+ kbID, req.Updates); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
@@ -244,14 +328,20 @@ func (h *FAQHandler) UpdateEntryTagBatch(c *gin.Context) {
// @Router /knowledge-bases/{id}/faq/entries/fields [put]
func (h *FAQHandler) UpdateEntryFieldsBatch(c *gin.Context) {
ctx := c.Request.Context()
+ kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
+ if err != nil {
+ c.Error(err)
+ return
+ }
var req types.FAQEntryFieldsBatchUpdate
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry fields batch payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
- if err := h.knowledgeService.UpdateFAQEntryFieldsBatch(ctx,
- secutils.SanitizeForLog(c.Param("id")), &req); err != nil {
+ if err := h.knowledgeService.UpdateFAQEntryFieldsBatch(effCtx,
+ kbID, &req); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
@@ -292,6 +382,12 @@ type addSimilarQuestionsRequest struct {
// @Router /knowledge-bases/{id}/faq/entries [delete]
func (h *FAQHandler) DeleteEntries(c *gin.Context) {
ctx := c.Request.Context()
+ kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
+ if err != nil {
+ c.Error(err)
+ return
+ }
var req faqDeleteRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Errorf(ctx, "Failed to bind FAQ delete payload: %s", secutils.SanitizeForLog(err.Error()))
@@ -299,8 +395,8 @@ func (h *FAQHandler) DeleteEntries(c *gin.Context) {
return
}
- if err := h.knowledgeService.DeleteFAQEntries(ctx,
- secutils.SanitizeForLog(c.Param("id")),
+ if err := h.knowledgeService.DeleteFAQEntries(effCtx,
+ kbID,
req.IDs); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
@@ -327,6 +423,12 @@ func (h *FAQHandler) DeleteEntries(c *gin.Context) {
// @Router /knowledge-bases/{id}/faq/search [post]
func (h *FAQHandler) SearchFAQ(c *gin.Context) {
ctx := c.Request.Context()
+ kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer)
+ if err != nil {
+ c.Error(err)
+ return
+ }
var req types.FAQSearchRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ search payload", err)
@@ -340,7 +442,7 @@ func (h *FAQHandler) SearchFAQ(c *gin.Context) {
if req.MatchCount > 200 {
req.MatchCount = 200
}
- entries, err := h.knowledgeService.SearchFAQEntries(ctx, secutils.SanitizeForLog(c.Param("id")), &req)
+ entries, err := h.knowledgeService.SearchFAQEntries(effCtx, kbID, &req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
@@ -368,8 +470,13 @@ func (h *FAQHandler) SearchFAQ(c *gin.Context) {
func (h *FAQHandler) ExportEntries(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer)
+ if err != nil {
+ c.Error(err)
+ return
+ }
- csvData, err := h.knowledgeService.ExportFAQEntries(ctx, kbID)
+ csvData, err := h.knowledgeService.ExportFAQEntries(effCtx, kbID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
@@ -401,13 +508,18 @@ func (h *FAQHandler) ExportEntries(c *gin.Context) {
func (h *FAQHandler) GetEntry(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer)
+ if err != nil {
+ c.Error(err)
+ return
+ }
entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("entry_id 必须是整数"))
return
}
- entry, err := h.knowledgeService.GetFAQEntry(ctx, kbID, entrySeqID)
+ entry, err := h.knowledgeService.GetFAQEntry(effCtx, kbID, entrySeqID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
@@ -471,6 +583,11 @@ type updateLastFAQImportResultDisplayStatusRequest struct {
func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
+ if err != nil {
+ c.Error(err)
+ return
+ }
var req updateLastFAQImportResultDisplayStatusRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -479,7 +596,7 @@ func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) {
return
}
- if err := h.knowledgeService.UpdateLastFAQImportResultDisplayStatus(ctx, kbID, req.DisplayStatus); err != nil {
+ if err := h.knowledgeService.UpdateLastFAQImportResultDisplayStatus(effCtx, kbID, req.DisplayStatus); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
@@ -508,6 +625,11 @@ func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) {
func (h *FAQHandler) AddSimilarQuestions(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
+ effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor)
+ if err != nil {
+ c.Error(err)
+ return
+ }
entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)
if err != nil {
@@ -522,7 +644,7 @@ func (h *FAQHandler) AddSimilarQuestions(c *gin.Context) {
return
}
- entry, err := h.knowledgeService.AddSimilarQuestions(ctx, kbID, entrySeqID, req.SimilarQuestions)
+ entry, err := h.knowledgeService.AddSimilarQuestions(effCtx, kbID, entrySeqID, req.SimilarQuestions)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.go
index 2d02c3ad5..9e4d1c9e4 100644
--- a/internal/handler/knowledge.go
+++ b/internal/handler/knowledge.go
@@ -93,6 +93,15 @@ func (h *KnowledgeHandler) validateKnowledgeBaseAccess(c *gin.Context) (*types.K
}
}
+ // Check 3: If not owner and no direct share, allow if user has any shared agent that can access this KB (e.g. opened from "通过智能体可见" list)
+ if userExists && h.agentShareService != nil {
+ can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
+ if err == nil && can {
+ logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
+ return kb, kbID, kb.TenantID, types.OrgRoleViewer, nil
+ }
+ }
+
// No permission: not owner and no shared access
logger.Warnf(
ctx,
@@ -137,6 +146,13 @@ func (h *KnowledgeHandler) validateKnowledgeBaseAccessWithKBID(c *gin.Context, k
}
}
}
+ if userExists && h.agentShareService != nil {
+ can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
+ if err == nil && can {
+ logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
+ return kb, kbID, kb.TenantID, types.OrgRoleViewer, nil
+ }
+ }
logger.Warnf(ctx, "Permission denied to access KB %s, tenant ID: %d, KB tenant: %d", kbID, tenantID, kb.TenantID)
return nil, kbID, 0, "", errors.NewForbiddenError("Permission denied to access this knowledge base")
}
@@ -169,7 +185,7 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k
return knowledge, context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID), nil
}
}
- // Shared agent: request passes agent_id, verify user has that shared agent and the agent has access to this knowledge/KB
+ // Shared agent: request passes agent_id, or user has any shared agent that can access this KB
if userExists && h.agentShareService != nil && requiredPermission == types.OrgRoleViewer {
agentID := c.Query("agent_id")
if agentID != "" {
@@ -194,6 +210,12 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
}
}
+ } else {
+ kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID}
+ can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kbRef)
+ if err == nil && can {
+ return knowledge, context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
+ }
}
}
return nil, ctx, errors.NewForbiddenError("Permission denied to access this knowledge")
diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.go
index f22421504..f846bed25 100644
--- a/internal/handler/knowledgebase.go
+++ b/internal/handler/knowledgebase.go
@@ -197,34 +197,39 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
}
}
- // Check 3: Shared agent — request has agent_id, verify user has that shared agent and the agent has access to this KB
+ // Check 3: Shared agent — allow if request has agent_id (and agent can access this KB) OR user has any shared agent that can access this KB (e.g. opened from "通过智能体可见" list without agent_id)
if userExists && h.agentShareService != nil {
+ currentTenantID := tenantID.(uint64)
agentID := c.Query("agent_id")
if agentID != "" {
- currentTenantID := c.GetUint64(types.TenantIDContextKey.String())
- if currentTenantID != 0 {
- agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID.(string), currentTenantID, agentID)
- if err == nil && agent != nil {
- if kb.TenantID != agent.TenantID {
- logger.Warnf(ctx, "Shared agent tenant mismatch, KB %s tenant: %d, agent tenant: %d", id, kb.TenantID, agent.TenantID)
- } else {
- mode := agent.Config.KBSelectionMode
- if mode == "none" {
- // no-op, fall through to forbid
- } else if mode == "all" {
- logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=all)", userID.(string), id, agentID)
- return kb, id, kb.TenantID, types.OrgRoleViewer, nil
- } else if mode == "selected" {
- for _, allowedID := range agent.Config.KnowledgeBases {
- if allowedID == id {
- logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=selected)", userID.(string), id, agentID)
- return kb, id, kb.TenantID, types.OrgRoleViewer, nil
- }
+ agent, err := h.agentShareService.GetSharedAgentForUser(ctx, userID.(string), currentTenantID, agentID)
+ if err == nil && agent != nil {
+ if kb.TenantID != agent.TenantID {
+ logger.Warnf(ctx, "Shared agent tenant mismatch, KB %s tenant: %d, agent tenant: %d", id, kb.TenantID, agent.TenantID)
+ } else {
+ mode := agent.Config.KBSelectionMode
+ if mode == "none" {
+ // no-op, fall through
+ } else if mode == "all" {
+ logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=all)", userID.(string), id, agentID)
+ return kb, id, kb.TenantID, types.OrgRoleViewer, nil
+ } else if mode == "selected" {
+ for _, allowedID := range agent.Config.KnowledgeBases {
+ if allowedID == id {
+ logger.Infof(ctx, "User %s accessing KB %s via shared agent %s (mode=selected)", userID.(string), id, agentID)
+ return kb, id, kb.TenantID, types.OrgRoleViewer, nil
}
}
}
}
}
+ } else {
+ // No agent_id in query: allow if user has any shared agent that can access this KB (e.g. from space list "通过智能体可见")
+ can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), currentTenantID, kb)
+ if err == nil && can {
+ logger.Infof(ctx, "User %s accessing KB %s via some shared agent (no agent_id in query)", userID.(string), id)
+ return kb, id, kb.TenantID, types.OrgRoleViewer, nil
+ }
}
}
@@ -254,7 +259,7 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
// @Router /knowledge-bases/{id} [get]
func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) {
// Validate and get the knowledge base
- kb, _, _, _, err := h.validateAndGetKnowledgeBase(c)
+ kb, _, _, permission, err := h.validateAndGetKnowledgeBase(c)
if err != nil {
c.Error(err)
return
@@ -263,10 +268,19 @@ func (h *KnowledgeBaseHandler) GetKnowledgeBase(c *gin.Context) {
if fillErr := h.service.FillKnowledgeBaseCounts(c.Request.Context(), kb); fillErr != nil {
logger.Warnf(c.Request.Context(), "Failed to fill KB counts for %s: %v", kb.ID, fillErr)
}
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": kb,
- })
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+ data := interface{}(kb)
+ if kb.TenantID != tenantID && permission != "" {
+ // Include my_permission in data so frontend can show role (e.g. "只读") instead of "--" for agent-visible KBs
+ var dataMap map[string]interface{}
+ b, _ := json.Marshal(kb)
+ _ = json.Unmarshal(b, &dataMap)
+ if dataMap != nil {
+ dataMap["my_permission"] = permission
+ data = dataMap
+ }
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": data})
}
// ListKnowledgeBases godoc
diff --git a/internal/handler/organization.go b/internal/handler/organization.go
index dc813fd17..f9e9a5a1c 100644
--- a/internal/handler/organization.go
+++ b/internal/handler/organization.go
@@ -23,6 +23,7 @@ type OrganizationHandler struct {
agentShareService interfaces.AgentShareService
customAgentService interfaces.CustomAgentService
userService interfaces.UserService
+ kbService interfaces.KnowledgeBaseService
knowledgeRepo interfaces.KnowledgeRepository
chunkRepo interfaces.ChunkRepository
}
@@ -34,6 +35,7 @@ func NewOrganizationHandler(
agentShareService interfaces.AgentShareService,
customAgentService interfaces.CustomAgentService,
userService interfaces.UserService,
+ kbService interfaces.KnowledgeBaseService,
knowledgeRepo interfaces.KnowledgeRepository,
chunkRepo interfaces.ChunkRepository,
) *OrganizationHandler {
@@ -43,6 +45,7 @@ func NewOrganizationHandler(
agentShareService: agentShareService,
customAgentService: customAgentService,
userService: userService,
+ kbService: kbService,
knowledgeRepo: knowledgeRepo,
chunkRepo: chunkRepo,
}
@@ -1254,6 +1257,73 @@ func (h *OrganizationHandler) ListOrgAgentShares(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"shares": response, "total": len(response)}})
}
+// GetMeResourceCounts returns per-organization resource counts for the list sidebar (one request instead of N).
+// 全部 total is not returned here; frontend keeps 全部 = 我的 + 他人共享给我(与「全部」Tab 一致).
+// @Summary 获取各空间资源数量(侧栏用)
+// @Description 一次请求返回各空间内知识库/智能体数量(含我共享的),用于列表页侧栏展示
+// @Tags 组织管理
+// @Produce json
+// @Success 200 {object} types.ResourceCountsByOrgResponse
+// @Security Bearer
+// @Router /me/resource-counts [get]
+func (h *OrganizationHandler) GetMeResourceCounts(c *gin.Context) {
+ ctx := c.Request.Context()
+ userID := c.GetString(types.UserIDContextKey.String())
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+
+ orgs, err := h.orgService.ListUserOrganizations(ctx, userID)
+ if err != nil {
+ logger.Errorf(ctx, "Failed to list user organizations: %v", err)
+ c.Error(apperrors.NewInternalServerError("Failed to list organizations"))
+ return
+ }
+ orgIDs := make([]string, 0, len(orgs))
+ for _, o := range orgs {
+ orgIDs = append(orgIDs, o.ID)
+ }
+
+ agentCounts, err := h.agentShareService.CountByOrganizations(ctx, orgIDs)
+ if err != nil {
+ logger.Errorf(ctx, "Failed to count agent shares by org: %v", err)
+ c.Error(apperrors.NewInternalServerError("Failed to get counts"))
+ return
+ }
+
+ byOrgKB := make(map[string]int)
+ for _, o := range orgs {
+ list, err := h.listSpaceKnowledgeBasesInOrganization(ctx, o.ID, userID, tenantID)
+ if err != nil {
+ if !errors.Is(err, service.ErrUserNotInOrg) {
+ logger.Warnf(ctx, "listSpaceKnowledgeBasesInOrganization org %s: %v", o.ID, err)
+ }
+ byOrgKB[o.ID] = 0
+ continue
+ }
+ byOrgKB[o.ID] = len(list)
+ }
+ byOrgAgent := make(map[string]int)
+ for id, n := range agentCounts {
+ byOrgAgent[id] = int(n)
+ }
+ for _, o := range orgs {
+ if _, ok := byOrgAgent[o.ID]; !ok {
+ byOrgAgent[o.ID] = 0
+ }
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": types.ResourceCountsByOrgResponse{
+ KnowledgeBases: struct {
+ ByOrganization map[string]int `json:"by_organization"`
+ }{ByOrganization: byOrgKB},
+ Agents: struct {
+ ByOrganization map[string]int `json:"by_organization"`
+ }{ByOrganization: byOrgAgent},
+ },
+ })
+}
+
// ListSharedAgents lists agents shared to the current user
func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) {
ctx := c.Request.Context()
@@ -1268,6 +1338,182 @@ func (h *OrganizationHandler) ListSharedAgents(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": list, "total": len(list)})
}
+// listSpaceKnowledgeBasesInOrganization returns merged list of direct shared KBs and agent-carried KBs in the org (for list and count).
+func (h *OrganizationHandler) listSpaceKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, tenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error) {
+ directList, err := h.shareService.ListSharedKnowledgeBasesInOrganization(ctx, orgID, userID, tenantID)
+ if err != nil {
+ return nil, err
+ }
+
+ directKbIDs := make(map[string]bool)
+ for _, item := range directList {
+ if item.KnowledgeBase != nil && item.KnowledgeBase.ID != "" {
+ directKbIDs[item.KnowledgeBase.ID] = true
+ }
+ }
+
+ agentList, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, userID, tenantID)
+ if err != nil {
+ return directList, nil
+ }
+
+ orgName := ""
+ if len(agentList) > 0 && agentList[0].OrganizationID == orgID {
+ orgName = agentList[0].OrgName
+ }
+ if orgName == "" {
+ if org, err := h.orgService.GetOrganization(ctx, orgID); err == nil && org != nil {
+ orgName = org.Name
+ }
+ }
+
+ merged := make([]*types.OrganizationSharedKnowledgeBaseItem, 0, len(directList)+64)
+ merged = append(merged, directList...)
+
+ for _, agentItem := range agentList {
+ if agentItem.Agent == nil {
+ continue
+ }
+ agent := agentItem.Agent
+ mode := agent.Config.KBSelectionMode
+ if mode == "none" {
+ continue
+ }
+
+ var kbIDs []string
+ switch mode {
+ case "selected":
+ if len(agent.Config.KnowledgeBases) == 0 {
+ continue
+ }
+ kbIDs = agent.Config.KnowledgeBases
+ case "all":
+ kbs, err := h.kbService.ListKnowledgeBasesByTenantID(ctx, agent.TenantID)
+ if err != nil {
+ logger.Warnf(ctx, "ListKnowledgeBasesByTenantID for agent %s: %v", agent.ID, err)
+ continue
+ }
+ kbIDs = make([]string, 0, len(kbs))
+ for _, kb := range kbs {
+ if kb != nil && kb.ID != "" {
+ kbIDs = append(kbIDs, kb.ID)
+ }
+ }
+ default:
+ if len(agent.Config.KnowledgeBases) > 0 {
+ kbIDs = agent.Config.KnowledgeBases
+ }
+ }
+
+ agentName := agent.Name
+ if agentName == "" {
+ agentName = agent.ID
+ }
+ sourceTenantID := agent.TenantID
+
+ for _, kbID := range kbIDs {
+ if kbID == "" || directKbIDs[kbID] {
+ continue
+ }
+ kb, err := h.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID)
+ if err != nil || kb == nil {
+ continue
+ }
+ if kb.TenantID != sourceTenantID {
+ continue
+ }
+ directKbIDs[kbID] = true
+
+ switch kb.Type {
+ case types.KnowledgeBaseTypeDocument:
+ if count, err := h.knowledgeRepo.CountKnowledgeByKnowledgeBaseID(ctx, sourceTenantID, kb.ID); err == nil {
+ kb.KnowledgeCount = count
+ }
+ case types.KnowledgeBaseTypeFAQ:
+ if count, err := h.chunkRepo.CountChunksByKnowledgeBaseID(ctx, sourceTenantID, kb.ID); err == nil {
+ kb.ChunkCount = count
+ }
+ }
+
+ merged = append(merged, &types.OrganizationSharedKnowledgeBaseItem{
+ SharedKnowledgeBaseInfo: types.SharedKnowledgeBaseInfo{
+ KnowledgeBase: kb,
+ ShareID: "",
+ OrganizationID: orgID,
+ OrgName: orgName,
+ Permission: types.OrgRoleViewer,
+ SourceTenantID: sourceTenantID,
+ SharedAt: agentItem.SharedAt,
+ },
+ IsMine: false,
+ SourceFromAgent: &types.SourceFromAgentInfo{
+ AgentID: agent.ID,
+ AgentName: agentName,
+ KBSelectionMode: agent.Config.KBSelectionMode,
+ },
+ })
+ }
+ }
+
+ return merged, nil
+}
+
+// ListOrganizationSharedKnowledgeBases lists all knowledge bases in the given organization (including those shared by the current tenant and those from shared agents), for the list page when a space is selected.
+// @Summary 获取空间内全部知识库(含我共享的、含智能体携带的)
+// @Description 获取指定空间下所有共享知识库,包含直接共享的与通过共享智能体可见的,用于列表页空间视角
+// @Tags 组织管理
+// @Produce json
+// @Param id path string true "组织ID"
+// @Success 200 {object} map[string]interface{}
+// @Security Bearer
+// @Router /organizations/{id}/shared-knowledge-bases [get]
+func (h *OrganizationHandler) ListOrganizationSharedKnowledgeBases(c *gin.Context) {
+ ctx := c.Request.Context()
+ orgID := c.Param("id")
+ userID := c.GetString(types.UserIDContextKey.String())
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+
+ list, err := h.listSpaceKnowledgeBasesInOrganization(ctx, orgID, userID, tenantID)
+ if err != nil {
+ if errors.Is(err, service.ErrUserNotInOrg) {
+ c.Error(apperrors.NewForbiddenError("You are not a member of this organization"))
+ return
+ }
+ logger.Errorf(ctx, "Failed to list organization shared knowledge bases: %v", err)
+ c.Error(apperrors.NewInternalServerError("Failed to list shared knowledge bases"))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": list, "total": len(list)})
+}
+
+// ListOrganizationSharedAgents lists all agents in the given organization (including those shared by the current tenant), for the list page when a space is selected.
+// @Summary 获取空间内全部智能体(含我共享的)
+// @Description 获取指定空间下所有共享智能体,包含他人共享的与我共享的,用于列表页空间视角
+// @Tags 组织管理
+// @Produce json
+// @Param id path string true "组织ID"
+// @Success 200 {object} map[string]interface{}
+// @Security Bearer
+// @Router /organizations/{id}/shared-agents [get]
+func (h *OrganizationHandler) ListOrganizationSharedAgents(c *gin.Context) {
+ ctx := c.Request.Context()
+ orgID := c.Param("id")
+ userID := c.GetString(types.UserIDContextKey.String())
+ tenantID := c.GetUint64(types.TenantIDContextKey.String())
+
+ list, err := h.agentShareService.ListSharedAgentsInOrganization(ctx, orgID, userID, tenantID)
+ if err != nil {
+ if errors.Is(err, service.ErrUserNotInOrg) {
+ c.Error(apperrors.NewForbiddenError("You are not a member of this organization"))
+ return
+ }
+ logger.Errorf(ctx, "Failed to list organization shared agents: %v", err)
+ c.Error(apperrors.NewInternalServerError("Failed to list shared agents"))
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true, "data": list, "total": len(list)})
+}
+
// SetSharedAgentDisabledByMeRequest is the body for POST /shared-agents/disabled
type SetSharedAgentDisabledByMeRequest struct {
AgentID string `json:"agent_id" binding:"required"`
diff --git a/internal/handler/tag.go b/internal/handler/tag.go
index 3ff718927..7db819de4 100644
--- a/internal/handler/tag.go
+++ b/internal/handler/tag.go
@@ -16,11 +16,12 @@ import (
// TagHandler handles knowledge base tag operations.
type TagHandler struct {
- tagService interfaces.KnowledgeTagService
- tagRepo interfaces.KnowledgeTagRepository
- chunkRepo interfaces.ChunkRepository
- kbService interfaces.KnowledgeBaseService
- kbShareService interfaces.KBShareService
+ tagService interfaces.KnowledgeTagService
+ tagRepo interfaces.KnowledgeTagRepository
+ chunkRepo interfaces.ChunkRepository
+ kbService interfaces.KnowledgeBaseService
+ kbShareService interfaces.KBShareService
+ agentShareService interfaces.AgentShareService
}
// DeleteTagRequest represents the request body for deleting a tag
@@ -35,8 +36,9 @@ func NewTagHandler(
chunkRepo interfaces.ChunkRepository,
kbService interfaces.KnowledgeBaseService,
kbShareService interfaces.KBShareService,
+ agentShareService interfaces.AgentShareService,
) *TagHandler {
- return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo, kbService: kbService, kbShareService: kbShareService}
+ return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo, kbService: kbService, kbShareService: kbShareService, agentShareService: agentShareService}
}
// effectiveCtxForKB validates KB access (owner or shared) and returns context with effectiveTenantID for downstream service calls.
@@ -70,6 +72,13 @@ func (h *TagHandler) effectiveCtxForKB(c *gin.Context, kbID string) (context.Con
}
}
}
+ if userExists && h.agentShareService != nil {
+ can, err := h.agentShareService.UserCanAccessKBViaSomeSharedAgent(ctx, userID.(string), tenantID, kb)
+ if err == nil && can {
+ logger.Infof(ctx, "User %s accessing KB %s via some shared agent", userID.(string), kbID)
+ return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil
+ }
+ }
logger.Warnf(ctx, "Permission denied to access KB %s", kbID)
return nil, errors.NewForbiddenError("Permission denied to access this knowledge base")
}
diff --git a/internal/router/router.go b/internal/router/router.go
index d588fa4b6..20928f988 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -502,6 +502,10 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
orgs.GET("/:id/shares", orgHandler.ListOrgShares)
// List agents shared to this organization
orgs.GET("/:id/agent-shares", orgHandler.ListOrgAgentShares)
+ // List all knowledge bases in this organization (including mine) for list-page space view
+ orgs.GET("/:id/shared-knowledge-bases", orgHandler.ListOrganizationSharedKnowledgeBases)
+ // List all agents in this organization (including mine) for list-page space view
+ orgs.GET("/:id/shared-agents", orgHandler.ListOrganizationSharedAgents)
}
// Knowledge base sharing routes (add to existing kb routes)
@@ -530,4 +534,6 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
// Shared agents route
r.GET("/shared-agents", orgHandler.ListSharedAgents)
r.POST("/shared-agents/disabled", orgHandler.SetSharedAgentDisabledByMe)
+ // Per-org resource counts for list sidebar (one request)
+ r.GET("/me/resource-counts", orgHandler.GetMeResourceCounts)
}
diff --git a/internal/types/interfaces/organization.go b/internal/types/interfaces/organization.go
index 822ae4d2b..4226adb2b 100644
--- a/internal/types/interfaces/organization.go
+++ b/internal/types/interfaces/organization.go
@@ -90,6 +90,7 @@ type KBShareService interface {
ListSharesByKnowledgeBase(ctx context.Context, kbID string, tenantID uint64) ([]*types.KnowledgeBaseShare, error)
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
ListSharedKnowledgeBases(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedKnowledgeBaseInfo, error)
+ ListSharedKnowledgeBasesInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedKnowledgeBaseItem, error)
GetShare(ctx context.Context, shareID string) (*types.KnowledgeBaseShare, error)
GetShareByKBAndOrg(ctx context.Context, kbID string, orgID string) (*types.KnowledgeBaseShare, error)
@@ -102,6 +103,8 @@ type KBShareService interface {
// Count shares for knowledge bases
CountSharesByKnowledgeBaseIDs(ctx context.Context, kbIDs []string) (map[string]int64, error)
+ // CountByOrganizations returns share counts per organization (for sidebar); excludes deleted KBs
+ CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
}
// KBShareRepository defines the knowledge base sharing repository interface
@@ -120,6 +123,7 @@ type KBShareRepository interface {
// List
ListByKnowledgeBase(ctx context.Context, kbID string) ([]*types.KnowledgeBaseShare, error)
ListByOrganization(ctx context.Context, orgID string) ([]*types.KnowledgeBaseShare, error)
+ CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
// Query for user's accessible shared knowledge bases
ListSharedKBsForUser(ctx context.Context, userID string) ([]*types.KnowledgeBaseShare, error)
@@ -136,14 +140,19 @@ type AgentShareService interface {
ListSharesByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
ListSharesByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
ListSharedAgents(ctx context.Context, userID string, currentTenantID uint64) ([]*types.SharedAgentInfo, error)
+ ListSharedAgentsInOrganization(ctx context.Context, orgID string, userID string, currentTenantID uint64) ([]*types.OrganizationSharedAgentItem, error)
// SetSharedAgentDisabledByMe sets whether the current tenant has "disabled" this shared agent for their conversation dropdown (per-user preference).
SetSharedAgentDisabledByMe(ctx context.Context, tenantID uint64, agentID string, sourceTenantID uint64, disabled bool) error
// GetSharedAgentForUser returns the shared agent by agentID if the user has access (source tenant is resolved from share); used to resolve KB scope for @ mention.
GetSharedAgentForUser(ctx context.Context, userID string, currentTenantID uint64, agentID string) (*types.CustomAgent, error)
+ // UserCanAccessKBViaSomeSharedAgent returns true if the user has at least one shared agent that can access the given KB (for opening KB detail from "通过智能体可见" list without passing agent_id).
+ UserCanAccessKBViaSomeSharedAgent(ctx context.Context, userID string, currentTenantID uint64, kb *types.KnowledgeBase) (bool, error)
GetShare(ctx context.Context, shareID string) (*types.AgentShare, error)
GetShareByAgentAndOrg(ctx context.Context, agentID string, orgID string) (*types.AgentShare, error)
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access, excluding source_tenant_id == excludeTenantID (e.g. current tenant to get shared-from-other only).
GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error)
+ // CountByOrganizations returns share counts per organization (for sidebar); excludes deleted agents
+ CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
}
// AgentShareRepository defines the agent sharing repository interface
@@ -158,6 +167,7 @@ type AgentShareRepository interface {
ListByAgent(ctx context.Context, agentID string) ([]*types.AgentShare, error)
ListByOrganization(ctx context.Context, orgID string) ([]*types.AgentShare, error)
ListSharedAgentsForUser(ctx context.Context, userID string) ([]*types.AgentShare, error)
+ CountByOrganizations(ctx context.Context, orgIDs []string) (map[string]int64, error)
// GetShareByAgentIDForUser returns one share for the given agentID that the user can access (user in org), excluding source_tenant_id == excludeTenantID.
GetShareByAgentIDForUser(ctx context.Context, userID, agentID string, excludeTenantID uint64) (*types.AgentShare, error)
}
diff --git a/internal/types/organization.go b/internal/types/organization.go
index 44a2c2416..2e904b2f2 100644
--- a/internal/types/organization.go
+++ b/internal/types/organization.go
@@ -245,6 +245,27 @@ type SharedAgentInfo struct {
DisabledByMe bool `json:"disabled_by_me"`
}
+// SourceFromAgentInfo indicates the KB is visible in the space via a shared agent (read-only, no KB share record).
+type SourceFromAgentInfo struct {
+ AgentID string `json:"agent_id"`
+ AgentName string `json:"agent_name"`
+ KBSelectionMode string `json:"kb_selection_mode"` // "all" | "selected" | "none"; for drawer copy "该智能体对知识库的策略"
+}
+
+// OrganizationSharedKnowledgeBaseItem is used by GET /organizations/:id/shared-knowledge-bases (space-scoped list including mine).
+// When SourceFromAgent is set, the KB is from a shared agent's config (no direct KB share); show as read-only and "来自智能体 XXX".
+type OrganizationSharedKnowledgeBaseItem struct {
+ SharedKnowledgeBaseInfo
+ IsMine bool `json:"is_mine"`
+ SourceFromAgent *SourceFromAgentInfo `json:"source_from_agent,omitempty"`
+}
+
+// OrganizationSharedAgentItem is used by GET /organizations/:id/shared-agents (space-scoped list including mine).
+type OrganizationSharedAgentItem struct {
+ SharedAgentInfo
+ IsMine bool `json:"is_mine"`
+}
+
// TenantDisabledSharedAgent records that a tenant has "disabled" a shared agent for their own dropdown
type TenantDisabledSharedAgent struct {
TenantID uint64 `json:"tenant_id" gorm:"primaryKey"`
@@ -421,6 +442,16 @@ type ListOrganizationsResponse struct {
Total int64 `json:"total"`
}
+// ResourceCountsByOrgResponse is the response for GET /me/resource-counts (sidebar counts per space)
+type ResourceCountsByOrgResponse struct {
+ KnowledgeBases struct {
+ ByOrganization map[string]int `json:"by_organization"`
+ } `json:"knowledge_bases"`
+ Agents struct {
+ ByOrganization map[string]int `json:"by_organization"`
+ } `json:"agents"`
+}
+
// SearchableOrganizationItem is a searchable org item for discovery (no invite code)
type SearchableOrganizationItem struct {
ID string `json:"id"`