chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)
This commit is contained in:
commit
9097ee699d
5769 files changed
+1446466
No files matched your search
@@ -0,0 +1,15 @@
|
||||
import { applyStreamingTailFade } from './chatMarkdownRenderer.ts'
|
||||
|
||||
const cases = [
|
||||
'<p>Great, that narrows it down a lot. Two more quick</p>',
|
||||
'<p>Great, that narrows it down a lot. <strong>Two</strong> more quick</p>\n',
|
||||
'<ol>\n<li>第一项</li>\n<li>正在生成的第二项内容</li>\n</ol>',
|
||||
'<p>结尾是引用 <span class="citation">doc</span></p>',
|
||||
'<p></p>',
|
||||
'',
|
||||
]
|
||||
for (const c of cases) {
|
||||
console.log('IN :', JSON.stringify(c))
|
||||
console.log('OUT:', JSON.stringify(applyStreamingTailFade(c)))
|
||||
console.log('')
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
const BUILTIN_QUICK_ANSWER_ID = 'builtin-quick-answer'
|
||||
const BUILTIN_SMART_REASONING_ID = 'builtin-smart-reasoning'
|
||||
|
||||
function isQuickAnswerAgentId(agentId) {
|
||||
return (agentId || BUILTIN_QUICK_ANSWER_ID) === BUILTIN_QUICK_ANSWER_ID
|
||||
}
|
||||
|
||||
function isAgentStreamAgentId(agentId, isAgentEnabled) {
|
||||
const id = agentId || BUILTIN_QUICK_ANSWER_ID
|
||||
if (id === BUILTIN_QUICK_ANSWER_ID) return false
|
||||
if (id === BUILTIN_SMART_REASONING_ID) return true
|
||||
return isAgentEnabled
|
||||
}
|
||||
|
||||
function reconcileBuiltinAgentMode(settings) {
|
||||
const agentId = settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID
|
||||
if (agentId === BUILTIN_QUICK_ANSWER_ID && settings.isAgentEnabled) {
|
||||
settings.isAgentEnabled = false
|
||||
return true
|
||||
}
|
||||
if (agentId === BUILTIN_SMART_REASONING_ID && !settings.isAgentEnabled) {
|
||||
settings.isAgentEnabled = true
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
test('isQuickAnswerAgentId treats builtin quick-answer as RAG mode', () => {
|
||||
assert.equal(isQuickAnswerAgentId('builtin-quick-answer'), true)
|
||||
assert.equal(isQuickAnswerAgentId(undefined), true)
|
||||
assert.equal(isQuickAnswerAgentId('builtin-smart-reasoning'), false)
|
||||
})
|
||||
|
||||
test('isAgentStreamAgentId prefers selectedAgentId for builtins', () => {
|
||||
assert.equal(
|
||||
isAgentStreamAgentId('builtin-quick-answer', true),
|
||||
false,
|
||||
'stale isAgentEnabled must not flip quick-answer into agent stream',
|
||||
)
|
||||
assert.equal(isAgentStreamAgentId('builtin-smart-reasoning', false), true)
|
||||
assert.equal(isAgentStreamAgentId('custom-agent', true), true)
|
||||
assert.equal(isAgentStreamAgentId('custom-agent', false), false)
|
||||
})
|
||||
|
||||
test('reconcileBuiltinAgentMode repairs drifted localStorage flags', () => {
|
||||
const quick = { selectedAgentId: 'builtin-quick-answer', isAgentEnabled: true }
|
||||
assert.equal(reconcileBuiltinAgentMode(quick), true)
|
||||
assert.equal(quick.isAgentEnabled, false)
|
||||
|
||||
const reasoning = { selectedAgentId: 'builtin-smart-reasoning', isAgentEnabled: false }
|
||||
assert.equal(reconcileBuiltinAgentMode(reasoning), true)
|
||||
assert.equal(reasoning.isAgentEnabled, true)
|
||||
|
||||
const custom = { selectedAgentId: 'custom-agent', isAgentEnabled: true }
|
||||
assert.equal(reconcileBuiltinAgentMode(custom), false)
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
import {
|
||||
BUILTIN_QUICK_ANSWER_ID,
|
||||
BUILTIN_SMART_REASONING_ID,
|
||||
BUILTIN_TRAINING_COACH_ID,
|
||||
} from '@/api/agent'
|
||||
|
||||
/** Whether the selected agent id is the builtin quick-answer (RAG) mode. */
|
||||
export function isQuickAnswerAgentId(agentId: string | null | undefined): boolean {
|
||||
return (agentId || BUILTIN_QUICK_ANSWER_ID) === BUILTIN_QUICK_ANSWER_ID
|
||||
}
|
||||
|
||||
/** Whether requests should use the Agent stream pipeline (not quick-answer RAG). */
|
||||
export function isAgentStreamAgentId(
|
||||
agentId: string | null | undefined,
|
||||
isAgentEnabled: boolean,
|
||||
): boolean {
|
||||
const id = agentId || BUILTIN_QUICK_ANSWER_ID
|
||||
if (id === BUILTIN_QUICK_ANSWER_ID) return false
|
||||
if (id === BUILTIN_SMART_REASONING_ID) return true
|
||||
// Training coach is a smart-reasoning preset: always the ReAct stream.
|
||||
if (id === BUILTIN_TRAINING_COACH_ID) return true
|
||||
return isAgentEnabled
|
||||
}
|
||||
|
||||
/** Reconcile builtin agent id with isAgentEnabled after localStorage reload. */
|
||||
export function reconcileBuiltinAgentMode(settings: {
|
||||
selectedAgentId?: string
|
||||
isAgentEnabled: boolean
|
||||
}): boolean {
|
||||
const agentId = settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID
|
||||
if (agentId === BUILTIN_QUICK_ANSWER_ID && settings.isAgentEnabled) {
|
||||
settings.isAgentEnabled = false
|
||||
return true
|
||||
}
|
||||
if (
|
||||
(agentId === BUILTIN_SMART_REASONING_ID || agentId === BUILTIN_TRAINING_COACH_ID) &&
|
||||
!settings.isAgentEnabled
|
||||
) {
|
||||
settings.isAgentEnabled = true
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
agentHasConfiguredChatModel,
|
||||
agentRequiresRerankModel,
|
||||
canLocallyConfigureAgent,
|
||||
getAgentNotReadyReasonKeys,
|
||||
resolveAgentNotReadySection,
|
||||
resolveAgentNotReadyHighlight,
|
||||
} from './agent-readiness.ts'
|
||||
|
||||
test('does not treat an unrelated built-in chat model as agent configuration', () => {
|
||||
assert.equal(agentHasConfiguredChatModel(
|
||||
{},
|
||||
[{ id: 'builtin-chat', type: 'KnowledgeQA' }],
|
||||
), false)
|
||||
})
|
||||
|
||||
test('accepts the chat model explicitly configured on the agent', () => {
|
||||
assert.equal(agentHasConfiguredChatModel(
|
||||
{ model_id: 'builtin-chat' },
|
||||
[{ id: 'builtin-chat', type: 'KnowledgeQA' }],
|
||||
), true)
|
||||
})
|
||||
|
||||
test('rejects a configured chat model that no longer exists', () => {
|
||||
assert.equal(agentHasConfiguredChatModel(
|
||||
{ model_id: 'deleted-chat' },
|
||||
[{ id: 'builtin-chat', type: 'KnowledgeQA' }],
|
||||
), false)
|
||||
})
|
||||
|
||||
test('requires rerank when search_knowledge has a knowledge-base scope', () => {
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'all',
|
||||
allowed_tools: ['search_knowledge'],
|
||||
}), true)
|
||||
})
|
||||
|
||||
test('still requires rerank for configs saved with the retired knowledge_search name', () => {
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'all',
|
||||
allowed_tools: ['knowledge_search'],
|
||||
}), true)
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'selected',
|
||||
allowed_tools: ['thinking', 'grep_chunks'],
|
||||
}), true)
|
||||
})
|
||||
|
||||
test('does not require rerank for read-only document tools', () => {
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'all',
|
||||
allowed_tools: ['read_document', 'list_documents'],
|
||||
}), false)
|
||||
})
|
||||
|
||||
test('does not require rerank when knowledge bases are disabled', () => {
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'none',
|
||||
allowed_tools: ['search_knowledge'],
|
||||
}), false)
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'none',
|
||||
allowed_tools: ['knowledge_search'],
|
||||
}), false)
|
||||
})
|
||||
|
||||
test('does not require rerank for wiki-only tools', () => {
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'all',
|
||||
allowed_tools: ['wiki_search', 'wiki_read_page'],
|
||||
}), false)
|
||||
})
|
||||
|
||||
test('matches backend default-tool behavior', () => {
|
||||
// Never set: the backend's default tools, which include search_knowledge.
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'all',
|
||||
allowed_tools: undefined,
|
||||
}), true)
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'all',
|
||||
allowed_tools: null,
|
||||
}), true)
|
||||
// Empty: no built-in tools, so nothing calls the reranker.
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'all',
|
||||
allowed_tools: [],
|
||||
}), false)
|
||||
assert.equal(agentRequiresRerankModel({
|
||||
kb_selection_mode: 'none',
|
||||
allowed_tools: [],
|
||||
}), false)
|
||||
})
|
||||
|
||||
test('resolveAgentNotReadySection opens model config for model issues', () => {
|
||||
assert.equal(resolveAgentNotReadySection(['summary_model']), 'model')
|
||||
assert.equal(resolveAgentNotReadySection(['rerank_model']), 'model')
|
||||
assert.equal(resolveAgentNotReadySection(['summary_model', 'allowed_tools']), 'model')
|
||||
})
|
||||
|
||||
test('resolveAgentNotReadySection opens tools config when only tools are missing', () => {
|
||||
assert.equal(resolveAgentNotReadySection(['allowed_tools']), 'tools')
|
||||
})
|
||||
|
||||
test('resolveAgentNotReadyHighlight returns the first missing item', () => {
|
||||
assert.equal(resolveAgentNotReadyHighlight(['summary_model', 'rerank_model']), 'summary_model')
|
||||
assert.equal(resolveAgentNotReadyHighlight(['allowed_tools']), 'allowed_tools')
|
||||
assert.equal(resolveAgentNotReadyHighlight([]), undefined)
|
||||
})
|
||||
|
||||
test('getAgentNotReadyReasonKeys flags missing chat model', () => {
|
||||
assert.deepEqual(getAgentNotReadyReasonKeys(
|
||||
{},
|
||||
[{ id: 'chat-1', type: 'KnowledgeQA' }],
|
||||
{ isAgentMode: false, isSharedAgent: false },
|
||||
), ['summary_model'])
|
||||
})
|
||||
|
||||
test('getAgentNotReadyReasonKeys requires rerank only in agent mode with KB search', () => {
|
||||
assert.deepEqual(getAgentNotReadyReasonKeys(
|
||||
{ kb_selection_mode: 'all', allowed_tools: ['search_knowledge'] },
|
||||
[{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }],
|
||||
{ isAgentMode: true, isSharedAgent: false },
|
||||
), ['summary_model', 'rerank_model'])
|
||||
assert.deepEqual(getAgentNotReadyReasonKeys(
|
||||
{ kb_selection_mode: 'all', allowed_tools: ['knowledge_search'] },
|
||||
[{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }],
|
||||
{ isAgentMode: true, isSharedAgent: false },
|
||||
), ['summary_model', 'rerank_model'])
|
||||
})
|
||||
|
||||
test('getAgentNotReadyReasonKeys does not treat current shared context as shared without sourceTenantId', () => {
|
||||
assert.deepEqual(getAgentNotReadyReasonKeys(
|
||||
{ model_id: 'deleted-chat' },
|
||||
[{ id: 'chat-1', type: 'KnowledgeQA' }],
|
||||
{ isAgentMode: false, isSharedAgent: false },
|
||||
), ['summary_model'])
|
||||
})
|
||||
|
||||
test('getAgentNotReadyReasonKeys treats an empty allowed_tools with a rerank model as ready', () => {
|
||||
assert.deepEqual(getAgentNotReadyReasonKeys(
|
||||
{
|
||||
model_id: 'chat-1',
|
||||
rerank_model_id: 'rerank-1',
|
||||
kb_selection_mode: 'all',
|
||||
allowed_tools: [],
|
||||
},
|
||||
[{ id: 'chat-1', type: 'KnowledgeQA' }, { id: 'rerank-1', type: 'Rerank' }],
|
||||
{ isAgentMode: true, isSharedAgent: false },
|
||||
), [])
|
||||
})
|
||||
|
||||
test('canLocallyConfigureAgent is false for shared agents', () => {
|
||||
assert.equal(canLocallyConfigureAgent('42'), false)
|
||||
assert.equal(canLocallyConfigureAgent(undefined), true)
|
||||
assert.equal(canLocallyConfigureAgent(''), true)
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { CustomAgentConfig } from '@/api/agent'
|
||||
import type { ModelConfig } from '@/api/model'
|
||||
import { allowedToolsInclude } from './legacy-tool-names'
|
||||
|
||||
export type AgentNotReadyReasonKey = 'summary_model' | 'rerank_model' | 'allowed_tools'
|
||||
|
||||
/**
|
||||
* An agent is chat-ready only when it explicitly references a usable chat
|
||||
* model. Merely having some built-in/default model in the tenant must not hide
|
||||
* incomplete agent configuration.
|
||||
*
|
||||
* For shared agents the model belongs to the source tenant, so the caller can
|
||||
* require a non-empty ID but must leave existence validation to the backend.
|
||||
*/
|
||||
export function agentHasConfiguredChatModel(
|
||||
config: Pick<CustomAgentConfig, 'model_id'> | undefined,
|
||||
models: Pick<ModelConfig, 'id' | 'type'>[],
|
||||
sourceModelIsRemote = false,
|
||||
): boolean {
|
||||
const modelID = config?.model_id?.trim()
|
||||
if (!modelID) return false
|
||||
if (sourceModelIsRemote) return true
|
||||
return models.some(model => model.type === 'KnowledgeQA' && model.id === modelID)
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep this aligned with backend agentRequiresRerankModel.
|
||||
*
|
||||
* Rerank is needed only when search_knowledge can actually run. Explicitly
|
||||
* disabling the knowledge-base scope makes KB tools ineffective, even if an
|
||||
* older agent configuration still contains the tool in allowed_tools.
|
||||
*
|
||||
* Stored configs may still carry the retired `knowledge_search` name (and
|
||||
* `grep_chunks`, which was folded into search_knowledge); those count too.
|
||||
*/
|
||||
export function agentRequiresRerankModel(
|
||||
config: Pick<CustomAgentConfig, 'kb_selection_mode' | 'allowed_tools'> | undefined,
|
||||
): boolean {
|
||||
if (!config || config.kb_selection_mode === 'none') return false
|
||||
|
||||
// An unset list selects the backend's DefaultAllowedTools, which include
|
||||
// search_knowledge. An empty list registers no built-in tool.
|
||||
if (config.allowed_tools == null) return true
|
||||
|
||||
return allowedToolsInclude(config.allowed_tools, 'search_knowledge')
|
||||
}
|
||||
|
||||
export function getAgentNotReadyReasonKeys(
|
||||
config: Pick<
|
||||
CustomAgentConfig,
|
||||
'model_id' | 'rerank_model_id' | 'kb_selection_mode' | 'allowed_tools' | 'agent_mode'
|
||||
> | undefined,
|
||||
models: Pick<ModelConfig, 'id' | 'type'>[],
|
||||
options: { isAgentMode: boolean; isSharedAgent: boolean },
|
||||
): AgentNotReadyReasonKey[] {
|
||||
const reasons: AgentNotReadyReasonKey[] = []
|
||||
|
||||
if (!agentHasConfiguredChatModel(config, models, options.isSharedAgent)) {
|
||||
reasons.push('summary_model')
|
||||
}
|
||||
|
||||
if (options.isAgentMode && agentRequiresRerankModel(config)) {
|
||||
const rerankModelID = config?.rerank_model_id?.trim()
|
||||
const rerankExists = !!rerankModelID && (
|
||||
options.isSharedAgent
|
||||
|| models.some(model => model.type === 'Rerank' && model.id === rerankModelID)
|
||||
)
|
||||
if (!rerankExists) {
|
||||
reasons.push('rerank_model')
|
||||
}
|
||||
}
|
||||
|
||||
return reasons
|
||||
}
|
||||
|
||||
/** Shared agents are owned by another tenant; receivers cannot edit their config. */
|
||||
export function canLocallyConfigureAgent(sourceTenantId?: string): boolean {
|
||||
return !sourceTenantId
|
||||
}
|
||||
|
||||
/** Map missing-config reasons to the agent editor section that fixes them. */
|
||||
export function resolveAgentNotReadySection(reasons: AgentNotReadyReasonKey[]): string {
|
||||
if (reasons.includes('summary_model') || reasons.includes('rerank_model')) {
|
||||
return 'model'
|
||||
}
|
||||
if (reasons.includes('allowed_tools')) {
|
||||
return 'tools'
|
||||
}
|
||||
return 'model'
|
||||
}
|
||||
|
||||
/** First missing item — used to highlight the corresponding editor field after navigation. */
|
||||
export function resolveAgentNotReadyHighlight(
|
||||
reasons: AgentNotReadyReasonKey[],
|
||||
): AgentNotReadyReasonKey | undefined {
|
||||
return reasons[0]
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { getAgentToolIconName } from './agent-tool-icons.ts'
|
||||
import {
|
||||
getKnowledgeSearchSummaryHtml,
|
||||
getQueryText,
|
||||
getRagPipelineStepTitle,
|
||||
getWikiPageText,
|
||||
} from './agent-tool-display.ts'
|
||||
|
||||
const t = (key, params) => {
|
||||
if (key === 'agentStream.search.foundResultsFromFiles') {
|
||||
return `found ${params?.count} from ${params?.files} files`
|
||||
}
|
||||
if (key === 'agentStream.search.candidatesBelowThreshold') {
|
||||
return `matched ${params?.count}, none relevant`
|
||||
}
|
||||
if (key === 'agentStream.ragPipeline.searchingWithQuery') {
|
||||
return `searching ${params?.query}`
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
test('getAgentToolIconName maps rag pipeline tools', () => {
|
||||
assert.equal(getAgentToolIconName('query_understand'), 'ai-search')
|
||||
assert.equal(getAgentToolIconName('knowledge_search'), 'data-search')
|
||||
})
|
||||
|
||||
test('getAgentToolIconName maps the consolidated knowledge tools and their retired names alike', () => {
|
||||
assert.equal(getAgentToolIconName('search_knowledge'), 'data-search')
|
||||
assert.equal(getAgentToolIconName('search_knowledge', 'web'), 'internet')
|
||||
assert.equal(getAgentToolIconName('read_document'), 'file-search')
|
||||
assert.equal(getAgentToolIconName('list_documents'), 'file-search')
|
||||
assert.equal(getAgentToolIconName('list_knowledge_chunks'), 'file-search')
|
||||
assert.equal(getAgentToolIconName('get_document_info'), 'file-search')
|
||||
})
|
||||
|
||||
test('getAgentToolIconName maps sandbox shell tools to the terminal icon', () => {
|
||||
assert.equal(getAgentToolIconName('shell_exec'), 'terminal')
|
||||
})
|
||||
|
||||
test('getAgentToolIconName maps skill and sandbox file tools', () => {
|
||||
assert.equal(getAgentToolIconName('read_file'), 'file')
|
||||
assert.equal(getAgentToolIconName('read_skill'), 'file')
|
||||
assert.equal(getAgentToolIconName('list_sandbox_files'), 'folder')
|
||||
assert.equal(getAgentToolIconName('read_sandbox_file'), 'file')
|
||||
assert.equal(getAgentToolIconName('execute_skill_script'), 'code')
|
||||
})
|
||||
|
||||
test('getAgentToolIconName maps operation and product-doc tools', () => {
|
||||
assert.equal(getAgentToolIconName('find_operations'), 'task')
|
||||
assert.equal(getAgentToolIconName('run_operation'), 'terminal')
|
||||
assert.equal(getAgentToolIconName('search_weknora_docs'), 'search')
|
||||
assert.equal(getAgentToolIconName('read_weknora_doc'), 'file')
|
||||
})
|
||||
|
||||
test('getAgentToolIconName maps Wiki tools to semantic search and reading icons', () => {
|
||||
assert.equal(getAgentToolIconName('wiki_search'), 'search')
|
||||
assert.equal(getAgentToolIconName('wiki_read_page'), 'file-search')
|
||||
assert.equal(getAgentToolIconName('wiki_read_source_doc'), 'file-search')
|
||||
})
|
||||
|
||||
test('getQueryText joins unique query strings', () => {
|
||||
assert.equal(getQueryText({ query: 'foo', queries: ['foo', 'bar'] }), 'foo,bar')
|
||||
})
|
||||
|
||||
test('getQueryText parses JSON-encoded queries string', () => {
|
||||
assert.equal(
|
||||
getQueryText({
|
||||
queries: '["合力天胜游泳俱乐部介绍", "合力天胜游泳训练机构", "合力天胜游泳队"]',
|
||||
}),
|
||||
'合力天胜游泳俱乐部介绍,合力天胜游泳训练机构,合力天胜游泳队',
|
||||
)
|
||||
})
|
||||
|
||||
test('getWikiPageText supports persisted slugs arrays', () => {
|
||||
assert.equal(
|
||||
getWikiPageText({ slugs: ['entity/知识助理', 'concept/API管理'] }),
|
||||
'entity/知识助理、concept/API管理',
|
||||
)
|
||||
assert.equal(getWikiPageText('{"slug":"index"}'), 'index')
|
||||
})
|
||||
|
||||
test('getKnowledgeSearchSummaryHtml includes file count when present', () => {
|
||||
const html = getKnowledgeSearchSummaryHtml(t, {
|
||||
results: [{}, {}],
|
||||
kb_counts: { a: 1, b: 2 },
|
||||
})
|
||||
assert.match(html, /found <strong>2<\/strong> from <strong>2<\/strong> files/)
|
||||
})
|
||||
|
||||
// Candidates that all fell below the relevance threshold never reached the
|
||||
// answer, so the row must not read like a plain empty search: the difference
|
||||
// points at the threshold rather than at the knowledge base.
|
||||
test('getKnowledgeSearchSummaryHtml distinguishes filtered candidates from an empty search', () => {
|
||||
assert.match(
|
||||
getKnowledgeSearchSummaryHtml(t, { count: 0, candidate_count: 10 }),
|
||||
/matched <strong>10<\/strong>, none relevant/,
|
||||
)
|
||||
assert.equal(
|
||||
getKnowledgeSearchSummaryHtml(t, { count: 0, candidate_count: 0 }),
|
||||
'agentStream.search.noResults',
|
||||
)
|
||||
})
|
||||
|
||||
test('getRagPipelineStepTitle uses query-aware search labels', () => {
|
||||
const title = getRagPipelineStepTitle(t, {
|
||||
tool_name: 'knowledge_search',
|
||||
pending: true,
|
||||
arguments: { query: '讯飞开放平台' },
|
||||
})
|
||||
assert.equal(title, 'searching 讯飞开放平台')
|
||||
})
|
||||
|
||||
test('getRagPipelineStepTitle uses web labels when search_source is web', () => {
|
||||
const title = getRagPipelineStepTitle(t, {
|
||||
tool_name: 'knowledge_search',
|
||||
pending: false,
|
||||
success: true,
|
||||
arguments: { search_source: 'web' },
|
||||
})
|
||||
assert.equal(title, 'agentStream.toolStatus.webSearch')
|
||||
})
|
||||
|
||||
test('getRagPipelineStepTitle uses attachment parsing labels', () => {
|
||||
assert.equal(
|
||||
getRagPipelineStepTitle(t, { tool_name: 'attachment_parsing', pending: true }),
|
||||
'agentStream.toolStatus.attachmentParsing',
|
||||
)
|
||||
assert.equal(
|
||||
getRagPipelineStepTitle(t, { tool_name: 'attachment_parsing', pending: false, success: true }),
|
||||
'agentStream.toolStatus.attachmentParsingDone',
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,213 @@
|
||||
import type { ComposerTranslation } from 'vue-i18n'
|
||||
|
||||
export type RetrievalSearchSource = 'knowledge' | 'web' | 'mixed'
|
||||
|
||||
function collectQueryStrings(value: unknown): string[] {
|
||||
if (value == null) return []
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return []
|
||||
if (trimmed.startsWith('[')) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed)
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed.filter((q): q is string => typeof q === 'string' && Boolean(q.trim()))
|
||||
}
|
||||
} catch {
|
||||
// fall through to treat as a single query string
|
||||
}
|
||||
}
|
||||
return [trimmed]
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.filter((q): q is string => typeof q === 'string' && Boolean(q.trim()))
|
||||
}
|
||||
|
||||
return []
|
||||
}
|
||||
|
||||
export function getQueryText(args: unknown): string {
|
||||
if (!args) return ''
|
||||
|
||||
let parsedArgs = args
|
||||
if (typeof parsedArgs === 'string') {
|
||||
try {
|
||||
parsedArgs = JSON.parse(parsedArgs)
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
if (!parsedArgs || typeof parsedArgs !== 'object') return ''
|
||||
|
||||
const queries: string[] = []
|
||||
const record = parsedArgs as Record<string, unknown>
|
||||
|
||||
queries.push(...collectQueryStrings(record.query))
|
||||
queries.push(...collectQueryStrings(record.queries))
|
||||
|
||||
return Array.from(new Set(queries)).join(',')
|
||||
}
|
||||
|
||||
export function getWikiPageText(args: unknown): string {
|
||||
if (!args) return ''
|
||||
|
||||
let parsedArgs = args
|
||||
if (typeof parsedArgs === 'string') {
|
||||
try {
|
||||
parsedArgs = JSON.parse(parsedArgs)
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
if (!parsedArgs || typeof parsedArgs !== 'object') return ''
|
||||
|
||||
const record = parsedArgs as Record<string, unknown>
|
||||
const slugs = [
|
||||
...collectQueryStrings(record.slug),
|
||||
...collectQueryStrings(record.slugs),
|
||||
]
|
||||
return Array.from(new Set(slugs)).join('、')
|
||||
}
|
||||
|
||||
export function getRetrievalSearchSource(
|
||||
args: unknown,
|
||||
toolData?: Record<string, unknown> | null,
|
||||
): RetrievalSearchSource {
|
||||
const fromArgs =
|
||||
args && typeof args === 'object'
|
||||
? String((args as Record<string, unknown>).search_source || '')
|
||||
: ''
|
||||
const fromData = toolData ? String(toolData.search_source || '') : ''
|
||||
const source = (fromData || fromArgs).trim()
|
||||
if (source === 'web' || source === 'mixed') {
|
||||
return source
|
||||
}
|
||||
return 'knowledge'
|
||||
}
|
||||
|
||||
function getRetrievalStatusKeys(source: RetrievalSearchSource, failed: boolean) {
|
||||
if (source === 'web') {
|
||||
return failed
|
||||
? { pending: 'agentStream.ragPipeline.searchingWeb', pendingWithQuery: 'agentStream.ragPipeline.searchingWebWithQuery', done: 'agentStream.toolStatus.webSearch', doneFailed: 'agentStream.toolStatus.webSearchFailed' }
|
||||
: { pending: 'agentStream.ragPipeline.searchingWeb', pendingWithQuery: 'agentStream.ragPipeline.searchingWebWithQuery', done: 'agentStream.toolStatus.webSearch', doneFailed: 'agentStream.toolStatus.webSearchFailed' }
|
||||
}
|
||||
if (source === 'mixed') {
|
||||
return {
|
||||
pending: 'agentStream.ragPipeline.searchingMixed',
|
||||
pendingWithQuery: 'agentStream.ragPipeline.searchingMixedWithQuery',
|
||||
done: 'agentStream.toolStatus.searchMixed',
|
||||
doneFailed: 'agentStream.toolStatus.searchMixedFailed',
|
||||
}
|
||||
}
|
||||
return {
|
||||
pending: 'agentStream.ragPipeline.searching',
|
||||
pendingWithQuery: 'agentStream.ragPipeline.searchingWithQuery',
|
||||
done: 'agentStream.toolStatus.searchKb',
|
||||
doneFailed: 'agentStream.toolStatus.searchKbFailed',
|
||||
}
|
||||
}
|
||||
|
||||
export function getKnowledgeSearchSummaryHtml(
|
||||
t: ComposerTranslation,
|
||||
toolData: Record<string, unknown> | null | undefined,
|
||||
): string {
|
||||
if (!toolData) return ''
|
||||
|
||||
const results = toolData.results
|
||||
const count = (Array.isArray(results) ? results.length : 0) || Number(toolData.count) || 0
|
||||
if (count === 0) {
|
||||
// Retrieval found candidates but none cleared the relevance threshold, so the
|
||||
// turn answered from the fallback with nothing retrieved in its context. Say
|
||||
// that rather than "no matching content": the difference is what tells you to
|
||||
// look at the threshold instead of the knowledge base.
|
||||
const candidateCount = Number(toolData.candidate_count) || 0
|
||||
if (candidateCount > 0) {
|
||||
return t('agentStream.search.candidatesBelowThreshold', {
|
||||
count: `<strong>${candidateCount}</strong>`,
|
||||
})
|
||||
}
|
||||
return t('agentStream.search.noResults')
|
||||
}
|
||||
|
||||
const searchSource = getRetrievalSearchSource(null, toolData)
|
||||
const webCount = Number(toolData.web_count) || 0
|
||||
const docCount = Number(toolData.doc_count) || 0
|
||||
|
||||
if (searchSource === 'web' || (webCount > 0 && docCount === 0)) {
|
||||
return t('agentStream.search.webResults', { count: `<strong>${count}</strong>` })
|
||||
}
|
||||
|
||||
const kbCounts = toolData.kb_counts
|
||||
const kbCount = kbCounts && typeof kbCounts === 'object' ? Object.keys(kbCounts).length : 0
|
||||
if (kbCount > 0) {
|
||||
return t('agentStream.search.foundResultsFromFiles', {
|
||||
count: `<strong>${count}</strong>`,
|
||||
files: `<strong>${kbCount}</strong>`,
|
||||
})
|
||||
}
|
||||
|
||||
if (searchSource === 'mixed' && docCount > 0 && webCount > 0) {
|
||||
return t('agentStream.search.foundMixedResults', {
|
||||
count: `<strong>${count}</strong>`,
|
||||
docCount: `<strong>${docCount}</strong>`,
|
||||
webCount: `<strong>${webCount}</strong>`,
|
||||
})
|
||||
}
|
||||
|
||||
return t('agentStream.search.foundResults', { count: `<strong>${count}</strong>` })
|
||||
}
|
||||
|
||||
type RagPipelineEvent = {
|
||||
tool_name?: string
|
||||
pending?: boolean
|
||||
success?: boolean
|
||||
arguments?: unknown
|
||||
tool_data?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export function getRagPipelineStepTitle(t: ComposerTranslation, event: RagPipelineEvent): string {
|
||||
const toolName = String(event.tool_name || '')
|
||||
const pending = event.pending === true
|
||||
const query =
|
||||
getQueryText(event.arguments) ||
|
||||
getQueryText(event.tool_data)
|
||||
|
||||
if (toolName === 'query_understand') {
|
||||
return pending
|
||||
? t('agentStream.toolStatus.queryUnderstanding')
|
||||
: t('agentStream.toolStatus.queryUnderstandDone')
|
||||
}
|
||||
|
||||
if (toolName === 'knowledge_search' || toolName === 'search_knowledge') {
|
||||
const searchSource = getRetrievalSearchSource(event.arguments, event.tool_data)
|
||||
const labels = getRetrievalStatusKeys(searchSource, event.success === false)
|
||||
if (pending) {
|
||||
return query
|
||||
? t(labels.pendingWithQuery, { query })
|
||||
: t(labels.pending)
|
||||
}
|
||||
|
||||
const baseTitle = event.success === false ? t(labels.doneFailed) : t(labels.done)
|
||||
return query ? `${baseTitle}:「${query}」` : baseTitle
|
||||
}
|
||||
|
||||
if (toolName === 'attachment_parsing') {
|
||||
if (pending) return t('agentStream.toolStatus.attachmentParsing')
|
||||
return event.success === false
|
||||
? t('agentStream.toolStatus.attachmentParsingFailed')
|
||||
: t('agentStream.toolStatus.attachmentParsingDone')
|
||||
}
|
||||
|
||||
if (toolName === 'image_analysis') {
|
||||
if (pending) return t('agentStream.toolStatus.imageAnalyzing')
|
||||
return event.success === false
|
||||
? t('agentStream.toolStatus.imageAnalysisFailed')
|
||||
: t('agentStream.toolStatus.imageAnalysisDone')
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
const COLLABORATION_TOOLS = new Set(['spawn_agent', 'list_agents', 'send_message', 'followup_task', 'interrupt_agent', 'wait_agent'])
|
||||
|
||||
/** Collaboration steps share the agent mark with child-task rows. */
|
||||
export function isCollaborationTool(toolName: string): boolean {
|
||||
return COLLABORATION_TOOLS.has(toolName)
|
||||
}
|
||||
|
||||
/** Semantic icon names shared by the agent and RAG timeline renderers. */
|
||||
export function getAgentToolIconName(
|
||||
toolName: string,
|
||||
searchSource?: 'knowledge' | 'web' | 'mixed',
|
||||
): string {
|
||||
if (toolName === 'local_browser') return 'browser'
|
||||
if (toolName === 'thinking') {
|
||||
return 'ai-search'
|
||||
}
|
||||
if (toolName === 'search_knowledge' || toolName === 'knowledge_search') {
|
||||
if (searchSource === 'web') {
|
||||
return 'internet'
|
||||
}
|
||||
return 'data-search'
|
||||
}
|
||||
if (toolName === 'wiki_search') {
|
||||
return 'search'
|
||||
}
|
||||
if (toolName === 'grep_chunks') {
|
||||
return 'search'
|
||||
}
|
||||
if (toolName === 'web_search' || toolName === 'web_fetch') {
|
||||
return 'internet'
|
||||
}
|
||||
if (toolName === 'read_document' || toolName === 'list_documents') {
|
||||
return 'file-search'
|
||||
}
|
||||
// Retired names still present in stored chat history
|
||||
if (toolName === 'get_document_info' || toolName === 'list_knowledge_chunks') {
|
||||
return 'file-search'
|
||||
}
|
||||
if (toolName === 'get_document_content' || toolName === 'wiki_read_page' || toolName === 'wiki_read_source_doc') {
|
||||
return 'file-search'
|
||||
}
|
||||
if (toolName === 'todo_write') {
|
||||
return 'task'
|
||||
}
|
||||
if (toolName === 'image_analysis' || toolName === 'query_understand') {
|
||||
return 'ai-search'
|
||||
}
|
||||
if (toolName === 'attachment_parsing') {
|
||||
return 'attach'
|
||||
}
|
||||
if (toolName === 'discover_mcp_tools') {
|
||||
return 'search'
|
||||
}
|
||||
if (toolName === 'call_mcp_tool' || toolName.startsWith('mcp_')) {
|
||||
return 'terminal'
|
||||
}
|
||||
if (toolName === 'shell_exec') {
|
||||
return 'terminal'
|
||||
}
|
||||
if (toolName === 'list_sandbox_files') {
|
||||
return 'folder'
|
||||
}
|
||||
if (toolName === 'read_file' || toolName === 'read_sandbox_file' || toolName === 'read_skill') {
|
||||
return 'file'
|
||||
}
|
||||
if (toolName === 'write_sandbox_file' || toolName === 'edit_sandbox_file') {
|
||||
return 'edit'
|
||||
}
|
||||
if (toolName === 'execute_skill_script') {
|
||||
return 'code'
|
||||
}
|
||||
if (toolName === 'find_operations') {
|
||||
return 'task'
|
||||
}
|
||||
if (toolName === 'run_operation') {
|
||||
return 'terminal'
|
||||
}
|
||||
if (isCollaborationTool(toolName)) {
|
||||
return 'agent'
|
||||
}
|
||||
if (toolName === 'open_page' || toolName === 'view_page') {
|
||||
return 'jump'
|
||||
}
|
||||
if (toolName === 'search_weknora_docs') {
|
||||
return 'search'
|
||||
}
|
||||
if (toolName === 'read_weknora_doc') {
|
||||
return 'file'
|
||||
}
|
||||
return 'file-paste'
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import type { AgentToolCatalog } from '../api/agent'
|
||||
import {
|
||||
allowedToolsToSave,
|
||||
buildToolOptions,
|
||||
effectiveToolSelection,
|
||||
resolveLoadedAllowedTools,
|
||||
storedExtraTools,
|
||||
} from './agent-tool-list.ts'
|
||||
import type { ScopeCapabilities } from './tool-capabilities.ts'
|
||||
|
||||
// Shaped like GET /api/v1/agents/tools, trimmed to the cases under test.
|
||||
const catalog: AgentToolCatalog = {
|
||||
tools: [
|
||||
{ name: 'thinking', label: '思考', description: 'd', group: 'base', requirement: {} },
|
||||
{ name: 'search_conversations', label: '回顾历史对话', description: 'd', group: 'base', requirement: {} },
|
||||
{ name: 'search_knowledge', label: '检索知识库', description: 'd', group: 'rag', requirement: { any_of: ['vector', 'keyword'] } },
|
||||
{ name: 'read_document', label: '阅读文档', description: 'd', group: 'rag', requirement: { any_of: ['vector', 'keyword', 'wiki'] } },
|
||||
{ name: 'wiki_delete_page', label: '删除Wiki', description: 'd', group: 'wiki_edit', danger: true, requirement: { all_of: ['wiki'] } },
|
||||
],
|
||||
default_tools: ['search_knowledge', 'read_document', 'search_conversations'],
|
||||
switch_managed_tools: ['web_search', 'search_memory'],
|
||||
}
|
||||
|
||||
const noKb: ScopeCapabilities = { vector: false, keyword: false, wiki: false, graph: false, faq: false }
|
||||
const ragKb: ScopeCapabilities = { ...noKb, vector: true, keyword: true }
|
||||
const noText = () => undefined
|
||||
|
||||
test('every catalog tool becomes a checkbox, including ones the editor has no translation for', () => {
|
||||
const options = buildToolOptions(catalog, [], ragKb, true, (name) =>
|
||||
name === 'thinking' ? { label: 'Thinking', description: 'Reflect' } : undefined,
|
||||
)
|
||||
assert.deepEqual(options.map((o) => o.value), catalog.tools.map((t) => t.name))
|
||||
const thinking = options.find((o) => o.value === 'thinking')!
|
||||
assert.equal(thinking.label, 'Thinking')
|
||||
const conversations = options.find((o) => o.value === 'search_conversations')!
|
||||
assert.equal(conversations.label, '回顾历史对话')
|
||||
assert.equal(options.find((o) => o.value === 'wiki_delete_page')!.danger, true)
|
||||
})
|
||||
|
||||
test('a missing capability blocks ticking a tool but never unticking it', () => {
|
||||
const unticked = buildToolOptions(catalog, [], noKb, false, noText).find((o) => o.value === 'search_knowledge')!
|
||||
assert.equal(unticked.unmet, true)
|
||||
assert.equal(unticked.missKind, 'needsKb')
|
||||
assert.equal(unticked.disabled, true)
|
||||
|
||||
// The knowledge-base-less agent that stores search_knowledge must be able to untick it.
|
||||
const ticked = buildToolOptions(catalog, ['search_knowledge'], noKb, false, noText).find((o) => o.value === 'search_knowledge')!
|
||||
assert.equal(ticked.unmet, true)
|
||||
assert.equal(ticked.disabled, false)
|
||||
})
|
||||
|
||||
test('stored names the catalog does not offer stay visible and removable', () => {
|
||||
const stored = ['search_knowledge', 'web_search', 'none', 'search_memory', 'none']
|
||||
const extras = storedExtraTools(catalog, stored, stored)
|
||||
assert.deepEqual(extras, [
|
||||
{ value: 'web_search', kind: 'switch_managed', disabled: false },
|
||||
{ value: 'none', kind: 'unrecognized', disabled: false },
|
||||
{ value: 'search_memory', kind: 'switch_managed', disabled: false },
|
||||
])
|
||||
|
||||
// Unticking keeps the entry on screen, but it cannot be ticked again.
|
||||
const afterUntick = storedExtraTools(catalog, stored, ['search_knowledge'])
|
||||
assert.deepEqual(afterUntick.map((e) => [e.value, e.disabled]), [
|
||||
['web_search', true], ['none', true], ['search_memory', true],
|
||||
])
|
||||
})
|
||||
|
||||
test('without a catalog nothing is classified, so stored values are left alone', () => {
|
||||
assert.deepEqual(buildToolOptions(null, ['none'], ragKb, true, noText), [])
|
||||
assert.deepEqual(storedExtraTools(null, ['none'], ['none']), [])
|
||||
})
|
||||
|
||||
test('an unset list shows the default tools the runtime uses', () => {
|
||||
const withKb = effectiveToolSelection(catalog, null, ragKb, true)
|
||||
assert.equal(withKb.usesDefaults, true)
|
||||
assert.deepEqual(withKb.names, ['search_conversations', 'search_knowledge', 'read_document'])
|
||||
assert.deepEqual(withKb.inactive, [])
|
||||
|
||||
// Without a knowledge base the runtime drops the retrieval defaults, so an
|
||||
// agent that never set a list ends up with search_conversations alone.
|
||||
const withoutKb = effectiveToolSelection(catalog, undefined, noKb, false)
|
||||
assert.deepEqual(withoutKb.names, ['search_conversations'])
|
||||
assert.deepEqual(withoutKb.inactive, [])
|
||||
})
|
||||
|
||||
test('a non-empty list registers the ticked tools the scope can serve and ignores the rest', () => {
|
||||
const selection = effectiveToolSelection(catalog, ['search_knowledge', 'thinking', 'web_search', 'none'], noKb, false)
|
||||
assert.equal(selection.usesDefaults, false)
|
||||
assert.deepEqual(selection.names, ['thinking'])
|
||||
assert.deepEqual(selection.inactive, ['search_knowledge'])
|
||||
})
|
||||
|
||||
test('an empty list registers no built-in tool', () => {
|
||||
const selection = effectiveToolSelection(catalog, [], ragKb, true)
|
||||
assert.equal(selection.usesDefaults, false)
|
||||
assert.deepEqual(selection.names, [])
|
||||
})
|
||||
|
||||
test('a list holding only names the catalog does not offer registers no default tool', () => {
|
||||
const selection = effectiveToolSelection(catalog, ['none', 'web_search'], ragKb, true)
|
||||
assert.equal(selection.usesDefaults, false)
|
||||
assert.deepEqual(selection.names, [])
|
||||
assert.deepEqual(selection.inactive, [])
|
||||
})
|
||||
|
||||
test('an unset list loads as the ticked default tools of a smart-reasoning agent', () => {
|
||||
assert.deepEqual(resolveLoadedAllowedTools(null, 'smart-reasoning', catalog),
|
||||
{ tools: catalog.default_tools, keepUnset: false })
|
||||
assert.deepEqual(resolveLoadedAllowedTools(undefined, 'smart-reasoning', catalog),
|
||||
{ tools: catalog.default_tools, keepUnset: false })
|
||||
})
|
||||
|
||||
test('an unset list stays unset without a catalog or outside smart-reasoning', () => {
|
||||
for (const [mode, cat] of [['smart-reasoning', null], ['quick-answer', catalog], [undefined, catalog]] as const) {
|
||||
const loaded = resolveLoadedAllowedTools(null, mode, cat)
|
||||
assert.deepEqual(loaded, { tools: [], keepUnset: true })
|
||||
assert.equal(allowedToolsToSave(loaded.tools, loaded.keepUnset), null, 'an untouched unset list saves as null')
|
||||
assert.deepEqual(allowedToolsToSave(['thinking'], loaded.keepUnset), ['thinking'], 'a ticked tool is saved as a list')
|
||||
}
|
||||
})
|
||||
|
||||
test('a stored list, empty or not, loads and saves as it is', () => {
|
||||
assert.deepEqual(resolveLoadedAllowedTools([], 'smart-reasoning', catalog), { tools: [], keepUnset: false })
|
||||
assert.deepEqual(allowedToolsToSave([], false), [])
|
||||
assert.deepEqual(resolveLoadedAllowedTools(['knowledge_search'], 'smart-reasoning', catalog),
|
||||
{ tools: ['knowledge_search'], keepUnset: false })
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Agent editor tool list.
|
||||
*
|
||||
* Builds what the agent editor shows for `allowed_tools` from the backend
|
||||
* tool catalog (`GET /api/v1/agents/tools`), so that the checkboxes, the
|
||||
* stored config and the tools the runtime registers can be read off the same
|
||||
* source. Two rules keep stored values reachable:
|
||||
* - a capability that the scope lacks only blocks ticking a tool; a ticked
|
||||
* tool stays clickable so it can be unticked;
|
||||
* - stored names the catalog does not offer are shown, ticked, so they can
|
||||
* be removed instead of being saved back unseen.
|
||||
*/
|
||||
import type { AgentToolCatalog, AgentToolRequirement } from '../api/agent'
|
||||
import {
|
||||
evaluateRequirement,
|
||||
type RequirementMissKind,
|
||||
type ScopeCapabilities,
|
||||
} from './tool-capabilities'
|
||||
|
||||
export interface ToolText {
|
||||
label: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface EditorToolOption extends ToolText {
|
||||
value: string
|
||||
group: string
|
||||
danger: boolean
|
||||
/** The current knowledge base scope lacks what the tool needs. */
|
||||
unmet: boolean
|
||||
missKind: RequirementMissKind
|
||||
/** Only adding is blocked, so a ticked tool is never disabled. */
|
||||
disabled: boolean
|
||||
}
|
||||
|
||||
export type StoredExtraKind = 'switch_managed' | 'unrecognized'
|
||||
|
||||
export interface StoredExtraTool {
|
||||
value: string
|
||||
kind: StoredExtraKind
|
||||
/** Once unticked it cannot be ticked again; the catalog does not offer it. */
|
||||
disabled: boolean
|
||||
}
|
||||
|
||||
function toRequirement(requirement: AgentToolRequirement | undefined) {
|
||||
return { anyOf: requirement?.any_of, allOf: requirement?.all_of }
|
||||
}
|
||||
|
||||
/**
|
||||
* The selectable tools in catalog order. `text` supplies translated labels;
|
||||
* when it returns nothing for a tool, the catalog's own label is used, so a
|
||||
* tool the frontend has no translation for still appears.
|
||||
*/
|
||||
export function buildToolOptions(
|
||||
catalog: AgentToolCatalog | null | undefined,
|
||||
selected: readonly string[],
|
||||
scope: ScopeCapabilities,
|
||||
hasAnyKb: boolean,
|
||||
text: (name: string) => ToolText | undefined,
|
||||
): EditorToolOption[] {
|
||||
if (!catalog) return []
|
||||
const chosen = new Set(selected)
|
||||
return catalog.tools.map((tool) => {
|
||||
const { ok, missKind } = evaluateRequirement(toRequirement(tool.requirement), scope, hasAnyKb)
|
||||
const translated = text(tool.name)
|
||||
return {
|
||||
value: tool.name,
|
||||
label: translated?.label || tool.label || tool.name,
|
||||
description: translated?.description || tool.description || '',
|
||||
group: tool.group,
|
||||
danger: !!tool.danger,
|
||||
unmet: !ok,
|
||||
missKind,
|
||||
disabled: !ok && !chosen.has(tool.name),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Stored or selected names the catalog does not offer as checkboxes, in the
|
||||
* order they appear. Pass the names stored when the editor opened together
|
||||
* with the current selection, so an entry stays visible after it is unticked.
|
||||
*/
|
||||
export function storedExtraTools(
|
||||
catalog: AgentToolCatalog | null | undefined,
|
||||
names: readonly string[],
|
||||
selected: readonly string[],
|
||||
): StoredExtraTool[] {
|
||||
// Without a catalog nothing can be classified; the values are left as they are.
|
||||
if (!catalog) return []
|
||||
const offered = new Set(catalog.tools.map((tool) => tool.name))
|
||||
const switchManaged = new Set(catalog.switch_managed_tools)
|
||||
const chosen = new Set(selected)
|
||||
const seen = new Set<string>()
|
||||
const extras: StoredExtraTool[] = []
|
||||
for (const name of names) {
|
||||
if (!name || offered.has(name) || seen.has(name)) continue
|
||||
seen.add(name)
|
||||
extras.push({
|
||||
value: name,
|
||||
kind: switchManaged.has(name) ? 'switch_managed' : 'unrecognized',
|
||||
disabled: !chosen.has(name),
|
||||
})
|
||||
}
|
||||
return extras
|
||||
}
|
||||
|
||||
export interface EffectiveToolSelection {
|
||||
/** Tools the runtime registers from the list, in display order. */
|
||||
names: string[]
|
||||
/** Ticked tools the current scope cannot serve. */
|
||||
inactive: string[]
|
||||
/** The list was never set, so the runtime uses the default tools. */
|
||||
usesDefaults: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* The built-in tools a smart-reasoning run registers from `allowed_tools`.
|
||||
* Mirrors the runtime: an unset list means the catalog's default tools and an
|
||||
* empty one means none, names the catalog does not offer register nothing,
|
||||
* and tools whose capability is missing are dropped. Switch-managed tools are
|
||||
* left to their switches.
|
||||
*/
|
||||
export function effectiveToolSelection(
|
||||
catalog: AgentToolCatalog | null | undefined,
|
||||
selected: readonly string[] | null | undefined,
|
||||
scope: ScopeCapabilities,
|
||||
hasAnyKb: boolean,
|
||||
): EffectiveToolSelection {
|
||||
if (!catalog) return { names: [], inactive: [], usesDefaults: false }
|
||||
const usesDefaults = selected == null
|
||||
const requested = new Set(selected ?? catalog.default_tools)
|
||||
const names: string[] = []
|
||||
const inactive: string[] = []
|
||||
for (const tool of catalog.tools) {
|
||||
if (!requested.has(tool.name)) continue
|
||||
if (evaluateRequirement(toRequirement(tool.requirement), scope, hasAnyKb).ok) {
|
||||
names.push(tool.name)
|
||||
} else if (!usesDefaults) {
|
||||
inactive.push(tool.name)
|
||||
}
|
||||
}
|
||||
return { names, inactive, usesDefaults }
|
||||
}
|
||||
|
||||
export interface LoadedAllowedTools {
|
||||
/** The list to edit, with retired names already rewritten by the caller. */
|
||||
tools: string[]
|
||||
/**
|
||||
* The stored list was never set and stays unset: saving an untouched,
|
||||
* empty list sends null so the agent keeps the default tools.
|
||||
*/
|
||||
keepUnset: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* How the editor loads a stored `allowed_tools`. An unset list selects the
|
||||
* default tools at runtime, while an empty one means none, so an unset list
|
||||
* must not turn into an empty one on save. For a smart-reasoning agent the
|
||||
* catalog's default tools are written in and ticked, so the editor shows what
|
||||
* runs; without a catalog, or for another mode, the list stays unset.
|
||||
*/
|
||||
export function resolveLoadedAllowedTools(
|
||||
stored: readonly string[] | null | undefined,
|
||||
agentMode: string | undefined,
|
||||
catalog: AgentToolCatalog | null | undefined,
|
||||
): LoadedAllowedTools {
|
||||
if (stored != null) return { tools: [...stored], keepUnset: false }
|
||||
if (agentMode === 'smart-reasoning' && catalog) {
|
||||
return { tools: [...catalog.default_tools], keepUnset: false }
|
||||
}
|
||||
return { tools: [], keepUnset: true }
|
||||
}
|
||||
|
||||
/** The `allowed_tools` value to send on save. */
|
||||
export function allowedToolsToSave(tools: readonly string[], keepUnset: boolean): string[] | null {
|
||||
return keepUnset && tools.length === 0 ? null : [...tools]
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { hydrateAgentPromptRefs, serializeAgentPrompts } from './agentPromptTemplates'
|
||||
import type { CustomAgentConfig } from '../api/agent'
|
||||
import type { PromptTemplatesConfig } from '../api/system'
|
||||
|
||||
const template = (id: string, content: string, extra = {}) => ({ id, name: id, description: '', content, ...extra })
|
||||
const templates: PromptTemplatesConfig = {
|
||||
agent_system_prompt: [template('agent', 'Agent default'), template('wiki', 'Wiki workflow')],
|
||||
system_prompt: [template('normal', 'QA default')],
|
||||
context_template: [template('context', '{{contexts}}')],
|
||||
rewrite: [template('rewrite', 'Rewrite default', { default: true, user: '{{query}}' })],
|
||||
fallback: [template('fallback', 'Fallback {{query}}', { default: true, mode: 'model' })],
|
||||
}
|
||||
|
||||
test('untouched templates round trip as references and follow updates in both modes', () => {
|
||||
for (const agent_mode of ['smart-reasoning', 'quick-answer'] as const) {
|
||||
const input: CustomAgentConfig = {
|
||||
agent_mode, system_prompt: agent_mode === 'smart-reasoning' ? 'Wiki workflow' : 'QA default',
|
||||
context_template: '{{contexts}}', rewrite_prompt_system: 'Rewrite default', rewrite_prompt_user: '{{query}}',
|
||||
fallback_prompt: 'Fallback {{query}}',
|
||||
}
|
||||
const saved = serializeAgentPrompts(input, templates)
|
||||
assert.equal(saved.system_prompt, '')
|
||||
assert.equal(saved.context_template, '')
|
||||
assert.equal(saved.rewrite_prompt_system, '')
|
||||
assert.equal(saved.rewrite_prompt_user, '')
|
||||
assert.equal(saved.fallback_prompt, '')
|
||||
assert.equal(hydrateAgentPromptRefs(saved, templates).system_prompt, input.system_prompt)
|
||||
const updated = structuredClone(templates)
|
||||
const list = agent_mode === 'smart-reasoning' ? updated.agent_system_prompt! : updated.system_prompt
|
||||
list.find(t => t.id === saved.system_prompt_id)!.content = 'Updated template'
|
||||
assert.equal(hydrateAgentPromptRefs(saved, updated).system_prompt, 'Updated template')
|
||||
assert.notEqual(input.system_prompt, '', 'serialization must not alter the visible textarea')
|
||||
}
|
||||
})
|
||||
|
||||
test('custom and legacy text survives unchanged and stale IDs are removed', () => {
|
||||
const input: CustomAgentConfig = {
|
||||
agent_mode: 'smart-reasoning', system_prompt_id: 'agent', system_prompt: ' Legacy default with edits\n',
|
||||
context_template_id: 'context', context_template: 'Custom {{contexts}}',
|
||||
rewrite_prompt_system: 'Custom rewrite', fallback_prompt: 'Custom {{query}}',
|
||||
}
|
||||
const saved = serializeAgentPrompts(input, templates)
|
||||
assert.equal(saved.system_prompt, input.system_prompt)
|
||||
assert.equal(saved.context_template, input.context_template)
|
||||
assert.equal(saved.system_prompt_id, undefined)
|
||||
assert.equal(saved.context_template_id, undefined)
|
||||
assert.equal(hydrateAgentPromptRefs(saved, templates).system_prompt, input.system_prompt)
|
||||
assert.equal(saved.rewrite_prompt_system, input.rewrite_prompt_system)
|
||||
assert.equal(saved.fallback_prompt, input.fallback_prompt)
|
||||
assert.deepEqual(serializeAgentPrompts(input, null), input)
|
||||
})
|
||||
|
||||
test('template refs cannot resolve from another mode or field', () => {
|
||||
assert.equal(hydrateAgentPromptRefs({ agent_mode: 'quick-answer', system_prompt_id: 'wiki' }, templates).system_prompt, '')
|
||||
assert.equal(hydrateAgentPromptRefs({ agent_mode: 'smart-reasoning', system_prompt_id: 'context' }, templates).system_prompt, '')
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { CustomAgentConfig } from '../api/agent'
|
||||
import type { PromptTemplate, PromptTemplatesConfig } from '../api/system'
|
||||
|
||||
const systemTemplates = (config: CustomAgentConfig, templates: PromptTemplatesConfig) =>
|
||||
config.agent_mode === 'smart-reasoning' ? templates.agent_system_prompt || [] : templates.system_prompt
|
||||
|
||||
function matchingTemplate(body: string | undefined, id: string | undefined, list: PromptTemplate[]) {
|
||||
// Preserve the selected identity if multiple templates have identical bodies.
|
||||
return list.find(t => t.id === id && t.content === body)
|
||||
|| list.find(t => t.content === body && !!body)
|
||||
}
|
||||
|
||||
// The textarea shows effective content. Persist untouched templates as references;
|
||||
// preserve every character of actual custom text and clear any stale reference.
|
||||
export function serializeAgentPrompts(config: CustomAgentConfig, templates: PromptTemplatesConfig | null): CustomAgentConfig {
|
||||
if (!templates) return { ...config }
|
||||
const result = { ...config }
|
||||
const system = matchingTemplate(config.system_prompt, config.system_prompt_id, systemTemplates(config, templates))
|
||||
const context = matchingTemplate(config.context_template, config.context_template_id, templates.context_template)
|
||||
if (system) {
|
||||
result.system_prompt = ''
|
||||
result.system_prompt_id = system.id
|
||||
} else if (config.system_prompt) {
|
||||
delete result.system_prompt_id
|
||||
}
|
||||
if (context) {
|
||||
result.context_template = ''
|
||||
result.context_template_id = context.id
|
||||
} else if (config.context_template) {
|
||||
delete result.context_template_id
|
||||
}
|
||||
// These fields already inherit the global defaults when empty.
|
||||
const rewrite = templates.rewrite.find(t => t.default)
|
||||
const fallback = templates.fallback.find(t => t.mode === 'model' && t.default)
|
||||
|| templates.fallback.find(t => t.mode === 'model')
|
||||
const fixed = templates.fallback.find(t => t.default && t.mode !== 'model')
|
||||
for (const [field, value] of [
|
||||
['rewrite_prompt_system', rewrite?.content], ['rewrite_prompt_user', rewrite?.user],
|
||||
['fallback_prompt', fallback?.content], ['fallback_response', fixed?.content],
|
||||
] as const) {
|
||||
if (value && result[field] === value) result[field] = ''
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function hydrateAgentPromptRefs(config: CustomAgentConfig, templates: PromptTemplatesConfig | null): CustomAgentConfig {
|
||||
if (!templates) return { ...config }
|
||||
return {
|
||||
...config,
|
||||
system_prompt: config.system_prompt || systemTemplates(config, templates).find(t => t.id === config.system_prompt_id)?.content || '',
|
||||
context_template: config.context_template || templates.context_template.find(t => t.id === config.context_template_id)?.content || '',
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { foldProgressIntoThinking } from './agentTimelinePresentation'
|
||||
import { withoutCollaborationWaits } from './collaborationDisplay'
|
||||
|
||||
test('live and recovered progress label the preceding reasoning without changing stored events', () => {
|
||||
for (const done of [false, true]) {
|
||||
const thought = Object.freeze({ type: 'thinking', event_id: 'r1', content: 'Check the agents', done })
|
||||
for (const update of [
|
||||
{ type: 'progress', event_id: 'p1', content: '我先查看智能体。', iteration: 1 },
|
||||
{ type: 'answer', event_id: 'p1', content: '我先查看智能体。', superseded: true },
|
||||
]) {
|
||||
const input = Object.freeze([thought, Object.freeze(update)])
|
||||
const output = foldProgressIntoThinking([...input])
|
||||
assert.deepEqual(output, [{ ...thought, title: update.content }])
|
||||
assert.equal(output[0].event_id, 'r1') // Preserve expansion identity.
|
||||
assert.equal('title' in thought, false)
|
||||
assert.equal(input[1].type, update.type)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('tools, approvals and user messages prevent cross-round association even when hidden', () => {
|
||||
for (const boundary of [
|
||||
{ type: 'tool_call', tool_name: 'wait_agent' },
|
||||
{ type: 'tool_call', tool_name: 'spawn_agent' },
|
||||
{ type: 'tool_approval_required' },
|
||||
{ type: 'user_message_injected' },
|
||||
]) {
|
||||
const events = [{ type: 'thinking', content: 'Earlier reasoning' }, boundary,
|
||||
{ type: 'progress', content: 'New update' }]
|
||||
const projected = withoutCollaborationWaits(foldProgressIntoThinking(events))
|
||||
assert.equal(projected[0].title, undefined)
|
||||
assert.equal(projected.at(-1)?.type, 'progress')
|
||||
}
|
||||
})
|
||||
|
||||
test('final answers, standalone progress, different rounds and subsequent updates remain separate', () => {
|
||||
const events = [
|
||||
{ type: 'progress', content: 'Starting' },
|
||||
{ type: 'thinking', content: 'Reasoning', iteration: 1 },
|
||||
{ type: 'progress', content: 'Different round', iteration: 2 },
|
||||
{ type: 'thinking', content: 'More reasoning' },
|
||||
{ type: 'progress', content: 'First update' },
|
||||
{ type: 'progress', content: 'Second update' },
|
||||
{ type: 'answer', content: 'Complete deliverable' },
|
||||
]
|
||||
const output = foldProgressIntoThinking(events)
|
||||
assert.equal(output.length, 6)
|
||||
assert.equal(output[1].title, undefined)
|
||||
assert.equal(output[3].title, 'First update')
|
||||
assert.deepEqual(output.at(-1), events.at(-1))
|
||||
assert.equal(output[4].content, 'Second update')
|
||||
})
|
||||
|
||||
test('adjacent visible progress keeps only the latest summary and preserves earlier updates for expansion', async () => {
|
||||
const { groupProgressUpdates } = await import('./agentTimelinePresentation')
|
||||
const { collaborationTimeline } = await import('./collaborationDisplay')
|
||||
const first = Object.freeze({ type: 'progress', event_id: 'p1', content: '等待审批', timestamp: 1 })
|
||||
const second = Object.freeze({ type: 'progress', event_id: 'p2', content: '正在读取全文', timestamp: 2 })
|
||||
const third = Object.freeze({ type: 'progress', event_id: 'p3', content: '正在整理结果', timestamp: 3 })
|
||||
const events = [first, { type: 'tool_call', tool_name: 'wait_agent', success: true }, second, third]
|
||||
const projected = groupProgressUpdates(collaborationTimeline(events, undefined))
|
||||
assert.equal(projected.length, 1)
|
||||
assert.equal(projected[0].event_id, 'p1')
|
||||
assert.equal(projected[0].content, third.content)
|
||||
assert.deepEqual(projected[0].progress_history, [first.content, second.content])
|
||||
assert.equal(first.content, '等待审批')
|
||||
assert.equal('progress_history' in third, false)
|
||||
const appended = groupProgressUpdates([...projected, { type: 'progress', event_id: 'p4', content: '即将完成' }])
|
||||
assert.equal(appended[0].event_id, 'p1')
|
||||
assert.deepEqual(appended[0].progress_history, [first.content, second.content, third.content])
|
||||
})
|
||||
|
||||
test('progress grouping preserves approval, reasoning, tool, user input and final answer boundaries', async () => {
|
||||
const { groupProgressUpdates } = await import('./agentTimelinePresentation')
|
||||
for (const type of ['tool_approval_required', 'agent_prompt_required', 'thinking', 'tool_call', 'user_message_injected', 'answer', 'stop']) {
|
||||
const events = [{ type: 'progress', content: 'Before' }, { type, content: 'Boundary' }, { type: 'progress', content: 'After' }]
|
||||
assert.deepEqual(groupProgressUpdates(events), events)
|
||||
}
|
||||
})
|
||||
|
||||
test('finished untitled reasoning rides on the tool call it led to', async () => {
|
||||
const { attachReasoningToTools } = await import('./agentTimelinePresentation')
|
||||
const tool = Object.freeze({ type: 'tool_call', tool_call_id: 't1', tool_name: 'knowledge_search' })
|
||||
const events = [
|
||||
{ type: 'thinking', event_id: 'r1', content: 'Search first' }, tool,
|
||||
{ type: 'thinking', event_id: 'r2', title: '我先读一下文档', content: 'Read it' },
|
||||
{ type: 'tool_call', tool_call_id: 't2', tool_name: 'read_document' },
|
||||
{ type: 'thinking', event_id: 'r3', content: 'Still thinking' },
|
||||
{ type: 'tool_call', tool_call_id: 't3', tool_name: 'web_search' },
|
||||
{ type: 'thinking', event_id: 'r4', content: 'Wrap up' },
|
||||
]
|
||||
const output = attachReasoningToTools(events, (e: any) => e.event_id !== 'r3')
|
||||
assert.deepEqual(output.map((e: any) => e.event_id || e.tool_call_id), ['t1', 'r2', 't2', 'r3', 't3', 'r4'])
|
||||
assert.deepEqual(output[0].reasoning, { id: 'reasoning-r1', content: 'Search first' })
|
||||
assert.equal('reasoning' in tool, false)
|
||||
assert.equal(output[2].reasoning, undefined, 'titled narration keeps its own row')
|
||||
assert.equal(output[4].reasoning, undefined, 'reasoning that cannot attach keeps its own row')
|
||||
})
|
||||
|
||||
test('earlier steps fold behind recent and attention-demanding rows', async () => {
|
||||
const { earlierStepKeys } = await import('./agentTimelinePresentation')
|
||||
const rows = (n: number, sticky: string[] = []) => Array.from({ length: n }, (_, i) => ({
|
||||
key: `k${i}`, step: true, sticky: sticky.includes(`k${i}`),
|
||||
}))
|
||||
assert.deepEqual(earlierStepKeys(rows(4)), [], 'folding a single row saves nothing')
|
||||
assert.deepEqual(earlierStepKeys(rows(6)), ['k0', 'k1', 'k2'])
|
||||
assert.deepEqual(earlierStepKeys(rows(5, ['k1'])), [], 'sticky rows stay out of the fold')
|
||||
assert.deepEqual(earlierStepKeys(rows(6, ['k1'])), ['k0', 'k2'])
|
||||
assert.deepEqual(earlierStepKeys([...rows(6), { key: 'answer', step: false, sticky: false }]), ['k0', 'k1', 'k2'])
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
/** Presentation only: keep reasoning and progress separate in the stored stream. */
|
||||
export function foldProgressIntoThinking(events: any[]): any[] {
|
||||
const result: any[] = []
|
||||
for (const event of events) {
|
||||
const progress = event.type === 'progress' || (event.type === 'answer' && event.superseded)
|
||||
if (!progress || typeof event.content !== 'string' || !event.content.trim()) {
|
||||
result.push(event)
|
||||
continue
|
||||
}
|
||||
const previous = result[result.length - 1]
|
||||
// Only adjacent events belong together. Tools, approvals and user input
|
||||
// remain boundaries, even when a later presentation filter hides them.
|
||||
const sameRound = previous?.iteration == null || event.iteration == null
|
||||
|| previous.iteration === event.iteration
|
||||
if (previous?.type === 'thinking' && !previous.title && sameRound) {
|
||||
result[result.length - 1] = { ...previous, title: event.content }
|
||||
} else {
|
||||
result.push(event.type === 'progress' ? event : { ...event, type: 'progress', done: true })
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Move finished, untitled reasoning onto the tool call it led to, so the
|
||||
* timeline shows one row per action instead of alternating thought/tool rows.
|
||||
* Titled reasoning (a relocated preamble) is user-facing narration and stays.
|
||||
*/
|
||||
export function attachReasoningToTools(events: any[], canAttach: (event: any) => boolean): any[] {
|
||||
const result: any[] = []
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
const event = events[i]
|
||||
const next = events[i + 1]
|
||||
const content = typeof event?.content === 'string' ? event.content.trim() : ''
|
||||
if (event?.type === 'thinking' && !event.title && content && event.event_id
|
||||
&& next?.type === 'tool_call' && next.tool_name !== 'thinking' && !next.reasoning
|
||||
&& canAttach(event)) {
|
||||
result.push({ ...next, reasoning: { id: `reasoning-${event.event_id}`, content: event.content } })
|
||||
i++
|
||||
continue
|
||||
}
|
||||
result.push(event)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Keys of early timeline rows to fold while a run streams. The most recent
|
||||
* rows and anything still demanding attention stay visible; folding fewer
|
||||
* than `minFolded` rows would cost a row without saving one.
|
||||
*/
|
||||
export function earlierStepKeys(
|
||||
rows: { key: string, step: boolean, sticky: boolean }[],
|
||||
keepRecent = 3,
|
||||
minFolded = 2,
|
||||
): string[] {
|
||||
const steps = rows.filter(row => row.step)
|
||||
const keys = steps.slice(0, Math.max(0, steps.length - keepRecent))
|
||||
.filter(row => !row.sticky)
|
||||
.map(row => row.key)
|
||||
return keys.length >= minFolded ? keys : []
|
||||
}
|
||||
|
||||
/** Compact adjacent visible updates without crossing tools, prompts or answers. */
|
||||
export function groupProgressUpdates(events: any[]): any[] {
|
||||
const result: any[] = []
|
||||
for (const event of events) {
|
||||
const previous = result.at(-1)
|
||||
if (event.type === 'progress' && typeof event.content === 'string' && event.content.trim()
|
||||
&& previous?.type === 'progress' && typeof previous.content === 'string' && previous.content.trim()) {
|
||||
result[result.length - 1] = {
|
||||
...event,
|
||||
// Keep the first row's identity so expansion survives streamed updates.
|
||||
event_id: previous.event_id,
|
||||
timestamp: previous.timestamp,
|
||||
progress_history: [...(previous.progress_history || []), previous.content],
|
||||
}
|
||||
} else {
|
||||
result.push(event)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
resolveAgentWebSearchProviderId,
|
||||
isAgentWebSearchReady,
|
||||
isTenantWebSearchReady,
|
||||
} from './agentWebSearch.ts';
|
||||
|
||||
const providers = [
|
||||
{ id: 'p1', name: 'Keenable', is_default: false },
|
||||
{ id: 'p2', name: 'Default', is_default: true },
|
||||
];
|
||||
|
||||
test('resolveAgentWebSearchProviderId uses explicit agent provider', () => {
|
||||
assert.equal(
|
||||
resolveAgentWebSearchProviderId({ web_search_provider_id: 'p1' }, providers),
|
||||
'p1',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveAgentWebSearchProviderId falls back to tenant default', () => {
|
||||
assert.equal(
|
||||
resolveAgentWebSearchProviderId({ web_search_provider_id: '' }, providers),
|
||||
'p2',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveAgentWebSearchProviderId returns null when default missing', () => {
|
||||
const noDefault = [{ id: 'p1', name: 'Keenable', is_default: false }];
|
||||
assert.equal(
|
||||
resolveAgentWebSearchProviderId({ web_search_provider_id: '' }, noDefault),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('isAgentWebSearchReady requires enabled flag and resolvable provider', () => {
|
||||
assert.equal(
|
||||
isAgentWebSearchReady({ web_search_enabled: true }, providers),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isAgentWebSearchReady({ web_search_enabled: true, web_search_provider_id: '' }, [
|
||||
{ id: 'p1', name: 'Keenable', is_default: false },
|
||||
]),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
isAgentWebSearchReady({ web_search_enabled: false }, providers),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('isAgentWebSearchReady trusts source workspace readiness for a shared agent', () => {
|
||||
assert.equal(
|
||||
isAgentWebSearchReady(
|
||||
{ web_search_enabled: true, web_search_provider_id: 'source-provider' },
|
||||
[],
|
||||
true,
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
isAgentWebSearchReady({ web_search_enabled: true }, providers, false),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('isTenantWebSearchReady checks default provider only', () => {
|
||||
assert.equal(isTenantWebSearchReady(providers), true);
|
||||
assert.equal(
|
||||
isTenantWebSearchReady([{ id: 'p1', name: 'Keenable', is_default: false }]),
|
||||
false,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { WebSearchProviderEntity } from '@/api/web-search-provider';
|
||||
|
||||
export type AgentWebSearchConfig = {
|
||||
web_search_enabled?: boolean;
|
||||
web_search_provider_id?: string;
|
||||
};
|
||||
|
||||
/** 解析智能体实际会使用的搜索引擎 ID(与后端 agent > tenant default 逻辑一致) */
|
||||
export function resolveAgentWebSearchProviderId(
|
||||
config: AgentWebSearchConfig | undefined,
|
||||
providers: WebSearchProviderEntity[],
|
||||
): string | null {
|
||||
const explicitId = config?.web_search_provider_id?.trim();
|
||||
if (explicitId) {
|
||||
return providers.some((p) => p.id === explicitId) ? explicitId : null;
|
||||
}
|
||||
const defaultProvider = providers.find((p) => p.is_default);
|
||||
return defaultProvider?.id ?? null;
|
||||
}
|
||||
|
||||
export function isAgentWebSearchEnabled(config: AgentWebSearchConfig | undefined): boolean {
|
||||
return config?.web_search_enabled === true;
|
||||
}
|
||||
|
||||
/** 智能体已启用网络搜索,且能解析到可用搜索引擎 */
|
||||
export function isAgentWebSearchReady(
|
||||
config: AgentWebSearchConfig | undefined,
|
||||
providers: WebSearchProviderEntity[],
|
||||
sourceWorkspaceReady?: boolean,
|
||||
): boolean {
|
||||
if (!isAgentWebSearchEnabled(config)) return false;
|
||||
if (sourceWorkspaceReady !== undefined) return sourceWorkspaceReady;
|
||||
return resolveAgentWebSearchProviderId(config, providers) !== null;
|
||||
}
|
||||
|
||||
/** 空间级默认搜索引擎是否可用(无智能体约束时) */
|
||||
export function isTenantWebSearchReady(providers: WebSearchProviderEntity[]): boolean {
|
||||
return providers.some((p) => p.is_default);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export function getApiBaseUrl(): string {
|
||||
// LocalHub plugin patch (2026-04-29): respect vite's BASE_URL so that
|
||||
// axios calls work at `/app/weknora/` (LocalHub reverse proxy). Without
|
||||
// this · axios hits `/api/v1/...` at LocalHub root · gets 404 "Cannot
|
||||
// POST". Strip trailing slash so axios doesn't produce `/app/weknora//api/v1/...`.
|
||||
// See: plugins/weknora/patches/api-base-baseurl.patch
|
||||
const base = (import.meta.env.BASE_URL || '/').replace(/\/+$/, '');
|
||||
return base;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { getFileIcon } from './files'
|
||||
import { resolveFilePreviewExt } from './filePreview'
|
||||
|
||||
/** Shared trusted SVG for Vue file rows and inline Markdown artifact cards. */
|
||||
export function renderArtifactFileIcon(fileName: string): string {
|
||||
const kind = getFileIcon(fileName)
|
||||
const ext = resolveFilePreviewExt(fileName)
|
||||
// Only this restricted extension label is interpolated, never the filename.
|
||||
const label = /^[a-z0-9]{1,4}$/i.test(ext) ? ext.toUpperCase() : 'FILE'
|
||||
return `<svg class="artifact-file-icon-svg kind-${kind}" viewBox="0 0 32 38" fill="none" aria-hidden="true">`
|
||||
+ '<path class="file-sheet" d="M6 1.5h13L28.5 11v22A3.5 3.5 0 0 1 25 36.5H6A3.5 3.5 0 0 1 2.5 33V5A3.5 3.5 0 0 1 6 1.5Z" />'
|
||||
+ '<path class="file-fold" d="M19 1.5V8a3 3 0 0 0 3 3h6.5" />'
|
||||
+ '<path class="file-lines" d="M8 14h9M8 18h14" />'
|
||||
+ '<rect x="5" y="23" width="24" height="11" rx="3" fill="currentColor" />'
|
||||
+ `<text x="17" y="30.8" text-anchor="middle">${label}</text></svg>`
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
ARTIFACT_CATEGORIES,
|
||||
artifactCategoryExtensions,
|
||||
artifactDateGroup,
|
||||
groupArtifactsByDate,
|
||||
parseArtifactCategory,
|
||||
} from './artifactLibrary.ts'
|
||||
|
||||
test('"all" sends no extension filter; categories send dotted lowercase extensions', () => {
|
||||
assert.deepEqual(artifactCategoryExtensions('all'), [])
|
||||
for (const category of ARTIFACT_CATEGORIES.filter((c) => c !== 'all')) {
|
||||
const exts = artifactCategoryExtensions(category)
|
||||
assert.ok(exts.length > 0, category)
|
||||
for (const ext of exts) assert.match(ext, /^\.[a-z0-9]+$/, `${category}: ${ext}`)
|
||||
}
|
||||
assert.ok(artifactCategoryExtensions('presentation').includes('.pptx'))
|
||||
})
|
||||
|
||||
test('categories do not overlap', () => {
|
||||
const seen = new Map()
|
||||
for (const category of ARTIFACT_CATEGORIES) {
|
||||
for (const ext of artifactCategoryExtensions(category)) {
|
||||
assert.equal(seen.get(ext), undefined, `${ext} is in both ${seen.get(ext)} and ${category}`)
|
||||
seen.set(ext, category)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('extension lists are copies', () => {
|
||||
artifactCategoryExtensions('image').push('.exe')
|
||||
assert.ok(!artifactCategoryExtensions('image').includes('.exe'))
|
||||
})
|
||||
|
||||
test('parseArtifactCategory falls back to all', () => {
|
||||
assert.equal(parseArtifactCategory('image'), 'image')
|
||||
assert.equal(parseArtifactCategory('bogus'), 'all')
|
||||
assert.equal(parseArtifactCategory(undefined), 'all')
|
||||
assert.equal(parseArtifactCategory(['image']), 'all')
|
||||
})
|
||||
|
||||
test('artifactDateGroup buckets by local calendar day', () => {
|
||||
const now = new Date(2026, 8, 18, 9, 0, 0)
|
||||
assert.equal(artifactDateGroup(new Date(2026, 8, 18, 0, 5).toISOString(), now), 'today')
|
||||
assert.equal(artifactDateGroup(new Date(2026, 8, 17, 23, 59).toISOString(), now), 'yesterday')
|
||||
assert.equal(artifactDateGroup(new Date(2026, 8, 13, 12, 0).toISOString(), now), 'last7Days')
|
||||
assert.equal(artifactDateGroup(new Date(2026, 8, 1, 12, 0).toISOString(), now), 'last30Days')
|
||||
assert.equal(artifactDateGroup(new Date(2026, 5, 1, 12, 0).toISOString(), now), 'earlier')
|
||||
assert.equal(artifactDateGroup('not a date', now), 'earlier')
|
||||
})
|
||||
|
||||
test('groupArtifactsByDate keeps order and merges consecutive items', () => {
|
||||
const now = new Date(2026, 8, 18, 9, 0, 0)
|
||||
const at = (d, h) => new Date(2026, 8, d, h).toISOString()
|
||||
const sections = groupArtifactsByDate(
|
||||
[
|
||||
{ id: 1, created_at: at(18, 8) },
|
||||
{ id: 2, created_at: at(18, 1) },
|
||||
{ id: 3, created_at: at(17, 20) },
|
||||
{ id: 4, created_at: at(2, 10) },
|
||||
],
|
||||
now,
|
||||
)
|
||||
assert.deepEqual(
|
||||
sections.map((s) => [s.group, s.items.map((i) => i.id)]),
|
||||
[
|
||||
['today', [1, 2]],
|
||||
['yesterday', [3]],
|
||||
['last30Days', [4]],
|
||||
],
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Type filters for the artifact library page. The server filters by an
|
||||
* extension allowlist, so each category is just the extensions it covers.
|
||||
*/
|
||||
export type ArtifactCategory = 'all' | 'document' | 'spreadsheet' | 'presentation' | 'image' | 'web' | 'data'
|
||||
|
||||
export const ARTIFACT_CATEGORIES: ArtifactCategory[] = [
|
||||
'all',
|
||||
'document',
|
||||
'spreadsheet',
|
||||
'presentation',
|
||||
'image',
|
||||
'web',
|
||||
'data',
|
||||
]
|
||||
|
||||
const CATEGORY_EXTENSIONS: Record<Exclude<ArtifactCategory, 'all'>, string[]> = {
|
||||
document: ['.pdf', '.doc', '.docx', '.md', '.txt', '.rtf', '.odt'],
|
||||
spreadsheet: ['.xlsx', '.xls', '.csv', '.tsv', '.ods'],
|
||||
presentation: ['.pptx', '.ppt', '.key', '.odp'],
|
||||
image: ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.bmp'],
|
||||
web: ['.html', '.htm'],
|
||||
data: ['.json', '.xml', '.yaml', '.yml', '.zip'],
|
||||
}
|
||||
|
||||
/** Extensions to send for a category; empty for "all". */
|
||||
export function artifactCategoryExtensions(category: ArtifactCategory): string[] {
|
||||
return category === 'all' ? [] : [...CATEGORY_EXTENSIONS[category]]
|
||||
}
|
||||
|
||||
/** Parses a ?type= query value, falling back to "all". */
|
||||
export function parseArtifactCategory(raw: unknown): ArtifactCategory {
|
||||
return typeof raw === 'string' && (ARTIFACT_CATEGORIES as string[]).includes(raw)
|
||||
? (raw as ArtifactCategory)
|
||||
: 'all'
|
||||
}
|
||||
|
||||
export type ArtifactDateGroup = 'today' | 'yesterday' | 'last7Days' | 'last30Days' | 'earlier'
|
||||
|
||||
/** Buckets an ISO timestamp relative to `now`, by local calendar day. */
|
||||
export function artifactDateGroup(raw: string, now: Date = new Date()): ArtifactDateGroup {
|
||||
const at = new Date(raw)
|
||||
if (Number.isNaN(at.getTime())) return 'earlier'
|
||||
const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
|
||||
const days = Math.round((startOfDay(now) - startOfDay(at)) / 86_400_000)
|
||||
if (days <= 0) return 'today'
|
||||
if (days === 1) return 'yesterday'
|
||||
if (days < 7) return 'last7Days'
|
||||
if (days < 30) return 'last30Days'
|
||||
return 'earlier'
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups items into consecutive date sections. Items arrive newest first, so
|
||||
* sections come out in order and a page boundary only ever splits the last one.
|
||||
*/
|
||||
export function groupArtifactsByDate<T extends { created_at: string }>(
|
||||
items: T[],
|
||||
now: Date = new Date(),
|
||||
): { group: ArtifactDateGroup; items: T[] }[] {
|
||||
const sections: { group: ArtifactDateGroup; items: T[] }[] = []
|
||||
for (const item of items) {
|
||||
const group = artifactDateGroup(item.created_at, now)
|
||||
const last = sections[sections.length - 1]
|
||||
if (last && last.group === group) {
|
||||
last.items.push(item)
|
||||
} else {
|
||||
sections.push({ group, items: [item] })
|
||||
}
|
||||
}
|
||||
return sections
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { buildAskUserResponse, canSubmitAskUser, summarizeAskUserAnswer, type AskUserQuestion } from './askUser.ts'
|
||||
|
||||
const form: AskUserQuestion = {
|
||||
question: 'Trip?',
|
||||
fields: [
|
||||
{ name: 'city', label: 'City', type: 'text', required: true },
|
||||
{ name: 'days', type: 'number' },
|
||||
{ name: 'tags', type: 'multiselect', options: ['a', 'b'] },
|
||||
],
|
||||
}
|
||||
|
||||
test('a form answer keeps filled fields only', () => {
|
||||
const r = buildAskUserResponse(form, { selected: [], values: { city: ' Paris ', days: 3, tags: [] }, text: 'ignored' })
|
||||
assert.deepEqual(r, { values: { city: 'Paris', days: 3 } })
|
||||
assert.equal(canSubmitAskUser(form, r), true)
|
||||
assert.equal(summarizeAskUserAnswer(form, r), 'City: Paris\ndays: 3')
|
||||
})
|
||||
|
||||
test('a form waits for its required fields', () => {
|
||||
const r = buildAskUserResponse(form, { selected: [], values: { days: 2 }, text: '' })
|
||||
assert.equal(canSubmitAskUser(form, r), false)
|
||||
})
|
||||
|
||||
test('options accept a choice or, when allowed, typed text', () => {
|
||||
const q: AskUserQuestion = { question: 'Pick', options: ['x', 'y'], allow_free_text: true }
|
||||
assert.equal(canSubmitAskUser(q, buildAskUserResponse(q, { selected: [], values: {}, text: '' })), false)
|
||||
assert.deepEqual(buildAskUserResponse(q, { selected: ['y'], values: {}, text: '' }), { selected: ['y'] })
|
||||
const typed = buildAskUserResponse(q, { selected: [], values: {}, text: 'z' })
|
||||
assert.deepEqual(typed, { text: 'z' })
|
||||
assert.equal(canSubmitAskUser(q, typed), true)
|
||||
const strict: AskUserQuestion = { question: 'Pick', options: ['x'] }
|
||||
assert.deepEqual(buildAskUserResponse(strict, { selected: [], values: {}, text: 'z' }), {})
|
||||
})
|
||||
|
||||
test('a free-text question needs text', () => {
|
||||
const q: AskUserQuestion = { question: 'Why?' }
|
||||
assert.equal(canSubmitAskUser(q, buildAskUserResponse(q, { selected: [], values: {}, text: ' ' })), false)
|
||||
assert.deepEqual(buildAskUserResponse(q, { selected: [], values: {}, text: ' because ' }), { text: 'because' })
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
export interface AskUserField {
|
||||
name: string
|
||||
label?: string
|
||||
type: 'text' | 'number' | 'select' | 'multiselect'
|
||||
required?: boolean
|
||||
options?: string[]
|
||||
}
|
||||
|
||||
/** Request of an ask_user prompt; mirrors types.AskUserPromptRequest. */
|
||||
export interface AskUserQuestion {
|
||||
question: string
|
||||
options?: string[]
|
||||
multi_select?: boolean
|
||||
fields?: AskUserField[]
|
||||
allow_free_text?: boolean
|
||||
}
|
||||
|
||||
export interface AskUserDraft {
|
||||
selected: string[]
|
||||
values: Record<string, unknown>
|
||||
text: string
|
||||
}
|
||||
|
||||
const isEmpty = (v: unknown) =>
|
||||
v === undefined || v === null || (typeof v === 'string' && !v.trim()) || (Array.isArray(v) && v.length === 0)
|
||||
|
||||
/** Builds the response the server validates, dropping untouched inputs. */
|
||||
export function buildAskUserResponse(q: AskUserQuestion, draft: AskUserDraft): Record<string, unknown> {
|
||||
const response: Record<string, unknown> = {}
|
||||
if (q.options?.length && draft.selected.length) response.selected = [...draft.selected]
|
||||
if (q.fields?.length) {
|
||||
const values: Record<string, unknown> = {}
|
||||
for (const f of q.fields) {
|
||||
const v = draft.values[f.name]
|
||||
if (!isEmpty(v)) values[f.name] = typeof v === 'string' ? v.trim() : v
|
||||
}
|
||||
if (Object.keys(values).length) response.values = values
|
||||
}
|
||||
const freeTextOnly = !q.options?.length && !q.fields?.length
|
||||
const text = draft.text.trim()
|
||||
if (text && (freeTextOnly || q.allow_free_text)) response.text = text
|
||||
return response
|
||||
}
|
||||
|
||||
/** Whether a response answers the question well enough to send. */
|
||||
export function canSubmitAskUser(q: AskUserQuestion, response: Record<string, unknown>): boolean {
|
||||
const values = (response.values || {}) as Record<string, unknown>
|
||||
if (q.fields?.some((f) => f.required && isEmpty(values[f.name]))) return false
|
||||
if (q.options?.length) return Boolean((response.selected as string[] | undefined)?.length || response.text)
|
||||
if (q.fields?.length) return true
|
||||
return Boolean(response.text)
|
||||
}
|
||||
|
||||
/** One line per part of an answer, labelled the way the question was. */
|
||||
export function summarizeAskUserAnswer(q: AskUserQuestion, answer: Record<string, unknown>): string {
|
||||
const lines: string[] = []
|
||||
const selected = answer.selected as string[] | undefined
|
||||
if (selected?.length) lines.push(selected.join(', '))
|
||||
const values = (answer.values || {}) as Record<string, unknown>
|
||||
for (const f of q.fields || []) {
|
||||
const v = values[f.name]
|
||||
if (isEmpty(v)) continue
|
||||
lines.push(`${f.label || f.name}: ${Array.isArray(v) ? v.join(', ') : String(v)}`)
|
||||
}
|
||||
if (typeof answer.text === 'string' && answer.text.trim()) lines.push(answer.text.trim())
|
||||
return lines.join('\n')
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { change, fixture } from '../test-utils/vueFixture.ts'
|
||||
|
||||
test('normalizes snake-case IDs, drops invalid IDs, and deduplicates', t => {
|
||||
const f = fixture(t)
|
||||
const listener = t.mock.fn()
|
||||
f.window.addEventListener(f.dataChange.ASSISTANT_DATA_CHANGE_EVENT, listener)
|
||||
f.emit({ operation: ' knowledge.move ', area: 'knowledge', ids: {
|
||||
knowledge_base_id: [' a ', 'a', '', 4], knowledge_id: ['doc'], agent_id: null,
|
||||
} })
|
||||
assert.deepEqual(structuredClone(listener.mock.calls[0].arguments[0].detail), {
|
||||
operation: 'knowledge.move', area: 'knowledge',
|
||||
ids: { knowledgeBaseIds: ['a'], knowledgeIds: ['doc'], agentIds: [] },
|
||||
})
|
||||
})
|
||||
|
||||
for (const raw of [null, [], {}, { area: 'agent' }, { operation: 'agent.', area: 'agent' },
|
||||
{ operation: 'wiki.revert', area: 'agent' }, { operation: 2, area: 'agent' },
|
||||
{ ...change('agent.create'), ids: [] }]) {
|
||||
test(`ignores malformed payload ${JSON.stringify(raw)}`, t => {
|
||||
const f = fixture(t)
|
||||
const handler = t.mock.fn()
|
||||
f.mount({ setup() { f.dataChange.useAssistantDataChange(handler) } })
|
||||
f.emit(raw)
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(handler.mock.callCount(), 0)
|
||||
})
|
||||
}
|
||||
|
||||
test('filters areas and coalesces bursts without losing operations or IDs', t => {
|
||||
const f = fixture(t)
|
||||
const handler = t.mock.fn()
|
||||
f.mount({ setup() { f.dataChange.useAssistantDataChange(handler, { areas: ['agent'] }) } })
|
||||
f.emit(change('agent.create', { agent_id: ['a'] }))
|
||||
t.mock.timers.tick(200)
|
||||
f.emit(change('wiki.revert'))
|
||||
f.emit(change('agent.update', { agent_id: ['b'] }))
|
||||
t.mock.timers.tick(299)
|
||||
assert.equal(handler.mock.callCount(), 0)
|
||||
t.mock.timers.tick(1)
|
||||
assert.equal(handler.mock.callCount(), 1)
|
||||
assert.deepEqual(structuredClone(handler.mock.calls[0].arguments[0].map((item: any) => item.ids.agentIds)), [['a'], ['b']])
|
||||
})
|
||||
|
||||
test('cancels queued work and removes the listener on unmount', t => {
|
||||
const f = fixture(t)
|
||||
const handler = t.mock.fn()
|
||||
const { close } = f.mount({ setup() { f.dataChange.useAssistantDataChange(handler, { debounceMs: 10 }) } })
|
||||
f.emit(change('agent.delete'))
|
||||
close()
|
||||
f.emit(change('agent.create'))
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(handler.mock.callCount(), 0)
|
||||
})
|
||||
|
||||
test('guards malformed window events and accepts omitted IDs', t => {
|
||||
const f = fixture(t)
|
||||
const handler = t.mock.fn()
|
||||
f.mount({ setup() { f.dataChange.useAssistantDataChange(handler) } })
|
||||
f.window.dispatchEvent(new CustomEvent(f.dataChange.ASSISTANT_DATA_CHANGE_EVENT, { detail: { ids: {} } }))
|
||||
f.emit({ operation: 'agent.create', area: 'agent' })
|
||||
t.mock.timers.tick(300)
|
||||
assert.equal(handler.mock.callCount(), 1)
|
||||
assert.deepEqual(structuredClone(handler.mock.calls[0].arguments[0][0].ids), {
|
||||
knowledgeBaseIds: [], knowledgeIds: [], agentIds: [],
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
import { onMounted, onUnmounted } from 'vue'
|
||||
|
||||
export const ASSISTANT_DATA_CHANGE_EVENT = 'weknora:assistant-data-change'
|
||||
|
||||
export interface AssistantDataChange {
|
||||
operation: string
|
||||
area: string
|
||||
ids: { knowledgeBaseIds: string[]; knowledgeIds: string[]; agentIds: string[] }
|
||||
}
|
||||
|
||||
type ChangeHandler = (changes: AssistantDataChange[]) => void
|
||||
interface ChangeOptions { areas?: string[]; debounceMs?: number }
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function stringIds(value: unknown): string[] {
|
||||
return Array.isArray(value)
|
||||
? [...new Set(value.filter((id): id is string => typeof id === 'string').map(id => id.trim()).filter(Boolean))]
|
||||
: []
|
||||
}
|
||||
|
||||
export function emitAssistantDataChange(raw: unknown): void {
|
||||
if (typeof window === 'undefined' || !isRecord(raw)) return
|
||||
if (typeof raw.operation !== 'string' || typeof raw.area !== 'string') return
|
||||
const operation = raw.operation.trim()
|
||||
const area = raw.area.trim()
|
||||
if (!area || !operation.startsWith(`${area}.`) || operation.length <= area.length + 1) return
|
||||
if (raw.ids !== undefined && !isRecord(raw.ids)) return
|
||||
const ids = isRecord(raw.ids) ? raw.ids : {}
|
||||
const change: AssistantDataChange = {
|
||||
operation, area,
|
||||
ids: {
|
||||
knowledgeBaseIds: stringIds(ids.knowledge_base_id),
|
||||
knowledgeIds: stringIds(ids.knowledge_id),
|
||||
agentIds: stringIds(ids.agent_id),
|
||||
},
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent(ASSISTANT_DATA_CHANGE_EVENT, { detail: change }))
|
||||
}
|
||||
|
||||
export function subscribeAssistantDataChange(handler: ChangeHandler, { areas, debounceMs = 300 }: ChangeOptions = {}) {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let pending: AssistantDataChange[] = []
|
||||
const listener = (event: Event) => {
|
||||
const change = (event as CustomEvent<AssistantDataChange>).detail
|
||||
if (!change || !isRecord(change.ids) || typeof change.operation !== 'string' || typeof change.area !== 'string') return
|
||||
const { knowledgeBaseIds, knowledgeIds, agentIds } = change.ids
|
||||
if (![knowledgeBaseIds, knowledgeIds, agentIds].every(ids =>
|
||||
Array.isArray(ids) && ids.every(id => typeof id === 'string'))) return
|
||||
if (areas && !areas.includes(change.area)) return
|
||||
pending.push(change)
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(() => {
|
||||
const changes = pending
|
||||
pending = []
|
||||
timer = undefined
|
||||
handler(changes)
|
||||
}, debounceMs)
|
||||
}
|
||||
window.addEventListener(ASSISTANT_DATA_CHANGE_EVENT, listener)
|
||||
return () => {
|
||||
window.removeEventListener(ASSISTANT_DATA_CHANGE_EVENT, listener)
|
||||
clearTimeout(timer)
|
||||
pending = []
|
||||
}
|
||||
}
|
||||
|
||||
export function useAssistantDataChange(handler: ChangeHandler, options: ChangeOptions = {}) {
|
||||
let unsubscribe: (() => void) | undefined
|
||||
onMounted(() => { unsubscribe = subscribeAssistantDataChange(handler, options) })
|
||||
onUnmounted(() => { unsubscribe?.() })
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
isAssistantPageLink, pageLinkDraft, pageLinkEndpoint, pageLinkLocation, pageLinkReturnPath, type AssistantPageLink,
|
||||
} from './assistantPageLink'
|
||||
|
||||
const link = (fields: Partial<AssistantPageLink>): AssistantPageLink =>
|
||||
({ display_type: 'open_page', page: 'knowledge_base', label: 'x', ...fields }) as AssistantPageLink
|
||||
|
||||
test('links use the deep links each page reads', () => {
|
||||
assert.deepEqual(pageLinkLocation(link({ knowledge_base_id: 'kb/1', knowledge_id: 'doc' })),
|
||||
{ path: '/platform/knowledge-bases/kb%2F1', query: { knowledge_id: 'doc' } })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'wiki', knowledge_base_id: 'kb', wiki_slug: 'entity/acme' })),
|
||||
{ path: '/platform/knowledge-bases/kb', query: { tab: 'wiki', slug: 'entity/acme' } })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'agent_editor', agent_id: 'a', section: 'tools' })),
|
||||
{ path: '/platform/agents', query: { edit: 'a', section: 'tools' } })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'settings_models', model_id: 'm' })),
|
||||
{ path: '/platform/settings', query: { section: 'models', model_id: 'm' } })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'mcp_services' })), { path: '/platform/toolbox/mcp', query: {} })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'automations', automation_id: 'a/1' })),
|
||||
{ path: '/platform/automations/a%2F1', query: {} })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'automations' })), { path: '/platform/automations', query: {} })
|
||||
assert.equal(pageLinkLocation(link({ page: 'agent_editor' })), null, 'a link without its target goes nowhere')
|
||||
})
|
||||
|
||||
test('a page the assistant opened goes back only to an in-app path', () => {
|
||||
assert.equal(pageLinkReturnPath(link({ navigated: true, return_path: '/platform/agents?x=1' })), '/platform/agents?x=1')
|
||||
assert.equal(pageLinkReturnPath(link({ return_path: '/platform/agents' })), '', 'a button has no way back')
|
||||
for (const bad of ['https://evil.example', '//evil.example', '/\\evil.example', '']) {
|
||||
assert.equal(pageLinkReturnPath(link({ navigated: true, return_path: bad })), '', bad)
|
||||
}
|
||||
})
|
||||
|
||||
test('pages without a resource open the settings section, the tool or the list', () => {
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'settings', section: 'general' })),
|
||||
{ path: '/platform/settings', query: { section: 'general' } })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'settings', section: 'system-global', panel: 'users' })),
|
||||
{ path: '/platform/settings', query: { section: 'system-global', panel: 'users' } })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'settings' })), { path: '/platform/settings', query: {} })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'toolbox', section: 'skills' })),
|
||||
{ path: '/platform/toolbox/skills', query: {} })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'toolbox' })), { path: '/platform/toolbox', query: {} })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'agents' })), { path: '/platform/agents', query: {} })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'knowledge_bases' })), { path: '/platform/knowledge-bases', query: {} })
|
||||
assert.deepEqual(pageLinkLocation(link({ page: 'organizations' })), { path: '/platform/organizations', query: {} })
|
||||
})
|
||||
|
||||
test('only a new model or service carries a form, and its endpoint is shown', () => {
|
||||
const model = link({ page: 'settings_models', model_draft: { type: 'chat', base_url: 'https://api.example/v1' } })
|
||||
assert.deepEqual(pageLinkDraft(model), { kind: 'model', draft: { type: 'chat', base_url: 'https://api.example/v1' } })
|
||||
assert.equal(pageLinkEndpoint(model), 'https://api.example/v1')
|
||||
assert.equal(pageLinkDraft(link({ page: 'settings_models', model_id: 'm', model_draft: { type: 'chat' } })), null)
|
||||
const mcp = link({ page: 'mcp_services', mcp_service_draft: { name: 'J', transport_type: 'sse', url: 'https://m.example' } })
|
||||
assert.equal(pageLinkDraft(mcp)?.kind, 'mcp_service')
|
||||
assert.equal(pageLinkEndpoint(mcp), 'https://m.example')
|
||||
assert.equal(pageLinkDraft(link({ knowledge_base_id: 'kb' })), null)
|
||||
assert.equal(isAssistantPageLink({ display_type: 'open_page', page: 'wiki', label: 'W' }), true)
|
||||
assert.equal(isAssistantPageLink({ display_type: 'search_results' }), false)
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import type {
|
||||
AssistantMcpServiceDraft,
|
||||
AssistantModelDraft,
|
||||
AssistantPageDraft,
|
||||
} from '@/stores/assistant'
|
||||
|
||||
/** The open_page tool's result: a checked link, optionally with a form to fill in. */
|
||||
export interface AssistantPageLink {
|
||||
display_type: 'open_page'
|
||||
page:
|
||||
| 'knowledge_base' | 'wiki' | 'agent_editor' | 'settings_models' | 'mcp_services'
|
||||
| 'settings' | 'toolbox' | 'agents' | 'knowledge_bases' | 'organizations' | 'automations'
|
||||
label: string
|
||||
detail?: string
|
||||
note?: string
|
||||
knowledge_base_id?: string
|
||||
knowledge_id?: string
|
||||
wiki_slug?: string
|
||||
agent_id?: string
|
||||
automation_id?: string
|
||||
section?: string
|
||||
/** A tab inside a settings section, e.g. system-global's users. */
|
||||
panel?: string
|
||||
model_id?: string
|
||||
model_draft?: AssistantModelDraft
|
||||
mcp_service_id?: string
|
||||
mcp_service_draft?: AssistantMcpServiceDraft
|
||||
/** The assistant opened the page itself; return_path is where the user was. */
|
||||
navigated?: boolean
|
||||
return_path?: string
|
||||
}
|
||||
|
||||
/** Where a navigated link's back button goes: an in-app path only. */
|
||||
export function pageLinkReturnPath(link: AssistantPageLink): string {
|
||||
const path = link.navigated ? link.return_path || '' : ''
|
||||
return path.startsWith('/') && !path.startsWith('//') && !path.includes('\\') ? path : ''
|
||||
}
|
||||
|
||||
export interface PageLinkLocation {
|
||||
path: string
|
||||
query: Record<string, string>
|
||||
}
|
||||
|
||||
export function isAssistantPageLink(value: unknown): value is AssistantPageLink {
|
||||
const link = value as AssistantPageLink | null
|
||||
return !!link && link.display_type === 'open_page' && typeof link.page === 'string' && typeof link.label === 'string'
|
||||
}
|
||||
|
||||
/** Where the link goes, using the deep links the pages already read. */
|
||||
export function pageLinkLocation(link: AssistantPageLink): PageLinkLocation | null {
|
||||
switch (link.page) {
|
||||
case 'knowledge_base':
|
||||
if (!link.knowledge_base_id) return null
|
||||
return {
|
||||
path: `/platform/knowledge-bases/${encodeURIComponent(link.knowledge_base_id)}`,
|
||||
query: link.knowledge_id ? { knowledge_id: link.knowledge_id } : {},
|
||||
}
|
||||
case 'wiki':
|
||||
if (!link.knowledge_base_id) return null
|
||||
return {
|
||||
path: `/platform/knowledge-bases/${encodeURIComponent(link.knowledge_base_id)}`,
|
||||
query: { tab: 'wiki', ...(link.wiki_slug ? { slug: link.wiki_slug } : {}) },
|
||||
}
|
||||
case 'agent_editor':
|
||||
if (!link.agent_id) return null
|
||||
return {
|
||||
path: '/platform/agents',
|
||||
query: { edit: link.agent_id, ...(link.section ? { section: link.section } : {}) },
|
||||
}
|
||||
case 'settings_models':
|
||||
return {
|
||||
path: '/platform/settings',
|
||||
query: { section: 'models', ...(link.model_id ? { model_id: link.model_id } : {}) },
|
||||
}
|
||||
case 'mcp_services':
|
||||
return {
|
||||
path: '/platform/toolbox/mcp',
|
||||
query: link.mcp_service_id ? { service_id: link.mcp_service_id } : {},
|
||||
}
|
||||
case 'settings':
|
||||
return {
|
||||
path: '/platform/settings',
|
||||
query: {
|
||||
...(link.section ? { section: link.section } : {}),
|
||||
...(link.panel ? { panel: link.panel } : {}),
|
||||
},
|
||||
}
|
||||
case 'toolbox':
|
||||
return {
|
||||
path: link.section ? `/platform/toolbox/${encodeURIComponent(link.section)}` : '/platform/toolbox',
|
||||
query: {},
|
||||
}
|
||||
case 'agents':
|
||||
return { path: '/platform/agents', query: {} }
|
||||
case 'knowledge_bases':
|
||||
return { path: '/platform/knowledge-bases', query: {} }
|
||||
case 'organizations':
|
||||
return { path: '/platform/organizations', query: {} }
|
||||
case 'automations':
|
||||
return {
|
||||
path: link.automation_id
|
||||
? `/platform/automations/${encodeURIComponent(link.automation_id)}`
|
||||
: '/platform/automations',
|
||||
query: {},
|
||||
}
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** The form the link's page should open filled in, if any. */
|
||||
export function pageLinkDraft(link: AssistantPageLink): AssistantPageDraft | null {
|
||||
if (link.page === 'settings_models' && link.model_draft && !link.model_id) {
|
||||
return { kind: 'model', draft: { ...link.model_draft } }
|
||||
}
|
||||
if (link.page === 'mcp_services' && link.mcp_service_draft && !link.mcp_service_id) {
|
||||
return { kind: 'mcp_service', draft: { ...link.mcp_service_draft } }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The endpoint a draft would connect to, shown so the user can check it before typing a key. */
|
||||
export function pageLinkEndpoint(link: AssistantPageLink): string {
|
||||
return link.model_draft?.base_url || link.mcp_service_draft?.url || ''
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { routeTitle } from './assistantRouteTitle'
|
||||
|
||||
const t = (key: string) => `<${key}>`
|
||||
|
||||
test('routeTitle names the pages the sidebar names', () => {
|
||||
assert.equal(routeTitle({ name: 'agentList' }, t), '<menu.agents>')
|
||||
assert.equal(routeTitle({ name: 'knowledgeBaseList' }, t), '<menu.knowledgeBase>')
|
||||
assert.equal(routeTitle({ name: 'organizationList' }, t), '<menu.organizations>')
|
||||
assert.equal(routeTitle({ name: 'chat', params: { chatid: 'x' } }, t), '<assistant.context.pages.chat>')
|
||||
})
|
||||
|
||||
test('routeTitle adds the toolbox section and skips unnamed routes', () => {
|
||||
assert.equal(routeTitle({ name: 'toolbox', params: { section: 'skills' } }, t),
|
||||
'<toolbox.title> / <settings.skills.title>')
|
||||
assert.equal(routeTitle({ name: 'toolbox', params: { section: 'nope' } }, t), '<toolbox.title>')
|
||||
assert.equal(routeTitle({ name: 'settings' }, t), '', 'settings names itself as a dialog')
|
||||
assert.equal(routeTitle({ name: undefined }, t), '')
|
||||
assert.equal(routeTitle({ name: Symbol('x') }, t), '')
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { TOOLBOX_ITEMS } from '../config/toolbox'
|
||||
|
||||
/** The bits of a route that name the page; vue-router's route fits. */
|
||||
export interface TitledRoute {
|
||||
name?: string | symbol | null
|
||||
params?: Record<string, unknown>
|
||||
}
|
||||
|
||||
// The sidebar's names for the pages. Settings is left out: it is a dialog
|
||||
// over the page, and the dialog names itself.
|
||||
const ROUTE_TITLE_KEYS: Record<string, string> = {
|
||||
knowledgeBaseList: 'menu.knowledgeBase',
|
||||
knowledgeBaseDetail: 'menu.knowledgeBase',
|
||||
home: 'menu.knowledgeBase',
|
||||
artifactLibrary: 'menu.artifacts',
|
||||
agentList: 'menu.agents',
|
||||
toolbox: 'toolbox.title',
|
||||
globalCreatChat: 'menu.newChat',
|
||||
kbCreatChat: 'menu.newChat',
|
||||
chat: 'assistant.context.pages.chat',
|
||||
organizationList: 'menu.organizations',
|
||||
}
|
||||
|
||||
/** The page the route shows, as the sidebar names it; '' when it has no name. */
|
||||
export function routeTitle(route: TitledRoute, t: (key: string) => string): string {
|
||||
const key = typeof route.name === 'string' ? ROUTE_TITLE_KEYS[route.name] : undefined
|
||||
if (!key) return ''
|
||||
const parts = [t(key)]
|
||||
if (route.name === 'toolbox') {
|
||||
const item = TOOLBOX_ITEMS.find(entry => entry.key === route.params?.section)
|
||||
if (item) parts.push(t(item.title))
|
||||
}
|
||||
return parts.join(' / ')
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
getAttachmentParsingSummaryHtml,
|
||||
resolveAttachmentParsingCounts,
|
||||
} from './attachmentParsingDisplay.ts'
|
||||
|
||||
const t = (key, params) => {
|
||||
if (key === 'agentStream.attachmentParsing.parsedSummary') {
|
||||
return `已解析 ${params?.count} 个附件`
|
||||
}
|
||||
if (key === 'agentStream.attachmentParsing.parsedWithSkipped') {
|
||||
return `已解析 ${params?.parsed} 个附件,${params?.skipped} 个未完成已跳过`
|
||||
}
|
||||
if (key === 'agentStream.attachmentParsing.noneReady') {
|
||||
return '没有可用的已解析附件'
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
test('resolveAttachmentParsingCounts prefers structured tool_data', () => {
|
||||
assert.deepEqual(
|
||||
resolveAttachmentParsingCounts({
|
||||
tool_data: { parsed_count: 2, skipped_count: 1 },
|
||||
}),
|
||||
{ parsed: 2, skipped: 1 },
|
||||
)
|
||||
})
|
||||
|
||||
test('resolveAttachmentParsingCounts falls back to legacy output text', () => {
|
||||
assert.deepEqual(
|
||||
resolveAttachmentParsingCounts({
|
||||
output: '已解析 3 个附件,1 个未完成已跳过',
|
||||
}),
|
||||
{ parsed: 3, skipped: 1 },
|
||||
)
|
||||
})
|
||||
|
||||
test('getAttachmentParsingSummaryHtml renders parsed count', () => {
|
||||
const html = getAttachmentParsingSummaryHtml(t, {
|
||||
success: true,
|
||||
tool_data: { parsed_count: 1, skipped_count: 0 },
|
||||
})
|
||||
assert.equal(html, '已解析 <strong>1</strong> 个附件')
|
||||
})
|
||||
|
||||
test('getAttachmentParsingSummaryHtml renders skipped count', () => {
|
||||
const html = getAttachmentParsingSummaryHtml(t, {
|
||||
success: true,
|
||||
tool_data: { parsed_count: 2, skipped_count: 1 },
|
||||
})
|
||||
assert.equal(html, '已解析 <strong>2</strong> 个附件,<strong>1</strong> 个未完成已跳过')
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { ComposerTranslation } from 'vue-i18n'
|
||||
|
||||
type AttachmentParsingEvent = {
|
||||
success?: boolean
|
||||
output?: string
|
||||
error?: string
|
||||
tool_data?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export function resolveAttachmentParsingCounts(event: AttachmentParsingEvent): {
|
||||
parsed: number
|
||||
skipped: number
|
||||
} {
|
||||
const toolData = event.tool_data
|
||||
if (toolData && toolData.parsed_count !== undefined) {
|
||||
return {
|
||||
parsed: Number(toolData.parsed_count) || 0,
|
||||
skipped: Number(toolData.skipped_count) || 0,
|
||||
}
|
||||
}
|
||||
|
||||
return parseAttachmentOutput(event.output)
|
||||
}
|
||||
|
||||
function parseAttachmentOutput(output?: string): { parsed: number; skipped: number } {
|
||||
if (!output) return { parsed: 0, skipped: 0 }
|
||||
|
||||
const parsedMatch = output.match(/已解析\s*(\d+)\s*个附件/)
|
||||
const skippedMatch = output.match(/(\d+)\s*个未完成已跳过/)
|
||||
const parsedEnMatch = output.match(/Parsed\s*(\d+)\s*attachment/i)
|
||||
const skippedEnMatch = output.match(/(\d+)\s*skipped/i)
|
||||
|
||||
return {
|
||||
parsed: Number(parsedMatch?.[1] ?? parsedEnMatch?.[1] ?? 0) || 0,
|
||||
skipped: Number(skippedMatch?.[1] ?? skippedEnMatch?.[1] ?? 0) || 0,
|
||||
}
|
||||
}
|
||||
|
||||
export function getAttachmentParsingSummaryHtml(
|
||||
t: ComposerTranslation,
|
||||
event: AttachmentParsingEvent,
|
||||
): string {
|
||||
if (event.success === false) {
|
||||
const err = String(event.error || event.output || '').trim()
|
||||
if (!err) return ''
|
||||
const normalized = err.replace(/^附件解析失败:\s*/i, '').trim()
|
||||
return normalized || err
|
||||
}
|
||||
|
||||
const { parsed, skipped } = resolveAttachmentParsingCounts(event)
|
||||
if (parsed === 0 && skipped === 0) {
|
||||
return t('agentStream.attachmentParsing.noneReady')
|
||||
}
|
||||
if (skipped > 0) {
|
||||
return t('agentStream.attachmentParsing.parsedWithSkipped', {
|
||||
parsed: `<strong>${parsed}</strong>`,
|
||||
skipped: `<strong>${skipped}</strong>`,
|
||||
})
|
||||
}
|
||||
return t('agentStream.attachmentParsing.parsedSummary', {
|
||||
count: `<strong>${parsed}</strong>`,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
isPreviewableAttachment,
|
||||
resolveAttachmentFileType,
|
||||
} from './attachmentPreview.ts';
|
||||
|
||||
test('resolveAttachmentFileType prefers explicit file_type', () => {
|
||||
assert.equal(resolveAttachmentFileType('report.PDF', '.pdf'), 'pdf');
|
||||
assert.equal(resolveAttachmentFileType('report.PDF', ''), 'pdf');
|
||||
});
|
||||
|
||||
test('isPreviewableAttachment requires id and supported type', () => {
|
||||
assert.equal(isPreviewableAttachment({ id: 'doc-1', file_name: 'notes.md' }), true);
|
||||
assert.equal(isPreviewableAttachment({ file_name: 'notes.md' }), false);
|
||||
assert.equal(isPreviewableAttachment({ id: 'doc-1', file_name: 'archive.zip' }), false);
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { resolveFilePreviewExt, isKnownPreviewableFile } from './filePreview'
|
||||
|
||||
export type ChatAttachmentLike = {
|
||||
id?: string
|
||||
file_name?: string
|
||||
file_type?: string
|
||||
}
|
||||
|
||||
export function resolveAttachmentFileType(fileName?: string, fileType?: string): string {
|
||||
return resolveFilePreviewExt(fileName, fileType)
|
||||
}
|
||||
|
||||
export function isPreviewableAttachment(attachment: ChatAttachmentLike | null | undefined): boolean {
|
||||
if (!attachment?.id) return false
|
||||
return isKnownPreviewableFile(attachment.file_name, attachment.file_type)
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
StreamAuthError,
|
||||
forceReloginRedirect,
|
||||
isStreamAuthError,
|
||||
refreshAccessTokenShared,
|
||||
resetAuthRefreshStateForTests,
|
||||
runStreamWithAuthRetry,
|
||||
} from './authRefresh.ts'
|
||||
|
||||
type Store = Record<string, string>
|
||||
|
||||
function installBrowser(pathname = '/chat') {
|
||||
const store: Store = {}
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: {
|
||||
getItem: (key: string) => (key in store ? store[key] : null),
|
||||
setItem: (key: string, value: string) => {
|
||||
store[key] = String(value)
|
||||
},
|
||||
removeItem: (key: string) => {
|
||||
delete store[key]
|
||||
},
|
||||
},
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
const location = { pathname, href: `http://localhost${pathname}` }
|
||||
Object.defineProperty(globalThis, 'window', {
|
||||
value: { location },
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
return { store, location }
|
||||
}
|
||||
|
||||
test.afterEach(() => {
|
||||
resetAuthRefreshStateForTests()
|
||||
})
|
||||
|
||||
test('isStreamAuthError matches the class and name-only wrappers', () => {
|
||||
assert.equal(isStreamAuthError(new StreamAuthError(401)), true)
|
||||
assert.equal(isStreamAuthError({ name: 'StreamAuthError', message: 'HTTP 401' }), true)
|
||||
assert.equal(isStreamAuthError(new Error('HTTP 401')), false)
|
||||
assert.equal(isStreamAuthError('HTTP 401'), false)
|
||||
})
|
||||
|
||||
test('concurrent 401s share a single refresh call', async () => {
|
||||
const { store } = installBrowser()
|
||||
store.weknora_refresh_token = 'rt-1'
|
||||
let calls = 0
|
||||
let release!: (value: { success: true; data: { token: string; refreshToken: string } }) => void
|
||||
const pending = new Promise<{ success: true; data: { token: string; refreshToken: string } }>(
|
||||
(resolve) => {
|
||||
release = resolve
|
||||
},
|
||||
)
|
||||
const refresh = async () => {
|
||||
calls += 1
|
||||
return pending
|
||||
}
|
||||
|
||||
const first = refreshAccessTokenShared({ refresh })
|
||||
await Promise.resolve()
|
||||
const second = refreshAccessTokenShared({ refresh })
|
||||
assert.equal(calls, 1)
|
||||
|
||||
release({ success: true, data: { token: 'access-2', refreshToken: 'rt-2' } })
|
||||
assert.deepEqual(await Promise.all([first, second]), ['access-2', 'access-2'])
|
||||
assert.equal(store.weknora_token, 'access-2')
|
||||
assert.equal(store.weknora_refresh_token, 'rt-2')
|
||||
assert.equal(calls, 1)
|
||||
})
|
||||
|
||||
test('missing refresh token clears credentials, redirects, and throws an Error', async () => {
|
||||
const { store, location } = installBrowser()
|
||||
store.weknora_token = 'expired'
|
||||
store.weknora_user = '{}'
|
||||
store.weknora_selected_tenant_id = '9'
|
||||
|
||||
await assert.rejects(
|
||||
() => refreshAccessTokenShared({
|
||||
refresh: async () => {
|
||||
throw new Error('should not refresh')
|
||||
},
|
||||
messages: { pleaseRelogin: 'please-relogin', tokenRefreshFailed: 'refresh-failed' },
|
||||
}),
|
||||
(err: unknown) => err instanceof Error && err.message === 'please-relogin',
|
||||
)
|
||||
assert.equal(store.weknora_token, undefined)
|
||||
assert.equal(store.weknora_selected_tenant_id, undefined)
|
||||
assert.equal(location.href, '/login')
|
||||
})
|
||||
|
||||
test('a failed refresh clears the newly irrelevant session and redirects', async () => {
|
||||
const { store, location } = installBrowser()
|
||||
store.weknora_refresh_token = 'rt-dead'
|
||||
store.weknora_token = 'expired'
|
||||
store.weknora_selected_tenant_id = '9'
|
||||
|
||||
await assert.rejects(
|
||||
() => refreshAccessTokenShared({
|
||||
refresh: async () => ({ success: false, message: 'revoked' }),
|
||||
}),
|
||||
/revoked/,
|
||||
)
|
||||
assert.equal(store.weknora_refresh_token, undefined)
|
||||
assert.equal(store.weknora_selected_tenant_id, undefined)
|
||||
assert.equal(location.href, '/login')
|
||||
})
|
||||
|
||||
test('runStreamWithAuthRetry refreshes once and replays with the new token', async () => {
|
||||
installBrowser()
|
||||
const tokens: string[] = []
|
||||
const result = await runStreamWithAuthRetry({
|
||||
initialToken: 'expired',
|
||||
isEmbed: false,
|
||||
isCurrent: () => true,
|
||||
refreshAccessToken: async () => 'fresh',
|
||||
reloginMessage: 'please-relogin',
|
||||
run: async (token) => {
|
||||
tokens.push(token)
|
||||
if (token === 'expired') throw new StreamAuthError(401)
|
||||
return `ok:${token}`
|
||||
},
|
||||
})
|
||||
assert.deepEqual(tokens, ['expired', 'fresh'])
|
||||
assert.equal(result, 'ok:fresh')
|
||||
})
|
||||
|
||||
test('embed visitors are not refreshed or redirected', async () => {
|
||||
let refreshed = 0
|
||||
await assert.rejects(
|
||||
() => runStreamWithAuthRetry({
|
||||
initialToken: 'embed-token',
|
||||
isEmbed: true,
|
||||
isCurrent: () => true,
|
||||
refreshAccessToken: async () => {
|
||||
refreshed += 1
|
||||
return 'nope'
|
||||
},
|
||||
reloginMessage: 'please-relogin',
|
||||
run: async () => {
|
||||
throw new StreamAuthError(401)
|
||||
},
|
||||
}),
|
||||
(err: unknown) => err instanceof StreamAuthError,
|
||||
)
|
||||
assert.equal(refreshed, 0)
|
||||
})
|
||||
|
||||
test('a second handshake 401 after a successful refresh does not wipe tokens', async () => {
|
||||
const { store, location } = installBrowser()
|
||||
store.weknora_token = 'expired'
|
||||
store.weknora_refresh_token = 'rt-1'
|
||||
location.href = 'http://localhost/chat'
|
||||
|
||||
await assert.rejects(
|
||||
() => runStreamWithAuthRetry({
|
||||
initialToken: 'expired',
|
||||
isEmbed: false,
|
||||
isCurrent: () => true,
|
||||
refreshAccessToken: async () => {
|
||||
const token = await refreshAccessTokenShared({
|
||||
refresh: async () => ({
|
||||
success: true,
|
||||
data: { token: 'fresh', refreshToken: 'rt-2' },
|
||||
}),
|
||||
})
|
||||
return token
|
||||
},
|
||||
reloginMessage: 'please-relogin',
|
||||
run: async () => {
|
||||
throw new StreamAuthError(401)
|
||||
},
|
||||
}),
|
||||
(err: unknown) => err instanceof Error && err.message === 'please-relogin',
|
||||
)
|
||||
assert.equal(store.weknora_token, 'fresh')
|
||||
assert.equal(store.weknora_refresh_token, 'rt-2')
|
||||
assert.equal(location.href, 'http://localhost/chat')
|
||||
})
|
||||
|
||||
test('a superseded send skips the replay', async () => {
|
||||
let runs = 0
|
||||
const result = await runStreamWithAuthRetry({
|
||||
initialToken: 'expired',
|
||||
isEmbed: false,
|
||||
isCurrent: () => false,
|
||||
refreshAccessToken: async () => 'fresh',
|
||||
reloginMessage: 'please-relogin',
|
||||
run: async () => {
|
||||
runs += 1
|
||||
throw new StreamAuthError(401)
|
||||
},
|
||||
})
|
||||
assert.equal(runs, 1)
|
||||
assert.equal(result, undefined)
|
||||
})
|
||||
|
||||
test('forceReloginRedirect does not bounce embed visitors to /login', () => {
|
||||
const { store, location } = installBrowser('/embed/ch-1')
|
||||
store.weknora_token = 'jwt'
|
||||
forceReloginRedirect()
|
||||
assert.equal(store.weknora_token, undefined)
|
||||
assert.equal(location.href, 'http://localhost/embed/ch-1')
|
||||
})
|
||||
|
||||
test('chat stream wires the shared retry and keeps the abort controller', () => {
|
||||
const source = readFileSync(new URL('../api/chat/streame.ts', import.meta.url), 'utf8')
|
||||
assert.match(source, /runStreamWithAuthRetry/)
|
||||
assert.match(source, /isStreamAuthError/)
|
||||
assert.match(source, /streamAbort/)
|
||||
assert.doesNotMatch(source, /forceReloginRedirect/)
|
||||
})
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* Shared access-token refresh used by both axios and the chat SSE client.
|
||||
*
|
||||
* Refresh tokens rotate, so concurrent 401s must queue behind one in-flight
|
||||
* /auth/refresh. The SSE handshake runs on raw fetch and cannot use the
|
||||
* axios interceptor; both planes call {@link refreshAccessTokenShared}.
|
||||
*/
|
||||
|
||||
const AUTH_STORAGE_KEYS = [
|
||||
'weknora_token',
|
||||
'weknora_refresh_token',
|
||||
'weknora_user',
|
||||
'weknora_tenant',
|
||||
'weknora_knowledge_bases',
|
||||
'weknora_current_kb',
|
||||
'weknora_selected_tenant_id',
|
||||
'weknora_selected_tenant_name',
|
||||
'weknora_memberships',
|
||||
] as const
|
||||
|
||||
let isRefreshing = false
|
||||
let failedQueue: Array<{
|
||||
resolve: (token: string) => void
|
||||
reject: (error: unknown) => void
|
||||
}> = []
|
||||
|
||||
export type TokenRefreshResult = {
|
||||
success: boolean
|
||||
data?: { token: string; refreshToken: string }
|
||||
message?: string
|
||||
}
|
||||
|
||||
export type RefreshAccessTokenOptions = {
|
||||
refresh?: (refreshToken: string) => Promise<TokenRefreshResult>
|
||||
messages?: {
|
||||
pleaseRelogin: string
|
||||
tokenRefreshFailed: string
|
||||
}
|
||||
}
|
||||
|
||||
const defaultMessages = {
|
||||
pleaseRelogin: 'Please log in again',
|
||||
tokenRefreshFailed: 'Token refresh failed',
|
||||
}
|
||||
|
||||
export class StreamAuthError extends Error {
|
||||
constructor(readonly status: number) {
|
||||
super(`HTTP ${status}`)
|
||||
this.name = 'StreamAuthError'
|
||||
}
|
||||
}
|
||||
|
||||
export function isStreamAuthError(err: unknown): boolean {
|
||||
if (!err || typeof err !== 'object') return false
|
||||
if (err instanceof StreamAuthError) return true
|
||||
return (err as { name?: string }).name === 'StreamAuthError'
|
||||
}
|
||||
|
||||
export function isEmbedPage(): boolean {
|
||||
if (typeof window === 'undefined') return false
|
||||
return window.location.pathname.startsWith('/embed/')
|
||||
}
|
||||
|
||||
export function redirectToLogin() {
|
||||
if (typeof window === 'undefined') return
|
||||
if (window.location.pathname === '/login') return
|
||||
if (isEmbedPage()) return
|
||||
window.location.href = '/login'
|
||||
}
|
||||
|
||||
export function clearAuthStorage() {
|
||||
for (const key of AUTH_STORAGE_KEYS) {
|
||||
localStorage.removeItem(key)
|
||||
}
|
||||
}
|
||||
|
||||
export function forceReloginRedirect() {
|
||||
clearAuthStorage()
|
||||
redirectToLogin()
|
||||
}
|
||||
|
||||
function processQueue(error: unknown, token: string | null = null) {
|
||||
failedQueue.forEach(({ resolve, reject }) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
} else {
|
||||
resolve(token as string)
|
||||
}
|
||||
})
|
||||
failedQueue = []
|
||||
}
|
||||
|
||||
async function defaultRefresh(refreshToken: string): Promise<TokenRefreshResult> {
|
||||
const { refreshToken: refreshTokenAPI } = await import('../api/auth/index')
|
||||
return refreshTokenAPI(refreshToken)
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the access token, de-duplicated across all callers.
|
||||
*
|
||||
* Resolves with the new access token. On failure it has already cleared
|
||||
* credentials and redirected to /login.
|
||||
*/
|
||||
export async function refreshAccessTokenShared(
|
||||
options: RefreshAccessTokenOptions = {},
|
||||
): Promise<string> {
|
||||
const messages = { ...defaultMessages, ...options.messages }
|
||||
const refresh = options.refresh ?? defaultRefresh
|
||||
|
||||
if (isRefreshing) {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
failedQueue.push({ resolve, reject })
|
||||
})
|
||||
}
|
||||
|
||||
isRefreshing = true
|
||||
const storedRefreshToken = localStorage.getItem('weknora_refresh_token')
|
||||
|
||||
if (!storedRefreshToken) {
|
||||
clearAuthStorage()
|
||||
const noRefreshTokenError = new Error(messages.pleaseRelogin)
|
||||
processQueue(noRefreshTokenError, null)
|
||||
isRefreshing = false
|
||||
redirectToLogin()
|
||||
throw noRefreshTokenError
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await refresh(storedRefreshToken)
|
||||
|
||||
if (!response.success || !response.data?.token) {
|
||||
throw new Error(response.message || messages.tokenRefreshFailed)
|
||||
}
|
||||
|
||||
const { token, refreshToken: newRefreshToken } = response.data
|
||||
localStorage.setItem('weknora_token', token)
|
||||
if (newRefreshToken) {
|
||||
localStorage.setItem('weknora_refresh_token', newRefreshToken)
|
||||
}
|
||||
processQueue(null, token)
|
||||
return token
|
||||
} catch (refreshError) {
|
||||
clearAuthStorage()
|
||||
processQueue(refreshError, null)
|
||||
redirectToLogin()
|
||||
throw refreshError
|
||||
} finally {
|
||||
isRefreshing = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replay an SSE handshake once after a 401. Refresh failure already
|
||||
* redirected; a second 401 after a successful refresh is surfaced to the
|
||||
* caller without wiping the newly minted session (axios does the same).
|
||||
*
|
||||
* Returns undefined when a newer send or an abort superseded the replay.
|
||||
*/
|
||||
export async function runStreamWithAuthRetry<T>(options: {
|
||||
run: (token: string) => Promise<T>
|
||||
initialToken: string
|
||||
isEmbed: boolean
|
||||
isCurrent: () => boolean
|
||||
refreshAccessToken: () => Promise<string>
|
||||
reloginMessage: string
|
||||
}): Promise<T | undefined> {
|
||||
try {
|
||||
return await options.run(options.initialToken)
|
||||
} catch (err) {
|
||||
if (!isStreamAuthError(err) || options.isEmbed) throw err
|
||||
|
||||
let refreshedToken: string
|
||||
try {
|
||||
refreshedToken = await options.refreshAccessToken()
|
||||
} catch {
|
||||
throw new Error(options.reloginMessage)
|
||||
}
|
||||
|
||||
if (!options.isCurrent()) return undefined
|
||||
|
||||
try {
|
||||
return await options.run(refreshedToken)
|
||||
} catch (retryErr) {
|
||||
if (isStreamAuthError(retryErr)) {
|
||||
throw new Error(options.reloginMessage)
|
||||
}
|
||||
throw retryErr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Reset module locks between unit tests. */
|
||||
export function resetAuthRefreshStateForTests() {
|
||||
isRefreshing = false
|
||||
failedQueue = []
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
describeTrigger,
|
||||
hasEndedOnceSchedule,
|
||||
scheduleFormFromTrigger,
|
||||
triggerFromScheduleForm,
|
||||
wallClockToISO,
|
||||
zonedWallClock,
|
||||
defaultScheduleForm,
|
||||
} from './automationSchedule'
|
||||
|
||||
test('presets round-trip through cron', () => {
|
||||
const cases = [
|
||||
{ kind: 'hourly', expr: '15 * * * *' },
|
||||
{ kind: 'daily', expr: '30 9 * * *' },
|
||||
{ kind: 'weekdays', expr: '0 8 * * 1-5' },
|
||||
{ kind: 'weekly', expr: '0 18 * * 1,5' },
|
||||
{ kind: 'monthly', expr: '0 7 1 * *' },
|
||||
]
|
||||
for (const { kind, expr } of cases) {
|
||||
const form = scheduleFormFromTrigger({ type: 'cron', expr, timezone: 'Asia/Shanghai' })
|
||||
assert.equal(form.kind, kind, expr)
|
||||
assert.deepEqual(triggerFromScheduleForm(form, 'Asia/Shanghai'), { type: 'cron', expr, timezone: 'Asia/Shanghai' })
|
||||
}
|
||||
})
|
||||
|
||||
test('expressions outside the presets stay custom', () => {
|
||||
for (const expr of ['*/30 * * * *', '0 9 * * MON', '0 0 9 * * *', '@daily', '0 9 1 1 *']) {
|
||||
const form = scheduleFormFromTrigger({ type: 'cron', expr })
|
||||
assert.equal(form.kind, 'custom', expr)
|
||||
assert.equal(triggerFromScheduleForm(form, 'UTC')?.expr, expr)
|
||||
}
|
||||
})
|
||||
|
||||
test('incomplete forms give no trigger', () => {
|
||||
assert.equal(triggerFromScheduleForm({ ...defaultScheduleForm(), kind: 'weekly', days: [] }, 'UTC'), null)
|
||||
assert.equal(triggerFromScheduleForm({ ...defaultScheduleForm(), kind: 'custom', expr: ' ' }, 'UTC'), null)
|
||||
assert.equal(triggerFromScheduleForm({ ...defaultScheduleForm(), kind: 'once', at: '' }, 'UTC'), null)
|
||||
})
|
||||
|
||||
test('once triggers use wall-clock time in their timezone', () => {
|
||||
assert.equal(wallClockToISO('2026-03-01 09:00', 'Asia/Shanghai'), '2026-03-01T01:00:00.000Z')
|
||||
// New York is UTC-5 in winter and UTC-4 in summer.
|
||||
assert.equal(wallClockToISO('2026-01-15 09:00', 'America/New_York'), '2026-01-15T14:00:00.000Z')
|
||||
assert.equal(wallClockToISO('2026-07-15 09:00', 'America/New_York'), '2026-07-15T13:00:00.000Z')
|
||||
assert.equal(zonedWallClock('2026-07-15T13:00:00Z', 'America/New_York'), '2026-07-15 09:00')
|
||||
assert.equal(wallClockToISO('soon', 'UTC'), '')
|
||||
|
||||
const trigger = triggerFromScheduleForm({ ...defaultScheduleForm(), kind: 'once', at: '2026-03-01 09:00' }, 'Asia/Shanghai')
|
||||
assert.deepEqual(trigger, { type: 'once', at: '2026-03-01T01:00:00.000Z', timezone: 'Asia/Shanghai' })
|
||||
assert.equal(scheduleFormFromTrigger(trigger!).at, '2026-03-01 09:00')
|
||||
})
|
||||
|
||||
test('describeTrigger names the schedule', () => {
|
||||
const t = (key: string, params?: Record<string, unknown>) => `${key}${params ? JSON.stringify(params) : ''}`
|
||||
assert.equal(
|
||||
describeTrigger({ type: 'cron', expr: '5 9 * * 1,3' }, t, 'en-US'),
|
||||
'automation.schedule.describe.weekly{"days":"Mon, Wed","time":"09:05"}',
|
||||
)
|
||||
assert.equal(
|
||||
describeTrigger({ type: 'cron', expr: '*/10 * * * *' }, t, 'en-US'),
|
||||
'automation.schedule.describe.everyMinutes{"n":10}',
|
||||
)
|
||||
assert.equal(
|
||||
describeTrigger({ type: 'cron', expr: '0 */2 * * *' }, t, 'en-US'),
|
||||
'automation.schedule.describe.everyHours{"n":2}',
|
||||
)
|
||||
assert.equal(
|
||||
describeTrigger({ type: 'cron', expr: '*/10 9-17 * * *' }, t, 'en-US'),
|
||||
'automation.schedule.describe.custom{"expr":"*/10 9-17 * * *"}',
|
||||
)
|
||||
})
|
||||
|
||||
test('only disabled one-shot schedules with no future occurrence have ended', () => {
|
||||
const now = Date.parse('2026-10-20T08:00:00Z')
|
||||
const once = (at: string, enabled = false) => ({ enabled, trigger: { type: 'once' as const, at } })
|
||||
assert.equal(hasEndedOnceSchedule(once('2026-10-20T15:59:59+08:00'), now), true)
|
||||
assert.equal(hasEndedOnceSchedule(once('2026-10-20T16:00:00+08:00'), now), true)
|
||||
assert.equal(hasEndedOnceSchedule(once('2026-10-20T16:00:01+08:00'), now), false)
|
||||
assert.equal(hasEndedOnceSchedule(once('2026-10-20T15:59:59+08:00', true), now), false)
|
||||
assert.equal(hasEndedOnceSchedule({ enabled: false, trigger: { type: 'cron', expr: '0 9 * * *' } }, now), false)
|
||||
})
|
||||
|
||||
|
||||
test('once triggers reject wall-clock times skipped by a timezone transition', () => {
|
||||
for (const [local, zone] of [
|
||||
['2026-03-08 02:30', 'America/New_York'],
|
||||
['2026-10-04 02:15', 'Australia/Lord_Howe'],
|
||||
['2011-12-30 12:00', 'Pacific/Apia'],
|
||||
]) {
|
||||
assert.equal(wallClockToISO(local, zone), '', `${local} in ${zone}`)
|
||||
assert.equal(triggerFromScheduleForm({ ...defaultScheduleForm(), kind: 'once', at: local }, zone), null)
|
||||
}
|
||||
})
|
||||
|
||||
test('once triggers reject invalid calendar dates, clock fields and timezone names', () => {
|
||||
for (const local of ['2026-02-29 09:00', '2026-04-31 09:00', '2026-13-01 09:00',
|
||||
'2026-01-00 09:00', '2026-01-01 24:00', '2026-01-01 09:60', '2026-01-01 09:00oops']) {
|
||||
assert.equal(wallClockToISO(local, 'UTC'), '', local)
|
||||
}
|
||||
assert.equal(wallClockToISO('2026-01-01 09:00', 'Invalid/Timezone'), '')
|
||||
})
|
||||
|
||||
test('valid leap days and times adjacent to transitions retain the requested wall clock', () => {
|
||||
for (const [local, zone] of [
|
||||
['2028-02-29 09:00', 'UTC'],
|
||||
['2026-03-08 01:30', 'America/New_York'],
|
||||
['2026-03-08 03:30', 'America/New_York'],
|
||||
['2026-11-01 01:30', 'America/New_York'],
|
||||
['2026-10-04 02:30', 'Australia/Lord_Howe'],
|
||||
]) {
|
||||
const iso = wallClockToISO(local, zone)
|
||||
assert.ok(iso, `${local} in ${zone}`)
|
||||
assert.equal(zonedWallClock(iso, zone), local)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,230 @@
|
||||
import type { Automation, AutomationTrigger } from '@/api/automation'
|
||||
|
||||
// The editor offers a few schedule shapes and falls back to a raw cron
|
||||
// expression for anything else. Cron here is the server's five-field form,
|
||||
// minute first, evaluated in the trigger's timezone.
|
||||
|
||||
/** An elapsed one-shot schedule has no future occurrence to resume. */
|
||||
export function hasEndedOnceSchedule(automation: Pick<Automation, 'enabled' | 'trigger'>, now = Date.now()): boolean {
|
||||
return !automation.enabled && automation.trigger.type === 'once'
|
||||
&& Date.parse(automation.trigger.at || '') <= now
|
||||
}
|
||||
|
||||
export type ScheduleKind = 'hourly' | 'daily' | 'weekdays' | 'weekly' | 'monthly' | 'once' | 'custom'
|
||||
|
||||
export interface ScheduleForm {
|
||||
kind: ScheduleKind
|
||||
minute: number
|
||||
hour: number
|
||||
/** Days of the week for weekly, 0 = Sunday. */
|
||||
days: number[]
|
||||
/** Day of the month for monthly. */
|
||||
day: number
|
||||
/** Wall-clock time of a once trigger in the timezone, "YYYY-MM-DD HH:mm". */
|
||||
at: string
|
||||
/** Expression of a custom trigger. */
|
||||
expr: string
|
||||
}
|
||||
|
||||
export function defaultScheduleForm(): ScheduleForm {
|
||||
return { kind: 'daily', minute: 0, hour: 9, days: [1], day: 1, at: '', expr: '' }
|
||||
}
|
||||
|
||||
export function browserTimezone(): string {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'
|
||||
} catch {
|
||||
return 'UTC'
|
||||
}
|
||||
}
|
||||
|
||||
export function timezoneOptions(current?: string): string[] {
|
||||
let zones: string[] = []
|
||||
try {
|
||||
zones = (Intl as unknown as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.('timeZone') ?? []
|
||||
} catch {
|
||||
zones = []
|
||||
}
|
||||
const set = new Set(zones.length ? zones : ['UTC', 'Asia/Shanghai', 'America/New_York', 'Europe/London'])
|
||||
set.add('UTC')
|
||||
if (current) set.add(current)
|
||||
return [...set]
|
||||
}
|
||||
|
||||
const NUM = /^\d{1,2}$/
|
||||
|
||||
function num(field: string, min: number, max: number): number | null {
|
||||
if (!NUM.test(field)) return null
|
||||
const n = Number(field)
|
||||
return n >= min && n <= max ? n : null
|
||||
}
|
||||
|
||||
/** Read a trigger back into the editor; anything the presets cannot express is custom. */
|
||||
export function scheduleFormFromTrigger(trigger: AutomationTrigger | undefined): ScheduleForm {
|
||||
const form = defaultScheduleForm()
|
||||
if (!trigger) return form
|
||||
if (trigger.type === 'once') {
|
||||
form.kind = 'once'
|
||||
form.at = trigger.at ? zonedWallClock(trigger.at, trigger.timezone) : ''
|
||||
return form
|
||||
}
|
||||
const expr = (trigger.expr || '').trim()
|
||||
form.expr = expr
|
||||
form.kind = 'custom'
|
||||
const f = expr.split(/\s+/)
|
||||
if (f.length !== 5) return form
|
||||
const [mi, h, dom, mon, dow] = f
|
||||
const minute = num(mi, 0, 59)
|
||||
if (minute === null || mon !== '*') return form
|
||||
if (h === '*' && dom === '*' && dow === '*') {
|
||||
return { ...form, kind: 'hourly', minute }
|
||||
}
|
||||
const hour = num(h, 0, 23)
|
||||
if (hour === null) return form
|
||||
if (dom === '*' && dow === '*') return { ...form, kind: 'daily', minute, hour }
|
||||
if (dom === '*' && dow === '1-5') return { ...form, kind: 'weekdays', minute, hour }
|
||||
if (dom === '*' && /^[0-6](,[0-6])*$/.test(dow)) {
|
||||
const days = [...new Set(dow.split(',').map(Number))].sort((a, b) => a - b)
|
||||
return { ...form, kind: 'weekly', minute, hour, days }
|
||||
}
|
||||
const day = num(dom, 1, 31)
|
||||
if (day !== null && dow === '*') return { ...form, kind: 'monthly', minute, hour, day }
|
||||
return form
|
||||
}
|
||||
|
||||
/** The trigger the editor describes, or null while it is incomplete. */
|
||||
export function triggerFromScheduleForm(form: ScheduleForm, timezone: string): AutomationTrigger | null {
|
||||
const tz = timezone || 'UTC'
|
||||
const m = form.minute
|
||||
const h = form.hour
|
||||
let expr = ''
|
||||
switch (form.kind) {
|
||||
case 'hourly':
|
||||
expr = `${m} * * * *`
|
||||
break
|
||||
case 'daily':
|
||||
expr = `${m} ${h} * * *`
|
||||
break
|
||||
case 'weekdays':
|
||||
expr = `${m} ${h} * * 1-5`
|
||||
break
|
||||
case 'weekly':
|
||||
if (!form.days.length) return null
|
||||
expr = `${m} ${h} * * ${[...new Set(form.days)].sort((a, b) => a - b).join(',')}`
|
||||
break
|
||||
case 'monthly':
|
||||
expr = `${m} ${h} ${form.day} * *`
|
||||
break
|
||||
case 'custom':
|
||||
expr = form.expr.trim()
|
||||
if (!expr) return null
|
||||
break
|
||||
case 'once': {
|
||||
const at = wallClockToISO(form.at, tz)
|
||||
return at ? { type: 'once', at, timezone: tz } : null
|
||||
}
|
||||
}
|
||||
return { type: 'cron', expr, timezone: tz }
|
||||
}
|
||||
|
||||
function zoneParts(date: Date, timeZone: string) {
|
||||
const parts = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone,
|
||||
hourCycle: 'h23',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
}).formatToParts(date)
|
||||
const get = (type: string) => Number(parts.find((p) => p.type === type)?.value ?? 0)
|
||||
return { y: get('year'), mo: get('month'), d: get('day'), h: get('hour') % 24, mi: get('minute'), s: get('second') }
|
||||
}
|
||||
|
||||
function offsetMs(date: Date, timeZone: string): number {
|
||||
const p = zoneParts(date, timeZone)
|
||||
return Date.UTC(p.y, p.mo - 1, p.d, p.h, p.mi, p.s) - Math.floor(date.getTime() / 1000) * 1000
|
||||
}
|
||||
|
||||
const WALL = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})$/
|
||||
|
||||
/** RFC 3339 instant of wall-clock time local in timeZone, or '' if local is malformed. */
|
||||
export function wallClockToISO(local: string, timeZone: string): string {
|
||||
const match = WALL.exec(local || '')
|
||||
if (!match) return ''
|
||||
const [, y, mo, d, h, mi] = match.map(Number)
|
||||
const guess = Date.UTC(y, mo - 1, d, h, mi)
|
||||
try {
|
||||
let t = guess - offsetMs(new Date(guess), timeZone)
|
||||
// A second pass settles instants near a daylight-saving change.
|
||||
t = guess - offsetMs(new Date(t), timeZone)
|
||||
const date = new Date(t)
|
||||
const p = zoneParts(date, timeZone)
|
||||
// Date.UTC normalizes invalid fields, and offset iteration can land on a
|
||||
// different local time inside a DST gap. Never schedule that other time.
|
||||
if (p.y !== y || p.mo !== mo || p.d !== d || p.h !== h || p.mi !== mi || p.s !== 0) return ''
|
||||
return date.toISOString()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/** Wall-clock "YYYY-MM-DD HH:mm" of iso in timeZone. */
|
||||
export function zonedWallClock(iso: string, timeZone?: string): string {
|
||||
const date = new Date(iso)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
const p = zoneParts(date, timeZone || 'UTC')
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${p.y}-${pad(p.mo)}-${pad(p.d)} ${pad(p.h)}:${pad(p.mi)}`
|
||||
}
|
||||
|
||||
/** iso as a medium date and short time in timeZone. */
|
||||
export function formatInZone(iso: string | null | undefined, timeZone: string | undefined, locale: string): string {
|
||||
if (!iso) return ''
|
||||
const date = new Date(iso)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
try {
|
||||
return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short', timeZone: timeZone || 'UTC' })
|
||||
.format(date)
|
||||
} catch {
|
||||
return date.toLocaleString(locale)
|
||||
}
|
||||
}
|
||||
|
||||
export function weekdayName(day: number, locale: string): string {
|
||||
// 2023-01-01 was a Sunday.
|
||||
return new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' }).format(new Date(Date.UTC(2023, 0, 1 + day)))
|
||||
}
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string
|
||||
|
||||
/** A short sentence for when trigger runs, such as "Every day at 09:00". */
|
||||
export function describeTrigger(trigger: AutomationTrigger, t: Translate, locale: string): string {
|
||||
const form = scheduleFormFromTrigger(trigger)
|
||||
const time = `${String(form.hour).padStart(2, '0')}:${String(form.minute).padStart(2, '0')}`
|
||||
switch (form.kind) {
|
||||
case 'hourly':
|
||||
return t('automation.schedule.describe.hourly', { minute: String(form.minute).padStart(2, '0') })
|
||||
case 'daily':
|
||||
return t('automation.schedule.describe.daily', { time })
|
||||
case 'weekdays':
|
||||
return t('automation.schedule.describe.weekdays', { time })
|
||||
case 'weekly':
|
||||
return t('automation.schedule.describe.weekly', {
|
||||
days: form.days.map((d) => weekdayName(d, locale)).join(', '),
|
||||
time,
|
||||
})
|
||||
case 'monthly':
|
||||
return t('automation.schedule.describe.monthly', { day: form.day, time })
|
||||
case 'once':
|
||||
return t('automation.schedule.describe.once', { at: formatInZone(trigger.at, trigger.timezone, locale) })
|
||||
default: {
|
||||
const every = /^\*\/(\d+) \* \* \* \*$/.exec(form.expr.trim())
|
||||
if (every) return t('automation.schedule.describe.everyMinutes', { n: Number(every[1]) })
|
||||
const hours = /^0 \*\/(\d+) \* \* \*$/.exec(form.expr.trim())
|
||||
if (hours) return t('automation.schedule.describe.everyHours', { n: Number(hours[1]) })
|
||||
return t('automation.schedule.describe.custom', { expr: form.expr })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
mergeBackgroundWork,
|
||||
createBackgroundWorkPoller,
|
||||
} from './backgroundWork.ts'
|
||||
import type { BackgroundWorkItem } from '../api/chat/background-work.ts'
|
||||
import { get, post } from '../utils/request.ts'
|
||||
|
||||
test('merge keeps newest state per work_id, running first', () => {
|
||||
const existing: BackgroundWorkItem[] = [
|
||||
{ work_id: 'sj_a', kind: 'shell', title: 'build', state: 'running' },
|
||||
{ work_id: 'sj_b', kind: 'shell', title: 'tests', state: 'running' },
|
||||
]
|
||||
const incoming: BackgroundWorkItem[] = [
|
||||
{ work_id: 'sj_b', kind: 'shell', title: 'tests', state: 'succeeded', finished_at: '2026-10-16T00:00:00Z' },
|
||||
{ work_id: 'sj_c', kind: 'shell', title: 'new', state: 'running' },
|
||||
]
|
||||
const merged = mergeBackgroundWork(existing, incoming)
|
||||
assert.deepEqual(merged.map(i => i.work_id), ['sj_a', 'sj_c', 'sj_b'])
|
||||
assert.equal(merged[2].state, 'succeeded', '新数据覆盖旧状态')
|
||||
})
|
||||
|
||||
test('poller retries after a list error instead of stopping', async () => {
|
||||
let calls = 0
|
||||
const seen: BackgroundWorkItem[][] = []
|
||||
const poller = createBackgroundWorkPoller({
|
||||
sessionId: 's1',
|
||||
intervalMs: 15,
|
||||
list: async () => {
|
||||
calls += 1
|
||||
if (calls === 1) throw new Error('unavailable')
|
||||
return [{ work_id: 'sj_a', kind: 'shell', title: 'build', state: 'running' }]
|
||||
},
|
||||
onUpdate: (items) => { seen.push(items) },
|
||||
onError: () => {},
|
||||
})
|
||||
poller.start()
|
||||
await new Promise((resolve) => setTimeout(resolve, 80))
|
||||
poller.stop()
|
||||
assert.ok(calls >= 2, '5xx 之后还要再拉')
|
||||
assert.ok(seen.some((items) => items.some((item) => item.work_id === 'sj_a')))
|
||||
})
|
||||
|
||||
test('poller stops on empty list and ignores stale session responses', async () => {
|
||||
const calls: string[] = []
|
||||
let respond: (v: any) => void = () => {}
|
||||
const gate = new Promise<void>(resolve => { respond = resolve })
|
||||
const fakeGet = (url: string) => {
|
||||
calls.push(url)
|
||||
return gate.then(() => ({ data: [] }))
|
||||
}
|
||||
const poller = createBackgroundWorkPoller({
|
||||
sessionId: 's1',
|
||||
intervalMs: 10,
|
||||
list: fakeGet,
|
||||
onUpdate: () => {},
|
||||
})
|
||||
poller.start()
|
||||
poller.stop() // 切会话:立即停
|
||||
respond(undefined)
|
||||
await new Promise(r => setTimeout(r, 30))
|
||||
assert.equal(calls.length, 1, '停止后不再发请求')
|
||||
})
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason: Error) => void
|
||||
const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no })
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
for (const staleItems of [[], [{ work_id: 'sj_old', kind: 'shell', title: 'old', state: 'running' }]] as BackgroundWorkItem[][]) {
|
||||
test(`manual refresh cannot replace another session or stop its polling (${staleItems.length} old items)`, async () => {
|
||||
let session = 'A'
|
||||
const requests: { session: string; response: ReturnType<typeof deferred<BackgroundWorkItem[]>> }[] = []
|
||||
const seen: BackgroundWorkItem[][] = []
|
||||
const poller = createBackgroundWorkPoller({
|
||||
sessionId: () => session,
|
||||
intervalMs: 60_000,
|
||||
list: (id) => {
|
||||
const response = deferred<BackgroundWorkItem[]>()
|
||||
requests.push({ session: id, response })
|
||||
return response.promise // Deliberately ignore AbortSignal, like a late network response.
|
||||
},
|
||||
onUpdate: items => seen.push(items),
|
||||
})
|
||||
try {
|
||||
const refreshA = poller.refresh()
|
||||
session = 'B'
|
||||
poller.stop()
|
||||
poller.start()
|
||||
const current: BackgroundWorkItem[] = [{ work_id: 'sj_new', kind: 'shell', state: 'running', title: 'new' }]
|
||||
requests[1].response.resolve(current)
|
||||
await Promise.resolve()
|
||||
requests[0].response.resolve(staleItems)
|
||||
await refreshA
|
||||
assert.deepEqual(seen, [current])
|
||||
const count = requests.length
|
||||
poller.start()
|
||||
assert.equal(requests.length, count, 'stale empty response must not stop B polling')
|
||||
} finally { poller.dispose() }
|
||||
})
|
||||
}
|
||||
|
||||
test('manual refresh is invalidated on switch away and back, unmount, and newer refresh', async () => {
|
||||
const requests: ReturnType<typeof deferred<BackgroundWorkItem[]>>[] = []
|
||||
const seen: BackgroundWorkItem[][] = []
|
||||
const poller = createBackgroundWorkPoller({
|
||||
sessionId: 'A',
|
||||
list: () => { const response = deferred<BackgroundWorkItem[]>(); requests.push(response); return response.promise },
|
||||
onUpdate: items => seen.push(items),
|
||||
})
|
||||
const first = poller.refresh()
|
||||
poller.stop() // A -> B -> A must invalidate the original A request too.
|
||||
const second = poller.refresh()
|
||||
const third = poller.refresh()
|
||||
requests[1].resolve([{ work_id: 'sj_old', kind: 'shell', state: 'running', title: '' }])
|
||||
requests[0].resolve([])
|
||||
await Promise.all([first, second])
|
||||
assert.deepEqual(seen, [])
|
||||
poller.dispose()
|
||||
requests[2].resolve([{ work_id: 'sj_late', kind: 'shell', state: 'running', title: '' }])
|
||||
await third
|
||||
await poller.refresh() // A cancellation completing after unmount must not restart polling.
|
||||
poller.start()
|
||||
assert.equal(requests.length, 3)
|
||||
assert.deepEqual(seen, [])
|
||||
})
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { BackgroundWorkItem } from '../api/chat/background-work'
|
||||
|
||||
function itemTime(item: BackgroundWorkItem): number {
|
||||
const parsed = Date.parse(item.started_at ?? item.finished_at ?? '')
|
||||
return Number.isFinite(parsed) ? parsed : 0
|
||||
}
|
||||
|
||||
function sameWorkItem(a: BackgroundWorkItem, b: BackgroundWorkItem): boolean {
|
||||
return a.work_id === b.work_id
|
||||
&& a.kind === b.kind
|
||||
&& a.title === b.title
|
||||
&& a.state === b.state
|
||||
&& a.started_at === b.started_at
|
||||
&& a.finished_at === b.finished_at
|
||||
}
|
||||
|
||||
function compareWork(a: BackgroundWorkItem, b: BackgroundWorkItem): number {
|
||||
const rank = (item: BackgroundWorkItem) => item.state === 'running' ? 0 : 1
|
||||
const byState = rank(a) - rank(b)
|
||||
if (byState !== 0) return byState
|
||||
return itemTime(a) - itemTime(b)
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge by work_id. Incoming wins. Unchanged items keep their object identity,
|
||||
* and an unchanged list keeps the same array, so a poll tick does not rerender.
|
||||
* Running rows stay above terminal ones; within a group, earlier times come first.
|
||||
*/
|
||||
export function mergeBackgroundWork(
|
||||
existing: BackgroundWorkItem[],
|
||||
incoming: BackgroundWorkItem[],
|
||||
): BackgroundWorkItem[] {
|
||||
const byID = new Map<string, BackgroundWorkItem>()
|
||||
for (const item of existing) byID.set(item.work_id, item)
|
||||
for (const item of incoming) {
|
||||
const prev = byID.get(item.work_id)
|
||||
if (prev && sameWorkItem(prev, item)) continue
|
||||
byID.set(item.work_id, item)
|
||||
}
|
||||
const sorted = [...byID.values()].sort(compareWork)
|
||||
if (sorted.length === existing.length && sorted.every((item, index) => item === existing[index])) {
|
||||
return existing
|
||||
}
|
||||
return sorted
|
||||
}
|
||||
|
||||
export interface PollerOptions {
|
||||
/** Current session, or a getter so a switch can drop the in-flight response. */
|
||||
sessionId: string | (() => string)
|
||||
intervalMs?: number
|
||||
list: (
|
||||
sessionId: string,
|
||||
signal: AbortSignal,
|
||||
) => Promise<BackgroundWorkItem[] | { data?: BackgroundWorkItem[] | null }>
|
||||
onUpdate: (items: BackgroundWorkItem[]) => void
|
||||
onError?: (message: string) => void
|
||||
}
|
||||
|
||||
function readSessionId(sessionId: PollerOptions['sessionId']): string {
|
||||
return typeof sessionId === 'function' ? sessionId() : sessionId
|
||||
}
|
||||
|
||||
function asWorkItems(
|
||||
value: BackgroundWorkItem[] | { data?: BackgroundWorkItem[] | null } | null | undefined,
|
||||
): BackgroundWorkItem[] {
|
||||
if (Array.isArray(value)) return value
|
||||
if (value && Array.isArray(value.data)) return value.data
|
||||
return []
|
||||
}
|
||||
|
||||
export function createBackgroundWorkPoller(options: PollerOptions): {
|
||||
start(): void; stop(): void; refresh(): Promise<void>; dispose(): void
|
||||
} {
|
||||
const intervalMs = options.intervalMs ?? 5000
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
let abort: AbortController | null = null
|
||||
let running = false
|
||||
let disposed = false
|
||||
|
||||
const stop = () => {
|
||||
running = false
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
abort?.abort()
|
||||
abort = null
|
||||
}
|
||||
|
||||
const tick = async () => {
|
||||
if (!running || disposed) return
|
||||
const sessionId = readSessionId(options.sessionId)
|
||||
const controller = new AbortController()
|
||||
abort?.abort()
|
||||
abort = controller
|
||||
try {
|
||||
const raw = await options.list(sessionId, controller.signal)
|
||||
if (!running || controller.signal.aborted) return
|
||||
if (readSessionId(options.sessionId) !== sessionId) {
|
||||
void tick()
|
||||
return
|
||||
}
|
||||
const items = asWorkItems(raw)
|
||||
options.onUpdate(items)
|
||||
if (!running) return
|
||||
if (items.length === 0) {
|
||||
running = false
|
||||
timer = null
|
||||
return
|
||||
}
|
||||
timer = setTimeout(() => { void tick() }, intervalMs)
|
||||
} catch (err) {
|
||||
if (!running || controller.signal.aborted) return
|
||||
options.onError?.(err instanceof Error ? err.message : String(err))
|
||||
if (!running) return
|
||||
timer = setTimeout(() => { void tick() }, intervalMs)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
start() {
|
||||
if (running || disposed) return
|
||||
running = true
|
||||
void tick()
|
||||
},
|
||||
stop,
|
||||
async refresh() {
|
||||
if (disposed) return
|
||||
// Manual refreshes use the same abort/generation boundary as polling.
|
||||
// A newer request, session switch or unmount invalidates their results.
|
||||
stop()
|
||||
running = true
|
||||
await tick()
|
||||
},
|
||||
dispose() {
|
||||
disposed = true
|
||||
stop()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { pairingPageOrigin, preferredDesktopAPIBase } from './browserPairingOrigin.ts'
|
||||
|
||||
test('pairingPageOrigin keeps an http or https page', () => {
|
||||
assert.equal(pairingPageOrigin('https://weknora.example'), 'https://weknora.example')
|
||||
assert.equal(pairingPageOrigin('http://127.0.0.1:8080'), 'http://127.0.0.1:8080')
|
||||
})
|
||||
|
||||
test('pairingPageOrigin uses the desktop API host when the page is the Wails shell', () => {
|
||||
assert.equal(
|
||||
pairingPageOrigin('wails://wails.localhost', 'http://127.0.0.1:53124/api/v1'),
|
||||
'http://127.0.0.1:53124',
|
||||
)
|
||||
})
|
||||
|
||||
test('pairingPageOrigin leaves a non-http page alone when no API base is known', () => {
|
||||
assert.equal(pairingPageOrigin('wails://wails.localhost', ''), 'wails://wails.localhost')
|
||||
})
|
||||
|
||||
test('pairingPageOrigin ignores a non-loopback API base for the Wails shell', () => {
|
||||
assert.equal(
|
||||
pairingPageOrigin('wails://wails.localhost', 'https://evil.example/api/v1'),
|
||||
'wails://wails.localhost',
|
||||
)
|
||||
})
|
||||
|
||||
test('preferredDesktopAPIBase uses the native binding before the page global', () => {
|
||||
assert.equal(
|
||||
preferredDesktopAPIBase('http://127.0.0.1:53124/api/v1', 'https://evil.example/api/v1'),
|
||||
'http://127.0.0.1:53124/api/v1',
|
||||
)
|
||||
assert.equal(preferredDesktopAPIBase('', 'http://127.0.0.1:53124/api/v1'), 'http://127.0.0.1:53124/api/v1')
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
const loopbackHosts = new Set(['localhost', '127.0.0.1', '::1'])
|
||||
|
||||
function isLoopbackHostname(hostname: string): boolean {
|
||||
return loopbackHosts.has(hostname.replace(/^\[|\]$/g, '').toLowerCase())
|
||||
}
|
||||
|
||||
// Native GetAPIBaseURL is the desktop listener. The page global is only a
|
||||
// fallback, because any script in the Lite window can overwrite it.
|
||||
export function preferredDesktopAPIBase(nativeBase?: string | null, injectedBase?: string | null): string {
|
||||
const native = (nativeBase ?? '').trim()
|
||||
if (native) return native
|
||||
return (injectedBase ?? '').trim()
|
||||
}
|
||||
|
||||
// The pairing link is a WebSocket the Chrome extension dials. A normal site
|
||||
// uses the page origin so a proxy port is preserved. The Lite window is
|
||||
// wails://wails.localhost, which cannot become ws/wss, so a loopback desktop
|
||||
// API base supplies the origin instead.
|
||||
export function pairingPageOrigin(pageOrigin: string, apiBase?: string): string {
|
||||
try {
|
||||
const page = new URL(pageOrigin)
|
||||
if (page.protocol === 'http:' || page.protocol === 'https:') {
|
||||
return page.origin
|
||||
}
|
||||
} catch {
|
||||
/* custom schemes and empty origins fall through */
|
||||
}
|
||||
const base = (apiBase || '').trim()
|
||||
if (!base) {
|
||||
return pageOrigin
|
||||
}
|
||||
try {
|
||||
const api = new URL(base)
|
||||
if ((api.protocol !== 'http:' && api.protocol !== 'https:') || !isLoopbackHostname(api.hostname)) {
|
||||
return pageOrigin
|
||||
}
|
||||
return api.origin
|
||||
} catch {
|
||||
return pageOrigin
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { browserToolTitle, browserToolSummary, browserToolContent, browserToolIncomplete, browserActionLabel } from './browserToolDisplay'
|
||||
const t = (key: string) => key
|
||||
|
||||
test('browser steps expose actions and host without URL credentials/query', () => {
|
||||
const title=browserToolTitle(t,{arguments:{method:'navigate',url:'https://user:secret@example.com/cart?token=private'},pending:true})
|
||||
assert.equal(title,'localBrowser.local · localBrowser.openPage · example.com…')
|
||||
assert.equal(browserToolTitle(t,{arguments:{method:'wait_ms'},success:false}),'localBrowser.local · localBrowser.waitPage · localBrowser.actionFailed')
|
||||
})
|
||||
|
||||
test('navigation timeout is incomplete even in historical success records', () => {
|
||||
const event = { arguments:{method:'navigate'}, success:true, output:{reached:'timeout',error_text:'Timed out waiting for load'} }
|
||||
assert.equal(browserToolIncomplete(event), true)
|
||||
assert.equal(browserToolSummary(t,event), 'localBrowser.navigationIncomplete')
|
||||
assert.match(browserToolTitle(t,event), /actionFailed/)
|
||||
assert.equal(browserToolContent(event).error, 'Timed out waiting for load')
|
||||
assert.equal(browserToolIncomplete({...event,arguments:{method:'evaluate'}}), false)
|
||||
})
|
||||
|
||||
test('diagnostic and evaluation results remain visible and bounded', () => {
|
||||
const logs = browserToolContent({arguments:{method:'console'},success:true,output:{entries:[{
|
||||
level:'error',text:'API failed <script>',url:'https://user:secret@example.com/app?token=private',stack_trace:[{function_name:'load',url:'https://example.com/app?secret=1',line:7}],
|
||||
}]}})
|
||||
assert.match(logs.text,/\[error\] API failed <script>/)
|
||||
assert.match(logs.text,/load https:\/\/example.com\/app:7/)
|
||||
assert.doesNotMatch(logs.text,/secret|private/)
|
||||
const network = browserToolContent({arguments:{method:'network'},output:{entries:[{method:'GET',status:500,url:'https://example.com/api?token=private',error_text:'Request failed'}]}})
|
||||
assert.equal(network.text,'GET 500 https://example.com/api Request failed')
|
||||
for (const value of [false,0,null,'',{count:123}]) {
|
||||
assert.equal(browserToolContent({arguments:{method:'evaluate'},output:{ok:true,value}}).text,JSON.stringify(value,null,2))
|
||||
}
|
||||
assert.equal(browserToolContent({arguments:{method:'console'},success:true,output:{entries:[]}}).empty,true)
|
||||
const large = browserToolContent({arguments:{method:'console'},output:{entries:[{text:'x'.repeat(20000)}]}})
|
||||
assert.equal(large.text.length,12000)
|
||||
assert.equal(large.truncated,true)
|
||||
})
|
||||
|
||||
test('screenshot image comes from structured data while text contains metadata only', () => {
|
||||
const content = browserToolContent({arguments:{method:'screenshot'},output:'{"width":1,"height":1,"format":"png"}',tool_data:{image_base64:'aGVsbG8=',format:'png'}})
|
||||
assert.equal(content.image,'data:image/png;base64,aGVsbG8=')
|
||||
assert.equal(content.text,'')
|
||||
assert.equal(browserActionLabel(t,'screenshot'),'localBrowser.captureScreenshot')
|
||||
const error = browserToolContent({success:false,output:{error:{message:'Missing ref'},recovery_hint:'Observe again'}})
|
||||
assert.equal(error.error,'Missing ref')
|
||||
assert.equal(error.recoveryHint,'Observe again')
|
||||
})
|
||||
test('browser failures provide recovery information instead of raw protocol messages',()=>{
|
||||
assert.equal(browserToolSummary(t,{success:false,output:'timeout: session already has an unfinished command'}),'localBrowser.commandBusy')
|
||||
assert.equal(browserToolSummary(t,{success:false,output:'invalid_params: missing field duration_ms'}),'localBrowser.invalidArguments')
|
||||
assert.equal(browserToolSummary(t,{success:false,output:'browser command interrupted or timed out'}),'localBrowser.commandInterrupted')
|
||||
})
|
||||
|
||||
test('all displayed steps identify the local browser and distinguish keys from clicks', () => {
|
||||
assert.equal(browserToolTitle(t, {arguments: JSON.stringify({method:'press',key:'Enter'})}), 'localBrowser.local · localBrowser.pressKey · Enter')
|
||||
assert.equal(browserToolTitle(t, {arguments: {method:'click'}}), 'localBrowser.local · localBrowser.clickPage')
|
||||
assert.equal(browserToolTitle(t, {arguments: {method:'wheel'}}), 'localBrowser.local · localBrowser.scrollPage')
|
||||
assert.equal(browserToolSummary(t, {pending:true}), 'localBrowser.actionPending')
|
||||
assert.equal(browserToolSummary(t, {}), 'localBrowser.actionRecorded')
|
||||
})
|
||||
test('browser results render page content and safe destinations without protocol envelopes', () => {
|
||||
const result = browserToolContent({output:JSON.stringify({text:'Heading\nButton: Search',url:'https://user:password@example.com/page?token=secret#fragment',tab_id:42,ref_count:10})})
|
||||
assert.equal(result.text, 'Heading\nButton: Search')
|
||||
assert.equal(result.address, 'https://example.com/page')
|
||||
assert.equal(JSON.stringify(result).includes('secret'), false)
|
||||
assert.equal(JSON.stringify(result).includes('tab_id'), false)
|
||||
assert.equal(browserToolContent({output:'not JSON'}).text, '')
|
||||
assert.equal(browserToolContent({output:{html:'<script>alert(1)</script>'}}).text, '<script>alert(1)</script>')
|
||||
const bounded = browserToolContent({output:{text:'a'.repeat(13000)}})
|
||||
assert.equal(bounded.text.length, 12000)
|
||||
assert.equal(bounded.truncated, true)
|
||||
})
|
||||
test('tab lists and screenshots have dedicated content instead of object stringification', () => {
|
||||
const result = browserToolContent({output:{tabs:[{title:'News',url:'https://example.com/news?secret=x'},null]}})
|
||||
assert.deepEqual(result.tabs,[{title:'News',address:'https://example.com/news'},{title:'',address:''}])
|
||||
assert.equal(browserToolContent({output:{image_base64:'aGVsbG8=',format:'png'}}).image, 'data:image/png;base64,aGVsbG8=')
|
||||
assert.equal(browserToolContent({output:{image_base64:'PHN2Zz4=',format:'svg+xml'}}).image, '')
|
||||
assert.equal(browserToolContent({output:{image_base64:'https://example.com/track',format:'jpeg'}}).image, '')
|
||||
})
|
||||
|
||||
test('browser argument validation errors distinguish calls never sent to Chrome', () => {
|
||||
const error = "Parameter validation failed: navigate requires url at the top level"
|
||||
for (const event of [{success:false,error}, {success:false,output:error}, {success:false,error:{message:error}}]) {
|
||||
assert.equal(browserToolSummary(t,event),'localBrowser.invalidArguments')
|
||||
}
|
||||
assert.equal(browserToolSummary(t,{success:false,error:"Parameter validation failed: required parameter 'method' is missing"}),'localBrowser.invalidArguments')
|
||||
assert.equal(browserToolSummary(t,{success:true,output:error}),'localBrowser.actionCompleted')
|
||||
})
|
||||
|
||||
test('flat arguments render destinations and help prompts', () => {
|
||||
assert.equal(browserToolContent({arguments:{method:'navigate',url:'https://user:secret@example.com/page?token=private'}}).address,'https://example.com/page')
|
||||
assert.equal(browserToolContent({arguments:{method:'request_help',prompt:'Please sign in'}}).prompt,'Please sign in')
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string
|
||||
export type BrowserToolEvent = { arguments?: unknown; output?: unknown; error?: unknown; pending?: boolean; success?: boolean; tool_data?: unknown }
|
||||
const methodKeys: Record<string, string> = {
|
||||
navigate: 'openPage', navigate_back: 'switchPage', navigate_forward: 'switchPage', reload: 'openPage',
|
||||
screenshot: 'captureScreenshot', stop: 'stop',
|
||||
observe: 'readPage', snapshot: 'readPage', get_html: 'readPage', tab_list: 'listTabs',
|
||||
click: 'clickPage', fill: 'fillPage', press: 'pressKey', wait_ms: 'waitPage', wait_for_navigation: 'waitPage',
|
||||
hover: 'hoverPage', wheel: 'scrollPage', scroll_to: 'scrollPage', focus: 'focusElement', blur: 'blurElement',
|
||||
select: 'selectOption', tab_close: 'closeTab', evaluate: 'runScript', console: 'readConsole', network: 'readNetwork',
|
||||
window_resize: 'resizeWindow', emulate: 'emulateDevice',
|
||||
tab_create: 'openTab', tab_select: 'switchTab', tab_borrow: 'authorizeTab', tab_return: 'returnTab',
|
||||
request_help: 'needHelp',
|
||||
}
|
||||
function record(value: unknown): Record<string, any> {
|
||||
if (typeof value === 'string') {
|
||||
try { value = JSON.parse(value) } catch { return {} }
|
||||
}
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, any> : {}
|
||||
}
|
||||
function text(value: unknown): string { return typeof value === 'string' ? value : '' }
|
||||
// Show the destination without credentials or query/fragment tokens. Never make
|
||||
// page-provided URLs clickable or fetch them while rendering a tool result.
|
||||
export function browserPageAddress(value: unknown): string {
|
||||
try {
|
||||
const url = new URL(text(value))
|
||||
return ['https:', 'http:'].includes(url.protocol) ? `${url.origin}${url.pathname}` : ''
|
||||
} catch { return '' }
|
||||
}
|
||||
function sourceLocation(entry: Record<string, any>): string {
|
||||
const address = browserPageAddress(entry.url)
|
||||
return address ? address + (Number.isInteger(entry.line) ? ':' + entry.line : '') + (Number.isInteger(entry.column) ? ':' + entry.column : '') : ''
|
||||
}
|
||||
const navigationMethods = new Set(['navigate', 'navigate_back', 'navigate_forward', 'reload', 'wait_for_navigation'])
|
||||
export function browserToolIncomplete(event: BrowserToolEvent): boolean {
|
||||
return event.success === false || navigationMethods.has(record(event.arguments).method) && record(event.output).reached === 'timeout'
|
||||
}
|
||||
export function browserActionLabel(t: Translate, method: string): string {
|
||||
return t(`localBrowser.${methodKeys[method] || 'browserAction'}`)
|
||||
}
|
||||
export function browserToolTitle(t: Translate, event: BrowserToolEvent): string {
|
||||
const args = record(event.arguments)
|
||||
const label = browserActionLabel(t, args.method)
|
||||
let target = ''
|
||||
if (args.method === 'navigate' || args.method === 'tab_create') {
|
||||
try { target = new URL(browserPageAddress(args.url)).host } catch { /* No valid destination yet. */ }
|
||||
} else if (args.method === 'press') {
|
||||
target = text(args.key).slice(0, 40)
|
||||
}
|
||||
return `${t('localBrowser.local')} · ${label}${target ? ` · ${target}` : ''}${event.pending ? '…' : browserToolIncomplete(event) ? ` · ${t('localBrowser.actionFailed')}` : ''}`
|
||||
}
|
||||
export function browserToolSummary(t: Translate, event: BrowserToolEvent): string {
|
||||
const failure = event.error || event.output
|
||||
const raw = typeof failure === 'string' ? failure : text(record(failure).message)
|
||||
if (event.pending) return t('localBrowser.actionPending')
|
||||
if (navigationMethods.has(record(event.arguments).method) && record(event.output).reached === 'timeout') return t('localBrowser.navigationIncomplete')
|
||||
if (event.success !== false) return t(event.success === true ? 'localBrowser.actionCompleted' : 'localBrowser.actionRecorded')
|
||||
if (/unfinished command|preview.*busy/i.test(raw)) return t('localBrowser.commandBusy')
|
||||
if (/Parameter validation failed|Invalid browser arguments|invalid_params|duration_ms/i.test(raw)) return t('localBrowser.invalidArguments')
|
||||
if (/paused|interrupted|timed out|timeout/i.test(raw)) return t('localBrowser.commandInterrupted')
|
||||
if (/disconnected|offline|connect BrowserSkill|not paired/i.test(raw)) return t('localBrowser.reconnectHint')
|
||||
return t('localBrowser.actionFailedHint')
|
||||
}
|
||||
export function browserToolContent(event: BrowserToolEvent) {
|
||||
const output = { ...record(event.tool_data), ...record(event.output) }
|
||||
const args = record(event.arguments)
|
||||
let content = text(output.text) || text(output.html)
|
||||
const entries = Array.isArray(output.entries) ? output.entries : []
|
||||
if (args.method === 'console') {
|
||||
content = entries.slice(0, 100).map(record).map(entry => {
|
||||
const location = sourceLocation(entry)
|
||||
const stack = Array.isArray(entry.stack_trace) ? entry.stack_trace.slice(0, 20).map(record).map(frame =>
|
||||
` ${text(frame.function_name)} ${sourceLocation(frame)}`).join('\n') : ''
|
||||
return `[${text(entry.level) || text(entry.kind)}] ${text(entry.text)}${location ? '\n' + location : ''}${stack ? '\n' + stack : ''}`
|
||||
}).join('\n\n')
|
||||
} else if (args.method === 'network') {
|
||||
content = entries.slice(0, 100).map(record).map(entry =>
|
||||
[text(entry.method), typeof entry.status === 'number' ? String(entry.status) : '', browserPageAddress(entry.url), text(entry.status_text), text(entry.error_text)].filter(Boolean).join(' ')
|
||||
).join('\n')
|
||||
} else if (args.method === 'evaluate' && Object.hasOwn(output, 'value')) {
|
||||
content = typeof output.value === 'string' && output.value !== '' ? output.value : JSON.stringify(output.value, null, 2) ?? ''
|
||||
}
|
||||
const resultError = record(output.error)
|
||||
const error = text(output.error_text) || text(resultError.message) || text(resultError.text) || text(event.error) || text(record(event.error).message)
|
||||
const diagnostics = args.method === 'console' || args.method === 'network'
|
||||
const image = text(output.image_base64)
|
||||
const format = text(output.format)
|
||||
return {
|
||||
error: error.slice(0, 4000),
|
||||
recoveryHint: text(output.recovery_hint).slice(0, 4000),
|
||||
empty: diagnostics && entries.length === 0 && !error && !event.pending && !browserToolIncomplete(event),
|
||||
title: text(output.title).slice(0, 300),
|
||||
address: browserPageAddress(output.final_url || output.url || args.url),
|
||||
text: content.slice(0, 12000),
|
||||
truncated: output.truncated === true || content.length > 12000 || diagnostics && (entries.length > 100 || entries.some(entry => record(entry).truncated === true || Array.isArray(record(entry).stack_trace) && record(entry).stack_trace.length > 20)),
|
||||
image: ['png', 'jpeg'].includes(format) && image.length <= 8 * 1024 * 1024 && /^[A-Za-z0-9+/\r\n]+={0,2}$/.test(image)
|
||||
? `data:image/${format};base64,${image}` : '',
|
||||
tabs: Array.isArray(output.tabs) ? output.tabs.map(record).map(tab => ({
|
||||
title: text(tab.title).slice(0, 300), address: browserPageAddress(tab.url),
|
||||
})) : [],
|
||||
prompt: args.method === 'request_help' ? text(args.prompt) : '',
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* Helpers to suppress card corner badges that repeat what a visible section
|
||||
* header (Group) already communicates.
|
||||
*/
|
||||
|
||||
export type ListCardSectionKey =
|
||||
| 'pinned'
|
||||
| 'mine'
|
||||
| 'tenantOthers'
|
||||
| 'builtin'
|
||||
| 'sharedByMe'
|
||||
| 'sharedEditable'
|
||||
| 'sharedReadonly'
|
||||
| 'created'
|
||||
| 'joined'
|
||||
|
||||
export type ResourceOriginVariant = 'mine' | 'tenant' | 'creator' | 'space' | 'shared'
|
||||
|
||||
/** ResourceOriginBadge on KB / Agent cards. */
|
||||
export function shouldShowResourceOriginBadge(opts: {
|
||||
section: ListCardSectionKey | null
|
||||
variant: ResourceOriginVariant
|
||||
creatorName?: string
|
||||
showSectionHeaders?: boolean
|
||||
}): boolean {
|
||||
if (!opts.showSectionHeaders) return true
|
||||
|
||||
const { section, variant, creatorName } = opts
|
||||
const hasCreator = Boolean(creatorName?.trim())
|
||||
|
||||
if (section === 'mine' && variant === 'mine') return false
|
||||
if (section === 'builtin') return false
|
||||
if (section === 'tenantOthers' && variant === 'creator' && !hasCreator) return false
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/** Owner / role tag on organization cards. */
|
||||
export function shouldShowOrgRelationTag(opts: {
|
||||
spaceSelection: 'all' | 'created' | 'joined'
|
||||
isOwner: boolean
|
||||
myRole?: string
|
||||
}): boolean {
|
||||
if (opts.spaceSelection === 'created') return false
|
||||
if (opts.spaceSelection === 'joined' && !opts.myRole) return false
|
||||
if (opts.spaceSelection === 'all' && opts.isOwner) return false
|
||||
if (opts.spaceSelection === 'all' && !opts.isOwner && !opts.myRole) return false
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
export interface CaretCoordinates {
|
||||
top: number;
|
||||
left: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export function getCaretCoordinates(element: HTMLTextAreaElement, position: number): CaretCoordinates {
|
||||
const div = document.createElement('div');
|
||||
const style = window.getComputedStyle(element);
|
||||
|
||||
// Copy styles
|
||||
const properties = [
|
||||
'direction', 'boxSizing', 'width', 'height', 'overflowX', 'overflowY',
|
||||
'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderStyle',
|
||||
'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',
|
||||
'fontStyle', 'fontVariant', 'fontWeight', 'fontStretch', 'fontSize', 'fontSizeAdjust', 'lineHeight', 'fontFamily',
|
||||
'textAlign', 'textTransform', 'textIndent', 'textDecoration', 'letterSpacing', 'wordSpacing',
|
||||
'tabSize', 'MozTabSize'
|
||||
];
|
||||
|
||||
properties.forEach(prop => {
|
||||
// @ts-ignore
|
||||
div.style[prop] = style[prop];
|
||||
});
|
||||
|
||||
div.style.position = 'absolute';
|
||||
div.style.visibility = 'hidden';
|
||||
div.style.whiteSpace = 'pre-wrap';
|
||||
div.style.wordWrap = 'break-word';
|
||||
div.style.top = '0';
|
||||
div.style.left = '0';
|
||||
|
||||
// We append a special character to the end of the text to handle the case where the caret is at the end
|
||||
const textContent = element.value.substring(0, position);
|
||||
div.textContent = textContent;
|
||||
|
||||
const span = document.createElement('span');
|
||||
// Use a zero-width space to simulate the caret position without adding visible width,
|
||||
// but if it's at the end of a line, we might need something else.
|
||||
// Standard trick is using a pipe or similar and measuring it.
|
||||
span.textContent = '|';
|
||||
div.appendChild(span);
|
||||
|
||||
document.body.appendChild(div);
|
||||
|
||||
const spanRect = span.getBoundingClientRect();
|
||||
const divRect = div.getBoundingClientRect();
|
||||
|
||||
const coordinates = {
|
||||
top: span.offsetTop + parseInt(style.borderTopWidth),
|
||||
left: span.offsetLeft + parseInt(style.borderLeftWidth),
|
||||
height: parseInt(style.lineHeight) || spanRect.height
|
||||
};
|
||||
|
||||
document.body.removeChild(div);
|
||||
|
||||
return coordinates;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createI18n, type ComposerTranslation } from 'vue-i18n'
|
||||
import { LOCALE_BUNDLES } from '../i18n/localeKeyAudit'
|
||||
import {
|
||||
docHits,
|
||||
docPages,
|
||||
docReadView,
|
||||
getCatalogToolDisplayType,
|
||||
getCatalogToolTitle,
|
||||
getOperationLabel,
|
||||
operationRows,
|
||||
parseCatalogPayload,
|
||||
runOperationView,
|
||||
safeDocUrl,
|
||||
unavailableOperationRows,
|
||||
} from './catalogToolDisplay'
|
||||
|
||||
const t = ((key: string, params?: Record<string, unknown>) => {
|
||||
if (params && 'name' in params) return `${key} ${params.name}`
|
||||
return key
|
||||
}) as ComposerTranslation
|
||||
|
||||
test('operation titles follow the UI locale for live events, history, and status changes', () => {
|
||||
const { global } = createI18n({ legacy: false, locale: 'zh-CN', messages: LOCALE_BUNDLES })
|
||||
const event = { tool_name: 'run_operation', arguments: { operation: 'model.list' } }
|
||||
assert.equal(getCatalogToolTitle(global.t, event), '执行操作:获取模型列表')
|
||||
assert.equal(getCatalogToolTitle(global.t, {
|
||||
tool_name: 'run_operation', arguments: { operation: 'automation.validate_trigger' },
|
||||
}), '执行操作:校验运行时间')
|
||||
assert.equal(getCatalogToolTitle(global.t, {
|
||||
tool_name: 'run_operation', output: JSON.stringify({ operation: 'agent.list' }),
|
||||
}), '执行操作:获取智能体列表')
|
||||
for (const status of [{ pending: true }, { success: false }]) {
|
||||
assert.match(getCatalogToolTitle(global.t, { ...event, ...status }), /获取模型列表/)
|
||||
}
|
||||
global.locale.value = 'en-US'
|
||||
assert.equal(getCatalogToolTitle(global.t, event), 'Run operation:List models')
|
||||
assert.equal(getOperationLabel(global.t, 'future.unknown'), 'future.unknown')
|
||||
assert.equal(getOperationLabel(global.t, ''), '')
|
||||
assert.equal(event.arguments.operation, 'model.list')
|
||||
})
|
||||
|
||||
test('every backend catalog operation has a label in every UI locale', () => {
|
||||
const spec = JSON.parse(readFileSync(new URL('../../../docs/swagger.json', import.meta.url), 'utf8'))
|
||||
const ids = new Set<string>()
|
||||
for (const path of Object.values(spec.paths)) {
|
||||
for (const op of Object.values(path as Record<string, any>)) {
|
||||
if (op['x-agent']?.id) ids.add(op['x-agent'].id)
|
||||
}
|
||||
}
|
||||
assert.ok(ids.size > 0)
|
||||
for (const [locale, bundle] of Object.entries(LOCALE_BUNDLES)) {
|
||||
const { global } = createI18n({ legacy: false, locale, fallbackLocale: false, messages: { [locale]: bundle } })
|
||||
for (const id of ids) {
|
||||
assert.ok(global.te(`agentStream.operations.names.${id}`), `${locale}: missing ${id}`)
|
||||
assert.notEqual(getOperationLabel(global.t, id), id, `${locale}: untranslated ${id}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('operation and product-doc tools have dedicated display types', () => {
|
||||
assert.equal(getCatalogToolDisplayType('find_operations'), 'find_operations')
|
||||
assert.equal(getCatalogToolDisplayType('run_operation'), 'run_operation')
|
||||
assert.equal(getCatalogToolDisplayType('search_weknora_docs'), 'search_weknora_docs')
|
||||
assert.equal(getCatalogToolDisplayType('read_weknora_doc'), 'read_weknora_doc')
|
||||
assert.equal(getCatalogToolDisplayType('web_search'), undefined)
|
||||
})
|
||||
|
||||
test('catalog payload prefers the output prop over the live event envelope', () => {
|
||||
const output = JSON.stringify({ operations: [{ id: 'knowledge.get', risk: 'read', summary: 'Get one' }] })
|
||||
const data = parseCatalogPayload(output, {
|
||||
tool_name: 'find_operations', success: true, output: '{"operations":[]}', data_change: { operation: 'x' },
|
||||
})
|
||||
assert.equal(operationRows(data)[0]?.id, 'knowledge.get')
|
||||
assert.equal('data_change' in data, false)
|
||||
})
|
||||
|
||||
test('titles name the operation, query, or page instead of the raw tool id', () => {
|
||||
assert.equal(
|
||||
getCatalogToolTitle(t, { tool_name: 'run_operation', arguments: { operation: 'knowledge.get' } }),
|
||||
'agentStream.tools.runOperation:knowledge.get',
|
||||
)
|
||||
assert.equal(
|
||||
getCatalogToolTitle(t, { tool_name: 'search_weknora_docs', arguments: { query: 'Wiki' }, pending: true }),
|
||||
'agentStream.toolStatus.calling agentStream.tools.searchWeKnoraDocs:「Wiki」',
|
||||
)
|
||||
assert.equal(
|
||||
getCatalogToolTitle(t, {
|
||||
tool_name: 'read_weknora_doc', success: false, arguments: { path: '03-features/14-wiki' },
|
||||
}),
|
||||
'agentStream.toolStatus.calledFailed agentStream.tools.readWeKnoraDoc:「03-features/14-wiki」',
|
||||
)
|
||||
assert.equal(getCatalogToolTitle(t, { tool_name: 'web_search' }), '')
|
||||
})
|
||||
|
||||
test('operation rows keep parameters and withheld reasons, and runs keep projected data', () => {
|
||||
const found = parseCatalogPayload(JSON.stringify({
|
||||
operations: [{
|
||||
id: 'knowledge.delete', risk: 'destructive', summary: 'Delete',
|
||||
description: 'Removes a document',
|
||||
params: [{ name: 'knowledge_id', type: 'string', required: true, description: 'Document', enum: ['a'], minimum: 1, maximum: 10 }],
|
||||
}],
|
||||
unavailable: [{ id: 'agent.create', risk: 'write', summary: 'Create', reason: 'read-only' }],
|
||||
hint: 'for the model',
|
||||
}))
|
||||
const row = operationRows(found)[0]
|
||||
assert.equal(row?.expandable, true)
|
||||
assert.equal(row?.params[0]?.required, true)
|
||||
assert.equal(row?.params[0]?.enumText, 'a')
|
||||
assert.deepEqual(row?.params[0]?.range, { min: 1, max: 10 })
|
||||
assert.equal(unavailableOperationRows(found)[0]?.reason, 'read-only')
|
||||
|
||||
const run = runOperationView(parseCatalogPayload(JSON.stringify({
|
||||
operation: 'knowledge.list',
|
||||
result: { data: [{ title: '手册' }], meta: { total: 1 }, truncated: true },
|
||||
})))
|
||||
assert.equal(run.operation, 'knowledge.list')
|
||||
assert.equal(run.truncated, true)
|
||||
assert.deepEqual(run.meta, { total: 1 })
|
||||
})
|
||||
|
||||
test('doc search, read, and links stay structured', () => {
|
||||
const listed = parseCatalogPayload(JSON.stringify({
|
||||
pages: [{ path: '03-features/14-wiki', title: 'Wiki', category: '03-features', url: 'https://docs.example/wiki' }],
|
||||
}))
|
||||
assert.equal(docPages(listed)[0]?.title, 'Wiki')
|
||||
const hits = docHits(parseCatalogPayload(JSON.stringify({
|
||||
results: [{ path: '03-features/14-wiki', anchor: 'setup', section: '安装', url: 'javascript:alert(1)', snippet: '<script>' }],
|
||||
})))
|
||||
assert.equal(hits[0]?.section, '安装')
|
||||
assert.equal(safeDocUrl(hits[0]?.url || ''), '')
|
||||
assert.equal(safeDocUrl('https://docs.example/wiki'), 'https://docs.example/wiki')
|
||||
const read = docReadView(parseCatalogPayload(JSON.stringify({
|
||||
title: 'Wiki', path: '03-features/14-wiki', content: '# 安装\n\n正文', outline: [{ anchor: 'setup', heading: '安装', level: 2 }],
|
||||
truncated: true,
|
||||
})))
|
||||
assert.equal(read.outline[0]?.heading, '安装')
|
||||
assert.equal(read.truncated, true)
|
||||
})
|
||||
@@ -0,0 +1,315 @@
|
||||
import type { ComposerTranslation } from 'vue-i18n'
|
||||
|
||||
export type CatalogDisplayType =
|
||||
| 'find_operations'
|
||||
| 'run_operation'
|
||||
| 'search_weknora_docs'
|
||||
| 'read_weknora_doc'
|
||||
|
||||
const PAYLOAD_KEYS = [
|
||||
'operations', 'unavailable',
|
||||
'operation', 'result',
|
||||
'pages', 'results',
|
||||
'path', 'title', 'category', 'anchor', 'section', 'url', 'content', 'outline',
|
||||
'truncated', 'offset', 'error',
|
||||
] as const
|
||||
|
||||
export type OperationParamRow = {
|
||||
name: string
|
||||
type: string
|
||||
required: boolean
|
||||
description: string
|
||||
enumText: string
|
||||
range: { min: number, max: number } | null
|
||||
}
|
||||
|
||||
export type OperationRow = {
|
||||
id: string
|
||||
risk: string
|
||||
summary: string
|
||||
description: string
|
||||
reason: string
|
||||
expandable: boolean
|
||||
params: OperationParamRow[]
|
||||
}
|
||||
|
||||
export type DocPageRow = {
|
||||
path: string
|
||||
title: string
|
||||
category: string
|
||||
url: string
|
||||
}
|
||||
|
||||
export type DocHitRow = DocPageRow & {
|
||||
anchor: string
|
||||
section: string
|
||||
snippet: string
|
||||
}
|
||||
|
||||
export type DocOutlineRow = {
|
||||
anchor: string
|
||||
heading: string
|
||||
level: number
|
||||
}
|
||||
|
||||
export type DocReadView = {
|
||||
title: string
|
||||
path: string
|
||||
section: string
|
||||
url: string
|
||||
content: string
|
||||
outline: DocOutlineRow[]
|
||||
truncated: boolean
|
||||
error: string
|
||||
}
|
||||
|
||||
export type RunOperationView = {
|
||||
operation: string
|
||||
data: unknown
|
||||
meta: Record<string, unknown>
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
type ToolEventLike = {
|
||||
tool_name?: string
|
||||
arguments?: unknown
|
||||
output?: string
|
||||
tool_data?: unknown
|
||||
pending?: boolean
|
||||
success?: boolean
|
||||
}
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
if (typeof value === 'string') {
|
||||
const parsed = parseJsonObject(value)
|
||||
return parsed || {}
|
||||
}
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: {}
|
||||
}
|
||||
|
||||
function parseJsonObject(value: unknown): Record<string, unknown> | null {
|
||||
if (typeof value !== 'string') return null
|
||||
const text = value.trim()
|
||||
if (!text.startsWith('{')) return null
|
||||
try {
|
||||
const parsed = JSON.parse(text)
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, unknown>
|
||||
}
|
||||
} catch {
|
||||
/* Plain error text, or a truncated historical output. */
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function stringField(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key]
|
||||
return typeof value === 'string' ? value.trim() : ''
|
||||
}
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
||||
}
|
||||
|
||||
export function getCatalogToolDisplayType(toolName?: string): CatalogDisplayType | undefined {
|
||||
if (toolName === 'find_operations' || toolName === 'run_operation' ||
|
||||
toolName === 'search_weknora_docs' || toolName === 'read_weknora_doc') {
|
||||
return toolName
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Reads the JSON these tools put in output. Live SSE also copies the event envelope onto tool_data. */
|
||||
export function parseCatalogPayload(output?: string, data?: unknown): Record<string, unknown> {
|
||||
const extra = record(data)
|
||||
const fromOutput = parseJsonObject(output) || {}
|
||||
const fromEnvelope = parseJsonObject(extra.output) || {}
|
||||
const overlay: Record<string, unknown> = {}
|
||||
for (const key of PAYLOAD_KEYS) {
|
||||
if (key in extra) overlay[key] = extra[key]
|
||||
}
|
||||
return { ...fromEnvelope, ...fromOutput, ...overlay }
|
||||
}
|
||||
|
||||
function paramRows(value: unknown): OperationParamRow[] {
|
||||
if (!Array.isArray(value)) return []
|
||||
return value.flatMap((item) => {
|
||||
const row = record(item)
|
||||
const name = stringField(row, 'name')
|
||||
if (!name) return []
|
||||
const enumText = Array.isArray(row.enum)
|
||||
? row.enum.map((entry) => String(entry ?? '').trim()).filter(Boolean).join(', ')
|
||||
: ''
|
||||
const min = numberOrNull(row.minimum)
|
||||
const max = numberOrNull(row.maximum)
|
||||
return [{
|
||||
name,
|
||||
type: stringField(row, 'type'),
|
||||
required: row.required === true,
|
||||
description: stringField(row, 'description'),
|
||||
enumText,
|
||||
range: min != null && max != null ? { min, max } : null,
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
function operationRow(value: unknown, withReason = false): OperationRow | null {
|
||||
const row = record(value)
|
||||
const id = stringField(row, 'id')
|
||||
if (!id) return null
|
||||
const params = paramRows(row.params)
|
||||
const description = stringField(row, 'description')
|
||||
const reason = withReason ? stringField(row, 'reason') : ''
|
||||
return {
|
||||
id,
|
||||
risk: stringField(row, 'risk'),
|
||||
summary: stringField(row, 'summary'),
|
||||
description,
|
||||
reason,
|
||||
expandable: Boolean(description || params.length),
|
||||
params,
|
||||
}
|
||||
}
|
||||
|
||||
export function operationRows(data: Record<string, unknown>): OperationRow[] {
|
||||
const source = data.operations
|
||||
if (!Array.isArray(source)) return []
|
||||
return source.flatMap((item) => {
|
||||
const row = operationRow(item)
|
||||
return row ? [row] : []
|
||||
})
|
||||
}
|
||||
|
||||
export function unavailableOperationRows(data: Record<string, unknown>): OperationRow[] {
|
||||
const source = data.unavailable
|
||||
if (!Array.isArray(source)) return []
|
||||
return source.flatMap((item) => {
|
||||
const row = operationRow(item, true)
|
||||
return row ? [row] : []
|
||||
})
|
||||
}
|
||||
|
||||
export function runOperationView(data: Record<string, unknown>): RunOperationView {
|
||||
const result = record(data.result)
|
||||
const hasEnvelope = 'data' in result || 'meta' in result || 'truncated' in result
|
||||
return {
|
||||
operation: stringField(data, 'operation'),
|
||||
data: hasEnvelope ? result.data : (data.result === undefined ? undefined : data.result),
|
||||
meta: record(result.meta),
|
||||
truncated: result.truncated === true,
|
||||
}
|
||||
}
|
||||
|
||||
export function isEmptyCatalogValue(value: unknown): boolean {
|
||||
if (value == null) return true
|
||||
if (typeof value === 'string') return value.trim() === ''
|
||||
if (Array.isArray(value)) return value.length === 0
|
||||
if (typeof value === 'object') return Object.keys(value).length === 0
|
||||
return false
|
||||
}
|
||||
|
||||
function docPage(value: unknown): DocPageRow | null {
|
||||
const row = record(value)
|
||||
const path = stringField(row, 'path')
|
||||
const title = stringField(row, 'title') || path
|
||||
if (!title && !path) return null
|
||||
return {
|
||||
path,
|
||||
title,
|
||||
category: stringField(row, 'category'),
|
||||
url: stringField(row, 'url'),
|
||||
}
|
||||
}
|
||||
|
||||
export function docPages(data: Record<string, unknown>): DocPageRow[] {
|
||||
if (!Array.isArray(data.pages)) return []
|
||||
return data.pages.flatMap((item) => {
|
||||
const row = docPage(item)
|
||||
return row ? [row] : []
|
||||
})
|
||||
}
|
||||
|
||||
export function docHits(data: Record<string, unknown>): DocHitRow[] {
|
||||
if (!Array.isArray(data.results)) return []
|
||||
return data.results.flatMap((item) => {
|
||||
const row = record(item)
|
||||
const page = docPage({ ...row, title: stringField(row, 'section') || stringField(row, 'path') })
|
||||
if (!page) return []
|
||||
return [{
|
||||
...page,
|
||||
title: stringField(row, 'section') || page.path,
|
||||
anchor: stringField(row, 'anchor'),
|
||||
section: stringField(row, 'section'),
|
||||
snippet: stringField(row, 'snippet'),
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
export function docReadView(data: Record<string, unknown>): DocReadView {
|
||||
const outline = Array.isArray(data.outline) ? data.outline.flatMap((item) => {
|
||||
const row = record(item)
|
||||
const heading = stringField(row, 'heading')
|
||||
if (!heading) return []
|
||||
const level = numberOrNull(row.level) ?? 2
|
||||
return [{ anchor: stringField(row, 'anchor'), heading, level }]
|
||||
}) : []
|
||||
return {
|
||||
title: stringField(data, 'title'),
|
||||
path: stringField(data, 'path'),
|
||||
section: stringField(data, 'section'),
|
||||
url: stringField(data, 'url'),
|
||||
content: stringField(data, 'content'),
|
||||
outline,
|
||||
truncated: data.truncated === true,
|
||||
error: stringField(data, 'error'),
|
||||
}
|
||||
}
|
||||
|
||||
export function safeDocUrl(value: string): string {
|
||||
const raw = value.trim()
|
||||
if (!/^https?:\/\//i.test(raw)) return ''
|
||||
try {
|
||||
const url = new URL(raw)
|
||||
return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
// Operation IDs belong to the API contract; only their visible labels are translated.
|
||||
export function getOperationLabel(t: ComposerTranslation, operation: string): string {
|
||||
if (!operation) return ''
|
||||
const key = `agentStream.operations.names.${operation}`
|
||||
const label = t(key, {}, { missingWarn: false, fallbackWarn: false })
|
||||
return label === key ? operation : label
|
||||
}
|
||||
|
||||
export function getCatalogToolTitle(t: ComposerTranslation, event: ToolEventLike): string {
|
||||
const type = getCatalogToolDisplayType(event.tool_name)
|
||||
if (!type) return ''
|
||||
const args = record(event.arguments)
|
||||
const data = parseCatalogPayload(event.output, event.tool_data)
|
||||
let title = ''
|
||||
if (type === 'find_operations') {
|
||||
const base = t('agentStream.tools.findOperations')
|
||||
const detail = [stringField(args, 'query'), stringField(args, 'domain')].filter(Boolean).join(' · ')
|
||||
title = detail ? `${base}:「${detail}」` : base
|
||||
} else if (type === 'run_operation') {
|
||||
const base = t('agentStream.tools.runOperation')
|
||||
const operation = stringField(args, 'operation') || stringField(data, 'operation')
|
||||
title = operation ? `${base}:${getOperationLabel(t, operation)}` : base
|
||||
} else if (type === 'search_weknora_docs') {
|
||||
const base = t('agentStream.tools.searchWeKnoraDocs')
|
||||
const detail = stringField(args, 'query') || stringField(args, 'category')
|
||||
title = detail ? `${base}:「${detail}」` : base
|
||||
} else {
|
||||
const base = t('agentStream.tools.readWeKnoraDoc')
|
||||
const detail = stringField(data, 'section') || stringField(data, 'title') || stringField(args, 'path')
|
||||
title = detail ? `${base}:「${detail}」` : base
|
||||
}
|
||||
if (event.pending) return t('agentStream.toolStatus.calling', { name: title })
|
||||
if (event.success === false) return t('agentStream.toolStatus.calledFailed', { name: title })
|
||||
return title
|
||||
}
|
||||
@@ -0,0 +1,667 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
applyStreamingTailFade,
|
||||
closeDanglingStreamingEmphasis,
|
||||
createChatMarkdownRenderer,
|
||||
markStandaloneStrongParagraphs,
|
||||
normalizeFullwidthMarkdownImageParentheses,
|
||||
normalizeLegacyImageContextMarkup,
|
||||
preprocessMathDelimiters,
|
||||
renderChatMarkdown,
|
||||
repairFlankingEmphasis,
|
||||
replaceIncompleteImageWithPlaceholder,
|
||||
stripTrailingStreamingHorizontalRule,
|
||||
stripTrailingStreamingListMarker,
|
||||
} from './chatMarkdownRenderer.ts'
|
||||
import {
|
||||
collapseStandaloneCitationParagraphs,
|
||||
joinCitationTagsToPreviousLine,
|
||||
resolveCitationChunkId,
|
||||
stripIncompleteCitationTag,
|
||||
} from './citationMarkdown.ts'
|
||||
|
||||
const SAMPLE_DOC = 'example-report.docx'
|
||||
const SAMPLE_CHUNK_A = '00000001-0000-4000-8000-000000000001'
|
||||
const SAMPLE_CHUNK_B = '00000002-0000-4000-8000-000000000002'
|
||||
const SAMPLE_CHUNK_C = '00000003-0000-4000-8000-000000000003'
|
||||
const SAMPLE_CHUNK_PRESERVE = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'
|
||||
|
||||
/** Remove the streaming tail-fade wrapper so structural assertions stay focused. */
|
||||
function stripFadeTail(html: string): string {
|
||||
return html.replace(/<span class="stream-fade-tail">([\s\S]*?)<\/span>/g, '$1')
|
||||
}
|
||||
|
||||
test('preprocessMathDelimiters converts escaped math delimiters for marked-katex', () => {
|
||||
assert.equal(
|
||||
preprocessMathDelimiters('inline \\(a+b\\) and block \\[x^2\\]'),
|
||||
'inline $a+b$ and block $$x^2$$',
|
||||
)
|
||||
})
|
||||
|
||||
test('replaceIncompleteImageWithPlaceholder hides an unfinished streaming image', () => {
|
||||
assert.equal(
|
||||
replaceIncompleteImageWithPlaceholder('before ,
|
||||
'before <span class="streaming-image-loading"><span class="streaming-image-loading__skeleton"></span></span>',
|
||||
)
|
||||
})
|
||||
|
||||
test('normalizeFullwidthMarkdownImageParentheses repairs localized image delimiters', () => {
|
||||
const ref = 'resource://yB7V7wE1gls7h9WonCDq5Q'
|
||||
assert.equal(
|
||||
normalizeFullwidthMarkdownImageParentheses(``),
|
||||
``,
|
||||
)
|
||||
assert.equal(
|
||||
normalizeFullwidthMarkdownImageParentheses(``),
|
||||
``,
|
||||
)
|
||||
assert.equal(
|
||||
normalizeFullwidthMarkdownImageParentheses(`普通中文(说明)和 `),
|
||||
`普通中文(说明)和 `,
|
||||
)
|
||||
})
|
||||
|
||||
test('normalizeFullwidthMarkdownImageParentheses preserves literal examples in code', () => {
|
||||
const code = '``\n```md\n\n```'
|
||||
assert.equal(normalizeFullwidthMarkdownImageParentheses(code), code)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown safely renders an image with fullwidth parentheses', () => {
|
||||
const renderer = createChatMarkdownRenderer({
|
||||
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
|
||||
isValidImageUrl: (href) => href.startsWith('resource://'),
|
||||
})
|
||||
const html = renderChatMarkdown('', {
|
||||
renderer,
|
||||
escapeMarkdown: (text) => text,
|
||||
sanitizeHtml: (value) => value,
|
||||
streaming: false,
|
||||
})
|
||||
|
||||
assert.match(html, /<img src="resource:\/\/yB7V7wE1gls7h9WonCDq5Q" alt="">/)
|
||||
assert.doesNotMatch(html, /(|)/)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown skips an image with an empty destination', () => {
|
||||
const renderer = createChatMarkdownRenderer({
|
||||
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
|
||||
invalidImageHtml: () => '<p>invalid</p>',
|
||||
isValidImageUrl: (href) => Boolean(href),
|
||||
})
|
||||
const html = renderChatMarkdown('![根目录示例文件]()', {
|
||||
renderer,
|
||||
escapeMarkdown: (text) => text,
|
||||
sanitizeHtml: (value) => value,
|
||||
streaming: false,
|
||||
})
|
||||
|
||||
assert.doesNotMatch(html, /<img/)
|
||||
assert.doesNotMatch(html, /invalid/)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown hides an unfinished fullwidth-parenthesis image while streaming', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const html = renderChatMarkdown('before  => text,
|
||||
sanitizeHtml: (value) => value,
|
||||
streaming: true,
|
||||
})
|
||||
|
||||
assert.match(html, /streaming-image-loading/)
|
||||
assert.doesNotMatch(html, /resource:\/\/|(/)
|
||||
})
|
||||
|
||||
test('normalizeLegacyImageContextMarkup converts copied image XML to Markdown', () => {
|
||||
const input = [
|
||||
'before',
|
||||
'<image url="resource://AbCdEfGhIjKlMnOpQrStUv">',
|
||||
'<image_caption>目标说话人提取的流程图 [测试]</image_caption>',
|
||||
'<image_ocr>目标说话人提取</image_ocr>',
|
||||
'</image>',
|
||||
'after',
|
||||
].join('\n')
|
||||
|
||||
const output = normalizeLegacyImageContextMarkup(input)
|
||||
assert.ok(
|
||||
output.includes('![目标说话人提取的流程图 \\[测试\\]](resource://AbCdEfGhIjKlMnOpQrStUv)'),
|
||||
)
|
||||
assert.doesNotMatch(output, /<image|image_caption|image_ocr/)
|
||||
assert.match(output, /before[\s\S]*after/)
|
||||
})
|
||||
|
||||
test('normalizeLegacyImageContextMarkup keeps original Markdown when present', () => {
|
||||
const input = [
|
||||
'<images>',
|
||||
'<image url="resource://AbCdEfGhIjKlMnOpQrStUv">',
|
||||
'<image_original></image_original>',
|
||||
'<image_caption>description</image_caption>',
|
||||
'</image>',
|
||||
'</images>',
|
||||
].join('\n')
|
||||
|
||||
assert.equal(
|
||||
normalizeLegacyImageContextMarkup(input).trim(),
|
||||
'',
|
||||
)
|
||||
})
|
||||
|
||||
test('normalizeLegacyImageContextMarkup hides an unfinished XML block while streaming', () => {
|
||||
const prefix = '测试阶段主要流程\n\n'
|
||||
for (const partial of [
|
||||
'<ima',
|
||||
'<image url="resource://AbCdEfGhIjKlMnOpQrStUv">',
|
||||
'<image url="resource://AbCdEfGhIjKlMnOpQrStUv">\n<image_caption>流程图',
|
||||
]) {
|
||||
const output = normalizeLegacyImageContextMarkup(prefix + partial, true)
|
||||
assert.equal(output, prefix + '<span class="streaming-image-loading"><span class="streaming-image-loading__skeleton"></span></span>')
|
||||
assert.doesNotMatch(output, /resource:\/\/|image_caption|<ima/)
|
||||
}
|
||||
})
|
||||
|
||||
test('normalizeLegacyImageContextMarkup preserves literal image XML in code', () => {
|
||||
const code = '```xml\n<image url="resource://example">\n</image>\n```'
|
||||
assert.equal(normalizeLegacyImageContextMarkup(code, true), code)
|
||||
assert.equal(normalizeLegacyImageContextMarkup(code, false), code)
|
||||
assert.equal(normalizeLegacyImageContextMarkup('ordinary <input', true), 'ordinary <input')
|
||||
})
|
||||
|
||||
test('renderChatMarkdown renders leaked legacy image XML through the safe image renderer', () => {
|
||||
const renderer = createChatMarkdownRenderer({
|
||||
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
|
||||
isValidImageUrl: (href) => href.startsWith('resource://'),
|
||||
})
|
||||
const html = renderChatMarkdown(
|
||||
'<image url="resource://AbCdEfGhIjKlMnOpQrStUv"><image_caption>流程图</image_caption></image>',
|
||||
{
|
||||
renderer,
|
||||
escapeMarkdown: (text) => text,
|
||||
sanitizeHtml: (value) => value,
|
||||
streaming: false,
|
||||
},
|
||||
)
|
||||
|
||||
assert.match(html, /<img src="resource:\/\/AbCdEfGhIjKlMnOpQrStUv" alt="流程图">/)
|
||||
assert.doesNotMatch(html, /image_caption|<image/)
|
||||
})
|
||||
|
||||
test('stripIncompleteCitationTag hides only an unfinished streaming citation tail', () => {
|
||||
const prefix = 'Source '
|
||||
const complete = '<kb doc="2.jpg" chunk_id="3c67efd5-f2ff-4e26-9032-9e44e6861178" />'
|
||||
|
||||
for (const partial of ['<', '<k', '<kb', '<kb ', '<kb doc="2.jpg"', '<w', '<we', '<web url="https://example.com"']) {
|
||||
assert.equal(stripIncompleteCitationTag(prefix + partial), prefix)
|
||||
}
|
||||
|
||||
assert.equal(stripIncompleteCitationTag(prefix + complete), prefix + complete)
|
||||
assert.equal(stripIncompleteCitationTag('Value < 5'), 'Value < 5')
|
||||
})
|
||||
|
||||
test('stripTrailingStreamingHorizontalRule hides an ambiguous trailing rule only mid-stream', () => {
|
||||
for (const rule of ['---', '* * *', '___']) {
|
||||
assert.equal(stripTrailingStreamingHorizontalRule(`- item\n\n${rule}`), '- item\n\n')
|
||||
}
|
||||
assert.equal(stripTrailingStreamingHorizontalRule('- item\n\n---\nnext'), '- item\n\n---\nnext')
|
||||
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const options = {
|
||||
renderer,
|
||||
escapeMarkdown: (text: string) => text,
|
||||
sanitizeHtml: (html: string) => html,
|
||||
}
|
||||
const source = '- item\n\n---'
|
||||
assert.doesNotMatch(renderChatMarkdown(source, { ...options, streaming: true }), /<hr>/)
|
||||
assert.match(renderChatMarkdown(source, { ...options, streaming: false }), /<hr>/)
|
||||
})
|
||||
|
||||
test('closeDanglingStreamingEmphasis closes unfinished inline markers without false positives', () => {
|
||||
assert.equal(closeDanglingStreamingEmphasis('**平台地址:example.com'), '**平台地址:example.com**')
|
||||
assert.equal(closeDanglingStreamingEmphasis('前文 *斜体'), '前文 *斜体*')
|
||||
assert.equal(closeDanglingStreamingEmphasis('前文 ~~删除'), '前文 ~~删除~~')
|
||||
assert.equal(closeDanglingStreamingEmphasis('***又粗又斜'), '***又粗又斜***')
|
||||
assert.equal(closeDanglingStreamingEmphasis('运行 `npm run'), '运行 `npm run`')
|
||||
|
||||
// A trailing marker run with no content after it is ambiguous (e.g. the start
|
||||
// of the next `**` in a bold list) and is hidden until content arrives, rather
|
||||
// than rendered as a literal `*`/`**` that flickers a frame later.
|
||||
assert.equal(closeDanglingStreamingEmphasis('4. **朝阳实验**\n5. *'), '4. **朝阳实验**\n5. ')
|
||||
assert.equal(closeDanglingStreamingEmphasis('5. **'), '5. ')
|
||||
assert.equal(closeDanglingStreamingEmphasis('3. **泳燃游泳*'), '3. **泳燃游泳**')
|
||||
|
||||
// No dangling markers / structural markers must be left untouched.
|
||||
assert.equal(closeDanglingStreamingEmphasis('正文 **加粗** 收尾'), '正文 **加粗** 收尾')
|
||||
assert.equal(closeDanglingStreamingEmphasis('* 列表项一'), '* 列表项一')
|
||||
assert.equal(closeDanglingStreamingEmphasis('普通文本没有标记'), '普通文本没有标记')
|
||||
// Markers inside an open fenced code block are literal, not emphasis.
|
||||
assert.equal(
|
||||
closeDanglingStreamingEmphasis('```js\nconst x = **y'),
|
||||
'```js\nconst x = **y',
|
||||
)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown renders an unfinished bold line as bold immediately while streaming', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const options = {
|
||||
renderer,
|
||||
escapeMarkdown: (text: string) => text,
|
||||
sanitizeHtml: (html: string) => html,
|
||||
}
|
||||
const partial = '**平台访问地址:chatbot.weixin.qq.com'
|
||||
// Streaming: optimistically bold so no raw `**` and no late layout jump.
|
||||
assert.match(
|
||||
stripFadeTail(renderChatMarkdown(partial, { ...options, streaming: true })),
|
||||
/<p class="md-strong-title"><strong>平台访问地址:chatbot\.weixin\.qq\.com<\/strong><\/p>/,
|
||||
)
|
||||
// Completed: a genuinely unterminated marker stays literal (we never invent
|
||||
// content for the final, authoritative render).
|
||||
assert.match(
|
||||
renderChatMarkdown(partial, { ...options, streaming: false }),
|
||||
/<p>\*\*平台访问地址/,
|
||||
)
|
||||
})
|
||||
|
||||
test('repairFlankingEmphasis bolds punctuation-adjacent emphasis CommonMark would drop', () => {
|
||||
// Closing delimiter sits between punctuation and a letter -> CommonMark rejects
|
||||
// it; we convert exactly that blocked pattern to explicit HTML.
|
||||
assert.equal(repairFlankingEmphasis('**XBRL(语言)**是一种'), '<strong>XBRL(语言)</strong>是一种')
|
||||
assert.equal(repairFlankingEmphasis('**a)**b'), '<strong>a)</strong>b')
|
||||
assert.equal(repairFlankingEmphasis('~~删除)~~文字'), '<del>删除)</del>文字')
|
||||
assert.equal(repairFlankingEmphasis('*斜体)*文字'), '<em>斜体)</em>文字')
|
||||
|
||||
// Opening delimiter sits between a letter/number and punctuation -> CommonMark
|
||||
// refuses to open emphasis even though the closer is valid; we bold it too.
|
||||
assert.equal(
|
||||
repairFlankingEmphasis('知识库中**《xxx》学程手册**整理'),
|
||||
'知识库中<strong>《xxx》学程手册</strong>整理',
|
||||
)
|
||||
assert.equal(repairFlankingEmphasis('在**《书名》**'), '在<strong>《书名》</strong>')
|
||||
assert.equal(repairFlankingEmphasis('看到~~《删》文字~~后面'), '看到<del>《删》文字</del>后面')
|
||||
|
||||
// Cases marked already handles, literal markers, and code must be untouched.
|
||||
assert.equal(repairFlankingEmphasis('**中文**后面'), '**中文**后面')
|
||||
assert.equal(repairFlankingEmphasis('**中文)** 后面'), '**中文)** 后面')
|
||||
assert.equal(repairFlankingEmphasis('正文 **加粗** 收尾'), '正文 **加粗** 收尾')
|
||||
assert.equal(repairFlankingEmphasis('`**a)**b`'), '`**a)**b`')
|
||||
assert.equal(repairFlankingEmphasis('2 ** 3 ** 4'), '2 ** 3 ** 4')
|
||||
assert.equal(repairFlankingEmphasis('价格 3 * 5 * 7 元'), '价格 3 * 5 * 7 元')
|
||||
// Exponent / glob markers stay literal: the opener is followed by a number or
|
||||
// path content, not an emphasis-opening punctuation run.
|
||||
assert.equal(repairFlankingEmphasis('x**2 + y**2'), 'x**2 + y**2')
|
||||
assert.equal(repairFlankingEmphasis('2**3**4'), '2**3**4')
|
||||
})
|
||||
|
||||
test('renderChatMarkdown bolds punctuation-adjacent emphasis both mid-stream and when complete', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const options = {
|
||||
renderer,
|
||||
escapeMarkdown: (text: string) => text,
|
||||
sanitizeHtml: (html: string) => html,
|
||||
}
|
||||
const text = '**XBRL(语言)**是一种标准'
|
||||
for (const streaming of [true, false]) {
|
||||
assert.match(
|
||||
stripFadeTail(renderChatMarkdown(text, { ...options, streaming })),
|
||||
/<strong>XBRL(语言)<\/strong>是一种标准/,
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('stripTrailingStreamingListMarker hides a content-less trailing list/underline marker', () => {
|
||||
assert.equal(stripTrailingStreamingListMarker('1. **AAAAA**\n - '), '1. **AAAAA**\n')
|
||||
assert.equal(stripTrailingStreamingListMarker('文本\n1. '), '文本\n')
|
||||
assert.equal(stripTrailingStreamingListMarker('标题\n=='), '标题\n')
|
||||
// A lone trailing number is the start of an ordered marker (no `.` yet).
|
||||
assert.equal(stripTrailingStreamingListMarker('文本\n1'), '文本\n')
|
||||
// A marker with content after it is a real list item and must stay.
|
||||
assert.equal(stripTrailingStreamingListMarker('- 项目'), '- 项目')
|
||||
assert.equal(stripTrailingStreamingListMarker('1. 内容'), '1. 内容')
|
||||
// An in-sentence number must not be touched.
|
||||
assert.equal(stripTrailingStreamingListMarker('值是 1'), '值是 1')
|
||||
})
|
||||
|
||||
test('renderChatMarkdown does not flash a setext heading when a nested bullet dash streams in', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const options = {
|
||||
renderer,
|
||||
escapeMarkdown: (text: string) => text,
|
||||
sanitizeHtml: (html: string) => html,
|
||||
streaming: true,
|
||||
}
|
||||
// A must stay a plain bold item through the whole lead-up to B: the bare dash
|
||||
// must not flash <h2>, and the next bullet's `*`/`**` (before its text) must
|
||||
// not flash an empty nested <li> under A.
|
||||
for (const partial of ['1. **AAAAA**\n - ', '1. **AAAAA**\n - *', '1. **AAAAA**\n - **']) {
|
||||
const html = stripFadeTail(renderChatMarkdown(partial, options))
|
||||
assert.doesNotMatch(html, /<h2/)
|
||||
assert.doesNotMatch(html, /<ul>/)
|
||||
assert.match(html, /<ol>\s*<li><strong>AAAAA<\/strong><\/li>\s*<\/ol>/)
|
||||
}
|
||||
})
|
||||
|
||||
test('renderChatMarkdown streams a bold ordered list without literal-marker flicker', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const options = {
|
||||
renderer,
|
||||
escapeMarkdown: (text: string) => text,
|
||||
sanitizeHtml: (html: string) => html,
|
||||
streaming: true,
|
||||
}
|
||||
// Next item's marker has arrived but its content/closing ** has not.
|
||||
const html = stripFadeTail(renderChatMarkdown('1. **速游**\n2. *', options))
|
||||
assert.doesNotMatch(html, /<li>\*+<\/li>/)
|
||||
assert.match(html, /<li><strong>速游<\/strong><\/li>/)
|
||||
})
|
||||
|
||||
test('markStandaloneStrongParagraphs tags only paragraphs that are entirely one bold run', () => {
|
||||
// A model emitting **小节标题** as a pseudo-heading: should be tagged.
|
||||
assert.equal(
|
||||
markStandaloneStrongParagraphs('<p><strong>小节标题:</strong></p>'),
|
||||
'<p class="md-strong-title"><strong>小节标题:</strong></p>',
|
||||
)
|
||||
|
||||
// Mid-stream body paragraph with one completed bold run plus body text must
|
||||
// NOT be tagged (this is the streaming spacing-jump regression).
|
||||
for (const html of [
|
||||
'<p>正文 <strong>加粗部分</strong> 与 **</p>',
|
||||
'<p>正文 <strong>A</strong> 与 <strong>B</strong> 收尾</p>',
|
||||
'<p><strong>加粗</strong> 后续文字</p>',
|
||||
]) {
|
||||
assert.equal(markStandaloneStrongParagraphs(html), html)
|
||||
}
|
||||
|
||||
// A bold list item (loose list wraps content in <p>) is list text, not a
|
||||
// subtitle: it must keep the list's own margins, not gain a 1.25em top margin.
|
||||
assert.equal(
|
||||
markStandaloneStrongParagraphs('<ol><li><p><strong>AAA</strong></p></li></ol>'),
|
||||
'<ol><li><p><strong>AAA</strong></p></li></ol>',
|
||||
)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown does not give a text-heavy paragraph the strong-title margin mid-stream', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const options = {
|
||||
renderer,
|
||||
escapeMarkdown: (text: string) => text,
|
||||
sanitizeHtml: (html: string) => html,
|
||||
streaming: true,
|
||||
}
|
||||
const head = '#### **总结与建议**\n\n'
|
||||
// One bold run closed inside an otherwise text-heavy body paragraph.
|
||||
const midStream = head + '总体来看,体现在 **"补短板"(高端核心部件)** 与 **'
|
||||
const html = renderChatMarkdown(midStream, options)
|
||||
assert.doesNotMatch(html, /<p class="md-strong-title">总体来看/)
|
||||
assert.match(html, /<h4><strong>总结与建议<\/strong><\/h4>/)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown preserves citations, math, and sanitized output through one shared pipeline', () => {
|
||||
const renderer = createChatMarkdownRenderer({
|
||||
imageRenderer: ({ href, title, text }) =>
|
||||
`<img src="${href}" alt="${text}" title="${title || ''}" class="markdown-image">`,
|
||||
isValidImageUrl: (href) => href.startsWith('https://'),
|
||||
})
|
||||
|
||||
const html = renderChatMarkdown(
|
||||
[
|
||||
'See <kb doc="sample-product-guide.pdf" chunk_id="chunk-1" kb_id="kb-1"/>',
|
||||
'',
|
||||
'Formula: \\(E=mc^2\\)',
|
||||
'',
|
||||
'| A | B |',
|
||||
'| --- | --- |',
|
||||
'| 1 | 2 |',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
')',
|
||||
].join('\n'),
|
||||
{
|
||||
renderer,
|
||||
escapeMarkdown: (text) => text,
|
||||
sanitizeHtml: (html) => html.replace(/javascript:alert\(1\)/g, ''),
|
||||
},
|
||||
)
|
||||
|
||||
assert.match(html, /class="citation citation-kb"/)
|
||||
assert.match(html, /data-chunk-id="chunk-1"/)
|
||||
assert.match(html, /katex/)
|
||||
assert.match(html, /<div class="chat-markdown-table"><table>/)
|
||||
assert.match(html, /<img src="https:\/\/example\.com\/a\.png"/)
|
||||
assert.doesNotMatch(html, /javascript:alert/)
|
||||
})
|
||||
|
||||
test('resolveCitationChunkId maps context index to retrieval chunk UUID', () => {
|
||||
const refs = [
|
||||
{ id: 'uuid-chunk-1', knowledge_title: 'Doc A', chunk_type: 'faq' },
|
||||
{ id: 'uuid-chunk-2', knowledge_title: 'FAQ TEST - FAQ', chunk_type: 'faq' },
|
||||
]
|
||||
|
||||
assert.equal(
|
||||
resolveCitationChunkId('2', { doc: 'FAQ TEST - FAQ' }, refs),
|
||||
'uuid-chunk-2',
|
||||
)
|
||||
assert.equal(
|
||||
resolveCitationChunkId('FAQ-2', { doc: 'FAQ TEST - FAQ' }, refs),
|
||||
'uuid-chunk-2',
|
||||
)
|
||||
assert.equal(
|
||||
resolveCitationChunkId('uuid-chunk-1', { doc: 'Doc A' }, refs),
|
||||
'uuid-chunk-1',
|
||||
)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown preserves chunk UUIDs when escapeMarkdown strips UUIDs from prose', () => {
|
||||
const renderer = createChatMarkdownRenderer({
|
||||
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
|
||||
isValidImageUrl: () => true,
|
||||
})
|
||||
const chunkId = SAMPLE_CHUNK_PRESERVE
|
||||
const stripUuids = (text: string) => text.replace(
|
||||
/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
|
||||
'',
|
||||
)
|
||||
|
||||
const html = renderChatMarkdown(
|
||||
`Sample text <kb doc="sample-topic.pdf" chunk_id="${chunkId}" />`,
|
||||
{
|
||||
renderer,
|
||||
escapeMarkdown: stripUuids,
|
||||
sanitizeHtml: (html) => html,
|
||||
},
|
||||
)
|
||||
|
||||
assert.match(html, /class="citation citation-kb"/)
|
||||
assert.match(html, new RegExp(`data-chunk-id="${chunkId}"`))
|
||||
})
|
||||
|
||||
test('renderChatMarkdown resolves indexed chunk_id when knowledge references are provided', () => {
|
||||
const renderer = createChatMarkdownRenderer({
|
||||
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
|
||||
isValidImageUrl: () => true,
|
||||
})
|
||||
|
||||
const html = renderChatMarkdown(
|
||||
'See <kb doc="Sample FAQ" chunk_id="2" />',
|
||||
{
|
||||
renderer,
|
||||
escapeMarkdown: (text) => text,
|
||||
sanitizeHtml: (html) => html,
|
||||
knowledgeReferences: [
|
||||
{ id: 'resolved-chunk-id', knowledge_title: 'Sample FAQ', chunk_type: 'faq' },
|
||||
{ id: 'other-chunk', knowledge_title: 'Other FAQ', chunk_type: 'faq' },
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
assert.match(html, /data-chunk-id="resolved-chunk-id"/)
|
||||
assert.doesNotMatch(html, /data-chunk-id="2"/)
|
||||
})
|
||||
|
||||
test('joinCitationTagsToPreviousLine removes blank lines before citation tags', () => {
|
||||
const input = 'Setup is complete.\n\n<kb doc="faq.pdf" chunk_id="1" />'
|
||||
assert.equal(joinCitationTagsToPreviousLine(input), 'Setup is complete. <kb doc="faq.pdf" chunk_id="1" />')
|
||||
})
|
||||
|
||||
test('joinCitationTagsToPreviousLine inlines consecutive citation tags across single newlines', () => {
|
||||
const tag1 = `<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_A}" />`
|
||||
const tag2 = `<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_B}" />`
|
||||
const tag3 = `<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_C}" />`
|
||||
const input = `${tag1}\n${tag2}\n${tag3}`
|
||||
assert.equal(joinCitationTagsToPreviousLine(input), `${tag1} ${tag2} ${tag3}`)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown inlines consecutive citation tags across newlines', () => {
|
||||
const renderer = createChatMarkdownRenderer({
|
||||
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
|
||||
isValidImageUrl: () => true,
|
||||
})
|
||||
const html = renderChatMarkdown(
|
||||
[
|
||||
`<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_A}" />`,
|
||||
`<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_B}" />`,
|
||||
`<kb doc="${SAMPLE_DOC}" chunk_id="${SAMPLE_CHUNK_C}" />`,
|
||||
].join('\n'),
|
||||
{
|
||||
renderer,
|
||||
escapeMarkdown: (text) => text,
|
||||
sanitizeHtml: (html) => html,
|
||||
},
|
||||
)
|
||||
|
||||
assert.equal((html.match(/citation-kb/g) || []).length, 3)
|
||||
assert.doesNotMatch(html, /<\/p>\s*<p>\s*<span class="citation citation-kb"/)
|
||||
})
|
||||
|
||||
test('joinCitationTagsToPreviousLine appends an indented citation to the preceding list item', () => {
|
||||
const tag = '<kb doc="阅读之星全国青少年阅读风采展示活动.pdf" chunk_id="chunk-1" />'
|
||||
const input = [
|
||||
'#### 5️⃣ 阅读之星培养基地',
|
||||
'- 每个组别冠亚季军及前十强所在的学校,将获得 **"阅读之星培养基地"** 奖牌',
|
||||
'',
|
||||
` ${tag}`,
|
||||
].join('\n')
|
||||
assert.equal(
|
||||
joinCitationTagsToPreviousLine(input),
|
||||
[
|
||||
'#### 5️⃣ 阅读之星培养基地',
|
||||
`- 每个组别冠亚季军及前十强所在的学校,将获得 **"阅读之星培养基地"** 奖牌 ${tag}`,
|
||||
].join('\n'),
|
||||
)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown renders a citation after a list item inline in that item', () => {
|
||||
const renderer = createChatMarkdownRenderer({
|
||||
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
|
||||
isValidImageUrl: () => true,
|
||||
})
|
||||
const tag = '<kb doc="阅读之星全国青少年阅读风采展示活动.pdf" chunk_id="chunk-1" />'
|
||||
const html = renderChatMarkdown(`- 培养基地奖牌\n\n ${tag}`, {
|
||||
renderer,
|
||||
escapeMarkdown: (text) => text,
|
||||
sanitizeHtml: (value) => value,
|
||||
})
|
||||
|
||||
assert.match(html, /<li>培养基地奖牌 <span class="citation citation-kb"/)
|
||||
assert.doesNotMatch(html, /<\/ul>\s*<p>\s*<span class="citation citation-kb"/)
|
||||
})
|
||||
|
||||
test('joinCitationTagsToPreviousLine does not merge citations onto fenced code closing delimiter', () => {
|
||||
const tag = '<kb doc="guide.pdf" chunk_id="1" />'
|
||||
const input = '```bash\nunzip setup.zip\n```\n\n' + tag
|
||||
assert.equal(joinCitationTagsToPreviousLine(input), '```bash\nunzip setup.zip\n```\n\n' + tag)
|
||||
})
|
||||
|
||||
test('joinCitationTagsToPreviousLine does not merge citations onto an unlabeled closing fence on a single newline', () => {
|
||||
const tag = '<kb doc="guide.pdf" chunk_id="1" />'
|
||||
const input = '```\nAPR = principal\n```\n' + tag
|
||||
assert.equal(joinCitationTagsToPreviousLine(input), '```\nAPR = principal\n```\n' + tag)
|
||||
})
|
||||
|
||||
test('applyStreamingTailFade wraps the trailing text run', () => {
|
||||
const out = applyStreamingTailFade('<p>Great, that narrows it down a lot. Two more quick</p>')
|
||||
assert.match(out, /<span class="stream-fade-tail">[^<]*Two more quick<\/span><\/p>$/)
|
||||
})
|
||||
|
||||
test('applyStreamingTailFade skips whitespace-only runs and fades the last list item', () => {
|
||||
const out = applyStreamingTailFade('<ol>\n<li>第一项</li>\n<li>正在生成的第二项</li>\n</ol>')
|
||||
assert.match(out, /<li><span class="stream-fade-tail">正在生成的第二项<\/span><\/li>/)
|
||||
})
|
||||
|
||||
test('applyStreamingTailFade is a no-op for empty content', () => {
|
||||
assert.equal(applyStreamingTailFade(''), '')
|
||||
assert.equal(applyStreamingTailFade('<p></p>'), '<p></p>')
|
||||
})
|
||||
|
||||
test('renderChatMarkdown adds the tail fade only while streaming', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const opts = {
|
||||
renderer,
|
||||
escapeMarkdown: (text: string) => text,
|
||||
sanitizeHtml: (html: string) => html,
|
||||
}
|
||||
const streamed = renderChatMarkdown('正在生成中的回答内容', { ...opts, streaming: true })
|
||||
assert.match(streamed, /stream-fade-tail/)
|
||||
const settled = renderChatMarkdown('正在生成中的回答内容', { ...opts, streaming: false })
|
||||
assert.doesNotMatch(settled, /stream-fade-tail/)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown keeps an unlabeled fenced code block closed when a citation immediately follows', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const tag = '<kb doc="guide.pdf" chunk_id="1" />'
|
||||
const html = renderChatMarkdown(
|
||||
['```', 'APR = principal', '```', tag, '', '### 重要性'].join('\n'),
|
||||
{
|
||||
renderer,
|
||||
escapeMarkdown: (text) => text,
|
||||
sanitizeHtml: (html) => html,
|
||||
},
|
||||
)
|
||||
|
||||
assert.doesNotMatch(html, /### 重要性/)
|
||||
assert.match(html, /<h3>重要性<\/h3>/)
|
||||
assert.equal((html.match(/<pre>/g) || []).length, 1)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown keeps fenced code blocks closed when citations follow', () => {
|
||||
const renderer = createChatMarkdownRenderer({
|
||||
imageRenderer: ({ href, text }) => `<img src="${href}" alt="${text}">`,
|
||||
isValidImageUrl: () => true,
|
||||
})
|
||||
const tag = '<kb doc="guide.pdf" chunk_id="1" />'
|
||||
const html = renderChatMarkdown(
|
||||
['```bash', 'unzip setup.zip', '```', '', tag, '', '#### Next step'].join('\n'),
|
||||
{
|
||||
renderer,
|
||||
escapeMarkdown: (text) => text,
|
||||
sanitizeHtml: (html) => html,
|
||||
},
|
||||
)
|
||||
|
||||
assert.doesNotMatch(html, /#### Next step/)
|
||||
assert.match(html, /<h4>Next step<\/h4>/)
|
||||
assert.equal((html.match(/<pre>/g) || []).length, 1)
|
||||
})
|
||||
|
||||
test('collapseStandaloneCitationParagraphs merges citations across empty paragraphs', () => {
|
||||
const html = '<p>Steps:</p><p></p><p><span class="citation citation-kb" data-chunk-id="x">doc</span></p>'
|
||||
const out = collapseStandaloneCitationParagraphs(html)
|
||||
assert.match(out, /Steps:.*citation-kb/s)
|
||||
assert.doesNotMatch(out, /<p><\/p>/)
|
||||
})
|
||||
|
||||
test('renderChatMarkdown keeps ~~strikethrough~~ while leaving single tildes literal', () => {
|
||||
const renderer = createChatMarkdownRenderer()
|
||||
const options = {
|
||||
renderer,
|
||||
escapeMarkdown: (text: string) => text,
|
||||
sanitizeHtml: (html: string) => html,
|
||||
streaming: false,
|
||||
}
|
||||
const html = renderChatMarkdown('~~a~~ and ~b~ and 2020~2035, 8:00~12:00.', options)
|
||||
assert.equal((html.match(/<del>/g) || []).length, 1)
|
||||
assert.match(html, /<del>a<\/del>/)
|
||||
assert.match(html, /~b~/)
|
||||
assert.match(html, /2020~2035/)
|
||||
assert.match(html, /8:00~12:00/)
|
||||
})
|
||||
@@ -0,0 +1,519 @@
|
||||
import { marked, type Renderer } from 'marked'
|
||||
import markedKatex from 'marked-katex-extension'
|
||||
import type { Tokens } from 'marked'
|
||||
|
||||
import type { CachedMermaidSvgHtml } from './mermaidStreaming.ts'
|
||||
import { ensureLiteralSingleTildeOnGlobalMarked } from './markedLiteralTilde.ts'
|
||||
import { normalizeSandboxArtifactRefs } from './sandboxArtifactRefs.ts'
|
||||
import {
|
||||
collapseStandaloneCitationParagraphs,
|
||||
extractCitationHtmlPlaceholders,
|
||||
joinCitationTagsToPreviousLine,
|
||||
preserveCitationTags,
|
||||
restoreCitationHtmlPlaceholders,
|
||||
restoreCitationTags,
|
||||
stripIncompleteCitationTag,
|
||||
type CitationKnowledgeRef,
|
||||
} from './citationMarkdown.ts'
|
||||
import { renderWeKnoraEntityLinks, type WeKnoraEntityLinkLabels } from './weknoraEntityLinks.ts'
|
||||
|
||||
const STREAMING_IMAGE_PLACEHOLDER =
|
||||
'<span class="streaming-image-loading"><span class="streaming-image-loading__skeleton"></span></span>'
|
||||
|
||||
let markedConfigured = false
|
||||
|
||||
export type ImageRendererArgs = {
|
||||
href: string
|
||||
title: string | null
|
||||
text: string
|
||||
}
|
||||
|
||||
export type ChatMarkdownRendererOptions = {
|
||||
codeRenderer?: Renderer['code']
|
||||
imageRenderer?: (args: ImageRendererArgs) => string
|
||||
invalidImageHtml?: (href: string) => string
|
||||
isValidImageUrl?: (href: string) => boolean
|
||||
}
|
||||
|
||||
export type RenderChatMarkdownOptions = {
|
||||
renderer: Renderer
|
||||
escapeMarkdown: (markdown: string) => string
|
||||
sanitizeHtml: (html: string) => string
|
||||
/** The source is still growing and may end in ambiguous partial Markdown. */
|
||||
streaming?: boolean
|
||||
collapseStandaloneCitations?: boolean
|
||||
knowledgeReferences?: CitationKnowledgeRef[] | null
|
||||
cachedMermaidSvgHtml?: CachedMermaidSvgHtml
|
||||
injectCachedMermaidSvg?: (html: string, cachedSvgHtml?: CachedMermaidSvgHtml) => string
|
||||
prepareMarkdown?: (markdown: string, cachedSvgHtml?: CachedMermaidSvgHtml) => string
|
||||
/** Render `weknora://` URIs as clickable entity links with these labels. */
|
||||
entityLinkLabels?: WeKnoraEntityLinkLabels
|
||||
}
|
||||
|
||||
export function configureMarkedForChatMarkdown(): void {
|
||||
if (markedConfigured) return
|
||||
marked.use({ breaks: true, gfm: true })
|
||||
ensureLiteralSingleTildeOnGlobalMarked()
|
||||
marked.use(markedKatex({ throwOnError: false, nonStandard: true }))
|
||||
markedConfigured = true
|
||||
}
|
||||
|
||||
export function preprocessMathDelimiters(rawText: string): string {
|
||||
if (!rawText || typeof rawText !== 'string') return ''
|
||||
return rawText
|
||||
.replace(/\\\[([\s\S]*?)\\\]/g, '$$$$$1$$$$')
|
||||
.replace(/\\\(([\s\S]*?)\\\)/g, '$$$1$$')
|
||||
}
|
||||
|
||||
export function replaceIncompleteImageWithPlaceholder(content: string): string {
|
||||
if (!content) return ''
|
||||
|
||||
const lastImgStart = content.lastIndexOf('![')
|
||||
if (lastImgStart < 0) return content
|
||||
|
||||
const tail = content.slice(lastImgStart)
|
||||
const hasImageOpen = tail.startsWith('![')
|
||||
const hasBracketClose = tail.includes(']')
|
||||
const hasParenOpen = tail.includes('(')
|
||||
const hasParenClose = tail.includes(')')
|
||||
if (!hasImageOpen) return content
|
||||
|
||||
if (!hasBracketClose || (hasParenOpen && !hasParenClose)) {
|
||||
return content.slice(0, lastImgStart) + STREAMING_IMAGE_PLACEHOLDER
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
const LEGACY_IMAGE_BLOCK_RE = /<image\b([^>]*)>([\s\S]*?)<\/images?>/gi
|
||||
const LEGACY_IMAGES_WRAPPER_RE = /<\/?images\b[^>]*>/gi
|
||||
const LEGACY_IMAGE_ORIGINAL_RE = /<image_original>([\s\S]*?)<\/image_original>/i
|
||||
const LEGACY_IMAGE_CAPTION_RE = /<image_caption>([\s\S]*?)<\/image_caption>/i
|
||||
const LEGACY_IMAGE_OCR_RE = /<image_ocr>([\s\S]*?)<\/image_ocr>/i
|
||||
const COMPLETE_MARKDOWN_CODE_RE = /(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`)/g
|
||||
const IMAGE_URL_SCHEME = '(?:https?|resource|storage|local|minio|s3|cos|tos|oss|obs|ks3)'
|
||||
const FULLWIDTH_IMAGE_OPEN_RE = new RegExp(`(!\\[[^\\]\\n]*\\])((?=${IMAGE_URL_SCHEME}://)`, 'gi')
|
||||
const FULLWIDTH_IMAGE_CLOSE_RE = new RegExp(
|
||||
`(!\\[[^\\]\\n]*\\]\\(${IMAGE_URL_SCHEME}://[^)\\n]*?))`,
|
||||
'gi',
|
||||
)
|
||||
|
||||
/**
|
||||
* Repair image Markdown when a model localizes its destination parentheses:
|
||||
* `` -> ``.
|
||||
*
|
||||
* The rewrite is limited to supported image URL schemes and skips code, so
|
||||
* ordinary Chinese punctuation and literal Markdown examples stay unchanged.
|
||||
* Normalizing an opening parenthesis before the closing one streams in also
|
||||
* lets the existing incomplete-image skeleton suppress the unstable tail.
|
||||
*/
|
||||
export function normalizeFullwidthMarkdownImageParentheses(content: string): string {
|
||||
if (!content || (!content.includes('(') && !content.includes(')'))) return content
|
||||
|
||||
const parts = content.split(COMPLETE_MARKDOWN_CODE_RE)
|
||||
for (let i = 0; i < parts.length; i += 2) {
|
||||
parts[i] = parts[i]
|
||||
.replace(FULLWIDTH_IMAGE_OPEN_RE, '$1(')
|
||||
.replace(FULLWIDTH_IMAGE_CLOSE_RE, '$1)')
|
||||
}
|
||||
return parts.join('')
|
||||
}
|
||||
|
||||
function legacyImageField(body: string, pattern: RegExp): string {
|
||||
const value = body.match(pattern)?.[1] || ''
|
||||
return value.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
function escapeMarkdownImageAlt(value: string): string {
|
||||
return value.replace(/\\/g, '\\\\').replace(/\[/g, '\\[').replace(/\]/g, '\\]')
|
||||
}
|
||||
|
||||
function legacyImageBlockToMarkdown(attributes: string, body: string): string {
|
||||
const original = body.match(LEGACY_IMAGE_ORIGINAL_RE)?.[1]?.trim()
|
||||
if (original) return original
|
||||
|
||||
const urlMatch = attributes.match(/\burl\s*=\s*(["'])(.*?)\1/i)
|
||||
const url = urlMatch?.[2]?.trim() || ''
|
||||
const caption = legacyImageField(body, LEGACY_IMAGE_CAPTION_RE)
|
||||
const ocr = legacyImageField(body, LEGACY_IMAGE_OCR_RE)
|
||||
if (!url) return caption || ocr
|
||||
|
||||
const alt = escapeMarkdownImageAlt(caption || ocr || 'image')
|
||||
return ``
|
||||
}
|
||||
|
||||
function normalizeLegacyImageSegment(content: string): string {
|
||||
return content
|
||||
.replace(
|
||||
LEGACY_IMAGE_BLOCK_RE,
|
||||
(_match, attributes: string, body: string) => legacyImageBlockToMarkdown(attributes, body),
|
||||
)
|
||||
.replace(LEGACY_IMAGES_WRAPPER_RE, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the legacy image-context protocol if a model copies it into an
|
||||
* answer. New chat context is Markdown-native, but persisted conversations and
|
||||
* older deployments can still contain `<image url="…">` blocks.
|
||||
*
|
||||
* Complete blocks become ordinary Markdown images and therefore pass through
|
||||
* the same URL validation/sanitization as model-authored images. While a block
|
||||
* is still streaming, its unfinished tail is replaced by the existing image
|
||||
* skeleton so internal tags, captions, and OCR never flash as prose.
|
||||
*/
|
||||
export function normalizeLegacyImageContextMarkup(content: string, streaming = false): string {
|
||||
if (!content) return content
|
||||
const hasLegacyImageTag = /<\/?images?\b/i.test(content)
|
||||
const partialTagPattern = /(^|\n)[ \t]*<i(?:m(?:a(?:g(?:e(?:[ \t][^>\n]*)?)?)?)?)?$/i
|
||||
const hasPartialStreamingTag = streaming && partialTagPattern.test(content)
|
||||
if (!hasLegacyImageTag && !hasPartialStreamingTag) return content
|
||||
|
||||
const parts = content.split(COMPLETE_MARKDOWN_CODE_RE)
|
||||
for (let i = 0; i < parts.length; i += 2) {
|
||||
parts[i] = normalizeLegacyImageSegment(parts[i])
|
||||
}
|
||||
if (streaming) {
|
||||
// The split always leaves normal Markdown in the final even-indexed part,
|
||||
// so code examples containing literal <image> tags stay untouched.
|
||||
const tailIndex = parts.length - 1
|
||||
let tail = parts[tailIndex]
|
||||
const openingMatches = Array.from(tail.matchAll(/<image(?:\s|>)/gi))
|
||||
const lastOpening = openingMatches[openingMatches.length - 1]
|
||||
if (lastOpening?.index !== undefined) {
|
||||
tail = tail.slice(0, lastOpening.index) + STREAMING_IMAGE_PLACEHOLDER
|
||||
} else {
|
||||
// Also hide the few frames before the opening tag name itself is complete.
|
||||
tail = tail.replace(partialTagPattern, `$1${STREAMING_IMAGE_PLACEHOLDER}`)
|
||||
}
|
||||
parts[tailIndex] = tail
|
||||
}
|
||||
return parts.join('')
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide a trailing Markdown horizontal-rule candidate while content is streaming.
|
||||
*
|
||||
* A model often emits `---` as the beginning of a table delimiter or another
|
||||
* structure. At that exact typewriter frame, marked renders it as `<hr>`, then
|
||||
* removes it when more characters arrive. A real completed horizontal rule is
|
||||
* still rendered because this guard is enabled only for an active stream.
|
||||
*/
|
||||
export function stripTrailingStreamingHorizontalRule(content: string): string {
|
||||
if (!content) return content
|
||||
return content.replace(
|
||||
/(^|\n)[ \t]{0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/,
|
||||
'$1',
|
||||
)
|
||||
}
|
||||
|
||||
function maskMatches(text: string, regex: RegExp): string {
|
||||
return text.replace(regex, (match) => match.replace(/[^\n]/g, '\u0000'))
|
||||
}
|
||||
|
||||
function isOdd(text: string, marker: RegExp): boolean {
|
||||
const matches = text.match(marker)
|
||||
return matches ? matches.length % 2 === 1 : false
|
||||
}
|
||||
|
||||
/**
|
||||
* Stabilize dangling inline markers while content is streaming.
|
||||
*
|
||||
* Two distinct mid-stream artifacts are smoothed out:
|
||||
*
|
||||
* - A marker run with **nothing after it yet** (`… 实验**\n5. *`, or a bare
|
||||
* trailing `**`) is ambiguous — it might open bold, italic, or be the start
|
||||
* of the next `**`. Rendering it shows literal `*`/`~` that vanish a frame
|
||||
* later, so it is hidden until real content follows (like the citation/image
|
||||
* guards).
|
||||
* - A marker run **with content after it** but no closer (`**平台地址:…`) is a
|
||||
* genuinely opened emphasis; its closer is appended so marked renders it as
|
||||
* emphasis from the first frame instead of showing raw `**` and then snapping
|
||||
* to bold (and, for a standalone bold line, also gaining the subtitle
|
||||
* margin) — the jump reported on streamed bold lists/headings.
|
||||
*
|
||||
* Inline/fenced code and leading list bullets are masked so their literal
|
||||
* `*`/`` ` `` are never treated as emphasis, and an open fenced block is left
|
||||
* untouched.
|
||||
*/
|
||||
export function closeDanglingStreamingEmphasis(text: string): string {
|
||||
if (!text || !/[*~`]/.test(text)) return text
|
||||
|
||||
// Mask code so markers inside it are never counted; \u0000 keeps offsets.
|
||||
let masked = maskMatches(text, /```[\s\S]*?```/g)
|
||||
if (isOdd(masked, /```/g)) {
|
||||
const open = masked.lastIndexOf('```')
|
||||
masked = masked.slice(0, open) + masked.slice(open).replace(/[^\n]/g, '\u0000')
|
||||
}
|
||||
masked = maskMatches(masked, /`[^`\n]*`/g)
|
||||
let appendInlineCode = false
|
||||
if (isOdd(masked, /`/g)) {
|
||||
appendInlineCode = true
|
||||
const open = masked.lastIndexOf('`')
|
||||
masked = masked.slice(0, open) + masked.slice(open).replace(/[^\n]/g, '\u0000')
|
||||
}
|
||||
|
||||
// Drop a trailing emphasis-marker run with no content after it: ambiguous and
|
||||
// not yet renderable. Anchored to the current line so earlier text is intact.
|
||||
let working = text
|
||||
if (!appendInlineCode) {
|
||||
const trailing = masked.match(/[*~]+[ \t]*$/)
|
||||
if (trailing) {
|
||||
working = text.slice(0, text.length - trailing[0].length)
|
||||
masked = masked.slice(0, masked.length - trailing[0].length)
|
||||
}
|
||||
}
|
||||
|
||||
// Leading list/bullet markers are structure, not emphasis.
|
||||
masked = masked.replace(/^(\s*)([*+-])(\s)/gm, (_m, p1, _p2, p3) => `${p1}\u0000${p3}`)
|
||||
|
||||
const needStrike = isOdd(masked, /~~/g)
|
||||
const withoutBold = maskMatches(masked, /\*\*/g)
|
||||
const needBold = isOdd(masked, /\*\*/g)
|
||||
const needItalic = isOdd(withoutBold, /\*/g)
|
||||
|
||||
let closers = ''
|
||||
if (appendInlineCode) closers += '`'
|
||||
if (needItalic) closers += '*'
|
||||
if (needBold) closers += '**'
|
||||
if (needStrike) closers += '~~'
|
||||
|
||||
if (!closers) return working
|
||||
|
||||
// A closing emphasis delimiter must not be preceded by whitespace (CommonMark
|
||||
// flanking rule), so insert the closers before any trailing whitespace. Bold
|
||||
// content with internal spaces (`**XBRL Reporting `) otherwise renders literal
|
||||
// (non-bold) on every frame that pauses on a space, flickering bold on/off.
|
||||
const trailingWs = working.match(/\s+$/)
|
||||
if (!trailingWs) return working + closers
|
||||
const cut = working.length - trailingWs[0].length
|
||||
return working.slice(0, cut) + closers + working.slice(cut)
|
||||
}
|
||||
|
||||
const FLANKING_BOLD = /(?<!\*)\*\*(?=\S)([^*\n]*?\p{P})\*\*(?=[\p{L}\p{N}])/gu
|
||||
const FLANKING_STRIKE = /(?<!~)~~(?=\S)([^~\n]*?\p{P})~~(?=[\p{L}\p{N}])/gu
|
||||
const FLANKING_ITALIC = /(?<![*\p{L}\p{N}])\*(?=\S)([^*\n]*?\p{P})\*(?=[\p{L}\p{N}])/gu
|
||||
|
||||
// Opening-delimiter variant of the rule above. CommonMark also refuses to *open*
|
||||
// emphasis when the run is preceded by a letter/number and immediately followed
|
||||
// by punctuation, so `知识库中**《手册》**整理` stays literal even though the
|
||||
// closing `**` is fine. The `(?=\p{P})` guard keeps exponent/glob/math markers
|
||||
// like `x**2`, `2**3**4`, and `**/*.js` untouched (those are followed by a
|
||||
// number or slash-as-content, not an emphasis-opening punctuation run).
|
||||
const FLANKING_BOLD_OPEN = /(?<=[\p{L}\p{N}])\*\*(?=\p{P})([^*\n]+?)\*\*/gu
|
||||
const FLANKING_STRIKE_OPEN = /(?<=[\p{L}\p{N}])~~(?=\p{P})([^~\n]+?)~~/gu
|
||||
|
||||
function repairFlankingEmphasisSegment(segment: string): string {
|
||||
return segment
|
||||
.replace(FLANKING_BOLD, '<strong>$1</strong>')
|
||||
.replace(FLANKING_BOLD_OPEN, '<strong>$1</strong>')
|
||||
.replace(FLANKING_STRIKE, '<del>$1</del>')
|
||||
.replace(FLANKING_STRIKE_OPEN, '<del>$1</del>')
|
||||
.replace(FLANKING_ITALIC, '<em>$1</em>')
|
||||
}
|
||||
|
||||
/**
|
||||
* Render emphasis the model clearly intended but CommonMark refuses to parse.
|
||||
*
|
||||
* CommonMark's flanking rule rejects a closing `**`/`*`/`~~` that is preceded by
|
||||
* punctuation and immediately followed by a letter/number, so a very common
|
||||
* model pattern like `**XBRL(…语言)**是一种` (and even ASCII `**a)**b`) renders
|
||||
* as literal asterisks — both mid-stream and when complete. The mirror case is
|
||||
* an *opening* `**`/`~~` preceded by a letter/number and immediately followed by
|
||||
* punctuation (`知识库中**《手册》**整理`), which CommonMark also refuses to open.
|
||||
* We convert just those blocked patterns into explicit HTML so they bold
|
||||
* reliably. Code spans/fences are skipped so their literal markers are untouched.
|
||||
*/
|
||||
export function repairFlankingEmphasis(text: string): string {
|
||||
if (!text || !/[*~]/.test(text)) return text
|
||||
const parts = text.split(/(```[\s\S]*?```|`[^`\n]*`)/g)
|
||||
for (let i = 0; i < parts.length; i += 2) {
|
||||
parts[i] = repairFlankingEmphasisSegment(parts[i])
|
||||
}
|
||||
return parts.join('')
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide a trailing list/underline marker that has no content after it yet.
|
||||
*
|
||||
* While streaming, the moment a nested bullet's dash arrives before its text
|
||||
* (`1. **AAAAA**\n - `), marked reads the lone `-` as a setext underline and
|
||||
* renders the previous line as a giant `<h2>`, which collapses back to bold text
|
||||
* once the bullet content streams in — a large layout swing. An ordered marker
|
||||
* with no content (`text\n1. `) and bare setext underlines (`==`/`--`) cause the
|
||||
* same fl/flicker. Dropping the dangling marker line defers it by a token until
|
||||
* it is unambiguous; a real list/heading still renders once content follows.
|
||||
*
|
||||
* A trailing line that is only a number (`…\n1`) is the start of an ordered
|
||||
* marker before its `.`/`)` arrives; rendering it shows a bare unstyled "1" that
|
||||
* disappears a frame later, so it is hidden too. Because the line must be only
|
||||
* the number, in-sentence numbers (`值是 1`) are unaffected.
|
||||
*/
|
||||
export function stripTrailingStreamingListMarker(text: string): string {
|
||||
if (!text) return text
|
||||
return text.replace(/(^|\n)[ \t]*(?:[-*+]|[-=]{2,}|\d{1,9}[.)]?)[ \t]*$/, '$1')
|
||||
}
|
||||
|
||||
const TAIL_TEXT_RE = />([^<>]+)</g
|
||||
|
||||
/**
|
||||
* Soften the most-recently streamed characters with a trailing fade.
|
||||
*
|
||||
* While the answer streams, the newest tail text is wrapped in a
|
||||
* `stream-fade-tail` span so CSS can fade its trailing edge (the newest words
|
||||
* are faint and settle to full color as more text arrives — the "tail reveal"
|
||||
* look). Runs on the final HTML so the span is never touched by the markdown
|
||||
* parser or sanitizer, and only the innermost last text run is wrapped.
|
||||
*/
|
||||
export function applyStreamingTailFade(html: string, tailLength = 24): string {
|
||||
if (!html) return html
|
||||
|
||||
// Track the last text run that actually has visible characters. Whitespace-only
|
||||
// runs (e.g. the `\n` marked emits between `</li>` and `</ol>`) are skipped so
|
||||
// they do not win the "last run" and suppress the fade.
|
||||
let lastMatch: RegExpExecArray | null = null
|
||||
let match: RegExpExecArray | null
|
||||
TAIL_TEXT_RE.lastIndex = 0
|
||||
while ((match = TAIL_TEXT_RE.exec(html)) !== null) {
|
||||
if (match[1].trim()) lastMatch = match
|
||||
}
|
||||
if (!lastMatch) return html
|
||||
|
||||
const text = lastMatch[1]
|
||||
|
||||
const textStart = lastMatch.index + 1
|
||||
const textEnd = textStart + text.length
|
||||
const chars = Array.from(text)
|
||||
const tailChars = chars.slice(Math.max(0, chars.length - tailLength))
|
||||
const tail = tailChars.join('')
|
||||
// Fade only the trailing run, keeping any leading whitespace outside the span.
|
||||
const tailTrimmed = tail.replace(/^\s+/, '')
|
||||
if (!tailTrimmed) return html
|
||||
const head = text.slice(0, text.length - tailTrimmed.length)
|
||||
const wrapped = `${head}<span class="stream-fade-tail">${tailTrimmed}</span>`
|
||||
return html.slice(0, textStart) + wrapped + html.slice(textEnd)
|
||||
}
|
||||
|
||||
export function createChatMarkdownRenderer(options: ChatMarkdownRendererOptions = {}): Renderer {
|
||||
const renderer = new marked.Renderer()
|
||||
|
||||
if (options.imageRenderer) {
|
||||
renderer.image = ({ href, title, text }: Tokens.Image) => {
|
||||
const imageHref = href || ''
|
||||
if (!imageHref.trim()) return ''
|
||||
if (options.isValidImageUrl && !options.isValidImageUrl(imageHref)) {
|
||||
return options.invalidImageHtml?.(imageHref) ?? ''
|
||||
}
|
||||
return options.imageRenderer?.({
|
||||
href: imageHref,
|
||||
title: title || null,
|
||||
text: text || '',
|
||||
}) ?? ''
|
||||
}
|
||||
}
|
||||
|
||||
if (options.codeRenderer) {
|
||||
renderer.code = options.codeRenderer
|
||||
}
|
||||
|
||||
return renderer
|
||||
}
|
||||
|
||||
export function wrapChatMarkdownTables(html: string): string {
|
||||
if (!html || !html.includes('<table')) return html
|
||||
return html.replace(
|
||||
/<table\b[\s\S]*?<\/table>/gi,
|
||||
(tableHtml) => `<div class="chat-markdown-table">${tableHtml}</div>`,
|
||||
)
|
||||
}
|
||||
|
||||
const STANDALONE_STRONG_PARAGRAPH_RE =
|
||||
/<p>\s*<strong>((?:(?!<\/strong>)[\s\S])*?)<\/strong>\s*<\/p>/g
|
||||
|
||||
/**
|
||||
* Tag paragraphs whose entire content is a single bold run (e.g. a model that
|
||||
* emits `**小节标题:**` instead of a real heading) so they can be styled as a
|
||||
* subtitle deterministically.
|
||||
*
|
||||
* This replaces the CSS `p:has(> strong:only-child)` heuristic, which was
|
||||
* streaming-unstable: CSS `:only-child` ignores text nodes, so a normal
|
||||
* paragraph that momentarily contained exactly one completed `**bold**` run
|
||||
* (surrounded by plenty of body text) matched it and gained a large top margin,
|
||||
* then lost it once a second bold run finished — a visible spacing jump
|
||||
* mid-stream. Matching the whole paragraph content here only fires when the
|
||||
* bold run truly is the entire paragraph.
|
||||
*/
|
||||
export function markStandaloneStrongParagraphs(html: string): string {
|
||||
if (!html || !html.includes('<strong>')) return html
|
||||
return html.replace(
|
||||
STANDALONE_STRONG_PARAGRAPH_RE,
|
||||
(match: string, inner: string, offset: number, full: string) => {
|
||||
// A `<p>` that is a list item's content is list text, not a standalone
|
||||
// subtitle. Marking it adds a large margin that shifts sibling items when
|
||||
// a streamed list flips from tight to loose, so leave list paragraphs to
|
||||
// the list's own (zero) margins.
|
||||
if (/<li>\s*$/.test(full.slice(0, offset))) return match
|
||||
return `<p class="md-strong-title"><strong>${inner}</strong></p>`
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
export function renderChatMarkdown(rawMarkdown: unknown, options: RenderChatMarkdownOptions): string {
|
||||
const rawText = typeof rawMarkdown === 'string' ? rawMarkdown : String(rawMarkdown || '')
|
||||
if (!rawText.trim()) return ''
|
||||
|
||||
configureMarkedForChatMarkdown()
|
||||
|
||||
const streamingSafeText = options.streaming
|
||||
? stripTrailingStreamingListMarker(stripTrailingStreamingHorizontalRule(rawText))
|
||||
: rawText
|
||||
const imageContextSafeText = normalizeLegacyImageContextMarkup(
|
||||
streamingSafeText,
|
||||
Boolean(options.streaming),
|
||||
)
|
||||
const citationSafeText = stripIncompleteCitationTag(imageContextSafeText)
|
||||
const { text: tagSafe, tags } = preserveCitationTags(citationSafeText)
|
||||
const normalizedImageMarkdown = normalizeFullwidthMarkdownImageParentheses(tagSafe)
|
||||
// Skill-generated file names routinely contain spaces and parentheses, which
|
||||
// marked would split the destination on. Collapse each reference into a
|
||||
// single token before parsing.
|
||||
const artifactSafe = normalizeSandboxArtifactRefs(normalizedImageMarkdown)
|
||||
const imageSafe = replaceIncompleteImageWithPlaceholder(artifactSafe)
|
||||
const mathSafe = preprocessMathDelimiters(imageSafe)
|
||||
const restoredTags = restoreCitationTags(mathSafe, tags)
|
||||
const inlineTags = joinCitationTagsToPreviousLine(restoredTags)
|
||||
// Run the list-marker guard again after emphasis balancing: closing/hiding a
|
||||
// dangling `*`/`**` (the first chars of the next bullet's bold) can re-expose a
|
||||
// bare ` - `, which would otherwise flash an empty nested item under the
|
||||
// previous line right as the next item starts streaming.
|
||||
const balancedInline = options.streaming
|
||||
? stripTrailingStreamingListMarker(closeDanglingStreamingEmphasis(inlineTags))
|
||||
: inlineTags
|
||||
const preparedMarkdown = options.prepareMarkdown
|
||||
? options.prepareMarkdown(balancedInline, options.cachedMermaidSvgHtml)
|
||||
: balancedInline
|
||||
const flankingSafeMarkdown = repairFlankingEmphasis(preparedMarkdown)
|
||||
// Convert <kb>/<web>/wiki tags to HTML placeholders before escapeMarkdown so
|
||||
// agent sanitizers (e.g. UUID stripping) cannot damage chunk_id attributes.
|
||||
const { content: markdownWithPlaceholders, htmlSnippets } =
|
||||
extractCitationHtmlPlaceholders(flankingSafeMarkdown, options.knowledgeReferences)
|
||||
const escapedMarkdown = options.escapeMarkdown(markdownWithPlaceholders)
|
||||
const html = marked.parse(markdownWithPlaceholders, {
|
||||
renderer: options.renderer,
|
||||
breaks: true,
|
||||
async: false,
|
||||
}) as string
|
||||
const restoredHtml = restoreCitationHtmlPlaceholders(html, htmlSnippets)
|
||||
const citationHtml = options.collapseStandaloneCitations === false
|
||||
? restoredHtml
|
||||
: collapseStandaloneCitationParagraphs(restoredHtml)
|
||||
const entityHtml = options.entityLinkLabels
|
||||
? renderWeKnoraEntityLinks(citationHtml, options.entityLinkLabels)
|
||||
: citationHtml
|
||||
const tableWrappedHtml = wrapChatMarkdownTables(entityHtml)
|
||||
const strongTitleHtml = markStandaloneStrongParagraphs(tableWrappedHtml)
|
||||
const sanitized = options.sanitizeHtml(strongTitleHtml)
|
||||
const withMermaid = options.injectCachedMermaidSvg
|
||||
? options.injectCachedMermaidSvg(sanitized, options.cachedMermaidSvgHtml)
|
||||
: sanitized
|
||||
return options.streaming ? applyStreamingTailFade(withMermaid) : withMermaid
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import i18n from '@/i18n';
|
||||
import { buildMermaidBlockHtml, buildMermaidLoadingHtml } from '@/utils/markdownEnhancements';
|
||||
import { buildManualDraft, deriveManualTitle } from './manualKnowledgeDraft';
|
||||
import {
|
||||
injectCachedMermaidSvg as injectCachedMermaidSvgHtml,
|
||||
maskMermaidBlocksForStreaming as maskMermaidBlocks,
|
||||
prepareStreamingMermaidMarkdown as prepareStreamingMermaid,
|
||||
replaceIncompleteMermaidWithPlaceholder as replaceIncompleteMermaid,
|
||||
type CachedMermaidSvgHtml,
|
||||
} from './mermaidStreaming';
|
||||
|
||||
export type { CachedMermaidSvgHtml };
|
||||
export {
|
||||
extractFirstMermaidCode,
|
||||
extractMermaidCodes,
|
||||
hasCompleteMermaidBlock,
|
||||
normalizeCachedMermaidSvgs,
|
||||
} from './mermaidStreaming';
|
||||
|
||||
const STREAMING_IMAGE_PLACEHOLDER = '<span class="streaming-image-loading"><span class="streaming-image-loading__skeleton"></span></span>';
|
||||
const STREAMING_MERMAID_PLACEHOLDER = buildMermaidLoadingHtml();
|
||||
|
||||
export const replaceIncompleteImageWithPlaceholder = (content: string): string => {
|
||||
if (!content) return '';
|
||||
|
||||
const lastImgStart = content.lastIndexOf('![');
|
||||
if (lastImgStart < 0) return content;
|
||||
|
||||
const tail = content.slice(lastImgStart);
|
||||
const hasImageOpen = tail.startsWith('![');
|
||||
const hasBracketClose = tail.includes(']');
|
||||
const hasParenOpen = tail.includes('(');
|
||||
const hasParenClose = tail.includes(')');
|
||||
if (!hasImageOpen) return content;
|
||||
|
||||
// Incomplete image syntax at stream tail, e.g. ) {
|
||||
return content.slice(0, lastImgStart) + STREAMING_IMAGE_PLACEHOLDER;
|
||||
}
|
||||
|
||||
return content;
|
||||
};
|
||||
|
||||
/** Hide an unclosed trailing ```mermaid fence while streaming to avoid layout jitter. */
|
||||
export const replaceIncompleteMermaidWithPlaceholder = (content: string): string => {
|
||||
return replaceIncompleteMermaid(content, STREAMING_MERMAID_PLACEHOLDER);
|
||||
};
|
||||
|
||||
/** Keep every mermaid fence as a stable placeholder; render SVG via cache injection. */
|
||||
export const maskMermaidBlocksForStreaming = (content: string): string => {
|
||||
return maskMermaidBlocks(content, STREAMING_MERMAID_PLACEHOLDER);
|
||||
};
|
||||
|
||||
/** While streaming: loading placeholder for mermaid; swap to cached SVG after sanitize. */
|
||||
export const prepareStreamingMermaidMarkdown = (
|
||||
content: string,
|
||||
_cachedSvgHtml?: CachedMermaidSvgHtml,
|
||||
): string => {
|
||||
return prepareStreamingMermaid(content, STREAMING_MERMAID_PLACEHOLDER);
|
||||
};
|
||||
|
||||
/** Inject trusted Mermaid SVG after DOMPurify, 1:1 with complete mermaid fences. */
|
||||
export const injectCachedMermaidSvg = (
|
||||
html: string,
|
||||
cachedSvgHtml: CachedMermaidSvgHtml,
|
||||
): string => {
|
||||
return injectCachedMermaidSvgHtml(html, cachedSvgHtml, buildMermaidBlockHtml);
|
||||
};
|
||||
|
||||
export const formatManualTitle = (question?: string): string => {
|
||||
return deriveManualTitle(question || '', i18n.global.t('chat.sessionExcerpt'));
|
||||
};
|
||||
|
||||
export const buildManualMarkdown = (_question: string, answer: string): string => {
|
||||
return buildManualDraft(answer, {
|
||||
emptyAnswer: i18n.global.t('chat.noAnswerContent'),
|
||||
sourcesHeading: i18n.global.t('chat.manualSourcesHeading'),
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,243 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
ACTIVE_QUESTION_TOP_OFFSET_PX,
|
||||
QUESTION_MINIMAP_TRACK_MAX_PX,
|
||||
QUESTION_TICK_GAP_PX,
|
||||
QUESTION_TICK_INSET_PX,
|
||||
QUESTION_TICK_MOUNTAIN_GAIN,
|
||||
CURRENT_TICK_SCALE,
|
||||
activeQuestionId,
|
||||
answerPreviewText,
|
||||
collectOutlineMessages,
|
||||
groupOutlineBounds,
|
||||
isChatOverflowing,
|
||||
mapQuestionTicks,
|
||||
nearestTickId,
|
||||
offsetFromScrollContent,
|
||||
questionDisplayText,
|
||||
questionMinimapTrackHeight,
|
||||
shouldShowQuestionMinimap,
|
||||
tickDisplayScale,
|
||||
tickMountainScale,
|
||||
viewportBand,
|
||||
visibleMessageIds,
|
||||
} from './chatQuestionMinimap.ts'
|
||||
|
||||
test('isChatOverflowing is false when content fits or matches the viewport', () => {
|
||||
assert.equal(isChatOverflowing(800, 800), false)
|
||||
assert.equal(isChatOverflowing(799, 800), false)
|
||||
assert.equal(isChatOverflowing(801, 800), true)
|
||||
})
|
||||
|
||||
test('questionMinimapTrackHeight packs ticks with a small gap instead of filling the rail', () => {
|
||||
assert.equal(questionMinimapTrackHeight(1, 800), QUESTION_TICK_INSET_PX * 2)
|
||||
assert.equal(questionMinimapTrackHeight(3, 800), 2 * QUESTION_TICK_GAP_PX + 2 * QUESTION_TICK_INSET_PX)
|
||||
assert.equal(questionMinimapTrackHeight(0, 800), 0)
|
||||
assert.equal(questionMinimapTrackHeight(3, 0), 0)
|
||||
})
|
||||
|
||||
test('questionMinimapTrackHeight still caps a long cluster to the centered rail', () => {
|
||||
assert.equal(questionMinimapTrackHeight(100, 800), QUESTION_MINIMAP_TRACK_MAX_PX)
|
||||
assert.equal(questionMinimapTrackHeight(100, 400), 200)
|
||||
})
|
||||
|
||||
test('shouldShowQuestionMinimap requires overflow, a turn, and room beside the messages', () => {
|
||||
assert.equal(shouldShowQuestionMinimap(true, 1, 60), true)
|
||||
assert.equal(shouldShowQuestionMinimap(true, 2, 44), true)
|
||||
assert.equal(shouldShowQuestionMinimap(true, 0, 60), false)
|
||||
assert.equal(shouldShowQuestionMinimap(false, 4, 60), false)
|
||||
assert.equal(shouldShowQuestionMinimap(true, 4, 43), false)
|
||||
assert.equal(shouldShowQuestionMinimap(true, 4, 0), false)
|
||||
assert.equal(shouldShowQuestionMinimap(true, 4, -20), false)
|
||||
})
|
||||
|
||||
test('collectOutlineMessages groups each query and its answers into one turn', () => {
|
||||
const questions = collectOutlineMessages([
|
||||
{ role: 'assistant', id: 'a1', content: 'hi' },
|
||||
{ role: 'user', content: 'no id yet' },
|
||||
{ role: 'user', id: 'u1', content: 'first', images: [{}] },
|
||||
{ role: 'assistant', id: 'a2', content: 'answer one' },
|
||||
{ role: 'user', id: 'u2', content: ' ', attachments: [{}] },
|
||||
])
|
||||
assert.deepEqual(
|
||||
questions.map((q) => ({ id: q.id, hasAttachments: q.hasAttachments, answerContent: q.answerContent })),
|
||||
[
|
||||
{ id: 'a1', hasAttachments: false, answerContent: '' },
|
||||
{ id: 'u1', hasAttachments: true, answerContent: 'answer one' },
|
||||
{ id: 'u2', hasAttachments: true, answerContent: '' },
|
||||
],
|
||||
)
|
||||
assert.deepEqual(questions.map(q => q.role), ['assistant', 'user', 'user'])
|
||||
assert.deepEqual(questions.map(q => q.messageIds), [['a1'], ['u1', 'a2'], ['u2']])
|
||||
})
|
||||
|
||||
test('all messages intersecting the viewport are highlighted, including partial and long answers', () => {
|
||||
const items = [
|
||||
{ id: 'above', offsetTop: 0, offsetBottom: 100 },
|
||||
{ id: 'user', offsetTop: 90, offsetBottom: 125 },
|
||||
{ id: 'assistant', offsetTop: 140, offsetBottom: 280 },
|
||||
{ id: 'next-user', offsetTop: 290, offsetBottom: 330 },
|
||||
{ id: 'below', offsetTop: 300, offsetBottom: 400 },
|
||||
{ id: 'hidden', offsetTop: 150, offsetBottom: 150 },
|
||||
]
|
||||
assert.deepEqual([...visibleMessageIds(items, 100, 200)], ['user', 'assistant', 'next-user'])
|
||||
assert.deepEqual([...visibleMessageIds([
|
||||
{ id: 'long-answer', offsetTop: 0, offsetBottom: 2000 },
|
||||
], 500, 200)], ['long-answer'])
|
||||
assert.equal(visibleMessageIds(items, 100, 0).size, 0)
|
||||
})
|
||||
|
||||
test('messages hidden under the sticky composer are not highlighted', () => {
|
||||
const items = [
|
||||
{ id: 'query-above', offsetTop: 0, offsetBottom: 80 },
|
||||
{ id: 'long-answer', offsetTop: 80, offsetBottom: 340 },
|
||||
{ id: 'query-under-composer', offsetTop: 400, offsetBottom: 440 },
|
||||
{ id: 'answer-under-composer', offsetTop: 450, offsetBottom: 800 },
|
||||
]
|
||||
assert.deepEqual([...visibleMessageIds(items, 100, 500, 200)], ['long-answer'])
|
||||
assert.deepEqual([...visibleMessageIds(items, 300, 500, 200)],
|
||||
['long-answer', 'query-under-composer', 'answer-under-composer'])
|
||||
assert.deepEqual([...visibleMessageIds(items, 450, 500, 200)], ['answer-under-composer'])
|
||||
assert.equal(visibleMessageIds(items, 100, 200, 250).size, 0)
|
||||
})
|
||||
|
||||
test('answerPreviewText strips markdown and stays empty when there is no answer yet', () => {
|
||||
assert.equal(
|
||||
answerPreviewText('## Hello\n**world** and [link](https://x)'),
|
||||
'Hello world and link',
|
||||
)
|
||||
assert.equal(answerPreviewText(' '), '')
|
||||
assert.equal(answerPreviewText(undefined), '')
|
||||
})
|
||||
|
||||
test('tickMountainScale is 1 without a pointer and peaks at the hovered tick', () => {
|
||||
assert.equal(tickMountainScale(100, null), 1)
|
||||
assert.equal(tickMountainScale(100, 100), 1 + QUESTION_TICK_MOUNTAIN_GAIN)
|
||||
assert.ok(tickMountainScale(100, 100) > tickMountainScale(108, 100))
|
||||
assert.ok(tickMountainScale(108, 100) > tickMountainScale(200, 100))
|
||||
})
|
||||
|
||||
test('tickDisplayScale lengthens the current tick at rest and follows the pointer when hovering', () => {
|
||||
assert.equal(tickDisplayScale(100, null, false), 1)
|
||||
assert.equal(tickDisplayScale(100, null, true), CURRENT_TICK_SCALE)
|
||||
assert.equal(tickDisplayScale(100, 100, false), 1 + QUESTION_TICK_MOUNTAIN_GAIN)
|
||||
})
|
||||
|
||||
test('nearestTickId picks the closest tick to the pointer', () => {
|
||||
const ticks = [
|
||||
{ id: 'u1', yPx: 10 },
|
||||
{ id: 'u2', yPx: 45 },
|
||||
{ id: 'u3', yPx: 80 },
|
||||
]
|
||||
assert.equal(nearestTickId(ticks, 12), 'u1')
|
||||
assert.equal(nearestTickId(ticks, 50), 'u2')
|
||||
assert.equal(nearestTickId([], 10), null)
|
||||
})
|
||||
|
||||
test('questionDisplayText uses trimmed content, else the placeholder', () => {
|
||||
assert.equal(questionDisplayText(' hello\nworld ', '(附件)'), 'hello world')
|
||||
assert.equal(questionDisplayText(' ', '(附件)'), '(附件)')
|
||||
assert.equal(questionDisplayText(undefined, '(附件)'), '(附件)')
|
||||
})
|
||||
|
||||
test('offsetFromScrollContent is viewport-relative plus scrollTop', () => {
|
||||
assert.equal(offsetFromScrollContent(120, 40, 80), 160)
|
||||
})
|
||||
|
||||
test('mapQuestionTicks clusters ticks in the center with a compact equal gap', () => {
|
||||
const ticks = mapQuestionTicks(
|
||||
[
|
||||
{ id: 'u1' },
|
||||
{ id: 'u2' },
|
||||
{ id: 'u3' },
|
||||
],
|
||||
200,
|
||||
)
|
||||
assert.equal(ticks[1].yPx - ticks[0].yPx, QUESTION_TICK_GAP_PX)
|
||||
assert.equal(ticks[2].yPx - ticks[1].yPx, QUESTION_TICK_GAP_PX)
|
||||
assert.equal((ticks[0].yPx + ticks[2].yPx) / 2, 100)
|
||||
})
|
||||
|
||||
test('mapQuestionTicks ignores message offsets and keeps equal gaps', () => {
|
||||
const ticks = mapQuestionTicks(
|
||||
[
|
||||
{ id: 'u1', offsetTop: 0 },
|
||||
{ id: 'u2', offsetTop: 2 },
|
||||
],
|
||||
200,
|
||||
)
|
||||
assert.equal(ticks[1].yPx - ticks[0].yPx, QUESTION_TICK_GAP_PX)
|
||||
assert.equal((ticks[0].yPx + ticks[1].yPx) / 2, 100)
|
||||
})
|
||||
|
||||
test('mapQuestionTicks still fits many ticks inside a short rail', () => {
|
||||
const ticks = mapQuestionTicks(
|
||||
[
|
||||
{ id: 'a' },
|
||||
{ id: 'b' },
|
||||
{ id: 'c' },
|
||||
{ id: 'd' },
|
||||
],
|
||||
20,
|
||||
)
|
||||
assert.equal(ticks.length, 4)
|
||||
assert.ok(ticks[0].yPx >= 0)
|
||||
assert.ok(ticks[3].yPx <= 20)
|
||||
const gap = ticks[1].yPx - ticks[0].yPx
|
||||
for (let i = 1; i < ticks.length; i++) {
|
||||
assert.ok(Math.abs(ticks[i].yPx - ticks[i - 1].yPx - gap) < 1e-9)
|
||||
}
|
||||
})
|
||||
|
||||
test('viewportBand maps the visible window onto the track with a 16px floor', () => {
|
||||
const band = viewportBand(250, 250, 1000, 200)
|
||||
assert.equal(band.topPx, 50)
|
||||
assert.equal(band.heightPx, 50)
|
||||
|
||||
const tiny = viewportBand(0, 10, 1000, 200)
|
||||
assert.equal(tiny.topPx, 0)
|
||||
assert.equal(tiny.heightPx, 16)
|
||||
})
|
||||
|
||||
test('activeQuestionId picks the last question at or above the top offset', () => {
|
||||
const items = [
|
||||
{ id: 'u1', offsetTop: 0 },
|
||||
{ id: 'u2', offsetTop: 400 },
|
||||
{ id: 'u3', offsetTop: 800 },
|
||||
]
|
||||
assert.equal(activeQuestionId(items, 0), 'u1')
|
||||
assert.equal(activeQuestionId(items, 400 - ACTIVE_QUESTION_TOP_OFFSET_PX), 'u2')
|
||||
assert.equal(activeQuestionId(items, 900), 'u3')
|
||||
assert.equal(activeQuestionId([], 0), null)
|
||||
})
|
||||
|
||||
|
||||
test('one turn tick stays highlighted for either query or any assistant segment', () => {
|
||||
const turns = collectOutlineMessages([
|
||||
{ role: 'user', id: 'u1', content: 'question' },
|
||||
{ role: 'assistant', id: 'a1', content: 'first segment' },
|
||||
{ role: 'tool', id: 'tool' },
|
||||
{ role: 'assistant', id: 'a2', content: 'continued answer' },
|
||||
{ role: 'user', id: 'u2', content: 'next question' },
|
||||
{ role: 'assistant', id: 'a3', content: 'next answer' },
|
||||
])
|
||||
assert.deepEqual(turns.map(turn => turn.id), ['u1', 'u2'])
|
||||
assert.equal(turns[0].answerContent, 'first segment\n\ncontinued answer')
|
||||
const bounds = groupOutlineBounds(turns, [
|
||||
{ id: 'u1', offsetTop: 0, offsetBottom: 60 },
|
||||
{ id: 'a1', offsetTop: 80, offsetBottom: 500 },
|
||||
{ id: 'a2', offsetTop: 520, offsetBottom: 1000 },
|
||||
{ id: 'u2', offsetTop: 1020, offsetBottom: 1080 },
|
||||
{ id: 'a3', offsetTop: 1100, offsetBottom: 1800 },
|
||||
])
|
||||
assert.equal(mapQuestionTicks(bounds, 100).length, 2)
|
||||
for (const top of [0, 100, 600]) {
|
||||
assert.deepEqual([...visibleMessageIds(bounds, top, 100)], ['u1'])
|
||||
}
|
||||
assert.deepEqual([...visibleMessageIds(bounds, 900, 200)], ['u1', 'u2'])
|
||||
assert.deepEqual([...visibleMessageIds(bounds, 1300, 200)], ['u2'])
|
||||
assert.equal(visibleMessageIds(bounds, 60, 20).size, 0, 'the gap alone is not visible content')
|
||||
assert.equal(groupOutlineBounds(turns, []).length, 0, 'unrendered messages do not create ticks')
|
||||
})
|
||||
@@ -0,0 +1,275 @@
|
||||
export const QUESTION_TICK_INSET_PX = 8
|
||||
export const QUESTION_TICK_GAP_PX = 8
|
||||
export const QUESTION_TICK_MOUNTAIN_GAIN = 0.8
|
||||
export const CURRENT_TICK_SCALE = 1.55
|
||||
export const ACTIVE_QUESTION_TOP_OFFSET_PX = 72
|
||||
export const VIEWPORT_BAND_MIN_HEIGHT_PX = 16
|
||||
export const QUESTION_MINIMAP_TRACK_MAX_PX = 360
|
||||
export const QUESTION_MINIMAP_TRACK_RATIO = 0.5
|
||||
// 28px rail + 4px hit-area extension + 12px clearance from message content.
|
||||
export const QUESTION_MINIMAP_MIN_GUTTER_PX = 44
|
||||
|
||||
export function questionMinimapTrackHeight(
|
||||
questionCount: number,
|
||||
clientHeight: number,
|
||||
): number {
|
||||
if (questionCount <= 0 || clientHeight <= 0) return 0
|
||||
const maxHeight = Math.min(
|
||||
QUESTION_MINIMAP_TRACK_MAX_PX,
|
||||
clientHeight * QUESTION_MINIMAP_TRACK_RATIO,
|
||||
)
|
||||
const naturalHeight = questionCount === 1
|
||||
? QUESTION_TICK_INSET_PX * 2
|
||||
: (questionCount - 1) * QUESTION_TICK_GAP_PX + QUESTION_TICK_INSET_PX * 2
|
||||
return Math.min(naturalHeight, maxHeight)
|
||||
}
|
||||
|
||||
export type ChatMessageLike = {
|
||||
id?: string
|
||||
role?: string
|
||||
content?: string
|
||||
images?: unknown[]
|
||||
attachments?: unknown[]
|
||||
}
|
||||
|
||||
export type OutlineMessage = {
|
||||
id: string
|
||||
role: 'user' | 'assistant'
|
||||
content: string
|
||||
hasAttachments: boolean
|
||||
answerContent: string
|
||||
messageIds: string[]
|
||||
}
|
||||
|
||||
export type QuestionTick = {
|
||||
id: string
|
||||
yRatio: number
|
||||
yPx: number
|
||||
}
|
||||
|
||||
export type ViewportBand = {
|
||||
topPx: number
|
||||
heightPx: number
|
||||
}
|
||||
|
||||
export function isChatOverflowing(scrollHeight: number, clientHeight: number): boolean {
|
||||
return scrollHeight > clientHeight
|
||||
}
|
||||
|
||||
export function shouldShowQuestionMinimap(overflowing: boolean, questionCount: number, availableGutter: number): boolean {
|
||||
return overflowing && questionCount >= 1 && availableGutter >= QUESTION_MINIMAP_MIN_GUTTER_PX
|
||||
}
|
||||
|
||||
export function collectOutlineMessages(messages: ChatMessageLike[]): OutlineMessage[] {
|
||||
const questions: OutlineMessage[] = []
|
||||
|
||||
let current: OutlineMessage | undefined
|
||||
for (const message of messages) {
|
||||
if (message.role === 'user') current = undefined
|
||||
if ((message.role !== 'user' && message.role !== 'assistant') || !message.id) continue
|
||||
|
||||
if (message.role === 'assistant' && current) {
|
||||
current.messageIds.push(message.id)
|
||||
if (message.content) {
|
||||
current.answerContent = [current.answerContent, message.content].filter(Boolean).join('\n\n')
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
current = {
|
||||
id: message.id,
|
||||
role: message.role,
|
||||
content: message.content ?? '',
|
||||
hasAttachments:
|
||||
(message.images?.length ?? 0) > 0 || (message.attachments?.length ?? 0) > 0,
|
||||
answerContent: '',
|
||||
messageIds: [message.id],
|
||||
}
|
||||
questions.push(current)
|
||||
}
|
||||
|
||||
return questions
|
||||
}
|
||||
|
||||
type MessageBounds = { id: string; offsetTop: number; offsetBottom: number }
|
||||
|
||||
/** One rail tick per turn, retaining each message's bounds for visibility. */
|
||||
export function groupOutlineBounds(
|
||||
turns: OutlineMessage[],
|
||||
messages: MessageBounds[],
|
||||
): Array<MessageBounds & { ranges: MessageBounds[] }> {
|
||||
const byId = new Map(messages.map(message => [message.id, message]))
|
||||
return turns.flatMap(turn => {
|
||||
const ranges = turn.messageIds.flatMap(id => {
|
||||
const bounds = byId.get(id)
|
||||
return bounds && bounds.offsetBottom > bounds.offsetTop ? [bounds] : []
|
||||
})
|
||||
if (!ranges.length) return []
|
||||
return [{
|
||||
id: turn.id,
|
||||
offsetTop: Math.min(...ranges.map(range => range.offsetTop)),
|
||||
offsetBottom: Math.max(...ranges.map(range => range.offsetBottom)),
|
||||
ranges,
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
/** Include partially visible messages and long answers spanning the viewport. */
|
||||
export function visibleMessageIds(
|
||||
items: Array<MessageBounds & { ranges?: MessageBounds[] }>,
|
||||
scrollTop: number,
|
||||
clientHeight: number,
|
||||
bottomInset: number = 0,
|
||||
): Set<string> {
|
||||
const visibleHeight = Math.max(0, clientHeight - bottomInset)
|
||||
if (visibleHeight <= 0) return new Set()
|
||||
const bottom = scrollTop + visibleHeight
|
||||
return new Set(items.filter(item => (item.ranges ?? [item]).some(range => (
|
||||
range.offsetBottom > range.offsetTop && range.offsetBottom > scrollTop && range.offsetTop < bottom
|
||||
))).map(item => item.id))
|
||||
}
|
||||
|
||||
export function questionDisplayText(
|
||||
content: string | undefined,
|
||||
attachmentPlaceholder: string,
|
||||
): string {
|
||||
const normalized = (content ?? '').replace(/\s+/g, ' ').trim()
|
||||
return normalized.length > 0 ? normalized : attachmentPlaceholder
|
||||
}
|
||||
|
||||
export function answerPreviewText(content: string | undefined): string {
|
||||
const normalized = (content ?? '')
|
||||
.replace(/```[\s\S]*?```/g, ' ')
|
||||
.replace(/`([^`]+)`/g, '$1')
|
||||
.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
|
||||
.replace(/[#>*_~-]+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
return normalized
|
||||
}
|
||||
|
||||
export function tickMountainScale(tickY: number, pointerY: number | null): number {
|
||||
if (pointerY === null) return 1
|
||||
const dy = tickY - pointerY
|
||||
const sigma = QUESTION_TICK_GAP_PX
|
||||
return 1 + QUESTION_TICK_MOUNTAIN_GAIN * Math.exp(-0.5 * (dy / sigma) ** 2)
|
||||
}
|
||||
|
||||
export function tickDisplayScale(
|
||||
tickY: number,
|
||||
pointerY: number | null,
|
||||
isCurrent: boolean,
|
||||
): number {
|
||||
if (pointerY !== null) return tickMountainScale(tickY, pointerY)
|
||||
return isCurrent ? CURRENT_TICK_SCALE : 1
|
||||
}
|
||||
|
||||
export function nearestTickId(
|
||||
ticks: Array<{ id: string; yPx: number }>,
|
||||
pointerY: number,
|
||||
): string | null {
|
||||
if (ticks.length === 0) return null
|
||||
|
||||
let bestId = ticks[0].id
|
||||
let bestDist = Math.abs(ticks[0].yPx - pointerY)
|
||||
for (let index = 1; index < ticks.length; index++) {
|
||||
const dist = Math.abs(ticks[index].yPx - pointerY)
|
||||
if (dist < bestDist) {
|
||||
bestDist = dist
|
||||
bestId = ticks[index].id
|
||||
}
|
||||
}
|
||||
return bestId
|
||||
}
|
||||
|
||||
export function offsetFromScrollContent(
|
||||
anchorTop: number,
|
||||
containerTop: number,
|
||||
scrollTop: number,
|
||||
): number {
|
||||
return anchorTop - containerTop + scrollTop
|
||||
}
|
||||
|
||||
export function mapQuestionTicks(
|
||||
items: Array<{ id: string; offsetTop?: number }>,
|
||||
trackHeight: number,
|
||||
): QuestionTick[] {
|
||||
const n = items.length
|
||||
if (n === 0 || trackHeight <= 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
if (n === 1) {
|
||||
return [{
|
||||
id: items[0].id,
|
||||
yRatio: 0.5,
|
||||
yPx: trackHeight / 2,
|
||||
}]
|
||||
}
|
||||
|
||||
const preferredSpan = (n - 1) * QUESTION_TICK_GAP_PX
|
||||
const minY = Math.min(QUESTION_TICK_INSET_PX, trackHeight / 2)
|
||||
const maxY = Math.max(minY, trackHeight - minY)
|
||||
const available = maxY - minY
|
||||
const span = preferredSpan <= trackHeight ? preferredSpan : available
|
||||
const start = (trackHeight - span) / 2
|
||||
|
||||
return items.map((item, index) => {
|
||||
const yRatio = index / (n - 1)
|
||||
return {
|
||||
id: item.id,
|
||||
yRatio,
|
||||
yPx: start + yRatio * span,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export function viewportBand(
|
||||
scrollTop: number,
|
||||
clientHeight: number,
|
||||
scrollHeight: number,
|
||||
trackHeight: number,
|
||||
minHeightPx: number = VIEWPORT_BAND_MIN_HEIGHT_PX,
|
||||
): ViewportBand {
|
||||
if (scrollHeight <= 0 || trackHeight <= 0) {
|
||||
return { topPx: 0, heightPx: minHeightPx }
|
||||
}
|
||||
|
||||
let topPx = (scrollTop / scrollHeight) * trackHeight
|
||||
let heightPx = Math.max(minHeightPx, (clientHeight / scrollHeight) * trackHeight)
|
||||
|
||||
heightPx = Math.min(heightPx, trackHeight)
|
||||
|
||||
if (topPx + heightPx > trackHeight) {
|
||||
topPx = trackHeight - heightPx
|
||||
}
|
||||
|
||||
topPx = Math.max(0, topPx)
|
||||
|
||||
if (topPx + heightPx > trackHeight) {
|
||||
heightPx = trackHeight - topPx
|
||||
}
|
||||
|
||||
return { topPx, heightPx }
|
||||
}
|
||||
|
||||
export function activeQuestionId(
|
||||
items: Array<{ id: string; offsetTop: number }>,
|
||||
scrollTop: number,
|
||||
topOffsetPx: number = ACTIVE_QUESTION_TOP_OFFSET_PX,
|
||||
): string | null {
|
||||
if (items.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const threshold = scrollTop + topOffsetPx
|
||||
let activeId: string | null = null
|
||||
|
||||
for (const item of items) {
|
||||
if (item.offsetTop <= threshold) {
|
||||
activeId = item.id
|
||||
}
|
||||
}
|
||||
|
||||
return activeId ?? items[0].id
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/** Sanitize stream POST body for display (strip large base64 payloads). */
|
||||
export function sanitizeStreamRequestBody(body: Record<string, unknown>): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = { ...body };
|
||||
if (Array.isArray(out.images)) {
|
||||
out.images = out.images.map((img: { data?: string }, i: number) => ({
|
||||
_placeholder: `image[${i}]`,
|
||||
bytes: typeof img?.data === 'string' ? img.data.length : 0,
|
||||
}));
|
||||
}
|
||||
if (Array.isArray(out.attachment_uploads)) {
|
||||
out.attachment_uploads = out.attachment_uploads.map(
|
||||
(att: { file_name?: string; file_size?: number; data?: string }, i: number) => ({
|
||||
file_name: att.file_name,
|
||||
file_size: att.file_size,
|
||||
_placeholder: `attachment[${i}]`,
|
||||
bytes: typeof att?.data === 'string' ? att.data.length : 0,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (typeof out.query === 'string' && out.query.length > 500) {
|
||||
out.query = `${out.query.slice(0, 500)}… (${out.query.length} chars)`;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface StreamRequestMeta {
|
||||
requestId: string;
|
||||
url: string;
|
||||
method: string;
|
||||
body: Record<string, unknown> | null;
|
||||
sentAt: number;
|
||||
}
|
||||
|
||||
export interface ChatRequestDebugInfo {
|
||||
requestId?: string;
|
||||
messageId?: string;
|
||||
sessionId?: string;
|
||||
url?: string;
|
||||
method?: string;
|
||||
body?: Record<string, unknown> | null;
|
||||
sentAt?: number;
|
||||
}
|
||||
|
||||
export function buildChatRequestDebugPayload(info: ChatRequestDebugInfo): string {
|
||||
return JSON.stringify(info, null, 2);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { chatSubmitShortcut } from './chatSubmitShortcut'
|
||||
|
||||
const enter = { key: 'Enter', keyCode: 13, isComposing: false, shiftKey: false, ctrlKey: false, altKey: false, metaKey: false }
|
||||
test('Enter queues during a run and Alt+Enter injects only while steering is available', () => {
|
||||
assert.equal(chatSubmitShortcut(enter, true), 'after')
|
||||
assert.equal(chatSubmitShortcut(enter, false), 'inject')
|
||||
assert.equal(chatSubmitShortcut({ ...enter, altKey: true }, true), 'inject')
|
||||
assert.equal(chatSubmitShortcut({ ...enter, altKey: true }, false), undefined)
|
||||
})
|
||||
test('Cmd+Enter injects during a run and sends normally when idle', () => {
|
||||
const cmdEnter = { ...enter, metaKey: true }
|
||||
assert.equal(chatSubmitShortcut(cmdEnter, true), 'inject')
|
||||
assert.equal(chatSubmitShortcut(cmdEnter, false), 'inject')
|
||||
for (const modifiers of [{ shiftKey: true }, { ctrlKey: true }, { isComposing: true }, { keyCode: 229 }]) {
|
||||
assert.equal(chatSubmitShortcut({ ...cmdEnter, ...modifiers }, true), undefined)
|
||||
}
|
||||
})
|
||||
test('newlines and IME confirmation never submit', () => {
|
||||
for (const modifiers of [{ shiftKey: true }, { ctrlKey: true }, { isComposing: true }, { keyCode: 229 }]) {
|
||||
assert.equal(chatSubmitShortcut({ ...enter, ...modifiers }, true), undefined)
|
||||
}
|
||||
assert.equal(chatSubmitShortcut({ ...enter, key: 'a', keyCode: 65 }, true), undefined)
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
/** Enter queues during a run; Cmd/Alt+Enter steers. Preserve newline and IME behavior. */
|
||||
export function chatSubmitShortcut(
|
||||
event: Pick<KeyboardEvent, 'key' | 'keyCode' | 'isComposing' | 'shiftKey' | 'ctrlKey' | 'altKey' | 'metaKey'>,
|
||||
canSteer: boolean,
|
||||
): 'inject' | 'after' | undefined {
|
||||
if (event.isComposing || event.keyCode === 229 || (event.key !== 'Enter' && event.keyCode !== 13)) return
|
||||
if (event.shiftKey || event.ctrlKey) return
|
||||
if (event.metaKey) return 'inject'
|
||||
if (event.altKey) return canSteer ? 'inject' : undefined
|
||||
return canSteer ? 'after' : 'inject'
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Each glyph performs one readable gesture, settles, then rests before repeating.
|
||||
// The phases borrow the anticipation/settling approach of open-claude-ui's
|
||||
// motion examples, implemented here with our own SVG geometry (no icon font).
|
||||
export interface TimelineIconAnimation {
|
||||
attribute: 'd' | 'opacity' | 'stroke-dashoffset'
|
||||
values: string[]
|
||||
times: string
|
||||
splines: string
|
||||
}
|
||||
|
||||
export interface TimelineIconPart {
|
||||
path: string
|
||||
animations?: TimelineIconAnimation[]
|
||||
transform?: {
|
||||
type: 'translate' | 'rotate'
|
||||
values: string[]
|
||||
times: string
|
||||
splines: string
|
||||
}
|
||||
draw?: boolean
|
||||
delay?: number
|
||||
}
|
||||
|
||||
export const TIMELINE_ICON_CYCLE = '2.8s'
|
||||
const gestureTimes = '0;.12;.3;.4;.56;.78;1'
|
||||
const ease = '.22 .7 .3 1'
|
||||
const settle = '.2 0 .2 1'
|
||||
const gestureSplines = [ease, ease, settle, ease, settle, ease].join(';')
|
||||
const traceTimes = '0;.12;.36;.6;.76;.82;1'
|
||||
const traceSplines = Array(6).fill(ease).join(';')
|
||||
|
||||
const gesture = (rest: string, overshoot: string, target: string) => ({
|
||||
values: [rest, rest, overshoot, target, target, rest, rest],
|
||||
times: gestureTimes,
|
||||
splines: gestureSplines,
|
||||
})
|
||||
|
||||
function move(
|
||||
part: TimelineIconPart, type: 'translate' | 'rotate',
|
||||
rest: string, overshoot: string, target: string,
|
||||
): TimelineIconPart {
|
||||
return { ...part, transform: { type, ...gesture(rest, overshoot, target) } }
|
||||
}
|
||||
|
||||
function morph(path: string, target: string, overshoot = target): TimelineIconPart {
|
||||
return { path, animations: [{ attribute: 'd', ...gesture(path, overshoot, target) }] }
|
||||
}
|
||||
|
||||
// Draw once, hold, fade, then reset while invisible. Never erase a visible line
|
||||
// backwards, flash the whole icon, or change the line weight.
|
||||
function trace(path: string, delay = 0): TimelineIconPart {
|
||||
return {
|
||||
path, draw: true, delay,
|
||||
animations: [
|
||||
{ attribute: 'stroke-dashoffset', values: ['1', '1', '0', '0', '0', '1', '1'], times: traceTimes, splines: traceSplines },
|
||||
{ attribute: 'opacity', values: ['0', '1', '1', '1', '0', '0', '0'], times: traceTimes, splines: traceSplines },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function reveal(path: string, delay = 0): TimelineIconPart {
|
||||
return {
|
||||
path, delay,
|
||||
animations: [{
|
||||
attribute: 'opacity', values: ['0', '0', '1', '1', '0', '0', '0'],
|
||||
times: traceTimes, splines: traceSplines,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
export function getTimelineIconMotion(name: string, paths: string[]): TimelineIconPart[] {
|
||||
const parts: TimelineIconPart[] = paths.map(path => ({ path }))
|
||||
switch (name) {
|
||||
case 'lightbulb':
|
||||
case 'ai-search':
|
||||
// Keep every lit stroke inside the glass, with space above the neck.
|
||||
// External rays can read as stray filament at the actual 18px size.
|
||||
return [...parts, trace('M9.5 9.5 12 12l2.5-2.5M12 12v2')]
|
||||
case 'search':
|
||||
return [...parts, trace('M6 10a4 4 0 0 1 4-4')]
|
||||
case 'data-search':
|
||||
case 'file-search':
|
||||
// One deliberate lens pass, followed by a small settle at the destination.
|
||||
return [parts[0], move(parts[1], 'translate', '0 0', '-2.5 -1.5', '-2 -1')]
|
||||
case 'internet':
|
||||
// Meridian bends across the globe instead of rocking the entire world.
|
||||
return [
|
||||
parts[0], parts[1],
|
||||
morph('M12 4C7 7 7 17 12 20', 'M12 4C17 7 17 17 12 20'),
|
||||
morph('M12 4C17 7 17 17 12 20', 'M12 4C7 7 7 17 12 20'),
|
||||
]
|
||||
case 'file':
|
||||
case 'file-paste':
|
||||
return [parts[0], trace('M8 14h8'), trace('M8 17h5', .18)]
|
||||
case 'folder':
|
||||
// The front opens while the back and tab stay anchored.
|
||||
return [
|
||||
{ path: 'M4 17V6a2 2 0 0 1 2-2h3l2 3h7a2 2 0 0 1 2 2v8' },
|
||||
morph(
|
||||
'M4 10h16l-1 8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2Z',
|
||||
'M6 11h16l-3 7a3 3 0 0 1-3 2H6a2 2 0 0 1-2-2Z',
|
||||
'M6.5 11h16l-3.5 7a3 3 0 0 1-3 2H6a2 2 0 0 1-2-2Z',
|
||||
),
|
||||
]
|
||||
case 'task':
|
||||
return [parts[0], parts[1], trace(parts[2].path), trace(parts[3].path, .2)]
|
||||
case 'bookmark':
|
||||
return [...parts, trace('M9 10h6'), trace('M9 13h4', .16)]
|
||||
case 'edit':
|
||||
return [move(parts[0], 'translate', '0 0', '2 -2', '1.5 -1.5'), trace('M5 21h8', .2)]
|
||||
case 'attach':
|
||||
return [move(parts[0], 'rotate', '0 12 12', '-16 12 12', '-12 12 12')]
|
||||
case 'terminal':
|
||||
return [
|
||||
move(parts[0], 'translate', '0 0', '2.5 0', '2 0'),
|
||||
trace('M15 18h5', .16),
|
||||
]
|
||||
case 'code':
|
||||
return [
|
||||
move(parts[0], 'translate', '0 0', '-1.5 0', '-1 0'),
|
||||
move(parts[1], 'translate', '0 0', '1.5 0', '1 0'),
|
||||
trace(parts[2].path, .18),
|
||||
]
|
||||
case 'chat':
|
||||
return [parts[0], trace('M8 10h8'), trace('M8 13h5', .18)]
|
||||
case 'agent':
|
||||
return [
|
||||
move(parts[0], 'translate', '0 0', '-1.2 0', '-.8 0'),
|
||||
{ ...move(parts[1], 'translate', '0 0', '1.2 0', '.8 0'), delay: .14 },
|
||||
]
|
||||
case 'browser':
|
||||
return [
|
||||
parts[0],
|
||||
move(parts[1], 'translate', '0 0', '-2 -1.5', '-1.5 -1'),
|
||||
reveal('M7.5 11.5h-2m3-2-1-1.5', .25),
|
||||
]
|
||||
case 'jump':
|
||||
return [
|
||||
move(parts[0], 'translate', '0 0', '2 -2', '1.5 -1.5'),
|
||||
parts[1],
|
||||
]
|
||||
case 'compaction':
|
||||
return [
|
||||
parts[0],
|
||||
// Keep the arrow tips apart, including at the overshoot, so their
|
||||
// strokes never collide into a heavier mark.
|
||||
morph('M8 7l4 4 4-4', 'M10 8l2 3 2-3', 'M10.5 8.2l1.5 2.8 1.5-2.8'),
|
||||
morph('M8 17l4-4 4 4', 'M10 16l2-3 2 3', 'M10.5 15.8l1.5-2.8 1.5 2.8'),
|
||||
]
|
||||
case 'ellipsis':
|
||||
return parts.map((part, index) => ({
|
||||
...move(part, 'translate', '0 0', '0 -2.5', '0 -2'), delay: index * .12,
|
||||
}))
|
||||
case 'secured':
|
||||
case 'check-circle':
|
||||
return [parts[0], trace(parts[1].path)]
|
||||
case 'lock-on':
|
||||
return [
|
||||
{ path: 'M8 10V8a4 4 0 0 1 8 0v2' },
|
||||
{ path: 'M7 10h10a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2Z' },
|
||||
trace(parts[1].path),
|
||||
]
|
||||
case 'help-circle':
|
||||
return [parts[0], trace(parts[1].path)]
|
||||
case 'time':
|
||||
return [
|
||||
parts[0], { path: 'M12 12l3 2' },
|
||||
{
|
||||
path: 'M12 12V7',
|
||||
transform: {
|
||||
type: 'rotate',
|
||||
values: [0, 0, 96, 90, 186, 180, 276, 270, 366, 360, 360].map(angle => `${angle} 12 12`),
|
||||
times: '0;.06;.18;.24;.38;.44;.58;.64;.78;.84;1',
|
||||
splines: Array(10).fill(ease).join(';'),
|
||||
},
|
||||
},
|
||||
]
|
||||
case 'play-circle':
|
||||
return [parts[0], move(parts[1], 'translate', '0 0', '1.5 0', '1 0')]
|
||||
case 'minus-circle':
|
||||
case 'close-circle':
|
||||
return [parts[0], trace(parts[1].path)]
|
||||
case 'chevron-right':
|
||||
case 'chevron-down':
|
||||
return parts
|
||||
default:
|
||||
// Unknown tools keep the generic file glyph and its reading gesture.
|
||||
return [parts[0], trace('M8 14h8'), trace('M8 17h5', .18)]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* The answer passage a citation marker supports: the text of the marker's
|
||||
* block (paragraph, list item, table cell) up to the marker, without other
|
||||
* citation markers, starting after the preceding marker. A marker on a line of its
|
||||
* own ("依据:[1]") borrows the blocks just before it.
|
||||
*/
|
||||
|
||||
const BLOCK_SELECTOR = 'li, p, td, th, blockquote, h1, h2, h3, h4, h5, h6, dd, dt'
|
||||
const CITATION_SELECTOR = '.citation, .citation-kb, .citation-web, .citation-wiki'
|
||||
const MIN_SENTENCE = 8
|
||||
const MAX_LOOKBACK = 3
|
||||
// Lookback never leaves the rendered answer.
|
||||
const ANSWER_ROOT_SELECTOR = '.markdown-content, body, [contenteditable]'
|
||||
|
||||
function letterCount(text: string): number {
|
||||
return text.replace(/[\s\p{P}\p{S}]/gu, '').length
|
||||
}
|
||||
|
||||
/** Last sentence of `text`, extended backwards while it is too short to align. */
|
||||
export function lastSentence(text: string): string {
|
||||
const pieces = String(text || '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.split(/(?<=[。!?!?;;])/u)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
let out = ''
|
||||
for (let i = pieces.length - 1; i >= 0; i--) {
|
||||
out = pieces[i] + out
|
||||
if (letterCount(out) >= MIN_SENTENCE) break
|
||||
}
|
||||
return out.slice(-300)
|
||||
}
|
||||
|
||||
/**
|
||||
* Anchor for a marker whose own text is `own`, prepending the texts of the
|
||||
* blocks before it (nearest first) while the sentence is too short to align.
|
||||
*/
|
||||
export function anchorWithContext(own: string, previous: string[]): string {
|
||||
let text = own
|
||||
for (const prev of previous) {
|
||||
if (letterCount(lastSentence(text)) >= MIN_SENTENCE) break
|
||||
text = `${prev} ${text}`
|
||||
}
|
||||
return lastSentence(text)
|
||||
}
|
||||
|
||||
function textWithoutCitations(node: Node): string {
|
||||
const clone = node.cloneNode(true) as Element | DocumentFragment
|
||||
clone.querySelectorAll?.(CITATION_SELECTOR).forEach((n) => n.remove())
|
||||
return clone.textContent || ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Text preceding `block` at each enclosing level, nearest first: earlier
|
||||
* siblings, and for a nested list the text of the item that holds it.
|
||||
*/
|
||||
function previousBlockTexts(block: Element): string[] {
|
||||
const out: string[] = []
|
||||
for (let node: Element | null = block; node?.parentElement && out.length < MAX_LOOKBACK; node = node.parentElement) {
|
||||
if (node.matches(ANSWER_ROOT_SELECTOR)) break
|
||||
const range = node.ownerDocument.createRange()
|
||||
range.setStart(node.parentElement, 0)
|
||||
range.setEndBefore(node)
|
||||
const text = textWithoutCitations(range.cloneContents()).trim()
|
||||
if (text) out.push(text)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function citationAnchorText(marker: Element): string {
|
||||
try {
|
||||
const block = marker.closest(BLOCK_SELECTOR) || marker.parentElement
|
||||
if (!block) return ''
|
||||
const range = marker.ownerDocument.createRange()
|
||||
range.setStart(block, 0)
|
||||
// A citation covers the preceding passage since the previous citation,
|
||||
// which can contain multiple sentences within the same paragraph.
|
||||
range.setEndBefore(marker)
|
||||
const preceding = [...block.querySelectorAll(CITATION_SELECTOR)]
|
||||
.filter(previous => previous.compareDocumentPosition(marker) & Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
for (const previous of preceding.reverse()) {
|
||||
const candidate = range.cloneRange()
|
||||
candidate.setStartAfter(previous)
|
||||
// Adjacent citations support the same passage; skip citation-only gaps.
|
||||
if (letterCount(textWithoutCitations(candidate.cloneContents())) > 0) {
|
||||
range.setStartAfter(previous)
|
||||
break
|
||||
}
|
||||
}
|
||||
const own = textWithoutCitations(range.cloneContents())
|
||||
const enough = letterCount(lastSentence(own)) >= MIN_SENTENCE
|
||||
return enough ? own.replace(/\s+/g, ' ').trim().slice(-300) : anchorWithContext(own, previousBlockTexts(block))
|
||||
} catch {
|
||||
// Alignment only narrows the highlight; without a sentence the whole chunk is shown.
|
||||
return ''
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import {
|
||||
clearCitationChunkCache,
|
||||
getCitationChunkCache,
|
||||
makeCitationCacheKey,
|
||||
setCitationChunkCache,
|
||||
} from './citationChunkCache.ts'
|
||||
|
||||
test('makeCitationCacheKey combines scope and chunkId', () => {
|
||||
assert.equal(makeCitationCacheKey('session-1', 'chunk-a'), 'session-1::chunk-a')
|
||||
assert.equal(
|
||||
makeCitationCacheKey('embed:ch:tok', 'chunk-b'),
|
||||
'embed:ch:tok::chunk-b',
|
||||
)
|
||||
})
|
||||
|
||||
test('get/set are isolated per scope', () => {
|
||||
clearCitationChunkCache()
|
||||
setCitationChunkCache('session-1', 'chunk-a', { content: 'one' })
|
||||
setCitationChunkCache('session-2', 'chunk-a', { content: 'two' })
|
||||
|
||||
assert.equal(getCitationChunkCache('session-1', 'chunk-a')?.content, 'one')
|
||||
assert.equal(getCitationChunkCache('session-2', 'chunk-a')?.content, 'two')
|
||||
})
|
||||
|
||||
test('clearCitationChunkCache clears one scope or all', () => {
|
||||
clearCitationChunkCache()
|
||||
setCitationChunkCache('session-1', 'chunk-a', { content: 'one' })
|
||||
setCitationChunkCache('session-2', 'chunk-a', { content: 'two' })
|
||||
|
||||
clearCitationChunkCache('session-1')
|
||||
assert.equal(getCitationChunkCache('session-1', 'chunk-a'), undefined)
|
||||
assert.equal(getCitationChunkCache('session-2', 'chunk-a')?.content, 'two')
|
||||
|
||||
clearCitationChunkCache()
|
||||
assert.equal(getCitationChunkCache('session-2', 'chunk-a'), undefined)
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
export type CitationChunkCacheValue = { content: string; error?: string }
|
||||
|
||||
const chunkCache = new Map<string, CitationChunkCacheValue>()
|
||||
|
||||
export function makeCitationCacheKey(scope: string, chunkId: string): string {
|
||||
return `${scope}::${chunkId}`
|
||||
}
|
||||
|
||||
export function getCitationChunkCache(
|
||||
scope: string,
|
||||
chunkId: string,
|
||||
): CitationChunkCacheValue | undefined {
|
||||
return chunkCache.get(makeCitationCacheKey(scope, chunkId))
|
||||
}
|
||||
|
||||
export function setCitationChunkCache(
|
||||
scope: string,
|
||||
chunkId: string,
|
||||
value: CitationChunkCacheValue,
|
||||
): void {
|
||||
chunkCache.set(makeCitationCacheKey(scope, chunkId), value)
|
||||
}
|
||||
|
||||
export function clearCitationChunkCache(scope?: string): void {
|
||||
if (scope === undefined) {
|
||||
chunkCache.clear()
|
||||
return
|
||||
}
|
||||
const prefix = `${scope}::`
|
||||
for (const key of chunkCache.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
chunkCache.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
/** Shared citation tag preprocessing for chat markdown (QA + agent). */
|
||||
|
||||
/** Self-closing or unclosed `<kb/>` / `<web/>` tags from model output. */
|
||||
export const KB_WEB_TAG_RE = /<(?:kb|web)\b[^>]*?\s*\/?>/g
|
||||
const KB_TAG_ATTR_RE = /<kb\b([^>]*?)\s*\/?>/g
|
||||
const WEB_TAG_ATTR_RE = /<web\b([^>]*?)\s*\/?>/g
|
||||
|
||||
const ATTRIBUTE_REGEX = /([\w-]+)\s*=\s*"([^"]*)"/g
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
|
||||
/**
|
||||
* Hide a citation tag while the typewriter has only emitted part of it.
|
||||
*
|
||||
* Without this guard, Markdown renders the leading `<` as ordinary text until
|
||||
* the closing `>` arrives. Only the unfinished tail is removed; a complete tag
|
||||
* continues through the normal citation pipeline.
|
||||
*/
|
||||
export function stripIncompleteCitationTag(content: string): string {
|
||||
if (!content) return content
|
||||
|
||||
const start = content.lastIndexOf('<')
|
||||
if (start < 0) return content
|
||||
|
||||
const tail = content.slice(start)
|
||||
if (tail.includes('>')) return content
|
||||
|
||||
const isCitationPrefix = tail === '<'
|
||||
|| /^<k(?:b(?:\s[\s\S]*)?)?$/i.test(tail)
|
||||
|| /^<w(?:e(?:b(?:\s[\s\S]*)?)?)?$/i.test(tail)
|
||||
|
||||
return isCitationPrefix ? content.slice(0, start) : content
|
||||
}
|
||||
|
||||
export type CitationKnowledgeRef = {
|
||||
id?: string
|
||||
knowledge_id?: string
|
||||
knowledge_title?: string
|
||||
knowledge_filename?: string
|
||||
chunk_index?: number
|
||||
chunk_type?: string
|
||||
knowledge_base_id?: string
|
||||
}
|
||||
|
||||
function parseTagAttributes(attrString: string): Record<string, string> {
|
||||
const attributes: Record<string, string> = {}
|
||||
if (!attrString) return attributes
|
||||
ATTRIBUTE_REGEX.lastIndex = 0
|
||||
let match: RegExpExecArray | null
|
||||
while ((match = ATTRIBUTE_REGEX.exec(attrString)) !== null) {
|
||||
attributes[match[1]] = match[2].replace(/&(amp|quot|apos|lt|gt|#39|#34);/g, (_, entity: string) =>
|
||||
({ amp: '&', quot: '"', apos: "'", lt: '<', gt: '>', '#39': "'", '#34': '"' })[entity] || _)
|
||||
}
|
||||
return attributes
|
||||
}
|
||||
|
||||
function escapeHtml(text: string): string {
|
||||
return String(text)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
}
|
||||
|
||||
function truncateMiddle(text: string, maxLength = 13): string {
|
||||
if (!text) return ''
|
||||
if (text.length <= maxLength) return text
|
||||
const half = Math.floor((maxLength - 3) / 2)
|
||||
const start = text.slice(0, half + ((maxLength - 3) % 2))
|
||||
const end = text.slice(-half)
|
||||
return `${start}...${end}`
|
||||
}
|
||||
|
||||
function normalizeDocTitle(title: string): string {
|
||||
return title.trim().toLowerCase()
|
||||
}
|
||||
|
||||
function docTitlesMatch(a: string, b: string): boolean {
|
||||
if (!a || !b) return false
|
||||
const na = normalizeDocTitle(a)
|
||||
const nb = normalizeDocTitle(b)
|
||||
return na === nb || na.includes(nb) || nb.includes(na)
|
||||
}
|
||||
|
||||
/** Map model context index (1, FAQ-1, DOC-2) to the real chunk UUID from retrieval results. */
|
||||
export function resolveCitationChunkId(
|
||||
rawChunkId: string,
|
||||
attrs: { doc?: string; kbId?: string },
|
||||
refs?: CitationKnowledgeRef[] | null,
|
||||
): string {
|
||||
const raw = String(rawChunkId || '').trim()
|
||||
if (!raw || UUID_RE.test(raw)) return raw
|
||||
|
||||
const list = (refs || []).filter((r) => r && r.chunk_type !== 'web_search')
|
||||
if (!list.length) return raw
|
||||
|
||||
const doc = (attrs.doc || '').trim()
|
||||
const kbId = (attrs.kbId || '').trim()
|
||||
|
||||
if (doc) {
|
||||
const byDoc = list.find(
|
||||
(r) =>
|
||||
docTitlesMatch(doc, r.knowledge_title || '') ||
|
||||
docTitlesMatch(doc, r.knowledge_filename || ''),
|
||||
)
|
||||
if (byDoc?.id) return byDoc.id
|
||||
}
|
||||
|
||||
const faqMatch = raw.match(/^FAQ-(\d+)$/i)
|
||||
if (faqMatch) {
|
||||
const faqRefs = list.filter((r) => r.chunk_type === 'faq')
|
||||
const hit = faqRefs[parseInt(faqMatch[1], 10) - 1]
|
||||
if (hit?.id) return hit.id
|
||||
}
|
||||
|
||||
const docMatch = raw.match(/^DOC-(\d+)$/i)
|
||||
if (docMatch) {
|
||||
const docRefs = list.filter((r) => r.chunk_type !== 'faq')
|
||||
const hit = docRefs[parseInt(docMatch[1], 10) - 1]
|
||||
if (hit?.id) return hit.id
|
||||
}
|
||||
|
||||
const num = parseInt(raw, 10)
|
||||
if (!Number.isNaN(num) && String(num) === raw) {
|
||||
const byPos = list[num - 1]
|
||||
if (byPos?.id) return byPos.id
|
||||
const byChunkIndex = list.find((r) => r.chunk_index === num || r.chunk_index === num - 1)
|
||||
if (byChunkIndex?.id) return byChunkIndex.id
|
||||
}
|
||||
|
||||
if (kbId) {
|
||||
const scoped = list.filter((r) => r.knowledge_base_id === kbId)
|
||||
if (doc) {
|
||||
const byDoc = scoped.find(
|
||||
(r) =>
|
||||
docTitlesMatch(doc, r.knowledge_title || '') ||
|
||||
docTitlesMatch(doc, r.knowledge_filename || ''),
|
||||
)
|
||||
if (byDoc?.id) return byDoc.id
|
||||
}
|
||||
if (scoped.length === 1 && scoped[0].id) return scoped[0].id
|
||||
}
|
||||
|
||||
return raw
|
||||
}
|
||||
|
||||
/** Convert <web/> / <kb/> / [[wiki]] tags into inline citation HTML. */
|
||||
export function preprocessCitationTags(
|
||||
contentStr: string,
|
||||
refs?: CitationKnowledgeRef[] | null,
|
||||
): string {
|
||||
if (!contentStr.trim()) return ''
|
||||
|
||||
return contentStr
|
||||
.replace(WEB_TAG_ATTR_RE, (_m, attrString: string) => {
|
||||
const attrs = parseTagAttributes(attrString)
|
||||
const url = attrs.url || ''
|
||||
const title = attrs.title || ''
|
||||
if (!url) return ''
|
||||
|
||||
let domain = url
|
||||
try {
|
||||
const u = new URL(url)
|
||||
const host = u.hostname || ''
|
||||
const parts = host.split('.')
|
||||
domain = parts.length >= 2 ? parts.slice(-2).join('.') : host || url
|
||||
} catch {
|
||||
// keep original
|
||||
}
|
||||
const safeTitle = escapeHtml(title)
|
||||
const safeUrl = escapeHtml(url)
|
||||
return `<a class="citation citation-web" data-url="${safeUrl}" href="${safeUrl}" target="_blank" rel="noopener noreferrer"><span class="citation-icon citation-icon--web" aria-hidden="true"></span><span class="citation-domain">${domain}</span><span class="citation-tip"><span class="tip-title">${safeTitle}</span><span class="tip-url">${safeUrl}</span></span></a>`
|
||||
})
|
||||
.replace(KB_TAG_ATTR_RE, (_m, attrString: string) => {
|
||||
const attrs = parseTagAttributes(attrString)
|
||||
const doc = attrs.doc || ''
|
||||
const rawChunkId = attrs.chunk_id || attrs.chunkId || ''
|
||||
const kbId = attrs.kb_id || attrs.kbId || ''
|
||||
const chunkId = resolveCitationChunkId(rawChunkId, { doc, kbId }, refs)
|
||||
if (!doc || !chunkId) return ''
|
||||
|
||||
const safeDoc = escapeHtml(doc)
|
||||
const safeKbId = escapeHtml(kbId)
|
||||
const safeChunkId = escapeHtml(chunkId)
|
||||
const displayDoc = escapeHtml(truncateMiddle(doc))
|
||||
return `<span class="citation citation-kb" data-kb-id="${safeKbId}" data-chunk-id="${safeChunkId}" data-doc="${safeDoc}" role="button" tabindex="0"><span class="citation-icon citation-icon--book" aria-hidden="true"></span><span class="citation-text">${displayDoc}</span><span class="citation-tip"><span class="tip-loading">…</span></span></span>`
|
||||
})
|
||||
.replace(/\[\[([^\]]+)\]\]/g, (match, inner: string) => {
|
||||
const pipeIdx = inner.indexOf('|')
|
||||
const slug = pipeIdx > 0 ? inner.substring(0, pipeIdx).trim() : inner.trim()
|
||||
if (!slug) return match
|
||||
let display = slug
|
||||
if (pipeIdx > 0) {
|
||||
display = inner.substring(pipeIdx + 1).trim()
|
||||
} else {
|
||||
const parts = slug.split('/')
|
||||
display = parts.length > 1 ? parts.slice(1).join('/') : slug
|
||||
}
|
||||
return `<a href="#" class="wiki-content-link citation-wiki" data-slug="${escapeHtml(slug)}">${escapeHtml(display)}</a>`
|
||||
})
|
||||
}
|
||||
|
||||
const HTML_PLACEHOLDER_RE = /@@WEKNORA_HTML_PLACEHOLDER_(\d+)@@/g
|
||||
|
||||
/** Protect citation HTML from markdown parser; restore after marked.parse. */
|
||||
export function extractCitationHtmlPlaceholders(
|
||||
contentStr: string,
|
||||
refs?: CitationKnowledgeRef[] | null,
|
||||
): { content: string; htmlSnippets: string[] } {
|
||||
const htmlSnippets: string[] = []
|
||||
const storeHtml = (html: string): string => {
|
||||
const idx = htmlSnippets.length
|
||||
htmlSnippets.push(html)
|
||||
return `@@WEKNORA_HTML_PLACEHOLDER_${idx}@@`
|
||||
}
|
||||
|
||||
const content = contentStr
|
||||
.replace(KB_WEB_TAG_RE, (match) => storeHtml(preprocessCitationTags(match, refs)))
|
||||
.replace(/\[\[([^\]]+)\]\]/g, (match) => storeHtml(preprocessCitationTags(match, refs)))
|
||||
|
||||
return { content, htmlSnippets }
|
||||
}
|
||||
|
||||
export function restoreCitationHtmlPlaceholders(html: string, htmlSnippets: string[]): string {
|
||||
if (!htmlSnippets.length) return html
|
||||
return html.replace(HTML_PLACEHOLDER_RE, (_match, idx) => htmlSnippets[Number(idx)] || '')
|
||||
}
|
||||
|
||||
/** Opening/closing fence for GFM fenced code blocks (up to 3 spaces indent). */
|
||||
const FENCED_CODE_DELIMITER_RE = /^ {0,3}(`{3,}|~{3,})(\s*\S.*)?\s*$/
|
||||
|
||||
function isFencedCodeDelimiterLine(line: string): boolean {
|
||||
return FENCED_CODE_DELIMITER_RE.test(line)
|
||||
}
|
||||
|
||||
/** Collapse newlines around <kb/> / <web/> so marked keeps citations inline. */
|
||||
export function joinCitationTagsToPreviousLine(content: string): string {
|
||||
if (!content) return content
|
||||
|
||||
let result = content
|
||||
|
||||
// Newlines between consecutive citation tags
|
||||
let prev = ''
|
||||
while (result !== prev) {
|
||||
prev = result
|
||||
result = result.replace(
|
||||
/(<(?:kb|web)\b[^>]*?\s*\/?>)\s*\n+\s*(<(?:kb|web)\b)/gi,
|
||||
'$1 $2',
|
||||
)
|
||||
}
|
||||
|
||||
// Blank lines before citations: join to the previous content. Fenced-code
|
||||
// delimiters are the only exception because ``` / ~~~ must stay on their own line.
|
||||
result = result.replace(/\n[ \t]*\n+([ \t]*<(?:kb|web)\b)/gi, (match, kbStart, offset, full) => {
|
||||
const before = full.slice(0, offset)
|
||||
const lastLine = before.split('\n').filter((line: string) => line.trim()).pop() || ''
|
||||
if (isFencedCodeDelimiterLine(lastLine)) {
|
||||
return `\n\n${kbStart}`
|
||||
}
|
||||
return ` ${kbStart.trimStart()}`
|
||||
})
|
||||
|
||||
// Single newline before citation when it follows text or another citation (not after a blank line)
|
||||
result = result.replace(
|
||||
/(?<!\n)(<(?:kb|web)\b[^>]*?\s*\/?>|[ \t]*\S[^\n]*?)\n([ \t]*<(?:kb|web)\b)/g,
|
||||
(match, beforePart: string, kbStart: string, offset: number, full: string) => {
|
||||
// Resolve the full preceding line: lazy capture + lookbehind can grab only a
|
||||
// partial line (e.g. ``` captured as ``), which would skip the fence check.
|
||||
const lineStart = full.lastIndexOf('\n', offset - 1) + 1
|
||||
const fullPrevLine = full.slice(lineStart, offset + beforePart.length)
|
||||
if (isFencedCodeDelimiterLine(fullPrevLine)) {
|
||||
return match
|
||||
}
|
||||
return `${beforePart} ${kbStart.trimStart()}`
|
||||
},
|
||||
)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
const CITATION_HTML_FRAGMENT =
|
||||
'(?:<span class="citation\\b[^]*?</span>|<a class="citation\\b[^]*?</a>)'
|
||||
|
||||
/** Merge citation-only <p> blocks into the preceding paragraph (marked splits on newlines). */
|
||||
export function collapseStandaloneCitationParagraphs(html: string): string {
|
||||
if (!html || !html.includes('citation')) return html
|
||||
|
||||
const mergePattern = new RegExp(
|
||||
`(<\\/(?:p|li)>)\\s*(?:<p>\\s*<\\/p>\\s*)*<p>\\s*(${CITATION_HTML_FRAGMENT})\\s*<\\/p>`,
|
||||
'g',
|
||||
)
|
||||
|
||||
let result = html
|
||||
let prev = ''
|
||||
while (result !== prev) {
|
||||
prev = result
|
||||
result = result.replace(mergePattern, (_match, closeTag: string, citation: string) => {
|
||||
return ` ${citation}${closeTag}`
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/** Preserve raw <kb>/<web> tags before sanitizers that would strip them. */
|
||||
export function preserveCitationTags(contentStr: string): { text: string; tags: string[] } {
|
||||
const tags: string[] = []
|
||||
const text = contentStr.replace(KB_WEB_TAG_RE, (match) => {
|
||||
const idx = tags.length
|
||||
tags.push(match)
|
||||
return `\x00TAG${idx}\x00`
|
||||
})
|
||||
return { text, tags }
|
||||
}
|
||||
|
||||
export function restoreCitationTags(text: string, tags: string[]): string {
|
||||
return text.replace(/\x00TAG(\d+)\x00/g, (_, idx) => tags[Number(idx)] || '')
|
||||
}
|
||||
|
||||
/** A line that holds nothing but `<kb/>` tags, including its line break. */
|
||||
const KB_ONLY_LINE_RE = /^[ \t]*(?:<kb\b[^>]*?\/?>[ \t]*)+\n?/gm
|
||||
/** An inline `<kb/>` tag together with the space that separated it from the text. */
|
||||
const KB_INLINE_TAG_RE = /[ \t]*<kb\b[^>]*?\s*\/?>/g
|
||||
|
||||
/**
|
||||
* Strip chat-only citation markup so an answer can live on as standalone
|
||||
* Markdown (e.g. saved into a knowledge base by "add to knowledge").
|
||||
*
|
||||
* `<web/>` becomes a plain Markdown link — the URL still means something
|
||||
* outside the chat. `<kb/>` points at chunk UUIDs that do not, so it is dropped
|
||||
* and its document name is returned instead, for the caller to render as a
|
||||
* source list. Removal stays local to the tags: no whitespace elsewhere in the
|
||||
* answer is touched, so code blocks survive unchanged.
|
||||
*/
|
||||
export function stripCitationTagsForMarkdown(
|
||||
content: string,
|
||||
): { text: string; sources: string[] } {
|
||||
if (!content) return { text: '', sources: [] }
|
||||
|
||||
const sources: string[] = []
|
||||
const seen = new Set<string>()
|
||||
KB_TAG_ATTR_RE.lastIndex = 0
|
||||
for (const match of content.matchAll(KB_TAG_ATTR_RE)) {
|
||||
const doc = (parseTagAttributes(match[1]).doc || '').trim()
|
||||
if (doc && !seen.has(doc)) {
|
||||
seen.add(doc)
|
||||
sources.push(doc)
|
||||
}
|
||||
}
|
||||
|
||||
const text = content
|
||||
.replace(WEB_TAG_ATTR_RE, (_match, attrString: string) => {
|
||||
const attrs = parseTagAttributes(attrString)
|
||||
const url = (attrs.url || '').trim()
|
||||
if (!url) return ''
|
||||
// Brackets inside the label would break the link syntax we emit.
|
||||
const label = (attrs.title || '').trim().replace(/[[\]]/g, ' ').trim() || url
|
||||
return `[${label}](${url})`
|
||||
})
|
||||
.replace(KB_ONLY_LINE_RE, '')
|
||||
.replace(KB_INLINE_TAG_RE, '')
|
||||
.trim()
|
||||
|
||||
return { text, sources }
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import i18n from '@/i18n'
|
||||
|
||||
/**
|
||||
* Copy text to the clipboard, falling back to a hidden textarea +
|
||||
* document.execCommand('copy') when the async Clipboard API is unavailable
|
||||
* (e.g. on non-secure HTTP origins) or rejects (e.g. permission denied).
|
||||
*
|
||||
* Returns true on success, false otherwise. This helper is UI-agnostic —
|
||||
* callers own any feedback. Use copyWithToast for the common "copy + toast"
|
||||
* case; call this directly when you need custom feedback (e.g. inline DOM
|
||||
* state) or none at all.
|
||||
*/
|
||||
export async function copyToClipboard(text: string): Promise<boolean> {
|
||||
if (!text) return false
|
||||
|
||||
// Prefer the async Clipboard API where available (HTTPS / localhost).
|
||||
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
return true
|
||||
} catch {
|
||||
// Fall through to the legacy path (e.g. permission denied).
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy fallback that also works on non-secure (HTTP) origins.
|
||||
try {
|
||||
const textArea = document.createElement('textarea')
|
||||
textArea.value = text
|
||||
textArea.style.position = 'fixed'
|
||||
textArea.style.top = '0'
|
||||
textArea.style.left = '0'
|
||||
textArea.style.opacity = '0'
|
||||
document.body.appendChild(textArea)
|
||||
textArea.focus()
|
||||
textArea.select()
|
||||
const ok = document.execCommand('copy')
|
||||
document.body.removeChild(textArea)
|
||||
return ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy text and surface the result via a toast. Returns the underlying
|
||||
* copyToClipboard result so callers can run extra side effects on success
|
||||
* (e.g. closing a dialog). Empty / null / undefined text is a silent no-op
|
||||
* (no toast), so callers can pass optional values (e.g. obj.value?.id)
|
||||
* without a separate guard. successKey is required; failureKey defaults to
|
||||
* the common message.
|
||||
*/
|
||||
export async function copyWithToast(
|
||||
text: string | null | undefined,
|
||||
successKey: string,
|
||||
failureKey: string = 'common.copyFailed',
|
||||
): Promise<boolean> {
|
||||
if (!text) return false
|
||||
const ok = await copyToClipboard(text)
|
||||
if (ok) {
|
||||
MessagePlugin.success(i18n.global.t(successKey))
|
||||
} else {
|
||||
MessagePlugin.error(i18n.global.t(failureKey))
|
||||
}
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { test } from 'node:test'
|
||||
import { collaborationTimeline, collaborationTasks, collaborationWaitState, withoutCollaborationWaits } from './collaborationDisplay'
|
||||
|
||||
test('parallel tasks retain separate identities and readable latest messages', () => {
|
||||
const tasks = collaborationTasks({ tasks: [
|
||||
{ id: 'a', name: 'research', status: 'running', latest_message: { content: 'Found evidence' }, progress: { phase: 'tool_running', tool_name: 'web_search' } },
|
||||
{ member_id: 'b', task_name: 'review', status: 'waiting', latest_message: { arbitrary: 'do not render JSON' } },
|
||||
] })
|
||||
assert.deepEqual(tasks.map(t => [t.id, t.name, t.status, t.latestMessage]), [['a','research','running','Found evidence'], ['b','review','waiting','']])
|
||||
assert.equal(tasks[0].progress?.tool_name, 'web_search')
|
||||
})
|
||||
test('wait polls fold without hiding actual progress or losing active wait', () => {
|
||||
const events = [
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', pending: false, output: '{"timed_out":true}' },
|
||||
{ type: 'progress', content: 'Review is still running' },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', pending: true },
|
||||
]
|
||||
assert.equal(collaborationWaitState(events), 'waiting')
|
||||
assert.equal(collaborationWaitState(events, true), 'finished')
|
||||
assert.deepEqual(withoutCollaborationWaits(events), [events[1]])
|
||||
assert.equal(collaborationWaitState([]), undefined)
|
||||
})
|
||||
test('cancellation and missing snapshots do not claim task completion', () => {
|
||||
assert.deepEqual(collaborationTasks(undefined), [])
|
||||
const tasks = collaborationTasks({ tasks: [{ id: 'a', status: 'running', cancel_requested: true }, { id: 'b', status: 'future-status' }] })
|
||||
assert.deepEqual(tasks.map(t => t.status), ['cancelling', 'unknown'])
|
||||
})
|
||||
|
||||
test('failed wait remains visible instead of becoming a successful wait summary', () => {
|
||||
assert.equal(collaborationWaitState([{ type: 'tool_call', tool_name: 'wait_agent', pending: false, success: false }]), 'failed')
|
||||
})
|
||||
|
||||
test('tool counts include calls represented by the task panel without mutating history', async () => {
|
||||
const { countToolCalls } = await import('./collaborationDisplay')
|
||||
const events = [
|
||||
{ type: 'tool_call', tool_name: 'spawn_agent', tool_call_id: 'spawn' },
|
||||
{ type: 'thinking', content: 'private reasoning' },
|
||||
{ type: 'progress', content: 'First progress' },
|
||||
{ type: 'tool_call', tool_name: 'list_agents', tool_call_id: 'list' },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', tool_call_id: 'wait-1' },
|
||||
{ type: 'progress', content: 'Latest progress' },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', tool_call_id: 'wait-2' },
|
||||
{ type: 'tool_approval_required', pending_id: 'one', resolved: false },
|
||||
{ type: 'agent_prompt_required', pending_id: 'two', resolved: false },
|
||||
{ type: 'tool_approval_required', pending_id: 'old', resolved: true },
|
||||
{ type: 'answer', content: 'Result' },
|
||||
]
|
||||
assert.equal(countToolCalls(events), 4)
|
||||
assert.equal(countToolCalls([...events, events[0]]), 4)
|
||||
assert.equal(events.filter(e => e.type === 'progress').length, 2, 'full history is untouched')
|
||||
})
|
||||
test('display name is distinct from the logical assignment name', () => {
|
||||
const [task] = collaborationTasks({ tasks: [{ id: 'id', name: 'review', display_name: '质量审核员', status: 'succeeded' }] })
|
||||
assert.equal(task.displayName, '质量审核员')
|
||||
assert.equal(task.name, 'review')
|
||||
})
|
||||
|
||||
test('child rows stay at spawn position and concurrent waits share one row', async () => {
|
||||
const { collaborationTimeline } = await import('./collaborationDisplay')
|
||||
const events = [
|
||||
{ type: 'progress', content: 'Starting' },
|
||||
{ type: 'tool_call', tool_name: 'spawn_agent', arguments: { task_name: 'a' } },
|
||||
{ type: 'tool_call', tool_name: 'spawn_agent', arguments: { task_name: 'b' } },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', pending: false },
|
||||
{ type: 'progress', content: 'Checking' },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', pending: true },
|
||||
]
|
||||
const snapshot = { tasks: [{ id: 'a', name: 'a', session_id: 'sa', run_id: 'ra', status: 'running' },
|
||||
{ id: 'b', name: 'b', session_id: 'sb', run_id: 'rb', status: 'waiting' }] }
|
||||
const result = collaborationTimeline(events, snapshot)
|
||||
assert.deepEqual(result.map(e => e.type), ['progress', 'child_task', 'child_task', 'progress'])
|
||||
assert.equal(result[1].task.sessionId, 'sa')
|
||||
assert.equal(result[2].task.sessionId, 'sb')
|
||||
assert.equal(result.filter(e => e.type === 'child_wait').length, 0, 'live waiting belongs at the response tail')
|
||||
const restored = collaborationTimeline([{ type: 'answer', content: 'Result' }], snapshot, true)
|
||||
assert.deepEqual(restored.map(e => e.type), ['child_task', 'child_task', 'answer'])
|
||||
})
|
||||
|
||||
|
||||
test('live waiting follows approval state and stops on cancellation, completion, or parent resumption', async () => {
|
||||
const { collaborationActivity, collaborationTimeline } = await import('./collaborationDisplay')
|
||||
const wait = { type: 'tool_call', tool_name: 'wait_agent', pending: true }
|
||||
const events: any[] = [{ ...wait, pending: false }, ...Array.from({ length: 60 }, () => ({ type: 'progress', content: 'progress' })), wait]
|
||||
const snapshot = { tasks: [{ id: 'a', status: 'running' }, { id: 'b', status: 'running' }] }
|
||||
assert.equal(collaborationActivity(events, snapshot), 'waiting')
|
||||
const prompt = { type: 'tool_approval_required', resolved: false }
|
||||
events.push(prompt)
|
||||
assert.equal(collaborationActivity(events, snapshot), 'approval')
|
||||
prompt.resolved = true
|
||||
assert.equal(collaborationActivity(events, snapshot), 'waiting')
|
||||
assert.equal(collaborationActivity(events, snapshot, true), undefined)
|
||||
assert.equal(collaborationActivity([...events, { type: 'stop' }], snapshot), undefined)
|
||||
assert.equal(collaborationActivity([...events, { type: 'agent_complete' }], snapshot), undefined)
|
||||
wait.pending = false
|
||||
assert.equal(collaborationActivity(events, snapshot), undefined, 'a running child alone does not mean its parent is waiting')
|
||||
const history = collaborationTimeline(events, snapshot, true)
|
||||
assert.equal(history.filter(e => e.type === 'child_wait' || e.tool_name === 'wait_agent').length, 0, 'completed polls are not user-facing milestones')
|
||||
})
|
||||
|
||||
|
||||
test('successful and timed-out waits disappear from history while real errors remain inspectable', async () => {
|
||||
const { collaborationTimeline } = await import('./collaborationDisplay')
|
||||
const completed = { type: 'tool_call', tool_name: 'wait_agent', pending: false, success: true, tool_data: { timed_out: true } }
|
||||
const failure = { ...completed, success: false, output: 'Connection failed' }
|
||||
assert.deepEqual(collaborationTimeline([completed], undefined, true), [])
|
||||
assert.deepEqual(collaborationTimeline([completed, failure], undefined, true), [failure])
|
||||
})
|
||||
|
||||
test('a continued child stays at its followup position in the new parent turn', () => {
|
||||
for (const target of ['child-id', 'novelist', '/root/novelist']) {
|
||||
const snapshot = { tasks: [{ id: 'child-id', name: 'novelist', session_id: 'original-session', run_id: 'new-run', status: 'running' }] }
|
||||
const events = [
|
||||
{ type: 'progress', content: '继续写第一章' },
|
||||
{ type: 'tool_call', tool_name: 'followup_task', arguments: { target }, success: true, timestamp: 'now' },
|
||||
{ type: 'thinking', content: 'Waiting for the chapter' },
|
||||
{ type: 'tool_call', tool_name: 'wait_agent', success: true },
|
||||
]
|
||||
const rows = collaborationTimeline(events, snapshot)
|
||||
assert.deepEqual(rows.map(row => row.type), ['progress', 'child_task', 'thinking'])
|
||||
assert.equal(rows[1].task.sessionId, 'original-session')
|
||||
assert.equal(rows[1].task.runId, 'new-run')
|
||||
assert.equal(rows[1].timestamp, 'now')
|
||||
events[1].success = false
|
||||
assert.ok(collaborationTimeline(events, snapshot).some(row => row.tool_name === 'followup_task'), 'failed continuation remains visible')
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
/** Presentation projection; never expose runtime IDs or raw tool payloads. */
|
||||
export interface CollaborationTaskView {
|
||||
id: string
|
||||
name: string
|
||||
sessionId: string
|
||||
runId: string
|
||||
displayName: string
|
||||
status: string
|
||||
progress?: { phase?: string; tool_name?: string; iteration?: number }
|
||||
latestMessage: string
|
||||
}
|
||||
const statuses = new Set(['queued', 'running', 'waiting', 'succeeded', 'failed', 'interrupted', 'cancelled', 'cancelling', 'needs_attention'])
|
||||
export function collaborationTasks(snapshot: unknown): CollaborationTaskView[] {
|
||||
const tasks = (snapshot as any)?.tasks
|
||||
if (!Array.isArray(tasks)) return []
|
||||
return tasks.filter((task: any) => task && typeof task === 'object').map((task: any, index: number) => {
|
||||
const latest = task.latest_message
|
||||
const message = typeof latest === 'string' ? latest : latest?.content ?? latest?.message
|
||||
return {
|
||||
id: String(task.id || task.member_id || task.name || task.task_name || index),
|
||||
name: String(task.name || task.task_name || ''),
|
||||
sessionId: String(task.session_id || ''),
|
||||
runId: String(task.run_id || ''),
|
||||
displayName: String(task.display_name || task.name || task.task_name || ''),
|
||||
status: task.cancel_requested && ['queued', 'running', 'waiting'].includes(task.status)
|
||||
? 'cancelling' : statuses.has(task.status) ? task.status : 'unknown',
|
||||
progress: task.progress && typeof task.progress === 'object' ? task.progress : undefined,
|
||||
latestMessage: typeof message === 'string' ? message : '',
|
||||
}
|
||||
})
|
||||
}
|
||||
export function collaborationWaitState(events: any[] = [], settled = false): 'waiting' | 'finished' | 'failed' | undefined {
|
||||
const waits = events.filter(event => event?.type === 'tool_call' && event.tool_name === 'wait_agent')
|
||||
if (!waits.length) return undefined
|
||||
if (!settled && waits.some(event => event.pending && !event.canceled)) return 'waiting'
|
||||
return waits[waits.length - 1].success === false ? 'failed' : 'finished'
|
||||
}
|
||||
/** Current activity belongs at the live response tail, not the first wait call. */
|
||||
export function collaborationActivity(events: any[], snapshot: unknown, settled = false): 'waiting' | 'approval' | undefined {
|
||||
if (settled || events.some(event => event?.type === 'stop' || event?.type === 'agent_complete')) return undefined
|
||||
if (collaborationWaitState(events) !== 'waiting') return undefined
|
||||
return events.some(isUnresolvedCollaborationPrompt) || collaborationTasks(snapshot).some(task => task.status === 'waiting')
|
||||
? 'approval' : 'waiting'
|
||||
}
|
||||
/** All wait polls share the task panel; they must not multiply timeline rows. */
|
||||
export function withoutCollaborationWaits(events: any[]): any[] {
|
||||
return events.filter(event => !(event?.type === 'tool_call' && event.tool_name === 'wait_agent'))
|
||||
}
|
||||
|
||||
export function isCollaborationTaskActive(status: string): boolean {
|
||||
return ['queued', 'running', 'waiting', 'cancelling'].includes(status)
|
||||
}
|
||||
export function isUnresolvedCollaborationPrompt(event: any): boolean {
|
||||
return ['tool_approval_required', 'agent_prompt_required', 'mcp_oauth_required'].includes(event?.type)
|
||||
&& !event.resolved && !event.canceled && !event.abandoned
|
||||
}
|
||||
/** Count the actual calls, including calls represented by the task panel. */
|
||||
export function countToolCalls(events: any[]): number {
|
||||
const calls = events.filter(event => event?.type === 'tool_call')
|
||||
const ids = new Set(calls.map(event => event.tool_call_id).filter(Boolean))
|
||||
return ids.size + calls.filter(event => !event.tool_call_id).length
|
||||
}
|
||||
|
||||
/** Keep child rows at their spawn/continuation location, including restored snapshots. */
|
||||
export function collaborationTimeline(events: any[], snapshot: unknown, settled = false): any[] {
|
||||
const tasks = collaborationTasks(snapshot)
|
||||
const seen = new Set<string>()
|
||||
const result: any[] = []
|
||||
const waitState = collaborationWaitState(events, settled)
|
||||
const lastWait = events.filter(event => event?.type === 'tool_call' && event.tool_name === 'wait_agent').at(-1)
|
||||
for (const event of events) {
|
||||
if (event.type === 'tool_call' && (event.tool_name === 'spawn_agent'
|
||||
|| (event.tool_name === 'followup_task' && event.success !== false && !event.canceled))) {
|
||||
const target = event.arguments?.target
|
||||
const task = tasks.find(t => event.tool_name === 'followup_task'
|
||||
? t.id === target || t.name === target || `/root/${t.name}` === target
|
||||
: t.id === event.tool_data?.member_id
|
||||
|| t.name === event.arguments?.task_name || t.name === event.arguments?.name)
|
||||
if (task) {
|
||||
if (!seen.has(task.id)) result.push({ type: 'child_task', event_id: `child-${task.id}`, task, timestamp: event.timestamp })
|
||||
seen.add(task.id)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (tasks.length && event.type === 'tool_call' && event.tool_name === 'list_agents') continue
|
||||
if (event.type === 'tool_call' && event.tool_name === 'wait_agent') {
|
||||
// Successful polls (including timeouts) are plumbing, not milestones.
|
||||
// Preserve an actual failure in the normal tool row for inspection.
|
||||
if (event === lastWait && waitState === 'failed') result.push(event)
|
||||
continue
|
||||
}
|
||||
result.push(event)
|
||||
}
|
||||
// A restored segment may lack the original spawn calls. Keep orphan rows in
|
||||
// the transcript before its answer, never in a separate top status panel.
|
||||
const missing = tasks.filter(t => !seen.has(t.id)).map(task => ({ type: 'child_task', event_id: `child-${task.id}`, task }))
|
||||
const answer = result.findIndex(e => e.type === 'answer' && !e.superseded)
|
||||
result.splice(answer < 0 ? result.length : answer, 0, ...missing)
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
DEFAULT_MODEL_CONTEXT_WINDOW,
|
||||
effectiveContextWindow,
|
||||
formatContextWindow,
|
||||
formatTokenCount,
|
||||
isDefaultContextWindow,
|
||||
modelHasContextWindow,
|
||||
} from './contextWindow.ts'
|
||||
|
||||
test('effectiveContextWindow falls back to 200K', () => {
|
||||
assert.equal(effectiveContextWindow(undefined), DEFAULT_MODEL_CONTEXT_WINDOW)
|
||||
assert.equal(effectiveContextWindow(0), DEFAULT_MODEL_CONTEXT_WINDOW)
|
||||
assert.equal(effectiveContextWindow(256000), 256000)
|
||||
})
|
||||
|
||||
test('formatTokenCount uses K/M for round thousands', () => {
|
||||
assert.equal(formatTokenCount(128000), '128K')
|
||||
assert.equal(formatTokenCount(200000), '200K')
|
||||
assert.equal(formatTokenCount(131072), '128K')
|
||||
assert.equal(formatTokenCount(1_000_000), '1M')
|
||||
assert.equal(formatTokenCount(1048576), '1M')
|
||||
assert.equal(formatTokenCount(8192), '8K')
|
||||
})
|
||||
|
||||
test('formatContextWindow uses the default when unset', () => {
|
||||
assert.equal(formatContextWindow(undefined), '200K')
|
||||
assert.equal(formatContextWindow(128000), '128K')
|
||||
})
|
||||
|
||||
test('modelHasContextWindow is chat and VLM only', () => {
|
||||
assert.equal(modelHasContextWindow('KnowledgeQA'), true)
|
||||
assert.equal(modelHasContextWindow('VLLM'), true)
|
||||
assert.equal(modelHasContextWindow('chat'), true)
|
||||
assert.equal(modelHasContextWindow('Embedding'), false)
|
||||
assert.equal(modelHasContextWindow('Rerank'), false)
|
||||
assert.equal(isDefaultContextWindow(0), true)
|
||||
assert.equal(isDefaultContextWindow(200000), false)
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
/** Matches internal/types.DefaultMaxContextTokens. */
|
||||
export const DEFAULT_MODEL_CONTEXT_WINDOW = 200000
|
||||
|
||||
export function modelHasContextWindow(type?: string): boolean {
|
||||
return type === 'KnowledgeQA' || type === 'VLLM' || type === 'chat' || type === 'vllm'
|
||||
}
|
||||
|
||||
/** Tokens the backend will actually use: the model's value, or 200K. */
|
||||
export function effectiveContextWindow(tokens?: number | null): number {
|
||||
if (typeof tokens === 'number' && tokens > 0) {
|
||||
return tokens
|
||||
}
|
||||
return DEFAULT_MODEL_CONTEXT_WINDOW
|
||||
}
|
||||
|
||||
export function isDefaultContextWindow(tokens?: number | null): boolean {
|
||||
return !(typeof tokens === 'number' && tokens > 0)
|
||||
}
|
||||
|
||||
/** Compact label: 128000 → 128K, 200000 → 200K, 1048576 → 1M. */
|
||||
export function formatTokenCount(tokens: number): string {
|
||||
if (!Number.isFinite(tokens) || tokens <= 0) {
|
||||
return ''
|
||||
}
|
||||
const n = Math.round(tokens)
|
||||
if (n >= 1_000_000 && n % 1_000_000 === 0) {
|
||||
return `${n / 1_000_000}M`
|
||||
}
|
||||
if (n >= 1000 && n % 1000 === 0) {
|
||||
return `${n / 1000}K`
|
||||
}
|
||||
if (n >= 1024 && n % 1024 === 0) {
|
||||
const k = n / 1024
|
||||
if (k >= 1024 && k % 1024 === 0) {
|
||||
return `${k / 1024}M`
|
||||
}
|
||||
return `${k}K`
|
||||
}
|
||||
return String(n)
|
||||
}
|
||||
|
||||
export function formatContextWindow(tokens?: number | null): string {
|
||||
return formatTokenCount(effectiveContextWindow(tokens))
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// cronHumanize maps known cron schedule presets to human-readable i18n keys.
|
||||
// Falls back to the raw cron expression for unknown patterns.
|
||||
|
||||
const CRON_PRESET_MAP: Record<string, string> = {
|
||||
'0 */30 * * * *': 'datasource.scheduleHuman.30min',
|
||||
'0 0 * * * *': 'datasource.scheduleHuman.1h',
|
||||
'0 0 */6 * * *': 'datasource.scheduleHuman.6h',
|
||||
'0 0 */12 * * *': 'datasource.scheduleHuman.12h',
|
||||
'0 0 2 * * *': 'datasource.scheduleHuman.24h',
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a cron expression to a human-readable string.
|
||||
* Uses i18n translate function for known presets, raw expression otherwise.
|
||||
*/
|
||||
export function humanizeCron(cron: string, t: (key: string) => string): string {
|
||||
const key = CRON_PRESET_MAP[cron]
|
||||
if (key) return t(key)
|
||||
return cron || '--'
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a timestamp as relative time (e.g. "3小时前", "2天前").
|
||||
* Falls back to locale date string for timestamps older than 30 days.
|
||||
*/
|
||||
export function relativeTime(ts: string | null, t: (key: string, params?: Record<string, string | number>) => string): string {
|
||||
if (!ts) return t('datasource.neverSynced')
|
||||
const then = new Date(ts).getTime()
|
||||
if (isNaN(then)) return t('datasource.neverSynced')
|
||||
const now = Date.now()
|
||||
const diffMs = now - then
|
||||
|
||||
// Future time or just happened (within 60s)
|
||||
if (diffMs < 60000) return t('datasource.justNow')
|
||||
|
||||
const minutes = Math.floor(diffMs / 60000)
|
||||
if (minutes < 60) return t('datasource.minutesAgo', { n: minutes })
|
||||
|
||||
const hours = Math.floor(diffMs / 3600000)
|
||||
if (hours < 24) return t('datasource.hoursAgo', { n: hours })
|
||||
|
||||
const days = Math.floor(diffMs / 86400000)
|
||||
if (days < 30) return t('datasource.daysAgo', { n: days })
|
||||
|
||||
return new Date(ts).toLocaleDateString()
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// 统一时间展示口径:全部按北京时间(Asia/Shanghai)格式化,页面展示不带秒。
|
||||
// 后端时间戳带原时区偏移,new Date 均可正确解析,再统一投到北京时区输出。
|
||||
const BEIJING_DATETIME = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
})
|
||||
|
||||
const BEIJING_CLOCK = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
})
|
||||
|
||||
/** fmtBeijingTime 任意时间戳 → 北京时间「YYYY/MM/DD HH:mm」(无秒);空/非法输入返回空串。 */
|
||||
export function fmtBeijingTime(raw: string | number | Date | null | undefined): string {
|
||||
if (raw === null || raw === undefined || raw === '') return ''
|
||||
const date = raw instanceof Date ? raw : new Date(raw)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
return BEIJING_DATETIME.format(date)
|
||||
}
|
||||
|
||||
/** fmtBeijingClock 北京时间「HH:mm」(无秒),通知横幅等紧凑场景用。 */
|
||||
export function fmtBeijingClock(raw: string | number | Date | null | undefined): string {
|
||||
if (raw === null || raw === undefined || raw === '') return ''
|
||||
const date = raw instanceof Date ? raw : new Date(raw)
|
||||
if (Number.isNaN(date.getTime())) return ''
|
||||
return BEIJING_CLOCK.format(date)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
|
||||
const source = readFileSync(new URL('./desktopProjectDir.ts', import.meta.url), 'utf8')
|
||||
|
||||
test('dirFromPickerResponse reads the HTTP envelope', () => {
|
||||
assert.match(source, /body\?\.data\?\.dir/)
|
||||
assert.match(source, /typeof dir === 'string'/)
|
||||
})
|
||||
|
||||
test('pickHostProjectDir calls the same-process HTTP picker', () => {
|
||||
assert.match(source, /\/api\/v1\/system\/host-project-dir/)
|
||||
assert.match(source, /timeout: 0/)
|
||||
assert.doesNotMatch(source, /window\['go'\]/)
|
||||
assert.doesNotMatch(source, /window\.go\.main/)
|
||||
assert.doesNotMatch(source, /EventsEmit/)
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { post } from '@/utils/request'
|
||||
|
||||
export function dirFromPickerResponse(body: { data?: { dir?: unknown } } | null | undefined): string {
|
||||
const dir = body?.data?.dir
|
||||
return typeof dir === 'string' ? dir.trim() : ''
|
||||
}
|
||||
|
||||
// Lite's SPA is reverse-proxied; Wails JS bindings are not injected. The
|
||||
// folder picker is a same-process HTTP call that opens the native dialog.
|
||||
export async function pickHostProjectDir(): Promise<string> {
|
||||
const res = await post<{ data?: { dir?: unknown } }>('/api/v1/system/host-project-dir', {}, { timeout: 0 })
|
||||
return dirFromPickerResponse(res)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Globally discourage browser/password-manager autofill on app inputs.
|
||||
* Skips elements that already declare autocomplete (e.g. login email).
|
||||
*/
|
||||
function guardElement(el: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement) {
|
||||
const explicit = el.getAttribute('autocomplete');
|
||||
if (explicit !== null && explicit !== '') return;
|
||||
if (el.closest('[data-allow-autofill]')) return;
|
||||
|
||||
if (el instanceof HTMLInputElement && el.type === 'password') {
|
||||
el.setAttribute('autocomplete', 'new-password');
|
||||
} else {
|
||||
el.setAttribute('autocomplete', 'off');
|
||||
}
|
||||
}
|
||||
|
||||
function guardTree(root: ParentNode) {
|
||||
if (root instanceof HTMLInputElement || root instanceof HTMLTextAreaElement || root instanceof HTMLSelectElement) {
|
||||
guardElement(root);
|
||||
}
|
||||
|
||||
root.querySelectorAll?.('input, textarea, select').forEach((node) => {
|
||||
guardElement(node as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement);
|
||||
});
|
||||
|
||||
root.querySelectorAll?.('form').forEach((form) => {
|
||||
if (!form.hasAttribute('autocomplete')) {
|
||||
form.setAttribute('autocomplete', 'off');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let installed = false;
|
||||
|
||||
export function installAutofillGuard() {
|
||||
if (installed || typeof document === 'undefined') return;
|
||||
installed = true;
|
||||
|
||||
guardTree(document);
|
||||
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
for (const mutation of mutations) {
|
||||
mutation.addedNodes.forEach((node) => {
|
||||
if (node instanceof HTMLElement) {
|
||||
guardTree(node);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
observer.observe(document.body, { childList: true, subtree: true });
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { strict as assert } from 'node:assert'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { test } from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { DOC_PAGES, docsUrl } from './docsUrl'
|
||||
|
||||
const WEBSITE_DOCS = resolve(dirname(fileURLToPath(import.meta.url)), '../../../website-docs')
|
||||
|
||||
// VitePress default slugify for the headings we link to: explicit `{#id}`
|
||||
// wins, otherwise lowercase with whitespace and punctuation collapsed to `-`.
|
||||
function headingIds(markdown: string): Set<string> {
|
||||
const ids = new Set<string>()
|
||||
for (const line of markdown.split('\n')) {
|
||||
const m = /^#{1,6}\s+(.*?)\s*$/.exec(line)
|
||||
if (!m) continue
|
||||
const explicit = /\{#([^}]+)\}$/.exec(m[1])
|
||||
if (explicit) {
|
||||
ids.add(explicit[1])
|
||||
continue
|
||||
}
|
||||
ids.add(
|
||||
m[1]
|
||||
.toLowerCase()
|
||||
.replace(/[\s~`!@#$%^&*()+=[\]{}|\\;:'",.<>/?]+/g, '-')
|
||||
.replace(/^-+|-+$/g, ''),
|
||||
)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
test('every linked doc page and anchor exists in website-docs', () => {
|
||||
for (const [key, target] of Object.entries(DOC_PAGES)) {
|
||||
const [page, anchor] = target.split('#')
|
||||
const file = resolve(WEBSITE_DOCS, page ? `${page}.md` : 'index.md')
|
||||
assert.ok(existsSync(file), `${key}: ${file} not found`)
|
||||
if (anchor) {
|
||||
assert.ok(headingIds(readFileSync(file, 'utf8')).has(anchor), `${key}: #${anchor} not found in ${file}`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('docsUrl points at the public docs site', () => {
|
||||
assert.equal(docsUrl('home'), 'https://weknora.weixin.qq.com/docs/')
|
||||
assert.equal(docsUrl('models'), 'https://weknora.weixin.qq.com/docs/03-features/06-models')
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
/** Public deployment of website-docs (VitePress, base `/docs/`). */
|
||||
export const DOCS_BASE_URL = 'https://weknora.weixin.qq.com/docs/'
|
||||
|
||||
/**
|
||||
* Doc pages linked from the UI, as website-docs paths without the `.md`
|
||||
* suffix. docsUrl.test.ts checks each one (and its anchor) still exists.
|
||||
*/
|
||||
export const DOC_PAGES = {
|
||||
home: '',
|
||||
tenantAuth: '03-features/01-tenant-auth',
|
||||
models: '03-features/06-models',
|
||||
modelsCompat: '03-features/06-models#协议兼容覆盖-compat-json',
|
||||
knowledgeGraph: '03-features/09-knowledge-graph',
|
||||
imIntegration: '03-features/12-im-integration',
|
||||
apiOverview: '04-api/01-api-overview',
|
||||
troubleshootingMigrations: '01-getting-started/05-troubleshooting#database-migrations',
|
||||
sandboxDeployment: '06-development/04-sandbox-deployment',
|
||||
} as const
|
||||
|
||||
export type DocPage = keyof typeof DOC_PAGES
|
||||
|
||||
export function docsUrl(page: DocPage): string {
|
||||
return DOCS_BASE_URL + DOC_PAGES[page]
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
isSafePreviewImageHref,
|
||||
renderDocumentPreviewMarkdown,
|
||||
} from './documentPreviewMarkdown.ts'
|
||||
import { applyDocumentPreviewImageAttributes } from './security.ts'
|
||||
|
||||
test('preview Markdown keeps native lazy image attributes', () => {
|
||||
const html = renderDocumentPreviewMarkdown('', value => value)
|
||||
|
||||
assert.match(html, /src="https:\/\/example.com\/test.png"/)
|
||||
assert.match(html, /loading="lazy"/)
|
||||
assert.match(html, /decoding="async"/)
|
||||
assert.match(html, /fetchpriority="low"/)
|
||||
})
|
||||
|
||||
test('preview Markdown keeps data URI images used by document parsers', () => {
|
||||
const html = renderDocumentPreviewMarkdown(
|
||||
'',
|
||||
value => value,
|
||||
)
|
||||
|
||||
assert.match(html, /src="data:image\/png;base64,AAAA"/)
|
||||
assert.match(html, /loading="lazy"/)
|
||||
})
|
||||
|
||||
test('preview Markdown keeps relative and protocol-relative images', () => {
|
||||
const relative = renderDocumentPreviewMarkdown('', value => value)
|
||||
const protocolRelative = renderDocumentPreviewMarkdown(
|
||||
'',
|
||||
value => value,
|
||||
)
|
||||
|
||||
assert.match(relative, /src="images\/a.png"/)
|
||||
assert.match(protocolRelative, /src="\/\/cdn.example.com\/a.png"/)
|
||||
})
|
||||
|
||||
test('preview Markdown drops javascript image URLs', () => {
|
||||
const html = renderDocumentPreviewMarkdown(')', value => value)
|
||||
|
||||
assert.doesNotMatch(html, /javascript:/i)
|
||||
assert.doesNotMatch(html, /<img/i)
|
||||
})
|
||||
|
||||
test('isSafePreviewImageHref matches the shared DOMPurify image URI policy', () => {
|
||||
assert.equal(isSafePreviewImageHref('https://example.com/a.png'), true)
|
||||
assert.equal(isSafePreviewImageHref('data:image/png;base64,AAAA'), true)
|
||||
assert.equal(isSafePreviewImageHref('resource://AbCdEfGhIjKlMnOpQrStUv'), true)
|
||||
assert.equal(isSafePreviewImageHref('/files/a.png'), true)
|
||||
assert.equal(isSafePreviewImageHref('images/a.png'), true)
|
||||
assert.equal(isSafePreviewImageHref('//cdn.example.com/a.png'), true)
|
||||
assert.equal(isSafePreviewImageHref('javascript:alert(1)'), false)
|
||||
assert.equal(isSafePreviewImageHref('data:text/html,<script>alert(1)</script>'), false)
|
||||
assert.equal(isSafePreviewImageHref('#fragment'), false)
|
||||
})
|
||||
|
||||
test('preview Markdown keeps the marked-katex extension when using an image renderer', () => {
|
||||
const html = renderDocumentPreviewMarkdown('公式 $E = mc^2$', value => value)
|
||||
|
||||
assert.match(html, /katex/)
|
||||
})
|
||||
|
||||
test('preview Markdown skips highlightAuto on huge unlabeled fences', () => {
|
||||
const source = 'a'.repeat(40_000)
|
||||
const html = renderDocumentPreviewMarkdown('```\n' + source + '\n```', value => value)
|
||||
|
||||
assert.match(html, /<pre><code class="hljs">/)
|
||||
assert.equal(html.includes(`>${source}<`), true)
|
||||
assert.doesNotMatch(html, /hljs-/)
|
||||
})
|
||||
|
||||
test('raw HTML images cannot override preview loading attributes', () => {
|
||||
const attributes = new Map([
|
||||
['alt', 'score > 90'],
|
||||
['title', 'A > B'],
|
||||
['loading', 'eager'],
|
||||
['fetchpriority', 'high'],
|
||||
])
|
||||
const image = {
|
||||
tagName: 'IMG',
|
||||
setAttribute: (name: string, value: string) => attributes.set(name, value),
|
||||
}
|
||||
applyDocumentPreviewImageAttributes(image as unknown as Node)
|
||||
assert.equal(attributes.get('alt'), 'score > 90')
|
||||
assert.equal(attributes.get('title'), 'A > B')
|
||||
assert.equal(attributes.get('loading'), 'lazy')
|
||||
assert.equal(attributes.get('decoding'), 'async')
|
||||
assert.equal(attributes.get('fetchpriority'), 'low')
|
||||
})
|
||||
|
||||
// GFM task lists must survive the preview pipeline as sanitizer-safe spans:
|
||||
// marked's default <input type="checkbox"> is stripped by the DOMPurify tag
|
||||
// allowlist, which degraded "- [x] 任务" to a plain bullet.
|
||||
test('task list items render styled checkbox spans, checked and unchecked', () => {
|
||||
const html = renderDocumentPreviewMarkdown(
|
||||
'- [x] 任务1\n\n- [ ] 任务2\n',
|
||||
value => value,
|
||||
)
|
||||
|
||||
assert.match(html, /<span class="task-checkbox checked"><\/span>任务1/)
|
||||
assert.match(html, /<span class="task-checkbox"><\/span>任务2/)
|
||||
assert.ok(!html.includes('<input'), 'no raw checkbox input may be emitted')
|
||||
})
|
||||
|
||||
test('plain bullets are not affected by the task checkbox override', () => {
|
||||
const html = renderDocumentPreviewMarkdown('- 普通项\n', value => value)
|
||||
|
||||
assert.match(html, /<li>普通项<\/li>/)
|
||||
assert.ok(!html.includes('task-checkbox'))
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import hljs from 'highlight.js'
|
||||
import { Marked, Renderer } from 'marked'
|
||||
import markedKatex from 'marked-katex-extension'
|
||||
|
||||
import { domPurifyAllowedUriRegexp } from './markdownDomPurify.ts'
|
||||
import { literalSingleTildeExtension } from './markedLiteralTilde.ts'
|
||||
import { escapeHTML, safeMarkdownToHTML, sanitizeDocumentPreviewHTML } from './security.ts'
|
||||
|
||||
const PREVIEW_IMAGE_ATTRIBUTES = 'loading="lazy" decoding="async" fetchpriority="low"'
|
||||
const HIGHLIGHT_AUTO_MAX_CHARS = 32_768
|
||||
|
||||
export function isSafePreviewImageHref(href: unknown): href is string {
|
||||
if (typeof href !== 'string') return false
|
||||
const trimmed = href.trim()
|
||||
if (!trimmed || trimmed.startsWith('#')) return false
|
||||
return domPurifyAllowedUriRegexp.test(trimmed)
|
||||
}
|
||||
|
||||
function highlightPreviewCode(source: string, lang?: string): string {
|
||||
if (lang && hljs.getLanguage(lang)) {
|
||||
try {
|
||||
return hljs.highlight(source, { language: lang }).value
|
||||
} catch {
|
||||
// Fall through to auto-detect or plain text.
|
||||
}
|
||||
}
|
||||
if (source.length > HIGHLIGHT_AUTO_MAX_CHARS) {
|
||||
return escapeHTML(source)
|
||||
}
|
||||
return hljs.highlightAuto(source).value
|
||||
}
|
||||
|
||||
function createPreviewMarkdownRenderer(): Renderer {
|
||||
const renderer = new Renderer()
|
||||
// GFM task lists: marked emits <input type="checkbox">, which the DOMPurify
|
||||
// tag allowlist strips (leaving a plain bullet) — render a styled span.
|
||||
renderer.checkbox = ({ checked }) =>
|
||||
`<span class="task-checkbox${checked ? ' checked' : ''}"></span>`
|
||||
renderer.image = ({ href, title, text }) => {
|
||||
if (!isSafePreviewImageHref(href)) return ''
|
||||
const safeHref = href.trim().replace(/"/g, '"')
|
||||
const safeTitle = title ? ` title="${escapeHTML(title)}"` : ''
|
||||
return `<img src="${safeHref}" alt="${escapeHTML(text || '')}"${safeTitle} class="markdown-image" ${PREVIEW_IMAGE_ATTRIBUTES}>`
|
||||
}
|
||||
renderer.code = ({ text, lang }) => {
|
||||
const source = typeof text === 'string' ? text : ''
|
||||
return `<pre><code class="hljs">${highlightPreviewCode(source, lang)}</code></pre>`
|
||||
}
|
||||
return renderer
|
||||
}
|
||||
|
||||
const previewMarked = new Marked({
|
||||
breaks: true,
|
||||
gfm: true,
|
||||
renderer: createPreviewMarkdownRenderer(),
|
||||
})
|
||||
previewMarked.use(markedKatex({ throwOnError: false, nonStandard: true }))
|
||||
previewMarked.use(literalSingleTildeExtension)
|
||||
|
||||
function preprocessMathDelimiters(rawText: string): string {
|
||||
if (!rawText || typeof rawText !== 'string') return ''
|
||||
return rawText
|
||||
.replace(/\\\[([\s\S]*?)\\\]/g, '$$$$$1$$$$')
|
||||
.replace(/\\\(([\s\S]*?)\\\)/g, '$$$1$$')
|
||||
}
|
||||
|
||||
export function renderDocumentPreviewMarkdown(
|
||||
markdown: string,
|
||||
sanitize: (html: string) => string = sanitizeDocumentPreviewHTML,
|
||||
): string {
|
||||
const mathSafe = preprocessMathDelimiters(markdown)
|
||||
return sanitize(previewMarked.parse(safeMarkdownToHTML(mathSafe)) as string)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { strict as assert } from 'node:assert'
|
||||
import { test } from 'node:test'
|
||||
import { validateAllowedOrigins } from './embedAllowedOrigins'
|
||||
|
||||
test('accepts host origins, ports, trailing slash and subdomain patterns', () => {
|
||||
for (const origin of ['https://shop.example.com', 'http://localhost:8080', 'https://shop.example.com/', '*.example.com', '*.example.com:8443']) {
|
||||
assert.equal(validateAllowedOrigins([origin], true).ok, true, origin)
|
||||
}
|
||||
})
|
||||
|
||||
test('rejects URLs that cannot be used as origin/CSP sources', () => {
|
||||
for (const origin of ['https://shop.example.com/path', 'https://user@shop.example.com', 'https://shop.example.com?q=1', 'https://shop.example.com#', 'https://shop.example.com;', 'https://shop.example.com; frame-ancestors *', 'https://*', 'https://shop.example.com/../']) {
|
||||
assert.equal(validateAllowedOrigins([origin], true).ok, false, origin)
|
||||
}
|
||||
assert.equal(validateAllowedOrigins([], true).ok, false)
|
||||
assert.equal(validateAllowedOrigins(['*'], true).ok, false)
|
||||
assert.equal(validateAllowedOrigins(['*'], false).ok, true)
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
export type AllowedOriginsValidationError =
|
||||
| { code: 'required' }
|
||||
| { code: 'wildcard_prod' }
|
||||
| { code: 'invalid'; origin: string }
|
||||
|
||||
/** Mirrors backend validateAllowedOrigins in internal/handler/embed_channel.go */
|
||||
export function parseAllowedOrigins(text: string): string[] {
|
||||
return text
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
export function validateAllowedOrigins(
|
||||
origins: string[],
|
||||
prod = import.meta.env?.PROD ?? false,
|
||||
): { ok: true; origins: string[] } | { ok: false; error: AllowedOriginsValidationError } {
|
||||
const cleaned = parseAllowedOrigins(origins.join('\n'))
|
||||
if (cleaned.length === 0) {
|
||||
return { ok: false, error: { code: 'required' } }
|
||||
}
|
||||
for (const origin of cleaned) {
|
||||
if (origin === '*') {
|
||||
if (prod) {
|
||||
return { ok: false, error: { code: 'wildcard_prod' } }
|
||||
}
|
||||
continue
|
||||
}
|
||||
let host = origin
|
||||
if (origin.startsWith('*.')) {
|
||||
host = `https://${origin.slice(2)}`
|
||||
}
|
||||
try {
|
||||
if (!/^https?:\/\/[^/?#\\\s]+\/?$/i.test(host)) {
|
||||
return { ok: false, error: { code: 'invalid', origin } }
|
||||
}
|
||||
const url = new URL(host)
|
||||
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || !url.host ||
|
||||
url.username || url.password || (url.pathname !== '' && url.pathname !== '/') ||
|
||||
host.includes('?') || host.includes('#') || /[\s'";,*\\]/.test(url.host)) {
|
||||
return { ok: false, error: { code: 'invalid', origin } }
|
||||
}
|
||||
} catch {
|
||||
return { ok: false, error: { code: 'invalid', origin } }
|
||||
}
|
||||
}
|
||||
return { ok: true, origins: cleaned }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/** Resolve the public origin used in embed iframe / widget URLs. */
|
||||
export function resolveEmbedBaseUrl(): string {
|
||||
if (typeof window === 'undefined') return ''
|
||||
const runtime = (window as Window & { __RUNTIME_CONFIG__?: { EMBED_BASE_URL?: string } }).__RUNTIME_CONFIG__
|
||||
const fromRuntime = runtime?.EMBED_BASE_URL?.trim()
|
||||
if (fromRuntime) {
|
||||
try {
|
||||
const u = new URL(fromRuntime, window.location.href)
|
||||
if (u.protocol === 'http:' || u.protocol === 'https:') return u.origin
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
}
|
||||
const fromEnv = import.meta.env.VITE_EMBED_BASE_URL?.trim()
|
||||
if (fromEnv) {
|
||||
try {
|
||||
const u = new URL(fromEnv, window.location.href)
|
||||
if (u.protocol === 'http:' || u.protocol === 'https:') return u.origin
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
}
|
||||
return window.location.origin
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { buildQueryWithHostContext, stripHostContextFromQuery } from './embedContext.ts'
|
||||
|
||||
test('strips injected host context from persisted user messages without changing the query', () => {
|
||||
const query = '我的userId是多少'
|
||||
const outboundQuery = buildQueryWithHostContext(query, { userId: '21', page: '/ai-agent' })
|
||||
|
||||
assert.equal(
|
||||
outboundQuery,
|
||||
`[Host context]\nuserId: 21\npage: /ai-agent\n\n${query}`,
|
||||
)
|
||||
assert.equal(stripHostContextFromQuery(outboundQuery), query)
|
||||
})
|
||||
|
||||
test('preserves ordinary user-message content without a host-context prefix', () => {
|
||||
assert.equal(stripHostContextFromQuery('我的userId是多少'), '我的userId是多少')
|
||||
})
|
||||
|
||||
test('preserves malformed host-context content when its query separator is missing', () => {
|
||||
const malformed = '[Host context]\nuserId: 21'
|
||||
assert.equal(stripHostContextFromQuery(malformed), malformed)
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
/** Prefix host-injected context onto the user query for embed chat. */
|
||||
export function buildQueryWithHostContext(
|
||||
query: string,
|
||||
hostContext?: Record<string, unknown>,
|
||||
): string {
|
||||
if (!hostContext || !Object.keys(hostContext).length) return query
|
||||
const lines = Object.entries(hostContext)
|
||||
.filter(([, v]) => v !== undefined && v !== null && v !== '')
|
||||
.map(([k, v]) => `${k}: ${typeof v === 'string' ? v : JSON.stringify(v)}`)
|
||||
if (!lines.length) return query
|
||||
return `[Host context]\n${lines.join('\n')}\n\n${query}`
|
||||
}
|
||||
|
||||
/** Remove the injected host-context block from a query for user-visible display. */
|
||||
export function stripHostContextFromQuery(query: string): string {
|
||||
const prefix = '[Host context]\n'
|
||||
if (!query.startsWith(prefix)) return query
|
||||
|
||||
const separatorIndex = query.indexOf('\n\n', prefix.length)
|
||||
if (separatorIndex === -1) return query
|
||||
return query.slice(separatorIndex + 2)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
export function isEmbedImageFile(file: File): boolean {
|
||||
if (file.type.startsWith('image/')) return true
|
||||
const name = file.name.toLowerCase()
|
||||
return ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'].some((ext) => name.endsWith(ext))
|
||||
}
|
||||
|
||||
export function fileToDataURI(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(String(reader.result || ''))
|
||||
reader.onerror = reject
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/** Lightweight toast for embed bundle (no TDesign). */
|
||||
export function embedToast(message: string, type: 'error' | 'info' = 'error') {
|
||||
if (!message || typeof document === 'undefined') return
|
||||
const el = document.createElement('div')
|
||||
el.textContent = message
|
||||
el.setAttribute('role', 'alert')
|
||||
Object.assign(el.style, {
|
||||
position: 'fixed',
|
||||
left: '50%',
|
||||
top: '16px',
|
||||
transform: 'translateX(-50%)',
|
||||
zIndex: '2147483647',
|
||||
maxWidth: 'min(90vw, 420px)',
|
||||
padding: '10px 14px',
|
||||
borderRadius: '8px',
|
||||
fontSize: '14px',
|
||||
lineHeight: '1.4',
|
||||
boxShadow: '0 4px 16px rgba(0,0,0,.12)',
|
||||
background: type === 'error' ? '#fff1f0' : '#f6ffed',
|
||||
color: type === 'error' ? '#cf1322' : '#389e0d',
|
||||
border: `1px solid ${type === 'error' ? '#ffccc7' : '#b7eb8f'}`,
|
||||
})
|
||||
document.body.appendChild(el)
|
||||
window.setTimeout(() => el.remove(), 4000)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { after, test } from 'node:test'
|
||||
import JSZip from 'jszip'
|
||||
import { DOMParser as XmlParser, XMLSerializer } from '@xmldom/xmldom'
|
||||
import { renderEpubPreview } from './epubPreview'
|
||||
|
||||
// Adapt the XML test DOM's missing browser conveniences. EPUB parsing and ZIP
|
||||
// resolution still run through the production renderer, with no mocked output.
|
||||
const originalParser = globalThis.DOMParser
|
||||
class TestParser {
|
||||
parseFromString(text: string) {
|
||||
const doc = new XmlParser().parseFromString(text, 'application/xhtml+xml')
|
||||
for (const element of Array.from(doc.getElementsByTagName('*'))) {
|
||||
Object.defineProperty(element, 'innerHTML', {
|
||||
get: () => Array.from(element.childNodes).map(node => new XMLSerializer().serializeToString(node)).join(''),
|
||||
})
|
||||
Object.assign(element, {
|
||||
querySelectorAll(selector: string) {
|
||||
assert.ok(selector === 'img' || selector === 'a[href]')
|
||||
const tag = selector === 'img' ? 'img' : 'a'
|
||||
return Array.from(element.getElementsByTagName(tag))
|
||||
.filter(node => tag !== 'a' || node.hasAttribute('href'))
|
||||
},
|
||||
})
|
||||
}
|
||||
Object.assign(doc, { body: doc.getElementsByTagName('body')[0] })
|
||||
return doc
|
||||
}
|
||||
}
|
||||
globalThis.DOMParser = TestParser as unknown as typeof DOMParser
|
||||
after(() => {
|
||||
if (originalParser) globalThis.DOMParser = originalParser
|
||||
else Reflect.deleteProperty(globalThis, 'DOMParser')
|
||||
})
|
||||
|
||||
const inlineImage = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='
|
||||
|
||||
async function fixture(body: string) {
|
||||
const zip = new JSZip()
|
||||
zip.file('META-INF/container.xml', '<container><rootfiles><rootfile full-path="EPUB/book.opf"/></rootfiles></container>')
|
||||
zip.file('EPUB/book.opf', '<package><manifest><item id="chapter" href="text/chapter.xhtml"/></manifest><spine><itemref idref="chapter"/></spine></package>')
|
||||
zip.file('EPUB/text/chapter.xhtml', `<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink"><head><title>Images</title></head><body>${body}</body></html>`)
|
||||
zip.file('EPUB/images/picture.gif', Buffer.from(inlineImage.split(',')[1], 'base64'))
|
||||
return zip.generateAsync({ type: 'arraybuffer' })
|
||||
}
|
||||
|
||||
test('EPUB keeps inline HTML and SVG image sources without creating blob URLs', async () => {
|
||||
const result = await renderEpubPreview(await fixture(
|
||||
`<img src="${inlineImage}"/><svg xmlns="http://www.w3.org/2000/svg"><image href="${inlineImage}"/><image xlink:href="${inlineImage}"/></svg>`,
|
||||
))
|
||||
assert.equal(result.html.split(inlineImage).length - 1, 3)
|
||||
assert.deepEqual(result.objectUrls, [])
|
||||
assert.match(result.html, /data-epub-section="1"/)
|
||||
})
|
||||
|
||||
test('EPUB keeps relative archive images working alongside inline images and reuses blobs', async () => {
|
||||
const result = await renderEpubPreview(await fixture(
|
||||
`<img src="${inlineImage}"/><img src="../images/picture.gif"/><img src="../images/picture.gif"/>`,
|
||||
))
|
||||
try {
|
||||
assert.ok(result.html.includes(inlineImage))
|
||||
assert.equal(result.objectUrls.length, 1)
|
||||
assert.equal(result.html.split(result.objectUrls[0]!).length - 1, 2)
|
||||
const blob = await (await fetch(result.objectUrls[0]!)).blob()
|
||||
assert.equal(blob.type, 'image/gif')
|
||||
assert.deepEqual(Buffer.from(await blob.arrayBuffer()), Buffer.from(inlineImage.split(',')[1], 'base64'))
|
||||
} finally {
|
||||
result.objectUrls.forEach(url => URL.revokeObjectURL(url))
|
||||
}
|
||||
})
|
||||
|
||||
test('non-image data and executable image sources are not preserved', async () => {
|
||||
const result = await renderEpubPreview(await fixture(
|
||||
'<img src="data:text/html;base64,PHNjcmlwdD4="/><img src="javascript:alert(1)"/><img src="missing.gif"/>',
|
||||
))
|
||||
assert.doesNotMatch(result.html, /data:text\/html|javascript:/)
|
||||
assert.deepEqual(result.objectUrls, [])
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Minimal EPUB rendering for previews: every spine item becomes a
|
||||
* `<section data-epub-section="N">` (N is the 1-based spine position, the same
|
||||
* numbering the backend uses in section locators), with images served from
|
||||
* blob URLs. The result must still be sanitized before it reaches the DOM.
|
||||
*/
|
||||
import JSZip from 'jszip'
|
||||
|
||||
export type EpubPreview = {
|
||||
html: string
|
||||
/** Blob URLs created for images; revoke them when the preview goes away. */
|
||||
objectUrls: string[]
|
||||
}
|
||||
|
||||
const IMAGE_MIME: Record<string, string> = {
|
||||
png: 'image/png',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
gif: 'image/gif',
|
||||
webp: 'image/webp',
|
||||
svg: 'image/svg+xml',
|
||||
bmp: 'image/bmp',
|
||||
}
|
||||
|
||||
/** Resolve `href` against the directory of `base` inside the archive. */
|
||||
export function resolveEpubPath(base: string, href: string): string {
|
||||
const clean = decodeURIComponent(href.split('#')[0].split('?')[0])
|
||||
if (clean.startsWith('/')) return clean.slice(1)
|
||||
const parts = base.split('/').slice(0, -1)
|
||||
for (const seg of clean.split('/')) {
|
||||
if (seg === '..') parts.pop()
|
||||
else if (seg && seg !== '.') parts.push(seg)
|
||||
}
|
||||
return parts.join('/')
|
||||
}
|
||||
|
||||
function parseXml(text: string): Document {
|
||||
return new DOMParser().parseFromString(text, 'application/xml')
|
||||
}
|
||||
|
||||
function parseChapter(text: string): Document {
|
||||
const xhtml = new DOMParser().parseFromString(text, 'application/xhtml+xml')
|
||||
if (!xhtml.getElementsByTagName('parsererror').length && xhtml.body) return xhtml
|
||||
return new DOMParser().parseFromString(text, 'text/html')
|
||||
}
|
||||
|
||||
function byLocalName(root: Document | Element, name: string): Element[] {
|
||||
return Array.from(root.getElementsByTagName('*')).filter((el) => el.localName === name)
|
||||
}
|
||||
|
||||
export async function renderEpubPreview(data: ArrayBuffer): Promise<EpubPreview> {
|
||||
const zip = await JSZip.loadAsync(data)
|
||||
const containerXml = await zip.file('META-INF/container.xml')?.async('string')
|
||||
if (!containerXml) throw new Error('EPUB: missing META-INF/container.xml')
|
||||
const rootfile = byLocalName(parseXml(containerXml), 'rootfile')[0]?.getAttribute('full-path')
|
||||
if (!rootfile) throw new Error('EPUB: no rootfile')
|
||||
const opfText = await zip.file(rootfile)?.async('string')
|
||||
if (!opfText) throw new Error('EPUB: missing package document')
|
||||
const opf = parseXml(opfText)
|
||||
|
||||
const manifest = new Map<string, string>()
|
||||
for (const item of byLocalName(opf, 'item')) {
|
||||
const id = item.getAttribute('id')
|
||||
const href = item.getAttribute('href')
|
||||
if (id && href) manifest.set(id, resolveEpubPath(rootfile, href))
|
||||
}
|
||||
// Keep unresolved entries so section numbers match spine positions.
|
||||
const spine = byLocalName(opf, 'itemref').map((ref) => manifest.get(ref.getAttribute('idref') || ''))
|
||||
|
||||
const objectUrls: string[] = []
|
||||
const imageUrls = new Map<string, string>()
|
||||
const imageUrl = async (path: string): Promise<string> => {
|
||||
const cached = imageUrls.get(path)
|
||||
if (cached) return cached
|
||||
const file = zip.file(path)
|
||||
if (!file) return ''
|
||||
const ext = path.split('.').pop()?.toLowerCase() || ''
|
||||
const blob = new Blob([await file.async('arraybuffer')], { type: IMAGE_MIME[ext] || 'application/octet-stream' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
objectUrls.push(url)
|
||||
imageUrls.set(path, url)
|
||||
return url
|
||||
}
|
||||
|
||||
// Inline images already contain their bytes; they are not ZIP entries.
|
||||
// The caller still sanitizes the rendered HTML before inserting it.
|
||||
const resolveImageUrl = (chapter: string, source: string): Promise<string> => {
|
||||
if (/^data:image\//i.test(source.trim())) return Promise.resolve(source)
|
||||
return imageUrl(resolveEpubPath(chapter, source))
|
||||
}
|
||||
|
||||
const sections: string[] = []
|
||||
for (let i = 0; i < spine.length; i++) {
|
||||
const path = spine[i]
|
||||
if (!path) continue
|
||||
const text = await zip.file(path)?.async('string')
|
||||
if (!text) continue
|
||||
const doc = parseChapter(text)
|
||||
const body = doc.body || doc.documentElement
|
||||
for (const img of Array.from(body.querySelectorAll('img'))) {
|
||||
const src = img.getAttribute('src')
|
||||
img.setAttribute('src', src ? await resolveImageUrl(path, src) : '')
|
||||
}
|
||||
for (const image of byLocalName(body as Element, 'image')) {
|
||||
const href = image.getAttribute('href') || image.getAttribute('xlink:href')
|
||||
if (href) {
|
||||
const url = await resolveImageUrl(path, href)
|
||||
image.setAttribute('href', url)
|
||||
image.removeAttribute('xlink:href')
|
||||
}
|
||||
}
|
||||
// Chapter links point inside the archive; keep the text, drop the target.
|
||||
for (const a of Array.from(body.querySelectorAll('a[href]'))) {
|
||||
const href = a.getAttribute('href') || ''
|
||||
if (!/^https?:/i.test(href)) a.removeAttribute('href')
|
||||
}
|
||||
sections.push(`<section class="epub-section" data-epub-section="${i + 1}">${body.innerHTML}</section>`)
|
||||
}
|
||||
return { html: sections.join('\n'), objectUrls }
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
getHighlightLang,
|
||||
getPreviewMimeType,
|
||||
isKnownPreviewableExt,
|
||||
isValidUTF8,
|
||||
prettyPrintJson,
|
||||
resolveFilePreviewExt,
|
||||
resolvePreviewKind,
|
||||
shouldPrettyPrintJson,
|
||||
sniffPreview,
|
||||
} from './filePreview.ts'
|
||||
|
||||
test('resolveFilePreviewExt prefers explicit type and strips a leading dot', () => {
|
||||
assert.equal(resolveFilePreviewExt('chart.html', '.HTML'), 'html')
|
||||
assert.equal(resolveFilePreviewExt('kb_stats.csv', ''), 'csv')
|
||||
assert.equal(resolveFilePreviewExt('noext', ''), '')
|
||||
})
|
||||
|
||||
test('resolvePreviewKind covers office, tables, html, media, and code', () => {
|
||||
assert.equal(resolvePreviewKind('html'), 'html')
|
||||
assert.equal(resolvePreviewKind('htm'), 'html')
|
||||
assert.equal(resolvePreviewKind('csv'), 'excel')
|
||||
assert.equal(resolvePreviewKind('tsv'), 'excel')
|
||||
assert.equal(resolvePreviewKind('xlsx'), 'excel')
|
||||
assert.equal(resolvePreviewKind('pdf'), 'pdf')
|
||||
assert.equal(resolvePreviewKind('docx'), 'docx')
|
||||
assert.equal(resolvePreviewKind('pptx'), 'pptx')
|
||||
// Legacy OLE2 formats are not parseable by the OOXML previewers and must
|
||||
// degrade to the unsupported state instead of failing with a zip error.
|
||||
assert.equal(resolvePreviewKind('doc'), 'unsupported')
|
||||
assert.equal(resolvePreviewKind('ppt'), 'unsupported')
|
||||
// SheetJS renders legacy .xls fine, so it stays previewable.
|
||||
assert.equal(resolvePreviewKind('xls'), 'excel')
|
||||
assert.equal(resolvePreviewKind('png'), 'image')
|
||||
assert.equal(resolvePreviewKind('svg'), 'image')
|
||||
assert.equal(resolvePreviewKind('md'), 'markdown')
|
||||
assert.equal(resolvePreviewKind('mp4'), 'video')
|
||||
assert.equal(resolvePreviewKind('mp3'), 'audio')
|
||||
assert.equal(resolvePreviewKind('mmd'), 'mermaid')
|
||||
assert.equal(resolvePreviewKind('vue'), 'text')
|
||||
assert.equal(resolvePreviewKind('ipynb'), 'text')
|
||||
assert.equal(resolvePreviewKind('exe'), 'unsupported')
|
||||
assert.equal(isKnownPreviewableExt('html'), true)
|
||||
assert.equal(isKnownPreviewableExt('bin'), false)
|
||||
})
|
||||
|
||||
test('sniffPreview detects html, svg, pdf, png, and mermaid from bytes', () => {
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('<!DOCTYPE html><html><body>ok</body></html>')).kind, 'html')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('<div id="chart"></div>')).kind, 'html')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('<table><tr><td>1</td></tr></table>')).kind, 'html')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"></svg>')).kind, 'image')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('%PDF-1.7\n')).kind, 'pdf')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('flowchart TD\n A-->B')).kind, 'mermaid')
|
||||
assert.equal(sniffPreview(new TextEncoder().encode('{"ok": true}')).kind, 'text')
|
||||
|
||||
const png = Uint8Array.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0])
|
||||
assert.equal(sniffPreview(png).kind, 'image')
|
||||
assert.equal(sniffPreview(png).ext, 'png')
|
||||
})
|
||||
|
||||
test('sniffPreview rejects NUL-containing binaries', () => {
|
||||
assert.equal(sniffPreview(Uint8Array.from([0x00, 0x01, 0x02, 0x03])).kind, 'unsupported')
|
||||
})
|
||||
|
||||
test('isValidUTF8 rejects invalid scalar encodings so GBK CSV can fall back', () => {
|
||||
// GBK for "蜡,1": accepting C0 AF as UTF-8 produces replacement characters.
|
||||
const csv = Uint8Array.from([0xC0, 0xAF, 0x2C, 0x31])
|
||||
assert.equal(isValidUTF8(csv), false)
|
||||
assert.equal(new TextDecoder('gbk').decode(csv), '蜡,1')
|
||||
for (const bytes of [
|
||||
[0xC1, 0xBF], [0xE0, 0x80, 0xAF], [0xED, 0xA0, 0x80],
|
||||
[0xF0, 0x80, 0x80, 0xAF], [0xF4, 0x90, 0x80, 0x80],
|
||||
[0xF5, 0x80, 0x80, 0x80], [0x80],
|
||||
]) {
|
||||
assert.equal(isValidUTF8(Uint8Array.from(bytes)), false, String(bytes))
|
||||
assert.equal(sniffPreview(Uint8Array.from(bytes)).kind, 'unsupported', String(bytes))
|
||||
}
|
||||
})
|
||||
|
||||
test('isValidUTF8 only tolerates valid incomplete prefixes when requested', () => {
|
||||
for (const bytes of [[0xC2], [0xE4, 0xB8], [0xF0, 0x9F, 0x98]]) {
|
||||
assert.equal(isValidUTF8(Uint8Array.from(bytes)), false)
|
||||
assert.equal(isValidUTF8(Uint8Array.from(bytes), true), true)
|
||||
}
|
||||
for (const bytes of [[0xC0], [0xF5], [0xE4, 0x41], [0xE0, 0x80], [0xED, 0xA0], [0xF4, 0x90]]) {
|
||||
assert.equal(isValidUTF8(Uint8Array.from(bytes), true), false, String(bytes))
|
||||
}
|
||||
})
|
||||
|
||||
test('isValidUTF8 accepts valid Unicode including scalar boundaries', () => {
|
||||
for (const text of ['', 'ASCII', '中文😀', '\u0080\u07FF\u0800\uD7FF\uE000\uFFFF', '\u{10000}\u{10FFFF}']) {
|
||||
const bytes = new TextEncoder().encode(text)
|
||||
assert.equal(isValidUTF8(bytes), true)
|
||||
assert.equal(isValidUTF8(bytes, true), true)
|
||||
}
|
||||
})
|
||||
|
||||
test('pretty-print helpers only rewrite canonical JSON documents', () => {
|
||||
assert.equal(shouldPrettyPrintJson('json'), true)
|
||||
assert.equal(shouldPrettyPrintJson('jsonl'), false)
|
||||
assert.equal(prettyPrintJson('{"a":1}'), '{\n "a": 1\n}')
|
||||
assert.equal(prettyPrintJson('not json'), 'not json')
|
||||
})
|
||||
|
||||
test('JSON preview preserves numeric literals instead of rounding or replacing them', () => {
|
||||
for (const number of [
|
||||
'9007199254740993', '-9007199254740993', '9223372036854775807',
|
||||
'0.1234567890123456789012345', '1e400', '1e-400', '-0', '1.2300',
|
||||
]) {
|
||||
assert.equal(prettyPrintJson(`{"value":${number}}`), `{\n "value": ${number}\n}`, number)
|
||||
}
|
||||
})
|
||||
|
||||
test('JSON preview formats nested containers without rewriting string contents', () => {
|
||||
// Strings containing JSON punctuation and escaped quotes are indivisible tokens.
|
||||
const ordinary = '{"items":[1,{"text":"a, b: [c] {d}","empty":[]}],"object":{},"ok":true,"nil":null}'
|
||||
assert.equal(prettyPrintJson(ordinary), JSON.stringify(JSON.parse(ordinary), null, 2))
|
||||
const escaped = String.raw`{"text":"comma, colon: quote\" slash\\ newline\n","id":9007199254740993}`
|
||||
assert.equal(prettyPrintJson(escaped), String.raw`{
|
||||
"text": "comma, colon: quote\" slash\\ newline\n",
|
||||
"id": 9007199254740993
|
||||
}`)
|
||||
})
|
||||
|
||||
test('JSON preview preserves top-level values and leaves invalid JSON unchanged', () => {
|
||||
for (const value of ['9007199254740993', '1e400', '-0', 'null', 'true', '"text"', '[]', '{}']) {
|
||||
assert.equal(prettyPrintJson(` ${value}\n`), value)
|
||||
}
|
||||
for (const value of [' {"id":01}', '{"id":1,}', '{"id":NaN}', '{"unfinished":', ' \n']) {
|
||||
assert.equal(prettyPrintJson(value), value)
|
||||
}
|
||||
})
|
||||
|
||||
test('mime and highlight maps cover skill-generated html/csv', () => {
|
||||
assert.equal(getPreviewMimeType('html'), 'text/html')
|
||||
assert.equal(getPreviewMimeType('csv'), 'text/csv')
|
||||
assert.equal(getHighlightLang('html'), 'xml')
|
||||
assert.equal(getHighlightLang('ts'), 'typescript')
|
||||
})
|
||||
|
||||
function ftyp(major: string, compatible: string[] = []) {
|
||||
const brands = major + String.fromCharCode(0, 0, 0, 0) + compatible.join('')
|
||||
const bytes = new Uint8Array(8 + brands.length)
|
||||
new DataView(bytes.buffer).setUint32(0, bytes.length)
|
||||
bytes.set(new TextEncoder().encode('ftyp'), 4)
|
||||
bytes.set(new TextEncoder().encode(brands), 8)
|
||||
return bytes
|
||||
}
|
||||
|
||||
test('sniffPreview distinguishes images and audio in ISO base media files', () => {
|
||||
for (const brand of ['avif', 'avis']) {
|
||||
assert.deepEqual(sniffPreview(ftyp(brand)), { kind: 'image', ext: 'avif' })
|
||||
}
|
||||
for (const brand of ['heic', 'heix', 'hevc', 'hevx']) {
|
||||
assert.deepEqual(sniffPreview(ftyp(brand)), { kind: 'image', ext: 'heic' })
|
||||
}
|
||||
for (const brand of ['M4A ', 'M4B ']) {
|
||||
assert.deepEqual(sniffPreview(ftyp(brand)), { kind: 'audio', ext: 'm4a' })
|
||||
}
|
||||
})
|
||||
|
||||
test('sniffPreview checks compatible image brands when the major brand is generic', () => {
|
||||
assert.deepEqual(sniffPreview(ftyp('mif1', ['miaf', 'avif'])), { kind: 'image', ext: 'avif' })
|
||||
assert.deepEqual(sniffPreview(ftyp('mif1', ['heic'])), { kind: 'image', ext: 'heic' })
|
||||
})
|
||||
|
||||
test('sniffPreview retains video fallback and confines brands to the ftyp box', () => {
|
||||
assert.deepEqual(sniffPreview(ftyp('isom', ['mp42'])), { kind: 'video', ext: 'mp4' })
|
||||
const video = ftyp('isom')
|
||||
const withTrailingBytes = new Uint8Array(video.length + 4)
|
||||
withTrailingBytes.set(video)
|
||||
withTrailingBytes.set(new TextEncoder().encode('avif'), video.length)
|
||||
assert.deepEqual(sniffPreview(withTrailingBytes), { kind: 'video', ext: 'mp4' })
|
||||
})
|
||||
@@ -0,0 +1,446 @@
|
||||
/**
|
||||
* Shared file-preview type resolution used by DocumentPreview, chat
|
||||
* attachments, and skill-generated artifacts.
|
||||
*
|
||||
* Unknown extensions are not immediately rejected: callers can fetch a
|
||||
* short byte prefix and run sniffPreview() so skill outputs without a
|
||||
* conventional suffix (or with a misleading one) still open when the
|
||||
* content is HTML, SVG, JSON-like text, PDF, images, audio, or video.
|
||||
*/
|
||||
|
||||
export type FilePreviewKind =
|
||||
| 'pdf'
|
||||
| 'docx'
|
||||
| 'pptx'
|
||||
| 'image'
|
||||
| 'excel'
|
||||
| 'text'
|
||||
| 'markdown'
|
||||
| 'html'
|
||||
| 'audio'
|
||||
| 'video'
|
||||
| 'mermaid'
|
||||
| 'epub'
|
||||
| 'unsupported'
|
||||
|
||||
export type FilePreviewSniff = {
|
||||
kind: FilePreviewKind
|
||||
ext: string
|
||||
}
|
||||
|
||||
const KIND_BY_EXT: Record<string, FilePreviewKind> = {}
|
||||
|
||||
function register(kind: FilePreviewKind, exts: string[]) {
|
||||
for (const ext of exts) {
|
||||
KIND_BY_EXT[ext] = kind
|
||||
}
|
||||
}
|
||||
|
||||
register('pdf', ['pdf'])
|
||||
// .doc (Word 97-2003) and .ppt (PowerPoint 97-2003) are legacy OLE2 binary
|
||||
// formats, while the docx/pptx previewers only parse OOXML (ZIP/XML) and
|
||||
// would fail with a raw zip error; leaving them unregistered degrades to the
|
||||
// unsupported-preview state with a download entry instead.
|
||||
register('docx', ['docx'])
|
||||
register('pptx', ['pptx'])
|
||||
register('image', [
|
||||
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'tif', 'svg', 'svgz',
|
||||
'ico', 'avif', 'apng', 'jfif', 'pjpeg', 'pjp', 'heic', 'heif',
|
||||
])
|
||||
register('excel', ['xlsx', 'xls', 'csv', 'tsv', 'tab'])
|
||||
register('markdown', ['md', 'markdown', 'mdown', 'mkd', 'mdx'])
|
||||
register('html', ['html', 'htm', 'xhtml'])
|
||||
register('audio', ['mp3', 'wav', 'm4a', 'flac', 'ogg', 'oga', 'aac', 'opus', 'weba'])
|
||||
register('video', ['mp4', 'webm', 'ogv', 'm4v', 'mov'])
|
||||
register('mermaid', ['mmd', 'mermaid'])
|
||||
register('epub', ['epub'])
|
||||
register('text', [
|
||||
'txt', 'text', 'log', 'out', 'err',
|
||||
'json', 'jsonc', 'json5', 'geojson', 'ipynb', 'jsonl', 'ndjson', 'har',
|
||||
'xml', 'xsl', 'xsd', 'dtd',
|
||||
'css', 'scss', 'less', 'sass', 'styl',
|
||||
'js', 'mjs', 'cjs', 'jsx', 'ts', 'tsx', 'mts', 'cts',
|
||||
'vue', 'svelte', 'astro',
|
||||
'py', 'pyi', 'pyw', 'java', 'kt', 'kts', 'scala', 'groovy', 'gradle',
|
||||
'go', 'rs', 'rb', 'php', 'cs', 'fs', 'fsx',
|
||||
'c', 'h', 'cc', 'cpp', 'cxx', 'hpp', 'hxx', 'hh',
|
||||
'swift', 'mm',
|
||||
'sh', 'bash', 'zsh', 'fish', 'ps1', 'bat', 'cmd',
|
||||
'yaml', 'yml', 'toml', 'ini', 'cfg', 'conf', 'config', 'env', 'properties',
|
||||
'editorconfig', 'gitignore', 'dockerignore', 'npmignore', 'gitattributes',
|
||||
'sql', 'graphql', 'gql', 'proto', 'prisma',
|
||||
'r', 'lua', 'pl', 'pm', 'tcl',
|
||||
'dart', 'ex', 'exs', 'erl', 'hrl', 'hs', 'lhs', 'ml', 'mli',
|
||||
'clj', 'cljs', 'cljc', 'lisp', 'el', 'scm', 'rkt',
|
||||
'vim', 'diff', 'patch',
|
||||
'makefile', 'mk', 'cmake', 'dockerfile',
|
||||
'tf', 'hcl', 'nix', 'zig', 'nim',
|
||||
'asm', 's',
|
||||
'rst', 'adoc', 'asciidoc', 'org', 'tex', 'latex',
|
||||
'lock', 'sum', 'mod',
|
||||
])
|
||||
|
||||
const MIME_BY_EXT: Record<string, string> = {
|
||||
pdf: 'application/pdf',
|
||||
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
doc: 'application/msword',
|
||||
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
epub: 'application/epub+zip',
|
||||
ppt: 'application/vnd.ms-powerpoint',
|
||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
xls: 'application/vnd.ms-excel',
|
||||
csv: 'text/csv',
|
||||
tsv: 'text/tab-separated-values',
|
||||
tab: 'text/tab-separated-values',
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
gif: 'image/gif',
|
||||
bmp: 'image/bmp',
|
||||
webp: 'image/webp',
|
||||
tiff: 'image/tiff',
|
||||
tif: 'image/tiff',
|
||||
svg: 'image/svg+xml',
|
||||
svgz: 'image/svg+xml',
|
||||
ico: 'image/x-icon',
|
||||
avif: 'image/avif',
|
||||
apng: 'image/apng',
|
||||
heic: 'image/heic',
|
||||
heif: 'image/heif',
|
||||
txt: 'text/plain',
|
||||
md: 'text/markdown',
|
||||
markdown: 'text/markdown',
|
||||
json: 'application/json',
|
||||
geojson: 'application/geo+json',
|
||||
xml: 'application/xml',
|
||||
html: 'text/html',
|
||||
htm: 'text/html',
|
||||
xhtml: 'application/xhtml+xml',
|
||||
css: 'text/css',
|
||||
js: 'text/javascript',
|
||||
mjs: 'text/javascript',
|
||||
ts: 'text/typescript',
|
||||
py: 'text/x-python',
|
||||
java: 'text/x-java',
|
||||
go: 'text/x-go',
|
||||
mp3: 'audio/mpeg',
|
||||
wav: 'audio/wav',
|
||||
m4a: 'audio/mp4',
|
||||
flac: 'audio/flac',
|
||||
ogg: 'audio/ogg',
|
||||
oga: 'audio/ogg',
|
||||
aac: 'audio/aac',
|
||||
opus: 'audio/opus',
|
||||
mp4: 'video/mp4',
|
||||
webm: 'video/webm',
|
||||
ogv: 'video/ogg',
|
||||
m4v: 'video/mp4',
|
||||
mov: 'video/quicktime',
|
||||
mmd: 'text/plain',
|
||||
mermaid: 'text/plain',
|
||||
}
|
||||
|
||||
const HIGHLIGHT_LANG_BY_EXT: Record<string, string> = {
|
||||
js: 'javascript',
|
||||
mjs: 'javascript',
|
||||
cjs: 'javascript',
|
||||
jsx: 'javascript',
|
||||
ts: 'typescript',
|
||||
tsx: 'typescript',
|
||||
mts: 'typescript',
|
||||
cts: 'typescript',
|
||||
py: 'python',
|
||||
pyi: 'python',
|
||||
rb: 'ruby',
|
||||
sh: 'bash',
|
||||
bash: 'bash',
|
||||
zsh: 'bash',
|
||||
fish: 'bash',
|
||||
yml: 'yaml',
|
||||
md: 'markdown',
|
||||
mdx: 'markdown',
|
||||
rs: 'rust',
|
||||
kt: 'kotlin',
|
||||
kts: 'kotlin',
|
||||
pl: 'perl',
|
||||
pm: 'perl',
|
||||
conf: 'ini',
|
||||
cfg: 'ini',
|
||||
env: 'ini',
|
||||
properties: 'ini',
|
||||
editorconfig: 'ini',
|
||||
log: 'plaintext',
|
||||
vue: 'xml',
|
||||
svelte: 'xml',
|
||||
astro: 'xml',
|
||||
html: 'xml',
|
||||
htm: 'xml',
|
||||
xhtml: 'xml',
|
||||
svg: 'xml',
|
||||
less: 'css',
|
||||
scss: 'scss',
|
||||
sass: 'scss',
|
||||
ipynb: 'json',
|
||||
geojson: 'json',
|
||||
jsonc: 'json',
|
||||
json5: 'json',
|
||||
jsonl: 'json',
|
||||
ndjson: 'json',
|
||||
har: 'json',
|
||||
proto: 'protobuf',
|
||||
gql: 'graphql',
|
||||
ps1: 'powershell',
|
||||
bat: 'dos',
|
||||
cmd: 'dos',
|
||||
dockerfile: 'dockerfile',
|
||||
makefile: 'makefile',
|
||||
cmake: 'cmake',
|
||||
tf: 'hcl',
|
||||
hcl: 'hcl',
|
||||
dart: 'dart',
|
||||
ex: 'elixir',
|
||||
exs: 'elixir',
|
||||
erl: 'erlang',
|
||||
hs: 'haskell',
|
||||
fs: 'fsharp',
|
||||
clj: 'clojure',
|
||||
lisp: 'lisp',
|
||||
vim: 'vim',
|
||||
diff: 'diff',
|
||||
patch: 'diff',
|
||||
tex: 'latex',
|
||||
prisma: 'javascript',
|
||||
mmd: 'plaintext',
|
||||
mermaid: 'plaintext',
|
||||
}
|
||||
|
||||
const JSON_PRETTY_EXTS = new Set(['json', 'jsonc', 'geojson', 'ipynb', 'har'])
|
||||
|
||||
const DEFAULT_EXT_BY_KIND: Record<FilePreviewKind, string> = {
|
||||
pdf: 'pdf',
|
||||
docx: 'docx',
|
||||
pptx: 'pptx',
|
||||
image: 'png',
|
||||
excel: 'csv',
|
||||
text: 'txt',
|
||||
markdown: 'md',
|
||||
html: 'html',
|
||||
audio: 'mp3',
|
||||
video: 'mp4',
|
||||
mermaid: 'mmd',
|
||||
epub: 'epub',
|
||||
unsupported: '',
|
||||
}
|
||||
|
||||
const SNIFF_BYTES = 16384
|
||||
|
||||
/** Strip a leading dot and lowercase. Prefers an explicit type over the filename suffix. */
|
||||
export function resolveFilePreviewExt(fileName?: string, fileType?: string): string {
|
||||
const normalizedType = String(fileType || '')
|
||||
.trim()
|
||||
.replace(/^\./, '')
|
||||
.toLowerCase()
|
||||
if (normalizedType) return normalizedType
|
||||
const name = String(fileName || '')
|
||||
const dot = name.lastIndexOf('.')
|
||||
if (dot < 0 || dot === name.length - 1) return ''
|
||||
return name.slice(dot + 1).toLowerCase()
|
||||
}
|
||||
|
||||
export function resolvePreviewKind(ext: string): FilePreviewKind {
|
||||
if (!ext) return 'unsupported'
|
||||
return KIND_BY_EXT[ext.toLowerCase()] || 'unsupported'
|
||||
}
|
||||
|
||||
export function isKnownPreviewableExt(ext: string): boolean {
|
||||
return resolvePreviewKind(ext) !== 'unsupported'
|
||||
}
|
||||
|
||||
export function isKnownPreviewableFile(fileName?: string, fileType?: string): boolean {
|
||||
return isKnownPreviewableExt(resolveFilePreviewExt(fileName, fileType))
|
||||
}
|
||||
|
||||
export function getPreviewMimeType(ext: string): string {
|
||||
return MIME_BY_EXT[ext?.toLowerCase()] || 'application/octet-stream'
|
||||
}
|
||||
|
||||
export function getHighlightLang(ext: string): string {
|
||||
const lower = ext?.toLowerCase() || ''
|
||||
return HIGHLIGHT_LANG_BY_EXT[lower] || lower
|
||||
}
|
||||
|
||||
export function shouldPrettyPrintJson(ext: string): boolean {
|
||||
return JSON_PRETTY_EXTS.has(ext?.toLowerCase())
|
||||
}
|
||||
|
||||
export function prettyPrintJson(text: string): string {
|
||||
const trimmed = text.trim()
|
||||
if (!trimmed) return text
|
||||
try {
|
||||
// Validate the document, but format its original tokens: serializing the
|
||||
// parsed value rounds large IDs/decimals and turns overflowing numbers into null.
|
||||
JSON.parse(trimmed)
|
||||
} catch {
|
||||
return text
|
||||
}
|
||||
const tokens = trimmed.match(/"(?:\\.|[^"\\])*"|[{}\[\],:]|[^\s{}\[\],:]+/g)!
|
||||
const output: string[] = []
|
||||
let depth = 0
|
||||
const newline = () => output.push('\n', ' '.repeat(depth))
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const token = tokens[i]
|
||||
if (token === '{' || token === '[') {
|
||||
output.push(token)
|
||||
const closing = token === '{' ? '}' : ']'
|
||||
if (tokens[i + 1] === closing) {
|
||||
output.push(closing)
|
||||
i++
|
||||
} else {
|
||||
depth++
|
||||
newline()
|
||||
}
|
||||
} else if (token === '}' || token === ']') {
|
||||
depth--
|
||||
newline()
|
||||
output.push(token)
|
||||
} else if (token === ',') {
|
||||
output.push(token)
|
||||
newline()
|
||||
} else if (token === ':') {
|
||||
output.push(': ')
|
||||
} else {
|
||||
output.push(token)
|
||||
}
|
||||
}
|
||||
return output.join('')
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `bytes` is well-formed UTF-8. A truncated trailing sequence at
|
||||
* the end of a prefix sample is tolerated so sniffing a slice does not
|
||||
* reject valid text files.
|
||||
*/
|
||||
export function isValidUTF8(bytes: Uint8Array, allowTruncatedEnd = false): boolean {
|
||||
try {
|
||||
// Streaming tolerates an incomplete final code point, but still rejects
|
||||
// invalid bytes already present (including overlong and surrogate encodings).
|
||||
new TextDecoder('utf-8', { fatal: true }).decode(bytes, { stream: allowTruncatedEnd })
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function asciiTag(bytes: Uint8Array, offset: number, length: number): string {
|
||||
if (offset + length > bytes.length) return ''
|
||||
let out = ''
|
||||
for (let i = 0; i < length; i++) {
|
||||
out += String.fromCharCode(bytes[offset + i])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function looksLikeMermaid(head: string): boolean {
|
||||
const line = head.split(/\r?\n/, 1)[0]?.trim() || ''
|
||||
if (/^(graph|flowchart)\s+[A-Za-z-]+\b/i.test(line)) return true
|
||||
return /^(sequenceDiagram|classDiagram|erDiagram|gantt|pie\b|mindmap|gitGraph|stateDiagram|journey|C4Context|requirementDiagram|quadrantChart|sankey-beta|xychart-beta|block-beta|timeline)\b/i.test(line)
|
||||
}
|
||||
|
||||
function sniffFromMagic(bytes: Uint8Array): FilePreviewSniff | null {
|
||||
if (bytes.length >= 4 && asciiTag(bytes, 0, 4) === '%PDF') {
|
||||
return { kind: 'pdf', ext: 'pdf' }
|
||||
}
|
||||
if (bytes.length >= 8 && bytes[0] === 0x89 && asciiTag(bytes, 1, 3) === 'PNG') {
|
||||
return { kind: 'image', ext: 'png' }
|
||||
}
|
||||
if (bytes.length >= 3 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF) {
|
||||
return { kind: 'image', ext: 'jpg' }
|
||||
}
|
||||
if (bytes.length >= 6 && asciiTag(bytes, 0, 3) === 'GIF') {
|
||||
return { kind: 'image', ext: 'gif' }
|
||||
}
|
||||
if (bytes.length >= 12 && asciiTag(bytes, 0, 4) === 'RIFF') {
|
||||
const tag = asciiTag(bytes, 8, 4)
|
||||
if (tag === 'WEBP') return { kind: 'image', ext: 'webp' }
|
||||
if (tag === 'WAVE') return { kind: 'audio', ext: 'wav' }
|
||||
if (tag === 'AVI ') return { kind: 'video', ext: 'avi' }
|
||||
}
|
||||
if (bytes.length >= 8 && asciiTag(bytes, 4, 4) === 'ftyp') {
|
||||
// ISO base media containers also carry images and audio. Compatible
|
||||
// brands matter when the major brand is generic (for example, mif1).
|
||||
const brands = new Set([asciiTag(bytes, 8, 4)])
|
||||
if (bytes.length >= 16) {
|
||||
const boxSize = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0)
|
||||
const end = Math.min(boxSize, bytes.length, SNIFF_BYTES)
|
||||
for (let offset = 16; offset + 4 <= end; offset += 4) {
|
||||
brands.add(asciiTag(bytes, offset, 4))
|
||||
}
|
||||
}
|
||||
if (brands.has('avif') || brands.has('avis')) return { kind: 'image', ext: 'avif' }
|
||||
if (['heic', 'heix', 'hevc', 'hevx'].some(brand => brands.has(brand))) {
|
||||
return { kind: 'image', ext: 'heic' }
|
||||
}
|
||||
if (brands.has('M4A ') || brands.has('M4B ')) return { kind: 'audio', ext: 'm4a' }
|
||||
return { kind: 'video', ext: 'mp4' }
|
||||
}
|
||||
if (bytes.length >= 4 && bytes[0] === 0x1A && bytes[1] === 0x45 && bytes[2] === 0xDF && bytes[3] === 0xA3) {
|
||||
return { kind: 'video', ext: 'webm' }
|
||||
}
|
||||
if (bytes.length >= 3 && asciiTag(bytes, 0, 3) === 'ID3') {
|
||||
return { kind: 'audio', ext: 'mp3' }
|
||||
}
|
||||
if (bytes.length >= 4 && bytes[0] === 0x66 && bytes[1] === 0x4C && bytes[2] === 0x61 && bytes[3] === 0x43) {
|
||||
return { kind: 'audio', ext: 'flac' }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer a preview kind from a byte prefix. Used when the filename has no
|
||||
* known extension, or when callers want a second opinion on unlabeled
|
||||
* skill output.
|
||||
*/
|
||||
export function sniffPreview(bytes: Uint8Array): FilePreviewSniff {
|
||||
if (!bytes || bytes.length === 0) {
|
||||
return { kind: 'text', ext: 'txt' }
|
||||
}
|
||||
const magic = sniffFromMagic(bytes)
|
||||
if (magic) return magic
|
||||
|
||||
const sample = bytes.subarray(0, Math.min(bytes.length, SNIFF_BYTES))
|
||||
if (sample.includes(0)) {
|
||||
return { kind: 'unsupported', ext: '' }
|
||||
}
|
||||
if (!isValidUTF8(sample, true)) {
|
||||
return { kind: 'unsupported', ext: '' }
|
||||
}
|
||||
|
||||
const head = new TextDecoder('utf-8').decode(sample).replace(/^\uFEFF/, '').trimStart()
|
||||
const headLower = head.slice(0, 512).toLowerCase()
|
||||
if (
|
||||
headLower.startsWith('<!doctype html') ||
|
||||
headLower.startsWith('<html') ||
|
||||
/^<(?:head|body|div|table|section|article|main|header|footer|nav|script|style|meta|link|span|p|h[1-6]|canvas|form|ul|ol|pre|template)[\s>]/i.test(head)
|
||||
) {
|
||||
return { kind: 'html', ext: 'html' }
|
||||
}
|
||||
if (/^<\?xml\b/i.test(head) && /<svg[\s>]/i.test(head.slice(0, 2048))) {
|
||||
return { kind: 'image', ext: 'svg' }
|
||||
}
|
||||
if (/^<svg[\s>]/i.test(head)) {
|
||||
return { kind: 'image', ext: 'svg' }
|
||||
}
|
||||
if (looksLikeMermaid(head)) {
|
||||
return { kind: 'mermaid', ext: 'mmd' }
|
||||
}
|
||||
if (
|
||||
(head.startsWith('{') || head.startsWith('[')) &&
|
||||
/"cells"\s*:/.test(head) &&
|
||||
/"nbformat"\s*:/.test(head)
|
||||
) {
|
||||
return { kind: 'text', ext: 'ipynb' }
|
||||
}
|
||||
return { kind: 'text', ext: DEFAULT_EXT_BY_KIND.text }
|
||||
}
|
||||
|
||||
export { SNIFF_BYTES as FILE_PREVIEW_SNIFF_BYTES }
|
||||
@@ -0,0 +1,26 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { shouldRejectKnowledgeFileType } from './fileTypeVerification.ts'
|
||||
|
||||
test('shouldRejectKnowledgeFileType accepts HTML in the fallback whitelist', () => {
|
||||
assert.equal(shouldRejectKnowledgeFileType('page.html'), false)
|
||||
assert.equal(shouldRejectKnowledgeFileType('legacy.HTM'), false)
|
||||
assert.equal(shouldRejectKnowledgeFileType('payload.exe'), true)
|
||||
})
|
||||
|
||||
test('shouldRejectKnowledgeFileType preserves dynamic whitelist behavior', () => {
|
||||
assert.equal(shouldRejectKnowledgeFileType('custom.xyz', ['xyz']), false)
|
||||
assert.equal(shouldRejectKnowledgeFileType('page.html', ['pdf']), true)
|
||||
assert.equal(shouldRejectKnowledgeFileType('page.html', []), false)
|
||||
})
|
||||
|
||||
test('XMind uploads work before engine discovery and respect discovered capabilities', () => {
|
||||
for (const filename of ['architecture.xmind', 'ARCHITECTURE.XMIND']) {
|
||||
assert.equal(shouldRejectKnowledgeFileType(filename), false)
|
||||
assert.equal(shouldRejectKnowledgeFileType(filename, []), false)
|
||||
assert.equal(shouldRejectKnowledgeFileType(filename, new Set()), false)
|
||||
assert.equal(shouldRejectKnowledgeFileType(filename, ['pdf', 'xmind']), false)
|
||||
assert.equal(shouldRejectKnowledgeFileType(filename, ['pdf']), true)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
const DEFAULT_VALID_TYPES = new Set([
|
||||
"pdf",
|
||||
"txt",
|
||||
"md",
|
||||
"docx",
|
||||
"doc",
|
||||
"pptx",
|
||||
"ppt",
|
||||
"epub",
|
||||
"xmind",
|
||||
"html",
|
||||
"htm",
|
||||
"mhtml",
|
||||
"jpg",
|
||||
"jpeg",
|
||||
"png",
|
||||
"csv",
|
||||
"xlsx",
|
||||
"xls",
|
||||
"mp3",
|
||||
"wav",
|
||||
"m4a",
|
||||
"flac",
|
||||
"ogg",
|
||||
]);
|
||||
|
||||
export function shouldRejectKnowledgeFileType(
|
||||
filename: string,
|
||||
validTypes?: Set<string> | string[],
|
||||
) {
|
||||
const provided = validTypes
|
||||
? validTypes instanceof Set
|
||||
? validTypes
|
||||
: new Set(validTypes)
|
||||
: undefined;
|
||||
const allowed = provided && provided.size > 0 ? provided : DEFAULT_VALID_TYPES;
|
||||
const type = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
|
||||
|
||||
return !allowed.has(type);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Format a byte count as a human-readable string (B / KB / MB).
|
||||
* Returns '' for null/undefined/non-positive values so callers can use it as a v-if guard.
|
||||
*/
|
||||
export function formatFileSize(bytes?: number | string | null): string {
|
||||
if (bytes == null || bytes === '') return '';
|
||||
const n = typeof bytes === 'string' ? parseInt(bytes, 10) : bytes;
|
||||
if (Number.isNaN(n) || n <= 0) return '';
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a knowledge item or filename to a TDesign icon name.
|
||||
* Accepts either a string (filename) or a knowledge-like object with `type`/`file_type`/`file_name`.
|
||||
*/
|
||||
export function getFileIcon(input: string | { type?: string; file_type?: string; file_name?: string }): string {
|
||||
let type: string | undefined;
|
||||
let ext: string | undefined;
|
||||
if (typeof input === 'string') {
|
||||
ext = input.split('.').pop()?.toLowerCase();
|
||||
} else {
|
||||
type = input.type;
|
||||
if (type === 'manual') return 'edit';
|
||||
if (type === 'url') return 'link';
|
||||
ext = (input.file_type || input.file_name?.split('.').pop() || '').toLowerCase();
|
||||
}
|
||||
if (!ext) return 'file';
|
||||
if (['pdf'].includes(ext)) return 'file-pdf';
|
||||
if (['doc', 'docx'].includes(ext)) return 'file-word';
|
||||
if (['xls', 'xlsx', 'csv'].includes(ext)) return 'file-excel';
|
||||
if (['ppt', 'pptx'].includes(ext)) return 'file-powerpoint';
|
||||
// TDesign 无稳定 `file-text` 字形时会导致空白,纯文类统一用 `file`
|
||||
if (['txt', 'md', 'markdown', 'json', 'log', 'yaml', 'yml', 'xml'].includes(ext)) return 'file';
|
||||
if (['py', 'pyc', 'pyo', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'go', 'rs', 'java', 'c', 'cc', 'cpp', 'h', 'hpp', 'sh', 'bash', 'rb', 'php', 'sql', 'html', 'htm'].includes(ext)) return 'code';
|
||||
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'image';
|
||||
if (['mp3', 'wav', 'm4a', 'flac', 'ogg', 'aac'].includes(ext)) return 'sound';
|
||||
if (['mp4', 'mov', 'webm', 'mkv', 'avi'].includes(ext)) return 'video';
|
||||
return 'file';
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// finalAnswer.ts
|
||||
//
|
||||
// Helpers for normalising LLM-emitted final answers before rendering.
|
||||
//
|
||||
// Background: the agent ends a turn by writing its answer as plain assistant
|
||||
// text. Many models — especially smaller ones or those SFT'd on different
|
||||
// conventions — wrap that answer inside <answer>…</answer>,
|
||||
// <final_answer>…</final_answer>, or prefix it with "Final Answer:" /
|
||||
// "最终答案:". When the agent loop accepts such a natural-stop response as the
|
||||
// final answer, those wrappers leak into the rendered output. This module
|
||||
// provides a single helper to strip them before the markdown renderer sees
|
||||
// the text.
|
||||
//
|
||||
// The function is intentionally conservative: it only strips a wrapper when
|
||||
// it covers the *entire* trimmed content. We don't want to corrupt user-
|
||||
// authored markdown that happens to contain the word "Final Answer:" or an
|
||||
// XML-style tag in the middle of a sentence.
|
||||
|
||||
const ANSWER_TAG_RE =
|
||||
/^\s*<(answer|final_answer|final-answer)\b[^>]*>([\s\S]*?)<\/\1>\s*$/i;
|
||||
|
||||
const FENCED_ANSWER_RE =
|
||||
/^\s*```(?:final_answer|answer)\s*\n?([\s\S]*?)\n?```\s*$/i;
|
||||
|
||||
const ANSWER_PREFIX_RE =
|
||||
/^\s*(?:final\s*answer|最终答案|答案|答)\s*[::]\s*/i;
|
||||
|
||||
/**
|
||||
* Remove common "final answer" wrappers that some models wrap their
|
||||
* plain-text answer in. Returns the original string
|
||||
* (trimmed only when stripping happens) when no wrapper is detected.
|
||||
*
|
||||
* Recognised wrappers (must cover the entire trimmed content):
|
||||
* - `<answer>…</answer>` / `<final_answer>…</final_answer>` (case-insensitive)
|
||||
* - ```` ```final_answer\n…\n``` ```` fenced code block
|
||||
* - Leading `Final Answer:` / `最终答案:` / `答:` prefix
|
||||
*/
|
||||
export function unwrapFinalAnswerWrappers(content: string): string {
|
||||
if (!content || typeof content !== 'string') {
|
||||
return content ?? '';
|
||||
}
|
||||
|
||||
let result = content;
|
||||
let changed = false;
|
||||
|
||||
// Strip outer XML-style answer tags. Loop in case the model nested them
|
||||
// (e.g. <final_answer><answer>…</answer></final_answer>), but cap iterations
|
||||
// to avoid pathological inputs.
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const tagMatch = result.match(ANSWER_TAG_RE);
|
||||
if (!tagMatch) break;
|
||||
result = tagMatch[2];
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// Strip fenced "```final_answer" code block wrappers.
|
||||
const fencedMatch = result.match(FENCED_ANSWER_RE);
|
||||
if (fencedMatch) {
|
||||
result = fencedMatch[1];
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// Strip a leading "Final Answer:" / "最终答案:" prefix when it is the very
|
||||
// first non-whitespace token. Only applied once.
|
||||
const prefixMatch = result.match(ANSWER_PREFIX_RE);
|
||||
if (prefixMatch) {
|
||||
result = result.slice(prefixMatch[0].length);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
return changed ? result.trim() : result;
|
||||
}
|
||||
|
||||
const THINK_BLOCK_RE = /<think\b[^>]*>[\s\S]*?<\/think>/gi;
|
||||
|
||||
/**
|
||||
* Normalise content for cross-event comparison. Strips <think>…</think>
|
||||
* blocks (which appear in raw thinking chunks but not in the final answer
|
||||
* event), strips final-answer wrappers, and collapses whitespace. Used to
|
||||
* detect when the natural-stop path emits the same content twice (once as
|
||||
* streaming thinking chunks and once as a final answer event).
|
||||
*/
|
||||
export function normaliseForComparison(content: string): string {
|
||||
if (!content || typeof content !== 'string') return '';
|
||||
const stripped = content.replace(THINK_BLOCK_RE, '');
|
||||
const unwrapped = unwrapFinalAnswerWrappers(stripped);
|
||||
return unwrapped.replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when `thinking` and `answer` represent the same final answer
|
||||
* after normalisation. Tolerates small differences (≤2% length delta with
|
||||
* matching head/tail) to absorb chunk-boundary whitespace noise.
|
||||
*/
|
||||
export function thinkingEqualsAnswer(thinking: string, answer: string): boolean {
|
||||
const a = normaliseForComparison(thinking);
|
||||
const b = normaliseForComparison(answer);
|
||||
if (!a || !b) return false;
|
||||
if (a === b) return true;
|
||||
|
||||
const maxLen = Math.max(a.length, b.length);
|
||||
// Require at least ~80 chars of signal to avoid matching trivial prefixes.
|
||||
if (maxLen < 80) return false;
|
||||
|
||||
const lenDelta = Math.abs(a.length - b.length);
|
||||
if (lenDelta > maxLen * 0.02) return false;
|
||||
|
||||
const head = 50;
|
||||
const tail = 50;
|
||||
return (
|
||||
a.slice(0, head) === b.slice(0, head) &&
|
||||
a.slice(-tail) === b.slice(-tail)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Completion is authoritative after sandbox names and version references have
|
||||
// been reconciled. Update both plain content and the Agent timeline.
|
||||
export function applyFinalArtifactContent(message: any, content: unknown): void {
|
||||
if (typeof content !== 'string' || content.trim() === '') return;
|
||||
message.content = content;
|
||||
if (!Array.isArray(message.agentEventStream)) return;
|
||||
const answers = message.agentEventStream.filter((e: any) => e.type === 'answer' && !e.superseded);
|
||||
const last = answers.pop();
|
||||
answers.forEach((e: any) => { e.superseded = true; });
|
||||
if (last) {
|
||||
last.content = content;
|
||||
last.done = true;
|
||||
} else if (content) {
|
||||
message.agentEventStream.push({ type: 'answer', event_id: 'completed-answer', content, done: true });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Locale-aware conjunction for short UI lists (e.g. missing config items). */
|
||||
export function formatLocalizedList(items: string[], locale = 'en-US'): string {
|
||||
if (items.length === 0) return ''
|
||||
if (typeof Intl !== 'undefined' && typeof Intl.ListFormat !== 'undefined') {
|
||||
try {
|
||||
return new Intl.ListFormat(locale, { style: 'long', type: 'conjunction' }).format(items)
|
||||
} catch {
|
||||
// Unsupported locale — fall through.
|
||||
}
|
||||
}
|
||||
return items.join(', ')
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { findSourceFragments } from './fragmentedSource'
|
||||
import { resolvePdfSource } from './pdfSourceLocate'
|
||||
import { sourceImageContext, sourceQuoteText } from './sourceLocator'
|
||||
import { mergeDocumentReferences, resolveReferenceSource } from './referenceSources'
|
||||
import { preprocessCitationTags } from './citationMarkdown'
|
||||
|
||||
test('Agent grouping retains every cited chunk identity and resolves the exact document', () => {
|
||||
const refs = mergeDocumentReferences([
|
||||
{ id: 'first', knowledge_id: 'doc', knowledge_title: '微信&企微.docx', content: 'first evidence' },
|
||||
{ id: 'second', knowledge_id: 'doc', knowledge_title: '微信&企微.docx', content: 'second evidence' },
|
||||
])
|
||||
assert.deepEqual(refs[0]?.chunk_ids, ['first', 'second'])
|
||||
const source = resolveReferenceSource(refs, { chunkId: 'second', openSource: true })
|
||||
assert.equal(source?.knowledgeId, 'doc')
|
||||
assert.equal(source?.chunkId, 'second')
|
||||
assert.equal(source?.content, undefined, 'grouped content must be fetched for the cited chunk')
|
||||
})
|
||||
|
||||
test('encoded citation titles are decoded once before HTML escaping', () => {
|
||||
const html = preprocessCitationTags('<kb doc="微信&企微.docx" id="kb" chunk_id="chunk"/>')
|
||||
assert.ok(!html.includes('&amp;'))
|
||||
assert.ok(html.includes('微信&企微.docx'))
|
||||
})
|
||||
|
||||
test('column-serialized table identifies a row-serialized page by independent cells', async () => {
|
||||
const pages = ['机器人研究社(周四) 张老师 教室A\n天文观测社(周四) 李老师 教室B', '机器人研究社(周四) 张老师 操场']
|
||||
const scope = '|课程|老师|地点|\n|机器人研究社(周四) 天文观测社(周四)|张老师 李老师|教室A 教室B|'
|
||||
const result = await resolvePdfSource({ token: 1, quotes: [], locators: [], scope, sentence: '天文观测社每周四开课。' }, pages.length, async p => pages[p - 1]!)
|
||||
assert.equal(result.reason, 'partial')
|
||||
assert.equal(result.targets[0]?.page, 1)
|
||||
assert.ok(result.targets[0]?.quote?.includes('天文观测社'))
|
||||
assert.ok(result.targets.every(t => t.page === 1))
|
||||
})
|
||||
|
||||
test('a conjunction of repeated cells must identify a unique page', () => {
|
||||
const scope = '|机器人研究社(周四) 天文观测社(周四)|'
|
||||
const pages = ['机器人研究社(周四) 张老师 天文观测社(周四) 李老师', '机器人研究社(周四)', '天文观测社(周四)']
|
||||
assert.equal(findSourceFragments(pages, scope).length, 2)
|
||||
assert.deepEqual(findSourceFragments([pages[0]!, pages[0]!], scope), [])
|
||||
})
|
||||
|
||||
test('fragment recovery cannot claim a missing numeric value or a coincidental opening', () => {
|
||||
assert.deepEqual(findSourceFragments(['Shared opening. Different conclusion.'], 'Shared opening. Missing conclusion.'), [])
|
||||
assert.deepEqual(findSourceFragments(['甲项目温度15度\n乙项目限值20毫米'], '|甲项目温度1.5度|乙项目限值2.0毫米|'), [])
|
||||
})
|
||||
|
||||
test('parser artifacts retain only verified sentences and explicitly report partial coverage', async () => {
|
||||
const scope = '绑定手机:点击账号à选择个人中心。\n\n学生选课开始时间为周一上午十一点。小学部高年级选课在周一下午一点开始。'
|
||||
const pages = ['绑定手机:点击账号→选择个人中心。学生选课开始时间为周一上午十一点。小学部高年级选课在周一下午一点开始。']
|
||||
const result = await resolvePdfSource({ token: 1, quotes: [], locators: [], scope }, 1, async () => pages[0]!)
|
||||
assert.equal(result.reason, 'partial')
|
||||
assert.equal(result.targets.length, 3)
|
||||
assert.ok(result.targets.every(t => !t.quote?.includes('à')))
|
||||
assert.ok(result.targets.some(t => t.quote === '绑定手机:点击账号'))
|
||||
})
|
||||
|
||||
test('OCR image context requires exact resource identity and at least one neighboring paragraph', () => {
|
||||
const md = '前一段明确来源。\n\n\n\n后一段明确来源。'
|
||||
assert.deepEqual(sourceImageContext(md, ['resource://image']), { before: '前一段明确来源。', after: '后一段明确来源。' })
|
||||
assert.equal(sourceImageContext(md, ['resource://another-image']), undefined)
|
||||
assert.deepEqual(sourceImageContext(md.replace('后一段明确来源。', ''), ['resource://image']), { before: '前一段明确来源。', after: '' })
|
||||
assert.equal(sourceImageContext(md + '\n\n' + md, ['resource://image']), undefined)
|
||||
assert.equal(sourceQuoteText(md).includes('descript'), false)
|
||||
})
|
||||
|
||||
test('title fallback rejects duplicate document titles even within one knowledge base', () => {
|
||||
const refs = ['doc-one', 'doc-two'].map(knowledge_id => ({ id: knowledge_id, knowledge_id, knowledge_title: 'Same.docx', knowledge_base_id: 'kb' }))
|
||||
assert.equal(resolveReferenceSource(refs, { chunkId: 'missing-chunk', documentTitle: 'Same.docx', knowledgeBaseId: 'kb' }), null)
|
||||
})
|
||||
|
||||
test('decoding a citation attribute never turns encoded markup into active HTML', () => {
|
||||
const html = preprocessCitationTags('<kb doc="<img src=x onerror=alert(1)>.docx" chunk_id="chunk"/>')
|
||||
assert.ok(html.includes('data-doc="<img'))
|
||||
assert.ok(!html.includes('<img'))
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
import { findTextMatches, normalizeForMatch, type TextMatch } from './sourceLocator'
|
||||
|
||||
/** Exact fragments for parsers that serialize table columns in a different order.
|
||||
* Every returned range is independently checked. Callers must report partial
|
||||
* coverage; unmatched text is never included in a highlight.
|
||||
*/
|
||||
export function findSourceFragments(pages: string[], scope: string): Array<TextMatch & { page: number; quote: string }> {
|
||||
const table = scope.includes('|')
|
||||
const parts = table ? scope.split(/[|\n]/u) : scope.split(/(?<=[。!?;!?;])|\n+|(?<=[\p{Script=Han}】)])\s*[à→\uE000-\uF8FF]\s*/u)
|
||||
const candidates = new Set<string>()
|
||||
for (const part of parts) {
|
||||
const clean = part.trim()
|
||||
if (!clean || /^[-: ]+$/.test(clean)) continue
|
||||
if (!table) { candidates.add(clean); continue }
|
||||
// Preserve whole cells first. Flattened cells may hold a list of courses;
|
||||
// use complete whitespace-delimited entries, never arbitrary n-grams.
|
||||
candidates.add(clean)
|
||||
const words = clean.split(/\s+/u)
|
||||
if (words.length > 1) for (const word of words) candidates.add(word)
|
||||
}
|
||||
const evidence = [...candidates].filter(q => normalizeForMatch(q).length >= (table ? 5 : 8))
|
||||
.map(quote => ({ quote, hits: pages.flatMap((text, i) => findTextMatches(text, quote).map(hit => ({ ...hit, page: i + 1 }))) }))
|
||||
const unique = evidence.filter(e => e.hits.length === 1)
|
||||
// Require independent anchors. A shared opening alone is not a location.
|
||||
const anchors = unique.filter(e => !unique.some(other => other !== e && normalizeForMatch(other.quote).includes(normalizeForMatch(e.quote))))
|
||||
let anchorPages = new Set(anchors.map(e => e.hits[0]!.page))
|
||||
if (anchors.length < 2) {
|
||||
// Repeated table entries can still identify a page by their intersection:
|
||||
// all matching cells must agree, not merely the highest-scoring page.
|
||||
const present = evidence.filter(e => e.hits.length)
|
||||
if (!table || present.length < 2) return []
|
||||
let common = new Set(present[0]!.hits.map(hit => hit.page))
|
||||
for (const entry of present.slice(1)) common = new Set([...common].filter(page => entry.hits.some(hit => hit.page === page)))
|
||||
if (common.size !== 1) return []
|
||||
anchorPages = common
|
||||
}
|
||||
const ranges: Array<TextMatch & { page: number; quote: string }> = []
|
||||
for (const { quote, hits } of evidence) {
|
||||
const scoped = hits.length === 1 ? hits : hits.filter(hit => anchorPages.has(hit.page))
|
||||
if (scoped.length !== 1) continue
|
||||
const hit = scoped[0]!
|
||||
ranges.push({ ...hit, quote: pages[hit.page - 1]!.slice(hit.start, hit.end) })
|
||||
}
|
||||
const nonOverlapping = ranges.filter((hit, i) => !ranges.some((other, j) => j !== i && other.page === hit.page &&
|
||||
other.start <= hit.start && other.end >= hit.end && (other.start < hit.start || other.end > hit.end || j < i)))
|
||||
if (!table) {
|
||||
// Images and OCR artifacts can occupy most of a chunk. Coverage percentage
|
||||
// is not evidence of location: require multiple complete, unique sentences
|
||||
// in the same local source order, and report the result as partial.
|
||||
for (let i = 1; i < nonOverlapping.length; i++) {
|
||||
const previous = nonOverlapping[i - 1]!, current = nonOverlapping[i]!
|
||||
if (current.page < previous.page || (current.page === previous.page && current.start < previous.end)) return []
|
||||
}
|
||||
if (nonOverlapping.length < 2 || nonOverlapping.at(-1)!.page - nonOverlapping[0]!.page > 2) return []
|
||||
}
|
||||
return nonOverlapping.sort((a, b) => a.page - b.page || a.start - b.start)
|
||||
}
|
||||
|
||||
/** Rank already verified ranges by verbatim overlap with the cited sentence.
|
||||
* This changes navigation order only; it cannot create a match or resolve ambiguity.
|
||||
*/
|
||||
export function sourceOverlapLength(quote: string, sentence: string): number {
|
||||
const source = normalizeForMatch(quote), answer = normalizeForMatch(sentence)
|
||||
let previous = new Uint32Array(answer.length + 1), best = 0
|
||||
for (const character of source) {
|
||||
const current = new Uint32Array(answer.length + 1)
|
||||
for (let j = 0; j < answer.length; j++) if (character === answer[j]) {
|
||||
current[j + 1] = previous[j]! + 1
|
||||
best = Math.max(best, current[j + 1]!)
|
||||
}
|
||||
previous = current
|
||||
}
|
||||
return best
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { countGrepDocuments, groupGrepChunkResults } from './grepResultsGroup.ts'
|
||||
|
||||
test('groupGrepChunkResults merges chunks from the same document', () => {
|
||||
const grouped = groupGrepChunkResults([
|
||||
{
|
||||
chunk_id: 'chunk-a',
|
||||
knowledge_id: 'doc-1',
|
||||
knowledge_base_id: 'kb-1',
|
||||
knowledge_title: 'sample-report.pdf',
|
||||
match_snippet: 'hit one',
|
||||
},
|
||||
{
|
||||
chunk_id: 'chunk-b',
|
||||
knowledge_id: 'doc-1',
|
||||
knowledge_base_id: 'kb-1',
|
||||
knowledge_title: 'sample-report.pdf',
|
||||
match_snippet: 'hit two',
|
||||
},
|
||||
{
|
||||
chunk_id: 'chunk-c',
|
||||
knowledge_id: 'doc-2',
|
||||
knowledge_base_id: 'kb-1',
|
||||
knowledge_title: 'other-report.pdf',
|
||||
match_snippet: 'other hit',
|
||||
},
|
||||
])
|
||||
|
||||
assert.equal(grouped.length, 2)
|
||||
assert.equal(grouped[0].chunk_hit_count, 2)
|
||||
assert.equal(grouped[0].chunks.length, 2)
|
||||
assert.equal(grouped[0].knowledge_base_id, 'kb-1')
|
||||
assert.deepEqual(grouped[0].chunks.map((chunk) => chunk.chunk_id), ['chunk-a', 'chunk-b'])
|
||||
assert.equal(grouped[1].chunk_hit_count, 1)
|
||||
})
|
||||
|
||||
test('groupGrepChunkResults keeps FAQ entries separate', () => {
|
||||
const grouped = groupGrepChunkResults([
|
||||
{
|
||||
chunk_id: 'faq-1',
|
||||
faq_id: 'faq-1',
|
||||
knowledge_id: 'doc-faq',
|
||||
knowledge_base_id: 'kb-1',
|
||||
knowledge_title: 'FAQ doc',
|
||||
chunk_type: 'faq',
|
||||
faq_question: 'Question A',
|
||||
match_snippet: 'answer a',
|
||||
},
|
||||
{
|
||||
chunk_id: 'faq-2',
|
||||
faq_id: 'faq-2',
|
||||
knowledge_id: 'doc-faq',
|
||||
knowledge_base_id: 'kb-1',
|
||||
knowledge_title: 'FAQ doc',
|
||||
chunk_type: 'faq',
|
||||
faq_question: 'Question B',
|
||||
match_snippet: 'answer b',
|
||||
},
|
||||
])
|
||||
|
||||
assert.equal(grouped.length, 2)
|
||||
assert.equal(grouped[0].title, 'Question A')
|
||||
assert.equal(grouped[1].title, 'Question B')
|
||||
})
|
||||
|
||||
test('countGrepDocuments prefers document_count from backend', () => {
|
||||
assert.equal(
|
||||
countGrepDocuments({
|
||||
document_count: 1,
|
||||
knowledge_results: [{ knowledge_id: 'doc-1' }, { knowledge_id: 'doc-2' }],
|
||||
chunk_results: [{ chunk_id: 'c1', knowledge_id: 'doc-1', knowledge_base_id: 'kb', knowledge_title: 'a' }],
|
||||
}),
|
||||
1,
|
||||
)
|
||||
})
|
||||
|
||||
test('countGrepDocuments prefers knowledge_results length when document_count absent', () => {
|
||||
assert.equal(
|
||||
countGrepDocuments({
|
||||
knowledge_results: [{ knowledge_id: 'doc-1' }, { knowledge_id: 'doc-2' }],
|
||||
chunk_results: [{ chunk_id: 'c1', knowledge_id: 'doc-1', knowledge_base_id: 'kb', knowledge_title: 'a' }],
|
||||
}),
|
||||
2,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { GrepChunkResult, GrepKnowledgeResult } from '@/types/tool-results'
|
||||
|
||||
export type GrepGroupedRow = {
|
||||
key: string
|
||||
knowledge_id: string
|
||||
knowledge_base_id: string
|
||||
title: string
|
||||
is_faq: boolean
|
||||
chunk_hit_count: number
|
||||
title_match: boolean
|
||||
match_snippet: string
|
||||
chunks: { content: string; chunk_id: string; knowledge_id: string }[]
|
||||
}
|
||||
|
||||
/** Collapse per-chunk grep hits into one row per document; FAQ entries stay separate. */
|
||||
export function groupGrepChunkResults(chunkRows: GrepChunkResult[]): GrepGroupedRow[] {
|
||||
const map = new Map<string, GrepGroupedRow>()
|
||||
const order: string[] = []
|
||||
|
||||
for (const result of chunkRows) {
|
||||
const isFAQ = !!result.faq_id || result.chunk_type === 'faq'
|
||||
const key = isFAQ ? (result.faq_id || result.chunk_id) : result.knowledge_id
|
||||
if (!key) continue
|
||||
|
||||
const snippet = String(result.match_snippet ?? '').trim()
|
||||
if (!map.has(key)) {
|
||||
map.set(key, {
|
||||
key,
|
||||
knowledge_id: result.knowledge_id,
|
||||
knowledge_base_id: result.knowledge_base_id,
|
||||
title: result.faq_question || result.knowledge_title || '',
|
||||
is_faq: isFAQ,
|
||||
chunk_hit_count: 0,
|
||||
title_match: false,
|
||||
match_snippet: snippet,
|
||||
chunks: [],
|
||||
})
|
||||
order.push(key)
|
||||
}
|
||||
|
||||
const group = map.get(key)!
|
||||
group.chunk_hit_count += 1
|
||||
if (result.title_match) group.title_match = true
|
||||
if (!group.match_snippet && snippet) group.match_snippet = snippet
|
||||
if (snippet) {
|
||||
group.chunks.push({
|
||||
content: snippet,
|
||||
chunk_id: result.faq_id || result.chunk_id,
|
||||
knowledge_id: result.knowledge_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return order.map((key) => map.get(key)!)
|
||||
}
|
||||
|
||||
export function countGrepDocuments(toolData: {
|
||||
document_count?: number
|
||||
knowledge_results?: GrepKnowledgeResult[]
|
||||
chunk_results?: GrepChunkResult[]
|
||||
} | null | undefined): number {
|
||||
if (!toolData) return 0
|
||||
if (typeof toolData.document_count === 'number' && toolData.document_count >= 0) {
|
||||
return toolData.document_count
|
||||
}
|
||||
if (toolData.knowledge_results?.length) {
|
||||
return toolData.knowledge_results.length
|
||||
}
|
||||
if (toolData.chunk_results?.length) {
|
||||
return groupGrepChunkResults(toolData.chunk_results).length
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
hostWorkspaceHeaderText,
|
||||
projectDirBasename,
|
||||
shouldRenderHostProjectSettings,
|
||||
withOptionalProjectDir,
|
||||
} from './hostWorkspace.ts'
|
||||
|
||||
test('host-capability off hides the new-session project picker', () => {
|
||||
assert.equal(shouldRenderHostProjectSettings(false), false)
|
||||
})
|
||||
|
||||
test('host-capability on shows the new-session project picker', () => {
|
||||
assert.equal(shouldRenderHostProjectSettings(true), true)
|
||||
})
|
||||
|
||||
test('createSession payload includes project_dir when a project is selected', () => {
|
||||
const body = withOptionalProjectDir({ agent_config: { enabled: true } }, '/Users/dev/My Project')
|
||||
assert.equal(body.project_dir, '/Users/dev/My Project')
|
||||
assert.equal(body.agent_config.enabled, true)
|
||||
})
|
||||
|
||||
test('createSession payload omits project_dir when unbound', () => {
|
||||
const empty = withOptionalProjectDir({ agent_config: { enabled: true } }, '')
|
||||
assert.equal(Object.hasOwn(empty, 'project_dir'), false)
|
||||
|
||||
const missing = withOptionalProjectDir({ agent_config: { enabled: true } })
|
||||
assert.equal(Object.hasOwn(missing, 'project_dir'), false)
|
||||
|
||||
const whitespace = withOptionalProjectDir({ agent_config: { enabled: true } }, ' ')
|
||||
assert.equal(Object.hasOwn(whitespace, 'project_dir'), false)
|
||||
|
||||
const stripped = withOptionalProjectDir(
|
||||
{ agent_config: { enabled: true }, project_dir: '' },
|
||||
'',
|
||||
)
|
||||
assert.equal(Object.hasOwn(stripped, 'project_dir'), false)
|
||||
})
|
||||
|
||||
test('session header shows the project basename, not the absolute path', () => {
|
||||
assert.equal(projectDirBasename('/Users/dev/My Project'), 'My Project')
|
||||
assert.equal(projectDirBasename('C:\\Users\\dev\\My Project'), 'My Project')
|
||||
assert.equal(
|
||||
hostWorkspaceHeaderText('/Users/dev/My Project', 'Temporary workspace'),
|
||||
'My Project',
|
||||
)
|
||||
const label = hostWorkspaceHeaderText('/Users/dev/My Project', '临时工作区')
|
||||
assert.equal(label.includes('/'), false)
|
||||
assert.equal(label.includes('\\'), false)
|
||||
assert.notEqual(label, '/Users/dev/My Project')
|
||||
})
|
||||
|
||||
test('session header shows the temporary workspace label when unbound', () => {
|
||||
assert.equal(hostWorkspaceHeaderText('', '临时工作区'), '临时工作区')
|
||||
assert.equal(hostWorkspaceHeaderText(undefined, 'Temporary workspace'), 'Temporary workspace')
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
export function shouldRenderHostProjectSettings(supported: boolean): boolean {
|
||||
return supported === true
|
||||
}
|
||||
|
||||
export function withOptionalProjectDir<T extends Record<string, unknown>>(
|
||||
data: T,
|
||||
projectDir?: string | null,
|
||||
): T & { project_dir?: string } {
|
||||
const trimmed = typeof projectDir === 'string' ? projectDir.trim() : ''
|
||||
const next: Record<string, unknown> = { ...data }
|
||||
delete next.project_dir
|
||||
if (trimmed) next.project_dir = trimmed
|
||||
return next as T & { project_dir?: string }
|
||||
}
|
||||
|
||||
export function projectDirBasename(dir: string): string {
|
||||
const trimmed = dir.replace(/[\\/]+$/, '').trim()
|
||||
if (!trimmed) return dir
|
||||
const parts = trimmed.split(/[/\\]/).filter(Boolean)
|
||||
return parts[parts.length - 1] || dir
|
||||
}
|
||||
|
||||
export function hostWorkspaceHeaderText(
|
||||
hostWorkspaceDir: string | null | undefined,
|
||||
temporaryLabel: string,
|
||||
): string {
|
||||
const trimmed = hostWorkspaceDir?.trim() ?? ''
|
||||
if (!trimmed) return temporaryLabel
|
||||
return projectDirBasename(trimmed)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import test from 'node:test'
|
||||
import vm from 'node:vm'
|
||||
import { buildHtmlPreview } from './htmlPreview.ts'
|
||||
|
||||
// The preview injects two top-level script blocks: the storage shim and the
|
||||
// wkui bridge. Evaluate both joined, so each fake frame gets the full stack.
|
||||
const bootstrap = [...buildHtmlPreview('').matchAll(/<script>([\s\S]*?)<\/script>/g)]
|
||||
.map((match) => match[1])
|
||||
.join('\n;\n')
|
||||
|
||||
function createFrame(overrides: Record<string, unknown> = {}) {
|
||||
const window = Object.defineProperties({}, {
|
||||
localStorage: { configurable: true, get() { throw new Error('SecurityError') } },
|
||||
sessionStorage: { configurable: true, get() { throw new Error('SecurityError') } },
|
||||
}) as Window
|
||||
const context = vm.createContext({ window, ...overrides })
|
||||
vm.runInContext(bootstrap, context)
|
||||
return { window, context }
|
||||
}
|
||||
|
||||
test('blocked storage no longer prevents generated page initialization and event handlers', () => {
|
||||
const button = { onclick: null as null | (() => void) }
|
||||
const { window, context } = createFrame({ button })
|
||||
vm.runInContext(`
|
||||
let best = Number(window.localStorage.getItem('best')) || 0;
|
||||
button.onclick = () => window.localStorage.setItem('best', ++best);
|
||||
`, context)
|
||||
assert.equal(typeof button.onclick, 'function')
|
||||
button.onclick!()
|
||||
button.onclick!()
|
||||
assert.equal(window.localStorage.getItem('best'), '2')
|
||||
})
|
||||
|
||||
test('memory storage supports string conversion, keys, removal and clearing', () => {
|
||||
const { localStorage: storage } = createFrame().window
|
||||
assert.equal(storage.getItem('missing'), null)
|
||||
assert.equal(storage.length, 0)
|
||||
storage.setItem('best', 42 as unknown as string)
|
||||
storage.setItem('empty', '')
|
||||
storage.setItem('null', null as unknown as string)
|
||||
assert.equal(storage.getItem('best'), '42')
|
||||
assert.equal(storage.getItem('empty'), '')
|
||||
assert.equal(storage.getItem('null'), 'null')
|
||||
assert.equal(storage.length, 3)
|
||||
assert.equal(storage.key(0), 'best')
|
||||
assert.equal(storage.key(3), null)
|
||||
assert.equal(storage.key(-1), null)
|
||||
storage.removeItem('best')
|
||||
assert.equal(storage.key(0), 'empty')
|
||||
storage.clear()
|
||||
assert.equal(storage.length, 0)
|
||||
})
|
||||
|
||||
test('property access, deletion and enumeration share the same stored values', () => {
|
||||
const { localStorage: storage } = createFrame().window
|
||||
storage.score = 128
|
||||
assert.equal(storage.getItem('score'), '128')
|
||||
storage.setItem('board', '[2,4]')
|
||||
assert.equal(storage.board, '[2,4]')
|
||||
assert.deepEqual(Object.keys(storage), ['score', 'board'])
|
||||
assert.equal(JSON.stringify(storage), '{"score":"128","board":"[2,4]"}')
|
||||
assert.equal('score' in storage, true)
|
||||
delete storage.score
|
||||
assert.equal(storage.score, undefined)
|
||||
assert.equal('score' in storage, false)
|
||||
storage.setItem('__proto__', 'safe')
|
||||
assert.equal(storage.getItem('__proto__'), 'safe')
|
||||
assert.equal(Object.getPrototypeOf(storage), null)
|
||||
storage.setItem('getItem', 'stored')
|
||||
assert.equal(storage.getItem('getItem'), 'stored')
|
||||
})
|
||||
|
||||
test('each frame and each storage area has independent, temporary state', () => {
|
||||
const first = createFrame().window
|
||||
const second = createFrame().window
|
||||
first.localStorage.setItem('best', '100')
|
||||
first.sessionStorage.setItem('best', '20')
|
||||
assert.equal(first.localStorage.getItem('best'), '100')
|
||||
assert.equal(first.sessionStorage.getItem('best'), '20')
|
||||
assert.equal(second.localStorage.getItem('best'), null)
|
||||
assert.equal(second.sessionStorage.getItem('best'), null)
|
||||
})
|
||||
|
||||
test('available native storage is preserved independently for each area', () => {
|
||||
const native = { length: 1, getItem: () => 'existing' }
|
||||
const window = { localStorage: native }
|
||||
vm.runInNewContext(bootstrap, { window })
|
||||
assert.equal(window.localStorage, native)
|
||||
assert.equal(window.localStorage.getItem(), 'existing')
|
||||
assert.equal((window as unknown as Window).sessionStorage.length, 0)
|
||||
})
|
||||
|
||||
test('wkui bridge forwards send-chat through window.parent and truncates long text', () => {
|
||||
const sent: Array<Record<string, unknown>> = []
|
||||
const window = {
|
||||
addEventListener: () => {},
|
||||
parent: { postMessage: (message: Record<string, unknown>) => sent.push(message) },
|
||||
}
|
||||
vm.runInNewContext(bootstrap, { window })
|
||||
const wkui = (window as any).wkui
|
||||
assert.equal(wkui.version, 1)
|
||||
wkui.sendChat('就按这个方案执行')
|
||||
assert.equal(sent[0].type, 'wkui:ready')
|
||||
// Compare field-by-field: the message object is created inside the VM realm,
|
||||
// so its prototype differs from the test realm's and deepEqual would fail.
|
||||
assert.equal(sent[1].channel, 'wkui')
|
||||
assert.equal(sent[1].type, 'wkui:send-chat')
|
||||
assert.equal(sent[1].text, '就按这个方案执行')
|
||||
wkui.sendChat('x'.repeat(5000))
|
||||
assert.equal((sent[2] as { text: string }).text.length, 4000)
|
||||
})
|
||||
|
||||
test('bootstrap precedes application scripts while preserving doctype, head and all source bytes', () => {
|
||||
const cases = [
|
||||
['', '<button>Play</button>'],
|
||||
['<!DOCTYPE html>', '<script>start()</script>'],
|
||||
['\uFEFF\n<!-- <head> decoy -->\n<!doctype html>\n<html lang="en">\n<head data-test=">">', '<script>start()</script></head><body></body></html>'],
|
||||
['<HTML><HEAD>', '<script>start()</script></HEAD></HTML>'],
|
||||
['', '<script>const text = "<head>";</script>'],
|
||||
]
|
||||
for (const [prefix, rest] of cases) {
|
||||
const source = prefix + rest
|
||||
const rendered = buildHtmlPreview(source)
|
||||
assert.equal(rendered, prefix + buildHtmlPreview('') + rest)
|
||||
assert.equal(rendered.replace(buildHtmlPreview(''), ''), source)
|
||||
}
|
||||
})
|
||||
|
||||
test('only executable artifact previews use the compatibility copy; source and sandbox stay intact', () => {
|
||||
const source = readFileSync(new URL('../components/document-preview.vue', import.meta.url), 'utf8')
|
||||
const htmlCase = source.slice(source.indexOf("case 'html':"), source.indexOf("case 'docx':"))
|
||||
assert.match(htmlCase, /if \(allowsHtmlScriptPreview\(\)\) \{\s*const previewHtml = buildHtmlPreview\(await blob\.text\(\)\)/)
|
||||
assert.match(htmlCase, /new Blob\(\[previewHtml\], \{ type: 'text\/html;charset=utf-8' \}\)/)
|
||||
assert.match(htmlCase, /await renderText\(blob, ft \|\| 'html'\)/)
|
||||
assert.match(source, /sandbox="allow-scripts"/)
|
||||
assert.doesNotMatch(source, /allow-same-origin/)
|
||||
})
|
||||
@@ -0,0 +1,117 @@
|
||||
// This is a standalone script: it runs inside the opaque-origin iframe, never
|
||||
// in the application window. Keep it independent of imports and bundler helpers.
|
||||
// Each frame owns two ephemeral stores, discarded when the frame is reloaded.
|
||||
const storageBootstrap = `<script>
|
||||
(() => {
|
||||
function createStorage() {
|
||||
const entries = new Map();
|
||||
const api = Object.create(null);
|
||||
Object.defineProperties(api, {
|
||||
length: { configurable: true, get: () => entries.size },
|
||||
key: { configurable: true, value: (index) => Array.from(entries.keys())[Number(index) >>> 0] ?? null },
|
||||
getItem: { configurable: true, value: (key) => entries.get(String(key)) ?? null },
|
||||
setItem: { configurable: true, value: (key, value) => { entries.set(String(key), String(value)); } },
|
||||
removeItem: { configurable: true, value: (key) => { entries.delete(String(key)); } },
|
||||
clear: { configurable: true, value: () => { entries.clear(); } },
|
||||
[Symbol.toStringTag]: { configurable: true, value: 'Storage' },
|
||||
});
|
||||
return new Proxy(api, {
|
||||
get(target, key) {
|
||||
return Reflect.has(target, key) ? Reflect.get(target, key) : entries.get(key);
|
||||
},
|
||||
set(target, key, value) {
|
||||
if (typeof key === 'string') entries.set(key, String(value));
|
||||
return true;
|
||||
},
|
||||
deleteProperty(target, key) {
|
||||
entries.delete(key);
|
||||
return true;
|
||||
},
|
||||
has(target, key) {
|
||||
return Reflect.has(target, key) || entries.has(key);
|
||||
},
|
||||
ownKeys() {
|
||||
return Array.from(entries.keys());
|
||||
},
|
||||
getOwnPropertyDescriptor(target, key) {
|
||||
return Reflect.getOwnPropertyDescriptor(target, key) || (entries.has(key)
|
||||
? { configurable: true, enumerable: true, writable: true, value: entries.get(key) }
|
||||
: undefined);
|
||||
},
|
||||
});
|
||||
}
|
||||
for (const name of ['localStorage', 'sessionStorage']) {
|
||||
try {
|
||||
// Leave working browser storage alone. Sandboxed opaque origins throw
|
||||
// here before a generated page can even register its event handlers.
|
||||
void window[name].length;
|
||||
} catch {
|
||||
const storage = createStorage();
|
||||
Object.defineProperty(window, name, { configurable: true, enumerable: true, get: () => storage });
|
||||
}
|
||||
}
|
||||
})();
|
||||
</script>`
|
||||
|
||||
// wkui bridge: lets a generated UI (artifact HTML) send one-line prompts into
|
||||
// the chat and make read-only data requests, without ever receiving
|
||||
// credentials. The parent side (document-preview.vue) only accepts messages
|
||||
// whose `source` is this exact iframe, so a hostile page gains nothing by
|
||||
// including the bridge — it can only talk about its own session's artifacts.
|
||||
const bridgeBootstrap = `<script>
|
||||
(() => {
|
||||
const CHANNEL = 'wkui';
|
||||
const MAX_TEXT = 4000;
|
||||
let seq = 0;
|
||||
const pending = new Map();
|
||||
function post(message) {
|
||||
try { window.parent.postMessage(Object.assign({ channel: CHANNEL }, message), '*'); } catch {}
|
||||
}
|
||||
function onMessage(event) {
|
||||
const data = event && event.data;
|
||||
if (!data || data.channel !== CHANNEL) return;
|
||||
if (data.type === 'wkui:data' && data.requestId != null) {
|
||||
const resolve = pending.get(data.requestId);
|
||||
if (resolve) { pending.delete(data.requestId); resolve(data); }
|
||||
}
|
||||
}
|
||||
// Degrade silently in restricted hosts: the bridge is an enhancement, the
|
||||
// generated page must stay fully usable without it.
|
||||
try { window.addEventListener('message', onMessage); } catch {}
|
||||
window.wkui = {
|
||||
version: 1,
|
||||
sendChat(text) {
|
||||
const value = typeof text === 'string' ? text : String(text == null ? '' : text);
|
||||
post({ type: 'wkui:send-chat', text: value.slice(0, MAX_TEXT) });
|
||||
},
|
||||
requestData(request) {
|
||||
const requestId = ++seq;
|
||||
return new Promise((resolve) => {
|
||||
pending.set(requestId, resolve);
|
||||
post({ type: 'wkui:request-data', requestId, request: request || {} });
|
||||
setTimeout(() => {
|
||||
if (pending.has(requestId)) {
|
||||
pending.delete(requestId);
|
||||
resolve({ ok: false, error: 'timeout' });
|
||||
}
|
||||
}, 15000);
|
||||
});
|
||||
},
|
||||
};
|
||||
post({ type: 'wkui:ready' });
|
||||
})();
|
||||
</script>`
|
||||
|
||||
/** Add compatibility only to the rendered copy, preserving the original source. */
|
||||
export function buildHtmlPreview(html: string): string {
|
||||
// Keep the doctype first (standards mode), and use an existing head when
|
||||
// present. Only inspect the document prefix: text resembling tags inside
|
||||
// comments, scripts or the body must never become an insertion point.
|
||||
const trivia = String.raw`(?:\s|<!--[\s\S]*?-->)*`
|
||||
const attributes = String.raw`(?:[^<>"']|"[^"]*"|'[^']*')*`
|
||||
const prefix = new RegExp(
|
||||
`^${trivia}(?:<!doctype\\b${attributes}>${trivia})?(?:<html\\b${attributes}>${trivia})?(?:<head\\b${attributes}>)?`,
|
||||
'i',
|
||||
).exec(html)?.[0] ?? ''
|
||||
return prefix + storageBootstrap + bridgeBootstrap + html.slice(prefix.length)
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { createI18n } from 'vue-i18n'
|
||||
|
||||
import type { ImageAttrSchema, ImageAttrSpec } from '@/api/knowledge-base'
|
||||
import enUS from '../i18n/locales/en-US.ts'
|
||||
import jaJP from '../i18n/locales/ja-JP.ts'
|
||||
import koKR from '../i18n/locales/ko-KR.ts'
|
||||
import ruRU from '../i18n/locales/ru-RU.ts'
|
||||
import zhCN from '../i18n/locales/zh-CN.ts'
|
||||
import { imageAttrConditionDisplay, imageAttrDisplay, imageAttrKeyBase } from './imageAttrDisplay.ts'
|
||||
|
||||
const SPEC: ImageAttrSpec = {
|
||||
name: 'contain.text',
|
||||
type: 'extent',
|
||||
values: [
|
||||
{ value: 'none', label: 'no text at all', description: 'the image carries no text at all' },
|
||||
{ value: 'sparse', label: 'a few words', description: 'a logo, a road sign, a single label' },
|
||||
{ value: 'block', label: 'a block of body text', description: 'a screenshot, a table, a document page' },
|
||||
],
|
||||
question: '',
|
||||
label: 'Text in the image',
|
||||
description: 'How much body text the picture carries.',
|
||||
}
|
||||
|
||||
const PRESENCE: ImageAttrSpec = {
|
||||
name: 'contain.data_visual',
|
||||
type: 'presence',
|
||||
question: '',
|
||||
label: 'Data visual',
|
||||
description: 'Whether the picture conveys data as a chart.',
|
||||
values: [
|
||||
{ value: 'true', label: 'yes' },
|
||||
{ value: 'false', label: 'no' },
|
||||
],
|
||||
}
|
||||
|
||||
const SCHEMA: ImageAttrSchema = {
|
||||
version: 'attrs/2',
|
||||
prompt: 'observe/1',
|
||||
attributes: [SPEC, PRESENCE],
|
||||
default_actions: {
|
||||
ocr: {
|
||||
on: [
|
||||
{ prop: 'contain.text', is: 'block' },
|
||||
{ prop: 'contain.data_visual', is: 'true' },
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
/** No translations at all: the registry's own wording has to carry the panel. */
|
||||
const noI18n = { t: (key: string) => key, te: () => false }
|
||||
|
||||
test('falls back to the registry wording when nothing is translated', () => {
|
||||
const display = imageAttrDisplay(SPEC, noI18n.t, noI18n.te)
|
||||
|
||||
assert.equal(display.name, 'contain.text')
|
||||
assert.equal(display.label, 'Text in the image')
|
||||
assert.equal(display.description, 'How much body text the picture carries.')
|
||||
assert.deepEqual(
|
||||
display.values.map((value) => value.value),
|
||||
['none', 'sparse', 'block'],
|
||||
)
|
||||
assert.equal(display.values[2].label, 'a block of body text')
|
||||
})
|
||||
|
||||
test('prefers the translation overlay, keyed by attribute name', () => {
|
||||
// Keys escape the dots in the attribute name (see imageAttrKeyBase).
|
||||
const zh: Record<string, string> = {
|
||||
'imageAttr.contain_text.label': '图中文字量',
|
||||
'imageAttr.contain_text.values.block.label': '成段正文',
|
||||
'imageAttr.contain_text.values.block.description': '成段正文 —— 截图、表格或文档页面',
|
||||
}
|
||||
const display = imageAttrDisplay(SPEC, (key) => zh[key] ?? key, (key) => key in zh)
|
||||
|
||||
assert.equal(display.label, '图中文字量')
|
||||
// Untranslated pieces keep the registry wording instead of exposing the key.
|
||||
assert.equal(display.description, 'How much body text the picture carries.')
|
||||
assert.equal(display.values[0].label, 'no text at all')
|
||||
assert.equal(display.values[2].label, '成段正文')
|
||||
// The same split applies to a value's longer text.
|
||||
assert.equal(display.values[2].description, '成段正文 —— 截图、表格或文档页面')
|
||||
assert.equal(display.values[0].description, 'the image carries no text at all')
|
||||
})
|
||||
|
||||
test('never shows a blank label when the registry omits display text', () => {
|
||||
const bare: ImageAttrSpec = {
|
||||
...SPEC,
|
||||
label: '',
|
||||
description: undefined,
|
||||
values: [
|
||||
{ value: 'none', label: '', description: '' },
|
||||
{ value: 'sparse', label: '', description: '' },
|
||||
{ value: 'block', label: '', description: '' },
|
||||
],
|
||||
}
|
||||
const display = imageAttrDisplay(bare, noI18n.t, noI18n.te)
|
||||
|
||||
assert.equal(display.label, 'contain.text')
|
||||
assert.equal(display.description, '')
|
||||
assert.deepEqual(
|
||||
display.values.map((value) => value.label),
|
||||
['none', 'sparse', 'block'],
|
||||
)
|
||||
})
|
||||
|
||||
test('a presence attribute without an explicit value list offers true/false', () => {
|
||||
const display = imageAttrDisplay(PRESENCE, noI18n.t, noI18n.te)
|
||||
|
||||
assert.deepEqual(
|
||||
display.values.map((value) => value.value),
|
||||
['true', 'false'],
|
||||
)
|
||||
assert.equal(display.values[0].label, 'yes')
|
||||
})
|
||||
|
||||
test('renders a policy condition in words next to its raw pair', () => {
|
||||
const zh: Record<string, string> = {
|
||||
'imageAttr.contain_text.label': '图中文字量',
|
||||
'imageAttr.contain_text.values.block.label': '成段正文',
|
||||
}
|
||||
const condition = imageAttrConditionDisplay(
|
||||
{ prop: 'contain.text', is: 'block' },
|
||||
SCHEMA,
|
||||
(key) => zh[key] ?? key,
|
||||
(key) => key in zh,
|
||||
)
|
||||
|
||||
assert.equal(condition.label, '图中文字量 = 成段正文')
|
||||
assert.equal(condition.raw, 'contain.text = block')
|
||||
})
|
||||
|
||||
test('an unknown attribute or value degrades to its raw form', () => {
|
||||
const unknownProp = imageAttrConditionDisplay(
|
||||
{ prop: 'contain.mystery', is: 'x' },
|
||||
SCHEMA,
|
||||
noI18n.t,
|
||||
noI18n.te,
|
||||
)
|
||||
assert.equal(unknownProp.label, 'contain.mystery = x')
|
||||
assert.equal(unknownProp.raw, 'contain.mystery = x')
|
||||
|
||||
const unknownValue = imageAttrConditionDisplay(
|
||||
{ prop: 'contain.text', is: 'huge' },
|
||||
SCHEMA,
|
||||
noI18n.t,
|
||||
noI18n.te,
|
||||
)
|
||||
assert.equal(unknownValue.label, 'Text in the image = huge')
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The real bundles, resolved by the real vue-i18n.
|
||||
//
|
||||
// The faked translators above answer a flat key lookup, so they would happily
|
||||
// "translate" a key the real bundle can never resolve — which is exactly how a
|
||||
// literal `'contain.text'` message key slipped through once (vue-i18n walks a
|
||||
// key segment by segment on the dots, so it looked for `imageAttr` → `contain`).
|
||||
// These tests therefore use createI18n, the same resolver the app runs.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Each bundle is wired with a literal locale key, the same shape the app's own
|
||||
// createI18n call uses, so the messages argument keeps a checkable type.
|
||||
const MESSAGES_BY_LOCALE = {
|
||||
'zh-CN': { 'zh-CN': zhCN },
|
||||
'en-US': { 'en-US': enUS },
|
||||
'ja-JP': { 'ja-JP': jaJP },
|
||||
'ko-KR': { 'ko-KR': koKR },
|
||||
'ru-RU': { 'ru-RU': ruRU },
|
||||
}
|
||||
|
||||
type TestLocale = keyof typeof MESSAGES_BY_LOCALE
|
||||
|
||||
const LOCALES = Object.keys(MESSAGES_BY_LOCALE) as TestLocale[]
|
||||
|
||||
function translator(locale: TestLocale) {
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale,
|
||||
fallbackLocale: locale,
|
||||
warnHtmlMessage: false,
|
||||
messages: MESSAGES_BY_LOCALE[locale],
|
||||
})
|
||||
const global = i18n.global as unknown as {
|
||||
t: (key: string) => string
|
||||
te: (key: string) => boolean
|
||||
}
|
||||
return {
|
||||
t: (key: string) => global.t(key),
|
||||
te: (key: string) => global.te(key),
|
||||
}
|
||||
}
|
||||
|
||||
test('every shipped locale translates every attribute key', () => {
|
||||
for (const locale of LOCALES) {
|
||||
const { te, t } = translator(locale)
|
||||
|
||||
for (const spec of SCHEMA.attributes) {
|
||||
const base = imageAttrKeyBase(spec.name)
|
||||
const keys = [
|
||||
`${base}.label`,
|
||||
`${base}.description`,
|
||||
...imageAttrDisplay(spec, t, te).values.map(
|
||||
(value) => `${base}.values.${value.value}.label`,
|
||||
),
|
||||
]
|
||||
for (const key of keys) {
|
||||
assert.equal(te(key), true, `${locale}: ${key} does not resolve`)
|
||||
assert.ok(t(key).length > 0, `${locale}: ${key} is empty`)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('every shipped locale translates every OCR condition key', () => {
|
||||
for (const locale of LOCALES) {
|
||||
const { te } = translator(locale)
|
||||
|
||||
for (const cond of SCHEMA.default_actions.ocr.on) {
|
||||
const base = imageAttrKeyBase(cond.prop)
|
||||
assert.equal(te(`${base}.label`), true, `${locale}: ${base}.label does not resolve`)
|
||||
assert.equal(
|
||||
te(`${base}.values.${cond.is}.label`),
|
||||
true,
|
||||
`${locale}: ${base}.values.${cond.is}.label does not resolve`,
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test('the panel actually renders the translated text, not the registry fallback', () => {
|
||||
const { t, te } = translator('zh-CN')
|
||||
|
||||
for (const spec of SCHEMA.attributes) {
|
||||
const display = imageAttrDisplay(spec, t, te)
|
||||
|
||||
assert.match(display.label, /[\u4e00-\u9fa5]/, `${spec.name}: label is not Chinese`)
|
||||
assert.match(display.description, /[\u4e00-\u9fa5]/, `${spec.name}: description is not Chinese`)
|
||||
for (const value of display.values) {
|
||||
assert.match(
|
||||
value.label,
|
||||
/[\u4e00-\u9fa5]/,
|
||||
`${spec.name}.${value.value}: value is not Chinese`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
for (const cond of SCHEMA.default_actions.ocr.on) {
|
||||
const display = imageAttrConditionDisplay(cond, SCHEMA, t, te)
|
||||
assert.match(display.label, /[\u4e00-\u9fa5]/, `${cond.prop}=${cond.is}: condition is not Chinese`)
|
||||
// The raw pair stays alongside, so the panel still lines up with the trace.
|
||||
assert.equal(display.raw, `${cond.prop} = ${cond.is}`)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
import type {
|
||||
ImageAttrCondition,
|
||||
ImageAttrSchema,
|
||||
ImageAttrSpec,
|
||||
ImageAttrValue,
|
||||
} from '@/api/knowledge-base'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Display text for the image-attribute panel.
|
||||
//
|
||||
// The registry returned by GET /image-attrs/schema is the single source of
|
||||
// truth — it carries the attribute's name, what it measures, and what each of
|
||||
// its values means. That is what lets a non-technical operator read
|
||||
// "Text in the image: a block of body text" instead of
|
||||
// "contain.text: block", and it is why adding an attribute to the backend shows
|
||||
// up here with no frontend change.
|
||||
//
|
||||
// Translations are an overlay keyed by the attribute name, applied on top of
|
||||
// the registry text. Anything not translated yet falls back to the registry
|
||||
// wording, so a brand-new attribute still reads as words rather than as a bare
|
||||
// key. (The i18n keys are built at runtime from the attribute name, which is
|
||||
// why the `imageAttr.` prefix is registered in localeKeyAudit's EXTRA_PREFIXES.)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type Translate = (key: string) => string
|
||||
type HasTranslation = (key: string) => boolean
|
||||
|
||||
/** One allowed value of an attribute, with its meaning in words. */
|
||||
export interface ImageAttrValueDisplay {
|
||||
/** The raw value as it appears in the registry and the processing trace. */
|
||||
value: string
|
||||
/** The short, on-screen name for this value. */
|
||||
label: string
|
||||
/** The sentence explaining the value; empty when the registry has none. */
|
||||
description: string
|
||||
}
|
||||
|
||||
/** One attribute as the settings panel shows it. */
|
||||
export interface ImageAttrDisplay {
|
||||
/** Stable attribute key, e.g. "contain.text". Shown small, to line up with the trace. */
|
||||
name: string
|
||||
/** Human-readable name, e.g. "Text in the image". */
|
||||
label: string
|
||||
/** One line saying what the attribute measures. Empty when unavailable. */
|
||||
description: string
|
||||
/** Every allowed value with its meaning, in the registry's order. */
|
||||
values: ImageAttrValueDisplay[]
|
||||
}
|
||||
|
||||
/** One OCR policy condition, in words plus the raw pair. */
|
||||
export interface ImageAttrConditionDisplay {
|
||||
/** e.g. "Text in the image = a block of body text" */
|
||||
label: string
|
||||
/** e.g. "contain.text = block" — keeps the panel aligned with the trace. */
|
||||
raw: string
|
||||
}
|
||||
|
||||
/** The values a spec declares; presence attributes list true/false implicitly. */
|
||||
function specValues(attr: ImageAttrSpec): ImageAttrValue[] {
|
||||
if (attr.values && attr.values.length) return attr.values
|
||||
return attr.type === 'presence' ? [{ value: 'true', label: 'true' }, { value: 'false', label: 'false' }] : []
|
||||
}
|
||||
|
||||
/**
|
||||
* The i18n namespace for one attribute.
|
||||
*
|
||||
* vue-i18n resolves a key by walking it segment by segment on the dots, so a
|
||||
* literal `'contain.text'` message key is unreachable through
|
||||
* `imageAttr.contain.text.label` — the lookup goes looking for `imageAttr` →
|
||||
* `contain` → `text` and stops. Attribute names therefore escape their dots
|
||||
* (`contain.text` → `contain_text`) to become a single resolvable segment. The
|
||||
* same mapping is applied in every locale bundle, so a new attribute only needs
|
||||
* its name spelled the same way.
|
||||
*/
|
||||
export function imageAttrKeyBase(name: string): string {
|
||||
return `imageAttr.${name.replace(/\./g, '_')}`
|
||||
}
|
||||
|
||||
/** Look up `key`, falling back to the registry's own wording. */
|
||||
function pick(key: string, fallback: string, t: Translate, te: HasTranslation): string {
|
||||
return te(key) ? t(key) : fallback
|
||||
}
|
||||
|
||||
/**
|
||||
* Render one registry attribute for the settings panel. Never returns an empty
|
||||
* label: an attribute that arrives without display text still shows its name,
|
||||
* so the panel degrades to identifiers rather than to blanks.
|
||||
*/
|
||||
export function imageAttrDisplay(
|
||||
attr: ImageAttrSpec,
|
||||
t: Translate,
|
||||
te: HasTranslation,
|
||||
): ImageAttrDisplay {
|
||||
const base = imageAttrKeyBase(attr.name)
|
||||
return {
|
||||
name: attr.name,
|
||||
label: pick(`${base}.label`, attr.label || attr.name, t, te),
|
||||
description: pick(`${base}.description`, attr.description ?? '', t, te),
|
||||
values: specValues(attr).map((value) => ({
|
||||
value: value.value,
|
||||
label: pick(
|
||||
`${base}.values.${value.value}.label`,
|
||||
value.label || value.value,
|
||||
t,
|
||||
te,
|
||||
),
|
||||
description: pick(
|
||||
`${base}.values.${value.value}.description`,
|
||||
value.description ?? '',
|
||||
t,
|
||||
te,
|
||||
),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render one OCR policy condition in the same words as the attribute list,
|
||||
* keeping the raw `prop = value` pair so an operator can still match the panel
|
||||
* against the processing trace.
|
||||
*/
|
||||
export function imageAttrConditionDisplay(
|
||||
cond: ImageAttrCondition,
|
||||
schema: ImageAttrSchema,
|
||||
t: Translate,
|
||||
te: HasTranslation,
|
||||
): ImageAttrConditionDisplay {
|
||||
const raw = `${cond.prop} = ${cond.is}`
|
||||
const attr = schema.attributes.find((candidate) => candidate.name === cond.prop)
|
||||
if (!attr) return { label: raw, raw }
|
||||
|
||||
const display = imageAttrDisplay(attr, t, te)
|
||||
const value = display.values.find((candidate) => candidate.value === cond.is)
|
||||
return { label: `${display.label} = ${value ? value.label : cond.is}`, raw }
|
||||
}
|
||||
Loaded 100 of 5769 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user