An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Open asset links with URL fragments in tabs and file actions https://github.com/siyuan-note/siyuan/issues/20961
Weidong Qi481044b30f25
diff --git a/app/src/asset/index.test.ts b/app/src/asset/index.test.tsnew file mode 100644index 0000000000..8edce89357--- /dev/null+++ b/app/src/asset/index.test.ts@@ -0,0 +1,76 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import * as path from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import * as escape from "../util/escape";+import * as mergePathSegments from "../util/mergePathSegments";++type Flags = {MOBILE: boolean; BROWSER: boolean};++const compile = (file: string, flags: Flags) => transpileModule(require("ifdef-loader/preprocessor").parse(+ readFileSync(file, "utf8"), flags, false, true), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const loadAsset = (flags: Flags) => {+ const window = {siyuan: {config: {fileTree: {}}, languages: {}}};+ const document = {getElementById: (id: string) => id === "baseURL" ? {getAttribute: () => "http://127.0.0.1:6806"} : null};+ const load = (file: string, modules: Record<string, unknown> = {}) => {+ const exports: Record<string, any> = {};+ runInNewContext(compile(file, flags), {exports, window, document, navigator: {userAgent: ""},+ SIYUAN_VERSION: "dev", NODE_ENV: "development",+ require: (id: string) => modules[id] ?? (id === "path" ? path : {})});+ return exports;+ };+ const pathName = load("src/util/pathName.ts", {"./mergePathSegments": mergePathSegments, "./escape": escape});+ const constants = load("src/constants.ts");+ const assetModule = load("src/asset/index.ts", {+ "../util/pathName": pathName,+ "../util/escape": escape,+ "../constants": constants,+ "../layout/Model": {Model: class {}},+ });+ const titles: string[] = [];+ const asset = Object.create(assetModule.Asset.prototype);+ Object.assign(asset, {+ element: {innerHTML: ""},+ parent: {updateTitle: (title: string) => titles.push(title)},+ pdfLoadState: {isDestroyed: false, clearPending() {}},+ });+ return {asset, titles};+};++for (const {name, flags} of [+ {name: "desktop", flags: {MOBILE: false, BROWSER: false}},+ {name: "browser", flags: {MOBILE: false, BROWSER: true}},+ {name: "mobile", flags: {MOBILE: true, BROWSER: true}},+]) {+ test(`asset tabs render media whose links carry queries or fragments (${name})`, () => {+ const {asset} = loadAsset(flags);+ for (const [assetPath, tag] of [+ ["assets/image.png", "img"],+ ["assets/image.png#preview", "img"],+ ["assets/image.png?v=1.2", "img"],+ ["assets/image.png?box=20260101000000-abcdefg#preview", "img"],+ ["assets/video.mp4#t=10", "video"],+ ["assets/song.MP3#t=30", "audio"],+ ]) {+ asset.path = assetPath;+ asset.element.innerHTML = "";+ asset.render();+ assert.match(asset.element.innerHTML, new RegExp(`^<div class="asset"><${tag} `), assetPath);+ // src 保留原始路径,以便内核读取 box 参数、浏览器按 #t= 定位媒体+ assert.ok(asset.element.innerHTML.includes(`src="http://127.0.0.1:6806/${assetPath}"`), assetPath);+ }+ });++ test(`asset tab titles omit queries and fragments (${name})`, () => {+ const {asset, titles} = loadAsset(flags);+ for (const assetPath of ["assets/image-20260101000000-abcdefg.png#preview", "assets/image-20260101000000-abcdefg.png?v=1.2"]) {+ asset.update(assetPath);+ }+ assert.deepEqual(titles, ["image-20260101000000-abcdefg.png", "image-20260101000000-abcdefg.png"]);+ });+}diff --git a/app/src/asset/index.ts b/app/src/asset/index.tsindex cf0754bc5e..d6ede3ccd7 100644--- a/app/src/asset/index.ts+++ b/app/src/asset/index.ts@@ -16,7 +16,7 @@ import {fetchPost} from "../util/fetch";import {bindPdfTheme} from "./pdfViewer";import type {App} from "../index";import {clearOBG} from "../layout/dock/util";-import {getDisplayName} from "../util/pathName";+import {getAssetExtension, getAssetPathWithoutQuery, getDisplayName} from "../util/pathName";import {PdfLoadState} from "./pdfLoadState";import {getPdfViewerHTML} from "./pdf/viewerTemplate";import {forEachPluginSubscriber} from "../plugin/EventBusCore";@@ -57,7 +57,7 @@ export class Asset extends Model {public update(path: string) {this.path = path;- this.parent.updateTitle(getDisplayName(path));+ this.parent.updateTitle(getDisplayName(getAssetPathWithoutQuery(path)));this.render(false);}@@ -109,7 +109,8 @@ export class Asset extends Model {void this.pdfObject.destroy();this.pdfObject = undefined;}- const type = this.path.substr(this.path.lastIndexOf(".")).toLowerCase().split("?")[0];+ // 类型按去掉查询和片段后的文件名判断,src 仍使用原始路径,以保留 box 参数和 #t= 等媒体片段+ const type = getAssetExtension(this.path).toLowerCase();// 对资源路径进行 HTML 转义后再拼入 src 属性,避免路径中包含 " 等字符导致属性逃逸引发 XSSconst src = escapeHtmlTextAndAttr(this.path.startsWith("file") ? this.path : document.getElementById("baseURL").getAttribute("href") + "/" + this.path);if (Constants.SIYUAN_ASSETS_IMAGE.includes(type)) {diff --git a/app/src/boot/globalEvent/command/global.test.ts b/app/src/boot/globalEvent/command/global.test.tsnew file mode 100644index 0000000000..585de3edbd--- /dev/null+++ b/app/src/boot/globalEvent/command/global.test.ts@@ -0,0 +1,64 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import * as path from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import * as escape from "../../../util/escape";+import * as mergePathSegments from "../../../util/mergePathSegments";++type Flags = {MOBILE: boolean; BROWSER: boolean};++const compile = (file: string, flags: Flags) => transpileModule(require("ifdef-loader/preprocessor").parse(+ readFileSync(file, "utf8"), flags, false, true), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const reopenClosedAsset = (flags: Flags, assetPath: string) => {+ const requests: Array<{url: string; data: {path: string}}> = [];+ const opened: Array<{assetPath: string; page: unknown}> = [];+ const window = {siyuan: {storage: {} as Record<string, unknown[]>}};+ const recorder = new Proxy({}, {get: (_target, name) => name === "__esModule" ? undefined : (): undefined => undefined});+ const load = (file: string, modules: Record<string, unknown> = {}) => {+ const exports: Record<string, any> = {};+ runInNewContext(compile(file, flags), {exports, window, navigator: {userAgent: ""},+ SIYUAN_VERSION: "dev", NODE_ENV: "development",+ require: (id: string) => modules[id] ?? (id === "path" ? path : recorder)});+ return exports;+ };+ const pathName = load("src/util/pathName.ts", {"./mergePathSegments": mergePathSegments, "./escape": escape});+ const constants = load("src/constants.ts");+ const global = load("src/boot/globalEvent/command/global.ts", {+ "../../../util/pathName": pathName,+ "../../../constants": constants,+ "../../../protyle/util/compatibility": {sanitizeClosedTabs: (tabs: unknown[]) => tabs, setStorageVal() {}},+ "../../../editor/util": {openFile: (options: {assetPath: string; page: unknown}) => opened.push(options)},+ "../../../util/fetch": {+ fetchPost: (url: string, data: {path: string}, callback: (response: {code: number}) => void) => {+ requests.push({url, data});+ callback({code: 0});+ },+ },+ });+ window.siyuan.storage[constants.Constants.LOCAL_CLOSED_TABS] = [{children: {instance: "Asset", path: assetPath, page: 3}}];+ assert.equal(global.globalCommand("recentClosed", {}), true);+ return {requests, opened};+};++for (const {name, flags} of [+ {name: "desktop", flags: {MOBILE: false, BROWSER: false}},+ {name: "browser", flags: {MOBILE: false, BROWSER: true}},+]) {+ test(`reopening a closed asset tab checks the file without its URL fragment (${name})`, () => {+ for (const [assetPath, statPath] of [+ ["assets/image.png", "assets/image.png"],+ ["assets/video.mp4#t=10", "assets/video.mp4"],+ ["assets/image.png?box=20260101000000-abcdefg#preview", "assets/image.png?box=20260101000000-abcdefg"],+ ]) {+ const {requests, opened} = reopenClosedAsset(flags, assetPath);+ assert.deepEqual(requests.map(request => [request.url, request.data.path]), [["/api/asset/statAsset", statPath]], assetPath);+ // 重新打开时仍使用原始路径,保留媒体片段+ assert.deepEqual(opened.map(options => [options.assetPath, options.page]), [[assetPath, 3]], assetPath);+ }+ });+}diff --git a/app/src/boot/globalEvent/command/global.ts b/app/src/boot/globalEvent/command/global.tsindex f5f50840dd..977c12712f 100644--- a/app/src/boot/globalEvent/command/global.ts+++ b/app/src/boot/globalEvent/command/global.ts@@ -40,6 +40,7 @@ import {openCard} from "../../../card/openCard";import {syncGuide} from "../../../sync/syncGuide";import {unsplitCurrentWnd, unsplitWnd} from "../../../menus/tab";import {openFile} from "../../../editor/util";+import {getAssetPathWithoutFragment} from "../../../util/pathName";import {fetchPost} from "../../../util/fetch";import {sanitizeClosedTabs, setStorageVal} from "../../../protyle/util/compatibility";import {adjustEditorFontSize} from "../../../util/editorFontSize";@@ -186,7 +187,8 @@ export const globalCommand = (command: string, app: App, range?: Range, openOnlyreturn true;}if (childData.instance === "Asset") {- fetchPost("/api/asset/statAsset", {path: childData.path}, (response) => {+ // 内核按文件名检查资源,需先去掉片段;重新打开时仍使用原始路径,保留 #t= 等媒体片段+ fetchPost("/api/asset/statAsset", {path: getAssetPathWithoutFragment(childData.path)}, (response) => {if (response.code !== 1) {openFile({app,diff --git a/app/src/editor/pdfAssetLink.test.ts b/app/src/editor/pdfAssetLink.test.tsindex 12b4a5c4f8..8e474eaeee 100644--- a/app/src/editor/pdfAssetLink.test.ts+++ b/app/src/editor/pdfAssetLink.test.ts@@ -84,6 +84,16 @@ describe("PDF asset link resolution", () => {});});+ it("drops fragments from box-scoped PDFs and keeps media fragments of other assets", () => {+ assert.deepEqual(resolvePdfAssetLink("assets/document.pdf?box=20260101000000-abcdefg#page=3"), {+ linkAddress: "assets/document.pdf?box=20260101000000-abcdefg",+ pdfParams: undefined,+ });+ assert.deepEqual(resolvePdfAssetLink("assets/video.mp4#t=10"), {+ linkAddress: "assets/video.mp4#t=10",+ });+ });+it("leaves non-PDF and non-asset links unchanged", () => {assert.deepEqual(resolvePdfAssetLink("assets/document.txt?page=2"), {linkAddress: "assets/document.txt?page=2",diff --git a/app/src/editor/util.test.ts b/app/src/editor/util.test.tsnew file mode 100644index 0000000000..7e1f1e909e--- /dev/null+++ b/app/src/editor/util.test.ts@@ -0,0 +1,55 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import * as path from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import * as escape from "../util/escape";+import * as mergePathSegments from "../util/mergePathSegments";++const compile = (file: string) => transpileModule(require("ifdef-loader/preprocessor").parse(+ readFileSync(file, "utf8"), {MOBILE: false, BROWSER: false}, false, true), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const loadOpenBy = () => {+ const calls: Array<{name: string; args: unknown[]}> = [];+ const window = {siyuan: {config: {system: {os: "darwin"}}, languages: {}, notebooks: [] as unknown[]},+ location: {origin: "http://127.0.0.1:6806"}};+ // 未显式提供的依赖统一替换为记录调用的空函数+ const recorder = new Proxy({}, {+ get: (_target, name) => typeof name === "string" && name !== "__esModule" ?+ (...args: unknown[]) => {+ calls.push({name, args});+ return name === "getHostCapabilities" ? {localFileSystem: true} : undefined;+ } : undefined,+ });+ const load = (file: string, modules: Record<string, unknown> = {}) => {+ const exports: Record<string, any> = {};+ runInNewContext(compile(file), {exports, window, navigator: {userAgent: ""}, URL,+ SIYUAN_VERSION: "dev", NODE_ENV: "development",+ require: (id: string) => modules[id] ?? (id === "path" ? path : recorder)});+ return exports;+ };+ const pathName = load("src/util/pathName.ts", {"./mergePathSegments": mergePathSegments, "./escape": escape});+ const util = load("src/editor/util.ts", {"../util/pathName": pathName});+ return {openBy: util.openBy, calls};+};++test("opening assets externally resolves them without URL fragments", () => {+ const {openBy, calls} = loadOpenBy();+ for (const [url, expected] of [+ ["assets/video.mp4#t=10", "assets/video.mp4"],+ ["assets/image.png?box=20260101000000-abcdefg#preview", "assets/image.png?box=20260101000000-abcdefg"],+ ["assets/document.pdf?page=3#view", "assets/document.pdf"],+ ["assets/image%23copy.png", "assets/image%23copy.png"],+ ]) {+ for (const type of ["app", "folder"] as const) {+ calls.length = 0;+ openBy(url, type);+ const request = calls.find(call => call.name === "fetchPost");+ assert.equal(request?.args[0], "/api/asset/resolveAssetPath", url);+ assert.equal((request?.args[1] as {path: string}).path, expected, `${url} ${type}`);+ }+ }+});diff --git a/app/src/editor/util.ts b/app/src/editor/util.tsindex fbc901069d..5194e337aa 100644--- a/app/src/editor/util.ts+++ b/app/src/editor/util.ts@@ -7,7 +7,15 @@ import {getInstanceById, getWndByLayout, newModelByInitData, pdfIsLoading, setPaimport {getDockByType} from "../layout/tabUtil";import {getAllModels, getAllTabs} from "../layout/getAll";import {highlightById, scrollCenter} from "../util/highlightById";-import {getAssetExtension, getDisplayName, getDocDisplayName, isEncryptedBox, useShell} from "../util/pathName";+import {+ getAssetExtension,+ getAssetPathWithoutFragment,+ getAssetPathWithoutQuery,+ getDisplayName,+ getDocDisplayName,+ isEncryptedBox,+ useShell+} from "../util/pathName";import {Constants} from "../constants";import {Files} from "../layout/dock/Files";import {fetchPost, fetchSyncPost} from "../util/fetch";@@ -622,7 +630,7 @@ export const newTab = (options: IOpenFileOptions, afterInitProtyle?: Constructor}tab = new Tab({icon,- title: getDisplayName(options.assetPath),+ title: getDisplayName(getAssetPathWithoutQuery(options.assetPath)),callback(tab) {tab.addModel(new Asset({app: options.app,@@ -943,7 +951,10 @@ export const openBy = (url: string, type: "folder" | "app") => {/// #if !BROWSERif (url.startsWith("assets/")) {const open = () => {- fetchPost("/api/asset/resolveAssetPath", {path: url.replace(/\.pdf\?page=\d{1,}$/, ".pdf")}, (response) => {+ // 内核按文件名解析资源,需先去掉片段;查询中的 box 参数用于定位加密笔记本中的资源+ fetchPost("/api/asset/resolveAssetPath", {+ path: getAssetPathWithoutFragment(url).replace(/\.pdf\?page=\d{1,}$/, ".pdf")+ }, (response) => {if (type === "app") {useShell("openPath", response.data);} else if (type === "folder") {diff --git a/app/src/menus/commonMenuItem.test.ts b/app/src/menus/commonMenuItem.test.tsnew file mode 100644index 0000000000..5b32f6df8f--- /dev/null+++ b/app/src/menus/commonMenuItem.test.ts@@ -0,0 +1,83 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import * as path from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import * as escape from "../util/escape";+import * as mergePathSegments from "../util/mergePathSegments";+import * as imageURL from "../util/imageURL";+import * as pdfAssetLink from "../editor/pdfAssetLink";++type Flags = {MOBILE: boolean; BROWSER: boolean};++const compile = (file: string, flags: Flags) => transpileModule(require("ifdef-loader/preprocessor").parse(+ readFileSync(file, "utf8"), flags, false, true), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const loadOpenMenu = (flags: Flags) => {+ const calls: Array<{name: string; args: unknown[]}> = [];+ const window = {siyuan: {config: {editor: {}, fileTree: {}}, languages: {}}};+ // 未显式提供的依赖统一替换为记录调用的空函数+ const recorder = new Proxy({}, {+ get: (_target, name) => typeof name === "string" && name !== "__esModule" ?+ (...args: unknown[]) => {+ calls.push({name, args});+ return name === "getHostCapabilities" ? {localFileSystem: true} : undefined;+ } : undefined,+ });+ const load = (file: string, modules: Record<string, unknown> = {}) => {+ const exports: Record<string, any> = {};+ runInNewContext(compile(file, flags), {exports, window, navigator: {userAgent: ""},+ SIYUAN_VERSION: "dev", NODE_ENV: "development", URL, URLSearchParams,+ require: (id: string) => modules[id] ?? (id === "path" ? path : recorder)});+ return exports;+ };+ const pathName = load("src/util/pathName.ts", {"./mergePathSegments": mergePathSegments, "./escape": escape});+ const constants = load("src/constants.ts", {});+ const menu = load("src/menus/commonMenuItem.ts", {+ "../util/pathName": pathName,+ "../constants": constants,+ "../util/imageURL": imageURL,+ "../editor/pdfAssetLink": pdfAssetLink,+ });+ return {openMenu: menu.openMenu, calls};+};++const app = {};++for (const {name, flags, newWindow} of [+ {name: "desktop", flags: {MOBILE: false, BROWSER: false}, newWindow: true},+ {name: "browser", flags: {MOBILE: false, BROWSER: true}, newWindow: false},+]) {+ test(`asset menu opens PDFs without fragments and passes the page separately (${name})`, () => {+ const {openMenu, calls} = loadOpenMenu(flags);+ const submenu = openMenu(app, " assets/document.pdf?box=20260101000000-abcdefg&page=3#view ", true, false);+ const opened = (id: string) => {+ calls.length = 0;+ submenu.find((item: {id: string}) => item.id === id).click();+ return calls.filter(call => call.name.startsWith("openAsset"));+ };+ const pdfPath = "assets/document.pdf?box=20260101000000-abcdefg";+ assert.deepEqual(opened("openBy"), [{name: "openAsset", args: [app, pdfPath, 3]}]);+ assert.deepEqual(opened("insertRight"), [{name: "openAsset", args: [app, pdfPath, 3, "right"]}]);+ assert.deepEqual(opened("insertBottom"), [{name: "openAsset", args: [app, pdfPath, 3, "bottom"]}]);+ assert.deepEqual(opened("openByBackground"), [{name: "openAssetInBackground", args: [app, pdfPath, 3]}]);+ if (newWindow) {+ // 窗口选项对象创建于 vm 上下文中,原型不同,按 JSON 比较+ assert.equal(JSON.stringify(opened("openByNewWindow")),+ JSON.stringify([{name: "openAssetNewWindow", args: [pdfPath, {}, 3]}]));+ } else {+ assert.equal(submenu.some((item: {id: string}) => item.id === "openByNewWindow"), false);+ }+ });++ test(`asset menu keeps media fragments when opening in a tab (${name})`, () => {+ const {openMenu, calls} = loadOpenMenu(flags);+ const submenu = openMenu(app, "assets/video.mp4#t=10", true, false);+ submenu.find((item: {id: string}) => item.id === "openBy").click();+ assert.deepEqual(calls.filter(call => call.name === "openAsset"),+ [{name: "openAsset", args: [app, "assets/video.mp4#t=10", undefined]}]);+ });+}diff --git a/app/src/menus/commonMenuItem.ts b/app/src/menus/commonMenuItem.tsindex 7076a680f9..46233582a7 100644--- a/app/src/menus/commonMenuItem.ts+++ b/app/src/menus/commonMenuItem.ts@@ -1,7 +1,7 @@import {toggleMenu} from "./menuToggle";import type {BlockQueryRequestInput} from "../types/api";import {confirmDialog} from "../dialog/confirmDialog";-import {getSearch, isMobile, isValidCustomAttrName} from "../util/functions";+import {isMobile, isValidCustomAttrName} from "../util/functions";import {getAssetExtension, isEncryptedBox, isLocalPath, movePathTo, moveToPath, pathPosix} from "../util/pathName";import {MenuItem} from "./Menu";import {onExport, saveExport} from "../protyle/export";@@ -1000,6 +1000,8 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAcceleratnoSplitScreen: window.siyuan.config.fileTree.noSplitScreenWhenOpenTab,}).map((gesture) => updateHotkeyTip(gestureLabels[gesture])).join(" / ");};+ // 与链接点击一致:PDF 去掉片段并单独取出页码或标注 ID,其他资源保留原始地址(如视频的 #t=)+ const {linkAddress: assetPath, pdfParams} = resolvePdfAssetLink(src.trim());if (previewable) {submenu.push({id: "openBy",@@ -1007,7 +1009,7 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAcceleraticon: "iconOpen",accelerator: getAccelerator("current"),click() {- openAsset(app, src.trim(), parseInt(getSearch("page", src)));+ openAsset(app, assetPath, pdfParams);}});submenu.push({@@ -1016,7 +1018,7 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAcceleratlabel: window.siyuan.languages.insertRight,accelerator: getAccelerator("right"),click() {- openAsset(app, src.trim(), parseInt(getSearch("page", src)), "right");+ openAsset(app, assetPath, pdfParams, "right");}});submenu.push({@@ -1025,7 +1027,7 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAcceleratlabel: window.siyuan.languages.insertBottom,accelerator: getAccelerator("bottom"),click() {- openAsset(app, src.trim(), parseInt(getSearch("page", src)), "bottom");+ openAsset(app, assetPath, pdfParams, "bottom");}});submenu.push({@@ -1034,7 +1036,7 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAcceleraticon: "iconEyeoff",accelerator: getAccelerator("background"),click() {- openAssetInBackground(app, src.trim(), parseInt(getSearch("page", src)));+ openAssetInBackground(app, assetPath, pdfParams);}});/// #if !BROWSER@@ -1044,7 +1046,7 @@ export const openMenu = (app: App, src: string, onlyMenu: boolean, showAcceleraticon: "iconOpenWindow",accelerator: getAccelerator("new-window"),click() {- openAssetNewWindow(src.trim());+ openAssetNewWindow(assetPath, {}, pdfParams);}});if (getHostCapabilities().localFileSystem) {diff --git a/app/src/menus/tab.test.ts b/app/src/menus/tab.test.tsnew file mode 100644index 0000000000..35e751b41c--- /dev/null+++ b/app/src/menus/tab.test.ts@@ -0,0 +1,70 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import * as path from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import * as escape from "../util/escape";+import * as mergePathSegments from "../util/mergePathSegments";++type Flags = {MOBILE: boolean; BROWSER: boolean};++const compile = (file: string, flags: Flags) => transpileModule(require("ifdef-loader/preprocessor").parse(+ readFileSync(file, "utf8"), flags, false, true), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const copyAssetTab = (flags: Flags, assetPath: string, title: string) => {+ const copied: string[] = [];+ const items: Array<{id: string; click?: () => void}> = [];+ const anyShortcut = new Proxy({}, {get: () => ({custom: ""})});+ const window = {siyuan: {languages: {}, config: {keymap: {general: anyShortcut}}, layout: {centerLayout: {}},+ menus: {menu: {remove() {}, append() {}, element: {setAttribute() {}}}}}};+ const recorder = new Proxy({}, {get: (_target, name) => name === "__esModule" ? undefined : (): undefined => undefined});+ const load = (file: string, modules: Record<string, unknown> = {}) => {+ const exports: Record<string, any> = {};+ runInNewContext(compile(file, flags), {exports, window, navigator: {userAgent: ""},+ SIYUAN_VERSION: "dev", NODE_ENV: "development",+ require: (id: string) => modules[id] ?? (id === "path" ? path : recorder)});+ return exports;+ };+ class Asset {}+ class Editor {}+ const pathName = load("src/util/pathName.ts", {"./mergePathSegments": mergePathSegments, "./escape": escape});+ const tabMenu = load("src/menus/tab.ts", {+ "../util/pathName": pathName,+ "../asset": {Asset},+ "../editor": {Editor},+ "../protyle/util/compatibility": {writeText: (text: string) => copied.push(text)},+ "./Menu": {MenuItem: class {+ element = {};+ constructor(options: {id: string; click?: () => void}) {+ items.push(options);+ }+ }},+ });+ const model = Object.assign(Object.create(Asset.prototype), {path: assetPath, parent: {title}});+ const tab: Record<string, unknown> = {id: "tab", model,+ headElement: {getAttribute: (): null => null, classList: {contains: () => false}}};+ tab.parent = {children: [tab]};+ tabMenu.initTabMenu({}, tab);+ items.find(item => item.id === "copy").click();+ return copied;+};++for (const {name, flags} of [+ {name: "desktop", flags: {MOBILE: false, BROWSER: false}},+ {name: "browser", flags: {MOBILE: false, BROWSER: true}},+]) {+ test(`copying an asset tab labels the link with the real file extension (${name})`, () => {+ for (const [assetPath, label] of [+ ["assets/image-20260101000000-abcdefg.png", "image.png"],+ ["assets/image-20260101000000-abcdefg.png#preview", "image.png"],+ ["assets/video-20260101000000-abcdefg.mp4#t=10", "video.mp4"],+ ["assets/image-20260101000000-abcdefg.png?v=1.2", "image.png"],+ ]) {+ const title = assetPath.split(/[?#]/, 1)[0].substring("assets/".length);+ assert.deepEqual(copyAssetTab(flags, assetPath, title), [`[${label}](${assetPath})`], assetPath);+ }+ });+}diff --git a/app/src/menus/tab.ts b/app/src/menus/tab.tsindex ddb9e3d823..488cffd5b0 100644--- a/app/src/menus/tab.ts+++ b/app/src/menus/tab.ts@@ -13,7 +13,7 @@ import {Wnd} from "../layout/Wnd";import {getAllWnds} from "../layout/getAll";import {Asset} from "../asset";import {writeText} from "../protyle/util/compatibility";-import {getAssetName, pathPosix} from "../util/pathName";+import {getAssetExtension, getAssetName} from "../util/pathName";import {Constants} from "../constants";const closeMenu = (tab: Tab) => {@@ -207,7 +207,7 @@ export const initTabMenu = (app: App, tab: Tab) => {label: window.siyuan.languages.copy,icon: "iconCopy",click() {- writeText(`[${getAssetName(model.parent.title)}${pathPosix().extname(model.path)}](${model.path})`);+ writeText(`[${getAssetName(model.parent.title)}${getAssetExtension(model.path)}](${model.path})`);}}).element);}diff --git a/app/src/util/pathName.test.ts b/app/src/util/pathName.test.tsindex d85af8204e..6b24d32395 100644--- a/app/src/util/pathName.test.ts+++ b/app/src/util/pathName.test.ts@@ -73,3 +73,16 @@ test("storage paths without a file segment are rejected instead of addressing thassert.equal(names.normalizeStoragePath(storageName), null, JSON.stringify(storageName));}});++test("asset paths drop fragments but keep queries for kernel resolution", () => {+ for (const [assetPath, expected] of [+ ["assets/image.png", "assets/image.png"],+ ["assets/image.png#preview", "assets/image.png"],+ ["assets/video.mp4#t=10", "assets/video.mp4"],+ ["assets/image.png?box=20260101000000-abcdefg#preview", "assets/image.png?box=20260101000000-abcdefg"],+ ["assets/image.png?v=1.2", "assets/image.png?v=1.2"],+ ["assets/image%23copy.png#preview", "assets/image%23copy.png"],+ ]) {+ assert.equal(names.getAssetPathWithoutFragment(assetPath), expected, assetPath);+ }+});diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.tsindex ea83b477ac..1cb0e1f8f0 100644--- a/app/src/util/pathName.ts+++ b/app/src/util/pathName.ts@@ -173,6 +173,11 @@ export const getAssetPathWithoutQuery = (assetPath: string) => {return assetPath.split(/[?#]/, 1)[0];};+// 只去掉片段,保留查询:内核依赖 box 等查询参数定位资源,但不处理片段。+export const getAssetPathWithoutFragment = (assetPath: string) => {+ return assetPath.split("#", 1)[0];+};+export const getAssetExtension = (assetPath: string) => {return pathPosix().extname(getAssetPathWithoutQuery(assetPath));};diff --git a/app/src/window/openNewWindow.test.ts b/app/src/window/openNewWindow.test.tsnew file mode 100644index 0000000000..83ac03838c--- /dev/null+++ b/app/src/window/openNewWindow.test.ts@@ -0,0 +1,52 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import * as path from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import * as escape from "../util/escape";+import * as mergePathSegments from "../util/mergePathSegments";+import * as imageURL from "../util/imageURL";++const compile = (file: string) => transpileModule(require("ifdef-loader/preprocessor").parse(+ readFileSync(file, "utf8"), {MOBILE: false, BROWSER: false}, false, true), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+}).outputText;++const openAssetWindow = (assetPath: string, page?: number) => {+ const sent: Array<{url: string}> = [];+ const window = {location: {origin: "http://127.0.0.1:6806"}};+ const recorder = new Proxy({}, {get: (_target, name) => name === "__esModule" ? undefined : (): undefined => undefined});+ const load = (file: string, modules: Record<string, unknown> = {}) => {+ const exports: Record<string, any> = {};+ runInNewContext(compile(file), {exports, window, navigator: {userAgent: ""}, URL,+ SIYUAN_VERSION: "dev", NODE_ENV: "development",+ require: (id: string) => modules[id] ?? (id === "path" ? path : recorder)});+ return exports;+ };+ const pathName = load("src/util/pathName.ts", {"./mergePathSegments": mergePathSegments, "./escape": escape});+ const constants = load("src/constants.ts");+ const newWindow = load("src/window/openNewWindow.ts", {+ "../util/pathName": pathName,+ "../constants": constants,+ "../util/imageURL": imageURL,+ "../util/hostCapabilities": {appendRemoteQuery: (url: URL) => url},+ "electron": {ipcRenderer: {send: (_channel: string, data: {url: string}) => sent.push(data)}},+ });+ newWindow.openAssetNewWindow(assetPath, {}, page);+ assert.equal(sent.length, 1, assetPath);+ return JSON.parse(new URL(sent[0].url).searchParams.get("json"))[0];+};++test("asset windows title files without queries or fragments and keep the original path", () => {+ for (const [assetPath, title] of [+ ["assets/image-20260101000000-abcdefg.png#preview", "image-20260101000000-abcdefg.png"],+ ["assets/video-20260101000000-abcdefg.mp4#t=10", "video-20260101000000-abcdefg.mp4"],+ ["assets/image-20260101000000-abcdefg.png?box=20260101000000-hijklmn", "image-20260101000000-abcdefg.png"],+ ]) {+ const tab = openAssetWindow(assetPath);+ assert.equal(tab.title, title, assetPath);+ assert.equal(tab.children.path, assetPath, assetPath);+ }+ assert.equal(openAssetWindow("assets/document.pdf", 3).children.page, 3);+});diff --git a/app/src/window/openNewWindow.ts b/app/src/window/openNewWindow.tsindex 1f2e4c5d65..d33236c36b 100644--- a/app/src/window/openNewWindow.ts+++ b/app/src/window/openNewWindow.ts@@ -6,7 +6,7 @@ import {Constants} from "../constants";import {Tab} from "../layout/Tab";import {fetchSyncPost} from "../util/fetch";import {showMessage} from "../dialog/message";-import {getAssetExtension, getDisplayName} from "../util/pathName";+import {getAssetExtension, getAssetPathWithoutQuery, getDisplayName} from "../util/pathName";import {getSearch} from "../util/functions";import {isBrowserRenderableImagePath} from "../util/imageURL";import {appendRemoteQuery} from "../util/hostCapabilities";@@ -118,7 +118,7 @@ export const openAssetNewWindow = (docIcon = "iconVideo";}const json: any = [{- title: getDisplayName(assetPath),+ title: getDisplayName(getAssetPathWithoutQuery(assetPath)),docIcon,pin: false,active: true,