WeKnora/frontend/src/views/knowledge/assistantRefresh.test.ts

120 lines
6.6 KiB
TypeScript
Raw Normal View History

feat(assistant): manage agents and skills, separate history, refresh pages (#4344) * feat(assistant): let the assistant manage agents Expose custom agents to the operation catalog (list, get, create, copy, update, delete) plus read-only model and MCP service lookups, so the assistant can set up agents end to end. - Add PATCH /api/v1/agents/:id. PUT replaces the whole config, so a one-field change from the assistant would wipe the rest; PATCH only overlays the fields it carries and reuses the PUT validation path. - Add x-agent-detail so long fields such as the system prompt are only projected for single-object reads, not lists. - Add label_param so a create without a target is labelled by its name. - The approval card lists agent setting changes and resolves model, knowledge base and MCP IDs to names. - Deny sharing, publishing channels, credentials and OAuth routes; model and MCP endpoints, headers and secrets are never projected. - Update the assistant prompt, starters, API docs and Go SDK. * feat(assistant): list skills and configure agent skill scope - Expose usable skill names for an agent sandbox without exposing skill administration or connection settings to the model. - Validate PATCH selections against the workspace sandbox usable set so invented names and missing sandbox selections cannot be saved. - Show skill changes in approvals and align the assistant prompt, API documentation, and Go SDK with focused refusal and projection tests. * feat(assistant): isolate conversation history - Keep assistant conversations out of ordinary session lists, search, artifacts and delete-all cleanup. - Add private, paginated assistant history with session switching, confirmed deletion and stale-session recovery. - Backfill session kinds safely on Postgres and SQLite, preserve kinds on forks, and align API docs and SDK coverage. * feat(assistant): refresh pages after successful data changes - Carry decoded mutation targets through live tool-result events without exposing refresh metadata to the model or persisted chat history. - Coalesce page and selector refreshes, update document drawers, and warn about changed agents while preserving open editor drafts. - Cover mutation, approval, stream, lifecycle and cache behavior with Go and Node tests using the existing frontend runner and component fixtures. * feat(assistant): add agent page context and resource scope limits - Attach verified agent context and persist personal scope across turns and approvals. - Enforce resource boundaries before operation and Wiki approvals, including edited arguments. - Add scope controls, translations, API and SDK support, and regression coverage. * refactor(assistant): remove the scope limit The scope picker confused users and duplicated what RBAC and the access level already enforce. Keep the agent page context: the agent editor still publishes agent_id and the backend still verifies it. * feat(assistant): render operation and product-doc results Show find/run operations and WeKnora docs as structured cards instead of raw JSON. * feat(assistant): default new agents to smart-reasoning Quick-answer cannot call MCP, and agent.update could not change the mode. New agents now start in smart-reasoning, and a patch can switch agent_mode. * fix: resolve assistant management CI failures
2026-10-15 13:43:20 +00:00
import assert from 'node:assert/strict'
import test from 'node:test'
import * as vue from 'vue'
import * as marked from 'marked'
import * as literalTilde from '../../utils/markedLiteralTilde.ts'
import * as sorting from '../../utils/resourceSorting.ts'
import { change, fixture, flush } from '../../test-utils/vueFixture.ts'
test('refreshes the FAQ entries and tags once per burst for its own KB only', async t => {
const f = fixture(t)
const listFAQEntries = t.mock.fn(async (_id: string, _params: unknown) => ({ data: { data: [], total: 1 } }))
const listKnowledgeTags = t.mock.fn(async (_id: string, _params: unknown) => ({ data: { data: [], total: 0 } }))
f.component(new URL('./components/FAQEntryManager.vue', import.meta.url), {
'vue-router': { useRouter: () => ({}) },
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
'tdesign-vue-next': { MessagePlugin: { error: assert.fail } },
'@/components/settings/useConfirmDelete': { useConfirmDelete: () => ({}) },
'@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
'@/stores/ui': { useUIStore: () => ({ clearSelectedTagIds() {} }) },
'@/stores/organization': { useOrganizationStore: () => ({ sharedKnowledgeBases: [], async fetchSharedKnowledgeBases() {} }) },
'@/stores/chatResources': { useChatResourcesStore: () => ({ rawKnowledgeBases: [], async ensureKnowledgeBases() {} }) },
'@/api/knowledge-base': {
listFAQEntries, listKnowledgeTags,
getKnowledgeBaseById: async () => ({ data: { id: 'kb', type: 'faq' } }),
},
xlsx: {}, papaparse: {},
}, { kbId: 'kb' })
await flush()
listFAQEntries.mock.resetCalls()
listKnowledgeTags.mock.resetCalls()
f.emit(change('faq.update_entry', { knowledge_base_id: ['other'] }))
f.emit(change('agent.create', { knowledge_base_id: ['kb'] }))
t.mock.timers.tick(300)
assert.equal(listFAQEntries.mock.callCount(), 0)
assert.equal(listKnowledgeTags.mock.callCount(), 0)
f.emit(change('faq.update_entry', { knowledge_base_id: ['kb'] }))
f.emit(change('faq.delete_entries', { knowledge_base_id: ['kb'] }))
t.mock.timers.tick(300)
await flush()
assert.equal(listFAQEntries.mock.callCount(), 1)
assert.equal(listKnowledgeTags.mock.callCount(), 1)
assert.equal(listFAQEntries.mock.calls[0].arguments[0], 'kb')
assert.equal(listKnowledgeTags.mock.calls[0].arguments[0], 'kb')
assert.equal((listKnowledgeTags.mock.calls[0].arguments[1] as any).page, 1)
})
test('refreshes Wiki pages, selected content and statistics for its own KB only', async t => {
const f = fixture(t)
const page = { id: 'page', slug: 'page', title: 'Updated title', content: '', version: 2 }
const getWikiPage = t.mock.fn(async (_id: string, _slug: string) => ({ data: page }))
const getWikiIndex = t.mock.fn(async () => ({ groups: [] }))
const getWikiStats = t.mock.fn(async () => ({}))
const { vm } = f.component(new URL('./wiki/WikiBrowser.vue', import.meta.url), {
marked,
'vue-router': { useRouter: () => ({}), useRoute: () => ({ query: {} }) },
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
'tdesign-vue-next': { MessagePlugin: { error: assert.fail } },
'@/stores/assistant': { useAssistantStore: () => ({ visible: false }) },
'@/composables/useAssistantPageContext': { useAssistantPageContext() {} },
'@/stores/settings': { useSettingsStore: () => ({}) },
'@/api/wiki': {
getWikiPage, getWikiIndex, getWikiStats,
listWikiIssues: async () => [], listWikiPages: async () => ({ pages: [], total: 0 }),
listWikiFolders: async () => ({ folders: [] }),
},
'@/utils/security': { sanitizeMarkdownHTML: (html: string) => html, hydrateProtectedFileImages: async () => {} },
'@/utils/markedLiteralTilde': literalTilde,
'vue-virtual-scroller': {}, '@/api/knowledge-base': {}, '@/api/chat': {},
}, { knowledgeBaseId: 'kb' })
await flush()
vm.selectedPage = { ...page, title: 'Old title' }
const reloads = [getWikiPage, getWikiIndex, getWikiStats]
reloads.forEach(reload => reload.mock.resetCalls())
f.emit(change('wiki.revert', { knowledge_base_id: ['other'] }))
f.emit(change('agent.create', { knowledge_base_id: ['kb'] }))
t.mock.timers.tick(300)
reloads.forEach(reload => assert.equal(reload.mock.callCount(), 0))
f.emit(change('wiki.revert', { knowledge_base_id: ['kb'] }))
f.emit(change('wiki.revert', { knowledge_base_id: ['kb'] }))
t.mock.timers.tick(300)
await flush()
reloads.forEach(reload => assert.equal(reload.mock.callCount(), 1))
assert.deepEqual(Array.from(getWikiPage.mock.calls[0].arguments), ['kb', 'page'])
assert.equal(vm.selectedPage.title, 'Updated title')
})
test('refreshes the mounted KB list with force for knowledge_base changes only', async t => {
const f = fixture(t)
const fetchKnowledgeBasesForList = t.mock.fn(async (_params: unknown, _force: boolean) => [{ id: 'kb', name: 'Updated KB' }])
const { vm } = f.component(new URL('./KnowledgeBaseList.vue', import.meta.url), {
'vue-router': { useRoute: () => ({ query: {} }), useRouter: () => ({}) },
'vue-i18n': { useI18n: () => ({ t: (key: string) => key }) },
'tdesign-vue-next': { MessagePlugin: {} },
'@/stores/auth': { useAuthStore: () => ({ hasRole: () => true }) },
'@/stores/ui': { useUIStore: () => ({}) },
'@/stores/organization': { useOrganizationStore: () => ({
sharedKnowledgeBases: [], async fetchOrganizations() {}, async fetchSharedKnowledgeBases() {},
}) },
'@/stores/chatResources': { useChatResourcesStore: () => ({ fetchKnowledgeBasesForList }) },
'@/components/settings/useConfirmDelete': { useConfirmDelete: () => ({}) },
'@/composables/useTenantModelReadiness': { useTenantModelReadiness: () => ({ loaded: vue.ref(true), isReadyForDocumentKb: vue.ref(true) }) },
'@/composables/useListUrlState': { useListUrlState: () => ({ scope: vue.ref('all'), creator: vue.ref('all'), query: vue.ref('') }) },
'@/composables/useResourcePins': { useResourcePins: () => ({ favorites: vue.ref([]), recents: vue.ref([]) }) },
'@/api/knowledge-base': {}, '@/api/organization': {}, '@/config/contextualGuides': {},
'@/utils/index': {}, '@/utils/kbPermission': {},
'@/utils/resourceListSearch': {}, '@/utils/card-list-badge': {}, '@/utils/resourceSorting': sorting,
})
await flush()
fetchKnowledgeBasesForList.mock.resetCalls()
f.emit(change('unknown.update'))
t.mock.timers.tick(300)
assert.equal(fetchKnowledgeBasesForList.mock.callCount(), 0)
f.emit(change('knowledge_base.generate_profile'))
t.mock.timers.tick(300)
await flush()
assert.equal(fetchKnowledgeBasesForList.mock.callCount(), 1)
assert.equal(fetchKnowledgeBasesForList.mock.calls[0].arguments[1], true)
assert.equal(vm.kbs[0].name, 'Updated KB')
})