Improve local evidence search and AI capabilities

This commit is contained in:
lix-2026
2026-06-05 23:00:53 +08:00
parent a1dcfc9f76
commit 4dbd9a978b
52 changed files with 6415 additions and 527 deletions
@@ -234,6 +234,12 @@ pub struct EvidenceSearchResult {
pub quote: String,
pub score: f64,
pub source: EvidenceLocator,
#[serde(skip_serializing_if = "Option::is_none")]
pub citation_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub citation_label: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub citation_markdown: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+5 -3
View File
@@ -143,7 +143,8 @@ pub const DOCS_TOOL_READ: ToolSpec = ToolSpec {
pub const EVIDENCE_TOOL_SEARCH: ToolSpec = ToolSpec {
name: "mnote.evidence.search",
display_name: "证据搜索",
description: "在工作区内搜索可回跳原文的证据块,返回 quote、locator 与 openAction。",
description:
"在工作区内搜索可回跳原文的证据块,返回 quote、locator、openAction 与 citationMarkdown。",
toolset_id: "toolset.evidence_read",
invocation_kind: InvocationKind::Query,
effect: ToolEffect::Read,
@@ -154,7 +155,8 @@ pub const EVIDENCE_TOOL_SEARCH: ToolSpec = ToolSpec {
pub const EVIDENCE_TOOL_READ: ToolSpec = ToolSpec {
name: "mnote.evidence.read",
display_name: "证据读回",
description: "按 EvidenceLocator 读取原文证据及周边上下文,供 AI 回答引用。",
description:
"按 EvidenceLocator 读取原文证据及周边上下文,供 AI 回答引用,并返回可点击引用链接。",
toolset_id: "toolset.evidence_read",
invocation_kind: InvocationKind::Query,
effect: ToolEffect::Read,
@@ -165,7 +167,7 @@ pub const EVIDENCE_TOOL_READ: ToolSpec = ToolSpec {
pub const EVIDENCE_TOOL_OPEN: ToolSpec = ToolSpec {
name: "mnote.evidence.open",
display_name: "证据打开",
description: "把 EvidenceLocator 归一化为 MNote 可执行的打开/定位动作。",
description: "把 EvidenceLocator 归一化为 MNote 可执行的打开/定位动作,并返回 citationUrl/citationMarkdown",
toolset_id: "toolset.evidence_read",
invocation_kind: InvocationKind::Query,
effect: ToolEffect::Read,
@@ -267,7 +267,15 @@ import {
root.setAttribute('data-mnote-evidence-open', 'true');
if (blockId) root.setAttribute('data-mnote-evidence-block-id', blockId);
if (lineRange) root.setAttribute('data-mnote-evidence-line-range', lineRange);
const target = blockId ? root.querySelector(`[data-block-id="${cssSafe(blockId)}"]`) : null;
let target = blockId ? root.querySelector(`[data-block-id="${cssSafe(blockId)}"]`) : null;
if (!(target instanceof HTMLElement) && lineRange) {
const start = Number(String(lineRange).split('-')[0] || 0);
if (Number.isFinite(start) && start > 0) {
const blocks = Array.from(root.querySelectorAll('.ProseMirror [data-block-id]'))
.filter((node) => node instanceof HTMLElement);
target = blocks[Math.max(0, Math.min(blocks.length - 1, start - 1))] || null;
}
}
if (target instanceof HTMLElement) {
root.querySelectorAll('[data-mnote-evidence-text-highlight="true"]').forEach((node) => {
if (node instanceof HTMLElement) node.removeAttribute('data-mnote-evidence-text-highlight');
@@ -302,6 +310,12 @@ import {
title,
fileName: title,
openTarget: 'active-tab',
page: url.searchParams.get('page') || undefined,
bbox: url.searchParams.get('bbox') || undefined,
sourceMapPath: String(url.searchParams.get('sourceMapPath') || '').trim(),
blockId: String(url.searchParams.get('blockId') || '').trim(),
lineRange: url.searchParams.get('lineRange') || null,
charRange: url.searchParams.get('charRange') || null,
};
};
@@ -418,6 +418,21 @@ export const createResourceTabRuntime = (dependencies = {}) => {
}
};
const officeOpenModeForEntry = (entry) => {
if (!entry || normalizeResourceTabKind(entry) !== 'office') return '';
const href = String(entry.passiveFrameSrc || entry.officeUrl || entry.href || '').trim()
|| String(entry.panel?.querySelector?.('iframe.mnote-resource-tab-frame')?.getAttribute?.('src') || '').trim();
if (href) {
try {
const url = new URL(href, window.location.origin);
if (url.pathname === '/office-preview' || url.pathname === '/office-n') return 'preview';
if (url.pathname === '/onlyoffice' || url.pathname.startsWith('/office/')) return 'onlyoffice_live';
} catch (_) {}
}
if (entry.onlyofficeSessionId || entry.bridgeSessionId) return 'onlyoffice_live';
return 'preview';
};
const openEditorsSnapshotEntry = (entry, key, generatedAt = Date.now()) => {
const active = entry?.tab instanceof HTMLElement
? entry.tab.getAttribute('aria-selected') === 'true'
@@ -432,15 +447,23 @@ export const createResourceTabRuntime = (dependencies = {}) => {
const kind = normalizeResourceTabKind(entry);
const dirtyState = resourceTabCloseGuardReason(entry?.session);
const officeBridgeDebug = kind === 'office' ? officeBridgeDebugForEntry(entry) : null;
const officeOpenMode = kind === 'office' ? officeOpenModeForEntry(entry) : '';
const onlyofficeSessionId = String(
officeBridgeDebug?.bridgeSessionId
|| entry?.onlyofficeSessionId
|| entry?.bridgeSessionId
|| '',
).trim();
const snapshotResourceKind = kind === 'office'
? (officeOpenMode === 'onlyoffice_live' || onlyofficeSessionId ? 'only_office' : 'attachment')
: kind;
const workspacePathSeed = entry?.workspacePath && typeof entry.workspacePath === 'object'
? { ...entry.workspacePath, resourceKind: snapshotResourceKind }
: entry?.workspacePath;
return {
objectIdentity,
workspacePath: buildWorkspacePath({
workspacePath: workspacePathSeed,
workspaceId,
sourceKind,
rootUri,
@@ -448,8 +471,7 @@ export const createResourceTabRuntime = (dependencies = {}) => {
documentId,
objectIdentity,
assetId,
resourceKind: kind,
workspacePath: entry?.workspacePath,
resourceKind: snapshotResourceKind,
}),
paneRole: normalizePaneRole(entry?.paneRole),
documentId,
@@ -465,13 +487,14 @@ export const createResourceTabRuntime = (dependencies = {}) => {
dirtyGuard: dirtyState,
assetId,
path: relativePath,
officeOpenMode,
onlyofficeSessionId,
bridgeSessionId: onlyofficeSessionId,
bridgeSessionReady: Boolean(onlyofficeSessionId),
bridgeDocumentId: String(officeBridgeDebug?.documentId || '').trim(),
bridgeAssetId: String(officeBridgeDebug?.assetId || '').trim(),
lastActiveAt: Number(entry?.session?.lastActiveAt || entry?.lastActiveAt || 0) || (active ? generatedAt : 0),
preview: false,
preview: officeOpenMode === 'preview',
pinned: false,
};
};
@@ -848,6 +871,7 @@ export const createResourceTabRuntime = (dependencies = {}) => {
panel.setAttribute('data-mnote-object-identity', objectIdentity);
panel.setAttribute('data-pane-role', paneRole);
panel.setAttribute('data-resource-kind', kind);
panel.setAttribute('data-resource-path', String(input.path || '').trim());
panel.hidden = true;
nodes.strip.append(tab);
nodes.panelRoot.append(panel);
@@ -989,6 +1013,16 @@ export const createResourceTabRuntime = (dependencies = {}) => {
if (bbox) url.searchParams.set('bbox', bbox);
if (locator.sourceMapPath) url.searchParams.set('sourceMapPath', String(locator.sourceMapPath));
if (locator.blockId) url.searchParams.set('blockId', String(locator.blockId));
if (url.pathname === '/office-preview' && frame.contentWindow) {
frame.contentWindow.postMessage({
type: 'mnote:office-evidence-locator',
page: locator.page,
bbox,
sourceMapPath: locator.sourceMapPath || '',
blockId: locator.blockId || '',
}, window.location.origin);
return;
}
frame.src = url.toString();
} catch (_) {}
};
@@ -1015,11 +1049,22 @@ export const createResourceTabRuntime = (dependencies = {}) => {
};
const applyEvidenceLocatorToTextPanel = (entry, locator) => {
if (!(entry?.panel instanceof HTMLElement) || !locator?.blockId) return;
if (!(entry?.panel instanceof HTMLElement) || !locator) return;
const root = entry.panel.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
if (!(root instanceof HTMLElement)) return;
const selector = `[data-block-id="${cssSafe(locator.blockId)}"]`;
const target = root.querySelector(selector);
const selector = locator.blockId ? `[data-block-id="${cssSafe(locator.blockId)}"]` : '';
let target = selector ? root.querySelector(selector) : null;
const query = String(locator?.openAction?.params?.query || locator?.query || '').trim();
if (!(target instanceof HTMLElement) && query) {
target = Array.from(root.querySelectorAll('.ProseMirror [data-block-id]'))
.find((node) => node instanceof HTMLElement && String(node.textContent || '').includes(query)) || null;
}
const lineStart = Number(locator?.lineRange?.start ?? locator?.line_range?.start ?? 0);
if (!(target instanceof HTMLElement) && Number.isFinite(lineStart) && lineStart > 0) {
const blocks = Array.from(root.querySelectorAll('.ProseMirror [data-block-id]'))
.filter((node) => node instanceof HTMLElement);
target = blocks[Math.max(0, Math.min(blocks.length - 1, lineStart - 1))] || null;
}
if (!(target instanceof HTMLElement)) return;
root.querySelectorAll('[data-mnote-evidence-text-highlight="true"]').forEach((node) => {
if (node instanceof HTMLElement) node.removeAttribute('data-mnote-evidence-text-highlight');
@@ -1364,6 +1409,7 @@ export const createResourceTabRuntime = (dependencies = {}) => {
rootUri: '',
jobsBySource: new Map(),
drawerOpen: false,
taskFilter: 'active',
eventSource: null,
fileTreeRefreshKeys: new Set(),
};
@@ -1467,13 +1513,36 @@ export const createResourceTabRuntime = (dependencies = {}) => {
: status || '未知';
};
const localOcrTaskCategory = (job) => {
const status = String(job?.status || '').trim();
if (['failed', 'stale', 'retry_scheduled'].includes(status)) return 'attention';
if (['done', 'succeeded', 'success'].includes(status)) return 'completed';
return 'active';
};
const localOcrTaskProgress = (job) => {
const current = Number(job?.progressCurrent ?? job?.currentProgress);
const total = Number(job?.progressTotal ?? job?.maxProgress);
if (Number.isFinite(current) && Number.isFinite(total) && total > 0) {
return Math.max(0, Math.min(100, Math.round((current / total) * 100)));
}
return null;
};
const localOcrTaskFilterLabel = (filter) => {
return filter === 'active' ? '进行中'
: filter === 'completed' ? '已完成'
: filter === 'attention' ? '需处理'
: '全部';
};
const ensureLocalOcrTaskDock = () => {
let dock = document.querySelector('[data-testid="mnote-local-ocr-task-dock"]');
if (!(dock instanceof HTMLElement)) {
dock = document.createElement('section');
dock.className = 'mnote-local-ocr-task-dock';
dock.setAttribute('data-testid', 'mnote-local-ocr-task-dock');
dock.innerHTML = '<div class="mnote-local-ocr-task-drawer" data-testid="mnote-local-ocr-task-drawer" hidden><div class="mnote-local-ocr-task-head"><strong>OCR 任务</strong><button type="button" class="mnote-local-ocr-task-close" data-mnote-local-ocr-task-close aria-label="收起 OCR 任务">×</button></div><div class="mnote-local-ocr-task-list" data-testid="mnote-local-ocr-task-list"></div></div>';
dock.innerHTML = '<div class="mnote-local-ocr-task-drawer" data-testid="mnote-local-ocr-task-drawer" hidden><div class="mnote-local-ocr-task-panel"><div class="mnote-local-ocr-task-head"><div><strong>后台任务</strong><span data-mnote-local-ocr-task-summary>暂无任务</span></div><button type="button" class="mnote-local-ocr-task-close" data-mnote-local-ocr-task-close aria-label="收起后台任务">×</button></div><div class="mnote-local-ocr-task-tabs" data-mnote-local-ocr-task-tabs></div><div class="mnote-local-ocr-task-toolbar"><span data-mnote-local-ocr-task-filter-label>进行中</span><button type="button" data-mnote-local-ocr-task-clear-completed>清除已完成</button></div><div class="mnote-local-ocr-task-list" data-testid="mnote-local-ocr-task-list"></div></div></div>';
document.body.appendChild(dock);
}
let toggle = document.querySelector('[data-testid="mnote-local-ocr-task-toggle"]');
@@ -1509,6 +1578,20 @@ export const createResourceTabRuntime = (dependencies = {}) => {
}
return;
}
const tabButton = event.target instanceof Element ? event.target.closest('[data-mnote-local-ocr-task-tab]') : null;
if (tabButton instanceof HTMLElement) {
localOcrTaskState.taskFilter = tabButton.getAttribute('data-mnote-local-ocr-task-tab') || 'active';
renderLocalOcrTaskDock();
return;
}
const clearCompleted = event.target instanceof Element ? event.target.closest('[data-mnote-local-ocr-task-clear-completed]') : null;
if (clearCompleted instanceof HTMLElement) {
Array.from(localOcrTaskState.jobsBySource.entries()).forEach(([key, job]) => {
if (localOcrTaskCategory(job) === 'completed') localOcrTaskState.jobsBySource.delete(key);
});
renderLocalOcrTaskDock();
return;
}
const deleteButton = event.target instanceof Element ? event.target.closest('[data-mnote-local-ocr-task-delete]') : null;
if (deleteButton instanceof HTMLElement) {
const sourcePath = deleteButton.getAttribute('data-mnote-local-ocr-task-delete') || '';
@@ -1568,12 +1651,18 @@ export const createResourceTabRuntime = (dependencies = {}) => {
const dock = ensureLocalOcrTaskDock();
const jobs = Array.from(localOcrTaskState.jobsBySource.values())
.sort((left, right) => Number(right.updatedAtMs || 0) - Number(left.updatedAtMs || 0));
const runningCount = jobs.filter((job) => !['done', 'failed', 'stale'].includes(String(job?.status || ''))).length;
const toggle = document.querySelector('[data-testid="mnote-local-ocr-task-toggle"]');
if (toggle instanceof HTMLButtonElement) {
const activeJobs = jobs.filter((job) => localOcrTaskCategory(job) === 'active');
const attentionJobs = jobs.filter((job) => localOcrTaskCategory(job) === 'attention');
const completedJobs = jobs.filter((job) => localOcrTaskCategory(job) === 'completed');
const runningCount = activeJobs.length;
const taskToggles = Array.from(document.querySelectorAll('[data-testid="mnote-local-ocr-task-toggle"], [data-testid="mnote-floating-task-toggle"]'))
.filter((node) => node instanceof HTMLButtonElement);
taskToggles.forEach((toggle) => {
const opensSettings = toggle.getAttribute('data-mnote-action') === 'open-ocr-settings';
const label = runningCount > 0 ? `${runningCount} 个 OCR 处理中,打开 OCR 设置` : (jobs.length > 0 ? `${jobs.length} 个 OCR 任务,打开 OCR 设置` : 'OCR 设置');
toggle.setAttribute('title', label);
toggle.setAttribute('aria-label', label);
const taskLabel = runningCount > 0 ? `${runningCount} 个后台任务正在运行` : (jobs.length > 0 ? `${jobs.length} 个后台任务` : '后台任务');
toggle.setAttribute('title', opensSettings ? label : taskLabel);
toggle.setAttribute('aria-label', opensSettings ? label : taskLabel);
toggle.setAttribute('aria-expanded', localOcrTaskState.drawerOpen ? 'true' : 'false');
toggle.classList.toggle('has-mnote-local-ocr-tasks', jobs.length > 0);
const badge = toggle.querySelector('[data-mnote-local-ocr-task-count]');
@@ -1583,28 +1672,85 @@ export const createResourceTabRuntime = (dependencies = {}) => {
} else {
toggle.textContent = runningCount > 0 ? `OCR ${runningCount} 处理中` : `OCR ${jobs.length}`;
}
}
});
const drawer = dock.querySelector('[data-testid="mnote-local-ocr-task-drawer"]');
if (drawer instanceof HTMLElement) drawer.hidden = !localOcrTaskState.drawerOpen;
const summary = dock.querySelector('[data-mnote-local-ocr-task-summary]');
if (summary instanceof HTMLElement) {
summary.textContent = `${runningCount} 进行中 · ${attentionJobs.length} 需处理 · ${completedJobs.length} 已完成`;
}
const tabs = dock.querySelector('[data-mnote-local-ocr-task-tabs]');
if (tabs instanceof HTMLElement) {
const tabItems = [
['active', '进行中', activeJobs.length],
['attention', '需处理', attentionJobs.length],
['completed', '已完成', completedJobs.length],
['all', '全部', jobs.length],
];
tabs.replaceChildren();
tabItems.forEach(([key, label, count]) => {
const button = document.createElement('button');
button.type = 'button';
button.setAttribute('data-mnote-local-ocr-task-tab', key);
button.setAttribute('aria-selected', localOcrTaskState.taskFilter === key ? 'true' : 'false');
button.textContent = `${label} ${count}`;
tabs.appendChild(button);
});
}
const filterLabel = dock.querySelector('[data-mnote-local-ocr-task-filter-label]');
if (filterLabel instanceof HTMLElement) filterLabel.textContent = localOcrTaskFilterLabel(localOcrTaskState.taskFilter);
const clearCompleted = dock.querySelector('[data-mnote-local-ocr-task-clear-completed]');
if (clearCompleted instanceof HTMLButtonElement) clearCompleted.disabled = completedJobs.length === 0;
const list = dock.querySelector('[data-testid="mnote-local-ocr-task-list"]');
if (!(list instanceof HTMLElement)) return;
list.replaceChildren();
if (!jobs.length) {
const visibleJobs = jobs.filter((job) => {
return localOcrTaskState.taskFilter === 'all' || localOcrTaskCategory(job) === localOcrTaskState.taskFilter;
});
if (!visibleJobs.length) {
const empty = document.createElement('div');
empty.className = 'mnote-local-ocr-task-empty';
empty.textContent = '暂无 OCR 任务';
empty.textContent = jobs.length ? `暂无${localOcrTaskFilterLabel(localOcrTaskState.taskFilter)}任务` : '暂无后台任务';
list.appendChild(empty);
return;
}
jobs.forEach((job) => {
visibleJobs.forEach((job) => {
const row = document.createElement('div');
row.className = 'mnote-local-ocr-task-row';
row.setAttribute('data-mnote-local-ocr-task-row', String(job.sourceRootRelativePath || ''));
row.setAttribute('data-mnote-local-ocr-task-status', String(job.status || ''));
row.setAttribute('data-mnote-local-ocr-task-category', localOcrTaskCategory(job));
const title = String(job.sourceRootRelativePath || '').split('/').filter(Boolean).pop() || 'OCR';
row.innerHTML = '<div class="mnote-local-ocr-task-main"><strong></strong><span></span></div><div class="mnote-local-ocr-task-actions"><button type="button" data-mnote-local-ocr-task-open>打开</button><button type="button" data-mnote-local-ocr-task-retry>重试</button><button type="button" data-mnote-local-ocr-task-clear>清除</button><button type="button" data-mnote-local-ocr-task-delete>删除</button></div>';
row.querySelector('strong').textContent = title;
row.querySelector('span').textContent = statusTextForLocalOcrJob(job);
const category = localOcrTaskCategory(job);
const progress = localOcrTaskProgress(job);
row.innerHTML = '<div class="mnote-local-ocr-task-main"><div class="mnote-local-ocr-task-title-line"><strong></strong><em></em></div><span></span><div class="mnote-local-ocr-task-progress" role="progressbar"><i></i></div></div><div class="mnote-local-ocr-task-actions"><button type="button" data-mnote-local-ocr-task-open>打开</button><button type="button" data-mnote-local-ocr-task-retry>重试</button><button type="button" data-mnote-local-ocr-task-clear>清除</button><button type="button" data-mnote-local-ocr-task-delete>删除</button></div>';
const titleNode = row.querySelector('strong');
if (titleNode instanceof HTMLElement) {
titleNode.textContent = title;
titleNode.setAttribute('title', String(job.sourceRootRelativePath || title));
}
const categoryNode = row.querySelector('em');
if (categoryNode instanceof HTMLElement) {
categoryNode.textContent = category === 'active' ? '进行中' : category === 'attention' ? '需处理' : '已完成';
}
const statusNode = row.querySelector('span');
if (statusNode instanceof HTMLElement) statusNode.textContent = statusTextForLocalOcrJob(job);
const progressBar = row.querySelector('.mnote-local-ocr-task-progress');
const progressValue = row.querySelector('.mnote-local-ocr-task-progress i');
if (progressBar instanceof HTMLElement && progressValue instanceof HTMLElement) {
progressBar.hidden = category !== 'active' && progress === null;
progressBar.setAttribute('aria-valuemin', '0');
progressBar.setAttribute('aria-valuemax', '100');
if (progress === null) {
progressBar.setAttribute('data-progress-mode', 'indeterminate');
progressBar.removeAttribute('aria-valuenow');
progressValue.style.width = '';
} else {
progressBar.setAttribute('data-progress-mode', 'determinate');
progressBar.setAttribute('aria-valuenow', String(progress));
progressValue.style.width = `${progress}%`;
}
}
const open = row.querySelector('[data-mnote-local-ocr-task-open]');
if (open instanceof HTMLButtonElement) {
open.setAttribute('data-mnote-local-ocr-task-open', String(job.sourceRootRelativePath || ''));
@@ -2178,6 +2324,20 @@ export const createResourceTabRuntime = (dependencies = {}) => {
return true;
};
const officePreviewBaseHref = (href) => {
const raw = String(href || '').trim();
if (!raw) return '';
try {
const url = new URL(raw, window.location.origin);
['page', 'bbox', 'sourceMapPath', 'blockId', 'lineRange', 'charRange', 'mnoteResourceReload'].forEach((key) => {
url.searchParams.delete(key);
});
return url.pathname + '?' + url.searchParams.toString();
} catch (_) {
return raw;
}
};
const refreshExistingOfficeResourceTab = (entry, input) => {
if (!entry || entry.kind !== 'office') return false;
const nextHref = String(input.officeUrl || input.href || '').trim();
@@ -2186,7 +2346,7 @@ export const createResourceTabRuntime = (dependencies = {}) => {
const currentHref = frame instanceof HTMLIFrameElement
? String(frame.getAttribute('src') || frame.src || '').trim()
: '';
if (currentHref !== nextHref) void openPassiveResourceTab(entry, input);
if (officePreviewBaseHref(currentHref) !== officePreviewBaseHref(nextHref)) void openPassiveResourceTab(entry, input);
return true;
};
@@ -24,6 +24,12 @@ export function createSidebarPageAiMarkdownRuntime(context) {
codeSpans.push('<code>' + code + '</code>');
return key;
});
html = html.replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, function(match, label, href) {
var normalizedHref = normalizePageAiMarkdownHref(href);
if (!normalizedHref) return match;
var citationAttr = isMnoteCitationHref(normalizedHref) ? ' data-page-ai-citation-link="true"' : '';
return '<a href="' + escapeHtml(normalizedHref) + '" target="_blank" rel="noopener noreferrer"' + citationAttr + '>' + label + '</a>';
});
html = html.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
html = html.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
codeSpans.forEach(function(value, index) {
@@ -32,6 +38,28 @@ export function createSidebarPageAiMarkdownRuntime(context) {
return html;
}
function normalizePageAiMarkdownHref(value) {
var href = String(value || '').trim()
.replace(/&amp;/g, '&')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'");
if (!href || /[\u0000-\u001f<>"']/.test(href)) return '';
var lower = href.toLowerCase();
if (lower.startsWith('javascript:') || lower.startsWith('data:') || lower.startsWith('vbscript:')) return '';
if (href.startsWith('/') || href.startsWith('#')) return href;
if (/^https?:\/\//i.test(href) || /^mailto:/i.test(href)) return href;
return '';
}
function isMnoteCitationHref(href) {
try {
var url = new URL(href, window.location.origin);
return url.origin === window.location.origin && url.pathname.startsWith('/documents/');
} catch (_error) {
return false;
}
}
function renderPageAiMarkdown(content) {
var lines = String(content || '').replace(/\r\n?/g, '\n').split('\n');
var blocks = [];
@@ -154,7 +154,7 @@ export function createSidebarPageAiProfileRuntime(context) {
function pageAiSessionAgentFilterOptions(rows) {
var byValue = { all: '全部 agent' };
pageAiNormalizeArray(rows).forEach(function(session) {
pageAiNormalizeArray(rows).filter(pageAiVisibleHistorySession).forEach(function(session) {
var value = pageAiSessionAgentFilterValue(session);
byValue[value] = pageAiSessionAgentLabel(session);
});
@@ -163,9 +163,16 @@ export function createSidebarPageAiProfileRuntime(context) {
});
}
function pageAiVisibleHistorySession(session) {
var source = String(session && session.source || '').trim();
var status = String(session && session.status || '').trim();
var messages = pageAiNormalizeArray(session && session.messages);
return !(source === 'draft' && status === 'draft' && messages.length === 0);
}
function pageAiFilteredHistoryRows(rows) {
var filterValue = String(pageUiState.pageAiSessionAgentFilter || 'all').trim() || 'all';
var normalized = pageAiNormalizeArray(rows);
var normalized = pageAiNormalizeArray(rows).filter(pageAiVisibleHistorySession);
if (filterValue === 'all') return normalized;
return normalized.filter(function(session) {
return pageAiSessionAgentFilterValue(session) === filterValue;
@@ -563,10 +563,13 @@ export function createSidebarPageAiRenderRuntime(context) {
var skillSourceSelect = drawer.querySelector('[data-page-ai-skill-source-select]');
if (skillSourceSelect instanceof HTMLSelectElement) {
var activeSkillSource = pageAiCurrentSkillSource();
skillSourceSelect.innerHTML = pageAiSkillSourceOptions().map(function(option) {
var sourceOptions = pageAiSkillSourceOptions();
skillSourceSelect.innerHTML = sourceOptions.map(function(option) {
return '<option value="' + escapeHtml(option.value) + '"' + (option.value === activeSkillSource ? ' selected' : '') + '>' + escapeHtml(option.label) + '</option>';
}).join('');
skillSourceSelect.value = activeSkillSource;
var sourceControl = skillSourceSelect.closest('[data-page-ai-skill-source-control]');
if (sourceControl instanceof HTMLElement) sourceControl.hidden = sourceOptions.length <= 1;
}
var hermesBuiltinToggle = drawer.querySelector('[data-page-ai-hide-hermes-builtin]');
if (hermesBuiltinToggle instanceof HTMLInputElement) {
@@ -580,7 +583,7 @@ export function createSidebarPageAiRenderRuntime(context) {
if (skillList instanceof HTMLElement) {
var skills = pageAiFilteredSkillEntries();
if (!skills.length) {
skillList.innerHTML = '<div class="wolai-page-ai-empty">没有匹配的能。</div>';
skillList.innerHTML = '<div class="wolai-page-ai-empty">没有匹配的能。</div>';
} else {
var sourceParts = pageAiSkillSourceParts(pageAiCurrentSkillSource());
var group = sourceParts.group;
@@ -593,14 +596,33 @@ export function createSidebarPageAiRenderRuntime(context) {
'<span>' + escapeHtml(String(skills.length) + headingExtra) + '</span>' +
'</button>' +
(collapsed ? '' : skills.map(function(skill) {
var sourceText = pageAiSkillOriginLabel(skill)
+ (skill.configScope ? ' · ' + skill.configScope : '')
+ (skill.readOnly ? ' · 只读' : '')
+ (skill.modified ? ' · modified' : '');
var toolCount = Number(skill.toolCount || pageAiNormalizeArray(skill.tools).length || 0);
var disabledToolCount = Number(skill.disabledToolCount || 0);
var capabilityMeta = [];
if (toolCount > 0) capabilityMeta.push(String(toolCount) + ' 工具');
if (disabledToolCount > 0) capabilityMeta.push(String(disabledToolCount) + ' 已关闭');
if (pageAiNormalizeArray(skill.requiresContextRefs).length > 0) capabilityMeta.push('需要上下文');
var categoryText = group === 'mnote' ? String(skill.categoryTitle || skill.category || '').trim() : '';
var sourceMetaParts = [];
if (group === 'mnote') {
sourceMetaParts.push(categoryText || 'MNote');
} else {
sourceMetaParts.push(pageAiSkillOriginLabel(skill));
sourceMetaParts.push('只读查看');
}
if (capabilityMeta.length) sourceMetaParts = sourceMetaParts.concat(capabilityMeta);
if (skill.readOnly && group === 'mnote') sourceMetaParts.push('只读');
if (skill.modified) sourceMetaParts.push('modified');
var sourceText = sourceMetaParts.filter(Boolean).join(' · ');
var description = String(skill.description || '').trim();
var hasDescription = description && description !== '---' && description !== '无描述';
var displayName = String(skill.title || skill.name || skill.id || '').trim();
var disabled = skill.toggleable === false || skill.readOnly === true;
var switchControl = group === 'mnote'
? '<button type="button" class="wolai-page-ai-skill-switch' + (pageAiSkillEnabled(skill) ? ' is-on' : '') + '" data-page-ai-skill-toggle="' + escapeHtml(skill.id || skill.name) + '" data-page-ai-skill-group="' + escapeHtml(group) + '" data-page-ai-skill-profile="' + escapeHtml(skill.profile || sourceParts.profile || '') + '" data-page-ai-skill-kind="' + escapeHtml(skill.skillKind || '') + '" aria-pressed="' + (pageAiSkillEnabled(skill) ? 'true' : 'false') + '"' + (disabled ? ' disabled' : '') + '>' +
'<span></span>' +
'</button>'
: '<span class="wolai-page-ai-skill-readonly-badge">查看</span>';
return '' +
'<div class="wolai-page-ai-skill-row">' +
'<div class="wolai-page-ai-skill-copy">' +
@@ -610,9 +632,7 @@ export function createSidebarPageAiRenderRuntime(context) {
'</div>' +
(hasDescription ? '<div class="wolai-page-ai-skill-desc">' + escapeHtml(description) + '</div>' : '') +
'</div>' +
'<button type="button" class="wolai-page-ai-skill-switch' + (pageAiSkillEnabled(skill) ? ' is-on' : '') + '" data-page-ai-skill-toggle="' + escapeHtml(skill.id || skill.name) + '" data-page-ai-skill-group="' + escapeHtml(group) + '" data-page-ai-skill-profile="' + escapeHtml(skill.profile || sourceParts.profile || '') + '" data-page-ai-skill-kind="' + escapeHtml(skill.skillKind || '') + '" aria-pressed="' + (pageAiSkillEnabled(skill) ? 'true' : 'false') + '"' + (disabled ? ' disabled' : '') + '>' +
'<span></span>' +
'</button>' +
switchControl +
'</div>';
}).join('')) +
'</section>';
@@ -751,7 +771,7 @@ export function createSidebarPageAiRenderRuntime(context) {
'<div class="wolai-page-ai-header-actions">' +
'<button type="button" class="wolai-page-ai-icon" data-page-ai-action="new-session" aria-label="新建 AI 会话" title="新建 AI 会话"></button>' +
'<button type="button" class="wolai-page-ai-icon" data-page-ai-action="history" aria-label="历史会话" title="历史会话">⌕</button>' +
'<button type="button" class="wolai-page-ai-icon" data-page-ai-tab="skills" aria-label="能" title="能">' +
'<button type="button" class="wolai-page-ai-icon" data-page-ai-tab="skills" aria-label="能" title="能">' +
'<svg class="wolai-page-ai-icon-svg" viewBox="0 0 24 24" aria-hidden="true" focusable="false">' +
'<path d="M12 3l1.35 4.15L17.5 8.5l-4.15 1.35L12 14l-1.35-4.15L6.5 8.5l4.15-1.35L12 3z" />' +
'<path d="M18.5 13l.8 2.4 2.2.8-2.2.8-.8 2.4-.8-2.4-2.2-.8 2.2-.8.8-2.4z" />' +
@@ -856,17 +876,17 @@ export function createSidebarPageAiRenderRuntime(context) {
'<button type="button" class="wolai-page-ai-back" data-page-ai-tab="chat">← 聊天</button>' +
'<div class="wolai-page-ai-settings-tabs" role="tablist" aria-label="页面 AI 设置">' +
'<button type="button" class="wolai-page-ai-tab" data-page-ai-tab="agent" role="tab" aria-selected="false">Agent</button>' +
'<button type="button" class="wolai-page-ai-tab is-active" data-page-ai-tab="skills" role="tab" aria-selected="true">Skills</button>' +
'<button type="button" class="wolai-page-ai-tab is-active" data-page-ai-tab="skills" role="tab" aria-selected="true">能力</button>' +
'<button type="button" class="wolai-page-ai-tab" data-page-ai-tab="runtime" role="tab" aria-selected="false">Runtime</button>' +
'</div>' +
'</div>' +
'<div class="wolai-page-ai-skills-toolbar">' +
'<label class="wolai-page-ai-skill-search">' +
'<span>搜索能</span>' +
'<input type="search" data-page-ai-skill-search placeholder="搜索能…" />' +
'<span>搜索能</span>' +
'<input type="search" data-page-ai-skill-search placeholder="搜索能…" />' +
'</label>' +
'<label class="wolai-page-ai-profile-select" data-page-ai-skill-source-control>' +
'<span>能来源</span>' +
'<span>能来源</span>' +
'<select data-page-ai-skill-source-select></select>' +
'</label>' +
'<label class="wolai-page-ai-skill-filter-toggle">' +
@@ -882,7 +902,7 @@ export function createSidebarPageAiRenderRuntime(context) {
'<button type="button" class="wolai-page-ai-back" data-page-ai-tab="chat">← 聊天</button>' +
'<div class="wolai-page-ai-settings-tabs" role="tablist" aria-label="页面 AI 设置">' +
'<button type="button" class="wolai-page-ai-tab" data-page-ai-tab="agent" role="tab" aria-selected="false">Agent</button>' +
'<button type="button" class="wolai-page-ai-tab" data-page-ai-tab="skills" role="tab" aria-selected="false">Skills</button>' +
'<button type="button" class="wolai-page-ai-tab" data-page-ai-tab="skills" role="tab" aria-selected="false">能力</button>' +
'<button type="button" class="wolai-page-ai-tab is-active" data-page-ai-tab="runtime" role="tab" aria-selected="true">Runtime</button>' +
'</div>' +
'</div>' +
@@ -911,9 +931,9 @@ export function createSidebarPageAiRenderRuntime(context) {
'</div>' +
'<div class="wolai-page-ai-tool-list" data-page-ai-queue-list></div>' +
'</div>' +
'<div class="wolai-page-ai-tools-panel">' +
'<div class="wolai-page-ai-tools-panel" hidden>' +
'<div class="wolai-page-ai-tools-head">' +
'<span>mnote tools</span>' +
'<span>MNote 工具调试</span>' +
'<span data-page-ai-last-tool>暂无 tool call</span>' +
'</div>' +
'<div class="wolai-page-ai-inline-error" data-page-ai-tool-error hidden></div>' +
@@ -982,6 +1002,231 @@ export function createSidebarPageAiRenderRuntime(context) {
}).join('');
}
function pageAiConversationShouldStickToBottom(conversation) {
var distance = conversation.scrollHeight - conversation.scrollTop - conversation.clientHeight;
return distance <= 48;
}
function pageAiCaptureOpenToolDetails(conversation) {
var openToolDetails = {};
conversation.querySelectorAll('[data-page-ai-collapse-card], [data-page-ai-tool-card]').forEach(function(card) {
if (!(card instanceof HTMLElement)) return;
var key = String(card.getAttribute('data-page-ai-collapse-id') || card.getAttribute('data-page-ai-tool-group-id') || card.getAttribute('data-page-ai-tool-call-id') || '').trim();
var details = card.querySelector('[data-page-ai-collapse-details], .wolai-page-ai-tool-details');
if (key && details instanceof HTMLDetailsElement && details.open) {
openToolDetails[key] = true;
}
});
return openToolDetails;
}
function pageAiRestoreOpenToolDetails(conversation, openToolDetails) {
if (!openToolDetails || typeof openToolDetails !== 'object') return;
conversation.querySelectorAll('[data-page-ai-collapse-card], [data-page-ai-tool-card]').forEach(function(card) {
if (!(card instanceof HTMLElement)) return;
var key = String(card.getAttribute('data-page-ai-collapse-id') || card.getAttribute('data-page-ai-tool-group-id') || card.getAttribute('data-page-ai-tool-call-id') || '').trim();
if (!key || openToolDetails[key] !== true) return;
var details = card.querySelector('[data-page-ai-collapse-details], .wolai-page-ai-tool-details');
if (details instanceof HTMLDetailsElement) details.open = true;
});
}
function pageAiRenderToolDetailRows(item) {
var locationRows = Array.isArray(item.locations) && item.locations.length
? '<div class="wolai-page-ai-tool-meta">位置:' + item.locations.map(function(loc) {
return '<span style="display:inline-flex;align-items:center;gap:4px;margin-right:8px">' +
'<span>' + escapeHtml(loc) + '</span>' +
'<button type="button" class="wolai-page-ai-ghost" style="font-size:0.85em;padding:0 4px;min-width:unset" data-page-ai-open-location="' + escapeHtml(loc) + '" data-page-ai-tool-call-id="' + escapeHtml(item.toolCallId || '') + '" title="打开文件">打开</button>' +
'</span>';
}).join('') + '</div>'
: '';
return [
locationRows,
item.argsSummary ? '<div class="wolai-page-ai-tool-meta">参数 ' + escapeHtml(item.argsSummary) + '</div>' : '',
item.resultSummary ? '<div class="wolai-page-ai-tool-meta">结果 ' + escapeHtml(item.resultSummary) + '</div>' : '',
item.changedFiles && item.changedFiles.length ? '<pre class="wolai-page-ai-tool-meta wolai-page-ai-changed-files">' + escapeHtml(pageAiFormatChangedFiles(item.changedFiles)) + '</pre>' : '',
(item.traceId || item.auditId) ? '<div class="wolai-page-ai-tool-meta">' + escapeHtml([item.traceId, item.auditId].filter(Boolean).join(' · ')) + '</div>' : ''
].filter(Boolean).join('');
}
function pageAiToolStatusLabel(status) {
if (status === 'completed') return '完成';
if (status === 'failed') return '失败';
return '运行中';
}
function pageAiToolGroupStatus(items) {
if (items.some(function(item) { return item.status === 'failed'; })) return 'failed';
if (items.some(function(item) { return item.status !== 'completed'; })) return 'running';
return 'completed';
}
function pageAiRenderToolGroup(items, groupIndex) {
var tools = pageAiNormalizeArray(items);
if (!tools.length) return '';
var status = pageAiToolGroupStatus(tools);
var completedCount = tools.filter(function(item) { return item.status === 'completed'; }).length;
var failedCount = tools.filter(function(item) { return item.status === 'failed'; }).length;
var runningCount = tools.length - completedCount - failedCount;
var countParts = [String(tools.length) + ' 个'];
if (completedCount) countParts.push('完成 ' + String(completedCount));
if (failedCount) countParts.push('失败 ' + String(failedCount));
if (runningCount) countParts.push('运行中 ' + String(runningCount));
var firstToolId = String(tools[0] && tools[0].toolCallId || '').trim();
var groupId = 'tool-group-' + String(groupIndex) + '-' + (firstToolId || String(tools.length));
var rows = tools.map(function(item) {
var statusLabel = pageAiToolStatusLabel(item.status);
var meta = [statusLabel, item.toolKind, item.toolCallId].filter(Boolean).join(' · ');
return '' +
'<div class="wolai-page-ai-tool-item" data-page-ai-tool-item data-page-ai-tool-call-id="' + escapeHtml(item.toolCallId || '') + '" data-page-ai-tool-status="' + escapeHtml(item.status || '') + '">' +
'<div class="wolai-page-ai-tool-item-head">' +
'<strong>' + escapeHtml(item.toolName || item.content || 'tool') + '</strong>' +
'<span>' + escapeHtml(meta) + '</span>' +
'</div>' +
(pageAiRenderToolDetailRows(item) || '<div class="wolai-page-ai-tool-meta">暂无参数或结果详情。</div>') +
'</div>';
}).join('');
return '' +
'<div class="wolai-page-ai-message wolai-page-ai-message--tool" data-page-ai-collapse-card data-page-ai-collapse-id="' + escapeHtml(groupId) + '" data-page-ai-tool-card data-page-ai-tool-group="true" data-page-ai-tool-group-id="' + escapeHtml(groupId) + '" data-page-ai-tool-status="' + escapeHtml(status) + '">' +
'<div class="wolai-page-ai-message-role">工具</div>' +
'<div class="wolai-page-ai-message-text">' +
'<details class="wolai-page-ai-tool-details wolai-page-ai-tool-group-details" data-page-ai-collapse-details>' +
'<summary>' +
'<strong>调用工具</strong>' +
'<span>' + escapeHtml(countParts.join(' · ')) + '</span>' +
'</summary>' +
'<div class="wolai-page-ai-tool-group-list">' + rows + '</div>' +
'</details>' +
'</div>' +
'</div>';
}
function pageAiRenderThoughtGroup(items, groupIndex) {
var thoughts = pageAiNormalizeArray(items).filter(function(item) {
return item && item.kind === 'thought' && String(item.content || '').trim();
});
if (!thoughts.length) return '';
var firstText = String(thoughts[0] && thoughts[0].content || '').slice(0, 24).replace(/\s+/g, ' ').trim();
var groupId = 'thought-group-' + String(groupIndex) + '-' + String(thoughts.length) + '-' + (firstText || 'delta');
var content = thoughts.map(function(item) {
return String(item.content || '').trim();
}).filter(Boolean).join('\n\n');
var countLabel = thoughts.length > 1 ? String(thoughts.length) + ' 段' : '1 段';
return '' +
'<div class="wolai-page-ai-message wolai-page-ai-message--assistant" data-page-ai-collapse-card data-page-ai-collapse-id="' + escapeHtml(groupId) + '" data-page-ai-thought-card="true">' +
'<div class="wolai-page-ai-message-role">AI</div>' +
'<div class="wolai-page-ai-message-text">' +
'<details class="wolai-page-ai-tool-details wolai-page-ai-thought-group-details" data-page-ai-collapse-details data-page-ai-thought-delta="true">' +
'<summary>' +
'<strong>思考过程</strong>' +
'<span>' + escapeHtml(countLabel) + '</span>' +
'</summary>' +
'<div class="wolai-page-ai-thought-group-list">' + escapeHtml(content) + '</div>' +
'</details>' +
'</div>' +
'</div>';
}
function pageAiRenderNonToolMessage(item) {
var roleLabel = item.role === 'user' ? '你' : (item.role === 'tool' ? '工具' : 'AI');
if (item.kind === 'thought') {
return '' +
'<div class="wolai-page-ai-message wolai-page-ai-message--assistant" data-page-ai-collapse-card data-page-ai-collapse-id="thought-single">' +
'<div class="wolai-page-ai-message-role">AI</div>' +
'<div class="wolai-page-ai-message-text">' +
'<details class="wolai-page-ai-tool-details wolai-page-ai-thought-group-details" data-page-ai-collapse-details data-page-ai-thought-delta="true">' +
'<summary><strong>思考过程</strong><span>1 段</span></summary>' +
'<div class="wolai-page-ai-thought-group-list">' + escapeHtml(item.content || '') + '</div>' +
'</details>' +
'</div>' +
'</div>';
}
if (item.kind === 'permission') {
var permissionActions = item.resolved ? '' : (
'<div class="wolai-page-ai-message-actions">' +
'<button type="button" class="wolai-page-ai-ghost" data-page-ai-permission-action="allow" data-page-ai-permission-id="' + escapeHtml(item.permissionId || '') + '">允许</button>' +
'<button type="button" class="wolai-page-ai-ghost" data-page-ai-permission-action="deny" data-page-ai-permission-id="' + escapeHtml(item.permissionId || '') + '">拒绝</button>' +
'</div>'
);
return '' +
'<div class="wolai-page-ai-message wolai-page-ai-message--tool" data-page-ai-permission-request="' + escapeHtml(item.permissionId || '') + '">' +
'<div class="wolai-page-ai-message-role">权限</div>' +
'<div class="wolai-page-ai-message-text">' +
'<strong>' + escapeHtml(item.toolName || 'session/request_permission') + '</strong><br />' +
'<span>' + escapeHtml(item.argsSummary || item.content || '') + '</span>' +
permissionActions +
'</div>' +
'</div>';
}
if (item.kind === 'plan') {
var planEntries = Array.isArray(item.entries) ? item.entries : [];
var listHtml = planEntries.map(function(entry) {
return '<li style="margin:2px 0">' + escapeHtml(String(entry || '')) + '</li>';
}).join('');
return '' +
'<div class="wolai-page-ai-message wolai-page-ai-message--assistant" data-page-ai-plan="true">' +
'<details class="wolai-page-ai-plan-details" open>' +
'<summary class="wolai-page-ai-message-role" style="cursor:pointer;user-select:none;opacity:0.8;font-size:0.85em">执行计划 · ' + planEntries.length + ' 步</summary>' +
'<div class="wolai-page-ai-message-text" style="margin-top:4px;opacity:0.75;font-size:0.9em;border-left:2px solid var(--wolai-border-color, #ddd);padding-left:8px">' +
'<ol style="margin:4px 0;padding-left:20px">' + listHtml + '</ol>' +
'</div>' +
'</details>' +
'</div>';
}
var streamingAttr = item.streaming ? ' data-page-ai-streaming="true"' : '';
return '' +
'<div class="wolai-page-ai-message wolai-page-ai-message--' + escapeHtml(item.role || 'assistant') + '"' + streamingAttr + '>' +
'<div class="wolai-page-ai-message-role">' + escapeHtml(roleLabel) + '</div>' +
'<div class="wolai-page-ai-message-text">' + (item.role === 'assistant' ? renderPageAiMarkdown(item.content || '') : escapeHtml(item.content || '')) + '</div>' +
'</div>';
}
function pageAiConversationRenderHtml(messages) {
var turns = [];
var current = null;
function ensureTurn() {
if (!current) current = { user: null, tools: [], status: [], assistants: [], others: [] };
return current;
}
function flushTurn() {
if (!current) return;
turns.push(current);
current = null;
}
pageAiNormalizeArray(messages).forEach(function(item) {
if (item && item.role === 'user') {
flushTurn();
current = { user: item, tools: [], status: [], assistants: [], others: [] };
return;
}
var turn = ensureTurn();
if (item && item.role === 'tool' && item.kind !== 'permission') {
turn.tools.push(item);
} else if (item && (item.kind === 'thought' || item.kind === 'plan' || item.kind === 'permission')) {
turn.status.push(item);
} else if (item && item.role === 'assistant') {
turn.assistants.push(item);
} else {
turn.others.push(item);
}
});
flushTurn();
var toolGroupIndex = 0;
var thoughtGroupIndex = 0;
return turns.map(function(turn) {
var html = [];
if (turn.user) html.push(pageAiRenderNonToolMessage(turn.user));
if (turn.tools.length) html.push(pageAiRenderToolGroup(turn.tools, toolGroupIndex++));
var thoughts = turn.status.filter(function(item) { return item && item.kind === 'thought'; });
var otherStatus = turn.status.filter(function(item) { return !(item && item.kind === 'thought'); });
if (thoughts.length) html.push(pageAiRenderThoughtGroup(thoughts, thoughtGroupIndex++));
html = html.concat(otherStatus.map(pageAiRenderNonToolMessage));
html = html.concat(turn.assistants.map(pageAiRenderNonToolMessage));
html = html.concat(turn.others.map(pageAiRenderNonToolMessage));
return html.join('');
}).join('');
}
function renderPageAiConversation() {
var drawer = ensurePageAiDrawer();
renderPageAiSuggestions();
@@ -1022,86 +1267,17 @@ export function createSidebarPageAiRenderRuntime(context) {
conversation.innerHTML = '<div class="wolai-page-ai-empty">围绕当前页面提问,我会优先使用当前页内容、页面结构和已保存设置。</div>';
return;
}
conversation.innerHTML = pageUiState.pageAiMessages.map(function(item) {
var roleLabel = item.role === 'user' ? '你' : (item.role === 'tool' ? '工具' : 'AI');
if (item.role === 'tool') {
var statusLabel = item.status === 'completed' ? '完成' : (item.status === 'failed' ? '失败' : '运行中');
var locationRows = Array.isArray(item.locations) && item.locations.length
? '<div class="wolai-page-ai-tool-meta">位置:' + item.locations.map(function(loc, idx) {
return '<span style="display:inline-flex;align-items:center;gap:4px;margin-right:8px">' +
'<span>' + escapeHtml(loc) + '</span>' +
'<button type="button" class="wolai-page-ai-ghost" style="font-size:0.85em;padding:0 4px;min-width:unset" data-page-ai-open-location="' + escapeHtml(loc) + '" data-page-ai-tool-call-id="' + escapeHtml(item.toolCallId || '') + '" title="打开文件">打开</button>' +
'</span>';
}).join('') + '</div>'
: '';
var detailRows = [
locationRows,
item.argsSummary ? '<div class="wolai-page-ai-tool-meta">参数 ' + escapeHtml(item.argsSummary) + '</div>' : '',
item.resultSummary ? '<div class="wolai-page-ai-tool-meta">结果 ' + escapeHtml(item.resultSummary) + '</div>' : '',
item.changedFiles && item.changedFiles.length ? '<pre class="wolai-page-ai-tool-meta wolai-page-ai-changed-files">' + escapeHtml(pageAiFormatChangedFiles(item.changedFiles)) + '</pre>' : '',
(item.traceId || item.auditId) ? '<div class="wolai-page-ai-tool-meta">' + escapeHtml([item.traceId, item.auditId].filter(Boolean).join(' · ')) + '</div>' : ''
].filter(Boolean).join('');
return '' +
'<div class="wolai-page-ai-message wolai-page-ai-message--tool" data-page-ai-tool-card data-page-ai-tool-call-id="' + escapeHtml(item.toolCallId || '') + '" data-page-ai-tool-status="' + escapeHtml(item.status || '') + '">' +
'<div class="wolai-page-ai-message-role">' + escapeHtml(roleLabel) + '</div>' +
'<div class="wolai-page-ai-message-text">' +
'<details class="wolai-page-ai-tool-details">' +
'<summary>' +
'<strong>' + escapeHtml(item.toolName || item.content || 'tool') + '</strong>' +
'<span>' + escapeHtml([statusLabel, item.toolKind, item.toolCallId].filter(Boolean).join(' · ')) + '</span>' +
'</summary>' +
(detailRows || '<div class="wolai-page-ai-tool-meta">暂无参数或结果详情。</div>') +
'</details>' +
'</div>' +
'</div>';
}
if (item.kind === 'thought') {
return '' +
'<details class="wolai-page-ai-message wolai-page-ai-message--assistant" data-page-ai-thought-delta="true">' +
'<summary class="wolai-page-ai-message-role" style="cursor:pointer;user-select:none;opacity:0.7;font-size:0.85em">思考过程</summary>' +
'<div class="wolai-page-ai-message-text" style="margin-top:4px;opacity:0.6;font-size:0.9em;border-left:2px solid var(--wolai-border-color, #ddd);padding-left:8px">' + escapeHtml(item.content || '') + '</div>' +
'</details>';
}
if (item.kind === 'permission') {
var permissionActions = item.resolved ? '' : (
'<div class="wolai-page-ai-message-actions">' +
'<button type="button" class="wolai-page-ai-ghost" data-page-ai-permission-action="allow" data-page-ai-permission-id="' + escapeHtml(item.permissionId || '') + '">允许</button>' +
'<button type="button" class="wolai-page-ai-ghost" data-page-ai-permission-action="deny" data-page-ai-permission-id="' + escapeHtml(item.permissionId || '') + '">拒绝</button>' +
'</div>'
);
return '' +
'<div class="wolai-page-ai-message wolai-page-ai-message--tool" data-page-ai-permission-request="' + escapeHtml(item.permissionId || '') + '">' +
'<div class="wolai-page-ai-message-role">权限</div>' +
'<div class="wolai-page-ai-message-text">' +
'<strong>' + escapeHtml(item.toolName || 'session/request_permission') + '</strong><br />' +
'<span>' + escapeHtml(item.argsSummary || item.content || '') + '</span>' +
permissionActions +
'</div>' +
'</div>';
}
if (item.kind === 'plan') {
var planEntries = Array.isArray(item.entries) ? item.entries : [];
var listHtml = planEntries.map(function(entry, idx) {
return '<li style="margin:2px 0">' + escapeHtml(String(entry || '')) + '</li>';
}).join('');
return '' +
'<div class="wolai-page-ai-message wolai-page-ai-message--assistant" data-page-ai-plan="true">' +
'<details class="wolai-page-ai-plan-details" open>' +
'<summary class="wolai-page-ai-message-role" style="cursor:pointer;user-select:none;opacity:0.8;font-size:0.85em">执行计划 · ' + planEntries.length + ' 步</summary>' +
'<div class="wolai-page-ai-message-text" style="margin-top:4px;opacity:0.75;font-size:0.9em;border-left:2px solid var(--wolai-border-color, #ddd);padding-left:8px">' +
'<ol style="margin:4px 0;padding-left:20px">' + listHtml + '</ol>' +
'</div>' +
'</details>' +
'</div>';
}
var streamingAttr = item.streaming ? ' data-page-ai-streaming="true"' : '';
return '' +
'<div class="wolai-page-ai-message wolai-page-ai-message--' + escapeHtml(item.role || 'assistant') + '"' + streamingAttr + '>' +
'<div class="wolai-page-ai-message-role">' + escapeHtml(roleLabel) + '</div>' +
'<div class="wolai-page-ai-message-text">' + (item.role === 'assistant' ? renderPageAiMarkdown(item.content || '') : escapeHtml(item.content || '')) + '</div>' +
'</div>';
}).join('');
conversation.scrollTop = conversation.scrollHeight;
var shouldStickToBottom = pageAiConversationShouldStickToBottom(conversation);
var previousScrollTop = conversation.scrollTop;
var openToolDetails = pageAiCaptureOpenToolDetails(conversation);
conversation.innerHTML = pageAiConversationRenderHtml(pageUiState.pageAiMessages);
pageAiRestoreOpenToolDetails(conversation, openToolDetails);
if (shouldStickToBottom) {
conversation.scrollTop = conversation.scrollHeight;
} else {
var maxScrollTop = Math.max(0, conversation.scrollHeight - conversation.clientHeight);
conversation.scrollTop = Math.min(previousScrollTop, maxScrollTop);
}
}
return {
@@ -724,6 +724,89 @@ export function createSidebarPageAiRuntime(context) {
});
}
function pageAiEvidenceRangeFromParam(value) {
var text = String(value || '').trim();
if (!text) return null;
var match = text.match(/^(\d+)[-:,](\d+)$/);
if (!match) return text;
return { start: Number(match[1]), end: Number(match[2]) };
}
function pageAiEvidenceBboxFromParam(value) {
var text = String(value || '').trim();
if (!text) return null;
var parts = text.split(',').map(function(part) { return Number(part.trim()); });
if (parts.length < 4 || parts.slice(0, 4).some(function(part) { return !Number.isFinite(part); })) return text;
return { x0: parts[0], y0: parts[1], x1: parts[2], y1: parts[3] };
}
function pageAiDocumentIdFromUrl(url) {
var prefix = '/documents/';
if (!url.pathname.startsWith(prefix)) return '';
try {
return decodeURIComponent(url.pathname.slice(prefix.length).split('/')[0] || '');
} catch (_error) {
return url.pathname.slice(prefix.length).split('/')[0] || '';
}
}
function pageAiCitationResourcePath(url, rootUri) {
var explicitPath = String(url.searchParams.get('resourcePath') || '').trim();
if (explicitPath) return explicitPath;
var raw = String(url.searchParams.get('resourceTab') || '').trim();
if (raw.indexOf('::') >= 0) raw = raw.slice(raw.indexOf('::') + 2);
if (!raw.startsWith('resource:file:')) return '';
var rest = raw.slice('resource:file:'.length);
var prefix = String(rootUri || '').trim() + ':';
if (!prefix.trim() || !rest.startsWith(prefix)) return '';
return rest.slice(prefix.length).replace(/^\/+/, '');
}
function pageAiOpenCitationUrl(href) {
var url;
try {
url = new URL(String(href || ''), window.location.origin);
} catch (_error) {
return false;
}
if (url.origin !== window.location.origin || !url.pathname.startsWith('/documents/')) return false;
var rootUri = String(url.searchParams.get('rootUri') || currentRootUri() || '').trim();
var resourcePath = pageAiCitationResourcePath(url, rootUri);
var documentId = pageAiDocumentIdFromUrl(url) || currentDocumentId() || '';
var workspaceId = String(url.searchParams.get('workspaceId') || resolveWorkspaceId(document.body) || '').trim();
if (resourcePath) {
void openLocalResourceInActiveTab({
path: resourcePath,
rootUri: rootUri,
documentId: documentId,
workspaceId: workspaceId,
sourceKind: String(url.searchParams.get('sourceKind') || currentSourceKind() || 'local_folder').trim(),
page: url.searchParams.get('page') || undefined,
bbox: pageAiEvidenceBboxFromParam(url.searchParams.get('bbox')),
sourceMapPath: String(url.searchParams.get('sourceMapPath') || '').trim(),
blockId: String(url.searchParams.get('blockId') || '').trim(),
lineRange: pageAiEvidenceRangeFromParam(url.searchParams.get('lineRange')),
charRange: pageAiEvidenceRangeFromParam(url.searchParams.get('charRange')),
openTarget: 'active-tab',
paneRole: 'primary'
}).then(function(opened) {
if (!opened) window.location.assign(url.pathname + url.search + url.hash);
});
return true;
}
if (typeof window.__mnoteDocumentPaneRuntime?.openPrimaryDocument === 'function') {
void window.__mnoteDocumentPaneRuntime.openPrimaryDocument({
documentId: documentId,
workspaceId: workspaceId,
sourceKind: String(url.searchParams.get('sourceKind') || currentSourceKind() || '').trim(),
rootUri: rootUri,
url: url
});
return true;
}
return false;
}
function pageAiChatOnlyProfileEntries() {
var profiles = pageAiNormalizeArray(pageUiState.pageAiProfiles);
return PAGE_AI_CHAT_ONLY_PROFILE_REGISTRY.map(function(spec) {
@@ -786,10 +869,13 @@ export function createSidebarPageAiRuntime(context) {
var archived = pageAiNormalizeArray(upstream && upstream.archived ? upstream.archived : []);
return {
categories: categories.map(function(category) {
var skillRows = pageAiNormalizeArray(category && (category.skills || category.capabilities));
return {
name: String(category && category.name || '').trim() || 'misc',
description: String(category && category.description || '').trim(),
skills: pageAiNormalizeArray(category && category.skills).map(function(skill) {
title: String(category && category.title || '').trim(),
capabilities: pageAiNormalizeArray(category && category.capabilities),
skills: skillRows.map(function(skill) {
return {
name: String(skill && skill.name || '').trim(),
id: String(skill && skill.id || skill && skill.name || '').trim(),
@@ -807,8 +893,18 @@ export function createSidebarPageAiRuntime(context) {
configScope: String(skill && skill.configScope || '').trim(),
skillKind: String(skill && skill.skillKind || '').trim(),
profileId: String(skill && skill.profileId || '').trim(),
toolNames: pageAiNormalizeArray(skill && skill.toolNames),
tools: pageAiNormalizeArray(skill && skill.tools),
toolCount: Number(skill && skill.toolCount || 0),
disabledToolCount: Number(skill && skill.disabledToolCount || 0),
status: String(skill && skill.status || '').trim(),
capabilityId: String(skill && skill.capabilityId || '').trim(),
capabilityKind: String(skill && skill.capabilityKind || '').trim(),
uiKind: String(skill && skill.uiKind || '').trim(),
requiresContextRefs: pageAiNormalizeArray(skill && skill.requiresContextRefs),
readOnly: Boolean(skill && (skill.readOnly || skill.readonly || skill.configurable === false)),
category: String(category && category.name || '').trim()
category: String(skill && skill.category || category && category.name || '').trim(),
categoryTitle: String(skill && skill.categoryTitle || category && category.title || category && category.name || '').trim()
};
})
};
@@ -831,6 +927,16 @@ export function createSidebarPageAiRuntime(context) {
configScope: String(skill && skill.configScope || '').trim(),
skillKind: String(skill && skill.skillKind || '').trim(),
profileId: String(skill && skill.profileId || '').trim(),
toolNames: pageAiNormalizeArray(skill && skill.toolNames),
tools: pageAiNormalizeArray(skill && skill.tools),
toolCount: Number(skill && skill.toolCount || 0),
disabledToolCount: Number(skill && skill.disabledToolCount || 0),
status: String(skill && skill.status || '').trim(),
capabilityId: String(skill && skill.capabilityId || '').trim(),
capabilityKind: String(skill && skill.capabilityKind || '').trim(),
uiKind: String(skill && skill.uiKind || '').trim(),
requiresContextRefs: pageAiNormalizeArray(skill && skill.requiresContextRefs),
categoryTitle: String(skill && skill.categoryTitle || '').trim(),
readOnly: Boolean(skill && (skill.readOnly || skill.readonly || skill.configurable === false))
};
})
@@ -859,6 +965,16 @@ export function createSidebarPageAiRuntime(context) {
configScope: skill.configScope || '',
skillKind: skill.skillKind || '',
profileId: skill.profileId || '',
toolNames: skill.toolNames || [],
tools: skill.tools || [],
toolCount: Number(skill.toolCount || 0),
disabledToolCount: Number(skill.disabledToolCount || 0),
status: skill.status || '',
capabilityId: skill.capabilityId || '',
capabilityKind: skill.capabilityKind || '',
uiKind: skill.uiKind || '',
requiresContextRefs: skill.requiresContextRefs || [],
categoryTitle: skill.categoryTitle || category.title || category.name || '',
readOnly: Boolean(skill.readOnly || skill.readonly || skill.configurable === false)
});
});
@@ -1310,18 +1426,21 @@ export function createSidebarPageAiRuntime(context) {
function pageAiLoadSkillCatalog(runtime, profile) {
var params = new URLSearchParams();
params.set('runtime', runtime);
var endpoint = '/api/hermes/client/skills';
if (runtime === 'mnote') {
params.set('agentId', pageUiState.pageAiAgentId || 'reasonix');
endpoint = '/api/hermes/client/capabilities';
params.set('agentId', 'reasonix');
if (profile) params.set('profile', profile);
} else if (runtime === 'reasonix') {
params.set('runtime', 'reasonix');
} else if (runtime === 'hermes' && profile) {
params.set('profileId', profile);
}
return fetch('/api/hermes/client/skills?' + params.toString(), {
return fetch(endpoint + '?' + params.toString(), {
headers: { 'accept': 'application/json' }
}).then(function(response) {
return response.json().catch(function(){ return null; }).then(function(payload) {
if (!response.ok) throw new Error(pageAiErrorMessage(payload, 'skills_failed_' + response.status));
if (!response.ok) throw new Error(pageAiErrorMessage(payload, 'capabilities_failed_' + response.status));
return pageAiNormalizeSkills(payload);
});
});
@@ -1478,21 +1597,30 @@ export function createSidebarPageAiRuntime(context) {
}
if (skillGroup === 'mnote') {
try {
var mnoteResponse = await fetch('/api/hermes/client/skills/toggle', {
var mnoteResponse = await fetch('/api/hermes/client/capabilities/toggle', {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
skillKind: 'mnote_builtin',
name: name,
runtime: 'mnote',
profile: skillProfile || pageAiCurrentProfile(),
id: name,
enabled: Boolean(enabled)
})
});
var mnotePayload = await mnoteResponse.json().catch(function(){ return null; });
if (!mnoteResponse.ok) throw new Error(pageAiErrorMessage(mnotePayload, 'mnote_skill_toggle_failed_' + mnoteResponse.status));
if (!mnoteResponse.ok) throw new Error(pageAiErrorMessage(mnotePayload, 'mnote_capability_toggle_failed_' + mnoteResponse.status));
pageAiSetSkillPreference(skillGroup, name, Boolean(enabled), skillProfile);
pageAiNormalizeArray(pageUiState.pageAiSkillCatalogs && pageUiState.pageAiSkillCatalogs.mnote && pageUiState.pageAiSkillCatalogs.mnote.categories).forEach(function(category) {
pageAiNormalizeArray(category.skills).forEach(function(skill) {
if (skill.id === name || skill.name === name) skill.enabled = Boolean(enabled);
if (skill.id === name || skill.name === name) {
skill.enabled = Boolean(enabled);
skill.status = enabled ? 'available' : 'disabled';
pageAiNormalizeArray(skill.tools).forEach(function(tool) {
tool.enabled = Boolean(enabled);
tool.status = enabled ? 'available' : 'disabled';
});
skill.disabledToolCount = enabled ? 0 : Number(skill.toolCount || pageAiNormalizeArray(skill.tools).length || 0);
}
});
});
document.documentElement.setAttribute('data-mnote-page-ai-skill-toggled', skillGroup + ':' + name);
@@ -1612,8 +1740,6 @@ export function createSidebarPageAiRuntime(context) {
pageAiLoadBackendSessions()
]).then(function() {
renderPageAiControls();
}).catch(function() {}).then(function() {
return pageAiEnsureHermesSession();
}).then(function() {
return pageAiRestoreHermesSession();
}).then(function() {
@@ -2119,6 +2245,14 @@ export function createSidebarPageAiRuntime(context) {
function handlePageAiClick(event, helpers) {
var closestAction = helpers && helpers.closestAction;
if (typeof closestAction !== 'function') return false;
var pageAiCitationLink = closestAction(event.target, 'a[data-page-ai-citation-link="true"]');
if (pageAiCitationLink && !(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)) {
var href = pageAiCitationLink.getAttribute('href') || '';
if (pageAiOpenCitationUrl(href)) {
event.preventDefault();
return true;
}
}
var pageAiClose = closestAction(event.target, '[data-page-ai-action="close"]');
if (pageAiClose) {
event.preventDefault();
@@ -60,9 +60,9 @@ export function createSidebarPageAiSessionRuntime(context) {
acpRuntime: pageUiState.pageAiAcpRuntime || 'reasonix',
createdAt: now,
updatedAt: now,
source: 'local',
source: 'draft',
usage: null,
status: 'idle',
status: 'draft',
messages: []
};
}
@@ -117,6 +117,10 @@ export function createSidebarPageAiSessionRuntime(context) {
if (title.length > 28) title = title.slice(0, 28) + '…';
var persistence = String(row.persistence || payload.persistence || '').trim();
var sessionStorage = String(row.sessionStorage || row.session_storage || payload.sessionStorage || '').trim();
var status = String(row.status || (row.runtime && row.runtime.status) || '').trim();
var hasConversationSignal = String(payload.message || payload.input || row.snippet || '').trim()
|| pageAiNormalizeArray(row.messages).length > 0;
if (status === 'session.created' && !hasConversationSignal) return null;
var agentId = pageAiNormalizeAgentId(row.agentId || row.agent_id || payload.agentId || payload.agent_id);
var profileId = String(row.profileId || row.profile_id || payload.profileId || payload.profile_id || '').trim();
var profile = String(row.profile || payload.profile || pageAiRunProfile()).trim() || 'default';
@@ -143,7 +147,7 @@ export function createSidebarPageAiSessionRuntime(context) {
shareId: String(row.shareId || row.share_id || payload.shareId || '').trim(),
acpSessionId: String(row.acpSessionId || row.acp_session_id || payload.acpSessionId || payload.acp_session_id || '').trim(),
runId: String(row.runId || row.run_id || '').trim(),
status: String(row.status || (row.runtime && row.runtime.status) || '').trim(),
status: status,
usage: row.usage && typeof row.usage === 'object' ? row.usage : null,
preview: String(payload.message || row.snippet || '').trim(),
messages: []
@@ -164,11 +168,24 @@ export function createSidebarPageAiSessionRuntime(context) {
return pageAiNormalizeSessions(Object.keys(byId).map(function(id) { return byId[id]; }));
}
function pageAiDedupeSessions(sessions) {
var byId = {};
var ordered = [];
pageAiNormalizeSessions(sessions).forEach(function(session) {
var id = String(session && session.id || '').trim();
if (!id || byId[id]) return;
byId[id] = true;
ordered.push(session);
});
return ordered;
}
function pageAiSessionStorageLabel(session) {
var storage = String(session && (session.sessionStorage || session.session_storage) || '').trim();
var persistence = String(session && session.persistence || '').trim();
if (storage === 'local_shared') return '共享会话';
if (storage === 'local_private') return '本地私有';
if (storage === 'sqlite_control_plane' || persistence === 'sqlite_acp_runtime_store') return '账号会话';
if (storage === 'cloud' || persistence === 'convex_acp_runtime_store') return '云端会话';
if (persistence === 'local_ai_session_jsonl') return '本地私有';
return String(session && session.source || '').trim() === 'acp' ? '云端会话' : '本地私有';
@@ -179,30 +196,11 @@ export function createSidebarPageAiSessionRuntime(context) {
try {
var raw = win.localStorage.getItem(pageAiStorageKey());
var parsed = raw ? JSON.parse(raw) : null;
var activeId = String(parsed && parsed.activeSessionId || '').trim();
var activeProfile = String(parsed && parsed.activeProfileName || '').trim();
var activeAcpRuntime = String(parsed && parsed.activeAcpRuntime || '').trim();
var sessions = pageAiNormalizeSessions(parsed && parsed.sessions);
var storageVersion = Number(parsed && parsed.version || 0);
if (storageVersion >= sessionStorageVersion && activeAcpRuntime) pageUiState.pageAiAcpRuntime = activeAcpRuntime;
if (activeProfile) pageAiSetActiveProfile(activeProfile);
if (sessions.length) {
pageUiState.pageAiSessions = sessions;
var activeSession = sessions.find(function(session) { return session.id === activeId; }) || sessions[0];
pageUiState.pageAiActiveSessionId = activeSession.id;
if (activeSession.profile) pageAiSetActiveProfile(activeSession.profile);
if (activeSession.agentId) pageUiState.pageAiAgentId = pageAiNormalizeAgentId(activeSession.agentId);
if (!pageUiState.pageAiAcpRuntime && activeSession.acpRuntime) pageUiState.pageAiAcpRuntime = activeSession.acpRuntime;
pageUiState.pageAiMessages = Array.isArray(activeSession.messages) ? activeSession.messages.slice() : [];
return;
}
if (activeId) {
pageUiState.pageAiSessions = [pageAiNewSession('当前页问答')];
pageUiState.pageAiSessions[0].id = activeId;
pageUiState.pageAiActiveSessionId = activeId;
pageUiState.pageAiMessages = [];
return;
}
} catch (_) {}
var fresh = pageAiNewSession();
pageUiState.pageAiSessions = [fresh];
@@ -219,8 +217,24 @@ export function createSidebarPageAiSessionRuntime(context) {
throw new Error(pageAiErrorMessage(payload, 'session_list_failed_' + response.status));
}
var backendSessions = pageAiNormalizeArray(payload.sessions).map(pageAiNormalizeBackendSessionRow).filter(Boolean);
if (!backendSessions.length) return [];
pageUiState.pageAiSessions = pageAiMergeSessions(pageUiState.pageAiSessions, backendSessions);
var draftSessions = pageAiNormalizeArray(pageUiState.pageAiSessions).filter(function(session) {
var id = String(session && session.id || '').trim();
return id && !id.startsWith('mnote_')
&& (id === pageUiState.pageAiActiveSessionId || (Array.isArray(session.messages) && session.messages.length > 0));
});
if (!backendSessions.length) {
if (!draftSessions.length && !pageUiState.pageAiActiveSessionId) {
var fresh = pageAiNewSession();
pageUiState.pageAiSessions = [fresh];
pageUiState.pageAiActiveSessionId = fresh.id;
pageUiState.pageAiMessages = [];
}
pageUiState.pageAiSessionError = '';
renderPageAiConversation();
renderPageAiControls();
return [];
}
pageUiState.pageAiSessions = pageAiDedupeSessions(backendSessions.concat(draftSessions));
if (!pageUiState.pageAiActiveSessionId || !pageUiState.pageAiSessions.find(function(session) { return session.id === pageUiState.pageAiActiveSessionId; })) {
pageUiState.pageAiActiveSessionId = pageUiState.pageAiSessions[0].id;
}
@@ -242,7 +256,7 @@ export function createSidebarPageAiSessionRuntime(context) {
var eventType = String(event.eventType || event.event_type || event.event || '').trim();
var payload = event.payload && typeof event.payload === 'object' ? event.payload : event;
if (eventType === 'message.delta') {
var delta = String(payload.delta || payload.text || payload.output_text || '').trim();
var delta = String(payload.delta || payload.text || payload.output_text || '');
return delta ? { role: 'assistant', content: delta } : null;
}
if (eventType === 'thought.delta') {
@@ -301,10 +315,34 @@ export function createSidebarPageAiSessionRuntime(context) {
var userMessage = String(runPayload.message || runPayload.input || '').trim();
if (userMessage) messages.push({ role: 'user', content: userMessage });
var runId = String(run && (run.runId || run.run_id) || '').trim();
var assistantDelta = '';
var completedOutput = '';
function flushAssistantDelta() {
var content = assistantDelta.trim();
if (content) messages.push({ role: 'assistant', content: content });
assistantDelta = '';
}
pageAiNormalizeArray(eventsByRunId[runId]).forEach(function(event) {
var message = pageAiMessageFromRuntimeEvent(event);
if (message) messages.push(message);
if (!message) return;
if (message.role === 'assistant' && !message.kind) {
var eventType = String(event && (event.eventType || event.event_type || event.event) || '').trim();
if (eventType === 'run.completed') {
completedOutput = String(message.content || '').trim();
return;
}
assistantDelta += String(message.content || '');
return;
}
flushAssistantDelta();
messages.push(message);
});
flushAssistantDelta();
if (completedOutput && !messages.some(function(message) {
return message.role === 'assistant' && String(message.content || '').trim() === completedOutput;
})) {
messages.push({ role: 'assistant', content: completedOutput });
}
});
}
if (!messages.length) messages = storedMessages;
@@ -381,8 +419,7 @@ export function createSidebarPageAiSessionRuntime(context) {
version: sessionStorageVersion,
activeSessionId: pageUiState.pageAiActiveSessionId,
activeProfileName: pageAiCurrentProfile(),
activeAcpRuntime: pageUiState.pageAiAcpRuntime || 'reasonix',
sessions: pageAiNormalizeSessions(pageUiState.pageAiSessions)
activeAcpRuntime: pageUiState.pageAiAcpRuntime || 'reasonix'
}));
} catch (_) {}
}
@@ -427,7 +464,12 @@ export function createSidebarPageAiSessionRuntime(context) {
updatedAt: Date.now(),
messages: pageUiState.pageAiMessages.slice()
};
pageUiState.pageAiSessions = pageAiNormalizeSessions([session]);
var previousSessionId = String(current && current.id || '').trim();
var retainedSessions = pageAiNormalizeArray(pageUiState.pageAiSessions).filter(function(item) {
var itemId = String(item && item.id || '').trim();
return itemId && itemId !== session.id && itemId !== previousSessionId;
});
pageUiState.pageAiSessions = pageAiNormalizeSessions([session].concat(retainedSessions));
pageUiState.pageAiActiveSessionId = session.id;
pageAiPersistSessions();
renderPageAiConversation();
@@ -13,30 +13,39 @@ export function createSidebarPageAiSkillRuntime(context) {
function pageAiSkillSourceOptions() {
var options = [
{ value: 'mnote', group: 'mnote', label: 'mnote', profile: '' },
{ value: 'reasonix', group: 'reasonix', label: 'reasonix', profile: '' }
{ value: 'mnote', group: 'mnote', label: 'MNote 公共能力', profile: '' },
{ value: 'reasonix', group: 'reasonix', label: 'Reasonix skill(查看)', profile: '', readonly: true }
];
pageAiNormalizeArray(pageUiState.pageAiProfiles).forEach(function(profile) {
var profileId = pageAiProfileValue(profile);
if (!profileId) return;
var label = profile.kind === 'shared'
? (profile.baseProfile === 'lite' || profileId === 'shared_lite' ? 'hermes_lite' : 'Hermes_shared')
: 'Hermes_user';
var alias = String(profile.alias || '').trim();
if (!profileId || pageAiProfileIsChatOnlySkillSource(profile)) return;
var label = profile.kind === 'shared' ? 'Hermes 共享 skill(查看)' : 'Hermes skill(查看)';
var alias = String(profile.alias || profile.displayName || '').trim();
options.push({
value: 'hermes:' + profileId,
group: 'hermes',
profile: profileId,
label: alias && alias !== label ? label + ' · ' + alias : label,
readonly: profile.readonly === true
readonly: true
});
});
return options;
}
function pageAiProfileIsChatOnlySkillSource(profile) {
var profileId = String(pageAiProfileValue(profile) || '').trim().toLowerCase();
var baseProfile = String(profile && profile.baseProfile || '').trim().toLowerCase();
var label = String(profile && (profile.displayName || profile.alias || profile.name) || '').trim().toLowerCase();
var providerKind = String(profile && profile.providerKind || '').trim().toLowerCase();
return profileId.indexOf('chat') >= 0
|| baseProfile.indexOf('chat') >= 0
|| label.indexOf('chat') >= 0
|| providerKind.indexOf('chat') >= 0
|| profileId === 'shared_lite'
|| baseProfile === 'lite';
}
function pageAiDefaultSkillSource() {
if (pageAiCurrentAgentId() === 'hermes') return 'hermes:' + pageAiCurrentProfile();
if (pageAiCurrentAgentId() === 'reasonix') return 'reasonix';
return 'mnote';
}
@@ -172,21 +181,29 @@ export function createSidebarPageAiSkillRuntime(context) {
group: group,
profile: profile || '',
category: category.name,
categoryTitle: skill.categoryTitle || category.title || category.name || '',
id: id,
name: skill.name || id,
title: skill.title || skill.name || id,
description: skill.description || '',
enabled: group === 'hermes' ? skill.enabled !== false : (skill.enabled !== false && overrides[id] !== false),
toggleable: skill.toggleable !== false,
enabled: group === 'mnote' ? (skill.enabled !== false && overrides[id] !== false) : skill.enabled !== false,
toggleable: group === 'mnote' && skill.toggleable !== false,
source: skill.source || group,
origin: skill.origin || '',
readOnly: skill.readOnly === true || skill.readonly === true || skill.configurable === false,
readOnly: group !== 'mnote' || skill.readOnly === true || skill.readonly === true || skill.configurable === false,
builtin: pageAiSkillIsBuiltin(skill),
configurable: skill.configurable !== false,
configScope: skill.configScope || '',
skillKind: skill.skillKind || '',
profileId: skill.profileId || '',
toolNames: skill.toolNames || [],
tools: skill.tools || [],
toolCount: Number(skill.toolCount || 0),
disabledToolCount: Number(skill.disabledToolCount || 0),
status: skill.status || '',
capabilityId: skill.capabilityId || '',
capabilityKind: skill.capabilityKind || '',
uiKind: skill.uiKind || '',
requiresContextRefs: skill.requiresContextRefs || []
});
});
@@ -198,21 +215,29 @@ export function createSidebarPageAiSkillRuntime(context) {
group: group,
profile: profile || '',
category: 'archived',
categoryTitle: skill.categoryTitle || 'archived',
id: id,
name: skill.name || id,
title: skill.title || skill.name || id,
description: skill.description || '',
enabled: group === 'hermes' ? skill.enabled !== false : (skill.enabled !== false && overrides[id] !== false),
toggleable: skill.toggleable !== false,
enabled: group === 'mnote' ? (skill.enabled !== false && overrides[id] !== false) : skill.enabled !== false,
toggleable: group === 'mnote' && skill.toggleable !== false,
source: skill.source || group,
origin: skill.origin || '',
readOnly: skill.readOnly === true || skill.readonly === true || skill.configurable === false,
readOnly: group !== 'mnote' || skill.readOnly === true || skill.readonly === true || skill.configurable === false,
builtin: pageAiSkillIsBuiltin(skill),
configurable: skill.configurable !== false,
configScope: skill.configScope || '',
skillKind: skill.skillKind || '',
profileId: skill.profileId || '',
toolNames: skill.toolNames || [],
tools: skill.tools || [],
toolCount: Number(skill.toolCount || 0),
disabledToolCount: Number(skill.disabledToolCount || 0),
status: skill.status || '',
capabilityId: skill.capabilityId || '',
capabilityKind: skill.capabilityKind || '',
uiKind: skill.uiKind || '',
requiresContextRefs: skill.requiresContextRefs || []
});
});
@@ -59,13 +59,26 @@ export function createSidebarPageAiTargetRuntime(context) {
var kind = String(entry && (entry.editorKind || entry.kind) || '').trim().toLowerCase();
var assetId = String(entry && entry.assetId || '').trim();
var path = String(entry && entry.path || '').trim().toLowerCase();
var workspacePath = entry && entry.workspacePath && typeof entry.workspacePath === 'object' ? entry.workspacePath : {};
var workspaceResourceKind = String(workspacePath.resourceKind || '').trim().toLowerCase();
var officeOpenMode = String(entry && entry.officeOpenMode || '').trim().toLowerCase();
var onlyofficeSessionId = String(entry && (entry.onlyofficeSessionId || entry.bridgeSessionId) || '').trim();
if (kind === 'page' || kind === 'markdown_page') return 'markdown_page';
if (kind === 'mindmap' || path.endsWith('.mindmap.json')) return 'mindmap';
if (kind === 'office' || kind === 'onlyoffice' || kind === 'only_office' || /\.(doc|docx|ppt|pptx|xls|xlsx)$/.test(path)) return 'only_office';
if (kind === 'office' || kind === 'onlyoffice' || kind === 'only_office' || workspaceResourceKind === 'only_office' || /\.(doc|docx|ppt|pptx|xls|xlsx)$/.test(path)) {
return officeOpenMode === 'onlyoffice_live' || onlyofficeSessionId ? 'only_office' : 'attachment';
}
if (kind === 'resource' && assetId) return 'resource';
return kind || 'markdown_page';
}
function pageAiIsOnlyOfficeLiveTarget(editorTarget) {
var workspacePath = editorTarget && editorTarget.workspacePath && typeof editorTarget.workspacePath === 'object' ? editorTarget.workspacePath : {};
var resourceKind = String(editorTarget && (editorTarget.resourceKind || editorTarget.editorKind) || workspacePath.resourceKind || '').trim().toLowerCase();
var officeOpenMode = String(editorTarget && editorTarget.officeOpenMode || '').trim().toLowerCase();
return resourceKind === 'only_office' || resourceKind === 'onlyoffice' || officeOpenMode === 'onlyoffice_live';
}
function pageAiTargetId(entry) {
if (!entry || typeof entry !== 'object') return '';
var workspacePath = entry.workspacePath && typeof entry.workspacePath === 'object' ? entry.workspacePath : {};
@@ -113,6 +126,7 @@ export function createSidebarPageAiTargetRuntime(context) {
lastActiveAt: entry.lastActiveAt || 0,
assetId: entry.assetId || workspacePath.assetId || '',
path: entry.path || workspacePath.relativePath || '',
officeOpenMode: entry.officeOpenMode || '',
onlyofficeSessionId: entry.onlyofficeSessionId || entry.bridgeSessionId || '',
bridgeSessionId: entry.bridgeSessionId || entry.onlyofficeSessionId || '',
bridgeSessionReady: entry.bridgeSessionReady === true
@@ -137,6 +151,7 @@ export function createSidebarPageAiTargetRuntime(context) {
lastActiveAt: Number(entry.lastActiveAt || 0) || 0,
assetId: String(entry.assetId || '').trim(),
path: String(entry.path || '').trim(),
officeOpenMode: String(entry.officeOpenMode || '').trim(),
onlyofficeSessionId: String(entry.onlyofficeSessionId || entry.bridgeSessionId || '').trim(),
bridgeSessionId: String(entry.bridgeSessionId || entry.onlyofficeSessionId || '').trim(),
bridgeSessionReady: entry.bridgeSessionReady === true
@@ -661,7 +676,7 @@ export function createSidebarPageAiTargetRuntime(context) {
var workspacePath = editorTarget && editorTarget.workspacePath && typeof editorTarget.workspacePath === 'object' ? editorTarget.workspacePath : {};
var resourceKind = String(editorTarget && (editorTarget.resourceKind || editorTarget.editorKind) || workspacePath.resourceKind || '').trim();
var onlyofficeSessionId = String(editorTarget && (editorTarget.onlyofficeSessionId || editorTarget.bridgeSessionId) || '').trim();
if ((resourceKind === 'office' || resourceKind === 'only_office' || resourceKind === 'onlyoffice') && !onlyofficeSessionId) {
if (pageAiIsOnlyOfficeLiveTarget(editorTarget) && !onlyofficeSessionId) {
var sessionError = new Error('ONLYOFFICE 资源仍在连接 MNote bridge,请等待 Office 页面加载完成后再让 AI 操作。');
sessionError.code = 'page_ai_onlyoffice_bridge_not_ready';
throw sessionError;
@@ -740,8 +740,15 @@ export function createSidebarPageSettingsRuntime(context) {
var status = summary.status || {};
var settings = status.settings && typeof status.settings === 'object' ? status.settings : {};
var includePaths = Array.isArray(settings.includePaths) ? settings.includePaths : ['.'];
statusNode.textContent = '索引 ' + Number(status.documentCount || 0) + ' 个页面 / ' + Number(status.resourceCount || 0) + ' 个资源 / ' + Number(status.evidenceBlockCount || 0) + ' 个证据块' + (status.scheduledDue ? ',已到计划时间' : '');
var savedIncludePaths = Array.isArray(settings.includePaths) ? settings.includePaths : [];
var indexedPaths = Array.isArray(status.indexedPaths) ? status.indexedPaths : [];
var includePaths = savedIncludePaths.length ? savedIncludePaths : indexedPaths;
var hasIndexCache = status.indexExists === true || status.evidenceIndexExists === true;
if (!savedIncludePaths.length && !hasIndexCache) {
statusNode.textContent = '未设置索引范围';
} else {
statusNode.textContent = '索引 ' + Number(status.documentCount || 0) + ' 个页面 / ' + Number(status.resourceCount || 0) + ' 个资源 / ' + Number(status.evidenceBlockCount || 0) + ' 个证据块' + (status.scheduledDue ? ',已到计划时间' : '');
}
if (!(rangesNode instanceof HTMLElement) || !rangesNode.contains(document.activeElement)) {
renderLocalIndexRangeRows(popover, includePaths, localIndexStatusKind(status), false, status);
}
@@ -762,6 +769,9 @@ export function createSidebarPageSettingsRuntime(context) {
function localIndexStatusKind(status) {
if (!status || typeof status !== 'object') return 'fault';
var settings = status.settings && typeof status.settings === 'object' ? status.settings : {};
var includePaths = Array.isArray(settings.includePaths) ? settings.includePaths : [];
if (!includePaths.length && status.indexExists !== true && status.evidenceIndexExists !== true) return 'indexed';
if (status.indexExists !== true) return 'fault';
if (status.cacheMatchesSettings === true && status.scheduledDue !== true) return 'indexed';
return 'indexing';
@@ -774,10 +784,10 @@ export function createSidebarPageSettingsRuntime(context) {
}
function localIndexPathStatusKind(path, status, fallbackKind) {
if (fallbackKind === 'fault' || fallbackKind === 'indexing') return fallbackKind;
var indexedPaths = Array.isArray(status && status.indexedPaths) ? status.indexedPaths : [];
var normalizedPath = String(path || '').trim() || '.';
if (indexedPaths.indexOf(normalizedPath) >= 0 && status.cacheMatchesSettings === true) return 'indexed';
if (indexedPaths.indexOf(normalizedPath) >= 0 && status.indexExists === true) return 'indexed';
if (fallbackKind === 'fault' || fallbackKind === 'indexing') return fallbackKind;
if (status.indexExists === true) return 'indexing';
return 'fault';
}
@@ -789,13 +799,26 @@ export function createSidebarPageSettingsRuntime(context) {
return String(value || '').trim();
}) : [];
var paths = disabled ? rawPaths.filter(Boolean) : rawPaths;
if (!paths.length && !disabled) paths = ['.'];
var savedPaths = Array.isArray(status && status.settings && status.settings.includePaths)
? status.settings.includePaths.map(function(value) { return String(value || '').trim(); }).filter(Boolean)
: [];
var indexedPaths = Array.isArray(status && status.indexedPaths)
? status.indexedPaths.map(function(value) { return String(value || '').trim(); }).filter(Boolean)
: [];
rangesNode.innerHTML = paths.map(function(path, index) {
var isPersisted = savedPaths.indexOf(path) >= 0 || indexedPaths.indexOf(path) >= 0;
var inputDisabled = disabled || isPersisted;
var kind = localIndexPathStatusKind(path, status || {}, fallbackKind || 'fault');
var normalizedPath = String(path || '').trim() || '.';
var displayPath = inputDisabled && normalizedPath === '.' ? '工作区根目录(全部)' : path;
var rootScopeHint = normalizedPath === '.'
? '<span class="wolai-page-settings-index-root-hint">当前工作区全部</span>'
: '';
return '' +
'<div class="wolai-page-settings-index-range-row" data-local-index-range-row="true">' +
'<span class="wolai-page-settings-index-status-dot" data-index-status="' + kind + '" title="' + escapeHtml(localIndexStatusLabel(kind)) + '"></span>' +
'<input type="text" class="wolai-page-settings-index-path" data-local-index-range-input="true" value="' + escapeHtml(path) + '" spellcheck="false"' + (disabled ? ' disabled' : '') + ' />' +
'<input type="text" class="wolai-page-settings-index-path" data-local-index-range-input="true" data-local-index-value="' + escapeHtml(normalizedPath) + '" value="' + escapeHtml(displayPath) + '" spellcheck="false"' + (inputDisabled ? ' disabled' : '') + (isPersisted ? ' data-local-index-persisted="true" title="已保存的索引目录不能直接修改;删除后重新新增范围"' : '') + ' />' +
rootScopeHint +
'<button type="button" class="wolai-page-settings-index-remove" data-local-index-action="remove-path" data-local-index-path-index="' + String(index) + '"' + (disabled ? ' disabled' : '') + ' aria-label="删除索引范围">×</button>' +
'</div>';
}).join('');
@@ -860,16 +883,17 @@ export function createSidebarPageSettingsRuntime(context) {
function localIndexIncludePathsFromForm() {
var popover = ensureLocalIndexSettingsPopover();
var values = currentLocalIndexRangeValues(popover).map(function(value) {
return currentLocalIndexRangeValues(popover).map(function(value) {
return value.trim();
}).filter(Boolean);
return values.length ? values : ['.'];
}
function currentLocalIndexRangeValues(popover) {
var root = popover || ensureLocalIndexSettingsPopover();
return Array.from(root.querySelectorAll('[data-local-index-range-input]')).map(function(input) {
return input instanceof HTMLInputElement ? input.value : '';
if (!(input instanceof HTMLInputElement)) return '';
if (input.disabled && input.dataset.localIndexValue) return input.dataset.localIndexValue;
return input.value;
});
}
@@ -901,7 +925,6 @@ export function createSidebarPageSettingsRuntime(context) {
var summary = pageUiState.localIndexSummary || {};
var values = currentLocalIndexRangeValues(popover);
values.splice(Number(index || 0), 1);
if (!values.length) values = [''];
renderLocalIndexRangeRows(popover, values, localIndexStatusKind(summary.status || {}), false, summary.status || {});
}
@@ -1162,6 +1162,8 @@ export const createSidebarTreeLiveApplyRuntime = (dependencies = {}) => {
var objectIdentity = fileObjectIdentity(item);
var ownerDocumentId = fileOwnerDocumentId(item, documentId, objectIdentity);
var iconKind = iconKindOf(item);
var indexStatus = String((item && item.indexStatus) || (item && item.resourceMeta && item.resourceMeta.indexStatus) || '').trim();
if (indexStatus !== 'indexed' && indexStatus !== 'failed') indexStatus = '';
var cachedChildren = relativePath ? cachedFileTreeRows(relativePath) : [];
var title = isFileTreeProjectionPageRow(rowKind, assetId)
? fileTreePageTitle(rawTitle)
@@ -1185,7 +1187,7 @@ export const createSidebarTreeLiveApplyRuntime = (dependencies = {}) => {
var childHtml = expandable && expanded && childRowsHtml
? '<ul class="tree-children">' + childRowsHtml + '</ul>'
: '';
return '<li class="tree-node" data-node-id="' + escapeHtml(nodeId) + '"><div class="tree-row" role="treeitem" aria-level="' + (depth + 1) + '" aria-expanded="' + String(expandable && expanded) + '" data-rust-rendered-row="filetree" data-testid="' + testId + '" data-row-id="' + escapeHtml(rowId) + '" data-row-kind="' + escapeHtml(rowKind) + '" data-node-id="' + escapeHtml(nodeId) + '"' + (parent ? ' data-parent-id="' + escapeHtml(parent) + '"' : '') + ' data-document-id="' + escapeHtml(documentId) + '" data-doc-id="' + escapeHtml(documentId) + '" data-owner-document-id="' + escapeHtml(ownerDocumentId) + '" data-asset-id="' + escapeHtml(assetId) + '" data-local-relative-path="' + escapeHtml(relativePath) + '" data-object-identity="' + escapeHtml(objectIdentityAttr(objectIdentity)) + '" data-object-kind="' + escapeHtml(String(objectIdentity.objectKind || '')) + '" data-capabilities="' + escapeHtml(fileCapabilitiesAttr(item)) + '" data-shell-mode="filetree" data-selected="' + String(selected) + '" data-active="false" draggable="true">' + toggle + '<span class="tree-kind-badge" data-kind="' + escapeHtml(iconKind) + '" aria-hidden="true"></span><button type="button" class="tree-link" data-rust-action="open" data-row-id="' + escapeHtml(rowId) + '" data-document-id="' + escapeHtml(documentId) + '" data-owner-document-id="' + escapeHtml(ownerDocumentId) + '" data-asset-id="' + escapeHtml(assetId) + '" data-local-relative-path="' + escapeHtml(relativePath) + '" title="' + escapeHtml(title) + '"><span class="tree-link-title" title="' + escapeHtml(title) + '">' + escapeHtml(title) + '</span></button><div class="tree-actions">' + createAction + '<button type="button" class="tree-action" data-testid="filetree-action-menu" data-rust-action="menu" data-row-id="' + escapeHtml(rowId) + '" aria-label="更多操作">…</button></div></div>' + childHtml + '</li>';
return '<li class="tree-node" data-node-id="' + escapeHtml(nodeId) + '"><div class="tree-row" role="treeitem" aria-level="' + (depth + 1) + '" aria-expanded="' + String(expandable && expanded) + '" data-rust-rendered-row="filetree" data-testid="' + testId + '" data-row-id="' + escapeHtml(rowId) + '" data-row-kind="' + escapeHtml(rowKind) + '" data-node-id="' + escapeHtml(nodeId) + '"' + (parent ? ' data-parent-id="' + escapeHtml(parent) + '"' : '') + ' data-document-id="' + escapeHtml(documentId) + '" data-doc-id="' + escapeHtml(documentId) + '" data-owner-document-id="' + escapeHtml(ownerDocumentId) + '" data-asset-id="' + escapeHtml(assetId) + '" data-local-relative-path="' + escapeHtml(relativePath) + '" data-object-identity="' + escapeHtml(objectIdentityAttr(objectIdentity)) + '" data-object-kind="' + escapeHtml(String(objectIdentity.objectKind || '')) + '"' + (indexStatus ? ' data-index-status="' + escapeHtml(indexStatus) + '"' : '') + ' data-capabilities="' + escapeHtml(fileCapabilitiesAttr(item)) + '" data-shell-mode="filetree" data-selected="' + String(selected) + '" data-active="false" draggable="true">' + toggle + '<span class="tree-kind-badge" data-kind="' + escapeHtml(iconKind) + '" aria-hidden="true"></span><button type="button" class="tree-link" data-rust-action="open" data-row-id="' + escapeHtml(rowId) + '" data-document-id="' + escapeHtml(documentId) + '" data-owner-document-id="' + escapeHtml(ownerDocumentId) + '" data-asset-id="' + escapeHtml(assetId) + '" data-local-relative-path="' + escapeHtml(relativePath) + '" title="' + escapeHtml(title) + '"><span class="tree-link-title" title="' + escapeHtml(title) + '">' + escapeHtml(title) + '</span></button><div class="tree-actions">' + createAction + '<button type="button" class="tree-action" data-testid="filetree-action-menu" data-rust-action="menu" data-row-id="' + escapeHtml(rowId) + '" aria-label="更多操作">…</button></div></div>' + childHtml + '</li>';
}).join('');
}
@@ -874,6 +874,7 @@ import { createSidebarPageSettingsRuntime } from './sidebar-page-settings-runtim
const inferOnlyOfficeFileType = (...args) => sidebarFileTreeOpen.inferOnlyOfficeFileType(...args);
const buildOnlyOfficeOpenUrl = (...args) => sidebarFileTreeOpen.buildOnlyOfficeOpenUrl(...args);
const buildOnlyOfficeOpenPath = (...args) => sidebarFileTreeOpen.buildOnlyOfficeOpenPath(...args);
const buildOfficePreviewOpenUrl = (...args) => sidebarFileTreeOpen.buildOfficePreviewOpenUrl(...args);
const buildPdfPreviewOpenUrl = (...args) => sidebarFileTreeOpen.buildPdfPreviewOpenUrl(...args);
const buildLocalOnlyOfficeOpenUrl = (...args) => sidebarFileTreeOpen.buildLocalOnlyOfficeOpenUrl(...args);
const openLocalOfficeFileInActiveTab = (...args) => sidebarFileTreeOpen.openLocalOfficeFileInActiveTab(...args);
@@ -2198,26 +2199,57 @@ import { createSidebarPageSettingsRuntime } from './sidebar-page-settings-runtim
return searchText(shell && shell.getAttribute('data-document-id')) || searchText(bodyId);
}
function localResourceDocumentIdFromPath(path) {
var normalized = searchText(path).replace(/\\/g, '/');
return normalized ? 'local-resource:' + normalized.replace(/\//g, '~2F') : '';
}
function currentSearchDocumentId() {
var activePanel = document.querySelector('[data-mnote-resource-tab-panel][data-pane-role="primary"]:not([hidden])');
if (activePanel instanceof HTMLElement) {
var resourceKind = searchText(activePanel.getAttribute('data-resource-kind')).toLowerCase();
var resourcePath = searchText(activePanel.getAttribute('data-resource-path'));
if (resourceKind && resourceKind !== 'markdown' && resourcePath) return localResourceDocumentIdFromPath(resourcePath);
try {
var locator = JSON.parse(activePanel.getAttribute('data-mnote-evidence-locator') || 'null');
var locatorDoc = searchText(locator && (locator.ownerDocumentId || locator.owner_document_id));
if (locatorDoc) return locatorDoc;
} catch (_) {}
}
return currentDocumentId();
}
function searchSwitchValue(overlay, name) {
var button = overlay.querySelector('[data-search-switch="' + name + '"]');
return button instanceof HTMLElement && button.getAttribute('aria-checked') === 'true';
}
function highlightedHtml(value) {
return escapeHtml(value)
.replace(/&lt;mark&gt;/g, '<mark>')
.replace(/&lt;\/mark&gt;/g, '</mark>');
}
function highlightSearchTitle(title, query) {
var cleanTitle = searchText(title);
function highlightSearchText(value, query, exact) {
var text = searchText(value);
var cleanQuery = searchText(query);
if (!cleanQuery) return escapeHtml(cleanTitle);
var index = cleanTitle.toLowerCase().indexOf(cleanQuery.toLowerCase());
if (index < 0) return escapeHtml(cleanTitle);
return escapeHtml(cleanTitle.slice(0, index)) +
'<mark>' + escapeHtml(cleanTitle.slice(index, index + cleanQuery.length)) + '</mark>' +
escapeHtml(cleanTitle.slice(index + cleanQuery.length));
if (!text || !cleanQuery) return escapeHtml(text);
var lower = text.toLowerCase();
var lowerQuery = cleanQuery.toLowerCase();
var exactIndex = lower.indexOf(lowerQuery);
if (exact || exactIndex >= 0) {
if (exactIndex < 0) return escapeHtml(text);
return escapeHtml(text.slice(0, exactIndex)) +
'<mark>' + escapeHtml(text.slice(exactIndex, exactIndex + cleanQuery.length)) + '</mark>' +
escapeHtml(text.slice(exactIndex + cleanQuery.length));
}
var chars = Array.from(cleanQuery.replace(/\s+/g, '').toLowerCase());
if (!chars.length) return escapeHtml(text);
var next = 0;
var html = '';
Array.from(text).forEach(function(ch) {
if (next < chars.length && ch.toLowerCase() === chars[next]) {
html += '<mark>' + escapeHtml(ch) + '</mark>';
next += 1;
} else {
html += escapeHtml(ch);
}
});
return next >= chars.length ? html : escapeHtml(text);
}
function searchResultEvidenceLocator(item) {
@@ -2243,6 +2275,38 @@ import { createSidebarPageSettingsRuntime } from './sidebar-page-settings-runtim
return searchText(action && action.url);
}
function evidenceLocatorLineRange(locator) {
return locator && (locator.lineRange || locator.line_range) || null;
}
function evidenceLocatorCharRange(locator) {
return locator && (locator.charRange || locator.char_range) || null;
}
function evidenceLocatorBlockId(locator) {
return searchText(locator && (locator.blockId || locator.block_id));
}
function resourceHrefForEvidenceLocator(resourceKind, resourcePath, fileName, ownerDocumentId, locator) {
var localFileUrl = buildLocalFileOpenUrl(resourcePath, false);
if (!localFileUrl) return '';
if (resourceKind === 'pdf') return buildPdfPreviewOpenUrl(localFileUrl, fileName);
if (resourceKind === 'office') {
var fileType = inferOnlyOfficeFileType(fileName, '') || (fileName.indexOf('.') >= 0 ? fileName.split('.').pop() : 'docx');
return buildOfficePreviewOpenUrl({
fileUrl: localFileUrl,
fileName: fileName,
fileType: fileType,
assetId: 'local-file:' + resourcePath,
documentId: ownerDocumentId || currentDocumentId() || '',
workspaceId: resolveWorkspaceId(document.body) || '',
sourceKind: currentSourceKind() || 'local_folder',
rootUri: searchText(locator && (locator.rootUri || locator.root_uri) || currentRootUri())
});
}
return localFileUrl;
}
async function openEvidenceSearchResult(item, event) {
var locator = searchResultEvidenceLocator(item);
if (!locator) {
@@ -2254,18 +2318,20 @@ import { createSidebarPageSettingsRuntime } from './sidebar-page-settings-runtim
var ownerDocumentId = searchText(locator.ownerDocumentId || locator.owner_document_id || item.documentId || '');
var resourceKind = evidenceLocatorResourceKind(locator, item && item.resourceType);
var openTarget = event && event.altKey ? 'side' : 'active-tab';
if (resourcePath && resourceKind && resourceKind !== 'markdown') {
if (resourcePath && resourceKind) {
var fileName = resourcePath.split('/').filter(Boolean).pop() || resourcePath;
var localFileUrl = buildLocalFileOpenUrl(resourcePath, false);
var href = resourceKind === 'pdf' ? buildPdfPreviewOpenUrl(localFileUrl, fileName) : localFileUrl;
await openLocalResourceInActiveTab({
var normalizedKind = resourceKind === 'raw_file' || resourceKind === 'resource' ? fileTreeIconKindForFileName(fileName) || 'file' : resourceKind;
var hostDocumentId = currentDocumentId() || ownerDocumentId || '';
var href = resourceHrefForEvidenceLocator(normalizedKind, resourcePath, fileName, hostDocumentId, locator);
var openedInResourceTab = await openLocalResourceInActiveTab({
path: resourcePath,
title: fileName,
kind: resourceKind,
kind: normalizedKind,
href: href,
officeUrl: normalizedKind === 'office' ? href : '',
assetId: 'local-file:' + resourcePath,
documentId: ownerDocumentId || currentDocumentId() || '',
ownerDocumentId: ownerDocumentId || currentDocumentId() || '',
documentId: hostDocumentId,
ownerDocumentId: ownerDocumentId || hostDocumentId,
workspaceId: resolveWorkspaceId(document.body) || '',
sourceKind: currentSourceKind() || 'local_folder',
rootUri: searchText(locator.rootUri || locator.root_uri || currentRootUri()),
@@ -2274,10 +2340,11 @@ import { createSidebarPageSettingsRuntime } from './sidebar-page-settings-runtim
page: locator.page,
bbox: locator.bbox,
sourceMapPath: searchText(locator.sourceMapPath || locator.source_map_path),
blockId: searchText(locator.blockId || locator.block_id),
lineRange: locator.lineRange || locator.line_range || null,
charRange: locator.charRange || locator.char_range || null
blockId: evidenceLocatorBlockId(locator),
lineRange: evidenceLocatorLineRange(locator),
charRange: evidenceLocatorCharRange(locator)
});
if (!openedInResourceTab) console.warn('mnote evidence 搜索结果无法在当前页面资源标签打开', locator);
closeSearchModal();
return;
}
@@ -2339,7 +2406,7 @@ import { createSidebarPageSettingsRuntime } from './sidebar-page-settings-runtim
workspaceId: resolveWorkspaceId(document.body),
sourceKind: currentSourceKind() || null,
rootUri: currentRootUri() || null,
documentId: currentDocumentId() || null,
documentId: searchSwitchValue(overlay, 'page') ? (currentSearchDocumentId() || null) : (currentDocumentId() || null),
query: query,
limit: 30,
filters: {
@@ -2368,10 +2435,11 @@ import { createSidebarPageSettingsRuntime } from './sidebar-page-settings-runtim
var locator = searchResultEvidenceLocator(item);
var locatorAttr = locator ? escapeHtml(JSON.stringify(locator)) : '';
var index = items.indexOf(item);
var exact = searchSwitchValue(overlay, 'exact');
return '<button type="button" class="wolai-search-result-row" data-testid="wolai-search-result-row" data-search-result-owner="rust-kernel" data-search-result-index="' + String(index) + '" data-document-id="' + escapeHtml(item.documentId || item.nodeId || item.id || '') + '" data-resource-type="' + escapeHtml(resourceType) + '"' + (locatorAttr ? ' data-evidence-locator="' + locatorAttr + '"' : '') + '>' +
'<span class="material-symbols-outlined wolai-search-result-icon" data-icon="article" aria-hidden="true"></span>' +
'<span class="wolai-search-result-main"><span class="wolai-search-result-title">' + highlightSearchTitle(title, query) + '</span>' +
'<span class="wolai-search-result-snippet">' + (snippet ? highlightedHtml(snippet) : escapeHtml(path)) + '</span>' +
'<span class="wolai-search-result-main"><span class="wolai-search-result-title">' + highlightSearchText(title, query, exact) + '</span>' +
'<span class="wolai-search-result-snippet">' + (snippet ? highlightSearchText(snippet, query, exact) : escapeHtml(path)) + '</span>' +
'<span class="wolai-search-result-path"><span>' + escapeHtml(path) + '</span><span class="wolai-search-result-type">' + escapeHtml(resourceType) + '</span></span></span>' +
'</button>';
}).join('');
@@ -2583,7 +2651,16 @@ import { createSidebarPageSettingsRuntime } from './sidebar-page-settings-runtim
return;
}
var ocrSettingsTrigger = closestAction(e.target, '[data-mnote-action="open-ocr-settings"], [data-mnote-action="toggle-ocr-tasks"]');
var ocrTaskTrigger = closestAction(e.target, '[data-mnote-action="toggle-ocr-tasks"]');
if (ocrTaskTrigger) {
e.preventDefault();
window.dispatchEvent(new CustomEvent('mnote:local-ocr-settings-action', {
detail: { action: 'tasks' }
}));
return;
}
var ocrSettingsTrigger = closestAction(e.target, '[data-mnote-action="open-ocr-settings"]');
if (ocrSettingsTrigger) {
e.preventDefault();
openLocalOcrSettingsPopover();
@@ -0,0 +1,229 @@
use crate::app::AppState;
use crate::context::RequestContext;
use crate::error::WebError;
use crate::hermes_tools::{ensure_write_authorized, ToolCallInput};
use crate::routes;
use axum::http::StatusCode;
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct IndexSettingsArgs {
#[serde(default)]
include_paths: Vec<String>,
#[serde(default)]
schedule_mode: Option<String>,
#[serde(default)]
schedule_time: Option<String>,
#[serde(default)]
schedule_date: Option<String>,
#[serde(default)]
run_on_change: Option<bool>,
}
pub async fn index_status(
state: &AppState,
context: &RequestContext,
input: &ToolCallInput,
) -> Result<Value, WebError> {
let workspace_id = effective_workspace_id(context, input);
let root_uri = required_root_uri(
context,
input,
"mnote_index_root_required",
"本地索引状态缺少 rootUri",
)?;
let root_path =
routes::ensure_local_workspace_read_access_with_state(state, context, &root_uri)
.map_err(|error| error.with_context(context))?;
let user_settings = read_user_settings(state, context, &workspace_id, &root_path)?;
let effective_settings = routes::effective_local_index_settings_for_root(
state.control_plane(),
&workspace_id,
&root_path,
)?;
let status = routes::local_index_status_with_settings(
&root_path,
&root_uri,
&workspace_id,
&user_settings,
&effective_settings,
)?;
Ok(json!({
"ok": true,
"schema": "mnote.index.status_result.v1",
"result": status
}))
}
pub async fn index_refresh(
state: &AppState,
context: &RequestContext,
input: &ToolCallInput,
) -> Result<Value, WebError> {
let workspace_id = effective_workspace_id(context, input);
let root_uri = required_root_uri(
context,
input,
"mnote_index_root_required",
"本地索引刷新缺少 rootUri",
)?;
let root_path =
routes::ensure_local_workspace_read_access_with_state(state, context, &root_uri)
.map_err(|error| error.with_context(context))?;
let effective_settings = routes::effective_local_index_settings_for_root(
state.control_plane(),
&workspace_id,
&root_path,
)?;
let refreshed = routes::refresh_local_search_index_with_settings(
&root_path,
&root_uri,
&workspace_id,
&effective_settings,
)?;
Ok(json!({
"ok": true,
"schema": "mnote.index.refresh_result.v1",
"index": refreshed
}))
}
pub async fn index_update_settings(
state: &AppState,
context: &RequestContext,
input: &ToolCallInput,
) -> Result<Value, WebError> {
ensure_write_authorized(context, input)?;
let workspace_id = effective_workspace_id(context, input);
let root_uri = required_root_uri(
context,
input,
"mnote_index_root_required",
"本地索引设置缺少 rootUri",
)?;
let args = parse_settings_args(context, input)?;
let root_path =
routes::ensure_local_workspace_write_access_with_state(state, context, &root_uri)
.map_err(|error| error.with_context(context))?;
let actor_id = routes::current_actor_id(state, context).ok_or_else(|| {
WebError::new(
StatusCode::UNAUTHORIZED,
"local_index_settings_auth_required",
"本地索引设置需要登录用户",
)
.with_context(context)
})?;
if input.dry_run == Some(true) {
let planned_settings = routes::preview_user_local_index_settings(
state.control_plane(),
&actor_id,
&workspace_id,
&root_path,
&args.include_paths,
args.schedule_mode.as_deref(),
args.schedule_time.as_deref(),
args.schedule_date.as_deref(),
args.run_on_change,
)?;
let current_status = index_status(state, context, input).await?;
let would_clear_index_files = planned_settings.include_paths.is_empty();
return Ok(json!({
"ok": true,
"schema": "mnote.index.update_settings_plan.v1",
"dryRun": true,
"plannedSettings": planned_settings,
"currentStatus": current_status.get("result").cloned().unwrap_or(Value::Null),
"wouldRefresh": true,
"wouldClearIndexFiles": would_clear_index_files
}));
}
let settings = routes::write_user_local_index_settings(
state.control_plane(),
&actor_id,
&workspace_id,
&root_path,
&args.include_paths,
args.schedule_mode.as_deref(),
args.schedule_time.as_deref(),
args.schedule_date.as_deref(),
args.run_on_change,
)?;
let effective_settings = routes::effective_local_index_settings_for_root(
state.control_plane(),
&workspace_id,
&root_path,
)?;
let refreshed = routes::refresh_local_search_index_with_settings(
&root_path,
&root_uri,
&workspace_id,
&effective_settings,
)?;
let status = routes::local_index_status_with_settings(
&root_path,
&root_uri,
&workspace_id,
&settings,
&effective_settings,
)?;
Ok(json!({
"ok": true,
"schema": "mnote.index.update_settings_result.v1",
"settings": settings,
"index": refreshed,
"result": status
}))
}
fn parse_settings_args(
context: &RequestContext,
input: &ToolCallInput,
) -> Result<IndexSettingsArgs, WebError> {
let args = input.args.clone().unwrap_or_else(|| json!({}));
serde_json::from_value::<IndexSettingsArgs>(args).map_err(|error| {
WebError::bad_request_code(
"mnote_index_settings_payload_invalid",
format!("本地索引设置参数无效: {error}"),
)
.with_context(context)
})
}
fn read_user_settings(
state: &AppState,
context: &RequestContext,
workspace_id: &str,
root_path: &std::path::Path,
) -> Result<routes::LocalIndexSettings, WebError> {
if let Some(actor_id) = routes::current_actor_id(state, context) {
return routes::read_user_local_index_settings(
state.control_plane(),
&actor_id,
workspace_id,
root_path,
);
}
routes::read_local_index_settings_or_default(root_path)
}
fn effective_workspace_id(context: &RequestContext, input: &ToolCallInput) -> String {
input
.effective_workspace_id()
.or_else(|| context.workspace.workspace_id.clone())
.unwrap_or_else(|| "default".into())
}
fn required_root_uri(
context: &RequestContext,
input: &ToolCallInput,
code: &'static str,
message: &'static str,
) -> Result<String, WebError> {
input
.effective_root_uri()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
.ok_or_else(|| WebError::bad_request_code(code, message).with_context(context))
}
@@ -1,9 +1,94 @@
use super::skill;
use serde_json::{json, Value};
pub const MANIFEST_SCHEMA_VERSION: &str = "mnote.hermes_tool_manifest.v1";
pub const TOOL_SCHEMA_VERSION: &str = "mnote.hermes_tool.v1";
pub fn manifest() -> Value {
let tools = annotate_tools_with_capabilities(vec![
skill_read_tool(),
context_snapshot_tool(),
context_read_current_page_tool(),
context_resolve_target_tool(),
doc_fetch_tool(),
doc_find_tool(),
evidence_search_tool(),
evidence_read_tool(),
evidence_open_tool(),
index_status_tool(),
index_refresh_tool(),
index_update_settings_tool(),
block_fetch_tool(),
doc_plan_update_tool(),
block_replace_tool(),
block_insert_after_tool(),
block_delete_tool(),
block_move_after_tool(),
doc_apply_block_ops_tool(),
doc_markdown_edit_tool(),
page_get_tool(),
page_save_tool(),
available_tool(
"mnote.page.update_title",
"更新当前页面标题",
["page.write"],
),
available_tool(
"mnote.page.update_options",
"更新当前页面设置",
["page.write"],
),
mindmap_fetch_tool(),
mindmap_apply_ops_tool(),
mindmap_create_from_outline_tool(),
office_fetch_summary_tool(),
office_propose_changes_tool(),
onlyoffice_session_current_tool(),
onlyoffice_capabilities_tool(),
onlyoffice_selection_get_tool(),
onlyoffice_document_insert_text_tool(),
onlyoffice_document_replace_selection_tool(),
onlyoffice_document_insert_html_tool(),
onlyoffice_document_export_tool(),
onlyoffice_document_search_replace_tool(),
onlyoffice_document_insert_table_tool(),
onlyoffice_document_get_comments_tool(),
onlyoffice_document_add_comment_tool(),
onlyoffice_sheet_get_sheets_tool(),
onlyoffice_sheet_add_sheet_tool(),
onlyoffice_sheet_rename_sheet_tool(),
onlyoffice_sheet_get_range_tool(),
onlyoffice_sheet_get_range_values_tool(),
onlyoffice_sheet_get_values_tool(),
onlyoffice_sheet_set_value_tool(),
onlyoffice_sheet_set_formula_tool(),
onlyoffice_sheet_batch_set_values_tool(),
onlyoffice_sheet_set_range_values_tool(),
onlyoffice_sheet_format_range_tool(),
onlyoffice_sheet_set_dimensions_tool(),
onlyoffice_sheet_sort_range_tool(),
onlyoffice_sheet_add_chart_tool(),
onlyoffice_presentation_get_slides_tool(),
onlyoffice_presentation_get_slide_texts_tool(),
onlyoffice_presentation_get_shapes_tool(),
onlyoffice_presentation_add_text_slide_tool(),
onlyoffice_presentation_replace_text_tool(),
onlyoffice_presentation_set_shape_text_tool(),
onlyoffice_presentation_delete_slide_tool(),
onlyoffice_presentation_add_table_tool(),
onlyoffice_presentation_clear_slide_tool(),
onlyoffice_presentation_add_shape_tool(),
available_tool(
"mnote.artifact.create_summary",
"为当前页面创建或更新 AI Summary",
["artifact.write"],
),
available_tool(
"mnote.artifact.create_ai_note",
"基于当前页面创建新的 AI Note",
["artifact.write"],
),
]);
json!({
"schemaVersion": MANIFEST_SCHEMA_VERSION,
"plugin": {
@@ -12,74 +97,30 @@ pub fn manifest() -> Value {
"runtimeOwner": "mnote-web",
"writeOwner": "rust-runtime-kernel"
},
"tools": [
skill_read_tool(),
context_snapshot_tool(),
context_read_current_page_tool(),
context_resolve_target_tool(),
doc_fetch_tool(),
doc_find_tool(),
evidence_search_tool(),
evidence_read_tool(),
evidence_open_tool(),
block_fetch_tool(),
doc_plan_update_tool(),
block_replace_tool(),
block_insert_after_tool(),
block_delete_tool(),
block_move_after_tool(),
doc_apply_block_ops_tool(),
doc_markdown_edit_tool(),
page_get_tool(),
page_save_tool(),
available_tool("mnote.page.update_title", "更新当前页面标题", ["page.write"]),
available_tool("mnote.page.update_options", "更新当前页面设置", ["page.write"]),
mindmap_fetch_tool(),
mindmap_apply_ops_tool(),
mindmap_create_from_outline_tool(),
office_fetch_summary_tool(),
office_propose_changes_tool(),
onlyoffice_session_current_tool(),
onlyoffice_capabilities_tool(),
onlyoffice_selection_get_tool(),
onlyoffice_document_insert_text_tool(),
onlyoffice_document_replace_selection_tool(),
onlyoffice_document_insert_html_tool(),
onlyoffice_document_export_tool(),
onlyoffice_document_search_replace_tool(),
onlyoffice_document_insert_table_tool(),
onlyoffice_document_get_comments_tool(),
onlyoffice_document_add_comment_tool(),
onlyoffice_sheet_get_sheets_tool(),
onlyoffice_sheet_add_sheet_tool(),
onlyoffice_sheet_rename_sheet_tool(),
onlyoffice_sheet_get_range_tool(),
onlyoffice_sheet_get_range_values_tool(),
onlyoffice_sheet_get_values_tool(),
onlyoffice_sheet_set_value_tool(),
onlyoffice_sheet_set_formula_tool(),
onlyoffice_sheet_batch_set_values_tool(),
onlyoffice_sheet_set_range_values_tool(),
onlyoffice_sheet_format_range_tool(),
onlyoffice_sheet_set_dimensions_tool(),
onlyoffice_sheet_sort_range_tool(),
onlyoffice_sheet_add_chart_tool(),
onlyoffice_presentation_get_slides_tool(),
onlyoffice_presentation_get_slide_texts_tool(),
onlyoffice_presentation_get_shapes_tool(),
onlyoffice_presentation_add_text_slide_tool(),
onlyoffice_presentation_replace_text_tool(),
onlyoffice_presentation_set_shape_text_tool(),
onlyoffice_presentation_delete_slide_tool(),
onlyoffice_presentation_add_table_tool(),
onlyoffice_presentation_clear_slide_tool(),
onlyoffice_presentation_add_shape_tool(),
available_tool("mnote.artifact.create_summary", "为当前页面创建或更新 AI Summary", ["artifact.write"]),
available_tool("mnote.artifact.create_ai_note", "基于当前页面创建新的 AI Note", ["artifact.write"])
]
"capabilities": skill::manifest_capabilities(),
"tools": tools
})
}
fn annotate_tools_with_capabilities(tools: Vec<Value>) -> Vec<Value> {
tools
.into_iter()
.map(|mut tool| {
let name = tool.get("name").and_then(Value::as_str).unwrap_or_default();
let capability_ids = skill::capability_ids_for_tool(name);
if let Value::Object(map) = &mut tool {
if let Some(first) = capability_ids.first() {
map.insert("capabilityId".into(), json!(first));
}
if !capability_ids.is_empty() {
map.insert("capabilityIds".into(), json!(capability_ids));
}
}
tool
})
.collect()
}
fn skill_read_tool() -> Value {
let mut properties = base_identity_properties();
if let Value::Object(map) = &mut properties {
@@ -286,7 +327,7 @@ fn evidence_search_tool() -> Value {
}
json!({
"name": "mnote.evidence.search",
"description": "搜索可回跳原文的文档证据,返回 quote、EvidenceLocatoropenAction。",
"description": "搜索可回跳原文的文档证据,返回 quote、EvidenceLocatoropenAction 与可直接放进最终回答的 citationMarkdown 链接",
"schemaVersion": TOOL_SCHEMA_VERSION,
"capabilityScope": ["evidence.read", "page.read"],
"status": "available",
@@ -317,7 +358,7 @@ fn evidence_read_tool() -> Value {
}
json!({
"name": "mnote.evidence.read",
"description": "按 EvidenceLocator 读取原文证据及周边上下文,供回答引用。",
"description": "按 EvidenceLocator 读取原文证据及周边上下文,返回 quote/contextBlocks 与可点击引用链接供回答引用。",
"schemaVersion": TOOL_SCHEMA_VERSION,
"capabilityScope": ["evidence.read", "page.read"],
"status": "available",
@@ -337,7 +378,7 @@ fn evidence_open_tool() -> Value {
}
json!({
"name": "mnote.evidence.open",
"description": "把 EvidenceLocator 归一化为 MNote 可执行的打开/定位动作。",
"description": "把 EvidenceLocator 归一化为 MNote 可执行的打开/定位动作,并返回 citationUrl/citationMarkdown",
"schemaVersion": TOOL_SCHEMA_VERSION,
"capabilityScope": ["evidence.read", "page.read"],
"status": "available",
@@ -350,6 +391,79 @@ fn evidence_open_tool() -> Value {
})
}
fn index_status_tool() -> Value {
let mut properties = base_identity_properties();
if let Value::Object(map) = &mut properties {
map.insert("rootUri".into(), json!({ "type": "string" }));
}
json!({
"name": "mnote.index.status",
"description": "查看本地索引范围、缓存文件、构建时间、文档数和 evidence block 数。",
"schemaVersion": TOOL_SCHEMA_VERSION,
"capabilityScope": ["index.read", "evidence.read"],
"status": "available",
"annotations": tool_annotations(true, false, true, false),
"inputSchema": {
"type": "object",
"required": ["workspaceId", "rootUri"],
"properties": properties
}
})
}
fn index_refresh_tool() -> Value {
let mut properties = base_identity_properties();
if let Value::Object(map) = &mut properties {
map.insert("rootUri".into(), json!({ "type": "string" }));
}
json!({
"name": "mnote.index.refresh",
"description": "按当前有效索引范围重建本地搜索/evidence 缓存,不修改 Markdown 正文。",
"schemaVersion": TOOL_SCHEMA_VERSION,
"capabilityScope": ["index.read", "evidence.read"],
"status": "available",
"annotations": tool_annotations(true, false, false, false),
"inputSchema": {
"type": "object",
"required": ["workspaceId", "rootUri"],
"properties": properties
}
})
}
fn index_update_settings_tool() -> Value {
let mut properties = base_identity_properties();
if let Value::Object(map) = &mut properties {
map.insert("rootUri".into(), json!({ "type": "string" }));
map.insert(
"includePaths".into(),
json!({ "type": "array", "items": { "type": "string" } }),
);
map.insert(
"scheduleMode".into(),
json!({ "type": "string", "enum": ["manual", "daily", "weekly", "monthly"] }),
);
map.insert("scheduleTime".into(), json!({ "type": "string" }));
map.insert("scheduleDate".into(), json!({ "type": "string" }));
map.insert("runOnChange".into(), json!({ "type": "boolean" }));
map.insert("dryRun".into(), json!({ "type": "boolean" }));
map.insert("idempotencyKey".into(), json!({ "type": "string" }));
}
json!({
"name": "mnote.index.update_settings",
"description": "新增或删除本地索引范围;includePaths 为空表示删除当前用户索引范围并在无有效范围时清空索引文件。",
"schemaVersion": TOOL_SCHEMA_VERSION,
"capabilityScope": ["index.write", "evidence.read"],
"status": "available",
"annotations": tool_annotations(false, true, false, false),
"inputSchema": {
"type": "object",
"required": ["workspaceId", "rootUri", "includePaths", "dryRun", "idempotencyKey"],
"properties": properties
}
})
}
fn block_fetch_tool() -> Value {
let mut properties = base_identity_properties();
if let Value::Object(map) = &mut properties {
@@ -3,6 +3,7 @@ pub mod block;
pub mod context_tools;
pub mod doc;
pub mod evidence;
pub mod index;
pub mod manifest;
pub mod onlyoffice_live;
pub mod page;
+113 -30
View File
@@ -5,10 +5,11 @@ use axum::http::StatusCode;
use serde_json::{json, Value};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MnoteSkill {
pub struct MnoteCapabilityPack {
pub id: &'static str,
pub title: &'static str,
pub description: &'static str,
pub category: &'static str,
pub agent_ids: &'static [&'static str],
pub read_only: bool,
pub requires_context_refs: &'static [&'static str],
@@ -16,11 +17,14 @@ pub struct MnoteSkill {
pub content: &'static str,
}
const SKILLS: &[MnoteSkill] = &[
MnoteSkill {
pub type MnoteSkill = MnoteCapabilityPack;
const CAPABILITY_PACKS: &[MnoteCapabilityPack] = &[
MnoteCapabilityPack {
id: "mnote-current-page",
title: "MNote current page",
description: "Read the current MNote Markdown page only when the task needs page content.",
title: "当前页读取",
description: "仅在任务需要当前 MNote Markdown 页面内容时读取当前页。",
category: "mnote",
agent_ids: &["hermes", "reasonix"],
read_only: true,
requires_context_refs: &["current_page"],
@@ -31,12 +35,13 @@ const SKILLS: &[MnoteSkill] = &[
],
content: include_str!("../../../../../skills/mnote-current-page/SKILL.md"),
},
MnoteSkill {
id: "mnote-document-evidence",
title: "MNote document evidence",
description: "Search local documents and resources with clickable evidence locators.",
MnoteCapabilityPack {
id: "mnote-local-index",
title: "本地索引与证据检索",
description: "检索本地文档证据,并管理本地索引范围、刷新和删除。",
category: "knowledge",
agent_ids: &["hermes", "reasonix"],
read_only: true,
read_only: false,
requires_context_refs: &["folder"],
tool_names: &[
"mnote.context.snapshot",
@@ -44,23 +49,28 @@ const SKILLS: &[MnoteSkill] = &[
"mnote.evidence.search",
"mnote.evidence.read",
"mnote.evidence.open",
"mnote.index.status",
"mnote.index.refresh",
"mnote.index.update_settings",
],
content: include_str!("../../../../../skills/mnote-document-evidence/SKILL.md"),
content: include_str!("../../../../../skills/mnote-local-index/SKILL.md"),
},
MnoteSkill {
MnoteCapabilityPack {
id: "mnote-local-file",
title: "MNote local file editing",
description: "Read and patch local Markdown files inside MNote allowed roots.",
title: "本地文件编辑",
description: "在 MNote 授权目录内读取和修改本地 Markdown 文件。",
category: "file",
agent_ids: &["hermes", "reasonix"],
read_only: false,
requires_context_refs: &["current_page", "file", "folder"],
tool_names: &["mnote.context.snapshot", "mnote.context.resolve_target"],
content: include_str!("../../../../../skills/mnote-local-file/SKILL.md"),
},
MnoteSkill {
MnoteCapabilityPack {
id: "mnote-onlyoffice-live",
title: "MNote ONLYOFFICE live bridge",
description: "Operate the currently open ONLYOFFICE editor session for Word, Excel, and PPT.",
title: "ONLYOFFICE 实时编辑",
description: "操作当前已打开的 ONLYOFFICE WordExcel、PPT 编辑会话。",
category: "office",
agent_ids: &["hermes", "reasonix"],
read_only: false,
requires_context_refs: &["onlyoffice"],
@@ -103,10 +113,11 @@ const SKILLS: &[MnoteSkill] = &[
],
content: include_str!("../../../../../skills/mnote-onlyoffice-live/SKILL.md"),
},
MnoteSkill {
MnoteCapabilityPack {
id: "mnote-mindmap",
title: "MNote mindmap editing",
description: "Read, update, summarize, or create MNote mindmap resources, including generating a new mindmap from PDF or document outlines.",
title: "思维导图",
description: "读取、更新、总结或创建 MNote 思维导图资源。",
category: "resource",
agent_ids: &["hermes", "reasonix"],
read_only: false,
requires_context_refs: &["current_page", "file", "folder", "resource"],
@@ -119,10 +130,11 @@ const SKILLS: &[MnoteSkill] = &[
],
content: include_str!("../../../../../skills/mnote-mindmap/SKILL.md"),
},
MnoteSkill {
MnoteCapabilityPack {
id: "mnote-chat-only",
title: "MNote chat only",
description: "Reply conversationally without reading or writing MNote page/file context.",
title: "纯聊天",
description: "只进行对话回复,不读取或写入 MNote 页面、文件上下文。",
category: "chat",
agent_ids: &["chat_only", "hermes", "reasonix"],
read_only: true,
requires_context_refs: &[],
@@ -132,20 +144,75 @@ const SKILLS: &[MnoteSkill] = &[
];
pub fn skill_summaries_for_agent(agent_id: Option<&str>) -> Vec<Value> {
SKILLS
capability_summaries_for_agent(agent_id)
}
pub fn capability_summaries_for_agent(agent_id: Option<&str>) -> Vec<Value> {
CAPABILITY_PACKS
.iter()
.filter(|skill| skill_matches_agent(skill, agent_id))
.map(skill_summary)
.collect()
}
pub fn public_capability_packs() -> &'static [MnoteCapabilityPack] {
CAPABILITY_PACKS
}
pub fn find_skill(skill_id: &str, agent_id: Option<&str>) -> Option<&'static MnoteSkill> {
let requested = skill_id.trim();
SKILLS
find_capability_pack(skill_id, agent_id)
}
pub fn find_capability_pack(
capability_id: &str,
agent_id: Option<&str>,
) -> Option<&'static MnoteCapabilityPack> {
let requested = canonical_skill_id(capability_id.trim());
CAPABILITY_PACKS
.iter()
.find(|skill| skill.id == requested && skill_matches_agent(skill, agent_id))
}
pub fn capability_ids_for_tool(tool_name: &str) -> Vec<&'static str> {
let name = tool_name.trim();
if name.is_empty() {
return Vec::new();
}
CAPABILITY_PACKS
.iter()
.filter(|pack| pack.tool_names.iter().any(|tool| *tool == name))
.map(|pack| pack.id)
.collect()
}
pub fn manifest_capabilities() -> Vec<Value> {
CAPABILITY_PACKS
.iter()
.map(|pack| {
json!({
"id": pack.id,
"title": pack.title,
"description": pack.description,
"category": pack.category,
"agentIds": pack.agent_ids,
"readOnly": pack.read_only,
"requiresContextRefs": pack.requires_context_refs,
"skillId": pack.id,
"toolNames": pack.tool_names,
"uiKind": if pack.category == "chat" { "chat" } else { "ai_capability" },
"public": true
})
})
.collect()
}
fn canonical_skill_id(skill_id: &str) -> &str {
match skill_id {
"mnote-document-evidence" => "mnote-local-index",
other => other,
}
}
pub async fn skill_read(
context: &RequestContext,
input: &ToolCallInput,
@@ -196,6 +263,7 @@ fn skill_summary(skill: &MnoteSkill) -> Value {
"id": skill.id,
"title": skill.title,
"description": skill.description,
"category": skill.category,
"agentIds": skill.agent_ids,
"readOnly": skill.read_only,
"requiresContextRefs": skill.requires_context_refs,
@@ -296,18 +364,33 @@ mod tests {
}
#[test]
fn skill_registry_exposes_document_evidence_skill_to_agents() {
fn skill_registry_exposes_local_index_skill_to_agents() {
let hermes_skills = skill_summaries_for_agent(Some("hermes"));
let skill = hermes_skills
.iter()
.find(|skill| skill["id"] == "mnote-document-evidence")
.expect("hermes should see document evidence skill");
assert_eq!(skill["readOnly"], true);
.find(|skill| skill["id"] == "mnote-local-index")
.expect("hermes should see local index skill");
assert_eq!(skill["readOnly"], false);
assert!(skill["toolNames"]
.as_array()
.expect("tool names")
.iter()
.any(|name| name == "mnote.evidence.search"));
assert!(skill["toolNames"]
.as_array()
.expect("tool names")
.iter()
.any(|name| name == "mnote.index.update_settings"));
assert!(!hermes_skills
.iter()
.any(|skill| skill["id"] == "mnote-document-evidence"));
}
#[test]
fn skill_read_keeps_document_evidence_compat_alias() {
let skill = find_skill("mnote-document-evidence", Some("reasonix"))
.expect("compat alias should resolve");
assert_eq!(skill.id, "mnote-local-index");
}
#[tokio::test]
+276 -22
View File
@@ -7,10 +7,10 @@ use axum::extract::{Extension, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode};
use axum::Json;
use core_protocol::{
EvidenceBBox, EvidenceLocator, EvidenceOpenAction, EvidenceOpenRequest, EvidenceReadRequest,
EvidenceResourceKind, EvidenceSearchMode, EvidenceSearchRequest, EvidenceSearchResponse,
EvidenceSearchResult, ResourceSourceMap, SourceMapBlock, SourceMapTextItem,
EVIDENCE_LOCATOR_SCHEMA,
EvidenceBBox, EvidenceLocator, EvidenceOpenAction, EvidenceOpenRequest, EvidenceRange,
EvidenceReadRequest, EvidenceResourceKind, EvidenceSearchMode, EvidenceSearchRequest,
EvidenceSearchResponse, EvidenceSearchResult, ResourceSourceMap, SourceMapBlock,
SourceMapTextItem, EVIDENCE_LOCATOR_SCHEMA,
};
use serde_json::Map;
use serde_json::{json, Value};
@@ -47,18 +47,31 @@ pub(crate) async fn search_payload(
)
.map_err(|error| error.with_context(context))?;
let page_id = body.scope.target_document_id.as_deref();
let evidence_owner_filter = if body.scope.include_resources || body.scope.include_ocr {
None
} else {
page_id
};
let query = body.query.trim().to_string();
if matches!(body.mode, EvidenceSearchMode::Graph) {
if let Some(results) = local_search_index::query_evidence_graph_results(
&root_path, &query, page_id, body.top_k,
if let Some(mut results) = local_search_index::query_evidence_graph_results(
&root_path,
&query,
evidence_owner_filter,
body.top_k,
)? {
enrich_citation_links(&mut results);
return Ok(json!(EvidenceSearchResponse { ok: true, results }));
}
}
if let Some(mut results) =
local_search_index::query_evidence_sqlite_results(&root_path, &query, page_id, body.top_k)?
{
if let Some(mut results) = local_search_index::query_evidence_sqlite_results(
&root_path,
&query,
evidence_owner_filter,
body.top_k,
)? {
enrich_sqlite_evidence_results(&mut results, &root_path, &query);
enrich_citation_links(&mut results);
if !results.is_empty() || !query.is_empty() {
let response = EvidenceSearchResponse { ok: true, results };
return Ok(json!(response));
@@ -77,9 +90,13 @@ pub(crate) async fn search_payload(
)?;
let response = EvidenceSearchResponse {
ok: true,
results: evidence_results_from_local_search(
&search, &root_path, &root_uri, body.mode, &query,
),
results: {
let mut results = evidence_results_from_local_search(
&search, &root_path, &root_uri, body.mode, &query,
);
enrich_citation_links(&mut results);
results
},
};
Ok(json!(response))
}
@@ -127,6 +144,149 @@ fn enrich_sqlite_evidence_results(
}
}
fn enrich_citation_links(results: &mut [EvidenceSearchResult]) {
for result in results {
let citation_url = citation_url_for_locator(&result.source);
result.source.open_action.url = citation_url.clone();
result.citation_label = Some(citation_label_for_locator(&result.source));
result.citation_markdown = Some(citation_markdown_for_locator(&result.source));
result.citation_url = Some(citation_url);
}
}
fn citation_markdown_for_locator(locator: &EvidenceLocator) -> String {
let label = citation_label_for_locator(locator);
let url = citation_url_for_locator(locator);
format!(
"[{}]({})",
markdown_link_label_escape(&label),
url.replace(')', "%29")
)
}
fn citation_label_for_locator(locator: &EvidenceLocator) -> String {
let source_path = locator
.resource_path
.as_deref()
.filter(|value| !value.trim().is_empty())
.unwrap_or(locator.owner_document_path.as_str());
let name = source_path
.rsplit('/')
.find(|part| !part.trim().is_empty())
.unwrap_or(source_path)
.trim();
let mut parts = vec![if name.is_empty() {
"证据".to_string()
} else {
name.to_string()
}];
if let Some(page) = locator.page {
parts.push(format!("p.{page}"));
}
if let Some(section) = locator
.section_path
.last()
.filter(|value| !value.trim().is_empty())
{
parts.push(section.to_string());
}
parts.join(" · ")
}
fn citation_url_for_locator(locator: &EvidenceLocator) -> String {
let owner_document_id = locator.owner_document_id.trim();
let mut url = if owner_document_id.is_empty() {
let existing = locator.open_action.url.trim();
if existing.is_empty() {
"/".to_string()
} else {
existing.to_string()
}
} else {
format!("/documents/{owner_document_id}")
};
append_query_param(&mut url, "sourceKind", "local_folder");
append_query_param(&mut url, "rootUri", locator.root_uri.trim());
if let Some(resource_path) = locator
.resource_path
.as_deref()
.filter(|value| !value.trim().is_empty())
{
append_query_param(
&mut url,
"resourceTab",
&format!(
"resource:file:{}:{}",
locator.root_uri.trim(),
resource_path
),
);
append_query_param(&mut url, "resourcePath", resource_path);
}
if let Some(page) = locator.page {
append_query_param(&mut url, "page", &page.to_string());
}
if let Some(bbox) = &locator.bbox {
append_query_param(
&mut url,
"bbox",
&format!("{},{},{},{}", bbox.x0, bbox.y0, bbox.x1, bbox.y1),
);
}
if let Some(block_id) = locator.block_id.as_deref() {
append_query_param(&mut url, "blockId", block_id);
}
if let Some(source_map_path) = locator.source_map_path.as_deref() {
append_query_param(&mut url, "sourceMapPath", source_map_path);
}
if let Some(line_range) = &locator.line_range {
append_query_param(
&mut url,
"lineRange",
&format!("{}-{}", line_range.start, line_range.end),
);
}
if let Some(char_range) = &locator.char_range {
append_query_param(
&mut url,
"charRange",
&format!("{}-{}", char_range.start, char_range.end),
);
}
url
}
fn append_query_param(url: &mut String, key: &str, value: &str) {
let value = value.trim();
if value.is_empty() {
return;
}
let separator = if url.contains('?') { '&' } else { '?' };
url.push(separator);
url.push_str(&encode_query_component(key));
url.push('=');
url.push_str(&encode_query_component(value));
}
fn encode_query_component(value: &str) -> String {
let mut encoded = String::with_capacity(value.len());
for byte in value.as_bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
encoded.push(*byte as char);
} else {
encoded.push_str(&format!("%{byte:02X}"));
}
}
encoded
}
fn markdown_link_label_escape(value: &str) -> String {
value
.replace('\\', "\\\\")
.replace('[', "\\[")
.replace(']', "\\]")
}
pub async fn read(
State(state): State<AppState>,
Extension(context): Extension<RequestContext>,
@@ -154,12 +314,13 @@ pub(crate) async fn read_payload(
state, context, &root_uri,
)
.map_err(|error| error.with_context(context))?;
if let Some(results) = read_source_map_context(
if let Some(mut results) = read_source_map_context(
&root_path,
&body.locator,
body.context.before_blocks,
body.context.after_blocks,
) {
enrich_citation_links(&mut results);
let quote = results
.iter()
.find(|item| locator_matches(&item.source, &body.locator))
@@ -176,17 +337,21 @@ pub(crate) async fn read_payload(
"locator": body.locator,
"quote": quote,
"sectionPath": section_path,
"citationUrl": citation_url_for_locator(&body.locator),
"citationLabel": citation_label_for_locator(&body.locator),
"citationMarkdown": citation_markdown_for_locator(&body.locator),
"contextBlocks": results,
});
return Ok(response);
}
if let Some(results) = local_search_index::read_evidence_sqlite_context(
if let Some(mut results) = local_search_index::read_evidence_sqlite_context(
&root_path,
&body.locator,
body.context.before_blocks,
body.context.after_blocks,
)? {
if !results.is_empty() {
enrich_citation_links(&mut results);
let quote = results
.iter()
.find(|item| locator_matches(&item.source, &body.locator))
@@ -197,6 +362,9 @@ pub(crate) async fn read_payload(
"ok": true,
"locator": body.locator,
"quote": quote,
"citationUrl": citation_url_for_locator(&body.locator),
"citationLabel": citation_label_for_locator(&body.locator),
"citationMarkdown": citation_markdown_for_locator(&body.locator),
"contextBlocks": results,
});
return Ok(response);
@@ -222,13 +390,14 @@ pub(crate) async fn read_payload(
false,
true,
)?;
let results = evidence_results_from_local_search(
let mut results = evidence_results_from_local_search(
&search,
&root_path,
&root_uri,
EvidenceSearchMode::Tree,
&query,
);
enrich_citation_links(&mut results);
let quote = results
.first()
.map(|item| item.quote.clone())
@@ -237,6 +406,9 @@ pub(crate) async fn read_payload(
"ok": true,
"locator": body.locator,
"quote": quote,
"citationUrl": citation_url_for_locator(&body.locator),
"citationLabel": citation_label_for_locator(&body.locator),
"citationMarkdown": citation_markdown_for_locator(&body.locator),
"contextBlocks": results,
});
Ok(response)
@@ -365,6 +537,9 @@ fn source_map_block_result(
quote: block.text.clone(),
score,
source,
citation_url: None,
citation_label: None,
citation_markdown: None,
}
}
@@ -394,7 +569,9 @@ pub(crate) async fn open_payload(
context: &RequestContext,
body: EvidenceOpenRequest,
) -> Result<Value, WebError> {
let locator = body.locator;
let mut locator = body.locator;
let citation_url = citation_url_for_locator(&locator);
locator.open_action.url = citation_url.clone();
let root_uri = locator.root_uri.trim().to_string();
if root_uri.is_empty() {
return Err(
@@ -410,6 +587,9 @@ pub(crate) async fn open_payload(
"ok": true,
"locator": locator.clone(),
"openAction": locator.open_action,
"citationUrl": citation_url,
"citationLabel": citation_label_for_locator(&locator),
"citationMarkdown": citation_markdown_for_locator(&locator),
});
Ok(response)
}
@@ -499,19 +679,29 @@ pub(crate) fn evidence_results_from_local_search(
})
.or_else(|| source_map_hit.as_ref().and_then(|hit| hit.bbox.clone()));
let block_id = result
.get("ocrEvidence")
.and_then(|_| source_map_hit.as_ref().and_then(|hit| hit.block_id.clone()))
.or_else(|| result.get("id").and_then(Value::as_str).map(str::to_string))
.get("blockId")
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| {
result
.get("ocrEvidence")
.and_then(|_| source_map_hit.as_ref().and_then(|hit| hit.block_id.clone()))
})
.or_else(|| source_map_hit.as_ref().and_then(|hit| hit.block_id.clone()));
let line_range = result.get("lineRange").and_then(evidence_range_from_value);
let char_range = source_map_hit
.as_ref()
.and_then(|hit| hit.char_range.clone());
.and_then(|hit| hit.char_range.clone())
.or_else(|| result.get("charRange").and_then(evidence_range_from_value));
let open_action_params = evidence_open_action_params(
&result,
query,
&mode,
page,
bbox.clone(),
block_id.clone(),
line_range.clone(),
char_range.clone(),
source_map_path.clone(),
);
let locator = EvidenceLocator {
@@ -534,7 +724,7 @@ pub(crate) fn evidence_results_from_local_search(
.collect::<Vec<_>>()
})
.unwrap_or_default(),
line_range: None,
line_range,
char_range,
block_id,
source_map_path: source_map_path.clone(),
@@ -557,6 +747,9 @@ pub(crate) fn evidence_results_from_local_search(
.to_string(),
score: result.get("score").and_then(Value::as_f64).unwrap_or(0.0),
source: locator,
citation_url: None,
citation_label: None,
citation_markdown: None,
}
})
.collect()
@@ -568,6 +761,9 @@ fn evidence_open_action_params(
mode: &EvidenceSearchMode,
page: Option<u32>,
bbox: Option<EvidenceBBox>,
block_id: Option<String>,
line_range: Option<EvidenceRange>,
char_range: Option<EvidenceRange>,
source_map_path: Option<String>,
) -> Map<String, Value> {
let mut params = Map::new();
@@ -586,12 +782,35 @@ fn evidence_open_action_params(
if let Some(bbox) = bbox {
params.insert("bbox".into(), json!(bbox));
}
if let Some(block_id) = block_id {
params.insert("blockId".into(), json!(block_id));
}
if let Some(line_range) = line_range {
params.insert("lineRange".into(), json!(line_range));
}
if let Some(char_range) = char_range {
params.insert("charRange".into(), json!(char_range));
}
if let Some(source_map_path) = source_map_path {
params.insert("sourceMapPath".into(), json!(source_map_path));
}
params
}
fn evidence_range_from_value(value: &Value) -> Option<EvidenceRange> {
if let Some(map) = value.as_object() {
let start = map.get("start")?.as_u64()?;
let end = map.get("end")?.as_u64()?;
return Some(EvidenceRange { start, end });
}
let text = value.as_str()?.trim();
let (start, end) = text.split_once('-')?;
Some(EvidenceRange {
start: start.trim().parse().ok()?,
end: end.trim().parse().ok()?,
})
}
fn infer_resource_kind(resource_type: &str, resource_path: Option<&str>) -> EvidenceResourceKind {
let extension = resource_path
.and_then(|path| Path::new(path).extension())
@@ -788,6 +1007,15 @@ mod tests {
)
.expect("readme");
let root_uri = format!("file://{}", root.display());
local_search_index::write_local_index_settings(
&root,
&[String::from(".")],
None,
None,
None,
None,
)
.expect("settings");
local_search_index::refresh_local_search_index(&root, &root_uri, "local-ws-evidence-route")
.expect("refresh");
fs::write(
@@ -838,6 +1066,7 @@ mod tests {
"scope": {
"workspaceId": "local-ws-evidence-route",
"rootUri": root_uri,
"targetDocumentId": "local-md:missing.md",
"includeResources": true,
"includeOcr": true
},
@@ -925,13 +1154,14 @@ mod tests {
}]
});
let results = evidence_results_from_local_search(
let mut results = evidence_results_from_local_search(
&payload,
&root,
"file:///workspace",
EvidenceSearchMode::Hybrid,
"OCR-only-token",
);
enrich_citation_links(&mut results);
fs::remove_dir_all(&root).ok();
@@ -954,6 +1184,16 @@ mod tests {
locator.open_action.params["sourceMapPath"].as_str(),
Some("docs/Page.ocr/photo.png.source-map.json")
);
let citation_url = results[0].citation_url.as_deref().unwrap_or_default();
assert!(citation_url.starts_with("/documents/local-md:docs~2FPage.md?"));
assert!(citation_url.contains("resourceTab=resource%3Afile%3Afile%3A%2F%2F%2Fworkspace%3Adocs%2FPage.assets%2Fphoto.png"));
assert!(citation_url.contains("page=1"));
assert!(citation_url.contains("blockId=p1_b1"));
assert!(results[0]
.citation_markdown
.as_deref()
.unwrap_or_default()
.contains("photo.png"));
}
#[test]
@@ -1011,9 +1251,13 @@ mod tests {
quote: "NeedleToken 原文定位".into(),
score: 1.0,
source: locator,
citation_url: None,
citation_label: None,
citation_markdown: None,
}];
enrich_sqlite_evidence_results(&mut results, &root, "NeedleToken");
enrich_citation_links(&mut results);
fs::remove_dir_all(&root).ok();
let locator = &results[0].source;
@@ -1029,6 +1273,16 @@ mod tests {
locator.open_action.params["blockId"].as_str(),
Some("p2_b7")
);
assert!(results[0]
.citation_url
.as_deref()
.unwrap_or_default()
.contains("sourceMapPath=docs%2FPage.ocr%2Fspec.pdf.source-map.json"));
assert!(results[0]
.citation_markdown
.as_deref()
.unwrap_or_default()
.contains("spec.pdf"));
}
#[test]
@@ -1318,6 +1318,123 @@ pub async fn toggle_skill(
))
}
pub async fn list_capabilities(
State(state): State<AppState>,
Extension(context): Extension<RequestContext>,
Query(query): Query<HashMap<String, String>>,
) -> Result<(StatusCode, HeaderMap, Json<Value>), WebError> {
ensure_authenticated(&context)?;
let runtime = query.get("runtime").map(String::as_str).unwrap_or("mnote");
if runtime != "mnote" {
return Ok((
StatusCode::OK,
stamp_client_headers(),
Json(json!({
"ok": true,
"runtime": runtime,
"categories": [],
"archived": []
})),
));
}
let fallback_profile = active_profile_name().unwrap_or_else(|| "default".into());
let profile = query
.get("profile")
.map(String::as_str)
.unwrap_or(fallback_profile.as_str());
let payload = mnote_capabilities_payload(
&state,
&context,
query.get("agentId").map(String::as_str),
profile,
)?;
Ok((StatusCode::OK, stamp_client_headers(), Json(payload)))
}
pub async fn toggle_capability(
State(state): State<AppState>,
Extension(context): Extension<RequestContext>,
Json(payload): Json<Value>,
) -> Result<(StatusCode, HeaderMap, Json<Value>), WebError> {
ensure_authenticated(&context)?;
let capability_id = payload
.get("id")
.or_else(|| payload.get("name"))
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| {
WebError::bad_request_code("hermes_client_bad_request", "缺少 capability id")
.with_context(&context)
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web")
.with_header(HEADER_HERMES_CLIENT_OWNER, "mnote-web-hermes-client")
})?;
let enabled = payload
.get("enabled")
.and_then(Value::as_bool)
.ok_or_else(|| {
WebError::bad_request_code("hermes_client_bad_request", "缺少 enabled")
.with_context(&context)
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web")
.with_header(HEADER_HERMES_CLIENT_OWNER, "mnote-web-hermes-client")
})?;
let runtime = payload
.get("runtime")
.and_then(Value::as_str)
.map(str::trim)
.unwrap_or("mnote");
if runtime != "mnote" {
return Err(WebError::bad_request_code(
"hermes_client_capability_runtime_unsupported",
"当前只支持 MNote 内置能力开关",
)
.with_context(&context));
}
let fallback_profile = active_profile_name().unwrap_or_else(|| "default".into());
let profile = payload
.get("profile")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or(fallback_profile.as_str());
let skill = crate::hermes_tools::skill::find_skill(capability_id, None).ok_or_else(|| {
WebError::new(
StatusCode::NOT_FOUND,
"mnote_capability_not_found",
"未知 MNote AI 能力",
)
.with_context(&context)
})?;
let actor_id = page_ai_actor_id(&state, &context)?;
ensure_page_ai_actor_user(&state, &actor_id, page_ai_actor_is_admin(&context))?;
set_mnote_builtin_capability_enabled(&state, &actor_id, capability_id, enabled, &context)?;
for tool_name in skill.tool_names {
if mnote_capability_tool_toggleable(tool_name) {
set_mnote_tool_enabled(profile, tool_name, enabled).map_err(|error| {
WebError::bad_gateway_code(
"hermes_client_capability_tool_toggle_failed",
format!("更新 MNote 能力工具设置失败: {error}"),
)
.with_context(&context)
.with_header(HEADER_MNOTE_WEB_OWNER, "mnote-web")
.with_header(HEADER_HERMES_CLIENT_OWNER, "mnote-web-hermes-client")
})?;
}
}
Ok((
StatusCode::OK,
stamp_client_headers(),
Json(json!({
"ok": true,
"runtime": "mnote",
"id": capability_id,
"enabled": enabled,
"profile": profile,
"configScope": "user_sqlite+profile_tool_policy"
})),
))
}
pub async fn toggle_tool(
Extension(context): Extension<RequestContext>,
Json(payload): Json<Value>,
@@ -4068,6 +4185,217 @@ fn mnote_tool_entry(tool: &Value, disabled: &[String]) -> Option<Value> {
}))
}
fn mnote_capabilities_payload(
state: &AppState,
context: &RequestContext,
agent_id: Option<&str>,
profile: &str,
) -> Result<Value, WebError> {
let mut skills_payload = mnote_builtin_skills_payload(agent_id);
stamp_mnote_builtin_skill_payload_policy(state, context, &mut skills_payload)?;
let tools_by_name = mnote_tools_payload(profile)
.into_iter()
.filter_map(|tool| {
let name = tool.get("name").and_then(Value::as_str)?.to_string();
Some((name, tool))
})
.collect::<BTreeMap<_, _>>();
let mut capability_categories: BTreeMap<String, Vec<Value>> = BTreeMap::new();
for category in skills_payload
.get("categories")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let mut capabilities = Vec::new();
for skill in category
.get("skills")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
let Some(id) = skill.get("id").and_then(Value::as_str) else {
continue;
};
if id == "mnote-chat-only" {
continue;
}
let tool_names = skill
.get("toolNames")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.filter(|name| !name.trim().is_empty())
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
})
.unwrap_or_default();
let tools = tool_names
.iter()
.filter_map(|name| tools_by_name.get(name).cloned())
.collect::<Vec<_>>();
let disabled_tool_count = tools
.iter()
.filter(|tool| tool.get("enabled").and_then(Value::as_bool) == Some(false))
.count();
let enabled = skill
.get("enabled")
.and_then(Value::as_bool)
.unwrap_or(true);
let status = if !enabled {
"disabled"
} else if disabled_tool_count > 0 {
"partial"
} else {
"available"
};
let capability_category = skill
.get("category")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or("mnote");
capabilities.push(json!({
"id": id,
"name": id,
"title": skill.get("title").cloned().unwrap_or_else(|| json!(id)),
"description": skill.get("description").cloned().unwrap_or(Value::Null),
"enabled": enabled,
"toggleable": skill.get("toggleable").cloned().unwrap_or_else(|| json!(true)),
"builtin": true,
"configurable": true,
"configScope": "user_sqlite+profile_tool_policy",
"skillKind": "mnote_capability",
"source": "mnote",
"origin": "builtin",
"category": capability_category,
"categoryTitle": mnote_capability_category_title(capability_category),
"capabilityId": id,
"capabilityKind": "mnote_builtin",
"uiKind": mnote_capability_ui_kind(capability_category),
"skillId": id,
"readOnly": skill.get("readOnly").cloned().unwrap_or(Value::Bool(false)),
"agentIds": skill.get("agentIds").cloned().unwrap_or(Value::Null),
"requiresContextRefs": skill.get("requiresContextRefs").cloned().unwrap_or(Value::Null),
"toolNames": tool_names,
"tools": tools,
"toolCount": tools.len(),
"disabledToolCount": disabled_tool_count,
"status": status,
}));
}
for capability in capabilities {
let category_name = capability
.get("category")
.and_then(Value::as_str)
.unwrap_or("mnote")
.to_string();
capability_categories
.entry(category_name)
.or_default()
.push(capability);
}
}
let categories = ordered_mnote_capability_categories(capability_categories)
.into_iter()
.map(|(name, capabilities)| {
json!({
"name": name,
"title": mnote_capability_category_title(&name),
"description": mnote_capability_category_description(&name),
"capabilities": capabilities.clone(),
"skills": capabilities
})
})
.collect::<Vec<_>>();
Ok(json!({
"ok": true,
"runtime": "mnote",
"profile": profile,
"categories": categories,
"archived": []
}))
}
fn ordered_mnote_capability_categories(
mut categories: BTreeMap<String, Vec<Value>>,
) -> Vec<(String, Vec<Value>)> {
let mut ordered = Vec::new();
for name in ["mnote", "knowledge", "file", "resource", "office", "chat"] {
if let Some(capabilities) = categories.remove(name) {
ordered.push((name.to_string(), capabilities));
}
}
ordered.extend(categories);
ordered
}
fn mnote_capability_category_title(category: &str) -> &'static str {
match category {
"knowledge" => "知识库与索引",
"file" => "本地文件",
"resource" => "资源编辑",
"office" => "Office / ONLYOFFICE",
"chat" => "聊天",
_ => "MNote",
}
}
fn mnote_capability_category_description(category: &str) -> &'static str {
match category {
"knowledge" => "本地索引、证据检索和资料范围管理。",
"file" => "授权目录内的本地 Markdown 文件读写。",
"resource" => "MNote 资源型编辑器能力,例如思维导图。",
"office" => "Office 摘要、建议和 ONLYOFFICE 实时编辑桥。",
"chat" => "不读取文档上下文的普通对话能力。",
_ => "MNote 页面上下文与基础能力。",
}
}
fn mnote_capability_ui_kind(category: &str) -> &'static str {
if category == "chat" {
"chat"
} else {
"ai_capability"
}
}
fn set_mnote_builtin_capability_enabled(
state: &AppState,
actor_id: &str,
capability_id: &str,
enabled: bool,
context: &RequestContext,
) -> Result<(), WebError> {
let key = format!("ai.agent.mnote_builtin.skill.{capability_id}.enabled");
state
.control_plane()
.upsert_user_ui_preference(control_plane::UpsertUserUiPreferenceInput {
id: None,
user_id: actor_id.to_string(),
workspace_id: None,
source_kind: None,
scope_kind: "page_ai_capability".to_string(),
scope_id: "mnote_builtin".to_string(),
key,
value_json: Value::Bool(enabled).to_string(),
})
.map(|_| ())
.map_err(|error| {
WebError::internal(format!("SQLite MNote AI 能力偏好写入失败: {error}"))
.with_context(context)
})
}
fn mnote_capability_tool_toggleable(tool_name: &str) -> bool {
!matches!(
tool_name,
"mnote.skill.read" | "mnote.context.snapshot" | "mnote.context.resolve_target"
)
}
fn extract_skill_description(markdown: &str) -> String {
markdown
.lines()
@@ -4451,6 +4779,7 @@ fn mnote_builtin_skills_payload(agent_id: Option<&str>) -> Value {
"skillKind": "mnote_builtin",
"source": "mnote",
"origin": "builtin",
"category": skill.get("category").cloned().unwrap_or_else(|| json!("mnote")),
"agentIds": skill.get("agentIds").cloned().unwrap_or(Value::Null),
"toolNames": skill.get("toolNames").cloned().unwrap_or(Value::Null),
"requiresContextRefs": skill.get("requiresContextRefs").cloned().unwrap_or(Value::Null)
@@ -10144,6 +10473,223 @@ mod tests {
let _ = fs::remove_dir_all(&hermes_home);
}
#[tokio::test]
async fn page_ai_capabilities_expose_local_index_and_toggle_tools() {
let _env_guard = env_lock().lock().expect("env lock");
let hermes_home = std::env::temp_dir().join(format!(
"mnote-web-ai-capability-policy-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&hermes_home);
fs::create_dir_all(&hermes_home).expect("hermes home");
std::env::set_var("HERMES_HOME", &hermes_home);
let app = build_app(test_state());
let response = app
.clone()
.oneshot(
Request::builder()
.method("GET")
.uri("/api/hermes/client/capabilities?runtime=mnote&agentId=reasonix&profile=chemist")
.header("x-mnote-actor-id", "user_1")
.header("x-mnote-actor-type", "user")
.body(Body::empty())
.expect("request"),
)
.await
.expect("capabilities");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("capabilities json");
let all_capabilities = payload["categories"]
.as_array()
.expect("categories")
.iter()
.flat_map(|category| category["capabilities"].as_array().into_iter().flatten())
.collect::<Vec<_>>();
assert!(
all_capabilities
.iter()
.all(|capability| capability["id"] != "mnote-chat-only"),
"纯聊天是 agent 模式,不应作为 MNote 公共能力展示"
);
let local_index = payload["categories"]
.as_array()
.expect("categories")
.iter()
.flat_map(|category| category["capabilities"].as_array().into_iter().flatten())
.find(|capability| capability["id"] == "mnote-local-index")
.expect("local index capability");
assert_eq!(local_index["enabled"], true);
assert_eq!(local_index["uiKind"], "ai_capability");
assert!(local_index["tools"]
.as_array()
.expect("local index tools")
.iter()
.any(|tool| tool["name"] == "mnote.index.status"));
assert!(local_index["tools"]
.as_array()
.expect("local index tools")
.iter()
.any(|tool| tool["name"] == "mnote.index.update_settings"));
let toggle_response = app
.clone()
.oneshot(
Request::builder()
.method("PUT")
.uri("/api/hermes/client/capabilities/toggle")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.header("x-mnote-actor-type", "user")
.body(Body::from(
json!({
"runtime": "mnote",
"profile": "chemist",
"id": "mnote-local-index",
"enabled": false
})
.to_string(),
))
.expect("request"),
)
.await
.expect("toggle capability");
assert_eq!(toggle_response.status(), StatusCode::OK);
let response = app
.clone()
.oneshot(
Request::builder()
.method("GET")
.uri("/api/hermes/client/capabilities?runtime=mnote&agentId=reasonix&profile=chemist")
.header("x-mnote-actor-id", "user_1")
.header("x-mnote-actor-type", "user")
.body(Body::empty())
.expect("request"),
)
.await
.expect("capabilities after toggle");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("capabilities json");
let local_index = payload["categories"]
.as_array()
.expect("categories")
.iter()
.flat_map(|category| category["capabilities"].as_array().into_iter().flatten())
.find(|capability| capability["id"] == "mnote-local-index")
.expect("local index capability");
assert_eq!(local_index["enabled"], false);
assert_eq!(local_index["status"], "disabled");
assert!(local_index["tools"]
.as_array()
.expect("local index tools")
.iter()
.any(|tool| tool["name"] == "mnote.index.status" && tool["enabled"] == false));
let tools_response = app
.oneshot(
Request::builder()
.method("GET")
.uri("/api/hermes/client/tools?scope=mnote&profile=chemist")
.header("x-mnote-actor-id", "user_1")
.body(Body::empty())
.expect("request"),
)
.await
.expect("tools after toggle");
assert_eq!(tools_response.status(), StatusCode::OK);
let body = to_bytes(tools_response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("tools json");
let tools = payload["tools"]
.as_array()
.expect("tools")
.iter()
.map(|tool| {
(
tool["name"].as_str().unwrap_or_default().to_string(),
tool.clone(),
)
})
.collect::<HashMap<_, _>>();
assert_eq!(tools["mnote.index.status"]["enabled"], false);
assert_eq!(tools["mnote.index.update_settings"]["enabled"], false);
std::env::remove_var("HERMES_HOME");
let _ = fs::remove_dir_all(&hermes_home);
}
#[tokio::test]
async fn page_ai_capabilities_group_onlyoffice_live_bridge() {
let _env_guard = env_lock().lock().expect("env lock");
let hermes_home = std::env::temp_dir().join(format!(
"mnote-web-ai-onlyoffice-capability-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&hermes_home);
fs::create_dir_all(&hermes_home).expect("hermes home");
std::env::set_var("HERMES_HOME", &hermes_home);
let response = build_app(test_state())
.oneshot(
Request::builder()
.method("GET")
.uri("/api/hermes/client/capabilities?runtime=mnote&agentId=reasonix&profile=chemist")
.header("x-mnote-actor-id", "user_1")
.header("x-mnote-actor-type", "user")
.body(Body::empty())
.expect("request"),
)
.await
.expect("capabilities");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("capabilities json");
let office_category = payload["categories"]
.as_array()
.expect("categories")
.iter()
.find(|category| category["name"] == "office")
.expect("office category");
assert_eq!(office_category["title"], "Office / ONLYOFFICE");
let onlyoffice = office_category["capabilities"]
.as_array()
.expect("office capabilities")
.iter()
.find(|capability| capability["id"] == "mnote-onlyoffice-live")
.expect("onlyoffice capability");
assert_eq!(onlyoffice["title"], "ONLYOFFICE 实时编辑");
assert_eq!(onlyoffice["categoryTitle"], "Office / ONLYOFFICE");
assert_eq!(onlyoffice["enabled"], true);
assert!(onlyoffice["tools"]
.as_array()
.expect("onlyoffice tools")
.iter()
.any(|tool| tool["name"] == "mnote.onlyoffice.session.current"));
assert!(onlyoffice["tools"]
.as_array()
.expect("onlyoffice tools")
.iter()
.any(|tool| tool["name"] == "mnote.onlyoffice.sheet.batch_set_values"));
assert!(onlyoffice["tools"]
.as_array()
.expect("onlyoffice tools")
.iter()
.any(|tool| tool["name"] == "mnote.onlyoffice.presentation.add_shape"));
std::env::remove_var("HERMES_HOME");
let _ = fs::remove_dir_all(&hermes_home);
}
#[test]
fn reasonix_memory_policy_defaults_off_and_reads_user_preference() {
let state = test_state();
@@ -3,8 +3,8 @@ use crate::app::AppState;
use crate::context::RequestContext;
use crate::error::WebError;
use crate::hermes_tools::{
artifact, block, context_tools, doc, evidence, manifest, onlyoffice_live, page, resource,
skill, ToolCallInput,
artifact, block, context_tools, doc, evidence, index, manifest, onlyoffice_live, page,
resource, skill, ToolCallInput,
};
use axum::extract::{Extension, Query, State};
use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode};
@@ -365,6 +365,11 @@ pub(crate) async fn execute_mnote_tool_call(
"mnote.evidence.search" => evidence::evidence_search(&state, &context, &input).await,
"mnote.evidence.read" => evidence::evidence_read(&state, &context, &input).await,
"mnote.evidence.open" => evidence::evidence_open(&state, &context, &input).await,
"mnote.index.status" => index::index_status(&state, &context, &input).await,
"mnote.index.refresh" => index::index_refresh(&state, &context, &input).await,
"mnote.index.update_settings" => {
index::index_update_settings(&state, &context, &input).await
}
"mnote.doc.plan_update" => doc::plan_update(&state, &context, &input).await,
"mnote.block.fetch" => block::block_fetch(&state, &context, &input).await,
"mnote.block.replace" => block::block_replace(&state, &context, &input).await,
@@ -704,6 +709,8 @@ fn is_read_tool(tool_name: &str) -> bool {
| "mnote.evidence.search"
| "mnote.evidence.read"
| "mnote.evidence.open"
| "mnote.index.status"
| "mnote.index.refresh"
| "mnote.block.fetch"
| "mnote.mindmap.fetch"
| "mnote.office.fetch_summary"
@@ -1578,6 +1585,70 @@ mod tests {
);
}
#[tokio::test]
async fn hermes_tools_manifest_exposes_mnote_capability_packs() {
let response = app()
.oneshot(
Request::builder()
.uri("/api/hermes/tools/mnote/manifest")
.header("x-mnote-actor-id", "user_1")
.body(Body::empty())
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
let manifest = &payload["manifest"];
let capabilities = manifest["capabilities"].as_array().expect("capabilities");
assert!(capabilities
.iter()
.any(|capability| capability["id"] == "mnote-local-index"));
assert!(capabilities
.iter()
.any(|capability| capability["id"] == "mnote-onlyoffice-live"));
let tools = manifest["tools"].as_array().expect("tools");
let index_status = tools
.iter()
.find(|tool| tool["name"] == "mnote.index.status")
.expect("index status tool");
assert!(index_status["capabilityIds"]
.as_array()
.expect("index capability ids")
.iter()
.any(|id| id == "mnote-local-index"));
let onlyoffice_batch_set = tools
.iter()
.find(|tool| tool["name"] == "mnote.onlyoffice.sheet.batch_set_values")
.expect("onlyoffice batch set tool");
assert_eq!(
onlyoffice_batch_set["capabilityId"],
"mnote-onlyoffice-live"
);
assert!(onlyoffice_batch_set["capabilityIds"]
.as_array()
.expect("onlyoffice capability ids")
.iter()
.any(|id| id == "mnote-onlyoffice-live"));
let context_snapshot = tools
.iter()
.find(|tool| tool["name"] == "mnote.context.snapshot")
.expect("context snapshot tool");
assert!(
context_snapshot["capabilityIds"]
.as_array()
.expect("context capability ids")
.len()
> 1
);
}
#[tokio::test]
async fn hermes_tools_onlyoffice_session_current_reads_registered_bridge_session() {
let app = app();
@@ -5386,6 +5457,21 @@ mod tests {
)
.expect("markdown");
let root_uri = format!("file://{}", root.display());
crate::routes::local_search_index::write_local_index_settings(
&root,
&[String::from(".")],
None,
None,
None,
None,
)
.expect("settings");
crate::routes::local_search_index::refresh_local_search_index(
&root,
&root_uri,
"local-ws-docs-search",
)
.expect("refresh");
let response = app()
.oneshot(
@@ -5437,6 +5523,12 @@ mod tests {
result["source"]["ownerDocumentPath"].as_str(),
Some("README.md")
);
assert!(result["citationMarkdown"]
.as_str()
.is_some_and(|value| value.contains("](/documents/")));
assert!(result["citationUrl"]
.as_str()
.is_some_and(|value| value.contains("resourceTab=")));
let evidence_id = result["evidenceId"].as_str().expect("evidence id");
assert_eq!(
payload["result"]["evidenceIds"][0].as_str(),
@@ -5480,6 +5572,112 @@ mod tests {
let _ = fs::remove_dir_all(&root);
}
#[tokio::test]
async fn hermes_tools_local_index_update_and_status_manage_scope() {
let root = std::env::temp_dir().join(format!("mnote-index-tool-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(root.join(".mnote")).expect("metadata");
fs::create_dir_all(root.join("docs")).expect("docs");
fs::write(
root.join(".mnote").join("workspace.json"),
r#"{"workspaceId":"local-ws-index-tool","ownerId":"user_1","createdAt":"2026-06-04T00:00:00Z","capabilities":["local_files","search"]}"#,
)
.expect("manifest");
fs::write(
root.join("docs").join("indexed.md"),
"# Indexed\n\nindex-tool-token\n",
)
.expect("markdown");
let root_uri = format!("file://{}", root.display());
let app = app();
let update_response = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.header("x-mnote-actor-type", "user")
.body(Body::from(
json!({
"toolName": "mnote.index.update_settings",
"workspaceId": "local-ws-index-tool",
"sourceKind": "local_folder",
"rootUri": root_uri,
"sessionId": "sess_index_tool",
"runId": "run_index_tool",
"toolCallId": "call_index_update",
"traceId": "trace_index_tool",
"dryRun": false,
"idempotencyKey": "idem_index_tool_update",
"args": {
"includePaths": ["docs"],
"scheduleMode": "manual",
"scheduleTime": "02:00",
"runOnChange": false
}
})
.to_string(),
))
.expect("update request"),
)
.await
.expect("update response");
assert_eq!(update_response.status(), StatusCode::OK);
let update_body = to_bytes(update_response.into_body(), usize::MAX)
.await
.expect("update body");
let update_payload: Value = serde_json::from_slice(&update_body).expect("update json");
assert_eq!(
update_payload["result"]["settings"]["includePaths"][0],
"docs"
);
assert_eq!(update_payload["result"]["index"]["documentCount"], 1);
assert!(root.join(".mnote/index/search-index.json").exists());
assert!(root.join(".mnote/index/evidence.sqlite").exists());
let status_response = app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/hermes/tools/mnote/call")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_1")
.header("x-mnote-actor-type", "user")
.body(Body::from(
json!({
"toolName": "mnote.index.status",
"workspaceId": "local-ws-index-tool",
"sourceKind": "local_folder",
"rootUri": root_uri,
"sessionId": "sess_index_tool",
"runId": "run_index_tool",
"toolCallId": "call_index_status",
"traceId": "trace_index_tool",
"args": {}
})
.to_string(),
))
.expect("status request"),
)
.await
.expect("status response");
assert_eq!(status_response.status(), StatusCode::OK);
let status_body = to_bytes(status_response.into_body(), usize::MAX)
.await
.expect("status body");
let status_payload: Value = serde_json::from_slice(&status_body).expect("status json");
assert_eq!(
status_payload["result"]["result"]["settings"]["includePaths"][0],
"docs"
);
assert_eq!(status_payload["audit"]["effect"], "read");
let _ = fs::remove_dir_all(&root);
}
#[tokio::test]
async fn hermes_tools_legacy_docs_read_returns_document_with_locator() {
let root =
@@ -295,6 +295,7 @@ struct LocalFolderRow {
capabilities: Vec<String>,
workspace_id: String,
root_source_uri: String,
index_status: Option<String>,
}
#[derive(Debug, Clone)]
@@ -303,6 +304,40 @@ struct LocalFolderScanResult {
watch_revision: LocalFolderWatchRevision,
}
#[derive(Debug, Clone, Default)]
struct LocalFileTreeIndexState {
indexed_paths: BTreeSet<String>,
failed_paths: BTreeSet<String>,
}
impl LocalFileTreeIndexState {
fn load(root: &Path) -> Self {
local_search_index::local_evidence_source_statuses(root)
.map(|statuses| Self {
indexed_paths: statuses.indexed_paths,
failed_paths: statuses.failed_paths,
})
.unwrap_or_default()
}
fn status_for_entry(&self, entry: &LocalFolderEntry) -> Option<String> {
if entry.is_dir || entry.is_symlink {
return None;
}
let path = entry.relative_path.trim();
if path.is_empty() {
return None;
}
if self.failed_paths.contains(path) {
return Some("failed".to_string());
}
if self.indexed_paths.contains(path) {
return Some("indexed".to_string());
}
None
}
}
#[derive(Debug, Clone)]
pub(crate) struct LocalUploadFile {
name: String,
@@ -2717,6 +2752,7 @@ fn load_local_folder_file_tree_scope_snapshot(
let workspace_id = local_workspace_id(&canonical_root);
let root_source_uri = file_uri_for_path(&canonical_root);
let metadata = load_local_folder_metadata(&canonical_root)?;
let index_state = LocalFileTreeIndexState::load(&canonical_root);
let parent_relative_path = parent_relative_path
.map(str::trim)
.filter(|value| !value.is_empty() && *value != ".")
@@ -2746,6 +2782,7 @@ fn load_local_folder_file_tree_scope_snapshot(
&root_source_uri,
&workspace_id,
&metadata,
&index_state,
)?;
append_file_tree_reveal_rows(
&canonical_root,
@@ -2754,6 +2791,7 @@ fn load_local_folder_file_tree_scope_snapshot(
&root_source_uri,
&workspace_id,
&metadata,
&index_state,
&mut scan_result.rows,
)?;
@@ -6648,6 +6686,7 @@ fn scan_directory(
root_source_uri: &str,
workspace_id: &str,
metadata: &LocalFolderMetadata,
index_state: &LocalFileTreeIndexState,
rows: &mut Vec<LocalFolderRow>,
) -> Result<(), WebError> {
let mut entries = read_sorted_entries(directory, root)?;
@@ -6698,6 +6737,7 @@ fn scan_directory(
capabilities: local_entry_capabilities(&entry),
workspace_id: workspace_id.to_string(),
root_source_uri: root_source_uri.to_string(),
index_status: index_state.status_for_entry(&entry),
});
if entry.is_dir && !entry.is_symlink && max_depth.map_or(true, |limit| depth < limit) {
scan_directory(
@@ -6709,6 +6749,7 @@ fn scan_directory(
root_source_uri,
workspace_id,
metadata,
index_state,
rows,
)?;
}
@@ -6725,6 +6766,7 @@ fn scan_directory_shallow_with_revision(
root_source_uri: &str,
workspace_id: &str,
metadata: &LocalFolderMetadata,
index_state: &LocalFileTreeIndexState,
) -> Result<LocalFolderScanResult, WebError> {
let mut entries = read_sorted_entries(directory, root)?;
let parent_key = file_order_parent_key_for_directory(root, directory)?;
@@ -6797,6 +6839,7 @@ fn scan_directory_shallow_with_revision(
capabilities: local_entry_capabilities(entry),
workspace_id: workspace_id.to_string(),
root_source_uri: root_source_uri.to_string(),
index_status: index_state.status_for_entry(entry),
});
}
@@ -6867,6 +6910,7 @@ fn append_file_tree_reveal_rows(
root_source_uri: &str,
workspace_id: &str,
metadata: &LocalFolderMetadata,
index_state: &LocalFileTreeIndexState,
rows: &mut Vec<LocalFolderRow>,
) -> Result<(), WebError> {
let Some(reveal_relative_path) = reveal_relative_path
@@ -6924,6 +6968,7 @@ fn append_file_tree_reveal_rows(
root_source_uri,
workspace_id,
metadata,
index_state,
&mut scoped_rows,
)?;
for row in scoped_rows {
@@ -7124,9 +7169,25 @@ fn should_ignore_entry(relative_path: &str, file_name: &str) -> bool {
}
relative_path == ".mnote/trash"
|| relative_path.starts_with(".mnote/trash/")
|| is_local_index_artifact_entry(relative_path)
|| is_local_ocr_intermediate_entry(relative_path, file_name)
}
fn is_local_index_artifact_entry(relative_path: &str) -> bool {
let normalized = relative_path.trim().trim_matches('/').replace('\\', "/");
if normalized.is_empty() {
return false;
}
let segments = normalized
.split('/')
.filter(|segment| !segment.trim().is_empty())
.collect::<Vec<_>>();
segments
.windows(2)
.any(|window| window[0] == ".mnote" && window[1] == "index")
|| segments.iter().any(|segment| segment.ends_with(".ocr"))
}
fn is_local_ocr_intermediate_entry(relative_path: &str, file_name: &str) -> bool {
let normalized = relative_path.trim().trim_matches('/').replace('\\', "/");
if normalized.is_empty() {
@@ -7435,6 +7496,7 @@ fn scan_markdown_page_tree(
capabilities: local_entry_capabilities(&entry),
workspace_id: workspace_id.to_string(),
root_source_uri: root_source_uri.to_string(),
index_status: None,
});
directory_rows.extend(child_rows);
contains_markdown = true;
@@ -7483,6 +7545,7 @@ fn scan_markdown_page_tree(
capabilities: local_entry_capabilities(&entry),
workspace_id: workspace_id.to_string(),
root_source_uri: root_source_uri.to_string(),
index_status: None,
});
}
directory_rows.extend(child_rows);
@@ -7510,6 +7573,7 @@ fn scan_markdown_page_tree(
capabilities: local_entry_capabilities(&entry),
workspace_id: workspace_id.to_string(),
root_source_uri: root_source_uri.to_string(),
index_status: None,
});
continue;
}
@@ -7546,6 +7610,7 @@ fn scan_markdown_page_tree(
capabilities: local_entry_capabilities(&entry),
workspace_id: workspace_id.to_string(),
root_source_uri: root_source_uri.to_string(),
index_status: None,
});
contains_markdown = true;
}
@@ -7691,6 +7756,10 @@ fn local_folder_row_to_projection_item(row: &LocalFolderRow) -> Value {
item["assetId"] = Value::String(asset_id.clone());
item["resourceMeta"]["assetId"] = Value::String(asset_id);
}
if let Some(index_status) = row.index_status.as_deref() {
item["indexStatus"] = Value::String(index_status.to_string());
item["resourceMeta"]["indexStatus"] = Value::String(index_status.to_string());
}
// Phase A1: 为 File/Page/Resource tree 输出统一 workspacePath
let object_kind = match row.row_kind.as_str() {
@@ -11648,6 +11717,15 @@ fn main() {}
.expect("write md");
let root_uri = format!("file://{}", root.display());
crate::routes::local_search_index::write_local_index_settings(
&root,
&[String::from(".")],
None,
None,
None,
Some(true),
)
.expect("settings");
crate::routes::local_search_index::refresh_local_search_index(
&root,
&root_uri,
@@ -12369,6 +12447,15 @@ fn main() {}
std::fs::write(root.join("README.md"), "# Before\nold-token\n").expect("write md");
let root_uri = format!("file://{}", root.display());
crate::routes::local_search_index::write_local_index_settings(
&root,
&[String::from(".")],
None,
None,
None,
Some(true),
)
.expect("settings");
crate::routes::local_search_index::refresh_local_search_index(
&root,
&root_uri,
@@ -13474,7 +13561,7 @@ fn main() {}
}
#[test]
fn local_ocr_sidecar_is_filetree_resource_not_page_tree_document() {
fn local_ocr_sidecar_artifacts_are_hidden_from_filetree_and_page_tree() {
let root = temp_root("mnote-local-ocr-sidecar-page-tree");
init_workspace(&root);
let root_uri = format!("file://{}", root.display());
@@ -13515,15 +13602,22 @@ fn main() {}
)
.expect("ocr image asset");
let docs_file_tree =
load_local_folder_file_tree_children_snapshot(&root_uri, "docs").expect("file tree");
let docs_file_items = docs_file_tree.projection["items"]
.as_array()
.expect("file items");
assert!(!docs_file_items
.iter()
.any(|item| item["title"].as_str() == Some("Page.ocr")));
let file_tree = load_local_folder_file_tree_children_snapshot(&root_uri, "docs/Page.ocr")
.expect("file tree");
.expect("direct hidden sidecar file tree");
let file_items = file_tree.projection["items"]
.as_array()
.expect("file items");
assert!(file_items
.iter()
.any(|item| item["title"].as_str() == Some("photo.png.ocr.md")));
for hidden_title in [
"photo.png.ocr.md",
"layout.json",
"abc_content_list.json",
"abc_model.json",
@@ -13534,7 +13628,7 @@ fn main() {}
!file_items
.iter()
.any(|item| item["title"].as_str() == Some(hidden_title)),
"OCR 中间产物不应出现在 FileTree: {hidden_title}"
"OCR / 索引产物不应出现在 FileTree: {hidden_title}"
);
}
@@ -13551,6 +13645,104 @@ fn main() {}
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn local_file_tree_marks_indexed_and_failed_source_files() {
let root = temp_root("mnote-local-filetree-index-status");
init_workspace(&root);
std::fs::write(root.join("ok.pdf"), b"%PDF-1.4\nok").expect("ok pdf");
std::fs::write(root.join("failed.pdf"), b"%PDF-1.4\nfailed").expect("failed pdf");
std::fs::write(root.join("draft.md"), "# Draft\n").expect("draft");
let index_dir = root.join(".mnote").join("index");
std::fs::create_dir_all(&index_dir).expect("index dir");
let evidence_path = index_dir.join("evidence.sqlite");
let connection = rusqlite::Connection::open(&evidence_path).expect("evidence sqlite");
connection
.execute_batch(
r#"
CREATE TABLE evidence_resource(
resource_id TEXT PRIMARY KEY,
owner_document_id TEXT NOT NULL,
owner_document_path TEXT NOT NULL,
source_root_relative_path TEXT NOT NULL,
provider TEXT NOT NULL,
source_hash TEXT NOT NULL,
artifact_root_relative_path TEXT NOT NULL,
source_map_root_relative_path TEXT NOT NULL,
updated_at_ms INTEGER NOT NULL
);
"#,
)
.expect("evidence schema");
connection
.execute(
"INSERT INTO evidence_resource(resource_id, owner_document_id, owner_document_path, source_root_relative_path, provider, source_hash, artifact_root_relative_path, source_map_root_relative_path, updated_at_ms) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
rusqlite::params![
"local-resource:ok.pdf#parse",
"local-resource:ok.pdf",
"ok.pdf",
"ok.pdf",
"liteparse",
"hash",
"ok.ocr/ok.pdf.parse.md",
"ok.ocr/ok.pdf.source-map.json",
1_i64,
],
)
.expect("insert indexed evidence");
connection
.execute(
"INSERT INTO evidence_resource(resource_id, owner_document_id, owner_document_path, source_root_relative_path, provider, source_hash, artifact_root_relative_path, source_map_root_relative_path, updated_at_ms) VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
rusqlite::params![
"local-md:draft.md",
"local-md:draft.md",
"draft.md",
"draft.md",
"markdown",
"hash",
"draft.md",
"draft.md.source-map.json",
1_i64,
],
)
.expect("insert markdown evidence");
let root_uri = format!("file://{}", root.display());
let search_index = json!({
"version": 1,
"builtAt": 1,
"rootUri": root_uri,
"workspaceId": "local-filetree-index-status",
"indexedPaths": ["."],
"documents": [],
"resources": [
{"resourceId": "local-resource:ok.pdf", "resourceType": "pdf", "title": "ok", "path": "ok.pdf", "updatedAt": 1},
{"resourceId": "local-resource:failed.pdf", "resourceType": "pdf", "title": "failed", "path": "failed.pdf", "updatedAt": 1}
]
});
std::fs::write(
index_dir.join("search-index.json"),
format!("{}\n", serde_json::to_string_pretty(&search_index).unwrap()),
)
.expect("search index");
let file_tree = load_local_folder_file_tree_snapshot(&format!("file://{}", root.display()))
.expect("file tree");
let items = file_tree.projection["items"].as_array().expect("items");
let status_for = |path: &str| {
items
.iter()
.find(|item| {
item["resourceMeta"]["extra"]["source"]["relativePath"].as_str() == Some(path)
})
.and_then(|item| item["indexStatus"].as_str())
};
assert_eq!(status_for("ok.pdf"), Some("indexed"));
assert_eq!(status_for("failed.pdf"), Some("failed"));
assert_eq!(status_for("draft.md"), None);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn local_rename_markdown_page_renames_nested_bundle() {
let root = temp_root("mnote-local-rename-nested-bundle");
@@ -15,6 +15,7 @@ use core_protocol::{
use rusqlite::{params, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::BTreeSet;
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -134,13 +135,19 @@ pub(crate) fn query_local_search_index_with_settings(
)?;
let normalized_query = normalize_search_text(query);
let page_id = page_id.map(str::trim).filter(|value| !value.is_empty());
let page_resource_path = page_id.and_then(local_resource_path_from_document_id);
let markdown_page_id = if page_resource_path.is_some() {
None
} else {
page_id
};
let recent_changes = local_recent_changes_projection(&index.documents, root_uri);
let mut results = Vec::new();
for document in index.documents.iter() {
if !index_relative_path_is_included(&document.path, &result_settings.include_paths) {
continue;
}
if let Some(page_id) = page_id {
if let Some(page_id) = markdown_page_id {
if document.document_id != page_id {
continue;
}
@@ -157,11 +164,16 @@ pub(crate) fn query_local_search_index_with_settings(
break;
}
}
if page_id.is_none() && results.len() < limit.max(1) as usize {
if markdown_page_id.is_none() && results.len() < limit.max(1) as usize {
for resource in index.resources.iter() {
if !index_relative_path_is_included(&resource.path, &result_settings.include_paths) {
continue;
}
if let Some(resource_path) = page_resource_path.as_deref() {
if resource.path != resource_path {
continue;
}
}
if !local_search_resource_matches(resource, &normalized_query, title_only, exact) {
continue;
}
@@ -180,7 +192,11 @@ pub(crate) fn query_local_search_index_with_settings(
continue;
}
if let Some(page_id) = page_id {
if entry.owner_document_id != page_id {
if let Some(resource_path) = page_resource_path.as_deref() {
if entry.source_root_relative_path != resource_path {
continue;
}
} else if entry.owner_document_id != page_id {
continue;
}
}
@@ -364,6 +380,43 @@ pub(crate) fn write_user_local_index_settings(
Ok(settings)
}
pub(crate) fn preview_user_local_index_settings(
store: &dyn ControlPlaneStore,
user_id: &str,
workspace_id: &str,
root_path: &Path,
include_paths: &[String],
schedule_mode: Option<&str>,
schedule_time: Option<&str>,
schedule_date: Option<&str>,
run_on_change: Option<bool>,
) -> Result<LocalIndexSettings, WebError> {
let user_id = user_id.trim();
if user_id.is_empty() || user_id == "anonymous" {
return Err(WebError::bad_request_code(
"local_index_settings_auth_required",
"本地索引设置需要登录用户",
));
}
let existing = read_user_local_index_settings(store, user_id, workspace_id, root_path)?;
let include_paths = normalize_index_include_paths(root_path, include_paths)?;
let schedule_mode =
normalize_index_schedule_mode(schedule_mode.unwrap_or(&existing.schedule_mode))?;
let schedule_time =
normalize_index_schedule_time(schedule_time.unwrap_or(&existing.schedule_time))?;
let schedule_date =
normalize_index_schedule_date(schedule_date.or(existing.schedule_date.as_deref()))?;
Ok(LocalIndexSettings {
schema: LOCAL_INDEX_SETTINGS_SCHEMA.to_string(),
include_paths,
schedule_mode,
schedule_time,
schedule_date,
run_on_change: run_on_change.unwrap_or(existing.run_on_change),
updated_at: now_ms(),
})
}
pub(crate) fn effective_local_index_settings_for_root(
store: &dyn ControlPlaneStore,
workspace_id: &str,
@@ -452,7 +505,7 @@ fn local_index_status_for_settings(
let mut document_count = 0usize;
let mut resource_count = 0usize;
let mut built_at = Value::Null;
let mut cache_matches_settings = false;
let cache_matches_settings;
let scheduled_due = if let Some(index) = index.as_ref() {
document_count = index.documents.len();
resource_count = index.resources.len();
@@ -463,6 +516,7 @@ fn local_index_status_for_settings(
&& normalized_indexed_paths(&index.indexed_paths) == settings.include_paths;
local_index_schedule_is_due(&settings, index.built_at)
} else {
cache_matches_settings = settings.include_paths.is_empty();
local_index_schedule_is_due(&settings, 0)
};
let evidence_block_count = if evidence_path.exists() {
@@ -622,6 +676,16 @@ pub(crate) fn query_evidence_sqlite_results(
query: &str,
owner_document_id: Option<&str>,
limit: u32,
) -> Result<Option<Vec<EvidenceSearchResult>>, WebError> {
query_evidence_sqlite_results_with_mode(root_path, query, owner_document_id, limit, true)
}
pub(crate) fn query_evidence_sqlite_results_with_mode(
root_path: &Path,
query: &str,
owner_document_id: Option<&str>,
limit: u32,
exact: bool,
) -> Result<Option<Vec<EvidenceSearchResult>>, WebError> {
let path = evidence_sqlite_path(root_path);
if !path.exists() {
@@ -631,24 +695,54 @@ pub(crate) fn query_evidence_sqlite_results(
if normalized_query.is_empty() {
return Ok(Some(Vec::new()));
}
let owner_document_id = owner_document_id
.map(str::trim)
.filter(|value| !value.is_empty());
let resource_path = owner_document_id.and_then(local_resource_path_from_document_id);
let owner_document_id = if resource_path.is_some() {
None
} else {
owner_document_id
};
let connection = Connection::open(&path).map_err(|error| {
WebError::bad_request_code(
"evidence_index_open_failed",
format!("无法打开 evidence 索引 {}: {error}", path.display()),
)
})?;
if !exact {
return Ok(Some(query_evidence_sqlite_fuzzy(
&connection,
normalized_query,
owner_document_id,
resource_path.as_deref(),
limit,
)?));
}
let fts_query = evidence_fts_phrase(normalized_query);
let results = match query_evidence_sqlite_fts(
&connection,
&fts_query,
normalized_query,
owner_document_id,
resource_path.as_deref(),
limit,
) {
Ok(results) if results.is_empty() => query_evidence_sqlite_like(
&connection,
normalized_query,
owner_document_id,
resource_path.as_deref(),
limit,
)?,
Ok(results) => results,
Err(_) => {
query_evidence_sqlite_like(&connection, normalized_query, owner_document_id, limit)?
}
Err(_) => query_evidence_sqlite_like(
&connection,
normalized_query,
owner_document_id,
resource_path.as_deref(),
limit,
)?,
};
Ok(Some(results))
}
@@ -718,6 +812,9 @@ pub(crate) fn read_evidence_sqlite_context(
0.8
},
source: source.clone(),
citation_url: None,
citation_label: None,
citation_markdown: None,
})
.collect::<Vec<_>>();
Ok(Some(results))
@@ -804,6 +901,9 @@ fn graph_edge_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<EvidenceSearchRes
block_id: source.block_id.or(Some(source_block_id)),
..source
},
citation_url: None,
citation_label: None,
citation_markdown: None,
})
}
@@ -824,6 +924,7 @@ fn query_evidence_sqlite_fts(
fts_query: &str,
display_query: &str,
owner_document_id: Option<&str>,
resource_path: Option<&str>,
limit: u32,
) -> Result<Vec<EvidenceSearchResult>, WebError> {
let mut sql = String::from(
@@ -835,8 +936,10 @@ fn query_evidence_sqlite_fts(
);
if owner_document_id.is_some() {
sql.push_str(" AND r.owner_document_id = ?2");
} else if resource_path.is_some() {
sql.push_str(" AND r.source_root_relative_path = ?2");
}
sql.push_str(if owner_document_id.is_some() {
sql.push_str(if owner_document_id.is_some() || resource_path.is_some() {
" ORDER BY rank LIMIT ?3"
} else {
" ORDER BY rank LIMIT ?2"
@@ -850,6 +953,13 @@ fn query_evidence_sqlite_fts(
})
.map_err(sqlite_error)?
.collect::<Result<Vec<_>, _>>()
} else if let Some(resource_path) = resource_path {
statement
.query_map(params![fts_query, resource_path, limit], |row| {
evidence_result_from_sqlite_row(row, display_query)
})
.map_err(sqlite_error)?
.collect::<Result<Vec<_>, _>>()
} else {
statement
.query_map(params![fts_query, limit], |row| {
@@ -865,6 +975,7 @@ fn query_evidence_sqlite_like(
connection: &Connection,
query: &str,
owner_document_id: Option<&str>,
resource_path: Option<&str>,
limit: u32,
) -> Result<Vec<EvidenceSearchResult>, WebError> {
let mut sql = String::from(
@@ -875,8 +986,10 @@ fn query_evidence_sqlite_like(
);
if owner_document_id.is_some() {
sql.push_str(" AND r.owner_document_id = ?2");
} else if resource_path.is_some() {
sql.push_str(" AND r.source_root_relative_path = ?2");
}
sql.push_str(if owner_document_id.is_some() {
sql.push_str(if owner_document_id.is_some() || resource_path.is_some() {
" LIMIT ?3"
} else {
" LIMIT ?2"
@@ -891,6 +1004,13 @@ fn query_evidence_sqlite_like(
})
.map_err(sqlite_error)?
.collect::<Result<Vec<_>, _>>()
} else if let Some(resource_path) = resource_path {
statement
.query_map(params![like_query, resource_path, limit], |row| {
evidence_result_from_sqlite_row(row, query)
})
.map_err(sqlite_error)?
.collect::<Result<Vec<_>, _>>()
} else {
statement
.query_map(params![like_query, limit], |row| {
@@ -902,6 +1022,80 @@ fn query_evidence_sqlite_like(
rows.map_err(sqlite_error)
}
fn query_evidence_sqlite_fuzzy(
connection: &Connection,
query: &str,
owner_document_id: Option<&str>,
resource_path: Option<&str>,
limit: u32,
) -> Result<Vec<EvidenceSearchResult>, WebError> {
let mut sql = String::from(
"SELECT b.block_id, b.text, b.locator_json, 0.0 AS rank \
FROM evidence_block b \
JOIN evidence_resource r ON r.resource_id = b.resource_id",
);
let first_char_like = query
.chars()
.find(|ch| !ch.is_whitespace())
.map(|ch| format!("%{}%", ch));
match (
owner_document_id.is_some() || resource_path.is_some(),
first_char_like.is_some(),
resource_path.is_some(),
) {
(true, true, true) => {
sql.push_str(" WHERE r.source_root_relative_path = ?1 AND b.text LIKE ?2 LIMIT ?3")
}
(true, true, false) => {
sql.push_str(" WHERE r.owner_document_id = ?1 AND b.text LIKE ?2 LIMIT ?3")
}
(true, false, true) => sql.push_str(" WHERE r.source_root_relative_path = ?1 LIMIT ?2"),
(true, false, false) => sql.push_str(" WHERE r.owner_document_id = ?1 LIMIT ?2"),
(false, true, _) => sql.push_str(" WHERE b.text LIKE ?1 LIMIT ?2"),
(false, false, _) => sql.push_str(" LIMIT ?1"),
}
let mut statement = connection.prepare(&sql).map_err(sqlite_error)?;
let scan_limit = i64::from(limit.max(1)) * 200;
let scope_value = owner_document_id.or(resource_path);
let rows = match (scope_value, first_char_like.as_deref()) {
(Some(scope_value), Some(first_char_like)) => statement
.query_map(params![scope_value, first_char_like, scan_limit], |row| {
evidence_result_from_sqlite_row(row, query)
})
.map_err(sqlite_error)?
.collect::<Result<Vec<_>, _>>(),
(Some(scope_value), None) => statement
.query_map(params![scope_value, scan_limit], |row| {
evidence_result_from_sqlite_row(row, query)
})
.map_err(sqlite_error)?
.collect::<Result<Vec<_>, _>>(),
(None, Some(first_char_like)) => statement
.query_map(params![first_char_like, scan_limit], |row| {
evidence_result_from_sqlite_row(row, query)
})
.map_err(sqlite_error)?
.collect::<Result<Vec<_>, _>>(),
(None, None) => statement
.query_map(params![scan_limit], |row| {
evidence_result_from_sqlite_row(row, query)
})
.map_err(sqlite_error)?
.collect::<Result<Vec<_>, _>>(),
}
.map_err(sqlite_error)?;
Ok(rows
.into_iter()
.filter(|result| {
fuzzy_search_match(
&normalize_search_text(&result.quote),
&normalize_search_text(query),
)
})
.take(limit.max(1) as usize)
.collect())
}
fn evidence_result_from_sqlite_row(
row: &rusqlite::Row<'_>,
query: &str,
@@ -922,6 +1116,9 @@ fn evidence_result_from_sqlite_row(
1.0 / (1.0 + rank.abs())
},
source,
citation_url: None,
citation_label: None,
citation_markdown: None,
})
}
@@ -945,6 +1142,18 @@ pub(crate) fn refresh_local_search_index_with_settings(
workspace_id: &str,
settings: &LocalIndexSettings,
) -> Result<Value, WebError> {
if settings.include_paths.is_empty() {
clear_local_search_index(root_path)?;
return Ok(json!({
"version": LOCAL_SEARCH_INDEX_VERSION,
"rootUri": root_uri,
"workspaceId": workspace_id,
"indexedPaths": [],
"builtAt": now_ms(),
"documentCount": 0,
"resourceCount": 0
}));
}
let index =
rebuild_local_search_index_with_settings(root_path, root_uri, workspace_id, settings)?;
Ok(json!({
@@ -1427,7 +1636,7 @@ fn parse_local_index_settings_value(
fn default_local_index_settings() -> LocalIndexSettings {
LocalIndexSettings {
schema: LOCAL_INDEX_SETTINGS_SCHEMA.to_string(),
include_paths: default_indexed_paths(),
include_paths: Vec::new(),
schedule_mode: default_index_schedule_mode(),
schedule_time: default_index_schedule_time(),
schedule_date: None,
@@ -1605,11 +1814,46 @@ fn normalize_index_include_paths(
if trimmed.is_empty() {
continue;
}
let raw_path = PathBuf::from(trimmed);
let normalized = if trimmed == "." || trimmed == "/" {
".".to_string()
} else if raw_path.is_absolute() {
let canonical = raw_path.canonicalize().map_err(|error| {
WebError::bad_request_code(
"local_index_scope_not_found",
format!("本地索引范围不存在 {}: {error}", raw_path.display()),
)
})?;
if !canonical.starts_with(&root_canonical) {
return Err(WebError::bad_request_code(
"local_index_scope_escape",
"本地索引目录必须位于当前授权 root 内",
));
}
if !canonical.is_dir() {
return Err(WebError::bad_request_code(
"local_index_scope_not_directory",
"本地索引范围必须是目录",
));
}
canonical
.strip_prefix(&root_canonical)
.map_err(|_| {
WebError::bad_request_code(
"local_index_scope_escape",
"本地索引目录必须位于当前授权 root 内",
)
})?
.to_string_lossy()
.replace('\\', "/")
} else {
normalize_index_relative_path(trimmed.trim_start_matches("./"))?
};
let normalized = if normalized.is_empty() {
".".to_string()
} else {
normalized
};
if normalized.split('/').any(|part| part == ".mnote") {
return Err(WebError::bad_request_code(
"local_index_scope_reserved",
@@ -1640,9 +1884,6 @@ fn normalize_index_include_paths(
}
output.push(normalized);
}
if output.is_empty() {
output.push(".".to_string());
}
Ok(normalized_indexed_paths(&output))
}
@@ -1884,6 +2125,27 @@ fn write_local_search_index_json(
})
}
fn clear_local_search_index(root_path: &Path) -> Result<(), WebError> {
let index_path = root_path
.join(".mnote")
.join("index")
.join("search-index.json");
let evidence_path = evidence_sqlite_path(root_path);
for path in [index_path, evidence_path] {
match fs::remove_file(&path) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(WebError::bad_request_code(
"local_search_index_delete_failed",
format!("无法删除本地搜索索引文件 {}: {error}", path.display()),
));
}
}
}
Ok(())
}
fn ensure_evidence_sqlite_index(
root_path: &Path,
index: &LocalSearchIndex,
@@ -3151,6 +3413,72 @@ fn count_evidence_blocks(path: &Path) -> Result<u64, WebError> {
.map_err(sqlite_error)
}
#[derive(Debug, Clone, Default)]
pub(crate) struct LocalEvidenceSourceStatuses {
pub(crate) indexed_paths: BTreeSet<String>,
pub(crate) failed_paths: BTreeSet<String>,
}
pub(crate) fn local_evidence_source_statuses(
root_path: &Path,
) -> Result<LocalEvidenceSourceStatuses, WebError> {
let mut statuses = LocalEvidenceSourceStatuses::default();
let evidence_path = evidence_sqlite_path(root_path);
if evidence_path.exists() {
let connection = Connection::open(&evidence_path).map_err(|error| {
WebError::bad_request_code(
"evidence_index_open_failed",
format!(
"无法打开 evidence 索引 {}: {error}",
evidence_path.display()
),
)
})?;
let mut statement = connection
.prepare(
"SELECT DISTINCT source_root_relative_path \
FROM evidence_resource \
WHERE provider NOT IN ('resource', 'markdown')",
)
.map_err(sqlite_error)?;
let rows = statement
.query_map([], |row| row.get::<_, String>(0))
.map_err(sqlite_error)?;
for row in rows {
if let Ok(path) = row {
if !path.trim().is_empty() {
statuses.indexed_paths.insert(path);
}
}
}
}
if let Some(index) = read_local_search_index(root_path)? {
for resource in index.resources {
if matches!(resource.resource_type.as_str(), "pdf" | "office")
&& !statuses.indexed_paths.contains(&resource.path)
{
statuses.failed_paths.insert(resource.path);
}
}
}
for entry in local_ocr::ocr_index_entries(root_path)? {
match entry.status.as_str() {
"done" => {
statuses
.indexed_paths
.insert(entry.source_root_relative_path);
}
"failed" | "interrupted" => {
statuses
.failed_paths
.insert(entry.source_root_relative_path);
}
_ => {}
}
}
Ok(statuses)
}
fn evidence_resource_kind_for_type(resource_type: &str) -> &'static str {
match resource_type {
"mindmap" => "mindmap",
@@ -3179,6 +3507,14 @@ fn evidence_resource_kind_for_path(path: &str) -> &'static str {
}
}
fn local_resource_path_from_document_id(document_id: &str) -> Option<String> {
document_id
.trim()
.strip_prefix("local-resource:")
.map(|value| value.replace("~2F", "/").replace("~2f", "/"))
.filter(|value| !value.trim().is_empty())
}
fn path_source_map_path(path: &str) -> Option<String> {
if let Some(stripped) = path.strip_suffix(".ocr.md") {
return Some(format!("{stripped}.source-map.json"));
@@ -3267,9 +3603,9 @@ fn local_search_document_matches(
))
};
if exact {
haystack == query
} else {
haystack.contains(query)
} else {
fuzzy_search_match(&haystack, query)
}
}
@@ -3291,9 +3627,9 @@ fn local_search_resource_matches(
))
};
if exact {
haystack == query
} else {
haystack.contains(query)
} else {
fuzzy_search_match(&haystack, query)
}
}
@@ -3319,9 +3655,9 @@ fn local_search_ocr_matches(
))
};
if exact {
haystack == query
} else {
haystack.contains(query)
} else {
fuzzy_search_match(&haystack, query)
}
}
@@ -3330,6 +3666,7 @@ fn local_search_document_projection(
root_uri: &str,
query: &str,
) -> Value {
let hit = search_document_hit(document, query);
json!({
"id": document.document_id,
"documentId": document.document_id,
@@ -3338,7 +3675,12 @@ fn local_search_document_projection(
"resourceType": "markdown",
"sourceKind": "local_folder",
"rootUri": root_uri,
"snippet": search_snippet(document, query),
"snippet": hit.snippet,
"blockId": hit.block_id,
"lineRange": {
"start": hit.line_number,
"end": hit.line_number,
},
"tags": document.tags,
"backlinks": document.backlinks,
"resourceRefs": document.resource_refs,
@@ -3548,16 +3890,43 @@ fn is_local_resource_reference(target: &str) -> bool {
}
fn search_snippet(document: &LocalSearchDocument, query: &str) -> String {
for line in document.raw_text.lines() {
search_document_hit(document, query).snippet
}
#[derive(Debug, Clone)]
struct SearchDocumentHit {
snippet: String,
line_number: usize,
block_id: String,
}
fn search_document_hit(document: &LocalSearchDocument, query: &str) -> SearchDocumentHit {
for (line_index, line) in document.raw_text.lines().enumerate() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if normalize_search_text(trimmed).contains(query) {
return trimmed.chars().take(180).collect();
let line_number = line_index + 1;
return SearchDocumentHit {
snippet: trimmed.chars().take(180).collect(),
line_number,
block_id: format!("{}#line{}", document.document_id, line_number),
};
}
}
document.raw_text.chars().take(180).collect()
let line_number = document
.raw_text
.lines()
.enumerate()
.find(|(_, line)| !line.trim().is_empty())
.map(|(line_index, _)| line_index + 1)
.unwrap_or(1);
SearchDocumentHit {
snippet: document.raw_text.chars().take(180).collect(),
line_number,
block_id: format!("{}#line{}", document.document_id, line_number),
}
}
fn ocr_search_snippet(body: &str, query: &str) -> String {
@@ -3576,11 +3945,73 @@ fn ocr_search_snippet(body: &str, query: &str) -> String {
.map(|(idx, _)| idx)
.unwrap_or(0);
normalized_body[start..].chars().take(160).collect()
} else if let Some(byte_index) = fuzzy_search_start_byte(&normalized_body, normalized_query) {
let start = normalized_body[..byte_index]
.char_indices()
.rev()
.nth(40)
.map(|(idx, _)| idx)
.unwrap_or(0);
normalized_body[start..].chars().take(180).collect()
} else {
normalized_body.chars().take(160).collect()
}
}
fn fuzzy_search_match(haystack: &str, query: &str) -> bool {
if query.is_empty() {
return false;
}
if haystack.contains(query) {
return true;
}
let mut query_chars = query.chars().filter(|ch| !ch.is_whitespace());
let Some(mut wanted) = query_chars.next() else {
return false;
};
for ch in haystack.chars().filter(|ch| !ch.is_whitespace()) {
if ch == wanted {
match query_chars.next() {
Some(next) => wanted = next,
None => return true,
}
}
}
false
}
fn fuzzy_search_start_byte(haystack: &str, query: &str) -> Option<usize> {
if query.is_empty() {
return None;
}
let query_chars = query
.chars()
.filter(|ch| !ch.is_whitespace())
.collect::<Vec<_>>();
if query_chars.is_empty() {
return None;
}
let haystack_chars = haystack.char_indices().collect::<Vec<_>>();
for (start_index, (byte_index, ch)) in haystack_chars.iter().enumerate() {
if ch != &query_chars[0] {
continue;
}
let mut query_index = 1usize;
for (_, next_ch) in haystack_chars.iter().skip(start_index + 1) {
if next_ch.is_whitespace() {
continue;
}
if query_index < query_chars.len() && next_ch == &query_chars[query_index] {
query_index += 1;
if query_index >= query_chars.len() {
return Some(*byte_index);
}
}
}
}
None
}
fn is_markdown_path(path: &Path) -> bool {
path.extension()
.and_then(|value| value.to_str())
@@ -3905,6 +4336,89 @@ mod tests {
let _ = fs::remove_dir_all(&root);
}
#[test]
fn local_index_settings_accepts_absolute_path_under_root_as_frozen_scope() {
let root = temp_root("mnote-local-index-settings-absolute");
fs::create_dir_all(root.join("docs").join("absolute")).expect("create absolute dir");
let absolute_scope = root.join("docs").join("absolute");
let settings = write_local_index_settings(
&root,
&[absolute_scope.to_string_lossy().to_string()],
None,
None,
None,
None,
)
.expect("absolute scope under root");
assert_eq!(settings.include_paths, vec![String::from("docs/absolute")]);
let _ = fs::remove_dir_all(&root);
}
#[test]
fn user_local_index_empty_scope_deletes_index_files() {
let root = temp_root("mnote-local-index-empty-delete");
fs::write(
root.join("docs").join("keep.md"),
"# Keep\nDeleteIndexToken\n",
)
.expect("write doc");
let root_uri = format!("file://{}", root.display());
let workspace_id = "local-ws-empty-delete";
let store = SqliteControlPlaneStore::in_memory().expect("init control plane");
write_user_local_index_settings(
&store,
"alice",
workspace_id,
&root,
&[String::from("docs")],
Some("manual"),
Some("02:00"),
None,
Some(false),
)
.expect("write indexed scope");
let effective = effective_local_index_settings_for_root(&store, workspace_id, &root)
.expect("effective indexed");
refresh_local_search_index_with_settings(&root, &root_uri, workspace_id, &effective)
.expect("refresh indexed");
assert!(root.join(".mnote/index/search-index.json").exists());
assert!(root.join(".mnote/index/evidence.sqlite").exists());
write_user_local_index_settings(
&store,
"alice",
workspace_id,
&root,
&[],
Some("manual"),
Some("02:00"),
None,
Some(false),
)
.expect("delete indexed scopes");
let empty_effective = effective_local_index_settings_for_root(&store, workspace_id, &root)
.expect("effective empty");
assert!(empty_effective.include_paths.is_empty());
refresh_local_search_index_with_settings(&root, &root_uri, workspace_id, &empty_effective)
.expect("clear index files");
assert!(!root.join(".mnote/index/search-index.json").exists());
assert!(!root.join(".mnote/index/evidence.sqlite").exists());
let status = local_index_status_with_settings(
&root,
&root_uri,
workspace_id,
&empty_effective,
&empty_effective,
)
.expect("status");
assert_eq!(status["cacheMatchesSettings"].as_bool(), Some(true));
let _ = fs::remove_dir_all(&root);
}
#[test]
fn local_index_settings_rejects_escape_and_internal_cache_scope() {
let root = temp_root("mnote-local-index-settings-escape");
@@ -3949,6 +4463,14 @@ mod tests {
initial_status["settings"]["runOnChange"].as_bool(),
Some(false)
);
assert_eq!(
initial_status["settings"]["includePaths"]
.as_array()
.map(Vec::len),
Some(0),
"默认不应索引工作区根目录;用户新增范围后才开始索引"
);
assert_eq!(initial_status["cacheMatchesSettings"].as_bool(), Some(true));
let settings = write_local_index_settings(
&root,
@@ -4356,6 +4878,8 @@ mod tests {
)
.expect("write child");
write_local_index_settings(&root, &[String::from(".")], None, None, None, None)
.expect("settings");
refresh_local_search_index(&root, &root_uri, workspace_id).expect("initial refresh");
fs::write(
root.join("docs").join("child.md"),
@@ -4643,6 +5167,8 @@ mod tests {
)
.expect("write child");
write_local_index_settings(&root, &[String::from(".")], None, None, None, None)
.expect("settings");
refresh_local_search_index(&root, &root_uri, workspace_id).expect("refresh");
let results = query_evidence_sqlite_results(&root, "EvidenceToken", None, 10)
@@ -4750,6 +5276,8 @@ mod tests {
)
.expect("write home");
write_local_index_settings(&root, &[String::from(".")], None, None, None, None)
.expect("settings");
refresh_local_search_index(&root, &root_uri, workspace_id).expect("refresh");
let results = query_evidence_sqlite_results(&root, "ReadContextToken", None, 10)
.expect("sqlite query")
@@ -4821,6 +5349,8 @@ JSON
let old_bin = std::env::var("MNOTE_LITEPARSE_BIN").ok();
std::env::set_var("MNOTE_LITEPARSE_BIN", &lit);
write_local_index_settings(&root, &[String::from(".")], None, None, None, None)
.expect("settings");
refresh_local_search_index(&root, &root_uri, workspace_id).expect("refresh");
if let Some(value) = old_bin {
@@ -4850,6 +5380,21 @@ JSON
hit.source.source_map_path.as_deref(),
Some("docs/Page.ocr/spec.pdf.source-map.json")
);
let resource_scoped = query_evidence_sqlite_results_with_mode(
&root,
"ResourceBodyToken",
Some("local-resource:docs~2FPage.assets~2Fspec.pdf"),
10,
true,
)
.expect("resource scoped sqlite query")
.expect("sqlite exists");
assert_eq!(resource_scoped.len(), 1);
assert_eq!(
resource_scoped[0].source.resource_path.as_deref(),
Some("docs/Page.assets/spec.pdf"),
"页面内搜索打开资源时应只限制到当前资源,而不是它的 owner Markdown"
);
assert!(root
.join("docs")
.join("Page.ocr")
+14 -1
View File
@@ -37,16 +37,21 @@ pub(crate) mod ui_preferences;
pub(crate) mod web_shell;
mod ws;
pub(crate) use gateway::current_actor_id;
pub(crate) use local_folder_source::{
decode_local_id_segment, ensure_local_path_read_access, ensure_local_workspace_access,
ensure_local_workspace_read_access_with_state, ensure_local_workspace_write_access_with_state,
local_markdown_conflict_detection_key, local_workspace_id_from_root_uri,
update_local_markdown_title, write_local_markdown_page_body,
};
#[cfg(test)]
pub(crate) use local_search_index::write_local_index_settings;
pub(crate) use local_search_index::{
refresh_local_search_index_for_change_path_with_store,
effective_local_index_settings_for_root, local_index_status_with_settings,
preview_user_local_index_settings, read_local_index_settings_or_default,
read_user_local_index_settings, refresh_local_search_index_for_change_path_with_store,
refresh_local_search_index_if_scheduled_due_with_store,
refresh_local_search_index_with_settings, write_user_local_index_settings, LocalIndexSettings,
};
use crate::app::AppState;
@@ -641,6 +646,14 @@ pub fn build_router(state: AppState) -> Router {
)
.route("/client/skills", get(hermes_client::list_skills))
.route("/client/skills/toggle", put(hermes_client::toggle_skill))
.route(
"/client/capabilities",
get(hermes_client::list_capabilities),
)
.route(
"/client/capabilities/toggle",
put(hermes_client::toggle_capability),
)
.route("/client/tools/toggle", put(hermes_client::toggle_tool))
.route("/client/runs", post(hermes_client::create_run))
.route(
+302
View File
@@ -229,6 +229,25 @@ pub async fn documents(
EvidenceSearchMode::Hybrid,
&normalized_query,
);
let limit = body.limit.unwrap_or(30).max(1) as usize;
let direct_evidence_results = if !filters.title_only.unwrap_or(false) {
local_search_index::query_evidence_sqlite_results_with_mode(
&root_path,
&normalized_query,
page_id.as_deref(),
body.limit.unwrap_or(30),
filters.exact.unwrap_or(false),
)?
.unwrap_or_default()
} else {
Vec::new()
};
let (result, evidence_results) = merge_local_search_with_evidence_results(
result,
evidence_results,
direct_evidence_results,
limit,
);
(result, evidence_results)
} else {
let result = load_search_results_with_filters(
@@ -419,6 +438,12 @@ pub async fn update_local_index_settings(
&effective_workspace_id,
&root_path,
)?;
let refreshed = local_search_index::refresh_local_search_index_with_settings(
&root_path,
root_uri,
&effective_workspace_id,
&effective_settings,
)?;
let status = local_search_index::local_index_status_with_settings(
&root_path,
root_uri,
@@ -434,6 +459,7 @@ pub async fn update_local_index_settings(
Json(json!({
"ok": true,
"settings": settings,
"index": refreshed,
"result": status,
"meta": {
"owner": "mnote-web",
@@ -446,6 +472,75 @@ pub async fn update_local_index_settings(
))
}
fn merge_local_search_with_evidence_results(
mut result: Value,
mut evidence_results: Vec<EvidenceSearchResult>,
direct_evidence_results: Vec<EvidenceSearchResult>,
limit: usize,
) -> (Value, Vec<EvidenceSearchResult>) {
if direct_evidence_results.is_empty() {
return (result, evidence_results);
}
let mut result_items = result
.get("results")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let mut seen_evidence_ids = evidence_results
.iter()
.map(|item| item.evidence_id.clone())
.collect::<std::collections::HashSet<_>>();
for evidence in direct_evidence_results {
if result_items.len() >= limit || !seen_evidence_ids.insert(evidence.evidence_id.clone()) {
continue;
}
result_items.push(search_result_from_evidence(&evidence));
evidence_results.push(evidence);
}
if let Some(map) = result.as_object_mut() {
map.insert("results".into(), Value::Array(result_items));
}
(result, evidence_results)
}
fn search_result_from_evidence(evidence: &EvidenceSearchResult) -> Value {
let source = &evidence.source;
let evidence_value = serde_json::to_value(evidence).unwrap_or(Value::Null);
let resource_path = source
.resource_path
.as_deref()
.unwrap_or(source.owner_document_path.as_str());
let title = std::path::Path::new(resource_path)
.file_name()
.and_then(|value| value.to_str())
.unwrap_or(resource_path)
.to_string();
let resource_type = match source.resource_kind {
core_protocol::EvidenceResourceKind::Markdown => "markdown",
core_protocol::EvidenceResourceKind::Pdf => "pdf",
core_protocol::EvidenceResourceKind::Image => "image",
core_protocol::EvidenceResourceKind::Office => "office",
core_protocol::EvidenceResourceKind::Mindmap => "mindmap",
core_protocol::EvidenceResourceKind::RawFile => "resource",
};
json!({
"id": format!("evidence:{}", evidence.evidence_id),
"documentId": source.owner_document_id,
"title": title,
"path": source.owner_document_path,
"resourceType": resource_type,
"sourceKind": "local_folder",
"rootUri": source.root_uri,
"snippet": evidence.quote,
"score": evidence.score,
"publicPath": source.open_action.url,
"evidence": evidence_value,
"source": {
"locator": source
},
})
}
fn attach_evidence_to_search_results(
results: Value,
evidence_results: &[EvidenceSearchResult],
@@ -463,6 +558,9 @@ fn attach_evidence_to_search_results(
};
let mut item = item;
if let Some(map) = item.as_object_mut() {
if map.get("evidence").is_some() {
return item;
}
let evidence_value = serde_json::to_value(evidence).unwrap_or(Value::Null);
map.insert("evidence".into(), evidence_value);
let source = map.entry("source").or_insert_with(|| json!({}));
@@ -793,6 +891,7 @@ fn stamp_search_headers(headers: &mut HeaderMap) {
#[cfg(test)]
mod tests {
use crate::app::{build_app, AppConfig, AppState};
use crate::routes::local_search_index;
use axum::body::{to_bytes, Body};
use axum::http::{Request, StatusCode};
use control_plane::{DirectoryGrantInput, UpsertUserInput};
@@ -998,6 +1097,15 @@ mod tests {
.expect("readme");
fs::write(root.join("docs").join("child.md"), "# Child\nalpha child\n").expect("child");
let root_uri = format!("file://{}", root.display());
local_search_index::write_local_index_settings(
&root,
&[String::from(".")],
None,
None,
None,
None,
)
.expect("settings");
let response = app()
.oneshot(
@@ -1102,6 +1210,104 @@ mod tests {
let _ = fs::remove_dir_all(&root);
}
#[tokio::test]
async fn search_documents_local_folder_includes_evidence_sqlite_body_hits() {
let root = std::env::temp_dir().join(format!(
"mnote-local-search-evidence-route-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(root.join(".mnote")).expect("metadata");
fs::write(
root.join(".mnote").join("workspace.json"),
r#"{"workspaceId":"local-ws-search-evidence","ownerId":"user_test","createdAt":"2026-05-19T00:00:00Z","capabilities":["local_files"]}"#,
)
.expect("manifest");
fs::write(
root.join("README.md"),
"# Search Home\nBodyOnlyEvidenceToken only exists inside evidence.sqlite after refresh.\n",
)
.expect("readme");
let root_uri = format!("file://{}", root.display());
local_search_index::write_local_index_settings(
&root,
&[String::from(".")],
None,
None,
None,
None,
)
.expect("settings");
local_search_index::refresh_local_search_index(
&root,
&root_uri,
"local-ws-search-evidence",
)
.expect("refresh");
fs::write(
root.join(".mnote").join("index").join("search-index.json"),
serde_json::to_string_pretty(&json!({
"version": 1,
"builtAt": 1,
"rootUri": root_uri,
"workspaceId": "local-ws-search-evidence",
"documents": [],
"resources": []
}))
.expect("stale search index"),
)
.expect("overwrite search index");
let response = app()
.oneshot(
Request::builder()
.method("POST")
.uri("/api/search/documents")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_test")
.header("x-mnote-actor-type", "user")
.body(Body::from(
json!({
"workspaceId": "local-ws-search-evidence",
"sourceKind": "local_folder",
"rootUri": root_uri,
"query": "BodyOnlyEvidenceToken",
"limit": 10,
"filters": {
"titleOnly": false,
"includeOcr": true
}
})
.to_string(),
))
.expect("request"),
)
.await
.expect("response");
assert_eq!(response.status(), StatusCode::OK);
let body = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let payload: Value = serde_json::from_slice(&body).expect("json");
let results = payload["results"].as_array().expect("results");
let hit = results
.iter()
.find(|item| {
item["snippet"]
.as_str()
.unwrap_or("")
.contains("BodyOnlyEvidenceToken")
})
.expect("evidence sqlite body hit should be promoted to search result");
assert_eq!(hit["resourceType"].as_str(), Some("markdown"));
assert_eq!(
hit["evidence"]["source"]["schema"].as_str(),
Some("mnote.evidence_locator.v1")
);
let _ = fs::remove_dir_all(&root);
}
#[tokio::test]
async fn search_local_index_refresh_rebuilds_authorized_root() {
let root = std::env::temp_dir().join(format!(
@@ -1156,6 +1362,102 @@ mod tests {
let _ = fs::remove_dir_all(&root);
}
#[tokio::test]
async fn local_index_settings_empty_scope_deletes_index_files() {
let root = std::env::temp_dir().join(format!(
"mnote-local-search-settings-delete-route-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&root);
fs::create_dir_all(root.join(".mnote")).expect("metadata");
fs::create_dir_all(root.join("docs")).expect("docs");
fs::write(
root.join(".mnote").join("workspace.json"),
r#"{"workspaceId":"local-ws-settings-delete","ownerId":"user_test","createdAt":"2026-05-19T00:00:00Z","capabilities":["local_files","search"]}"#,
)
.expect("manifest");
fs::write(
root.join("docs").join("keep.md"),
"# Keep\nRouteDeleteToken\n",
)
.expect("doc");
let root_uri = format!("file://{}", root.display());
let app = app();
let create_response = app
.clone()
.oneshot(
Request::builder()
.method("PUT")
.uri("/api/search/local-index/settings")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_test")
.header("x-mnote-actor-type", "user")
.body(Body::from(
json!({
"workspaceId": "local-ws-settings-delete",
"rootUri": root_uri,
"includePaths": ["docs"],
"scheduleMode": "manual",
"scheduleTime": "02:00",
"runOnChange": false
})
.to_string(),
))
.expect("create settings request"),
)
.await
.expect("create settings response");
assert_eq!(create_response.status(), StatusCode::OK);
assert!(root.join(".mnote/index/search-index.json").exists());
assert!(root.join(".mnote/index/evidence.sqlite").exists());
let delete_response = app
.oneshot(
Request::builder()
.method("PUT")
.uri("/api/search/local-index/settings")
.header("content-type", "application/json")
.header("x-mnote-actor-id", "user_test")
.header("x-mnote-actor-type", "user")
.body(Body::from(
json!({
"workspaceId": "local-ws-settings-delete",
"rootUri": root_uri,
"includePaths": [],
"scheduleMode": "manual",
"scheduleTime": "02:00",
"runOnChange": false
})
.to_string(),
))
.expect("delete settings request"),
)
.await
.expect("delete settings response");
assert_eq!(delete_response.status(), StatusCode::OK);
let delete_body = to_bytes(delete_response.into_body(), usize::MAX)
.await
.expect("delete body");
let delete_payload: Value = serde_json::from_slice(&delete_body).expect("delete json");
assert_eq!(
delete_payload["index"]["indexedPaths"]
.as_array()
.map(Vec::len),
Some(0)
);
assert_eq!(
delete_payload["result"]["settings"]["includePaths"]
.as_array()
.map(Vec::len),
Some(0)
);
assert!(!root.join(".mnote/index/search-index.json").exists());
assert!(!root.join(".mnote/index/evidence.sqlite").exists());
let _ = fs::remove_dir_all(&root);
}
#[tokio::test]
async fn search_local_index_backlinks_and_tags_read_authorized_root() {
let root = std::env::temp_dir().join(format!(
+11
View File
@@ -660,6 +660,17 @@ pub(crate) fn collect_filetree_render_rows(
object_identity: resource_meta
.and_then(|meta| meta.get("objectIdentity"))
.and_then(|value| serde_json::to_string(value).ok()),
index_status: item
.get("indexStatus")
.and_then(Value::as_str)
.or_else(|| {
resource_meta
.and_then(|meta| meta.get("indexStatus"))
.and_then(Value::as_str)
})
.map(str::trim)
.filter(|value| *value == "indexed" || *value == "failed")
.map(ToOwned::to_owned),
selected,
})
})
+330 -1
View File
@@ -986,6 +986,14 @@ pub struct OfficePreviewQuery {
source_kind: Option<String>,
root_uri: Option<String>,
document_id: Option<String>,
#[serde(default)]
page: Option<u32>,
#[serde(default)]
bbox: Option<String>,
#[serde(default, alias = "sourceMapPath")]
source_map_path: Option<String>,
#[serde(default, alias = "blockId")]
block_id: Option<String>,
}
pub async fn office_preview_page(Query(query): Query<OfficePreviewQuery>) -> Response {
@@ -1013,6 +1021,13 @@ pub async fn office_preview_page(Query(query): Query<OfficePreviewQuery>) -> Res
let source_kind = query.source_kind.unwrap_or_default();
let root_uri = query.root_uri.unwrap_or_default();
let document_id = query.document_id.unwrap_or_default();
let target_page = query
.page
.map(|value| value.to_string())
.unwrap_or_default();
let target_bbox = query.bbox.unwrap_or_default();
let target_source_map_path = query.source_map_path.unwrap_or_default();
let target_block_id = query.block_id.unwrap_or_default();
let html = format!(
r#"<!doctype html>
<html lang="zh-CN">
@@ -1047,6 +1062,10 @@ pub async fn office_preview_page(Query(query): Query<OfficePreviewQuery>) -> Res
.mnote-office-viewer .mnote-docx-wrapper {{ width: 100%; background: transparent !important; padding: 0 !important; align-items: stretch !important; }}
.mnote-office-viewer .docx-wrapper > section.docx,
.mnote-office-viewer .mnote-docx-wrapper > section.mnote-docx {{ width: 100% !important; max-width: none !important; margin: 0 0 14px !important; box-shadow: 0 2px 10px rgba(25, 25, 22, .08); }}
.mnote-office-viewer {{ position: relative; }}
.mnote-office-viewer [data-mnote-office-evidence-target="true"] {{ outline: 0; border-radius: 2px; background: #FFE9E6; color: #D83A32; box-shadow: 0 0 0 1px rgba(216, 58, 50, .22); }}
.mnote-office-evidence-marker {{ position: absolute; z-index: 3; left: 24px; max-width: min(720px, calc(100% - 48px)); padding: 6px 10px; border: 1px solid rgba(216, 58, 50, .45); border-radius: 6px; background: rgba(255, 249, 248, .96); color: #D83A32; font-size: 13px; line-height: 1.5; box-shadow: 0 2px 10px rgba(15, 23, 42, .12); }}
.mnote-office-evidence-marker[data-mnote-office-evidence-marker-mode="range"] {{ pointer-events: none; background: rgba(255, 233, 230, .72); box-shadow: 0 0 0 1px rgba(216, 58, 50, .28); }}
.mnote-office-pptx-stage {{ width: 100%; overflow: auto; }}
.mnote-office-pptx-stage .pptx-preview-wrapper {{ max-width: 100%; background: transparent !important; }}
.mnote-office-pptx-stage .pptx-preview-slide-wrapper {{ box-shadow: 0 2px 10px rgba(25, 25, 22, .08); }}
@@ -1055,7 +1074,7 @@ pub async fn office_preview_page(Query(query): Query<OfficePreviewQuery>) -> Res
}}
</style>
</head>
<body data-file-url="{file_url}" data-file-name="{file_name}" data-file-type="{file_type}" data-page-width-content-type="{page_width_content_type}" data-workspace-id="{workspace_id}" data-mnote-source-kind="{source_kind}" data-mnote-root-uri="{root_uri}" data-document-id="{document_id}">
<body data-file-url="{file_url}" data-file-name="{file_name}" data-file-type="{file_type}" data-page-width-content-type="{page_width_content_type}" data-workspace-id="{workspace_id}" data-mnote-source-kind="{source_kind}" data-mnote-root-uri="{root_uri}" data-document-id="{document_id}" data-evidence-page="{target_page}" data-evidence-bbox="{target_bbox}" data-evidence-source-map-path="{target_source_map_path}" data-evidence-block-id="{target_block_id}">
<main class="mnote-office-preview">
<section class="mnote-office-viewer" id="mnote-office-viewer"></section>
</main>
@@ -1070,6 +1089,10 @@ pub async fn office_preview_page(Query(query): Query<OfficePreviewQuery>) -> Res
const fileName = body.dataset.fileName || '';
const fileType = (body.dataset.fileType || '').toLowerCase();
const pageWidthContentType = body.dataset.pageWidthContentType || 'word';
let evidencePage = Number(body.dataset.evidencePage || 0);
let evidenceBbox = body.dataset.evidenceBbox || '';
let evidenceSourceMapPath = body.dataset.evidenceSourceMapPath || '';
let evidenceBlockId = body.dataset.evidenceBlockId || '';
let currentPptxBuffer = null;
let pptxRenderToken = 0;
let pptxResizeTimer = 0;
@@ -1136,6 +1159,299 @@ pub async fn office_preview_page(Query(query): Query<OfficePreviewQuery>) -> Res
viewer.append(message);
}}
function normalizeEvidenceText(value) {{
return String(value || '').replace(/\s+/g, ' ').trim();
}}
function markEvidenceTarget(target) {{
if (!(target instanceof HTMLElement)) return false;
viewer.querySelectorAll('[data-mnote-office-evidence-target="true"]').forEach(node => {{
if (node instanceof HTMLElement) node.removeAttribute('data-mnote-office-evidence-target');
}});
target.setAttribute('data-mnote-office-evidence-target', 'true');
window.setTimeout(() => target.scrollIntoView({{ block: 'center', inline: 'nearest' }}), 0);
document.documentElement.setAttribute('data-mnote-office-evidence-applied', 'true');
return true;
}}
function normalizedTextWithRawOffsets(value) {{
const raw = String(value || '');
let text = '';
const offsets = [];
let previousWhitespace = true;
for (let index = 0; index < raw.length; index += 1) {{
const ch = raw[index];
if (/\s/.test(ch)) {{
if (text && !previousWhitespace) {{
text += ' ';
offsets.push(index);
}}
previousWhitespace = true;
}} else {{
text += ch;
offsets.push(index);
previousWhitespace = false;
}}
}}
if (text.endsWith(' ')) {{
text = text.slice(0, -1);
offsets.pop();
}}
return {{ text, offsets }};
}}
function compactTextWithRawOffsets(value) {{
const raw = String(value || '');
let text = '';
const offsets = [];
for (let index = 0; index < raw.length; index += 1) {{
const ch = raw[index];
if (/\s/.test(ch)) continue;
text += ch;
offsets.push(index);
}}
return {{ text, offsets }};
}}
function wrapEvidenceTextNode(node, needle) {{
if (!(node instanceof Text)) return null;
const raw = String(node.textContent || '');
let start = raw.indexOf(needle);
let end = start >= 0 ? start + needle.length : -1;
if (start < 0) {{
const compact = compactTextWithRawOffsets(raw);
const compactNeedle = normalizeEvidenceText(needle).replace(/\s+/g, '');
let normalizedStart = compact.text.indexOf(compactNeedle);
let sourceOffsets = compact.offsets;
if (normalizedStart < 0) {{
const mapped = normalizedTextWithRawOffsets(raw);
const mappedNeedle = normalizeEvidenceText(needle);
normalizedStart = mapped.text.indexOf(mappedNeedle);
sourceOffsets = mapped.offsets;
if (normalizedStart < 0) return null;
start = sourceOffsets[normalizedStart];
end = sourceOffsets[normalizedStart + mappedNeedle.length - 1] + 1;
if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end <= start) return null;
const range = document.createRange();
range.setStart(node, start);
range.setEnd(node, end);
const span = document.createElement('span');
span.setAttribute('data-mnote-office-evidence-target', 'true');
try {{
range.surroundContents(span);
return span;
}} catch (_) {{
return null;
}}
}}
if (normalizedStart < 0) return null;
start = sourceOffsets[normalizedStart];
end = sourceOffsets[normalizedStart + compactNeedle.length - 1] + 1;
}}
if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end <= start) return null;
const range = document.createRange();
range.setStart(node, start);
range.setEnd(node, end);
const span = document.createElement('span');
span.setAttribute('data-mnote-office-evidence-target', 'true');
try {{
range.surroundContents(span);
return span;
}} catch (_) {{
return null;
}}
}}
function markEvidenceRangeAcrossTextNodes(needle) {{
if (!viewer) return false;
const compactNeedle = normalizeEvidenceText(needle).replace(/\s+/g, '');
if (!compactNeedle) return false;
const refs = [];
let compactText = '';
const walker = document.createTreeWalker(viewer, NodeFilter.SHOW_TEXT);
let node = walker.nextNode();
while (node) {{
const raw = String(node.textContent || '');
for (let offset = 0; offset < raw.length; offset += 1) {{
const ch = raw[offset];
if (/\s/.test(ch)) continue;
compactText += ch;
refs.push({{ node, offset }});
}}
node = walker.nextNode();
}}
const startIndex = compactText.indexOf(compactNeedle);
if (startIndex < 0) return false;
const endIndex = startIndex + compactNeedle.length - 1;
const startRef = refs[startIndex];
const endRef = refs[endIndex];
if (!startRef || !endRef) return false;
const range = document.createRange();
range.setStart(startRef.node, startRef.offset);
range.setEnd(endRef.node, endRef.offset + 1);
const rect = range.getBoundingClientRect();
if (!rect || rect.width <= 0 || rect.height <= 0) return false;
let marker = viewer.querySelector('[data-mnote-office-evidence-marker="true"]');
if (!(marker instanceof HTMLElement)) {{
marker = document.createElement('div');
marker.className = 'mnote-office-evidence-marker';
marker.setAttribute('data-mnote-office-evidence-marker', 'true');
viewer.append(marker);
}}
const viewerRect = viewer.getBoundingClientRect();
marker.textContent = '';
marker.setAttribute('data-mnote-office-evidence-target-text', normalizeEvidenceText(needle));
marker.setAttribute('data-mnote-office-evidence-marker-mode', 'range');
marker.style.left = Math.max(0, Math.round(rect.left - viewerRect.left + viewer.scrollLeft)).toString() + 'px';
marker.style.top = Math.max(0, Math.round(rect.top - viewerRect.top + viewer.scrollTop)).toString() + 'px';
marker.style.width = Math.max(8, Math.round(rect.width)).toString() + 'px';
marker.style.height = Math.max(8, Math.round(rect.height)).toString() + 'px';
marker.style.maxWidth = 'none';
marker.style.padding = '0';
return markEvidenceTarget(marker);
}}
function pageForEvidenceBlock(sourceMap, block) {{
if (!sourceMap || typeof sourceMap !== 'object' || !block) return null;
const pages = Array.isArray(sourceMap.pages) ? sourceMap.pages : [];
for (const page of pages) {{
const blocks = Array.isArray(page && page.blocks) ? page.blocks : [];
if (blocks.includes(block)) return page;
}}
return null;
}}
function findEvidenceBlockInSourceMap(sourceMap) {{
if (!sourceMap || typeof sourceMap !== 'object' || !evidenceBlockId) return null;
const pages = Array.isArray(sourceMap.pages) ? sourceMap.pages : [];
for (const page of pages) {{
const blocks = Array.isArray(page && page.blocks) ? page.blocks : [];
const block = blocks.find(item => String(item && (item.id || item.blockId || item.block_id) || '') === evidenceBlockId);
if (block) return block;
}}
return null;
}}
async function fetchEvidenceSourceMap() {{
if (!evidenceSourceMapPath || !body.dataset.mnoteRootUri) return null;
const params = new URLSearchParams();
params.set('rootUri', body.dataset.mnoteRootUri);
params.set('path', evidenceSourceMapPath);
const response = await fetch('/api/local-folder/files/open?' + params.toString(), {{
credentials: 'same-origin',
headers: {{ accept: 'application/json, text/plain, */*' }}
}});
if (!response.ok) return null;
return response.json().catch(() => null);
}}
function scrollToEvidenceText(text) {{
const needle = normalizeEvidenceText(text);
if (!needle || !viewer) return false;
viewer.querySelectorAll('[data-mnote-office-evidence-target="true"]').forEach(node => {{
if (node instanceof HTMLElement) {{
if (node.tagName === 'SPAN' && node.childNodes.length === 1 && node.firstChild instanceof Text) {{
node.replaceWith(node.firstChild);
}} else {{
node.removeAttribute('data-mnote-office-evidence-target');
}}
}}
}});
const walker = document.createTreeWalker(viewer, NodeFilter.SHOW_TEXT);
let node = walker.nextNode();
while (node) {{
if (normalizeEvidenceText(node.textContent).includes(needle)) {{
const inlineTarget = wrapEvidenceTextNode(node, needle);
if (inlineTarget) return markEvidenceTarget(inlineTarget);
const target = node.parentElement && node.parentElement.closest('p, div, span, table, section') || node.parentElement;
if (target instanceof HTMLElement) {{
const rect = target.getBoundingClientRect();
if (rect.height > window.innerHeight * 1.8 || normalizeEvidenceText(target.textContent).length > 4000) break;
}}
return markEvidenceTarget(target);
}}
node = walker.nextNode();
}}
if (markEvidenceRangeAcrossTextNodes(needle)) return true;
return false;
}}
function scrollToEvidenceCoordinate(sourceMap, block) {{
if (!viewer || !sourceMap || !block) return false;
const page = pageForEvidenceBlock(sourceMap, block);
const bbox = block.bbox && typeof block.bbox === 'object' ? block.bbox : null;
const pageNumber = Number(page && page.page || evidencePage || 0);
const pageCount = Math.max(1, Number(sourceMap.pageCount || (Array.isArray(sourceMap.pages) ? sourceMap.pages.length : 0)) || 1);
if (!Number.isFinite(pageNumber) || pageNumber <= 0) return false;
const renderedPages = Array.from(viewer.querySelectorAll('section.docx, section.mnote-docx, .pptx-preview-slide-wrapper'))
.filter(node => node instanceof HTMLElement);
const pageElement = renderedPages[pageNumber - 1];
let top = 0;
if (pageElement instanceof HTMLElement) {{
const pageHeight = Math.max(1, pageElement.scrollHeight || pageElement.getBoundingClientRect().height || 1);
const sourcePageHeight = Math.max(1, Number(page && page.height || 0) || pageHeight);
top = pageElement.offsetTop + (bbox ? (Number(bbox.y0) / sourcePageHeight) * pageHeight : pageHeight / 2);
}} else {{
const contentHeight = Math.max(1, viewer.scrollHeight || document.documentElement.scrollHeight || 1);
const estimatedPageHeight = contentHeight / pageCount;
const sourcePageHeight = Math.max(1, Number(page && page.height || 0) || estimatedPageHeight);
top = estimatedPageHeight * (pageNumber - 1) + (bbox ? (Number(bbox.y0) / sourcePageHeight) * estimatedPageHeight : estimatedPageHeight / 2);
}}
let marker = viewer.querySelector('[data-mnote-office-evidence-marker="true"]');
if (!(marker instanceof HTMLElement)) {{
marker = document.createElement('div');
marker.className = 'mnote-office-evidence-marker';
marker.setAttribute('data-mnote-office-evidence-marker', 'true');
viewer.append(marker);
}}
marker.textContent = normalizeEvidenceText(block.text || evidenceBlockId || '');
marker.removeAttribute('data-mnote-office-evidence-target-text');
marker.setAttribute('data-mnote-office-evidence-marker-mode', 'estimated');
marker.style.width = '';
marker.style.height = '';
marker.style.padding = '';
marker.style.top = Math.max(0, Math.round(top)).toString() + 'px';
return markEvidenceTarget(marker);
}}
function scrollToEvidencePageFallback() {{
if (!viewer || !Number.isFinite(evidencePage) || evidencePage <= 0) return false;
const pages = Array.from(viewer.querySelectorAll('section.docx, section.mnote-docx, .pptx-preview-slide-wrapper'));
const target = pages[Math.max(0, Math.min(pages.length - 1, evidencePage - 1))];
return markEvidenceTarget(target);
}}
async function applyEvidenceLocator() {{
if (!viewer || (!evidencePage && !evidenceBlockId && !evidenceBbox)) return;
try {{
const sourceMap = await fetchEvidenceSourceMap();
const block = findEvidenceBlockInSourceMap(sourceMap);
if (block && scrollToEvidenceText(block.text)) return;
if (scrollToEvidenceCoordinate(sourceMap, block)) return;
}} catch (_) {{}}
scrollToEvidencePageFallback();
}}
function updateEvidenceLocator(locator) {{
const next = locator && typeof locator === 'object' ? locator : {{}};
evidencePage = Number(next.page || 0);
evidenceBbox = String(next.bbox || '');
evidenceSourceMapPath = String(next.sourceMapPath || '');
evidenceBlockId = String(next.blockId || '');
body.dataset.evidencePage = evidencePage ? String(evidencePage) : '';
body.dataset.evidenceBbox = evidenceBbox;
body.dataset.evidenceSourceMapPath = evidenceSourceMapPath;
body.dataset.evidenceBlockId = evidenceBlockId;
document.documentElement.removeAttribute('data-mnote-office-evidence-applied');
void applyEvidenceLocator();
}}
window.addEventListener('message', (event) => {{
if (event.origin !== window.location.origin) return;
const data = event.data && typeof event.data === 'object' ? event.data : {{}};
if (data.type === 'mnote:office-evidence-locator') updateEvidenceLocator(data);
}});
async function fetchArrayBuffer() {{
const response = await fetch(fileUrl, {{ credentials: fileUrl.startsWith('/') ? 'same-origin' : 'include' }});
if (!response.ok) throw new Error(fileReadErrorMessage(response.status));
@@ -1321,6 +1637,7 @@ pub async fn office_preview_page(Query(query): Query<OfficePreviewQuery>) -> Res
else if (fileType === 'csv') await renderCsv();
else if (fileType === 'pptx') await renderPptx();
else showMessage(' POC .' + fileType + ' OnlyOffice ');
await applyEvidenceLocator();
setStatus('');
}} catch (error) {{
console.warn('[mnote office preview] render failed', error);
@@ -1342,6 +1659,10 @@ pub async fn office_preview_page(Query(query): Query<OfficePreviewQuery>) -> Res
source_kind = escape_html(&source_kind),
root_uri = escape_html(&root_uri),
document_id = escape_html(&document_id),
target_page = escape_html(&target_page),
target_bbox = escape_html(&target_bbox),
target_source_map_path = escape_html(&target_source_map_path),
target_block_id = escape_html(&target_block_id),
);
let mut response = Html(html).into_response();
stamp_shell_headers(response.headers_mut(), "office-preview");
@@ -3310,6 +3631,12 @@ mod tests {
let resource_runtime = DOCUMENT_RESOURCE_TAB_RUNTIME_JS;
assert!(runtime.contains("document-resource-tab-runtime.js"));
assert!(resource_runtime.contains("resourceTabBadgeKind(input, kind)"));
assert!(resource_runtime.contains("后台任务"));
assert!(resource_runtime.contains("data-mnote-local-ocr-task-tab"));
assert!(resource_runtime.contains("data-mnote-local-ocr-task-clear-completed"));
assert!(resource_runtime.contains("role=\"progressbar\""));
assert!(resource_runtime.contains("localOcrTaskCategory(job)"));
assert!(resource_runtime.contains("localOcrTaskProgress(job)"));
assert!(resource_runtime.contains("mnote.open_editors_snapshot.v1"));
assert!(runtime.contains("getOpenEditorsSnapshot"));
assert!(resource_runtime.contains("bindMainEditorTabStrip"));
@@ -3361,6 +3688,8 @@ mod tests {
assert!(resource_runtime.contains("data-mnote-evidence-bbox"));
assert!(resource_runtime.contains("data-mnote-evidence-text-highlight"));
assert!(runtime.contains("applyDocumentEvidenceLocatorFromUrl"));
assert!(runtime.contains("sourceMapPath: String(url.searchParams.get('sourceMapPath')"));
assert!(runtime.contains("blockId: String(url.searchParams.get('blockId')"));
let sidebar_runtime = SIDEBAR_TREE_RUNTIME_JS;
assert!(sidebar_runtime.contains("openEvidenceSearchResult"));
assert!(sidebar_runtime.contains("data-evidence-locator"));
+47 -7
View File
@@ -201,7 +201,7 @@ pub fn PageLayout(
{children()}
</article>
<div class="wolai-floating-actions" aria-label="浮动操作">
<button type="button" data-testid="wolai-floating-help" class="wolai-floating-button wolai-floating-button--help" aria-label="帮助"><span class="material-symbols-outlined" data-icon="help" aria-hidden="true"></span></button>
<button type="button" data-testid="mnote-floating-task-toggle" class="wolai-floating-button wolai-floating-button--tasks mnote-local-ocr-task-toggle" title="后台任务" aria-label="后台任务" data-mnote-action="toggle-ocr-tasks"><span class="material-symbols-outlined" data-icon="pending_actions" aria-hidden="true"></span><span class="mnote-local-ocr-task-badge" data-mnote-local-ocr-task-count hidden>0</span></button>
<button type="button" data-testid="wolai-floating-ai" class="wolai-floating-button wolai-floating-button--ai" aria-label="AI 助手" title="点击 进入空间智能问答" data-mnote-action="open-page-ai"><span class="material-symbols-outlined material-symbols-filled" data-icon="auto_awesome" aria-hidden="true"></span></button>
</div>
</div>
@@ -232,6 +232,8 @@ mod tests {
include_str!("../../../browser/sidebar-page-tree-runtime.js");
const SIDEBAR_PAGE_AI_RUNTIME_JS: &str =
include_str!("../../../browser/sidebar-page-ai-runtime.js");
const SIDEBAR_PAGE_AI_MARKDOWN_RUNTIME_JS: &str =
include_str!("../../../browser/sidebar-page-ai-markdown-runtime.js");
const SIDEBAR_PAGE_AI_RENDER_RUNTIME_JS: &str =
include_str!("../../../browser/sidebar-page-ai-render-runtime.js");
const SIDEBAR_PAGE_AI_PERMISSION_RUNTIME_JS: &str =
@@ -499,6 +501,9 @@ mod tests {
assert!(html.contains(r#"data-icon="manage_search""#));
assert!(html.contains(r#"data-testid="mnote-local-ocr-task-toggle""#));
assert!(html.contains(r#"data-mnote-action="open-ocr-settings""#));
assert!(html.contains(r#"data-testid="mnote-floating-task-toggle""#));
assert!(html.contains(r#"data-mnote-action="toggle-ocr-tasks""#));
assert!(html.contains(r#"data-icon="pending_actions""#));
}
#[test]
@@ -515,12 +520,30 @@ mod tests {
"新增索引范围必须保留空白输入行,不能先过滤成默认 ."
);
assert!(
SIDEBAR_PAGE_SETTINGS_RUNTIME_JS.contains("if (!values.length) values = [''];"),
"删除最后一个索引范围时 UI 应显示空行,不能强制回填 ."
SIDEBAR_PAGE_SETTINGS_RUNTIME_JS.contains("data-local-index-persisted=\"true\""),
"已保存索引范围必须锁定为不可直接修改"
);
assert!(
SIDEBAR_PAGE_SETTINGS_RUNTIME_JS
.contains("return currentLocalIndexRangeValues(popover).map"),
"删除最后一个索引范围后保存应提交空数组,不能强制回填 ."
);
assert!(
SIDEBAR_PAGE_SETTINGS_RUNTIME_JS
.contains("var savedIncludePaths = Array.isArray(settings.includePaths) ? settings.includePaths : [];"),
"索引面板默认不应把空配置回填成工作区根目录"
);
assert!(
SIDEBAR_PAGE_SETTINGS_RUNTIME_JS.contains(
"var includePaths = savedIncludePaths.length ? savedIncludePaths : indexedPaths;"
),
"无用户配置但已有索引缓存时仍应展示旧索引范围,便于删除"
);
assert!(SIDEBAR_PAGE_SETTINGS_RUNTIME_JS
.contains("data-local-ocr-settings-action=\"run-active\""));
assert!(SIDEBAR_TREE_RUNTIME_JS.contains("mnote:local-ocr-settings-action"));
assert!(SIDEBAR_TREE_RUNTIME_JS.contains("[data-mnote-action=\"toggle-ocr-tasks\"]"));
assert!(SIDEBAR_TREE_RUNTIME_JS.contains("detail: { action: 'tasks' }"));
assert!(!SIDEBAR_PAGE_SETTINGS_RUNTIME_JS.contains("data-page-settings-tab=\"index\""));
assert!(!SIDEBAR_PAGE_SETTINGS_RUNTIME_JS.contains("本地索引仅在本地工作区页面可用"));
assert!(
@@ -617,6 +640,11 @@ mod tests {
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("function pageAiLoadBackendSessions"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("/api/hermes/client/sessions?"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("params.set('source', 'acp')"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains(
"var draftSessions = pageAiNormalizeArray(pageUiState.pageAiSessions).filter"
));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS
.contains("pageAiDedupeSessions(backendSessions.concat(draftSessions))"));
assert!(
SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("function pageAiLoadBackendSessionDetail")
);
@@ -625,6 +653,9 @@ mod tests {
assert!(SIDEBAR_PAGE_AI_RENDER_RUNTIME_JS.contains("data-page-ai-session-delete"));
assert!(SIDEBAR_PAGE_AI_RENDER_RUNTIME_JS.contains("data-page-ai-session-resume"));
assert!(SIDEBAR_PAGE_AI_RENDER_RUNTIME_JS.contains("data-page-ai-session-search"));
assert!(SIDEBAR_PAGE_AI_RENDER_RUNTIME_JS.contains("function pageAiRenderThoughtGroup"));
assert!(SIDEBAR_PAGE_AI_RENDER_RUNTIME_JS.contains("data-page-ai-thought-card"));
assert!(SIDEBAR_PAGE_AI_RENDER_RUNTIME_JS.contains("data-page-ai-collapse-card"));
assert!(SIDEBAR_PAGE_AI_RUNTIME_JS.contains("pageAiUsageSummary"));
assert!(SIDEBAR_PAGE_AI_RUNTIME_JS.contains("usage.updated"));
assert!(SIDEBAR_PAGE_AI_RUNTIME_JS.contains("thought.delta"));
@@ -664,9 +695,11 @@ mod tests {
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("function pageAiSessionStorageLabel"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("local_private"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("local_shared"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("sqlite_control_plane"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("convex_acp_runtime_store"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("本地私有"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("共享会话"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("账号会话"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("云端会话"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("sessionStorage:"));
assert!(SIDEBAR_PAGE_AI_SESSION_RUNTIME_JS.contains("permissionLevel:"));
@@ -688,6 +721,10 @@ mod tests {
assert!(SIDEBAR_PAGE_AI_RUNTIME_JS.contains("pageAiNormalizeAcpRuntimes(acpRuntimes)"));
assert!(SIDEBAR_PAGE_AI_RUNTIME_JS.contains("pageAiAcpRuntimeSelect.value || 'reasonix'"));
assert!(SIDEBAR_PAGE_AI_RUNTIME_JS.contains("function handlePageAiClick"));
assert!(SIDEBAR_PAGE_AI_RUNTIME_JS.contains("function pageAiOpenCitationUrl"));
assert!(SIDEBAR_PAGE_AI_RUNTIME_JS.contains("a[data-page-ai-citation-link=\"true\"]"));
assert!(SIDEBAR_PAGE_AI_MARKDOWN_RUNTIME_JS.contains("data-page-ai-citation-link=\"true\""));
assert!(SIDEBAR_PAGE_AI_MARKDOWN_RUNTIME_JS.contains("target=\"_blank\""));
assert!(SIDEBAR_PAGE_AI_RUNTIME_JS.contains("function handlePageAiChange"));
assert!(SIDEBAR_PAGE_AI_RUNTIME_JS.contains("function installPageAiDelegates"));
assert!(SIDEBAR_TREE_RUNTIME_JS.contains("sidebarPageAi.installPageAiDelegates()"));
@@ -722,7 +759,8 @@ mod tests {
#[test]
fn sidebar_workspace_source_switch_remembers_real_cloud_workspace_before_local_folder() {
assert!(
!SIDEBAR_TREE_RUNTIME_JS.contains("rememberCloudWorkspaceId(resolveWorkspaceId(document.body))"),
!SIDEBAR_TREE_RUNTIME_JS
.contains("rememberCloudWorkspaceId(resolveWorkspaceId(document.body))"),
"进入本地文件夹前不能用 document.body 推导 workspaceId;它会在无 workspaceId URL 时回退成 default"
);
assert!(
@@ -881,7 +919,8 @@ mod tests {
assert!(LOCAL_UPLOAD_RUNTIME_JS.contains("uploadFilesWithResolvedTarget"));
assert!(LOCAL_UPLOAD_RUNTIME_JS.contains("__mnoteLastEditorUploadRoot"));
assert!(
LOCAL_UPLOAD_RUNTIME_JS.contains("var imageUrl = localOpenUrl || fallbackUrl || markdownHref;"),
LOCAL_UPLOAD_RUNTIME_JS
.contains("var imageUrl = localOpenUrl || fallbackUrl || markdownHref;"),
"图片上传首屏必须使用本地 open URL 渲染,避免相对 href 在 /documents 下命中退役 Convex 兼容路径"
);
assert!(
@@ -1530,8 +1569,9 @@ mod tests {
);
assert!(SIDEBAR_TREE_LIVE_APPLY_RUNTIME_JS
.contains("fileTreeViewState.selectedRowIds.add(rowId)"));
assert!(SIDEBAR_TREE_LIVE_APPLY_RUNTIME_JS
.contains("row.setAttribute('data-selected', String(fileTreeViewState.selectedRowIds.has(rowId)))"));
assert!(SIDEBAR_TREE_LIVE_APPLY_RUNTIME_JS.contains(
"row.setAttribute('data-selected', String(fileTreeViewState.selectedRowIds.has(rowId)))"
));
assert!(SIDEBAR_TREE_LIVE_APPLY_RUNTIME_JS.contains(
"row.setAttribute('data-focused', String(rowId === fileTreeViewState.focusedRowId))"
));
+346 -56
View File
@@ -1732,7 +1732,8 @@ body {
justify-content: center;
flex: 0 0 20px;
color: #9A958F;
overflow: hidden;
overflow: visible;
position: relative;
}
.sidebar-tree .tree-kind-badge::before {
@@ -1745,6 +1746,32 @@ body {
mask: var(--mnote-filetree-icon-mask) center / contain no-repeat;
}
.sidebar-tree .tree-row[data-index-status="indexed"] .tree-kind-badge::after,
.sidebar-tree .tree-row[data-index-status="failed"] .tree-kind-badge::after {
position: absolute;
left: -1px;
bottom: 1px;
width: 9px;
height: 9px;
border-radius: 2px;
color: #FFFFFF;
font-size: 8px;
line-height: 9px;
font-weight: 700;
text-align: center;
box-shadow: 0 0 0 1px #FFFFFF;
}
.sidebar-tree .tree-row[data-index-status="indexed"] .tree-kind-badge::after {
content: "";
background: #38B86E;
}
.sidebar-tree .tree-row[data-index-status="failed"] .tree-kind-badge::after {
content: "x";
background: #D94841;
}
.sidebar-tree .tree-kind-badge[data-kind="page"]::before {
--mnote-filetree-icon-mask: var(--mnote-filetree-icon-file);
}
@@ -2783,9 +2810,10 @@ body {
.mnote-local-ocr-task-dock {
position: fixed;
right: 16px;
top: 48px;
z-index: 90;
top: 12px;
right: 12px;
bottom: 12px;
z-index: 89;
color: #37352f;
font-size: 13px;
pointer-events: none;
@@ -2813,30 +2841,61 @@ body {
}
.mnote-local-ocr-task-drawer {
width: min(360px, calc(100vw - 36px));
max-height: min(420px, calc(100vh - 120px));
overflow: auto;
border: 1px solid rgba(55, 53, 47, 0.14);
border-radius: 6px;
background: #FFF;
box-shadow: 0 14px 36px rgba(15, 23, 42, 0.16);
width: min(440px, calc(100vw - 24px));
height: 100%;
pointer-events: auto;
}
.mnote-local-ocr-task-drawer[hidden] {
display: none !important;
}
.mnote-local-ocr-task-panel {
height: 100%;
display: flex;
flex-direction: column;
gap: 12px;
padding: 14px;
border: 1px solid rgba(27, 28, 28, 0.08);
border-radius: 14px;
background: rgba(255, 255, 255, 0.98);
box-shadow: -18px 0 42px rgba(27, 28, 28, 0.14);
box-sizing: border-box;
}
.mnote-local-ocr-task-head {
display: flex;
align-items: center;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
border-bottom: 1px solid rgba(55, 53, 47, 0.1);
}
.mnote-local-ocr-task-head > div {
min-width: 0;
}
.mnote-local-ocr-task-head strong {
display: block;
color: #1B1C1C;
font-size: 16px;
font-weight: 650;
line-height: 22px;
}
.mnote-local-ocr-task-head span {
display: block;
margin-top: 2px;
color: #8B8782;
font-size: 12px;
line-height: 18px;
}
.mnote-local-ocr-task-close {
width: 24px;
height: 24px;
flex: 0 0 auto;
width: 28px;
height: 28px;
border: 0;
border-radius: 4px;
border-radius: 6px;
background: transparent;
color: #787774;
cursor: pointer;
@@ -2847,55 +2906,208 @@ body {
color: #37352f;
}
.mnote-local-ocr-task-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
border-bottom: 1px solid rgba(55, 53, 47, 0.08);
.mnote-local-ocr-task-tabs {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 4px;
padding: 3px;
border-radius: 8px;
background: #F4F3F2;
}
.mnote-local-ocr-task-main {
.mnote-local-ocr-task-tabs button {
min-width: 0;
}
.mnote-local-ocr-task-main strong,
.mnote-local-ocr-task-main span {
display: block;
height: 28px;
border: 0;
border-radius: 6px;
background: transparent;
color: #5A5A5A;
font-size: 12px;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mnote-local-ocr-task-main span,
.mnote-local-ocr-task-empty {
.mnote-local-ocr-task-tabs button[aria-selected="true"] {
background: #FFF;
color: #1B1C1C;
box-shadow: 0 1px 4px rgba(27, 28, 28, 0.08);
}
.mnote-local-ocr-task-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.mnote-local-ocr-task-toolbar span {
color: #8B8782;
font-size: 12px;
}
.mnote-local-ocr-task-toolbar button,
.mnote-local-ocr-task-actions button {
min-height: 28px;
border: 1px solid rgba(27, 28, 28, 0.08);
border-radius: 6px;
background: #FFF;
color: #1B1C1C;
font-size: 12px;
cursor: pointer;
}
.mnote-local-ocr-task-toolbar button:disabled {
color: #AAA6A0;
cursor: default;
}
.mnote-local-ocr-task-list {
min-height: 0;
overflow: auto;
display: flex;
flex-direction: column;
gap: 8px;
}
.mnote-local-ocr-task-row {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: start;
gap: 12px;
padding: 10px;
border: 1px solid rgba(27, 28, 28, 0.08);
border-radius: 8px;
background: #FFF;
}
.mnote-local-ocr-task-main {
min-width: 0;
display: grid;
gap: 5px;
}
.mnote-local-ocr-task-title-line {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.mnote-local-ocr-task-main strong {
display: block;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #1B1C1C;
font-size: 13px;
font-weight: 600;
line-height: 18px;
}
.mnote-local-ocr-task-main em {
flex: 0 0 auto;
padding: 1px 6px;
border-radius: 999px;
background: #F0EFED;
color: #8B8782;
font-size: 10px;
font-style: normal;
line-height: 15px;
}
.mnote-local-ocr-task-row[data-mnote-local-ocr-task-category="attention"] .mnote-local-ocr-task-main em {
background: #FEE2E2;
color: #B3261E;
}
.mnote-local-ocr-task-row[data-mnote-local-ocr-task-category="active"] .mnote-local-ocr-task-main em {
background: #DBEAFE;
color: #1D4ED8;
}
.mnote-local-ocr-task-main span {
display: block;
min-width: 0;
overflow: hidden;
color: #787774;
font-size: 12px;
line-height: 17px;
text-overflow: ellipsis;
white-space: nowrap;
}
.mnote-local-ocr-task-progress {
position: relative;
height: 4px;
overflow: hidden;
border-radius: 999px;
background: #ECE9E4;
}
.mnote-local-ocr-task-progress i {
display: block;
height: 100%;
border-radius: inherit;
background: #5B8DEF;
}
.mnote-local-ocr-task-progress[data-progress-mode="indeterminate"] i {
width: 40%;
animation: mnote-task-progress-slide 1.15s ease-in-out infinite;
}
@keyframes mnote-task-progress-slide {
0% {
transform: translateX(-120%);
}
100% {
transform: translateX(260%);
}
}
.mnote-local-ocr-task-empty {
padding: 12px;
padding: 24px 12px;
border: 1px dashed rgba(27, 28, 28, 0.12);
border-radius: 8px;
color: #787774;
text-align: center;
}
.mnote-local-ocr-task-actions {
display: flex;
display: grid;
flex: 0 0 auto;
gap: 6px;
}
.mnote-local-ocr-task-actions button {
height: 26px;
border: 1px solid rgba(55, 53, 47, 0.14);
border-radius: 4px;
background: #FFF;
color: #37352f;
cursor: pointer;
padding: 0 8px;
}
.mnote-local-ocr-task-actions button[data-mnote-local-ocr-task-delete] {
color: #b3261e;
}
@media (max-width: 720px) {
.mnote-local-ocr-task-dock {
left: 12px;
}
.mnote-local-ocr-task-drawer {
width: 100%;
}
.mnote-local-ocr-task-row {
grid-template-columns: 1fr;
}
.mnote-local-ocr-task-actions {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
.mnote-resource-tab-frame,
.mnote-resource-tab-image,
.mnote-resource-tab-text-shell {
@@ -3481,7 +3693,7 @@ body {
cursor: pointer;
}
.wolai-floating-button--help {
.wolai-floating-button--tasks {
width: 40px;
height: 40px;
border: 1px solid rgba(27, 28, 28, 0.1);
@@ -3767,6 +3979,12 @@ body {
color: #A19D97;
}
.wolai-page-settings-index-root-hint {
color: #8B8782;
font-size: 11px;
white-space: nowrap;
}
.wolai-page-settings-index-remove,
.wolai-page-settings-index-add {
border: 1px solid #D8D4CE;
@@ -4597,13 +4815,14 @@ body {
.wolai-page-ai-skills-toolbar {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(124px, 160px) max-content;
grid-template-columns: minmax(0, 1fr);
align-items: end;
gap: 8px;
}
.wolai-page-ai-skill-filter-toggle {
display: inline-flex;
grid-column: 1 / -1;
min-height: 34px;
align-items: center;
gap: 6px;
@@ -4670,10 +4889,10 @@ body {
.wolai-page-ai-skill-row {
display: flex;
min-height: 38px;
align-items: center;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
padding: 6px 8px;
padding: 8px;
border: 0;
border-radius: 6px;
background: transparent;
@@ -4687,20 +4906,21 @@ body {
display: grid;
gap: 2px;
min-width: 0;
flex: 1 1 auto;
}
.wolai-page-ai-skill-main {
display: flex;
display: grid;
min-width: 0;
align-items: center;
gap: 8px;
gap: 2px;
}
.wolai-page-ai-skill-name {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
overflow: visible;
text-overflow: clip;
white-space: normal;
word-break: break-word;
}
.wolai-page-ai-skill-desc {
@@ -4708,18 +4928,22 @@ body {
color: #5A5A5A;
font-size: 11px;
line-height: 15px;
text-overflow: ellipsis;
white-space: nowrap;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
text-overflow: clip;
white-space: normal;
}
.wolai-page-ai-skill-source {
flex: 0 0 auto;
padding: 1px 5px;
border-radius: 999px;
background: #F0EFED;
padding: 0;
border-radius: 0;
background: transparent;
color: #8B8782;
font-size: 10px;
line-height: 14px;
white-space: normal;
word-break: break-word;
}
.wolai-page-ai-skill-switch {
@@ -4753,6 +4977,17 @@ body {
transform: translateX(14px);
}
.wolai-page-ai-skill-readonly-badge {
flex: 0 0 auto;
margin-top: 2px;
padding: 2px 6px;
border-radius: 999px;
background: #F0EFED;
color: #8B8782;
font-size: 10px;
line-height: 14px;
}
.wolai-page-ai-message {
display: flex;
flex-direction: column;
@@ -4867,6 +5102,61 @@ button.wolai-page-ai-message-text {
white-space: nowrap;
}
.wolai-page-ai-tool-group-list {
display: grid;
gap: 8px;
margin-top: 8px;
}
.wolai-page-ai-thought-group-list {
min-width: 0;
margin-top: 8px;
padding-left: 10px;
border-left: 2px solid rgba(27, 28, 28, 0.12);
color: #6F6B66;
font-size: 12px;
line-height: 18px;
white-space: pre-wrap;
}
.wolai-page-ai-tool-item {
display: grid;
gap: 4px;
min-width: 0;
padding: 8px;
border: 1px solid rgba(27, 28, 28, 0.08);
border-radius: 6px;
background: rgba(255, 255, 255, 0.58);
}
.wolai-page-ai-tool-item-head {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(92px, auto);
gap: 8px;
align-items: center;
}
.wolai-page-ai-tool-item-head strong {
min-width: 0;
overflow: hidden;
color: #1B1C1C;
font-size: 12px;
line-height: 18px;
text-overflow: ellipsis;
white-space: nowrap;
}
.wolai-page-ai-tool-item-head span {
min-width: 0;
overflow: hidden;
color: #8B8782;
font-size: 11px;
line-height: 16px;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.wolai-page-ai-footer {
position: relative;
z-index: 20;
@@ -16,6 +16,7 @@ pub struct FileTreeRenderRow {
pub asset_id: Option<String>,
pub relative_path: Option<String>,
pub object_identity: Option<String>,
pub index_status: Option<String>,
pub selected: bool,
}
@@ -90,8 +91,13 @@ fn render_filetree_row(
_ => "",
};
let owner_document_id = row.document_id.as_deref().unwrap_or_default();
let index_status_attr = row
.index_status
.as_deref()
.map(|status| format!(r#" data-index-status="{}""#, escape_html(status)))
.unwrap_or_default();
html.push_str(&format!(
r#"<li class="tree-node" data-node-id="{node_id}"><div class="tree-row" role="treeitem" aria-level="{aria_level}" aria-expanded="{expanded_attr}" data-rust-rendered-row="filetree" data-testid="{test_id}" data-row-id="{row_id}" data-row-kind="{row_kind}" data-node-id="{node_id}"{parent_attr} data-document-id="{document_id}" data-doc-id="{document_id}" data-owner-document-id="{owner_document_id}" data-asset-id="{asset_id}" data-local-relative-path="{relative_path}" data-object-identity="{object_identity}" data-shell-mode="filetree" data-selected="{selected}" data-active="false" draggable="true">{toggle_html}<span class="tree-kind-badge" data-kind="{icon_kind}" aria-hidden="true"></span><button type="button" class="tree-link" data-rust-action="open" data-row-id="{row_id}" data-document-id="{document_id}" data-owner-document-id="{owner_document_id}" data-asset-id="{asset_id}" data-local-relative-path="{relative_path}" title="{title}"><span class="tree-link-title" title="{title}">{title}</span></button><div class="tree-actions">{create_action_html}<button type="button" class="tree-action" data-testid="filetree-action-menu" data-rust-action="menu" data-row-id="{row_id}" aria-label="更多操作">…</button></div></div>"#,
r#"<li class="tree-node" data-node-id="{node_id}"><div class="tree-row" role="treeitem" aria-level="{aria_level}" aria-expanded="{expanded_attr}" data-rust-rendered-row="filetree" data-testid="{test_id}" data-row-id="{row_id}" data-row-kind="{row_kind}" data-node-id="{node_id}"{parent_attr} data-document-id="{document_id}" data-doc-id="{document_id}" data-owner-document-id="{owner_document_id}" data-asset-id="{asset_id}" data-local-relative-path="{relative_path}" data-object-identity="{object_identity}"{index_status_attr} data-shell-mode="filetree" data-selected="{selected}" data-active="false" draggable="true">{toggle_html}<span class="tree-kind-badge" data-kind="{icon_kind}" aria-hidden="true"></span><button type="button" class="tree-link" data-rust-action="open" data-row-id="{row_id}" data-document-id="{document_id}" data-owner-document-id="{owner_document_id}" data-asset-id="{asset_id}" data-local-relative-path="{relative_path}" title="{title}"><span class="tree-link-title" title="{title}">{title}</span></button><div class="tree-actions">{create_action_html}<button type="button" class="tree-action" data-testid="filetree-action-menu" data-rust-action="menu" data-row-id="{row_id}" aria-label="更多操作">…</button></div></div>"#,
node_id = escape_html(&row.node_id),
aria_level = row.depth + 1,
expanded_attr = if row.expandable && row.expanded { "true" } else { "false" },
@@ -104,6 +110,7 @@ fn render_filetree_row(
asset_id = escape_html(row.asset_id.as_deref().unwrap_or_default()),
relative_path = escape_html(row.relative_path.as_deref().unwrap_or_default()),
object_identity = escape_html(row.object_identity.as_deref().unwrap_or_default()),
index_status_attr = index_status_attr,
selected = row.selected,
toggle_html = toggle_html,
icon_kind = escape_html(&row.icon_kind),
@@ -182,6 +189,7 @@ mod tests {
object_identity: Some(
r#"{"objectKind":"page","documentId":"page_root","blockId":null,"assetId":null}"#.into(),
),
index_status: None,
selected: true,
},
FileTreeRenderRow {
@@ -200,6 +208,7 @@ mod tests {
object_identity: Some(
r#"{"objectKind":"mindmap","documentId":"page_root","blockId":null,"assetId":"mind_1"}"#.into(),
),
index_status: None,
selected: false,
},
],
@@ -241,6 +250,7 @@ mod tests {
asset_id: None,
relative_path: Some("docs".into()),
object_identity: None,
index_status: None,
selected: false,
},
FileTreeRenderRow {
@@ -257,6 +267,7 @@ mod tests {
asset_id: None,
relative_path: Some("docs/README.md".into()),
object_identity: None,
index_status: None,
selected: false,
},
],
@@ -286,11 +297,13 @@ mod tests {
asset_id: None,
relative_path: Some("design/03-rust-web".into()),
object_identity: None,
index_status: Some("indexed".into()),
selected: false,
}],
});
assert!(html.contains(r#"data-local-relative-path="design/03-rust-web""#));
assert!(html.contains(r#"data-index-status="indexed""#));
assert!(html.contains(r#"<button type="button" class="tree-link""#));
}
}
@@ -135,6 +135,7 @@ mod tests {
asset_id: None,
relative_path: None,
object_identity: None,
index_status: None,
selected: false,
},
FileTreeRenderRow {
@@ -151,6 +152,7 @@ mod tests {
asset_id: Some("asset_1".into()),
relative_path: Some("asset_1".into()),
object_identity: None,
index_status: None,
selected: false,
},
]);