An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Improve agent SQL search capabilities https://github.com/siyuan-note/siyuan/issues/20383
Daniel25ce075bf0f9
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-l3qg72k.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-l3qg72k.syindex 82096e8921..91dd02d101 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-l3qg72k.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-l3qg72k.sy@@ -7,7 +7,7 @@"id": "20210808180303-l3qg72k","title": "Advanced search","type": "doc",- "updated": "20261009182324"+ "updated": "20261010113646"},"Children": [{@@ -44,7 +44,7 @@"Type": "NodeHeading","Properties": {"id": "20261009182324-t1r641c",- "updated": "20261009182324"+ "updated": "20261010113646"},"Children": [{@@ -96,6 +96,29 @@}]},+ {+ "ID": "20261010113646-apg2y00",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261010113646-apg2y00",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Desktop and mobile SQL search support pasted multiline statements and preserve comments. In SQL mode, press "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Enter"+ },+ {+ "Type": "NodeText",+ "Data": " to insert a newline. Keep the newline after a -- line comment so that the following statement is not treated as a comment. The search window requires complete block columns, such as SELECT b.* FROM blocks b; use the agent's sql.query for projections or aggregates."+ }+ ]+ },{"ID": "20261009182324-seagl6e","Type": "NodeParagraph",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.syindex 74e7b431e7..0fba72d054 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.sy@@ -6,7 +6,7 @@"id": "20260804171004-aiagt03","title": "AI Agent","type": "doc",- "updated": "20261008125238"+ "updated": "20261010113646"},"Children": [{@@ -1135,6 +1135,35 @@}]},+ {+ "ID": "20261010113646-aewwqju",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261010113646-aewwqju",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Structured SQL search"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261010113646-f4xjowe",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261010113646-f4xjowe",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "For block types, inline formatting, ancestry, combined filters or statistics, the agent can request sql.schema for index definitions and examples, then query with sql.query. Results include original rows and clickable block links. Statistics can be used directly in an answer; complete block queries can be displayed in search using open_search with method=2. Omitting the method keeps the current setting; subsequent calls update the query and method in the existing window."+ }+ ]+ },{"ID": "20260804170109-sbl6g5j","Type": "NodeHeading",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-gyngv2x.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-gyngv2x.syindex 49afe54c7b..16228897f2 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-gyngv2x.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-gyngv2x.sy@@ -7,7 +7,7 @@"id": "20210808180320-gyngv2x","title": "搜索进阶","type": "doc",- "updated": "20261009182324"+ "updated": "20261010113646"},"Children": [{@@ -44,7 +44,7 @@"Type": "NodeHeading","Properties": {"id": "20261009182324-ljls7op",- "updated": "20261009182324"+ "updated": "20261010113646"},"Children": [{@@ -96,6 +96,29 @@}]},+ {+ "ID": "20261010113646-r0h5r0j",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261010113646-r0h5r0j",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "桌面端和移动端的 SQL 搜索支持粘贴多行语句并保留注释。SQL 模式下按 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Enter"+ },+ {+ "Type": "NodeText",+ "Data": " 换行;请保留 -- 行注释后的换行,避免后续语句被视为注释。搜索窗口需要完整块字段,例如 SELECT b.* FROM blocks b;仅选择部分字段或统计结果应交给智能体的 sql.query。"+ }+ ]+ },{"ID": "20261009182324-mayn7w7","Type": "NodeParagraph",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.syindex 1a6716d232..b2a67b8f11 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.sy@@ -6,7 +6,7 @@"id": "20260804171000-aiagt01","title": "AI 智能体","type": "doc",- "updated": "20261008125238"+ "updated": "20261010113646"},"Children": [{@@ -1135,6 +1135,35 @@}]},+ {+ "ID": "20261010113646-kdzs7xm",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261010113646-kdzs7xm",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "结构化 SQL 搜索"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261010113646-xl27dnz",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261010113646-xl27dnz",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "对于块类型、行内格式、父子层级、多条件筛选或统计需求,智能体可按需调用 sql.schema 获取索引结构和示例,再通过 sql.query 查询。查询结果包含原始行数据和可点击的块链接;统计结果直接用于回答,完整块查询可通过 open_search 的 method=2 在搜索窗口展示。未指定搜索方式时沿用当前设置,再次调用会更新已有窗口的查询内容和方式。"+ }+ ]+ },{"ID": "20260804170109-njpec5z","Type": "NodeHeading",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120933-vnjgwwh.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120933-vnjgwwh.syindex 7495cf2547..721b626f77 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120933-vnjgwwh.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120933-vnjgwwh.sy@@ -7,7 +7,7 @@"id": "20211226120933-vnjgwwh","title": "搜索進階","type": "doc",- "updated": "20261009182324"+ "updated": "20261010113646"},"Children": [{@@ -44,7 +44,7 @@"Type": "NodeHeading","Properties": {"id": "20261009182324-g42svwc",- "updated": "20261009182324"+ "updated": "20261010113646"},"Children": [{@@ -96,6 +96,29 @@}]},+ {+ "ID": "20261010113646-lqqhbxx",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261010113646-lqqhbxx",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "桌面端與行動端的 SQL 搜尋支援貼上多行語句並保留註解。SQL 模式下按 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Enter"+ },+ {+ "Type": "NodeText",+ "Data": " 換行;請保留 -- 行註解後的換行,避免後續語句被視為註解。搜尋視窗需要完整區塊欄位,例如 SELECT b.* FROM blocks b;僅選取部分欄位或統計結果應交給智能體的 sql.query。"+ }+ ]+ },{"ID": "20261009182324-7v8lo26","Type": "NodeParagraph",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.syindex 6ec425c997..e82972d07f 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.sy@@ -6,7 +6,7 @@"id": "20260804171002-aiagt02","title": "AI 智能體","type": "doc",- "updated": "20261008125238"+ "updated": "20261010113646"},"Children": [{@@ -1135,6 +1135,35 @@}]},+ {+ "ID": "20261010113646-gmbl8rw",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261010113646-gmbl8rw",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "結構化 SQL 搜尋"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261010113646-6398erx",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261010113646-6398erx",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "對於區塊類型、行內格式、父子層級、多條件篩選或統計需求,智能體可按需呼叫 sql.schema 取得索引結構與範例,再透過 sql.query 查詢。查詢結果包含原始列資料與可點擊的區塊連結;統計結果直接用於回答,完整區塊查詢可透過 open_search 的 method=2 在搜尋視窗顯示。未指定搜尋方式時沿用目前設定,再次呼叫會更新既有視窗的查詢內容與方式。"+ }+ ]+ },{"ID": "20260804170109-gephumz","Type": "NodeHeading",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-a91lmk2.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-a91lmk2.syindex 3b5070c956..7df4c17b67 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-a91lmk2.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-a91lmk2.sy@@ -8,7 +8,7 @@"id": "20240530101000-a91lmk2","title": "高度な検索","type": "doc",- "updated": "20261009182324"+ "updated": "20261010113646"},"Children": [{@@ -45,7 +45,7 @@"Type": "NodeHeading","Properties": {"id": "20261009182324-svc2r56",- "updated": "20261009182324"+ "updated": "20261010113646"},"Children": [{@@ -97,6 +97,29 @@}]},+ {+ "ID": "20261010113646-3gi11r9",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261010113646-3gi11r9",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "デスクトップとモバイルの SQL 検索では、複数行の文を貼り付け、コメントを保持できます。SQL モードでは "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Enter"+ },+ {+ "Type": "NodeText",+ "Data": " で改行します。-- 行コメントの後の改行を残し、後続の文がコメントに含まれないようにしてください。検索画面には SELECT b.* FROM blocks b のような完全なブロック列が必要です。列の一部や集計結果にはエージェントの sql.query を使用してください。"+ }+ ]+ },{"ID": "20261009182324-5i14ow7","Type": "NodeParagraph",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.syindex 6a55d64a9c..f81c0fe56f 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.sy@@ -6,7 +6,7 @@"id": "20260804171006-aiagt04","title": "AI エージェント","type": "doc",- "updated": "20261008125238"+ "updated": "20261010113646"},"Children": [{@@ -1123,6 +1123,35 @@}]},+ {+ "ID": "20261010113646-e4bfwsj",+ "Type": "NodeHeading",+ "Properties": {+ "id": "20261010113646-e4bfwsj",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "構造に基づく SQL 検索"+ }+ ],+ "HeadingLevel": 2+ },+ {+ "ID": "20261010113646-71xuifp",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261010113646-71xuifp",+ "updated": "20261010113646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "ブロックタイプ、インライン書式、親子関係、複数条件や集計には、エージェントが必要に応じて sql.schema で索引の構造と例を取得し、sql.query で問い合わせます。結果には元の行データとクリックできるブロックリンクが含まれます。集計結果は回答に使用でき、完全なブロック行を返すクエリは open_search の method=2 で検索画面に表示できます。検索方法を省略すると現在の設定を引き継ぎ、再度呼び出すと既存の画面のクエリと検索方法が更新されます。"+ }+ ]+ },{"ID": "20260804170109-yrnzqjt","Type": "NodeHeading",diff --git a/app/src/assets/scss/business/_search.scss b/app/src/assets/scss/business/_search.scssindex fdf4a5419f..e5cf755b3a 100644--- a/app/src/assets/scss/business/_search.scss+++ b/app/src/assets/scss/business/_search.scss@@ -2,6 +2,15 @@@use "../component/form";.search {+ &__input {+ resize: none;++ &--sql {+ height: 100px;+ max-height: 30vh;+ }+ }+&__av-content {-webkit-line-clamp: 7;overflow-wrap: anywhere;@@ -59,6 +68,10 @@padding: 5px 8px 5px 44px !important;box-shadow: none;width: 100%;++ &.search__input--sql {+ height: 100px;+ }}.b3-form__icon-icon {diff --git a/app/src/assets/scss/main/_mobile.scss b/app/src/assets/scss/main/_mobile.scssindex 5eb35e3ebb..82853667c5 100644--- a/app/src/assets/scss/main/_mobile.scss+++ b/app/src/assets/scss/main/_mobile.scss@@ -278,6 +278,11 @@ body.mobile-keyboard--open {display: flex;align-items: center;height: 48px;++ &--sql {+ height: auto;+ min-height: 48px;+ }}&__text {@@ -294,6 +299,10 @@ body.mobile-keyboard--open {height: 48px;-webkit-line-clamp: unset;}++ &--search-sql {+ height: auto;+ }}&__tabs {diff --git a/app/src/boot/globalEvent/searchKeydown.test.ts b/app/src/boot/globalEvent/searchKeydown.test.tsindex ad6069a039..cff53385d5 100644--- a/app/src/boot/globalEvent/searchKeydown.test.ts+++ b/app/src/boot/globalEvent/searchKeydown.test.ts@@ -39,4 +39,5 @@ test("search input Enter retains keyword document creation and ordinary result oassert.deepEqual(runEnter("searchInput", 0, "search-new"), {calls: ["newFile"], handled: true});assert.deepEqual(runEnter("searchInput", 1, "search-new"), {calls: [], handled: false});assert.deepEqual(runEnter("searchInput", 0, "search-result"), {calls: ["open"], handled: true});+ assert.deepEqual(runEnter("searchInput", 2, "search-result"), {calls: [], handled: false});});diff --git a/app/src/boot/globalEvent/searchKeydown.ts b/app/src/boot/globalEvent/searchKeydown.tsindex ff716bcae0..9904a8e95a 100644--- a/app/src/boot/globalEvent/searchKeydown.ts+++ b/app/src/boot/globalEvent/searchKeydown.ts@@ -62,14 +62,18 @@ export const searchKeydown = (app: App, event: KeyboardEvent) => {const unRefElement = element.querySelector("#searchUnRefPanel");const searchType = assetsElement.classList.contains("fn__none") ? (unRefElement.classList.contains("fn__none") ? "doc" : "unRef") : "asset";const listElement = searchType === "asset" ? assetsElement.querySelector("#searchAssetList") : (searchType === "doc" ? element.querySelector("#searchList") : unRefElement.querySelector("#searchUnRefList"));- const searchInputElement = element.querySelector("#searchInput") as HTMLInputElement;+ const searchInputElement = element.querySelector("#searchInput") as HTMLTextAreaElement;+ const targetId = (event.target as HTMLElement).id;+ if (targetId === "searchInput" && config.method === 2 && !event.altKey && !event.ctrlKey && !event.metaKey &&+ (event.key === "Enter" || event.key.startsWith("Arrow"))) {+ return false;+ }if (searchType === "doc" && matchHotKey(window.siyuan.config.keymap.general.newFile, event)) {if (config.method === 0) {newFile(app, searchInputElement.value);}return true;}- const targetId = (event.target as HTMLElement).id;if (event.key === "ArrowDown" && event.altKey) {if (searchType === "asset") {toggleAssetHistory(assetsElement);diff --git a/app/src/layout/dock/agent/frontendCapabilities.test.ts b/app/src/layout/dock/agent/frontendCapabilities.test.tsindex 81e7982e3e..c75abc41dd 100644--- a/app/src/layout/dock/agent/frontendCapabilities.test.ts+++ b/app/src/layout/dock/agent/frontendCapabilities.test.ts@@ -17,6 +17,8 @@ for (const mobile of [false, true]) {const input = {value: "", dispatchEvent: () => actions.push("filter")};const dialog = {element: {querySelector: () => input}};const constants = {CB_GET_FOCUS: "focus", DIALOG_GLOBALSEARCH: "search"};+ const searchOptions: Array<{key?: string, method?: number}> = [];+ const siyuan = {dialogs: [dialog], config: {ai: {embedding: {enabled: true}}}};const dependencies: Record<string, unknown> = {"../../../config": {openSetting: () => { actions.push("settings"); return dialog; }},"../../getAll": {getAllEditor: () => [{protyle: {wysiwyg: {element: {querySelector: (): null => null}}}}, editor]},@@ -27,8 +29,14 @@ for (const mobile of [false, true]) {"../../../editor/util": {openFileById: (options: {id: string, action: string[]}) =>actions.push("document:" + options.id + ":" + options.action[0])},"../../../constants": {Constants: constants},- "../../../search/spread": {openSearch: (options: {key: string}) => actions.push("search:" + options.key)},- "../../../mobile/menu/search": {popSearch: () => actions.push("search")},+ "../../../search/spread": {openSearch: (options: {key?: string, method?: number}) => {+ searchOptions.push(options); actions.push("search:" + options.key);+ }},+ "../../../mobile/menu/search": {popSearch: (_app: unknown, _config: unknown, _focus: boolean,+ options: {key?: string, method?: number}) => {+ searchOptions.push(options); actions.push("search");+ }},+ "../../../protyle/util/compatibility": {isDisabledFeature: () => false},};const source = parse(readFileSync("src/layout/dock/agent/frontendCapabilities.ts", "utf8"),{MOBILE: mobile, BROWSER: true}, false, true, "frontendCapabilities.ts");@@ -39,7 +47,7 @@ for (const mobile of [false, true]) {runInNewContext(code, {exports, require: (name: string) => {assert.ok(name in dependencies, name);return dependencies[name];- }, window: {siyuan: {dialogs: [dialog]}}, document: {getElementById: () => input},+ }, window: {siyuan}, document: {getElementById: () => input},Event: class {}, InputEvent: class {}, setTimeout: (callback: () => void) => delayed.push(callback)});const capability = (name: string) => exports.lookupCapability("native/frontend/" + name);assert.equal(exports.listCapabilityManifests().length, 4);@@ -60,7 +68,22 @@ for (const mobile of [false, true]) {assert.deepEqual(actions, mobile ? ["hide", "document:doc:focus"] : ["document:doc:focus"]);actions.length = 0;await capability("open_search").handler({query: " foo "}, {} as App);- assert.deepEqual(actions, mobile ? ["hide", "search", "filter"] : ["search:foo"]);- if (mobile) assert.equal(input.value, "foo");+ assert.deepEqual(actions, mobile ? ["hide", "search"] : ["search:foo"]);+ assert.equal(searchOptions.at(-1).key, "foo");+ assert.equal(searchOptions.at(-1).method, undefined);+ const sql = "-- comment\nSELECT * FROM blocks";+ await capability("open_search").handler({query: sql, method: 2}, {} as App);+ assert.equal(searchOptions.at(-1).key, sql);+ assert.equal(searchOptions.at(-1).method, 2);+ await capability("open_search").handler({query: "", method: 0}, {} as App);+ assert.equal(searchOptions.at(-1).key, "");+ actions.length = 0;+ for (const method of [-1, 5, 2.5, "2"]) {+ assert.ok((await capability("open_search").handler({method}, {} as App)).error);+ }+ assert.ok((await capability("open_search").handler({query: 2}, {} as App)).error);+ siyuan.config.ai.embedding.enabled = false;+ assert.ok((await capability("open_search").handler({method: 4}, {} as App)).error);+ assert.deepEqual(actions, []);});}diff --git a/app/src/layout/dock/agent/frontendCapabilities.ts b/app/src/layout/dock/agent/frontendCapabilities.tsindex 00c71c98e7..9c5686bf52 100644--- a/app/src/layout/dock/agent/frontendCapabilities.ts+++ b/app/src/layout/dock/agent/frontendCapabilities.ts@@ -15,6 +15,8 @@// along with this program. If not, see <https://www.gnu.org/licenses/>.import type {App} from "../../../index";+import type {SearchOpenOptions} from "../../../search/openOptions";+import {isDisabledFeature} from "../../../protyle/util/compatibility";// 浏览器能力只在当前应用实例中执行,内核持有声明和本轮不可变的调用映射。@@ -214,18 +216,32 @@ registerCapability({registerCapability({id: "native/frontend/open_search",title: "Open search",- description: mobileFrontend ? "Open the SiYuan mobile search interface and optionally fill in a query." :- "Open the SiYuan search interface and optionally fill in a query.",- inputSchema: {type: "object", properties: {query: {type: "string"}}, additionalProperties: false},+ description: `Open the SiYuan ${mobileFrontend ? "mobile search interface" : "search interface"} and optionally set a query and method. Omitted values preserve the current search settings. For SQL (method=2), return complete block rows with SELECT b.* FROM blocks b, rather than projections or aggregates; express filters and LIMIT/OFFSET in SQL. Use sql.query for statistics and arbitrary columns, and sql.schema for structural search guidance. Newlines and SQL comments are preserved.`,+ inputSchema: {type: "object", properties: {+ query: {type: "string"},+ method: {type: "integer", enum: [0, 1, 2, 3, 4],+ description: "0 keyword, 1 query syntax, 2 SQL, 3 regex, 4 semantic (requires enabled embeddings)"},+ }, additionalProperties: false},source: "native",handler: async (args, app) => {+ if (args.query !== undefined && typeof args.query !== "string") {+ return {error: "query must be a string"};+ }+ if (args.method !== undefined && (!Number.isInteger(args.method) ||+ (args.method as number) < 0 || (args.method as number) > 4)) {+ return {error: "method must be an integer from 0 to 4"};+ }const query = (args.query as string | undefined)?.trim();+ const method = args.method as SearchOpenOptions["method"];+ if (method === 4 && (isDisabledFeature("ai") || !window.siyuan.config.ai.embedding.enabled)) {+ return {error: "Semantic search requires enabled AI and embeddings"};+ }/// #if !MOBILEconst [{openSearch}, {Constants}] = await Promise.all([import("../../../search/spread"),import("../../../constants"),]);- await openSearch({app, hotkey: Constants.DIALOG_GLOBALSEARCH, key: query});+ await openSearch({app, hotkey: Constants.DIALOG_GLOBALSEARCH, key: query, method});return {result: query ? `Opened search dialog with query "${query}".` : "Opened search dialog."};/// #elseconst [{popSearch}, {hideMobileAgent}] = await Promise.all([@@ -233,14 +249,7 @@ registerCapability({import("../../../mobile/agent/MobileAgentChat"),]);hideMobileAgent();- popSearch(app);- if (query) {- const input = document.getElementById("toolbarSearch") as HTMLInputElement | null;- if (input) {- input.value = query;- input.dispatchEvent(new InputEvent("input", {bubbles: true}));- }- }+ popSearch(app, undefined, false, {key: query, method});return {result: query ? `Opened mobile search with query "${query}".` : "Opened mobile search."};/// #endif},diff --git a/app/src/mobile/menu/search.ts b/app/src/mobile/menu/search.tsindex ea38014cfa..9bde92c65c 100644--- a/app/src/mobile/menu/search.ts+++ b/app/src/mobile/menu/search.ts@@ -3,6 +3,7 @@ import {updateSearchMethodControls} from "../../search/methodCapabilities";import {buildSearchRequest, refreshSearchConfigHPath} from "../../search/config";import {resolveCurrentSearchHPath} from "../../search/path";import {focusSearchInput} from "../../search/focus";+import {applySearchOpenOptions, SearchOpenOptions} from "../../search/openOptions";import {getAttr} from "../../search/attrs";import type {APICallbackResponse, APIPOSTRoutes} from "../../types/api";import {getCurrentEditor, openMobileFileById} from "../editor";@@ -67,7 +68,7 @@ const replace = (element: Element, config: Config.IUILayoutTabSearchConfig, isAlloadElement.nextElementSibling.classList.add("fn__none");const currentId = currentLiElement.getAttribute("data-node-id");fetchPost("/api/search/findReplace", {- k: config.method === 0 || config.method === 1 ? getKeyByLiElement(currentLiElement) : (document.querySelector("#toolbarSearch") as HTMLInputElement).value,+ k: config.method === 0 || config.method === 1 ? getKeyByLiElement(currentLiElement) : (document.querySelector("#toolbarSearch") as HTMLTextAreaElement).value,r: replaceInputElement.value,ids: isAll ? [] : [currentId],types: {...config.types},@@ -162,8 +163,8 @@ const updateConfig = (element: Element, newConfig: Config.IUILayoutTabSearchConf} else {searchIncludeElement.setAttribute("disabled", "disabled");}- if (newConfig.k || clear) {- (document.querySelector("#toolbarSearch") as HTMLInputElement).value = newConfig.k;+ if (newConfig.k !== undefined || clear) {+ (document.querySelector("#toolbarSearch") as HTMLTextAreaElement).value = newConfig.k;document.querySelector("#toolbarSearch").dispatchEvent(new Event("change"));}(element.querySelector("#toolbarReplace") as HTMLInputElement).value = newConfig.r;@@ -240,7 +241,7 @@ ${childItem.tag ? `<span class="b3-list-item__meta b3-list-item__meta--ellipsis"`<div class="b3-list-item b3-list-item--focus" data-type="search-new"><svg class="b3-list-item__graphic"><use xlink:href="#iconAddDoc"></use></svg><span class="b3-list-item__text">- ${window.siyuan.languages.newFile} <mark>${(document.querySelector("#toolbarSearch") as HTMLInputElement).value}</mark>+ ${window.siyuan.languages.newFile} <mark>${(document.querySelector("#toolbarSearch") as HTMLTextAreaElement).value}</mark></span></div>`;listElement.scrollTop = 0;@@ -301,7 +302,7 @@ export const updateSearchResult = (config: Config.IUILayoutTabSearchConfig, elemloadingElement.style.top = element.querySelector(".b3-list--background").getBoundingClientRect().top + "px";const previousElement = element.querySelector('[data-type="previous"]');const nextElement = element.querySelector('[data-type="next"]');- const inputElement = document.getElementById("toolbarSearch") as HTMLInputElement;+ const inputElement = document.getElementById("toolbarSearch") as HTMLTextAreaElement;config.query = inputElement.value;if (!config.page) {config.page = 1;@@ -362,8 +363,13 @@ export const updateSearchResult = (config: Config.IUILayoutTabSearchConfig, elemconst initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTabSearchConfig) => {let focusTimeout = 0;- const searchInputElement = document.getElementById("toolbarSearch") as HTMLInputElement;+ const searchInputElement = document.getElementById("toolbarSearch") as HTMLTextAreaElement;searchInputElement.value = config.k || "";+ searchInputElement.addEventListener("keydown", (event) => {+ if (event.key === "Enter" && config.method !== 2) {+ event.preventDefault();+ }+ });searchInputElement.addEventListener("compositionend", (event: InputEvent) => {if (event && event.isComposing) {return;@@ -770,7 +776,8 @@ const initSearchEvent = (app: App, element: Element, config: Config.IUILayoutTabreturn () => clearTimeout(focusTimeout);};-export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConfig, focusInput = false) => {+export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConfig, focusInput = false,+ options?: SearchOpenOptions) => {const config: Config.IUILayoutTabSearchConfig = JSON.parse(JSON.stringify(window.siyuan.storage[Constants.LOCAL_SEARCHDATA]));const currentEditor = getCurrentEditor();if (currentEditor && isEncryptedBox(currentEditor.protyle.notebookId)) {@@ -793,6 +800,9 @@ export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConf}});}+ if (options) {+ applySearchOpenOptions(config, options);+ }if (window.siyuan.isPublish) {config.hasReplace = false;@@ -817,7 +827,7 @@ export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConf<svg class="svg--mid"><use xlink:href="#iconSearch"></use></svg><svg class="svg--smaller"><use xlink:href="#iconDown"></use></svg></span>- <input id="toolbarSearch" placeholder="${window.siyuan.languages.showRecentUpdatedBlocks}" class="toolbar__title fn__block" autocomplete="off" autocorrect="off" spellcheck="false">+ <textarea id="toolbarSearch" rows="1" placeholder="${window.siyuan.languages.showRecentUpdatedBlocks}" class="toolbar__title fn__block search__input" autocomplete="off" autocorrect="off" spellcheck="false"></textarea><svg id="toolbarSearchNew" class="toolbar__icon"><use xlink:href="#iconAddDoc"></use></svg></div>`,html: `<div class="fn__flex-column" style="height: 100%">@@ -913,7 +923,7 @@ export const popSearch = (app: App, searchConfig?: Config.IUILayoutTabSearchConf},bindEvent(element) {document.querySelector("#toolbarSearchNew").addEventListener("click", () => {- newFile(app, (document.querySelector("#toolbarSearch") as HTMLInputElement).value);+ newFile(app, (document.querySelector("#toolbarSearch") as HTMLTextAreaElement).value);});const historyElement = document.querySelector('.toolbar [data-type="history"]');historyElement.addEventListener("click", () => {diff --git a/app/src/search/focus.ts b/app/src/search/focus.tsindex 1fb186c8cc..f26af78a14 100644--- a/app/src/search/focus.ts+++ b/app/src/search/focus.ts@@ -1,6 +1,6 @@import {isInIOS} from "../protyle/util/compatibility";-export const focusSearchInput = (input: HTMLInputElement) => {+export const focusSearchInput = (input: HTMLInputElement | HTMLTextAreaElement) => {const nativeComposition = isInIOS() && window.webkit?.messageHandlers.finishKeyboardComposition;if (nativeComposition) {const value = input.value;diff --git a/app/src/search/methodCapabilities.test.ts b/app/src/search/methodCapabilities.test.tsindex 411438ae5f..9605289a3a 100644--- a/app/src/search/methodCapabilities.test.ts+++ b/app/src/search/methodCapabilities.test.ts@@ -47,7 +47,9 @@ for (const mobile of [true, false]) {searchControlUnavailable: "unavailable", specifyPath: "path", searchType: "types", includeChildDoc: "children",filterCurrentDocument: "current document", replace: "replace", remove: "remove",}}} as unknown as Window & typeof globalThis;- globalThis.document = {querySelector: () => ({classList: {contains: () => true}})} as unknown as Document;+ const searchInput = {...control(), closest: (): null => null};+ globalThis.document = {querySelector: (selector: string) => selector === "#toolbarSearch" ? searchInput :+ {classList: {contains: () => true}}} as unknown as Document;try {const controls = new Map<string, ReturnType<typeof control>>();const row = {...control(), value: "replacement text"};@@ -74,6 +76,7 @@ for (const mobile of [true, false]) {config.method = 2;refresh();assert.equal(row.classes.has("fn__none"), true);+ assert.equal((mobile ? searchInput : controls.get("#searchInput")).classes.has("search__input--sql"), true);assert.equal(controls.get(filter).attributes["aria-disabled"], "true");assert.equal(controls.get(include).attributes["aria-disabled"], "true");assert.ok(controls.get(filter).attributes["aria-label"].endsWith("unavailable"));diff --git a/app/src/search/methodCapabilities.ts b/app/src/search/methodCapabilities.tsindex 5f5c805adf..f4c4df168d 100644--- a/app/src/search/methodCapabilities.ts+++ b/app/src/search/methodCapabilities.ts@@ -34,6 +34,12 @@ export const updateSearchMethodControls = (element: Element, config: Config.IUILmobile = false) => {const capabilities = getSearchMethodCapabilities(config.method, config.group);const language = window.siyuan.languages;+ const input = mobile ? document.querySelector("#toolbarSearch") : element.querySelector("#searchInput");+ input?.classList.toggle("search__input--sql", config.method === 2);+ if (mobile && input) {+ input.closest(".toolbar__search")?.classList.toggle("toolbar__search--sql", config.method === 2);+ input.closest(".toolbar__text")?.classList.toggle("toolbar__text--search-sql", config.method === 2);+ }const pathAvailable = capabilities.path;const includeAvailable = (config.idPath || []).some(path => path.split("/").length > 1);const controls: Array<[string, boolean, string, boolean]> = mobile ? [diff --git a/app/src/search/openOptions.ts b/app/src/search/openOptions.tsnew file mode 100644index 0000000000..6849196db5--- /dev/null+++ b/app/src/search/openOptions.ts@@ -0,0 +1,16 @@+export interface SearchOpenOptions {+ key?: string;+ method?: 0 | 1 | 2 | 3 | 4;+}++export const applySearchOpenOptions = (config: Config.IUILayoutTabSearchConfig, options: SearchOpenOptions) => {+ if (options.key !== undefined) {+ config.k = options.key;+ }+ if (options.method !== undefined) {+ config.method = options.method;+ }+ if (options.key !== undefined || options.method !== undefined) {+ config.page = 1;+ }+};diff --git a/app/src/search/spread.test.ts b/app/src/search/spread.test.tsnew file mode 100644index 0000000000..e08408c506--- /dev/null+++ b/app/src/search/spread.test.ts@@ -0,0 +1,61 @@+import {test} from "node:test";+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {applySearchOpenOptions} from "./openOptions";+import * as searchConfig from "./config";+import type {App} from "../index";++const compiled = transpileModule(readFileSync("src/search/spread.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++test("opening and reusing search applies explicit SQL query and method ahead of selected text", async () => {+ const saved = {k: "saved", method: 1, page: 5, hPath: "", idPath: [] as string[]};+ const dialogs: Array<{data: typeof saved, element: unknown, editors: unknown}> = [];+ const body = {querySelector: (): null => null};+ let hotkey = "global";+ let pathCallback: (data: {data: string[]}) => void;+ const element = {isConnected: true, setAttribute: (_name: string, value: string) => { hotkey = value; },+ getAttribute: () => hotkey, querySelector: (selector: string) => selector === "#searchList" ? {} : body};+ const editor = {protyle: {path: "/doc.sy", notebookId: "box"}};+ const api = {} as typeof import("./spread");+ runInNewContext(compiled, {exports: api, window: {siyuan: {storage: {search: saved}, dialogs}},+ getSelection: () => ({rangeCount: 1, getRangeAt: () => ({cloneRange: () => ({}), toString: () => "selection"})}),+ require: (name: string) => ({+ "../util/pathName": {getNotebookName: () => "box", pathPosix: () => ({join: (...parts: string[]) => parts.join("/")})},+ "../constants": {Constants: {LOCAL_SEARCHDATA: "search", DIALOG_GLOBALSEARCH: "global",+ DIALOG_SEARCH: "document", DIALOG_REPLACE: "replace"}},+ "../dialog": {Dialog: class {+ element = element;+ constructor() { dialogs.push(this as unknown as typeof dialogs[number]); }+ }},+ "../util/fetch": {fetchPost: (_url: string, _data: unknown, callback: typeof pathCallback) => { pathCallback = callback; }},+ "../protyle/util/selectionOffsets": {},+ "./util": {genSearch: () => ({edit: editor}),+ updateConfig: (_body: unknown, config: typeof saved) => config},+ "./request": {}, "./config": searchConfig,+ "./path": {beginSearchPathRequest: () => () => true},+ "../protyle/util/compatibility": {}, "./focus": {}, "./openOptions": {applySearchOpenOptions},+ })[name]});+ const app = {} as App;+ const sql = "-- first line\nSELECT * FROM blocks";+ await api.openSearch({app, hotkey: "global", key: sql, method: 2});+ assert.equal(dialogs[0].data.k, sql);+ assert.equal(dialogs[0].data.method, 2);+ assert.equal(dialogs[0].data.page, 1);+ await api.openSearch({app, hotkey: "global", key: "SELECT * FROM blocks WHERE type='p'", method: 2});+ assert.equal(dialogs.length, 1);+ assert.equal(dialogs[0].data.k, "SELECT * FROM blocks WHERE type='p'");+ await api.openSearch({app, hotkey: "document", key: sql, method: 2});+ pathCallback({data: ["/Document"]});+ assert.equal(dialogs[0].data.k, sql);+ assert.equal(dialogs[0].data.method, 2);+ await api.openSearch({app, hotkey: "global", key: "", method: 0});+ assert.equal(dialogs[0].data.k, "");+ assert.equal(dialogs[0].data.method, 0);+ await api.openSearch({app, hotkey: "global"});+ assert.equal(dialogs[0].data.method, 0);+ assert.equal(saved.k, "saved");+});diff --git a/app/src/search/spread.ts b/app/src/search/spread.tsindex f6affcdcde..c9bac3ef9a 100644--- a/app/src/search/spread.ts+++ b/app/src/search/spread.ts@@ -15,13 +15,13 @@ import {import {beginSearchPathRequest} from "./path";import {isDisabledFeature, isInIOS} from "../protyle/util/compatibility";import {focusSearchInput} from "./focus";+import {applySearchOpenOptions, SearchOpenOptions} from "./openOptions";let openSearchVersion = 0;-export const openSearch = async (options: {+export const openSearch = async (options: SearchOpenOptions & {app: App,hotkey: string,- key?: string,notebookId?: string,notebookIds?: string[],searchPath?: string,@@ -70,7 +70,7 @@ export const openSearch = async (options: {}const config = {removed: localData.removed,- k: options.key || localData.k,+ k: localData.k,r: localData.r,hasReplace: options.hotkey === Constants.DIALOG_REPLACE,method: localData.method === 4 && (isDisabledFeature("ai") || !window.siyuan.config.ai.embedding.enabled) ? 0 : localData.method,@@ -81,8 +81,9 @@ export const openSearch = async (options: {types: Object.assign({}, localData.types),subTypes: Object.assign({}, localData.subTypes),replaceTypes: Object.assign({}, localData.replaceTypes),- page: options.key ? 1 : localData.page+ page: localData.page};+ applySearchOpenOptions(config, options);setSearchConfigTemporaryPath(config, hasScopedPath || options.hotkey === Constants.DIALOG_SEARCH);// 搜索中继续执行 ctrl+F/P 不退出 https://github.com/siyuan-note/siyuan/issues/11637const exitDialog = window.siyuan.dialogs.find((item) => {@@ -97,6 +98,7 @@ export const openSearch = async (options: {if (selectText) {cloneData.k = selectText;}+ applySearchOpenOptions(cloneData, options);if (hasScopedPath) {setSearchConfigTemporaryPath(item.data, true);} else if (options.hotkey === Constants.DIALOG_GLOBALSEARCH) {@@ -139,6 +141,7 @@ export const openSearch = async (options: {if (selectText) {currentData.k = selectText;}+ applySearchOpenOptions(currentData, options);currentData.idPath = [pathPosix().join(toNotebook, toPath)];currentData.hPath = response.data[0];setSearchConfigTemporaryPath(item.data, true);diff --git a/app/src/search/util.ts b/app/src/search/util.tsindex 0842e2dbc9..173011e314 100644--- a/app/src/search/util.ts+++ b/app/src/search/util.ts@@ -190,7 +190,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, ele<svg data-menu="true" class="b3-form__icon-icon"><use xlink:href="#iconSearch"></use></svg><svg class="search__arrowdown"><use xlink:href="#iconDown"></use></svg></span>- <input id="searchInput" class="b3-text-field b3-text-field--text" placeholder="${window.siyuan.languages.showRecentUpdatedBlocks}" autocomplete="off" autocorrect="off" spellcheck="false">+ <textarea id="searchInput" rows="1" class="b3-text-field b3-text-field--text search__input" placeholder="${window.siyuan.languages.showRecentUpdatedBlocks}" autocomplete="off" autocorrect="off" spellcheck="false"></textarea></div><div class="block__icons"><span id="searchFilter" aria-label="${window.siyuan.languages.searchType}" class="block__icon ariaLabel" data-position="9south">@@ -287,7 +287,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, eleconst criteriaData: Config.IUILayoutTabSearchConfig[] = [];initCriteriaMenu(element.querySelector("#criteria"), criteriaData, config);const searchPanelElement = element.querySelector("#searchList");- const searchInputElement = element.querySelector("#searchInput") as HTMLInputElement;+ const searchInputElement = element.querySelector("#searchInput") as HTMLTextAreaElement;const replaceInputElement = element.querySelector("#replaceInput") as HTMLInputElement;const edit = new Protyle(app, element.querySelector("#searchPreview") as HTMLElement, {blockId: "",@@ -878,7 +878,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, eleif (isClick) {clickTimeout = window.setTimeout(() => {const activeElement = document.activeElement;- const shouldRestoreFocus = (inputElement: HTMLInputElement) =>+ const shouldRestoreFocus = (inputElement: HTMLInputElement | HTMLTextAreaElement) =>!activeElement || activeElement === document.body ||activeElement === inputElement || target.contains(activeElement);if (searchType === "asset") {@@ -987,6 +987,9 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, elesaveKeyList("keys", searchInputElement.value, config);});searchInputElement.addEventListener("keydown", (event) => {+ if (event.key === "Enter" && config.method !== 2) {+ event.preventDefault();+ }electronUndo(event);});replaceInputElement.addEventListener("keydown", (event) => {@@ -1188,8 +1191,8 @@ export const updateConfig = (element: Element, item: Config.IUILayoutTabSearchCo} else {searchIncludeElement.setAttribute("disabled", "disabled");}- if (runtimeConfig.k || options?.clear) {- (element.querySelector("#searchInput") as HTMLInputElement).value = runtimeConfig.k;+ if (runtimeConfig.k !== undefined || options?.clear) {+ (element.querySelector("#searchInput") as HTMLTextAreaElement).value = runtimeConfig.k;}(element.querySelector("#replaceInput") as HTMLInputElement).value = runtimeConfig.r;element.querySelector("#searchSyntaxCheck").outerHTML = genQueryHTML(runtimeConfig.method, "searchSyntaxCheck");@@ -1427,7 +1430,7 @@ export const replace = (element: Element, config: Config.IUILayoutTabSearchConfi}const searchPanelElement = element.querySelector("#searchList");const replaceInputElement = element.querySelector("#replaceInput") as HTMLInputElement;- const searchInputElement = element.querySelector("#searchInput") as HTMLInputElement;+ const searchInputElement = element.querySelector("#searchInput") as HTMLTextAreaElement;const loadElement = element.querySelector("svg.fn__rotate");if (!loadElement.classList.contains("fn__none")) {@@ -1489,7 +1492,7 @@ export const replace = (element: Element, config: Config.IUILayoutTabSearchConficonst emitBeforeSearchResultsRender = (blocks: IBlock[], edit: Protyle,config: Config.IUILayoutTabSearchConfig,- searchElement: HTMLInputElement) => {+ searchElement: HTMLTextAreaElement) => {const detail = {protyle: edit,config,@@ -1529,7 +1532,7 @@ export const inputEvent = (element: Element, config: Config.IUILayoutTabSearchCocreateTask(version) {const listElement = element.querySelector("#searchList") as HTMLElement;loadingElement.style.top = listElement.offsetTop + "px";- const searchInputElement = element.querySelector("#searchInput") as HTMLInputElement;+ const searchInputElement = element.querySelector("#searchInput") as HTMLTextAreaElement;config.query = searchInputElement.value;if (!config.page) {config.page = 1;@@ -1694,7 +1697,7 @@ ${countHTML}edit,id: currentData.id,config,- value: (element.querySelector("#searchInput") as HTMLInputElement).value,+ value: (element.querySelector("#searchInput") as HTMLTextAreaElement).value,matches: getSearchAVMatchesFromHTML(currentData.content),});} else {@@ -1705,7 +1708,7 @@ ${countHTML}config.method === 0 ? `<div class="b3-list-item b3-list-item--focus" data-type="search-new"><svg class="b3-list-item__graphic"><use xlink:href="#iconFile"></use></svg><span class="b3-list-item__text">- ${window.siyuan.languages.newFile} <mark>${escapeHtml((element.querySelector("#searchInput") as HTMLInputElement).value)}</mark>+ ${window.siyuan.languages.newFile} <mark>${escapeHtml((element.querySelector("#searchInput") as HTMLTextAreaElement).value)}</mark></span><kbd class="b3-list-item__meta">${window.siyuan.languages.enterNew}</kbd></div>diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex d778fb1431..ca43eaded9 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -58,6 +58,7 @@ const systemPrompt = `You are a SiYuan AI assistant. You help users manage their## Tool Usage Patterns- Find: search.fulltext (keyword) → block.get (by ID). For semantic search use search.semantic.+- Structural search: for block types, inline formats, ancestry or statistics, first fetch sql.schema, then use sql.query. To show matching blocks in the frontend, use native/frontend/open_search(query, method=2) with SELECT b.* FROM blocks b; use projections and aggregates only with sql.query.- Explore structure: document.list (children under an hPath) → document.get → block.get_children → block.get. Use block breadcrumb to trace a block's location.- Create content: document.create (notebook + hPath) → block.append/prepend/insert.- Modify: block.update replaces ONE block's content — it does NOT create or append new blocks. To both modify and add, call block.update first, then block.append/prepend/insert as separate calls.diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.goindex 8cd03e1293..b44680d94d 100644--- a/kernel/agent/tools_test.go+++ b/kernel/agent/tools_test.go@@ -374,6 +374,7 @@ func TestQueryToolActionEffects(t *testing.T) {needsConfirm bool}{{toolName: "sql", action: "query"},+ {toolName: "sql", action: "schema"},{toolName: "sql", action: ""},{toolName: "sql", action: "select"},{toolName: "search", action: "fulltext"},diff --git a/kernel/apicontract/search_query.go b/kernel/apicontract/search_query.goindex a63e81f26e..05e499bb69 100644--- a/kernel/apicontract/search_query.go+++ b/kernel/apicontract/search_query.go@@ -55,6 +55,8 @@ type SearchBlockRequest struct {}type FullTextSearchBlockRequest struct {+ // method=2 保留 SQL 原文的换行、注释和字面量大小写,结果需要返回完整块字段。+ // 支持 SELECT * 和带别名的完整块投影;普通类型与路径筛选不作用于 SQL。SearchBlockRequestNotebook string `json:"notebook" api:"optional,nullable,ignoretype"`SearchHPath *bool `json:"searchHPath" api:"optional"`diff --git a/kernel/mcp/tools/search_sql_fts5_test.go b/kernel/mcp/tools/search_sql_fts5_test.goindex fb8a2c9b46..b1f3e64194 100644--- a/kernel/mcp/tools/search_sql_fts5_test.go+++ b/kernel/mcp/tools/search_sql_fts5_test.go@@ -44,6 +44,7 @@ func TestSearchSQLQueries(t *testing.T) {isError bool}{{"projection", "SELECT id, type FROM blocks ORDER BY id LIMIT 3", "| row-1 | p |", false},+ {"line comments", "-- first comment\nWITH selected AS (SELECT * FROM blocks)\nSELECT * FROM selected -- preserve newline\nWHERE id='row-1'", "row-1", false},{"all columns", "SELECT * FROM blocks LIMIT 3", "row-1", false},{"aggregate", "SELECT count(*) AS total FROM blocks", "| 3 |", false},{"literal", "SELECT id FROM blocks WHERE hpath = '/中文ABC'", "| row-1 |", false},@@ -71,6 +72,19 @@ func TestSearchSQLQueries(t *testing.T) {}})}+ const blockID = "20261010120000-sqltest"+ if err := sql.Exec("INSERT INTO blocks VALUES ('" + blockID + "', '', '" + blockID + "', '', '', '', '', '', '', '', '', 'inline|text', '', '', 11, 'p', '', '', 0, '', '')"); err != nil {+ t.Fatal(err)+ }+ result, err := sqlHandler(map[string]any{"action": "query", "stmt": "SELECT id, content FROM blocks WHERE id='" + blockID + "'"})+ if err != nil || result.IsError || !result.HasStructuredContent() ||+ !strings.Contains(result.Content[0].Text, "siyuan://blocks/"+blockID) {+ t.Fatalf("SQL block links: %+v, %v", result, err)+ }+ output := result.StructuredContent.(map[string]any)+ if output["rowCount"] != 1 || output["rows"].([]map[string]any)[0]["content"] != "inline|text" {+ t.Fatalf("SQL structured rows: %+v", output)+ }const boxID = "20260915000000-mcpsql1"boxDir := filepath.Join(util.DataDir, boxID, ".siyuan")if err := os.MkdirAll(boxDir, 0755); err != nil {diff --git a/kernel/mcp/tools/sql.go b/kernel/mcp/tools/sql.goindex d7a37d081a..ae79ae9b5e 100644--- a/kernel/mcp/tools/sql.go+++ b/kernel/mcp/tools/sql.go@@ -21,6 +21,7 @@ import ("sort""strings"+ "github.com/88250/lute/ast""github.com/siyuan-note/siyuan/kernel/sql")@@ -28,20 +29,21 @@ const sqlQueryDefaultLimit = 100var SQLTool = &Tool{Name: "sql",- Description: "Read-only SQL on SiYuan's database. Action: query(stmt) — SELECT only. Results default to at most 100 rows; use explicit LIMIT and OFFSET clauses for pagination.",+ Description: "Read-only SQL on SiYuan's database. Actions: schema() for table definitions, type codes, hierarchy and search examples; query(stmt) for statistics, arbitrary projections and structural searches. Results include raw structured rows and verified block links. Results default to at most 100 rows; use explicit LIMIT and OFFSET for pagination. For the frontend SQL search interface, use SELECT b.* FROM blocks b to return complete block rows; ordinary search filters do not apply to SQL.",InputSchema: ToolSchema{Type: "object",Properties: map[string]Property{- "action": {Type: "string", Description: "Operation", Enum: []string{"query"}},+ "action": {Type: "string", Description: "Operation", Enum: []string{"query", "schema"}},"stmt": {Type: "string", Description: "SQL SELECT statement. Results default to at most 100 rows; use LIMIT and OFFSET for pagination"},"notebook": {Type: "string", Description: "Optional notebook ID used to query an encrypted notebook"},},- Required: []string{"action", "stmt"},+ Required: []string{"action"},},EffectScope: EffectScopeLocal,ActionEffects: map[string]ToolEffects{- "": {LocalRead: true},- "query": {LocalRead: true},+ "": {LocalRead: true},+ "query": {LocalRead: true},+ "schema": {LocalRead: true},},Handler: sqlHandler,}@@ -52,12 +54,15 @@ func init() {func sqlHandler(args map[string]any) (CallToolResult, error) {action, _ := args["action"].(string)+ if action == "schema" {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: sqlSchemaGuide}}}, nil+ }if action != "query" {if stmt, ok := args["stmt"].(string); ok && stmt != "" {return sqlQuery(args)}return CallToolResult{- Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected 'query'"}},+ Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected 'query' or 'schema'"}},IsError: true,}, nil}@@ -102,11 +107,64 @@ func sqlQuery(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "query failed: " + err.Error()}}, IsError: true}, nil}- if len(rows) == 0 {- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no results"}}}, nil- }+ return sqlQueryResult(rows, possiblyTruncated, boxID), nil+}- return CallToolResult{Content: []ContentItem{{Type: "text", Text: formatSQLRows(rows, possiblyTruncated)}}}, nil+func sqlQueryResult(rows []map[string]any, possiblyTruncated bool, boxID string) CallToolResult {+ if rows == nil {+ rows = []map[string]any{}+ }+ columns, candidateIDs := map[string]bool{}, map[string]bool{}+ for _, row := range rows {+ for column, value := range row {+ columns[column] = true+ if column == "id" || column == "block_id" || column == "root_id" || column == "parent_id" {+ if id, ok := value.(string); ok && ast.IsNodeIDPattern(id) {+ candidateIDs[id] = true+ }+ }+ }+ }+ columnNames, ids := []string{}, []string{}+ for column := range columns {+ columnNames = append(columnNames, column)+ }+ for id := range candidateIDs {+ ids = append(ids, id)+ }+ sort.Strings(columnNames)+ sort.Strings(ids)+ links := []map[string]string{}+ if len(ids) > 0 {+ var blocks []*sql.Block+ if boxID == "" {+ blocks = sql.GetBlocks(ids)+ } else {+ blocks = sql.GetBlocksInBox(ids, boxID)+ }+ for _, block := range blocks {+ if block != nil {+ links = append(links, map[string]string{"id": block.ID, "url": "siyuan://blocks/" + block.ID})+ }+ }+ }+ text := "no results"+ if len(rows) > 0 {+ text = formatSQLRows(rows, possiblyTruncated)+ }+ if len(links) > 0 {+ text += "\nBlocks:\n"+ for _, link := range links {+ text += "- [" + link["id"] + "](" + link["url"] + ")\n"+ }+ }+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: text}},+ StructuredContent: map[string]any{"rows": rows, "columns": columnNames,+ "rowCount": len(rows), "possiblyTruncated": possiblyTruncated, "defaultLimit": sqlQueryDefaultLimit,+ "blocks": links},+ StructuredContentSet: true,+ }}func formatSQLRows(rows []map[string]any, possiblyTruncated bool) string {@@ -124,7 +182,10 @@ func formatSQLRows(rows []map[string]any, possiblyTruncated bool) string {for _, row := range rows {vals := make([]string, 0, len(columns))for _, k := range columns {- vals = append(vals, fmt.Sprintf("%v", row[k]))+ value := fmt.Sprintf("%v", row[k])+ value = strings.ReplaceAll(value, "|", "\\|")+ value = strings.ReplaceAll(strings.ReplaceAll(value, "\r\n", "\n"), "\n", "<br>")+ vals = append(vals, value)}sb.WriteString("| " + strings.Join(vals, " | ") + " |\n")}diff --git a/kernel/mcp/tools/sql_schema.go b/kernel/mcp/tools/sql_schema.gonew file mode 100644index 0000000000..88a1b3403f--- /dev/null+++ b/kernel/mcp/tools/sql_schema.go@@ -0,0 +1,37 @@+package tools++// SQL 索引说明按需返回,不向每轮智能体系统提示词注入完整表结构。+const sqlSchemaGuide = `# SiYuan read-only SQL and search guide++Choose keyword search.fulltext for words; method=1 for query syntax, method=3 for regex, and search.semantic for meaning. Prefer SQL for block types, inline formatting, combined predicates, ancestry and aggregates. Use sql.query to inspect arbitrary columns or statistics; search.fulltext(method=2) delegates to it, ignoring page/pageSize, path/type/subtype/orderBy/groupBy filters. Express filters, ordering and LIMIT/OFFSET in SQL. The default limit is 100; explicit LIMIT and OFFSET paginate ordinary SQL. Encrypted notebook queries require the notebook parameter and an unlocked notebook, are isolated, and remain capped at 100 rows. Never use SQL to mutate indexes.++To show blocks in the frontend, call native/frontend/open_search with method=2 and a query returning complete block rows (SELECT b.* FROM blocks b). Projections and aggregates belong in sql.query, not the search window. Newlines terminate -- comments; preserve them. Query results include original rows, columns, rowCount, defaultLimit, possiblyTruncated and verified blocks {id,url}. A possible truncation warning is conservative, not a total count. URLs use siyuan://blocks/ID; retrieve full content with block.get.++## Indexed tables+- blocks(id, parent_id, root_id, hash, box, path, hpath, name, alias, memo, tag, content, fcontent, markdown, length, type, subtype, ial, sort, created, updated): id is a block ID; parent_id is the immediate container block; root_id is its document ID (document id=root_id). box is the notebook ID. path is an internal ID-based document path; hpath is the title path. content is searchable plain text, markdown is formatted Markdown, fcontent is the first child content used for containers. Containers can aggregate descendant content: select leaf types to avoid duplicate matches. ial is serialized block attributes; created/updated are YYYYMMDDHHMMSS strings, sort is sibling ordering. Headings are leaf siblings, not parents of following sections.+- spans(id, block_id, root_id, box, path, content, markdown, type, ial): indexed inline elements. id is an index record ID, NOT an addressable block; join block_id=blocks.id. Images use type='img'; formatted text uses space-separated tokens beginning with 'textmark', e.g. 'textmark code', 'textmark strong code', 'textmark tag', 'textmark a', 'textmark block-ref'. Match tokens with (' ' || type || ' ') LIKE '% code %', not equality, when combined formats should match. Ordinary plain text is not a code span. content is the inline plain text; markdown preserves formatting.+- attributes(id, name, value, type, block_id, root_id, box, path): indexed named attributes; type='b' for blocks, 's' for spans. Join block_id for ownership; not every IAL attribute is indexed.+- assets(id, block_id, root_id, box, docpath, path, name, title, hash): asset references; path is the asset path and docpath is the internal document path.++## Stored block type codes+d document; p paragraph; h heading; l list; i list item; c code block; m math block; t table; b blockquote; s super block; html HTML; query_embed block query embed; av attribute view; iframe iframe; widget widget; tb thematic break; video video; audio audio; custom custom block; callout callout; tabs tabs; tab tab item; mindmap mind map; mindmap_item mind map item. subtype: headings h1..h6; lists/items and mind maps/items u unordered, o ordered, t task; other types usually empty. SQL codes differ from AST names such as NodeParagraph.++## Examples+Statistics: SELECT type, count(*) AS total FROM blocks GROUP BY type ORDER BY total DESC+Type and pagination: SELECT b.* FROM blocks b WHERE b.type='h' AND b.subtype='h2' ORDER BY b.updated DESC, b.id LIMIT 100 OFFSET 0+Direct children: SELECT b.* FROM blocks b WHERE b.parent_id='PARENT_BLOCK_ID' ORDER BY b.sort, b.id LIMIT 100+Inline code within any list ancestor (strict format check, one result per paragraph):++WITH RECURSIVE in_list(id) AS (+ SELECT id FROM blocks WHERE type='l'+ UNION+ SELECT b.id FROM blocks b JOIN in_list i ON b.parent_id=i.id+)+SELECT b.* FROM blocks b+WHERE b.type='p' AND b.id IN (SELECT id FROM in_list)+ AND EXISTS (SELECT 1 FROM spans s WHERE s.block_id=b.id+ AND (' ' || s.type || ' ') LIKE '% code %' AND s.content='fullscreen=1')+ORDER BY b.id LIMIT 100 OFFSET 0++Use EXISTS rather than a plain JOIN when multiple matching spans should produce only one block. Quote SQL string literals with single quotes and double any embedded single quote. Use UNION in recursive ancestry queries to deduplicate and bound revisits. Filter notebook/paths directly in SQL, for example b.box='NOTEBOOK_ID' or b.hpath LIKE '/Diary/%'.+`diff --git a/kernel/mcp/tools/sql_test.go b/kernel/mcp/tools/sql_test.goindex 1be78a61c3..a65fe0e9c3 100644--- a/kernel/mcp/tools/sql_test.go+++ b/kernel/mcp/tools/sql_test.go@@ -52,3 +52,37 @@ func TestFormatSQLRowsReportsPossibleTruncation(t *testing.T) {t.Fatalf("missing SQL result truncation warning:\n%s", got)}}++func TestSQLSchemaActionAndEmptyStructuredResult(t *testing.T) {+ validator, err := CompileToolValidator(SQLTool)+ if err != nil {+ t.Fatal(err)+ }+ if err = validator.ValidateInput(map[string]any{"action": "schema"}); err != nil {+ t.Fatalf("schema must not require stmt: %v", err)+ }+ result, err := sqlHandler(map[string]any{"action": "schema"})+ if err != nil || result.IsError || len(result.Content) != 1 {+ t.Fatalf("schema result: %+v, %v", result, err)+ }+ for _, text := range []string{"spans", "parent_id", "textmark code", "WITH RECURSIVE", "SELECT b.*", "LIMIT/OFFSET"} {+ if !strings.Contains(result.Content[0].Text, text) {+ t.Fatalf("schema missing %q", text)+ }+ }+ empty := sqlQueryResult(nil, false, "")+ output := empty.StructuredContent.(map[string]any)+ if empty.Content[0].Text != "no results" || output["rows"] == nil || output["rowCount"] != 0 {+ t.Fatalf("empty SQL result: %+v", empty)+ }+}++func TestSQLResultPreservesRawValuesAndEscapesTable(t *testing.T) {+ rows := []map[string]any{{"text": "a|b\nc", "total": int64(4)}}+ result := sqlQueryResult(rows, false, "")+ output := result.StructuredContent.(map[string]any)+ if output["rows"].([]map[string]any)[0]["text"] != "a|b\nc" ||+ !strings.Contains(result.Content[0].Text, "a\\|b<br>c") {+ t.Fatalf("SQL values were corrupted: %+v", result)+ }+}diff --git a/kernel/model/search.go b/kernel/model/search.goindex f5c41580ce..108dd63d57 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -1635,7 +1635,9 @@ func FullTextSearchBlock(options BlockSearchOptions) (ret []*Block, matchedBlockreturn}- query = filterQueryInvisibleChars(query)+ if method != 2 {+ query = filterQueryInvisibleChars(query)+ }if 2 != method && 3 != method && ast.IsNodeIDPattern(query) && isHiddenBoxDocBlock(query, boxID) {return}@@ -2205,13 +2207,15 @@ func searchBySQLInBoxContext(ctx context.Context, stmt string, beforeLen, page,return}- stmt = strings.ToLower(stmt)- stdQuery := !strings.Contains(stmt, "with recursive") && !strings.Contains(stmt, "union")+ // 仅改写已知投影的前缀,保留条件中的大小写、注释和完整块查询的别名。+ lowerStmt := strings.ToLower(stmt)+ stdQuery := !strings.Contains(lowerStmt, "union") &&+ (strings.HasPrefix(lowerStmt, "select * ") || strings.HasPrefix(lowerStmt, "select a.* "))if stdQuery {- if strings.HasPrefix(stmt, "select a.* ") { // 多个搜索关键字匹配文档 https://github.com/siyuan-note/siyuan/issues/7350- stmt = strings.ReplaceAll(stmt, "select a.* ", "select COUNT(a.id) AS `matches`, COUNT(DISTINCT(a.root_id)) AS `docs` ")+ if strings.HasPrefix(lowerStmt, "select a.* ") {+ stmt = "SELECT COUNT(a.id) AS `matches`, COUNT(DISTINCT(a.root_id)) AS `docs` " + stmt[len("select a.* "):]} else {- stmt = strings.ReplaceAll(stmt, "select * ", "select COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` ")+ stmt = "SELECT COUNT(id) AS `matches`, COUNT(DISTINCT(root_id)) AS `docs` " + stmt[len("select * "):]}}stmt = removeLimitClause(stmt)@@ -2226,8 +2230,13 @@ func searchBySQLInBoxContext(ctx context.Context, stmt string, beforeLen, page,if !stdQuery {var rootIDs, blockIDs []stringfor _, queryResult := range result {- rootIDs = append(rootIDs, queryResult["root_id"].(string))- blockIDs = append(blockIDs, queryResult["id"].(string))+ rootID, hasRoot := queryResult["root_id"].(string)+ blockID, hasID := queryResult["id"].(string)+ if !hasRoot || !hasID {+ return ret, 0, 0+ }+ rootIDs = append(rootIDs, rootID)+ blockIDs = append(blockIDs, blockID)}rootIDs = gulu.Str.RemoveDuplicatedElem(rootIDs)blockIDs = gulu.Str.RemoveDuplicatedElem(blockIDs)diff --git a/kernel/model/search_sql_comments_test.go b/kernel/model/search_sql_comments_test.gonew file mode 100644index 0000000000..d244aef0d6--- /dev/null+++ b/kernel/model/search_sql_comments_test.go@@ -0,0 +1,57 @@+//go:build fts5++package model++import (+ "os"+ "os/exec"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestSQLSearchPreservesCommentsAndLiteralCase(t *testing.T) {+ const childEnv = "SIYUAN_TEST_SQL_SEARCH_COMMENTS"+ if os.Getenv(childEnv) != "1" {+ cmd := exec.Command(os.Args[0], "-test.run=^TestSQLSearchPreservesCommentsAndLiteralCase$", "-test.timeout=30s")+ cmd.Env = append(os.Environ(), childEnv+"=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("SQL search regression failed: %v\n%s", err, output)+ }+ return+ }+ util.TempDir, util.DataDir = t.TempDir(), t.TempDir()+ util.QueueDir = filepath.Join(util.TempDir, "queue")+ util.DBPath = filepath.Join(util.TempDir, "siyuan.db")+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")+ Conf = NewAppConf()+ Conf.Search, Conf.FileTree = conf.NewSearch(), conf.NewFileTree()+ sql.InitDatabase(true)+ sql.InitHistoryDatabase(true)+ sql.InitAssetContentDatabase(true)+ t.Cleanup(sql.CloseDatabase)+ const id = "20261010120000-sqltest"+ if err := sql.Exec("INSERT INTO blocks VALUES ('" + id + "', '', '" + id + "', '', '', '', '/Document', '', '', '', '', 'ABC', '', 'ABC', 3, 'p', '', '', 0, '20261010120000', '20261010120000')"); err != nil {+ t.Fatal(err)+ }+ for _, stmt := range []string{+ "SELECT * FROM blocks WHERE content='ABC'",+ "SELECT b.* FROM blocks b WHERE b.content='ABC'",+ "-- first comment\nSELECT b.* FROM blocks b -- second comment\nWHERE b.content='ABC'",+ "WITH RECURSIVE selected(id) AS (SELECT id FROM blocks WHERE content='ABC')\nSELECT b.* FROM blocks b JOIN selected s ON s.id=b.id -- trailing comment",+ } {+ t.Run(stmt, func(t *testing.T) {+ blocks, count, roots, pages, _ := FullTextSearchBlock(BlockSearchOptions{+ Query: stmt, Method: 2, Page: 1, PageSize: 10,+ })+ if len(blocks) != 1 || blocks[0].ID != id || count != 1 || roots != 1 || pages != 1 {+ t.Fatalf("SQL search returned blocks=%+v, count=%d roots=%d pages=%d", blocks, count, roots, pages)+ }+ })+ }+}