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: Prevent asset upload overwrite and target drift https://github.com/siyuan-note/siyuan/issues/18878
Danielb1c9fb352e5d
diff --git a/app/src/protyle/render/av/asset.ts b/app/src/protyle/render/av/asset.tsindex 7ba0c100ad..b2bc3d08b0 100644--- a/app/src/protyle/render/av/asset.ts+++ b/app/src/protyle/render/av/asset.ts@@ -12,8 +12,13 @@ import {setPosition} from "../../../util/setPosition";import {getAVBatchEditMode, getAVBatchSourceValue} from "./batchValue";import {previewAttrViewImages} from "../../preview/image";import {showMessage} from "../../../dialog/message";-import {hasClosestBlock} from "../../util/hasClosest";-import {genCellValueByElement, getTypeByCellElement, updateAttrViewCellInOtherElements} from "./cell";+import {hasClosestBlock, hasClosestByClassName} from "../../util/hasClosest";+import {+ genCellValueByElement,+ getTypeByCellElement,+ updateAttrViewCellInOtherElements,+ updateCellsValue+} from "./cell";import {writeText} from "../../util/compatibility";import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";import {renameAsset} from "../../../editor/rename";@@ -25,6 +30,8 @@ import {base64ToURL, showBase64ImageSizeLimit} from "../../upload/base64";import {isBrowserRenderableImagePath} from "../../../util/imageURL";import {genNetworkImageAssetValue} from "./assetValue";import {getAssetUploadSuccesses} from "../../upload/uploadResult";+import {getAVSelectedCells, type IAVSelectedCell} from "./selectionState";+import {getAVSelectedTableCells} from "./virtualScroll";export const bindAssetEvent = (options: {protyle: IProtyle,@@ -39,6 +46,9 @@ export const bindAssetEvent = (options: {return;}uploadFiles(options.protyle, event.target.files, event.target, (res) => {+ if (!document.body.contains(options.blockElement)) {+ return;+ }const resData = JSON.parse(res);const value: IAVCellAssetValue[] = [];getAssetUploadSuccesses(resData.data).forEach((success) => {@@ -52,7 +62,8 @@ export const bindAssetEvent = (options: {protyle: options.protyle,cellElements: options.cellElements,addValue: value,- blockElement: options.blockElement+ blockElement: options.blockElement,+ menuElement: options.menuElement,});}, undefined, {source: "file-picker", target: "av-cell"});});@@ -128,7 +139,8 @@ export const updateAssetCell = (options: {addValue?: IAVCellAssetValue[],updateValue?: { index: number, value: IAVCellAssetValue }removeIndex?: number,- blockElement: Element+ blockElement: Element,+ menuElement?: HTMLElement | null,}) => {const viewType = options.blockElement.getAttribute("data-av-type") as TAVView;const colId = getColId(options.cellElements[0], viewType);@@ -209,7 +221,9 @@ export const updateAssetCell = (options: {data: dayjs().format("YYYYMMDDHHmmss"),});transaction(options.protyle, cellDoOperations, cellUndoOperations);- const menuElement = document.querySelector(".av__panel > .b3-menu") as HTMLElement;+ const menuElement = typeof options.menuElement === "undefined" ?+ document.querySelector<HTMLElement>(".av__panel > .b3-menu") :+ options.menuElement?.isConnected ? options.menuElement : null;if (menuElement) {menuElement.innerHTML = getAssetHTML(options.cellElements);bindAssetEvent({@@ -499,48 +513,198 @@ ${window.siyuan.languages.title}menu.element.querySelector("textarea").focus();};+const getUploadedAssetValues = (result: Omit<IAssetUploadResult, "requestId" | "input">,+ formatName: (name: string) => string = name => name,+ sort = false) => {+ const values: IAVCellAssetValue[] = [];+ const successes = Array.from(getAssetUploadSuccesses(result));+ if (sort) {+ successes.sort((a, b) => a.name.localeCompare(b.name, undefined, {numeric: true}) || a.index - b.index);+ }+ successes.forEach(success => {+ const type = getAssetExtension(success.name).toLowerCase();+ const filename = formatName(success.name);+ values.push({+ type: Constants.SIYUAN_ASSETS_IMAGE.includes(type) ? "image" : "file",+ name: filename.substring(0, filename.length - type.length),+ content: success.path,+ });+ });+ return values;+};++const getAssetCellMenu = (cellElement: HTMLElement) => {+ const menuElement = document.querySelector<HTMLElement>(".av__panel > .b3-menu");+ const ids = menuElement?.querySelector(".b3-menu__items")?.getAttribute("data-ids")?.split(",") || [];+ return ids.includes(cellElement.dataset.id) ? menuElement : null;+};+const updateCellWithUploadedAssets = (result: Omit<IAssetUploadResult, "requestId" | "input">,- protyle: IProtyle, cellElement: HTMLElement) => {- const blockElement = hasClosestBlock(cellElement);- if (!blockElement) {+ protyle: IProtyle, blockElement: Element, cellElement: HTMLElement,+ menuElement: HTMLElement | null) => {+ if (!document.body.contains(blockElement)) {return;}- const addValue: IAVCellAssetValue[] = [];- getAssetUploadSuccesses(result).forEach(success => {- const type = getAssetExtension(success.name).toLowerCase();- const name = success.name.substring(0, success.name.length - type.length);- if (Constants.SIYUAN_ASSETS_IMAGE.includes(type)) {- addValue.push({- type: "image",- name,- content: success.path,- });+ if (!blockElement.contains(cellElement)) {+ const viewType = blockElement.getAttribute("data-av-type") as TAVView;+ const rowID = getFieldIdByCellElement(cellElement, viewType);+ if (viewType === "table") {+ cellElement = blockElement.querySelector<HTMLElement>(`.av__row[data-id="${rowID}"] .av__cell[data-col-id="${cellElement.dataset.colId}"]`) ||+ blockElement.querySelector<HTMLElement>(`.fn__flex-1[data-col-id="${cellElement.dataset.colId}"]`);} else {- addValue.push({- type: "file",- name,- content: success.path,- });+ cellElement = blockElement.querySelector<HTMLElement>(`.av__gallery-item[data-id="${rowID}"] .av__cell[data-field-id="${cellElement.dataset.fieldId}"]`);}- });+ if (!cellElement) {+ return;+ }+ }updateAssetCell({protyle,blockElement,cellElements: [cellElement],- addValue+ addValue: getUploadedAssetValues(result),+ menuElement,});};+export const captureAVAssetUploadHandler = (protyle: IProtyle, blockElement: HTMLElement) => {+ const panelElement = document.querySelector<HTMLElement>(".av__panel");+ const usePanelTarget = Boolean(panelElement?.querySelector(".b3-form__upload"));+ const cellElements: HTMLElement[] = [];+ let stableCells: IAVSelectedCell[] = [];++ if (usePanelTarget) {+ blockElement.querySelectorAll<HTMLElement>(".av__cell--active").forEach(item => {+ if (getTypeByCellElement(item) === "mAsset") {+ cellElements.push(item);+ }+ });+ if (cellElements.length === 0) {+ panelElement.querySelector(".b3-menu__items")?.getAttribute("data-ids")?.split(",").forEach(id => {+ const item = blockElement.querySelector<HTMLElement>(+ `.av__gallery-fields [data-dtype="mAsset"][data-id="${id}"]`);+ if (item) {+ cellElements.push(item);+ }+ });+ }+ } else {+ const selectedCells = getAVSelectedCells(blockElement);+ const stableCellCandidates = (selectedCells.length > 0 ? selectedCells :+ getAVSelectedTableCells(blockElement)).filter(item => item.column.type === "mAsset");+ blockElement.querySelectorAll(".av__row--select:not(.av__row--header)").forEach(item => {+ item.querySelectorAll<HTMLElement>(".av__cell").forEach(cellItem => {+ if (getTypeByCellElement(cellItem) === "mAsset") {+ cellElements.push(cellItem);+ }+ });+ });+ if (cellElements.length === 0) {+ blockElement.querySelectorAll<HTMLElement>(".av__cell--active").forEach(item => {+ if (getTypeByCellElement(item) === "mAsset") {+ cellElements.push(item);+ }+ });+ }+ if (stableCellCandidates.length > cellElements.length) {+ stableCells = stableCellCandidates;+ }+ }++ const targetCellElements = Array.from(cellElements);+ if (!usePanelTarget && stableCells.length === 0 && cellElements.length > 1) {+ const colId = cellElements[0].dataset.colId;+ let currentRowElement = hasClosestByClassName(cellElements[cellElements.length - 1], "av__row") as HTMLElement;+ while (currentRowElement?.nextElementSibling?.classList.contains("av__row")) {+ currentRowElement = currentRowElement.nextElementSibling as HTMLElement;+ const cellElement = currentRowElement.querySelector<HTMLElement>(`.av__cell[data-col-id="${colId}"]`);+ if (cellElement) {+ targetCellElements.push(cellElement);+ }+ }+ }++ return async (result: Omit<IAssetUploadResult, "requestId" | "input">) => {+ if (!document.body.contains(blockElement)) {+ return;+ }+ const values = getUploadedAssetValues(result, protyle.options.upload.filename, true);+ if (values.length === 0) {+ return;+ }+ if (usePanelTarget) {+ if (cellElements.length > 0) {+ await updateCellsValue(protyle, blockElement, values, cellElements);+ if (panelElement.isConnected) {+ panelElement.remove();+ }+ }+ return;+ }+ if (stableCells.length === 1 || cellElements.length === 1) {+ await updateCellsValue(protyle, blockElement, values, cellElements, undefined, undefined,+ false, false, false, stableCells);+ return;+ }+ if (stableCells.length === 0 && cellElements.length === 0) {+ return;+ }+ const doOperations: IOperation[] = [];+ const undoOperations: IOperation[] = [];+ for (let i = 0; i < values.length; i++) {+ const selectedCell = stableCells[i];+ const cellElement = targetCellElements[i];+ if (!selectedCell && !cellElement) {+ break;+ }+ const operations = await updateCellsValue(protyle, blockElement, [values[i]],+ cellElement ? [cellElement] : undefined, undefined, undefined,+ true, false, false, selectedCell ? [selectedCell] : undefined);+ doOperations.push(...operations.doOperations);+ undoOperations.push(...operations.undoOperations);+ }+ if (doOperations.length > 0 && document.body.contains(blockElement)) {+ const id = blockElement.dataset.nodeId;+ doOperations.push({+ action: "doUpdateUpdated",+ id,+ data: dayjs().format("YYYYMMDDHHmmss"),+ });+ undoOperations.push({+ action: "doUpdateUpdated",+ id,+ data: blockElement.getAttribute("updated"),+ });+ transaction(protyle, doOperations, undoOperations);+ }+ };+};+export const dragUpload = (files: ILocalFiles[], protyle: IProtyle, cellElement: HTMLElement,position?: IAssetUploadPosition) => {+ const blockElement = hasClosestBlock(cellElement);+ if (!blockElement) {+ return;+ }+ const menuElement = getAssetCellMenu(cellElement);uploadLocalFiles(files, protyle, true, {source: "drop", target: "av-cell", position}, (_response, result) => {- updateCellWithUploadedAssets(result, protyle, cellElement);+ updateCellWithUploadedAssets(result, protyle, blockElement, cellElement, menuElement);});};+export const uploadFilesToAssetCell = (files: FileList | File[], protyle: IProtyle, cellElement: HTMLElement,+ options: { source: TAssetUploadSource, position?: IAssetUploadPosition }) => {+ const blockElement = hasClosestBlock(cellElement);+ if (!blockElement) {+ return;+ }+ const menuElement = getAssetCellMenu(cellElement);+ uploadFiles(protyle, files, undefined, (_response, result) => {+ updateCellWithUploadedAssets(result, protyle, blockElement, cellElement, menuElement);+ }, undefined, {source: options.source, target: "av-cell", position: options.position});+};+export const dragUploadFiles = (files: FileList | File[], protyle: IProtyle, cellElement: HTMLElement,position?: IAssetUploadPosition) => {- uploadFiles(protyle, files, undefined, (_response, result) => {- updateCellWithUploadedAssets(result, protyle, cellElement);- }, undefined, {source: "drop", target: "av-cell", position});+ uploadFilesToAssetCell(files, protyle, cellElement, {source: "drop", position});};diff --git a/app/src/protyle/render/av/blockAttr.ts b/app/src/protyle/render/av/blockAttr.tsindex d196537316..64761d4d19 100644--- a/app/src/protyle/render/av/blockAttr.ts+++ b/app/src/protyle/render/av/blockAttr.ts@@ -7,9 +7,8 @@ import {openEmojiPanel, unicode2Emoji} from "../../../emoji";import {getFileTreeIconHTML} from "../../../emoji/fileTreeIcon";import {transaction} from "../../wysiwyg/transaction";import {openMenuPanel} from "./openMenuPanel";-import {uploadFiles} from "../../upload";import {openLink} from "../../../editor/openLink";-import {dragUpload, dragUploadFiles, editAssetItem} from "./asset";+import {dragUpload, dragUploadFiles, editAssetItem, uploadFilesToAssetCell} from "./asset";import {previewImages} from "../../preview/image";/// #if !BROWSERimport {webUtils} from "electron";@@ -343,10 +342,7 @@ export const renderAVAttribute = (element: HTMLElement, id: string, protyle: IPrevent.preventDefault();event.stopPropagation();if (files && files.length > 0) {- uploadFiles(protyle, files, undefined, undefined, undefined, {- source: "paste",- target: "av-cell",- });+ uploadFilesToAssetCell(files, protyle, assetCellElement, {source: "paste"});} else {const textPlain = event.clipboardData.getData("text/plain");const blockElement = hasClosestBlock(assetCellElement);diff --git a/app/src/protyle/upload/index.ts b/app/src/protyle/upload/index.tsindex 410858685c..a965afc53b 100644--- a/app/src/protyle/upload/index.ts+++ b/app/src/protyle/upload/index.ts@@ -7,16 +7,11 @@ import {fetchSyncPost} from "../../util/fetch";import {getEditorRange, getUndoFocusContext, restoreFocusContext} from "../util/selection";import {pathPosix} from "../../util/pathName";import {genAssetHTML} from "../../asset/renderAssets";-import {hasClosestBlock, hasClosestByClassName} from "../util/hasClosest";+import {hasClosestBlock} from "../util/hasClosest";import {getContenteditableElement} from "../wysiwyg/getBlock";-import {getTypeByCellElement, updateCellsValue} from "../render/av/cell";import {scrollCenter} from "../../util/highlightById";import {confirmDialog} from "../../dialog/confirmDialog";import {filesize} from "filesize";-import {transaction} from "../wysiwyg/transaction";-import * as dayjs from "dayjs";-import {getAVSelectedCells} from "../render/av/selectionState";-import {getAVSelectedTableCells} from "../render/av/virtualScroll";import {createUploadInsertPosition, isUploadInsertPositionAvailable} from "./insertPosition";import type {IUploadInsertPosition} from "./insertPosition";import {@@ -143,6 +138,9 @@ const genUploadedLabel = async (responseText: string, protyle: IProtyle, optionsif (errorTip) {showMessage(errorTip);}+ if ((options?.target || "editor") !== "editor") {+ return;+ }let insertBlock = true;const range = getUploadInsertRange(protyle, options?.insertPosition);if (range.toString() === "" && range.startContainer.nodeType === 3 && protyle.toolbar.getCurrentType(range).length > 0) {@@ -167,18 +165,12 @@ const genUploadedLabel = async (responseText: string, protyle: IProtyle, optionslet successFileText = "";// 插入多个资源文件时按文件名自然升序排列 Use natural ascending order when inserting multiple assets https://github.com/siyuan-note/siyuan/issues/14643successes.sort((a, b) => a.name.localeCompare(b.name, undefined, {numeric: true}) || a.index - b.index);- const avAssets: IAVCellAssetValue[] = [];let hasImage = false;successes.forEach((success, index) => {const type = pathPosix().extname(success.name).toLowerCase();const filename = protyle.options.upload.filename(success.name);const name = filename.substring(0, filename.length - type.length);hasImage = Constants.SIYUAN_ASSETS_IMAGE.includes(type);- avAssets.push({- type: Constants.SIYUAN_ASSETS_IMAGE.includes(type) ? "image" : "file",- content: success.path,- name: name- });successFileText += genAssetHTML(type, success.path, name, filename,getHostCapabilities().localFileSystem && options?.htmlAsIframe);if (!Constants.SIYUAN_ASSETS_AUDIO.includes(type) && !Constants.SIYUAN_ASSETS_VIDEO.includes(type) &&@@ -193,105 +185,6 @@ const genUploadedLabel = async (responseText: string, protyle: IProtyle, options}});- if (document.querySelector(".av__panel")) {- const cellElements: HTMLElement[] = [document.querySelector('.custom-attr__avvalue[data-type="mAsset"][data-active="true"]')];- if (!cellElements[0]) {- cellElements.splice(0, 1);- protyle.wysiwyg.element.querySelectorAll(".av__cell--active").forEach((item: HTMLElement) => {- if (getTypeByCellElement(item) === "mAsset") {- cellElements.push(item);- }- });- if (cellElements.length === 0) {- document.querySelector(".av__panel .b3-menu__items")?.getAttribute("data-ids")?.split(",").forEach((id: string) => {- const item = protyle.wysiwyg.element.querySelector(`.av__gallery-fields [data-dtype="mAsset"][data-id="${id}"]`) as HTMLElement;- if (item) {- cellElements.push(item);- }- });- }- }- if (cellElements.length > 0) {- const blockElement = hasClosestBlock(cellElements[0]);- if (blockElement) {- await updateCellsValue(protyle, blockElement, avAssets, cellElements);- document.querySelector(".av__panel")?.remove();- return;- }- } else {- return;- }- } else if (nodeElement && nodeElement.classList.contains("av")) {- const selectedCells = getAVSelectedCells(nodeElement);- const stableCellCandidates = (selectedCells.length > 0 ? selectedCells :- getAVSelectedTableCells(nodeElement)).filter(item => item.column.type === "mAsset");- const cellElements: HTMLElement[] = [];- nodeElement.querySelectorAll(".av__row--select:not(.av__row--header)").forEach(item => {- item.querySelectorAll(".av__cell").forEach((cellItem: HTMLElement) => {- if (getTypeByCellElement(cellItem) === "mAsset") {- cellElements.push(cellItem);- }- });- });- if (cellElements.length === 0) {- nodeElement.querySelectorAll(".av__cell--active").forEach((item: HTMLElement) => {- if (getTypeByCellElement(item) === "mAsset") {- cellElements.push(item);- }- });- }- const stableCells = stableCellCandidates.length > cellElements.length ? stableCellCandidates : [];- if (stableCells.length === 1 || cellElements.length === 1) {- await updateCellsValue(protyle, nodeElement, avAssets, cellElements, undefined, undefined,- false, false, false, stableCells);- } else if (stableCells.length > 1 || cellElements.length > 1) {- const doOperations: IOperation[] = [];- const undoOperations: IOperation[] = [];- let currentRowElement;- const colId = cellElements[0]?.getAttribute("data-col-id");- for (let i = 0; i < avAssets.length; i++) {- const selectedCell = stableCells[i];- if (stableCells.length > 0 && !selectedCell) {- break;- }- let cellElement = cellElements[i];- if (!cellElement && stableCells.length === 0) {- if (!currentRowElement) {- currentRowElement = hasClosestByClassName(cellElements[i - 1], "av__row") as HTMLElement;- }- if (currentRowElement) {- currentRowElement = currentRowElement.nextElementSibling;- if (currentRowElement && currentRowElement.classList.contains("av__row")) {- cellElement = currentRowElement.querySelector(`.av__cell[data-col-id="${colId}"]`);- }- }- }- if (!cellElement && !selectedCell) {- break;- }- const operations = await updateCellsValue(protyle, nodeElement,- [avAssets[i]], cellElement ? [cellElement] : undefined, undefined, undefined,- true, false, false, selectedCell ? [selectedCell] : undefined);- doOperations.push(...operations.doOperations);- undoOperations.push(...operations.undoOperations);- }- if (doOperations.length > 0) {- const id = nodeElement.dataset.nodeId;- doOperations.push({- action: "doUpdateUpdated",- id,- data: dayjs().format("YYYYMMDDHHmmss"),- });- undoOperations.push({- action: "doUpdateUpdated",- id,- data: nodeElement.getAttribute("updated"),- });- transaction(protyle, doOperations, undoOperations);- }- }- return;- }// 避免插入代码块中,其次因为都要独立成块 https://github.com/siyuan-note/siyuan/issues/7607if (options?.insertPosition) {protyle.toolbar.range = range;diff --git a/app/src/protyle/upload/pluginEvent.test.ts b/app/src/protyle/upload/pluginEvent.test.tsindex d5f7d63061..8857452952 100644--- a/app/src/protyle/upload/pluginEvent.test.ts+++ b/app/src/protyle/upload/pluginEvent.test.ts@@ -387,6 +387,28 @@ describe("asset upload plugin event", () => {}});+ it("fails closed when a listener throws a falsy value", async () => {+ for (const thrownValue of [null, undefined, false, 0, ""]) {+ let laterPluginCalled = false;+ const prepared = await prepareAssetUpload({+ plugins: [+ createPlugin(() => {+ throw thrownValue;+ }),+ createPlugin(() => {+ laterPluginCalled = true;+ }),+ ],+ protyle,+ input: {kind: "files", files: [createFile("a.png")]},+ context,+ });++ assert.equal(prepared.state, "failed");+ assert.equal(laterPluginCalled, false);+ }+ });+it("rejects an async listener that does not claim the request synchronously", async () => {const originalConsoleError = console.error;console.error = () => undefined;diff --git a/app/src/protyle/upload/pluginEvent.ts b/app/src/protyle/upload/pluginEvent.tsindex 96d682ff70..42c6be0fbf 100644--- a/app/src/protyle/upload/pluginEvent.ts+++ b/app/src/protyle/upload/pluginEvent.ts@@ -413,7 +413,7 @@ export const prepareAssetUpload = (options: {return fail(error);}acceptingRegistrations = false;- if (emitResult.error) {+ if (Object.prototype.hasOwnProperty.call(emitResult, "error")) {discardResponse();return fail(new Error(`Plugin ${pluginLabel} failed during before-upload-assets: ${getErrorMessage(emitResult.error)}`));}diff --git a/app/src/protyle/util/editorCommonEvent.ts b/app/src/protyle/util/editorCommonEvent.tsindex 00ffd8cdd1..a5c3af917a 100644--- a/app/src/protyle/util/editorCommonEvent.ts+++ b/app/src/protyle/util/editorCommonEvent.ts@@ -37,7 +37,7 @@ import {updatePanelByEditor} from "../../editor/util";/// #endifimport {blockRender} from "../render/blockRender";/// #else-import {uploadFiles, uploadLocalFiles} from "../upload";+import {uploadLocalFiles} from "../upload";import {getLocalDropFiles, hasDataTransferFiles} from "../upload/localDropFiles";import {insertHTML} from "./insertHTML";import {isBrowser} from "../../util/functions";@@ -50,6 +50,7 @@ import {isFoldedHeading, shouldUnfoldMovedHeading} from "./foldHeadingMove";import {webUtils} from "electron";import {dragUpload} from "../render/av/asset";/// #endif+import {dragUploadFiles} from "../render/av/asset";import {addDragFill, getTypeByCellElement} from "../render/av/cell";import {insertGalleryItemAnimation} from "../render/av/gallery/item";import {clearSelect} from "./clear";@@ -2201,32 +2202,23 @@ export const dropEvent = (protyle: IProtyle, editorElement: HTMLElement) => {/// #if !BROWSERif (!getHostCapabilities().localFileSystem) {focusBlock(hasClosestBlock(cellElement) as HTMLElement);- uploadFiles(protyle, event.dataTransfer.files, undefined, undefined, undefined, {- source: "drop",- target: "av-cell",- position: {x: event.clientX, y: event.clientY},- });+ dragUploadFiles(event.dataTransfer.files, protyle, cellElement,+ {x: event.clientX, y: event.clientY});} else {const files = getLocalDropFiles(event.dataTransfer.files,file => webUtils.getPathForFile(file));if (!files) {focusBlock(hasClosestBlock(cellElement) as HTMLElement);- uploadFiles(protyle, event.dataTransfer.files, undefined, undefined, undefined, {- source: "drop",- target: "av-cell",- position: {x: event.clientX, y: event.clientY},- });+ dragUploadFiles(event.dataTransfer.files, protyle, cellElement,+ {x: event.clientX, y: event.clientY});} else {dragUpload(files, protyle, cellElement, {x: event.clientX, y: event.clientY});}}/// #elsefocusBlock(hasClosestBlock(cellElement) as HTMLElement);- uploadFiles(protyle, event.dataTransfer.files, undefined, undefined, undefined, {- source: "drop",- target: "av-cell",- position: {x: event.clientX, y: event.clientY},- });+ dragUploadFiles(event.dataTransfer.files, protyle, cellElement,+ {x: event.clientX, y: event.clientY});/// #endif}}diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.tsindex cdf69cfc8a..f685ca0443 100644--- a/app/src/protyle/util/paste.ts+++ b/app/src/protyle/util/paste.ts@@ -20,6 +20,7 @@ import {hideElements} from "../ui/hideElements";import {showMessage} from "../../dialog/message";import {avRender} from "../render/av/render";import {cellScrollIntoView, getCellText} from "../render/av/cell";+import {captureAVAssetUploadHandler} from "../render/av/asset";import {fixAdjacentTags, getCalloutInfo, getContenteditableElement} from "../wysiwyg/getBlock";import {clearBlockElement} from "./clear";import {remapTabsDOMIDs, wrapPastedTabItems} from "./tabsCopy";@@ -342,7 +343,9 @@ export const restoreLuteMarkdownSyntax = (protyle: IProtyle) => {});};-const readLocalFile = async (protyle: IProtyle, localFiles: ILocalFiles[], options?: IUploadInsertOptions) => {+const readLocalFile = async (protyle: IProtyle, localFiles: ILocalFiles[], options?: IUploadInsertOptions,+ successCB?: (response: IWebSocketData,+ result: Omit<IAssetUploadResult, "requestId" | "input">) => void) => {if (areProtylePluginExtensionsEnabled(protyle) && protyle.app?.plugins && hasPluginSubscriber("paste")) {const plugins = Array.from(protyle.app.plugins);for (let i = 0; i < plugins.length; i++) {@@ -402,7 +405,7 @@ const readLocalFile = async (protyle: IProtyle, localFiles: ILocalFiles[], optio!isUploadInsertPositionAvailable(protyle.wysiwyg.element, options.insertPosition)) {return;}- uploadLocalFiles(localFiles, protyle, true, options);+ uploadLocalFiles(localFiles, protyle, true, options, successCB);};export const convertPastedListItemSubtype = (listItemElement: HTMLElement, subtype: string) => {@@ -634,6 +637,10 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven}const pasteInsertPosition = uploadOptions?.insertPosition ||createUploadInsertPosition(getEditorRange(protyle.wysiwyg.element));+ const initialBlockElement = (hasClosestBlock(event.target) ||+ hasClosestBlock(pasteInsertPosition.range.startContainer)) as HTMLElement;+ const avAssetUploadHandler = initialBlockElement?.classList.contains("av") ?+ captureAVAssetUploadHandler(protyle, initialBlockElement) : undefined;const isPasteInsertPositionAvailable = () =>isUploadInsertPositionAvailable(protyle.wysiwyg.element, pasteInsertPosition);const restorePasteInsertRange = () => {@@ -650,6 +657,11 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEventarget: uploadOptions?.target || "editor",position: uploadOptions?.position || ("dataTransfer" in event ? {x: event.clientX, y: event.clientY} : undefined),};+ const directAssetUploadOptions: IUploadInsertOptions = avAssetUploadHandler ?+ {...assetUploadOptions, target: "av-cell"} : assetUploadOptions;+ const avAssetUploadSuccess = avAssetUploadHandler ?+ (_response: unknown, result: Omit<IAssetUploadResult, "requestId" | "input">) => avAssetUploadHandler(result) :+ undefined;let textHTML: string;let textPlain: string;let siyuanHTML: string;@@ -685,7 +697,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven}} else {if (!blockDOMSanitizer && event.localFiles?.length > 0) {- readLocalFile(protyle, event.localFiles, assetUploadOptions);+ readLocalFile(protyle, event.localFiles, directAssetUploadOptions, avAssetUploadSuccess);return;}textHTML = event.textHTML;@@ -733,7 +745,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvenreturn;}if (localFiles.length > 0) {- readLocalFile(protyle, localFiles, assetUploadOptions);+ readLocalFile(protyle, localFiles, directAssetUploadOptions, avAssetUploadSuccess);return;}}@@ -888,7 +900,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven}if (!nodeElement) {if (files && files.length > 0) {- uploadFiles(protyle, files, undefined, undefined, undefined, assetUploadOptions);+ uploadFiles(protyle, files, undefined, avAssetUploadSuccess, undefined, directAssetUploadOptions);}return;}@@ -1112,7 +1124,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven}const fallback = getWPSPresentationFallback(wpsPresentation.type, Boolean(files?.length));if (fallback === "files") {- uploadFiles(protyle, files, undefined, undefined, undefined, assetUploadOptions);+ uploadFiles(protyle, files, undefined, avAssetUploadSuccess, undefined, directAssetUploadOptions);return;}files = [];@@ -1368,7 +1380,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEveninsertConvertedBlockDOM(protyle, conversionResponse.data, range);return;} else if (files && files.length > 0) {- uploadFiles(protyle, files, undefined, undefined, undefined, assetUploadOptions);+ uploadFiles(protyle, files, undefined, avAssetUploadSuccess, undefined, directAssetUploadOptions);return;} else if (textPlain.trim() !== "" && (files && files.length === 0 || !files)) {const selectedText = stripSemanticMarkersFromRangeText(range).split(Constants.ZWSP).join("");diff --git a/kernel/model/upload.go b/kernel/model/upload.goindex fd3844d950..03766316a4 100644--- a/kernel/model/upload.go+++ b/kernel/model/upload.go@@ -66,18 +66,17 @@ func InsertAssetBytes(id, fileName string, data []byte) (assetPath string, creatreturn "", false, err}if existAssetPath := GetAssetPathByHash(hash, bt.BoxID); existAssetPath != "" {- originalName := util.RemoveID(filepath.Base(existAssetPath))- if strings.EqualFold(fName, originalName) {+ originalName := assetNameWithoutID(filepath.Base(existAssetPath))+ if strings.EqualFold(assetNameWithoutID(fName), originalName) {return strings.TrimPrefix(existAssetPath, "/"), false, nil}hash = "random_2_" + gulu.Rand.String(12)}- blockID := ast.NewNodeID()if IsEncryptedBox(bt.BoxID) {- fName = encryptedAssetName(util.Ext(fName), blockID)+ fName = encryptedAssetName(util.Ext(fName), ast.NewNodeID())} else {- fName = util.AssetName(fName, blockID)+ fName = newAssetFileName(fName)}writePath := filepath.Join(assetsDirPath, fName)if err = writeAssetFile(writePath, bytes.NewReader(data), bt.BoxID, baseName); err != nil {@@ -117,6 +116,33 @@ func recordAssetUploadFailure(failedFiles *[]AssetUploadFailure, index int, name*failedFiles = append(*failedFiles, AssetUploadFailure{Index: index, Name: name, Error: err.Error()})}+// assetNameWithoutID 移除外部文件名携带的资源 ID,并为仅由 ID 组成的名称补充可读前缀。+func assetNameWithoutID(name string) string {+ ext := util.Ext(name)+ base := strings.TrimSuffix(name, ext)+ _, id := util.LastID(name)+ if ast.IsNodeIDPattern(id) {+ base = strings.TrimSuffix(base[:len(base)-len(id)], "-")+ }+ if base == "" || ast.IsNodeIDPattern(base) {+ base = "asset"+ }+ return base + ext+}++// newAssetFileName 为新增资源生成新的资源 ID,避免外部文件名指定已有资源的写入路径。+func newAssetFileName(name string) string {+ return util.AssetName(assetNameWithoutID(name), ast.NewNodeID())+}++func readRTFDDir(dir string) ([]os.DirEntry, error) {+ entries, err := os.ReadDir(dir)+ if err != nil {+ logging.LogErrorf("read dir [%s] failed: %s", dir, err)+ }+ return entries, err+}+func copyRTFDEntries(entries []os.DirEntry, srcDir, destDir string, copyFile func(string, string) error) error {for _, entry := range entries {from := filepath.Join(srcDir, entry.Name())@@ -219,8 +245,8 @@ func insertLocalAssets(id string, assetAbsPaths []string, isUpload, validateHTMLexistAssetPath := GetAssetPathByHash(hash, boxID)if "" != existAssetPath {- originalName := util.RemoveID(filepath.Base(existAssetPath))- if strings.ToLower(fName) != strings.ToLower(originalName) {+ originalName := assetNameWithoutID(filepath.Base(existAssetPath))+ if !strings.EqualFold(assetNameWithoutID(fName), originalName) {hash = "random_2_" + gulu.Rand.String(12)}}@@ -229,12 +255,11 @@ func insertLocalAssets(id string, assetAbsPaths []string, isUpload, validateHTMLrecordAssetUploadSuccess(succMap, &succFiles, index, baseName, strings.TrimPrefix(existAssetPath, "/"))f.Close()} else {- blockID := ast.NewNodeID()if IsEncryptedBox(boxID) {// 加密 box:磁盘文件名脱敏为 uuid-blockID.ext,原始名存加密映射- fName = encryptedAssetName(util.Ext(fName), blockID)+ fName = encryptedAssetName(util.Ext(fName), ast.NewNodeID())} else {- fName = util.AssetName(fName, blockID)+ fName = newAssetFileName(fName)}writePath := filepath.Join(assetsDirPath, fName)if _, seekErr := f.Seek(0, io.SeekStart); seekErr != nil {@@ -382,8 +407,8 @@ func Upload(c *gin.Context) {existAssetPath := GetAssetPathByHash(hash, uploadBoxID)if "" != existAssetPath {- originalName := util.RemoveID(filepath.Base(existAssetPath))- if strings.ToLower(fName) != strings.ToLower(originalName) {+ originalName := assetNameWithoutID(filepath.Base(existAssetPath))+ if !strings.EqualFold(assetNameWithoutID(fName), originalName) {hash = "random_2_" + gulu.Rand.String(12)}}@@ -417,14 +442,14 @@ func Upload(c *gin.Context) {}}- if "" == lastID {- lastID = ast.NewNodeID()- }if IsEncryptedBox(uploadBoxID) {+ if "" == lastID {+ lastID = ast.NewNodeID()+ }// 加密 box:磁盘文件名脱敏为 uuid-blockID.ext,原始名存加密映射fName = encryptedAssetName(util.Ext(fName), lastID)} else {- fName = util.AssetName(fName, lastID)+ fName = newAssetFileName(fName)}writePath := filepath.Join(assetsDirPath, fName)tmpDir := filepath.Join(util.TempDir, "convert", "zip", gulu.Rand.String(7))@@ -466,7 +491,7 @@ func Upload(c *gin.Context) {fName = strings.TrimSuffix(fName, ext)ext = strings.ToLower(ext)fName += ext- fName = util.AssetName(fName, ast.NewNodeID())+ fName = newAssetFileName(fName)tmpDir2 := filepath.Join(util.TempDir, "convert", "zip", gulu.Rand.String(7))if err = gulu.Zip.Unzip(writePath, tmpDir2); err != nil {recordFailure(index, file.Filename, fName, err)@@ -475,9 +500,8 @@ func Upload(c *gin.Context) {continue}- entries, readErr := os.ReadDir(tmpDir2)+ entries, readErr := readRTFDDir(tmpDir2)if nil != readErr {- logging.LogErrorf("read dir [%s] failed: %s", tmpDir2, readErr)recordFailure(index, file.Filename, fName, readErr)_ = os.RemoveAll(tmpDir)_ = os.RemoveAll(tmpDir2)@@ -493,9 +517,8 @@ func Upload(c *gin.Context) {}dirName := entries[0].Name()srcDir := filepath.Join(tmpDir2, dirName)- entries, readErr = os.ReadDir(srcDir)+ entries, readErr = readRTFDDir(srcDir)if nil != readErr {- logging.LogErrorf("read dir [%s] failed: %s", filepath.Join(tmpDir2, entries[0].Name()), readErr)recordFailure(index, file.Filename, fName, readErr)_ = os.RemoveAll(tmpDir)_ = os.RemoveAll(tmpDir2)@@ -644,7 +667,7 @@ func storeAssetForBox(boxID, assetDirPath, originalName string, data []byte) (diname = "asset"}for {- diskName = util.AssetName(name+ext, ast.NewNodeID())+ diskName = newAssetFileName(name + ext)writePath = filepath.Join(assetDirPath, diskName)if !filelock.IsExist(writePath) {breakdiff --git a/kernel/model/upload_test.go b/kernel/model/upload_test.goindex e5fe0477b4..4bdd140e99 100644--- a/kernel/model/upload_test.go+++ b/kernel/model/upload_test.go@@ -119,6 +119,17 @@ func executeAssetUploadTestRequest(t *testing.T, request *http.Request) assetUplreturn response}+func cleanupAssetUploadTestHashes(t *testing.T, successes []AssetUploadSuccess) {+ t.Helper()+ t.Cleanup(func() {+ for _, success := range successes {+ if hash := cache.GetAssetHashByPath(success.Path); hash != nil {+ cache.RemoveAssetHash(hash.Hash)+ }+ }+ })+}+func TestRecordAssetUploadSuccessPreservesDuplicateNames(t *testing.T) {succMap := map[string]any{}var succFiles []AssetUploadSuccess@@ -253,6 +264,126 @@ func TestMultipartUploadContinuesAfterDuplicateMatch(t *testing.T) {}}+func TestMultipartUploadDoesNotOverwriteFilesWithTheSameAssetID(t *testing.T) {+ assetsDir := setupAssetUploadTest(t)+ name := "photo-20260828120000-abcdefg.png"+ firstData := []byte("first file with an existing asset ID")+ secondData := []byte("second file with an existing asset ID")+ cacheAssetUploadTestFile(t, assetsDir, "first-seed.png", firstData)+ cacheAssetUploadTestFile(t, assetsDir, "second-seed.png", secondData)+ request := newAssetUploadTestRequest(t, []assetUploadTestFile{+ {name: name, data: firstData},+ {name: name, data: secondData},+ }, nil)++ response := executeAssetUploadTestRequest(t, request)+ cleanupAssetUploadTestHashes(t, response.Data.SuccFiles)++ if len(response.Data.FailedFiles) != 0 || len(response.Data.SuccFiles) != 2 {+ t.Fatalf("unexpected upload response: %+v", response)+ }+ firstPath := response.Data.SuccFiles[0].Path+ secondPath := response.Data.SuccFiles[1].Path+ if firstPath == secondPath {+ t.Fatalf("different files used the same asset path: %s", firstPath)+ }+ firstUploaded, err := os.ReadFile(filepath.Join(assetsDir, filepath.Base(firstPath)))+ if err != nil {+ t.Fatal(err)+ }+ secondUploaded, err := os.ReadFile(filepath.Join(assetsDir, filepath.Base(secondPath)))+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(firstUploaded, firstData) || !bytes.Equal(secondUploaded, secondData) {+ t.Fatalf("uploaded contents were overwritten: first=%q second=%q", firstUploaded, secondUploaded)+ }+}++func TestMultipartUploadReusesSameContentWhenAssetIDsDiffer(t *testing.T) {+ assetsDir := setupAssetUploadTest(t)+ existingName := "photo-20260828120001-hijklmn.png"+ uploadName := "photo-20260828120000-abcdefg.png"+ data := []byte("same file with an existing asset ID")+ cacheAssetUploadTestFile(t, assetsDir, existingName, data)+ request := newAssetUploadTestRequest(t, []assetUploadTestFile{+ {name: uploadName, data: data},+ {name: uploadName, data: data},+ }, nil)++ response := executeAssetUploadTestRequest(t, request)++ if len(response.Data.FailedFiles) != 0 || len(response.Data.SuccFiles) != 2 {+ t.Fatalf("unexpected upload response: %+v", response)+ }+ expectedPath := "assets/" + existingName+ if response.Data.SuccFiles[0].Path != expectedPath || response.Data.SuccFiles[1].Path != expectedPath {+ t.Fatalf("identical files were not reused: %+v", response.Data.SuccFiles)+ }+ entries, err := os.ReadDir(assetsDir)+ if err != nil {+ t.Fatal(err)+ }+ if len(entries) != 1 {+ t.Fatalf("identical files created %d assets", len(entries))+ }+}++func TestInsertLocalAssetsDoesNotOverwriteFilesWithTheSameAssetID(t *testing.T) {+ assetsDir := setupAssetUploadTest(t)+ name := "photo-20260828120000-abcdefg.png"+ firstData := []byte("first local file with an existing asset ID")+ secondData := []byte("second local file with an existing asset ID")+ cacheAssetUploadTestFile(t, assetsDir, "first-local-seed.png", firstData)+ cacheAssetUploadTestFile(t, assetsDir, "second-local-seed.png", secondData)+ firstPath := filepath.Join(t.TempDir(), name)+ secondPath := filepath.Join(t.TempDir(), name)+ if err := os.WriteFile(firstPath, firstData, 0644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(secondPath, secondData, 0644); err != nil {+ t.Fatal(err)+ }++ _, successes, failures, err := InsertLocalAssets("", []string{firstPath, secondPath}, true)+ if err != nil {+ t.Fatal(err)+ }+ cleanupAssetUploadTestHashes(t, successes)+ if len(failures) != 0 || len(successes) != 2 {+ t.Fatalf("unexpected local upload result: successes=%+v failures=%+v", successes, failures)+ }+ if successes[0].Path == successes[1].Path {+ t.Fatalf("different local files used the same asset path: %+v", successes)+ }+ firstUploaded, err := os.ReadFile(filepath.Join(assetsDir, filepath.Base(successes[0].Path)))+ if err != nil {+ t.Fatal(err)+ }+ secondUploaded, err := os.ReadFile(filepath.Join(assetsDir, filepath.Base(successes[1].Path)))+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(firstUploaded, firstData) || !bytes.Equal(secondUploaded, secondData) {+ t.Fatalf("local uploaded contents were overwritten: first=%q second=%q", firstUploaded, secondUploaded)+ }+}++func TestReadRTFDDirReturnsAnErrorForAFile(t *testing.T) {+ filePath := filepath.Join(t.TempDir(), ".DS_Store")+ if err := os.WriteFile(filePath, []byte("metadata"), 0644); err != nil {+ t.Fatal(err)+ }++ entries, err := readRTFDDir(filePath)+ if err == nil {+ t.Fatal("expected reading a file as an RTFD directory to fail")+ }+ if len(entries) != 0 {+ t.Fatalf("unexpected RTFD entries: %+v", entries)+ }+}+func TestCopyRTFDEntriesRemovesPartialDestinationOnFailure(t *testing.T) {srcDir := t.TempDir()destDir := filepath.Join(t.TempDir(), "document.rtfd")