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
feat(import/onenote): improve error tolerance and report errors properly
Elian Doran6df65c08683b
diff --git a/apps/client/src/services/onenote_import.spec.ts b/apps/client/src/services/onenote_import.spec.tsindex fea3181a0f..97a7c73ce3 100644--- a/apps/client/src/services/onenote_import.spec.ts+++ b/apps/client/src/services/onenote_import.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { buildSectionSelections, type OneNoteNotebook, orderedChildren } from "./onenote_import.js";+import { buildSectionSelections, extractServerMessage, type OneNoteNotebook, orderedChildren } from "./onenote_import.js";const NOTEBOOKS: OneNoteNotebook[] = [{@@ -96,3 +96,18 @@ describe("buildSectionSelections", () => {expect(buildSectionSelections(NOTEBOOKS, new Set(["does-not-exist"]))).toEqual([]);});});++describe("extractServerMessage", () => {+ it("unwraps both response shapes the API rejects with, and reports nothing usable as null", () => {+ // A thrown server error arrives as the JSON envelope; a [status, message] route result as text.+ expect(extractServerMessage('{"message":"The OneNote connection was lost."}')).toBe("The OneNote connection was lost.");+ expect(extractServerMessage("Not connected to OneNote.")).toBe("Not connected to OneNote.");+ expect(extractServerMessage(new Error("Failed to fetch"))).toBe("Failed to fetch");++ // Nothing worth showing: the caller falls back to its own wording rather than printing "{}" or "".+ expect(extractServerMessage('{"message":" "}')).toBeNull();+ expect(extractServerMessage('{"status":500}')).toBeNull();+ expect(extractServerMessage(" ")).toBeNull();+ expect(extractServerMessage(undefined)).toBeNull();+ });+});diff --git a/apps/client/src/services/onenote_import.ts b/apps/client/src/services/onenote_import.tsindex 6e4ffbfe71..6a107d4057 100644--- a/apps/client/src/services/onenote_import.ts+++ b/apps/client/src/services/onenote_import.ts@@ -62,6 +62,28 @@ export default {runImport};+/**+ * Pulls the human-readable reason out of a rejected API call, so the dialog can show what actually went+ * wrong instead of a generic failure. The request layer rejects with the raw response body, which is+ * either a JSON error envelope (`{"message": …}`, from a server error) or plain text (from a+ * `[status, message]` route result) — both shapes are unwrapped here. Returns null when the response+ * carried no usable message and the caller should fall back to its own wording.+ */+export function extractServerMessage(e: unknown): string | null {+ const raw = typeof e === "string" ? e : e instanceof Error ? e.message : null;+ const trimmed = raw?.trim();+ if (!trimmed) {+ return null;+ }+ try {+ const parsed = JSON.parse(trimmed) as { message?: unknown };+ return typeof parsed.message === "string" && parsed.message.trim() ? parsed.message : null;+ } catch {+ // Not JSON: a plain-text body is already the message.+ return trimmed;+ }+}+export type OneNoteContainer = OneNoteNotebook | OneNoteSectionGroup;/** A container's direct child in the OneNote left rail — either a section or a (nested) section group. */diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex fa98d7342a..ced483b72b 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -269,7 +269,9 @@"connected_as": "Connected as {{name}}","disconnect": "Disconnect","load_failed": "Could not load your OneNote notebooks.",+ "load_retry": "Try again","no_notebooks": "No notebooks were found in this account.",+ "no_notebooks_hint": "Only notebooks stored in this account's own OneDrive are listed. Notebooks shared with you, or kept on a SharePoint or Teams site, cannot be imported.","select_sections": "Select the sections to import","select_sections_hint": "OneNote doesn't include the original ordering in the import data, so sections and groups are sorted by creation date and may not match how they appear in OneNote.","import": "Import selected",diff --git a/apps/server/src/routes/api/onenote_import.spec.ts b/apps/server/src/routes/api/onenote_import.spec.tsindex 63f31807a4..8b70186641 100644--- a/apps/server/src/routes/api/onenote_import.spec.ts+++ b/apps/server/src/routes/api/onenote_import.spec.ts@@ -35,7 +35,9 @@ function fakeRequest(oneNoteImport?: Request["session"]["oneNoteImport"]): RequebeforeEach(() => {oauthMock.requestDeviceCode.mockReset();oauthMock.pollDeviceToken.mockReset();+ oauthMock.refreshAccessToken.mockReset();graphMock.getAccount.mockReset();+ graphMock.listNotebooks.mockReset();});describe("deviceLogin", () => {@@ -80,6 +82,31 @@ describe("deviceLogin", () => {});});+describe("getNotebooks", () => {+ it("lists the notebooks while the stored token is still valid", async () => {+ graphMock.listNotebooks.mockResolvedValue([{ id: "nb1", title: "Notebook 1", sections: [], sectionGroups: [] }]);+ const req = fakeRequest({ accessToken: "access-token", refreshToken: "refresh-token", expiresAt: Date.now() + 3_600_000 });++ expect(await onenoteImportRoute.getNotebooks(req)).toEqual({ notebooks: [{ id: "nb1", title: "Notebook 1", sections: [], sectionGroups: [] }] });+ expect(oauthMock.refreshAccessToken).not.toHaveBeenCalled();+ });++ it("reports why an expired connection failed instead of an empty notebook list", async () => {+ // The status endpoint still calls this session connected (a token is stored), so a flat 401 would+ // leave the dialog showing "no notebooks were found" for what is really an expired sign-in.+ oauthMock.refreshAccessToken.mockRejectedValue(new Error("OAuth token request failed: AADSTS700082: The refresh token has expired."));+ const req = fakeRequest({ accessToken: "stale-token", refreshToken: "dead-refresh-token", expiresAt: Date.now() - 1000 });++ expect(await onenoteImportRoute.getNotebooks(req)).toEqual([401, expect.stringContaining("The refresh token has expired.")]);+ expect(graphMock.listNotebooks).not.toHaveBeenCalled();+ });++ it("tells a disconnected session to sign in again rather than listing nothing", async () => {+ expect(await onenoteImportRoute.getNotebooks(fakeRequest())).toEqual([401, expect.stringContaining("sign in again")]);+ expect(graphMock.listNotebooks).not.toHaveBeenCalled();+ });+});+describe("devicePoll", () => {it("rejects a poll with no sign-in in progress", async () => {const result = await onenoteImportRoute.devicePoll(fakeRequest());diff --git a/apps/server/src/routes/api/onenote_import.ts b/apps/server/src/routes/api/onenote_import.tsindex 18bb953acd..b9f56312d8 100644--- a/apps/server/src/routes/api/onenote_import.ts+++ b/apps/server/src/routes/api/onenote_import.ts@@ -125,16 +125,18 @@ async function disconnect(req: Request) {async function getNotebooks(req: Request) {const getAccessToken = buildTokenProvider(req);- if (!(await isConnected(getAccessToken))) {- return [401, "Not connected to OneNote."];+ const failure = await connectionFailure(getAccessToken);+ if (failure) {+ return [401, failure];}return { notebooks: await graph.listNotebooks(getAccessToken) };}async function runImport(req: Request) {const getAccessToken = buildTokenProvider(req);- if (!(await isConnected(getAccessToken))) {- return [401, "Not connected to OneNote."];+ const failure = await connectionFailure(getAccessToken);+ if (failure) {+ return [401, failure];}const { parentNoteId, sections, taskId, debug, shrinkImages } = req.body as { parentNoteId: string; sections: OneNoteSectionSelection[]; taskId: string; debug?: boolean; shrinkImages?: boolean };@@ -170,13 +172,23 @@ function buildTokenProvider(req: Request): AccessTokenProvider {});}-/** True when the connection can currently produce an access token; false when disconnected/unrefreshable. */-async function isConnected(getAccessToken: AccessTokenProvider): Promise<boolean> {+/**+ * The reason the connection cannot currently produce an access token, or null when it can.+ *+ * The message is passed through to the client rather than flattened into a generic "not connected",+ * because a stored-but-unrefreshable token is the case that matters: /status reports the connection as+ * live (it only sees that a token is stored), so without this reason the notebook list comes back empty+ * and the dialog can only say the account has no notebooks. The token provider's messages already tell+ * the user to sign in again.+ */+async function connectionFailure(getAccessToken: AccessTokenProvider): Promise<string | null> {try {await getAccessToken();- return true;- } catch {- return false;+ return null;+ } catch (e) {+ const reason = e instanceof Error ? e.message : String(e);+ getLog().info(`OneNote import: the stored connection could not produce an access token: ${reason}`);+ return reason || "Not connected to OneNote.";}}diff --git a/apps/server/src/services/import/onenote/token_provider.spec.ts b/apps/server/src/services/import/onenote/token_provider.spec.tsindex 3b9047fcd0..f1035fb1f4 100644--- a/apps/server/src/services/import/onenote/token_provider.spec.ts+++ b/apps/server/src/services/import/onenote/token_provider.spec.ts@@ -102,7 +102,9 @@ describe("createGraphTokenProvider", () => {refresh.mockRejectedValueOnce(new Error("invalid_grant"));refresh.mockResolvedValueOnce(refreshResult);- await expect(getAccessToken()).rejects.toThrow("invalid_grant");+ // The provider's reason is kept, but paired with the remedy — the message is shown verbatim in+ // the import report and the import dialog, where a bare OAuth code says nothing to the user.+ await expect(getAccessToken()).rejects.toThrow(/invalid_grant.*sign in again/is);// The failed refresh must not wedge the single-flight latch shut.await expect(getAccessToken()).resolves.toBe("new-access");expect(refresh).toHaveBeenCalledTimes(2);diff --git a/apps/server/src/services/import/onenote/token_provider.ts b/apps/server/src/services/import/onenote/token_provider.tsindex af5d745737..d19914d74f 100644--- a/apps/server/src/services/import/onenote/token_provider.ts+++ b/apps/server/src/services/import/onenote/token_provider.ts@@ -39,7 +39,7 @@ export function createGraphTokenProvider(deps: GraphTokenProviderDeps): () => Prlet inFlightRefresh: Promise<string> | null = null;async function refreshNow(refreshToken: string): Promise<string> {- const tokens = await deps.refresh(refreshToken);+ const tokens = await refreshOrExplain(refreshToken);await deps.write({accessToken: tokens.access_token,// Reuse the current refresh token when the provider chose not to rotate it.@@ -49,6 +49,20 @@ export function createGraphTokenProvider(deps: GraphTokenProviderDeps): () => Prreturn tokens.access_token;}+ /**+ * Refreshes, restating a failure as something the user can act on. A refresh token that Microsoft has+ * expired or revoked comes back as a bare OAuth error ("…AADSTS700082…"), which is shown verbatim+ * wherever the connection is used (the import report, the import dialog), so the message has to carry+ * the remedy alongside the provider's reason: this is unrecoverable without a fresh sign-in.+ */+ async function refreshOrExplain(refreshToken: string): Promise<TokenResponse> {+ try {+ return await deps.refresh(refreshToken);+ } catch (e) {+ throw new Error(`The OneNote connection could not be refreshed (${e instanceof Error ? e.message : String(e)}). Please sign in again.`);+ }+ }+return async function getAccessToken(): Promise<string> {const session = deps.read();if (!session?.accessToken) {