Skip to content

Build your personal knowledge base with Trilium Notes

feat(onenote): show Graph throttling in the import progress toast

Elian Doran2a789e109813
diff --git a/apps/client/src/services/import.ts b/apps/client/src/services/import.ts
index 9bf2ae2301..c7ff965c61 100644
--- a/apps/client/src/services/import.ts
+++ b/apps/client/src/services/import.ts
@@ -80,6 +80,8 @@ function makeToast(id: string, message: string): ToastOptionsWithRequiredId {
/**
* Builds the persistent "import in progress" toast:
+ * - the "throttled" phase (OneNote under Graph rate limiting) → an explicit "waiting for the service"
+ * message, since the count can legitimately sit still for up to an hour and must not look hung;
* - a phase is known (zip import) → a phase-specific message: "Extracted X items of N" while extracting
* archive entries, "Processed X notes of N" while post-processing the created notes;
* - a total but no phase (single-format importers like Notion/Obsidian) → "Imported X notes of N";
@@ -90,7 +92,11 @@ function makeToast(id: string, message: string): ToastOptionsWithRequiredId {
function makeProgressToast(taskId: string, progressCount: number, totalCount?: number, phase?: ProgressPhase): ToastOptionsWithRequiredId {
const hasTotal = typeof totalCount === "number" && totalCount > 0;
let message: string;
- if (hasTotal && phase === "extracting") {
+ if (phase === "throttled") {
+ message = hasTotal
+ ? t("import.throttled-with-total", { progress: progressCount, total: totalCount })
+ : t("import.throttled");
+ } else if (hasTotal && phase === "extracting") {
message = t("import.extracting", { progress: progressCount, total: totalCount });
} else if (hasTotal && phase === "processing") {
message = t("import.processing", { progress: progressCount, total: totalCount });
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index a22ab53570..1abe0bb243 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -243,6 +243,8 @@
"in-progress-with-total": "Imported {{progress}} notes out of {{total}}",
"extracting": "Extracted {{progress}} items out of {{total}}",
"processing": "Processed {{progress}} notes out of {{total}}",
+ "throttled": "The service is rate limiting requests; the import is waiting for access to resume…",
+ "throttled-with-total": "Imported {{progress}} notes out of {{total}} — the service is rate limiting requests, waiting for access to resume…",
"successful": "Import finished successfully."
},
"file_upload": {
diff --git a/apps/server/src/services/import/onenote/graph.spec.ts b/apps/server/src/services/import/onenote/graph.spec.ts
index d8c2d107ef..a2438f8fc1 100644
--- a/apps/server/src/services/import/onenote/graph.spec.ts
+++ b/apps/server/src/services/import/onenote/graph.spec.ts
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../../safe_fetch.js", () => ({ safeFetch: vi.fn() }));
import { safeFetch } from "../../safe_fetch.js";
-import { backoffDelayMs, ENCRYPTED_SECTION_ERROR_CODE, extractGraphErrorDetail, getAccount, getPageContent, getResource, getThrottleStats, GraphRequestError, isEncryptedSectionError, listPages, resetThrottleGate, resetThrottleStats, retryAfterMs, sanitizeGraphUrl } from "./graph.js";
+import { backoffDelayMs, ENCRYPTED_SECTION_ERROR_CODE, extractGraphErrorDetail, getAccount, getPageContent, getResource, getThrottleStats, GraphRequestError, isEncryptedSectionError, listPages, resetThrottleGate, resetThrottleStats, retryAfterMs, sanitizeGraphUrl, setThrottleListener } from "./graph.js";
const safeFetchMock = vi.mocked(safeFetch);
@@ -68,10 +68,40 @@ describe("throttling retries", () => {
afterEach(() => {
resetThrottleGate();
+ setThrottleListener(null);
vi.useRealTimers();
safeFetchMock.mockReset();
});
+ it("notifies the registered throttle listener on each gate extension, and stops once cleared", async () => {
+ const listener = vi.fn();
+ setThrottleListener(listener);
+ let calls = 0;
+ safeFetchMock.mockImplementation(async () => {
+ calls++;
+ return calls <= 2 ? graphResponse(429, "", { "Retry-After": "30" }) : graphResponse(200, JSON.stringify({ displayName: "Ada" }));
+ });
+
+ const promise = getAccount(token);
+ await vi.runAllTimersAsync();
+ await expect(promise).resolves.toEqual({ name: "Ada", email: "" });
+
+ // One notification per throttled response, carrying the wait pushed onto the shared gate —
+ // this is what lets the importer flip its progress toast to "waiting out rate limiting".
+ expect(listener).toHaveBeenCalledTimes(2);
+ expect(listener).toHaveBeenCalledWith(30_000);
+
+ // After clearing (the importer does this when its run ends), later throttling must not reach
+ // the stale listener.
+ setThrottleListener(null);
+ calls = 0;
+ safeFetchMock.mockClear();
+ const second = getAccount(token);
+ await vi.runAllTimersAsync();
+ await second;
+ expect(listener).toHaveBeenCalledTimes(2);
+ });
+
it("keeps retrying well past eight attempts while the wait budget lasts", async () => {
let calls = 0;
safeFetchMock.mockImplementation(async () => {
diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.ts
index 6e951451bf..9ca45c6f5e 100644
--- a/apps/server/src/services/import/onenote/graph.ts
+++ b/apps/server/src/services/import/onenote/graph.ts
@@ -50,6 +50,18 @@ const MAX_GATEWAY_TIMEOUT_RETRIES = 5;
// "don't send until" timestamp that ALL requests wait on, so the whole pool backs off together.
let throttledUntilMs = 0;
+// Notified whenever the shared throttle gate is extended — i.e. Graph is actively throttling and every
+// request is now waiting. The importer uses this to flip its progress toast to a "waiting out rate
+// limiting" message: during a long throttle window no page completes, so the progress count sits still
+// for up to an hour and is otherwise indistinguishable from a hang (users have killed multi-hour
+// imports — losing all fetched work — over exactly that).
+let throttleListener: ((waitMs: number) => void) | null = null;
+
+/** Registers (or clears, with null) the single throttle-gate listener. */
+export function setThrottleListener(listener: ((waitMs: number) => void) | null): void {
+ throttleListener = listener;
+}
+
// Aggregate throttle statistics for the current import, surfaced in the import report (they answer
// "why did this take hours?"). `requestCount` counts throttled (429/503) responses; `waitMs`
// accumulates net extensions of the shared gate — wall-clock time spent waiting out throttles —
@@ -126,6 +138,7 @@ async function graphFetch(getAccessToken: AccessTokenProvider, url: string): Pro
throttledUntilMs = Math.max(throttledUntilMs, Date.now() + waitMs);
throttleAttempt++;
getLog().info(`OneNote import: Graph throttled (HTTP ${response.status}) on ${sanitizeGraphUrl(url)}; retry ${throttleAttempt} after ${waitMs}ms (${Math.round((giveUpAtMs - Date.now()) / 60_000)}min of wait budget left)`);
+ throttleListener?.(waitMs);
}
}
@@ -489,5 +502,6 @@ export default {
getResource,
getThrottleStats,
resetThrottleStats,
+ setThrottleListener,
isEncryptedSectionError
};
diff --git a/apps/server/src/services/import/onenote/importer.spec.ts b/apps/server/src/services/import/onenote/importer.spec.ts
index c080c692a0..e138e2daa1 100644
--- a/apps/server/src/services/import/onenote/importer.spec.ts
+++ b/apps/server/src/services/import/onenote/importer.spec.ts
@@ -1,4 +1,4 @@
-import { becca, cls, date_utils, note_service as noteService } from "@triliumnext/core";
+import { becca, cls, date_utils, note_service as noteService, ws } from "@triliumnext/core";
import { beforeAll, describe, expect, it, vi } from "vitest";
import sqlInit from "../../sql_init.js";
@@ -14,6 +14,7 @@ vi.mock("./graph.js", () => ({
getResource: vi.fn(),
getThrottleStats: vi.fn(() => ({ requestCount: 0, waitMs: 0 })),
resetThrottleStats: vi.fn(),
+ setThrottleListener: vi.fn(),
isEncryptedSectionError: vi.fn(() => false)
}
}));
@@ -120,6 +121,57 @@ describe("importSelection (real DB)", () => {
expect(sectionNote?.getOwnedLabelValue("oneNotePageId")).toBeNull();
});
+ it("reports a throttled phase while Graph rate limits and clears it once work resumes", async () => {
+ const sent: { type: string; taskId?: string; phase?: string; progressCount?: number }[] = [];
+ const wsSpy = vi.spyOn(ws, "sendMessageToAllClients").mockImplementation((message) => {
+ sent.push(message as (typeof sent)[number]);
+ });
+
+ // Capture the listener importSelection registers so the test can play the role of graphFetch's
+ // shared throttle gate.
+ let throttleListener: ((waitMs: number) => void) | null = null;
+ graphMock.setThrottleListener.mockImplementation((listener) => {
+ throttleListener = listener;
+ });
+
+ graphMock.listPages.mockResolvedValue([{ id: "1-thr", title: "Throttled Page", level: 0 }]);
+ graphMock.getPageContent.mockImplementation(async () => {
+ // Two gate extensions before the page finally arrives — a sustained throttle re-fires the
+ // listener on every retry, but the toast must only be flipped once.
+ throttleListener?.(30_000);
+ throttleListener?.(60_000);
+ return { html: "<p>hello</p>", inkml: "" };
+ });
+
+ try {
+ await cls.init(() => importSelection({
+ getAccessToken: () => Promise.resolve("token"),
+ parentNoteId: "root",
+ sections: [{ id: "sec-thr", title: "Throttled Section", groupPath: [], notebookId: "nb-thr", notebookTitle: "Notebook" }],
+ taskId: "task-throttled"
+ }));
+ } finally {
+ wsSpy.mockRestore();
+ }
+
+ const progress = sent.filter((message) => message.type === "taskProgressCount" && message.taskId === "task-throttled");
+ const throttledIndex = progress.findIndex((message) => message.phase === "throttled");
+
+ // The throttle flips the toast exactly once (repeat extensions are deduplicated)...
+ expect(throttledIndex).toBeGreaterThanOrEqual(0);
+ expect(progress.filter((message) => message.phase === "throttled")).toHaveLength(1);
+
+ // ...and the next completed unit of work sends promptly with the label gone, so the toast
+ // returns to the normal "Imported X out of N" message.
+ const after = progress.slice(throttledIndex + 1);
+ expect(after.length).toBeGreaterThan(0);
+ expect(after.every((message) => message.phase === undefined)).toBe(true);
+
+ // The run unregisters its listener so a stale one can't outlive the import.
+ expect(graph.setThrottleListener).toHaveBeenLastCalledWith(null);
+ graphMock.setThrottleListener.mockReset();
+ });
+
it("writes an import report as the root import note's content", async () => {
graphMock.listPages.mockResolvedValue([
{ id: "1-abc", title: "Report Page One", level: 0 },
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index b9b63d7230..25e72d4bc5 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -122,6 +122,24 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
const startedAtMs = Date.now();
graph.resetThrottleStats();
+ // While Graph is throttling, no page completes and the progress count sits still — for up to an
+ // hour — which looks exactly like a hang; users have killed healthy multi-hour imports (losing all
+ // fetched work, since notes are only committed at the end) over it. So the first gate extension
+ // flips the toast to a "waiting out rate limiting" phase, and the next completed unit of work flips
+ // it back (clearThrottledPhase below). The extra flag keeps a sustained throttle — which re-fires
+ // the listener on every retry — from re-sending an identical message each time.
+ let throttleReported = false;
+ graph.setThrottleListener(() => {
+ if (!throttleReported) {
+ throttleReported = true;
+ taskContext.reportPhase("throttled");
+ }
+ });
+ const clearThrottledPhase = () => {
+ throttleReported = false;
+ taskContext.clearPhase();
+ };
+
try {
// Phase 1: pull everything over the network first, so note creation can run in a single
// synchronous transaction afterwards.
@@ -138,6 +156,7 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
try {
sectionPages.push({ section, pages: await graph.listPages(getAccessToken, section.id) });
consecutiveSectionFailures = 0;
+ clearThrottledPhase();
} 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
@@ -190,6 +209,7 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
throw new Error(`Aborting the OneNote import: ${consecutivePageFailures} pages in a row failed to fetch, which points to a systemic problem rather than individual broken pages. Last error: ${message}`);
}
fetchedPages.push(buildPlaceholderPage(page, message));
+ clearThrottledPhase();
taskContext.increaseProgressCount();
continue;
}
@@ -203,6 +223,7 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
getLog().error(`OneNote import: fetched page '${page.title}' (${page.id}) but could not process its content; a placeholder note will be imported instead: ${message}`);
fetchedPages.push(buildPlaceholderPage(page, message));
}
+ clearThrottledPhase();
taskContext.increaseProgressCount();
}
fetched.push(toFetchedSection(section, fetchedPages));
@@ -215,6 +236,8 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
} catch (e: unknown) {
getLog().error(`OneNote import failed: ${e instanceof Error ? (e.stack ?? e.message) : e}`);
taskContext.reportError(e instanceof Error ? e.message : String(e));
+ } finally {
+ graph.setThrottleListener(null);
}
}
diff --git a/packages/commons/src/lib/ws_api.ts b/packages/commons/src/lib/ws_api.ts
index c1e80d0025..e0cf91f62b 100644
--- a/packages/commons/src/lib/ws_api.ts
+++ b/packages/commons/src/lib/ws_api.ts
@@ -69,8 +69,12 @@ export type TaskResult<T extends TaskType> = TaskResultDefinitions[T];
* Identifies which phase of a multi-phase task a progress message belongs to, so the client can label
* the bar accordingly (e.g. zip import counts archive entries while "extracting", then notes while
* "processing"). Single-phase tasks omit it and the client falls back to a generic message.
+ *
+ * "throttled" is a transient state rather than a pipeline stage: the task is alive but deliberately
+ * waiting out an external service's rate limiting (e.g. the OneNote importer under Graph throttling),
+ * so the count will not move for a while and the client should say why instead of looking hung.
*/
-export type ProgressPhase = "extracting" | "processing";
+export type ProgressPhase = "extracting" | "processing" | "throttled";
type TaskDefinition<T extends TaskType> = {
type: "taskProgressCount",
diff --git a/packages/trilium-core/src/services/task_context.spec.ts b/packages/trilium-core/src/services/task_context.spec.ts
index 877eacbf4f..b27493fc38 100644
--- a/packages/trilium-core/src/services/task_context.spec.ts
+++ b/packages/trilium-core/src/services/task_context.spec.ts
@@ -135,6 +135,45 @@ describe("TaskContext", () => {
});
});
+ describe("reportPhase and clearPhase", () => {
+ it("pushes the phase immediately and drops it from the next flushed count", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1_000);
+ const ctx = new TaskContext("phase-2", "importNotes", importData);
+ ctx.setTotalCount(10);
+ sendMessageToAllClients.mockClear();
+
+ // reportPhase must not wait for the next unit of work — its whole point is signalling a
+ // stall (e.g. Graph throttling) while no counts are flowing, so it sends even inside the
+ // 300ms coalescing window and without an increment.
+ vi.setSystemTime(1_100);
+ ctx.reportPhase("throttled");
+ expect(sendMessageToAllClients).toHaveBeenCalledTimes(1);
+ expect(sendMessageToAllClients).toHaveBeenLastCalledWith(expect.objectContaining({ phase: "throttled", progressCount: 0, totalCount: 10 }));
+
+ // clearPhase alone sends nothing, but forces the next increment out immediately (still
+ // inside the window) — one message carrying the corrected label and count together.
+ vi.setSystemTime(1_200);
+ ctx.clearPhase();
+ expect(sendMessageToAllClients).toHaveBeenCalledTimes(1);
+ ctx.increaseProgressCount();
+ expect(sendMessageToAllClients).toHaveBeenCalledTimes(2);
+ expect(sendMessageToAllClients).toHaveBeenLastCalledWith(expect.not.objectContaining({ phase: expect.anything() }));
+
+ // With no phase set, clearPhase is inert — it must not defeat the coalescing window.
+ ctx.clearPhase();
+ vi.setSystemTime(1_300);
+ ctx.increaseProgressCount();
+ expect(sendMessageToAllClients).toHaveBeenCalledTimes(2);
+ });
+
+ it("stays silent for the reserved no-progress-reporting id", () => {
+ const ctx = new TaskContext("no-progress-reporting", "importNotes", importData);
+ ctx.reportPhase("throttled");
+ expect(sendMessageToAllClients).not.toHaveBeenCalled();
+ });
+ });
+
describe("reportError", () => {
it("broadcasts a taskError message with the failure text and task metadata", () => {
const ctx = new TaskContext("err-1", "importNotes", importData);
diff --git a/packages/trilium-core/src/services/task_context.ts b/packages/trilium-core/src/services/task_context.ts
index 2483ecd23a..4aabd7c457 100644
--- a/packages/trilium-core/src/services/task_context.ts
+++ b/packages/trilium-core/src/services/task_context.ts
@@ -72,24 +72,54 @@ class TaskContext<T extends TaskType> {
this.progressCount = 0;
}
+ /**
+ * Sets the phase and pushes the current progress immediately, without waiting for the next unit of
+ * work. For phases entered while no counts are flowing — e.g. the OneNote importer waiting out Graph
+ * throttling, where the next increaseProgressCount() may be an hour away — setPhase() alone would
+ * leave the client showing the previous label (and a seemingly hung count) the whole time.
+ */
+ reportPhase(phase: ProgressPhase) {
+ this.phase = phase;
+ this.sendProgressMessage();
+ }
+
+ /**
+ * Clears the phase so subsequent progress messages drop the label. Does not send by itself: callers
+ * clear right before counting the unit of work that ended the phase, and the forced flush here makes
+ * that very next increaseProgressCount() deliver the corrected label and count in one message.
+ */
+ clearPhase() {
+ if (this.phase !== null) {
+ this.phase = null;
+ this.lastSentCountTs = 0;
+ }
+ }
+
increaseProgressCount() {
this.progressCount++;
- if (Date.now() - this.lastSentCountTs >= 300 && this.taskId !== "no-progress-reporting") {
- this.lastSentCountTs = Date.now();
-
- ws.sendMessageToAllClients({
- type: "taskProgressCount",
- taskId: this.taskId,
- taskType: this.taskType,
- data: this.data,
- progressCount: this.progressCount,
- ...(this.totalCount !== null ? { totalCount: this.totalCount } : {}),
- ...(this.phase !== null ? { phase: this.phase } : {})
- } as WebSocketMessage);
+ if (Date.now() - this.lastSentCountTs >= 300) {
+ this.sendProgressMessage();
}
}
+ private sendProgressMessage() {
+ if (this.taskId === "no-progress-reporting") {
+ return;
+ }
+ this.lastSentCountTs = Date.now();
+
+ ws.sendMessageToAllClients({
+ type: "taskProgressCount",
+ taskId: this.taskId,
+ taskType: this.taskType,
+ data: this.data,
+ progressCount: this.progressCount,
+ ...(this.totalCount !== null ? { totalCount: this.totalCount } : {}),
+ ...(this.phase !== null ? { phase: this.phase } : {})
+ } as WebSocketMessage);
+ }
+
reportError(message: string) {
ws.sendMessageToAllClients({
type: "taskError",