Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(desktop): reuse the temp file when reopening an unchanged note
Elian Doran12754d771db6
diff --git a/apps/server/src/routes/api/files.spec.ts b/apps/server/src/routes/api/files.spec.tsindex 1ec65557da..6dc1dabb2c 100644--- a/apps/server/src/routes/api/files.spec.ts+++ b/apps/server/src/routes/api/files.spec.ts@@ -133,7 +133,8 @@ describe("Files API", () => {it("removes the other temp files when one cannot be removed", () => {const locked = cls.init(() => filesRoute.saveNoteToTmpDir(fileReq({ noteId }))).tmpFilePath;- const other = cls.init(() => filesRoute.saveNoteToTmpDir(fileReq({ noteId }))).tmpFilePath;+ const attachmentReq = fileReq({ attachmentId } as Record<string, string>) as unknown as Request<{ attachmentId: string }>;+ const other = cls.init(() => filesRoute.saveAttachmentToTmpDir(attachmentReq)).tmpFilePath;const rmSync = fs.rmSync;const spy = vi.spyOn(fs, "rmSync").mockImplementation((filePath, options) => {if (filePath === locked) {@@ -170,6 +171,18 @@ describe("Files API", () => {const save = () => cls.init(() => filesRoute.saveNoteToTmpDir(fileReq({ noteId: watchedNoteId }))).tmpFilePath;+ it("reuses the temp file while it holds the note's content, and keeps one with pending edits", () => {+ const first = save();+ expect(save()).toBe(first);+ expect(h.watchers).toHaveLength(1);++ fs.writeFileSync(first, "pending edit");+ const second = save();+ expect(second).not.toBe(first);+ expect(fs.readFileSync(first, "utf8")).toBe("pending edit");+ expect(h.watchers.map((watcher) => watcher.path)).toEqual([ first, second ]);+ });+it("reports the modification time of a changed file", () => {const tmpFilePath = save();const [ watcher ] = h.watchers;diff --git a/apps/server/src/routes/api/files.ts b/apps/server/src/routes/api/files.tsindex 9fbe7d4cd4..14ca72730b 100644--- a/apps/server/src/routes/api/files.ts+++ b/apps/server/src/routes/api/files.ts@@ -29,8 +29,17 @@ function saveAttachmentToTmpDir(req: Request<{ attachmentId: string }>) {}const createdTemporaryFiles = new Set<string>();+/** The latest temp file of each entity, keyed by `entityType/entityId`. */+const latestTemporaryFiles = new Map<string, string>();function saveToTmpDir(fileName: string, content: string | Uint8Array, entityType: string, entityId: string) {+ // Opening an entity again reuses its temp file and watcher, unless the file holds edits that are not uploaded yet.+ const entityKey = `${entityType}/${entityId}`;+ const latest = latestTemporaryFiles.get(entityKey);+ if (latest && holdsContent(latest, content)) {+ return { tmpFilePath: latest };+ }+const tmpFileName = `tmp-${process.pid}-${utils.randomString(12)}-${fileName}`;const tmpFilePath = path.resolve(dataDirs.TMP_DIR, tmpFileName);fs.writeFileSync(tmpFilePath, content, { flag: "wx", mode: 0o600 });@@ -39,6 +48,7 @@ function saveToTmpDir(fileName: string, content: string | Uint8Array, entityTypeprocess.once("exit", removeTemporaryFiles);}createdTemporaryFiles.add(tmpFilePath);+ latestTemporaryFiles.set(entityKey, tmpFilePath);getLog().info(`Saved temporary file ${tmpFilePath}`);@@ -59,6 +69,14 @@ function saveToTmpDir(fileName: string, content: string | Uint8Array, entityType};}+function holdsContent(filePath: string, content: string | Uint8Array) {+ try {+ return fs.readFileSync(filePath).equals(Buffer.from(content));+ } catch {+ return false;+ }+}+function removeTemporaryFiles() {for (const filePath of createdTemporaryFiles) {try {