chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,136 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test, { type TestContext } from 'node:test'
|
||||
import * as vue from 'vue'
|
||||
import * as pinia from 'pinia'
|
||||
import { fixture, flush } from '../test-utils/vueFixture.ts'
|
||||
|
||||
type Request = {
|
||||
url: string
|
||||
resolve: (response: unknown) => void
|
||||
reject: (error: unknown) => void
|
||||
}
|
||||
|
||||
function setup(t: TestContext) {
|
||||
const f = fixture(t)
|
||||
const metadata: Request[] = []
|
||||
const chunks: Request[] = []
|
||||
const put = t.mock.fn(async (_url: string, _body: unknown) => ({ success: true }))
|
||||
const apiSource = readFileSync(new URL('../api/knowledge-base/index.ts', import.meta.url), 'utf8')
|
||||
const api = f.evaluate(`import { URLSearchParams } from 'node:url'\n${apiSource}`, {
|
||||
'node:url': { URLSearchParams },
|
||||
'../../utils/request': {
|
||||
get: (url: string) => new Promise((resolve, reject) => {
|
||||
const requests = url.startsWith('/api/v1/chunks/') ? chunks : metadata
|
||||
requests.push({ url, resolve, reject })
|
||||
}),
|
||||
put,
|
||||
},
|
||||
'./knowledgeFileListQuery': {},
|
||||
})
|
||||
const stores = f.evaluate(readFileSync(new URL('../stores/knowledge.ts', import.meta.url), 'utf8'), { vue, pinia })
|
||||
const root = pinia.createPinia()
|
||||
pinia.setActivePinia(root)
|
||||
t.after(() => pinia.disposePinia(root))
|
||||
const { default: useKnowledgeBase } = f.evaluate(readFileSync(new URL('./useKnowledgeBase.ts', import.meta.url), 'utf8'), {
|
||||
vue, pinia,
|
||||
'../utils/index': { formatStringDate: (date: Date) => date.toISOString() },
|
||||
'@/api/knowledge-base/index': api,
|
||||
'@/stores/knowledge': stores,
|
||||
'vue-router': { useRoute: () => ({ params: { kbId: 'kb' } }) },
|
||||
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
|
||||
})
|
||||
const hook: ReturnType<typeof import('./useKnowledgeBase')['default']> = useKnowledgeBase('kb')
|
||||
return { hook, metadata, chunks, api, put }
|
||||
}
|
||||
|
||||
function detail(id: string, revision = 'current') {
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
id, file_name: `${id}-${revision}.pdf`, file_type: 'pdf',
|
||||
updated_at: '2026-01-01T00:00:00Z', description: `${id}-${revision} summary`,
|
||||
custom_metadata: { revision }, tags: [{ id: revision, name: revision }],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const chunkPage = (content: string) => ({ success: true, data: [{ id: content, content }], total: 50 })
|
||||
|
||||
test('late metadata and chunks from a previous document cannot replace the current document', async t => {
|
||||
const { hook, metadata, chunks } = setup(t)
|
||||
hook.getCardDetails({ id: 'a' })
|
||||
hook.getCardDetails({ id: 'b' })
|
||||
metadata[1].resolve(detail('b'))
|
||||
chunks[1].resolve(chunkPage('b content'))
|
||||
await flush()
|
||||
const current = JSON.stringify(hook.details)
|
||||
|
||||
metadata[0].resolve(detail('a', 'stale'))
|
||||
chunks[0].resolve(chunkPage('a content'))
|
||||
await flush()
|
||||
assert.equal(JSON.stringify(hook.details), current)
|
||||
assert.equal(hook.details.id, 'b')
|
||||
assert.equal(hook.details.md[0].content, 'b content')
|
||||
})
|
||||
|
||||
for (const ids of [['a', 'b', 'a'], ['a', 'a']]) {
|
||||
test(`only the latest metadata request applies when opening ${ids.join(' → ')}`, async t => {
|
||||
const { hook, metadata } = setup(t)
|
||||
for (const id of ids) hook.getCardDetails({ id })
|
||||
metadata.at(-1)!.resolve(detail('a', 'newest'))
|
||||
await flush()
|
||||
for (let i = metadata.length - 2; i >= 0; i--) metadata[i].resolve(detail(ids[i], 'stale'))
|
||||
await flush()
|
||||
|
||||
assert.equal(hook.details.id, 'a')
|
||||
assert.equal(hook.details.title, 'a-newest.pdf')
|
||||
assert.equal(hook.details.description, 'a-newest summary')
|
||||
assert.equal(hook.details.custom_metadata.revision, 'newest')
|
||||
assert.equal(hook.details.tags[0].id, 'newest')
|
||||
})
|
||||
}
|
||||
|
||||
test('chunk pagination does not discard pending metadata for the same document', async t => {
|
||||
const { hook, metadata, chunks } = setup(t)
|
||||
hook.getCardDetails({ id: 'a' })
|
||||
hook.getfDetails('a', 2)
|
||||
assert.match(chunks[1].url, /page=2&/)
|
||||
chunks[1].resolve(chunkPage('page 2'))
|
||||
await flush()
|
||||
metadata[0].resolve(detail('a'))
|
||||
chunks[0].resolve(chunkPage('stale page 1'))
|
||||
await flush()
|
||||
|
||||
assert.equal(hook.details.id, 'a')
|
||||
assert.equal(hook.details.title, 'a-current.pdf')
|
||||
assert.equal(hook.details.md[0].content, 'page 2')
|
||||
assert.equal(hook.details.chunkLoading, false)
|
||||
})
|
||||
|
||||
test('summary updates target the current document after an old detail response arrives', async t => {
|
||||
const { hook, metadata, api, put } = setup(t)
|
||||
hook.getCardDetails({ id: 'a' })
|
||||
hook.getCardDetails({ id: 'b' })
|
||||
metadata[1].resolve(detail('b'))
|
||||
await flush()
|
||||
metadata[0].resolve(detail('a', 'stale'))
|
||||
await flush()
|
||||
|
||||
// The drawer submits its current details.id to this production API helper.
|
||||
await api.updateKnowledgeSummary(hook.details.id, 'Edited B summary')
|
||||
assert.equal(put.mock.calls[0].arguments[0], '/api/v1/knowledge/b')
|
||||
assert.equal((put.mock.calls[0].arguments[1] as { description: string }).description, 'Edited B summary')
|
||||
})
|
||||
|
||||
test('a rejected old metadata request leaves the current document intact', async t => {
|
||||
const { hook, metadata } = setup(t)
|
||||
hook.getCardDetails({ id: 'a' })
|
||||
hook.getCardDetails({ id: 'b' })
|
||||
metadata[1].resolve(detail('b'))
|
||||
await flush()
|
||||
metadata[0].reject(new Error('old request failed'))
|
||||
await flush()
|
||||
assert.equal(hook.details.id, 'b')
|
||||
assert.equal(hook.details.title, 'b-current.pdf')
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
import { ref, reactive } from "vue";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { formatStringDate } from "../utils/index";
|
||||
import {
|
||||
listKnowledgeFiles,
|
||||
getKnowledgeDetails,
|
||||
getKnowledgeDetailsCon,
|
||||
type ListKnowledgeFilesParams,
|
||||
} from "@/api/knowledge-base/index";
|
||||
import { knowledgeStore } from "@/stores/knowledge";
|
||||
import { useRoute } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
export default function (knowledgeBaseId?: string) {
|
||||
const usemenuStore = knowledgeStore();
|
||||
const route = useRoute();
|
||||
const { t } = useI18n();
|
||||
const { cardList, total } = storeToRefs(usemenuStore);
|
||||
let moreIndex = ref(-1);
|
||||
const details = reactive({
|
||||
title: "",
|
||||
time: "",
|
||||
md: [] as any[],
|
||||
id: "",
|
||||
total: 0,
|
||||
type: "",
|
||||
source: "",
|
||||
channel: "",
|
||||
file_type: "",
|
||||
description: "",
|
||||
summary_status: "",
|
||||
parse_status: "",
|
||||
error_message: "",
|
||||
custom_metadata: {} as Record<string, unknown>,
|
||||
chunkLoading: false,
|
||||
chunkLoadError: "",
|
||||
tags: [] as Array<{ id: string; name: string; color?: string }>,
|
||||
});
|
||||
let knowledgeListGeneration = 0;
|
||||
let detailRequestGeneration = 0;
|
||||
let chunkRequestGeneration = 0;
|
||||
let activeKnowledgeId = '';
|
||||
const getKnowled = (
|
||||
query: ListKnowledgeFilesParams = { page: 1, page_size: 35 },
|
||||
kbId?: string,
|
||||
): Promise<void> => {
|
||||
const targetKbId = kbId || knowledgeBaseId;
|
||||
if (!targetKbId) return Promise.resolve();
|
||||
const requestGeneration = query.page === 1 ? ++knowledgeListGeneration : knowledgeListGeneration;
|
||||
|
||||
return listKnowledgeFiles(targetKbId, query)
|
||||
.then((result: any) => {
|
||||
if (requestGeneration !== knowledgeListGeneration) return;
|
||||
|
||||
const currentRouteKbId = (route.params as any)?.kbId as string | undefined;
|
||||
if (currentRouteKbId && currentRouteKbId !== targetKbId) return;
|
||||
|
||||
const { data, total: totalResult } = result;
|
||||
const cardList_ = data.map((item: any) => {
|
||||
const rawName = item.file_name || item.title || item.source || t('knowledgeBase.untitledDocument')
|
||||
const dotIndex = rawName.lastIndexOf('.')
|
||||
const displayName = dotIndex > 0 ? rawName.substring(0, dotIndex) : rawName
|
||||
const fileTypeSource = item.file_type || (item.type === 'manual' ? 'MANUAL' : '')
|
||||
return {
|
||||
...item,
|
||||
original_file_name: item.file_name,
|
||||
display_name: displayName,
|
||||
file_name: displayName,
|
||||
folder_path: item.folder_path || '',
|
||||
updated_at: formatStringDate(new Date(item.updated_at)),
|
||||
isMore: false,
|
||||
file_type: fileTypeSource ? String(fileTypeSource).toLocaleUpperCase() : '',
|
||||
}
|
||||
});
|
||||
|
||||
if (query.page === 1) {
|
||||
cardList.value = cardList_;
|
||||
} else {
|
||||
cardList.value.push(...cardList_);
|
||||
}
|
||||
total.value = totalResult;
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
const openMore = (index: number) => {
|
||||
moreIndex.value = index;
|
||||
};
|
||||
const onVisibleChange = (visible: boolean) => {
|
||||
if (!visible) {
|
||||
moreIndex.value = -1;
|
||||
}
|
||||
};
|
||||
const getCardDetails = (item: any) => {
|
||||
const requestGeneration = ++detailRequestGeneration;
|
||||
activeKnowledgeId = item.id;
|
||||
chunkRequestGeneration++;
|
||||
Object.assign(details, {
|
||||
title: "",
|
||||
time: "",
|
||||
md: [],
|
||||
id: "",
|
||||
type: "",
|
||||
source: "",
|
||||
channel: "",
|
||||
file_type: "",
|
||||
description: "",
|
||||
summary_status: "",
|
||||
parse_status: "",
|
||||
error_message: "",
|
||||
custom_metadata: {},
|
||||
chunkLoadError: "",
|
||||
tags: item?.tags ? [...item.tags] : [],
|
||||
});
|
||||
getKnowledgeDetails(item.id)
|
||||
.then((result: any) => {
|
||||
if (requestGeneration !== detailRequestGeneration || activeKnowledgeId !== item.id) return;
|
||||
if (result.success && result.data) {
|
||||
const { data } = result;
|
||||
Object.assign(details, {
|
||||
title: data.file_name || data.title || data.source || t('knowledgeBase.untitledDocument'),
|
||||
time: formatStringDate(new Date(data.updated_at)),
|
||||
id: data.id,
|
||||
type: data.type || 'file',
|
||||
source: data.source || '',
|
||||
channel: data.channel || '',
|
||||
file_type: data.file_type || '',
|
||||
description: data.description || '',
|
||||
summary_status: data.summary_status || '',
|
||||
parse_status: data.parse_status || '',
|
||||
error_message: data.error_message || '',
|
||||
custom_metadata: data.custom_metadata || {},
|
||||
tags: data.tags?.length ? data.tags : (item?.tags || []),
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
getfDetails(item.id, 1);
|
||||
};
|
||||
|
||||
const getfDetails = (id: string, page: number) => {
|
||||
const requestGeneration = ++chunkRequestGeneration;
|
||||
details.chunkLoading = true;
|
||||
details.chunkLoadError = "";
|
||||
getKnowledgeDetailsCon(id, page)
|
||||
.then((result: any) => {
|
||||
if (requestGeneration !== chunkRequestGeneration || activeKnowledgeId !== id) return;
|
||||
if (result.success && result.data) {
|
||||
const { data, total: totalResult } = result;
|
||||
details.md = data;
|
||||
details.total = totalResult;
|
||||
} else {
|
||||
details.chunkLoadError = result?.message || result?.error?.message || t('knowledgeBase.chunkLoadFailed');
|
||||
}
|
||||
})
|
||||
.catch((err: any) => {
|
||||
if (requestGeneration !== chunkRequestGeneration || activeKnowledgeId !== id) return;
|
||||
details.chunkLoadError = err?.message || t('knowledgeBase.chunkLoadFailed');
|
||||
console.error("[ChunkLoad] failed", {
|
||||
knowledgeId: id,
|
||||
page,
|
||||
error: err,
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
if (requestGeneration === chunkRequestGeneration) {
|
||||
details.chunkLoading = false;
|
||||
}
|
||||
});
|
||||
};
|
||||
return {
|
||||
cardList,
|
||||
moreIndex,
|
||||
getKnowled,
|
||||
details,
|
||||
openMore,
|
||||
onVisibleChange,
|
||||
getCardDetails,
|
||||
total,
|
||||
getfDetails,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
/**
|
||||
* Provides a shared navigation helper for knowledge-base creation success.
|
||||
* Redirects to the knowledge-base list page and highlights the newly created KB.
|
||||
*/
|
||||
export const useKnowledgeBaseCreationNavigation = () => {
|
||||
const router = useRouter()
|
||||
|
||||
const navigateToKnowledgeBaseList = (kbId: string) => {
|
||||
if (!kbId) return
|
||||
router.push({
|
||||
path: '/platform/knowledge-bases',
|
||||
query: { highlightKbId: kbId },
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
navigateToKnowledgeBaseList,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
import { computed, onBeforeUnmount, ref, type Ref } from 'vue';
|
||||
|
||||
type Rect = { left: number; top: number; right: number; bottom: number };
|
||||
/** iOS Photos select-mode marquee: add or subtract for the whole gesture. */
|
||||
type MarqueeMode = 'add' | 'subtract';
|
||||
|
||||
const IGNORE_TARGET_SELECTOR = [
|
||||
'button',
|
||||
'a',
|
||||
'input',
|
||||
'textarea',
|
||||
'select',
|
||||
'label',
|
||||
'.t-checkbox',
|
||||
'.more-wrap',
|
||||
'.card-menu',
|
||||
'.card-menu-item',
|
||||
'.card-tag-selector',
|
||||
'.row-more-btn',
|
||||
'.row-menu',
|
||||
'.row-menu-item',
|
||||
'.doc-list-header',
|
||||
].join(', ');
|
||||
|
||||
const DEFAULT_MIN_DRAG_PX = 6;
|
||||
|
||||
function normalizeRect(x1: number, y1: number, x2: number, y2: number): Rect {
|
||||
return {
|
||||
left: Math.min(x1, x2),
|
||||
top: Math.min(y1, y2),
|
||||
right: Math.max(x1, x2),
|
||||
bottom: Math.max(y1, y2),
|
||||
};
|
||||
}
|
||||
|
||||
function rectsIntersect(a: Rect, b: DOMRect): boolean {
|
||||
return !(a.right < b.left || a.left > b.right || a.bottom < b.top || a.top > b.bottom);
|
||||
}
|
||||
|
||||
function shouldIgnoreTarget(target: EventTarget | null): boolean {
|
||||
if (!(target instanceof Element)) return true;
|
||||
return !!target.closest(IGNORE_TARGET_SELECTOR);
|
||||
}
|
||||
|
||||
/**
|
||||
* iOS Photos「选择」模式框选规则:
|
||||
* - 手势起点落在未选中项(或空白区域)→ 本次拖选全程追加选中
|
||||
* - 手势起点落在已选中项 → 本次拖选全程取消选中
|
||||
*/
|
||||
function resolveMarqueeModeFromStart(
|
||||
e: MouseEvent,
|
||||
itemSelector: string,
|
||||
getItemId: (el: HTMLElement) => string | null,
|
||||
selectedIds: Set<string>,
|
||||
): MarqueeMode {
|
||||
const target = e.target;
|
||||
if (!(target instanceof Element)) return 'add';
|
||||
const itemEl = target.closest<HTMLElement>(itemSelector);
|
||||
if (!itemEl) return 'add';
|
||||
const id = getItemId(itemEl);
|
||||
if (!id) return 'add';
|
||||
return selectedIds.has(id) ? 'subtract' : 'add';
|
||||
}
|
||||
|
||||
export interface UseMarqueeSelectOptions {
|
||||
containerRef: Ref<HTMLElement | null>;
|
||||
itemSelector: string;
|
||||
selectedIds: Ref<Set<string>>;
|
||||
getItemId: (el: HTMLElement) => string | null;
|
||||
enabled?: Ref<boolean>;
|
||||
onSelectionStart?: () => void;
|
||||
minDragDistance?: number;
|
||||
}
|
||||
|
||||
export function useMarqueeSelect(options: UseMarqueeSelectOptions) {
|
||||
const {
|
||||
containerRef,
|
||||
itemSelector,
|
||||
selectedIds,
|
||||
getItemId,
|
||||
enabled,
|
||||
onSelectionStart,
|
||||
minDragDistance = DEFAULT_MIN_DRAG_PX,
|
||||
} = options;
|
||||
|
||||
const isActive = ref(false);
|
||||
const boxVisible = ref(false);
|
||||
const boxStyle = ref<Record<string, string>>({});
|
||||
const suppressClickUntil = ref(0);
|
||||
const marqueeMode = ref<MarqueeMode>('add');
|
||||
|
||||
let startClientX = 0;
|
||||
let startClientY = 0;
|
||||
let currentClientX = 0;
|
||||
let currentClientY = 0;
|
||||
let baseSelection = new Set<string>();
|
||||
let dragMode: MarqueeMode = 'add';
|
||||
|
||||
const updateBoxStyle = () => {
|
||||
const container = containerRef.value;
|
||||
if (!container) return;
|
||||
const rect = container.getBoundingClientRect();
|
||||
const left = Math.min(startClientX, currentClientX) - rect.left + container.scrollLeft;
|
||||
const top = Math.min(startClientY, currentClientY) - rect.top + container.scrollTop;
|
||||
const width = Math.abs(currentClientX - startClientX);
|
||||
const height = Math.abs(currentClientY - startClientY);
|
||||
boxStyle.value = {
|
||||
left: `${left}px`,
|
||||
top: `${top}px`,
|
||||
width: `${width}px`,
|
||||
height: `${height}px`,
|
||||
};
|
||||
};
|
||||
|
||||
const collectIntersectingIds = (): Set<string> => {
|
||||
const container = containerRef.value;
|
||||
if (!container) return new Set();
|
||||
const box = normalizeRect(startClientX, startClientY, currentClientX, currentClientY);
|
||||
const ids = new Set<string>();
|
||||
container.querySelectorAll<HTMLElement>(itemSelector).forEach((el) => {
|
||||
const id = getItemId(el);
|
||||
if (!id) return;
|
||||
if (rectsIntersect(box, el.getBoundingClientRect())) ids.add(id);
|
||||
});
|
||||
return ids;
|
||||
};
|
||||
|
||||
const applyMarqueeSelection = () => {
|
||||
const hit = collectIntersectingIds();
|
||||
const next = new Set(baseSelection);
|
||||
if (dragMode === 'subtract') {
|
||||
hit.forEach((id) => next.delete(id));
|
||||
} else {
|
||||
hit.forEach((id) => next.add(id));
|
||||
}
|
||||
selectedIds.value = next;
|
||||
};
|
||||
|
||||
const endDrag = () => {
|
||||
if (!isActive.value) return;
|
||||
isActive.value = false;
|
||||
boxVisible.value = false;
|
||||
marqueeMode.value = 'add';
|
||||
document.body.style.removeProperty('user-select');
|
||||
document.removeEventListener('mousemove', onDocumentMouseMove);
|
||||
document.removeEventListener('mouseup', onDocumentMouseUp);
|
||||
if (Math.hypot(currentClientX - startClientX, currentClientY - startClientY) >= minDragDistance) {
|
||||
suppressClickUntil.value = Date.now() + 150;
|
||||
}
|
||||
};
|
||||
|
||||
const onDocumentMouseMove = (e: MouseEvent) => {
|
||||
if (!isActive.value) return;
|
||||
currentClientX = e.clientX;
|
||||
currentClientY = e.clientY;
|
||||
const distance = Math.hypot(currentClientX - startClientX, currentClientY - startClientY);
|
||||
if (!boxVisible.value && distance >= minDragDistance) {
|
||||
boxVisible.value = true;
|
||||
marqueeMode.value = dragMode;
|
||||
onSelectionStart?.();
|
||||
}
|
||||
if (boxVisible.value) {
|
||||
updateBoxStyle();
|
||||
applyMarqueeSelection();
|
||||
}
|
||||
};
|
||||
|
||||
const onDocumentMouseUp = () => {
|
||||
endDrag();
|
||||
};
|
||||
|
||||
const onContainerMouseDown = (e: MouseEvent) => {
|
||||
if (e.button !== 0) return;
|
||||
if (enabled && !enabled.value) return;
|
||||
if (shouldIgnoreTarget(e.target)) return;
|
||||
|
||||
const container = containerRef.value;
|
||||
if (!container) return;
|
||||
|
||||
dragMode = resolveMarqueeModeFromStart(e, itemSelector, getItemId, selectedIds.value);
|
||||
baseSelection = new Set(selectedIds.value);
|
||||
|
||||
isActive.value = true;
|
||||
startClientX = e.clientX;
|
||||
startClientY = e.clientY;
|
||||
currentClientX = e.clientX;
|
||||
currentClientY = e.clientY;
|
||||
boxVisible.value = false;
|
||||
boxStyle.value = {};
|
||||
|
||||
document.body.style.userSelect = 'none';
|
||||
document.addEventListener('mousemove', onDocumentMouseMove);
|
||||
document.addEventListener('mouseup', onDocumentMouseUp);
|
||||
};
|
||||
|
||||
const shouldSuppressClick = () => Date.now() < suppressClickUntil.value;
|
||||
|
||||
const marqueeVisible = computed(() => boxVisible.value);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
endDrag();
|
||||
});
|
||||
|
||||
return {
|
||||
onContainerMouseDown,
|
||||
marqueeVisible,
|
||||
marqueeMode,
|
||||
boxStyle,
|
||||
shouldSuppressClick,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user