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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ui/src/views/document-detail/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -527,5 +527,6 @@ onMounted(() => {
:document-id="documentId"
@success="handleReplaceParagraph"
@closed="editDialogMounted = false"
:resource-type="documentDetail?.resource_type"
/>
</template>
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { useDocumentDetailContext } from '@/views/document-detail/context'
import ParagraphForm from './components/ParagraphForm.vue'
import ParagraphQuestions from './components/ParagraphQuestions.vue'
import { MsgSuccess } from '@/utils/message'
import { isSystemResource, isSystemSharedResource, isWorkspaceSharedResource } from '@/utils/resource-context'
import { perm } from '@/permission'

defineOptions({ name: 'CreateParagraphDialog' })
const { t } = useI18n({ useScope: 'global' })
Expand All @@ -17,6 +19,16 @@ const props = defineProps<{
const { resourceApi } = useDocumentDetailContext()
const emit = defineEmits<{ success: [mode: 'create']; closed: [] }>()

/**
* 知识库「问题」只读权限判断
*/
function knowledgeQuestionPermission(): boolean {
if (isSystemResource()) return Boolean(perm.knowledge.system.problemRead())
if (isSystemSharedResource()) return Boolean(perm.knowledge.share.problemRead())
if (isWorkspaceSharedResource()) return false // 共享知识库在工作空间侧只读
return Boolean(perm.knowledge.workspace.problemRead(props.knowledgeId))
}

/* 添加弹窗按需挂载,草稿在关闭后随实例释放。 */
const visible = ref(false)
const targetKnowledgeId = ref('')
Expand Down Expand Up @@ -74,7 +86,12 @@ defineExpose({ open, close })
<div v-loading="loading" class="flex w-full gap-4">
<ParagraphForm ref="paragraphFormRef" v-model="paragraphForm" :knowledge-id="targetKnowledgeId" />
<!-- 关联问题 -->
<ParagraphQuestions v-model="relatedQuestions" :knowledge-id="targetKnowledgeId" :document-id="targetDocumentId" />
<ParagraphQuestions
v-model="relatedQuestions"
:show="knowledgeQuestionPermission()"
:knowledge-id="targetKnowledgeId"
:document-id="targetDocumentId"
/>
</div>
<template #footer>
<!-- 取消添加分段 -->

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Review

No major irregularities. The diff is clean and consistent with the existing patterns (isSystemResource, perm.*.problemRead). Notes below are minor.

1. Import path consistency (verify)

import { perm } from '@/permission'

Most codebases in this style import permissions at a specific granularity. Confirm the symbol exists and returns functions (it's called as perm.knowledge.system.problemRead() and perm.knowledge.workspace.problemRead(id) — i.e. methods, not booleans). If problemRead is a static boolean, calling it will throw at runtime. Double-check the API shape.

2. Naming / intent

  • knowledgeQuestionPermission() reads like a getter but acts as a permission check. A clearer name: canShowKnowledgeQuestions() or hasQuestionReadPerm(). Also, it takes no args yet closes over props.knowledgeId — acceptable, but a named param would be more explicit:
    function canReadQuestions(knowledgeId: string): boolean { ... }

3. Called directly in template

:show="knowledgeQuestionPermission()"

This runs on every re-render (cheap here, but if perm.*.problemRead ever becomes async or expensive it'll thrash). Safer pattern: a computed.

const showQuestions = computed(() => {
  if (isSystemResource()) return Boolean(perm.knowledge.system.problemRead())
  if (isSystemSharedResource()) return Boolean(perm.knowledge.share.problemRead())
  if (isWorkspaceSharedResource()) return false
  return Boolean(perm.knowledge.workspace.problemRead(props.knowledgeId))
})

Then :show="showQuestions".

This also gives you a single place to unit-test the branch logic.

4. Ordering of branches (behavioral assumption)

The isWorkspaceSharedResource() → false branch means "shared KB is read-only on the workspace side." That encodes a product decision inside a view component. Consider moving the "which resource context am I in?" resolution into resource-context.ts (e.g. getResourceScope()), so this file only maps scope → permission. Keeps the switch testable and avoids drift if another context is added later.

Otherwise, ordering is correct: system → shared → workspace-shared → workspace.

5. Default fallthrough

If none of the is* guards match (e.g. an unknown/new context), it silently falls through to perm.knowledge.workspace.problemRead(props.knowledgeId). If that's intentional, fine; if a new context should be denied by default, make the default explicit:

return Boolean(perm.knowledge.workspace.problemRead(props.knowledgeId)) // default: own workspace

6. props.knowledgeId vs targetKnowledgeId

The template passes :knowledge-id="targetKnowledgeId", but the permission check uses props.knowledgeId. Confirm these are always the same at render time. During open(...) there may be a tick where targetKnowledgeId is set but props.knowledgeId isn't (or vice versa) — then show could disagree with what ParagraphQuestions actually queries. If they can differ, use targetKnowledgeId for the check too:

function canReadQuestions(kid: string) { ... }   // pass targetKnowledgeId
:show="canReadQuestions(targetKnowledgeId)"

7. Comment language

Code comments (知识库「问题」只读权限判断, 共享知识库在工作空间侧只读) are Chinese while the project apparently mixes English naming. Not a bug — flag only if the repo lint/convention requires English comments.

8. defineExpose / reactivity (unchanged, just FYI)

knowledgeQuestionPermission is not exposed — fine, since it's only used in the template. No issue.

Summary of suggested changes

# Severity Change
1 Check Verify perm.*.problemRead are methods, not booleans
3 Low Wrap in computed for clarity/perf/ testability
6 Low–Med Align props.knowledgeId with targetKnowledgeId
4 Low Move scope→permission mapping out of the view
2 Nit Rename to canReadQuestions / canShowQuestions

Expand Down
30 changes: 27 additions & 3 deletions ui/src/views/document-detail/paragraph-dialog/ParagraphDialog.vue
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<script setup lang="ts">
import { ref } from 'vue'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import type { ParagraphQuestionDraft } from './types.ts'
import type { ParagraphDetail, ParagraphItem, ParagraphUpdatePayload } from '@/api/types'
import type { DocumentResourceType, ParagraphDetail, ParagraphItem, ParagraphUpdatePayload } from '@/api/types'
import { DOCUMENT_RESOURCE_TYPE } from '@/api/enums'
import { useDocumentDetailContext } from '@/views/document-detail/context'
import ParagraphForm from './components/ParagraphForm.vue'
import ParagraphPreview from './components/ParagraphPreview.vue'
Expand All @@ -23,13 +24,33 @@ function knowledgeDocPermission(method: KnowledgeDocPermissionMethod): boolean {
return Boolean(perm.knowledge.workspace[method](props.knowledgeId))
}

type KnowledgeImagePermissionMethod = 'edit'

function knowledgeImagePermission(method: KnowledgeImagePermissionMethod): boolean {
if (isSystemResource()) return Boolean(perm.knowledge.system.image[method]())
if (isSystemSharedResource()) return Boolean(perm.knowledge.share.image[method]())
if (isWorkspaceSharedResource()) return false // 共享知识库在工作空间侧只读
return Boolean(perm.knowledge.workspace.image[method](props.knowledgeId))
}

/**
* 知识库「问题」只读权限判断
*/
function hasProblemReadPermission(): boolean {
if (isSystemResource()) return Boolean(perm.knowledge.system.problemRead())
if (isSystemSharedResource()) return Boolean(perm.knowledge.share.problemRead())
if (isWorkspaceSharedResource()) return false // 共享知识库在工作空间侧只读
return Boolean(perm.knowledge.workspace.problemRead(props.knowledgeId))
}

defineOptions({ name: 'EditParagraphDialog' })
const { t } = useI18n({ useScope: 'global' })
const props = defineProps<{
knowledgeId: string
documentId: string
sourceFileId?: string
title?: string
resourceType?: DocumentResourceType
}>()
const { resourceApi } = useDocumentDetailContext()
const emit = defineEmits<{ success: [paragraph: ParagraphItem]; closed: [] }>()
Expand All @@ -44,6 +65,8 @@ const targetParagraphId = ref('')
const loading = ref(false)
const detailFailed = ref(false)
const relatedQuestions = ref<ParagraphQuestionDraft[]>([])
const isImageDocument = computed(() => props.resourceType === DOCUMENT_RESOURCE_TYPE.IMAGE)
const showQuestions = computed(() => hasProblemReadPermission())

function loadParagraphDetail() {
if (loading.value) return
Expand Down Expand Up @@ -129,7 +152,7 @@ defineExpose({ open, close })
<el-card v-if="mode === 'detail'" shadow="never" class="mk-paragraph-card group relative min-w-0 flex-1" body-class="flex-column h-full">
<!-- 编辑分段标题和内容 -->
<el-button
v-if="!isWorkspaceSharedResource() && knowledgeDocPermission('docEdit')"
v-if="!isWorkspaceSharedResource() && (isImageDocument ? knowledgeImagePermission('edit') : knowledgeDocPermission('docEdit'))"
circle
class="group-hover-visible absolute! top-2 right-2 z-10 shadow-md"
@click="handleEdit"
Expand All @@ -152,6 +175,7 @@ defineExpose({ open, close })
<!-- 关联问题 -->
<ParagraphQuestions
v-model="relatedQuestions"
:show="showQuestions"
:knowledge-id="targetKnowledgeId"
:document-id="targetDocumentId"
:paragraph-id="targetParagraphId"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Here's my review of the diff:

Issues & Observations

1. Inconsistent behavior: isWorkspaceSharedResource returns false vs. other branches

function knowledgeImagePermission(method) {
  if (isSystemResource()) return Boolean(perm.knowledge.system.image[method]())
  if (isSystemSharedResource()) return Boolean(perm.knowledge.share.image[method]())
  if (isWorkspaceSharedResource()) return false // 共享知识库在工作空间侧只读
  return Boolean(perm.knowledge.workspace.image[method](props.knowledgeId))
}

This hard-codes permission resolution per resource type. It works but duplicates logic from knowledgeDocPermission. Consider extracting a generic higher-order helper (e.g., resourcePermission(getterKey, method)) to avoid repeating this branching pattern every time a new permission is added. This is now duplicated at least three times.

2. Comment language inconsistency

Comments are in Chinese (// 共享知识库在工作空间侧只读, 知识库「问题」只读权限判断) while you requested English answers and the project otherwise appears to mix. Keep consistent with the codebase convention (if it's Chinese elsewhere, fine — just confirm).

3. hasProblemReadPermission() naming / semantics

  • The name suggests a boolean, but it also embeds resource-type dispatch that could become stale if new resource types are added to DOCUMENT_RESOURCE_TYPE or the perm structure.
  • Since showQuestions is derived via computed(() => hasProblemReadPermission()), note that if any of the underlying perm.* getters are reactive refs/proxies, this will recompute correctly; if they are plain functions reading non-reactive state, the computed won't update. Verify reactivity of the perm object.

4. resourceType prop is optional but drives crucial behavior

resourceType?: DocumentResourceType
const isImageDocument = computed(() => props.resourceType === DOCUMENT_RESOURCE_TYPE.IMAGE)

If the parent doesn't pass resourceType, images fall back to the doc-permission check (knowledgeDocPermission('docEdit')), which may incorrectly gate editing. Options:

  • Make it required, or
  • Derive it from resourceApi/context instead of relying on the caller.

5. Missing newline / formatting in template condition

v-if="!isWorkspaceSharedResource() && (isImageDocument ? knowledgeImagePermission('edit') : knowledgeDocPermission('docEdit'))"

Long inline ternary in template hurts readability. Extract to a computed like canEditParagraph:

const canEditParagraph = computed(() =>
  !isWorkspaceSharedResource() &&
  (isImageDocument.value ? knowledgeImagePermission('edit') : knowledgeDocPermission('docEdit'))
)

Then v-if="canEditParagraph". This also avoids re-evaluating permission calls on every render.

6. Potential redundant permission evaluation per render

Both canEditParagraph (above) and hasProblemReadPermission() call permission functions directly in render. If these getters have side effects or are expensive, caching via computed is preferable. The showQuestions computed already helps, but canEditParagraph currently does not.

7. showQuestions always-overrides child visibility

The child component receives :show="showQuestions". Confirm the child treats show as "fully hide" (not merely disable interaction). If it previously always showed questions for some flows (e.g., preview mode), adding show may unintentionally hide them. Also consider whether show should short-circuit v-model updates, i.e., prevent loading question APIs when hidden — ideally pass it down so the child can v-if internally and skip network requests.

8. KnowledgeImagePermissionMethod only supports 'edit'

Fine for now, but if image permissions later need view/delete, consider widening to match the shape used by KnowledgeDocPermissionMethod for symmetry and reuse.

9. Type import ordering

DocumentResourceType was added to an existing import type { ... } from '@/api/types' line; ensure alphabetical/lint ordering matches project conventions (some setups enforce sorted imports). Run ESLint to confirm.

10. perm.knowledge.*.image[method] guards

The code assumes perm.knowledge.system.image, perm.knowledge.share.image, etc., all exist and expose edit. If these were introduced alongside this change, ensure the source of truth (perm) defines them for all resource types; otherwise add optional chaining or explicit feature-flag gating to avoid runtime undefined-access errors.

Summary of suggested changes

  • Extract a shared permission-dispatch helper to remove triple duplication.
  • Extract canEditParagraph computed and use it in the template.
  • Consider making resourceType required or deriving it from context.
  • Verify perm reactivity for the new computeds.
  • Ensure the child respects show by skipping its own data fetch/permission calls when false.
  • Confirm lint passes for import sorting and run unit tests covering image/shared/system/workspace combinations for both edit and problem-read.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const props = defineProps<{
knowledgeId: string
documentId: string
paragraphId?: string
show: boolean
}>()
const { resourceApi } = useDocumentDetailContext()
const relatedProblems = defineModel<ParagraphQuestionDraft[]>({ required: true })
Expand Down Expand Up @@ -141,7 +142,7 @@ function handleRemoveProblem(index: number) {
</script>

<template>
<aside v-if="knowledgeQuestionPermission('problemRead')" v-loading="loading" class="mk-gray-card-lg flex-column w-60 shrink-0">
<aside v-if="show" v-loading="loading" class="mk-gray-card-lg flex-column w-60 shrink-0">
<div class="mb-4 flex-between shrink-0 gap-3">
<h4>{{ t('knowledge.paragraph.relatedQuestions.label') }}</h4>
<!-- 添加关联问题 -->
Expand Down
1 change: 1 addition & 0 deletions ui/src/views/knowledge-detail/hit-test/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ function testKnowledge(query: Required<Pick<KnowledgeHitTestPayload, 'query_text
:knowledge-id="selectedParagraph.knowledge_id"
:document-id="selectedParagraph.document_id"
:source-file-id="selectedParagraph.document_image_id || undefined"
:resource-type="selectedParagraph.document_resource_type ?? undefined"
@success="handleParagraphSuccess"
@closed="selectedParagraph = undefined"
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,24 @@ import type { DocumentImportParagraph, ParagraphUpdatePayload } from '@/api/type
import type { ParagraphQuestionDraft } from '@/views/document-detail/paragraph-dialog/types'
import ParagraphForm from '@/views/document-detail/paragraph-dialog/components/ParagraphForm.vue'
import ParagraphQuestions from '@/views/document-detail/paragraph-dialog/components/ParagraphQuestions.vue'
import { isSystemResource, isSystemSharedResource, isWorkspaceSharedResource } from '@/utils/resource-context'
import { perm } from '@/permission'

defineOptions({ name: 'EditImportParagraphDialog' })
const { t } = useI18n({ useScope: 'global' })
defineProps<{ knowledgeId: string }>()
const props = defineProps<{ knowledgeId: string }>()
const emit = defineEmits<{ submit: [paragraph: DocumentImportParagraph]; closed: [] }>()

/**
* 知识库「问题」只读权限判断
*/
function knowledgeQuestionPermission(): boolean {
if (isSystemResource()) return Boolean(perm.knowledge.system.problemRead())
if (isSystemSharedResource()) return Boolean(perm.knowledge.share.problemRead())
if (isWorkspaceSharedResource()) return false // 共享知识库在工作空间侧只读
return Boolean(perm.knowledge.workspace.problemRead(props.knowledgeId))
}

/* 编辑弹窗按需挂载,保存前仅维护导入分段和关联问题的本地草稿。 */
const visible = ref(false)
const paragraphDraft = ref<DocumentImportParagraph>({ title: '', content: '' })
Expand Down Expand Up @@ -71,7 +83,7 @@ defineExpose({ open, close })
<div v-loading="loading" class="flex w-full gap-4">
<ParagraphForm ref="paragraphFormRef" v-model="paragraphForm" :knowledge-id="knowledgeId" />
<!-- 关联问题仅保存到导入草稿,未创建文档不传入分段 ID -->
<ParagraphQuestions v-model="relatedQuestions" :knowledge-id="knowledgeId" document-id="" />
<ParagraphQuestions v-model="relatedQuestions" :show="knowledgeQuestionPermission()" :knowledge-id="knowledgeId" document-id="" />
</div>
<template #footer>
<!-- 取消分段编辑 -->

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The diff is syntactically valid. Main concerns are reactivity, permission semantics, and ensuring the UI permission is actually enforced.

Potential issues

  1. Permission function is called directly in the template

    • knowledgeQuestionPermission() runs on every render and is not cached.
    • If permission/resource state can change while the dialog is open, it may not update as expected unless all accessed state is reactive.
    • Prefer a computed.
  2. show may only hide the component, not enforce permission

    • If ParagraphQuestions still mounts, fetches data, or keeps relatedQuestions, the user may still submit previously selected questions.
    • Use v-if if the component should not mount without permission, and sanitize on submit:
    if (!canReadQuestions.value) relatedQuestions.value = []
    • Backend/API must also enforce the permission; do not rely on this UI check.
  3. Permission name vs. actual operation

    • The comment says “read permission” (problemRead), but ParagraphQuestions uses v-model, implying editing/selection.
    • If the component allows editing, a read-only permission may be insufficient. Verify whether it should check read, create, or update permission.
    • If workspace-shared knowledge bases should be read-only, hiding the component may be wrong — consider a readonly/disabled mode instead.
  4. Workspace-shared branch is hardcoded to false

    • Confirm this is the intended business rule.
    • Also verify branch ordering: if a workspace-shared resource can also satisfy isSystemSharedResource(), the isWorkspaceSharedResource() branch will never be reached.
  5. Ensure ParagraphQuestions actually defines a show prop

    • If it does not, :show becomes a fallthrough attribute and has no effect.
  6. Ensure permission getters return synchronous booleans

    • Boolean(perm.knowledge...()) will be true for a Promise. If any permission method is async, this code is incorrect.
  7. Stale relatedQuestions

    • If permission changes or knowledgeId changes, previously selected questions may remain. Clear them when permission becomes false.

Recommended refactor

const canReadQuestions = computed(() => {
  if (isSystemResource()) return Boolean(perm.knowledge.system.problemRead())
  if (isSystemSharedResource()) return Boolean(perm.knowledge.share.problemRead())
  if (isWorkspaceSharedResource()) return false
  return Boolean(perm.knowledge.workspace.problemRead(props.knowledgeId))
})

watch(canReadQuestions, (allowed) => {
  if (!allowed) relatedQuestions.value = []
})

Template:

<ParagraphQuestions
  v-if="canReadQuestions"
  v-model="relatedQuestions"
  :knowledge-id="knowledgeId"
  document-id=""
/>

Or, if show is required:

<ParagraphQuestions
  v-model="relatedQuestions"
  :show="canReadQuestions"
  :knowledge-id="knowledgeId"
  document-id=""
/>

Optimization suggestions

  • Use computed instead of a template function call.
  • Consider renaming to a boolean-style name such as canReadQuestions.
  • Add tests for the permission matrix: system, system-shared, workspace-shared, and normal workspace.
  • Centralize this permission logic if similar checks are used elsewhere.

Expand Down
1 change: 1 addition & 0 deletions ui/src/views/knowledge-detail/library/image/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,7 @@ onBeforeUnmount(() => {
:knowledge-id="knowledgeId"
:document-id="selectedParagraph.document_id"
:source-file-id="selectedParagraph.source_file_id"
:resource-type="DOCUMENT_RESOURCE_TYPE.IMAGE"
@success="refreshAfterOperation"
@closed="selectedParagraph = undefined"
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ defineExpose({ refresh: handleLoadParagraphs })
:knowledge-id="knowledgeId"
:document-id="selectedParagraph.document_id"
:source-file-id="selectedParagraph.document_image_id ?? undefined"
:resource-type="selectedParagraph.document_resource_type"
@closed="handleParagraphClosed"
/>
</template>
Loading