Skip to content

Build your personal knowledge base with Trilium Notes

fix(onenote): abort import when section enumeration fails systemically

Elian Dorane7ea9f0c1af1
diff --git a/apps/server/src/services/import/onenote/importer.spec.ts b/apps/server/src/services/import/onenote/importer.spec.ts
index f1be1d6ee4..1bf54ceffd 100644
--- a/apps/server/src/services/import/onenote/importer.spec.ts
+++ b/apps/server/src/services/import/onenote/importer.spec.ts
@@ -375,6 +375,69 @@ describe("importSelection (real DB)", () => {
expect(parent.getChildNotes()).toHaveLength(0);
});
+ it("aborts the import when too many consecutive sections fail to enumerate (systemic failure)", async () => {
+ // Every section's page list fails for a non-protected reason (e.g. the token expired mid-import):
+ // this must abort rather than build a placeholder-only tree and report success.
+ graphMock.isEncryptedSectionError.mockReturnValue(false);
+ graphMock.listPages.mockClear();
+ graphMock.listPages.mockImplementation(async () => {
+ throw new Error("Microsoft Graph request failed (HTTP 401: 40001: Access token has expired.)");
+ });
+
+ const parent = cls.init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "section breaker parent",
+ content: "",
+ type: "text",
+ mime: "text/html"
+ }).note);
+
+ await cls.init(() => importSelection({
+ getAccessToken: () => Promise.resolve("token"),
+ parentNoteId: parent.noteId,
+ sections: Array.from({ length: 8 }, (_, i) => ({ id: `sec-cb${i}`, title: `SB Section ${i}`, groupPath: [], notebookId: "nb-sb", notebookTitle: "SB Notebook" })),
+ taskId: "task-section-breaker"
+ }));
+
+ // Six consecutive enumeration failures trip the breaker: the remaining sections are never listed
+ // and the import aborts without creating any notes (a placeholder-only tree would be worthless).
+ expect(graphMock.listPages).toHaveBeenCalledTimes(6);
+ expect(parent.getChildNotes()).toHaveLength(0);
+ });
+
+ it("does not trip the section breaker on a notebook full of password-protected sections", async () => {
+ // Password-protected sections are an expected, healthy outcome (Graph answers with 403/20185), so
+ // even a long run of them must not abort — every one becomes a placeholder.
+ graphMock.isEncryptedSectionError.mockImplementation((e) => e instanceof Error && e.message.includes("20185"));
+ graphMock.listPages.mockClear();
+ graphMock.listPages.mockImplementation(async () => {
+ throw new Error("Microsoft Graph request failed (HTTP 403: 20185: Encrypted sections are not accessible.)");
+ });
+
+ const parent = cls.init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "all locked parent",
+ content: "",
+ type: "text",
+ mime: "text/html"
+ }).note);
+
+ await cls.init(() => importSelection({
+ getAccessToken: () => Promise.resolve("token"),
+ parentNoteId: parent.noteId,
+ sections: Array.from({ length: 8 }, (_, i) => ({ id: `sec-lk${i}`, title: `Locked ${i}`, groupPath: [], notebookId: "nb-lk", notebookTitle: "Locked Notebook" })),
+ taskId: "task-all-locked"
+ }));
+
+ // All eight were listed (no early abort) and each imported as a locked placeholder folder. Scope
+ // the check to this import's tree: import root → the single shared notebook folder → 8 sections.
+ expect(graphMock.listPages).toHaveBeenCalledTimes(8);
+ const notebookFolder = parent.getChildNotes()[0]?.getChildNotes()[0];
+ const sectionNotes = notebookFolder?.getChildNotes() ?? [];
+ expect(sectionNotes).toHaveLength(8);
+ expect(sectionNotes.every((note) => note.getOwnedLabelValue("iconClass") === "bx bx-lock-alt")).toBe(true);
+ });
+
it("does not trip the breaker when pages fetch but fail local processing", async () => {
// All eight pages fetch successfully (Graph is healthy) but every one fails to convert. These
// are isolated bad pages, not a systemic outage, so the import must finish with placeholders
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index 9319f7f53d..7a23109dd6 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -65,6 +65,16 @@ interface FetchedPage {
*/
const MAX_CONSECUTIVE_PAGE_FAILURES = 5;
+/**
+ * Aborts the import once this many sections in a row fail to enumerate for a non-protected reason.
+ * A section whose page list can't be listed normally becomes a placeholder folder, but a streak of
+ * such failures means a systemic problem (expired token, Graph outage) rather than individual bad
+ * sections — failing fast beats marking a placeholder-only tree "successful". Password-protected
+ * sections don't count: Graph answered cleanly (a structured 403/20185), so auth and connectivity
+ * are healthy and a placeholder is the correct, expected outcome.
+ */
+const MAX_CONSECUTIVE_SECTION_FAILURES = 5;
+
interface DownloadedResource {
/** The Graph resource URL as it still appears in the converted HTML; used to match references. */
url: string;
@@ -118,6 +128,7 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
// Enumerate every selected section's pages up front so the total page count is known before
// any content is fetched — this lets the client show a real progress bar rather than a bare count.
const sectionPages: { section: OneNoteSectionSelection; pages: OneNotePage[]; error?: string; passwordProtected?: boolean }[] = [];
+ let consecutiveSectionFailures = 0;
for (const section of sections) {
// A section whose page list can't be fetched doesn't abort the whole import: it is tagged
// with the error here and imported as a placeholder folder below, holding its place so the
@@ -125,6 +136,7 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
// sections — which Graph rejects outright — as well as any other per-section Graph failure.
try {
sectionPages.push({ section, pages: await graph.listPages(getAccessToken, section.id) });
+ consecutiveSectionFailures = 0;
} catch (e: unknown) {
const rawMessage = e instanceof Error ? e.message : String(e);
// A password-protected section is a user-fixable, expected case, so replace Graph's opaque
@@ -134,6 +146,15 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
const error = passwordProtected ? t("onenote_import.protected-section-error") : rawMessage;
getLog().error(`OneNote import: could not list the pages of section '${section.title}' (${section.id}); it will be imported as a placeholder: ${rawMessage}`);
sectionPages.push({ section, pages: [], error, passwordProtected });
+
+ // Only unexpected failures count toward the circuit breaker: a protected section means
+ // Graph is healthy (it returned a structured 403/20185), so it doesn't signal a systemic
+ // problem and mustn't trip the breaker on a notebook full of locked sections.
+ if (passwordProtected) {
+ consecutiveSectionFailures = 0;
+ } else if (++consecutiveSectionFailures > MAX_CONSECUTIVE_SECTION_FAILURES) {
+ throw new Error(`Aborting the OneNote import: ${consecutiveSectionFailures} sections in a row failed to list their pages, which points to a systemic problem (expired authentication, Graph outage) rather than individual unreadable sections. Last error: ${rawMessage}`);
+ }
}
}
taskContext.setTotalCount(sectionPages.reduce((total, entry) => total + entry.pages.length, 0));