Skip to content

Build your personal knowledge base with Trilium Notes

feat(onenote): show notebook-loading failures inline instead of claiming an empty account

Elian Doranda5609007ea0
diff --git a/apps/client/src/services/onenote_import.ts b/apps/client/src/services/onenote_import.ts
index a99656b1d4..460d47c88a 100644
--- a/apps/client/src/services/onenote_import.ts
+++ b/apps/client/src/services/onenote_import.ts
@@ -43,7 +43,9 @@ function disconnect() {
}
function getNotebooks() {
- return server.get<{ notebooks: OneNoteNotebook[] }>("onenote-import/notebooks");
+ // silent: a 401 here (expired/lost connection) is presented inline by the import dialog with the
+ // server's reason and a retry button — the generic "unknown HTTP error" toast would double-report.
+ return server.getWithSilentUnauthorized<{ notebooks: OneNoteNotebook[] }>("onenote-import/notebooks");
}
// Kicks off the import and returns as soon as the server has accepted it. The import itself runs in the
diff --git a/apps/client/src/services/server.spec.ts b/apps/client/src/services/server.spec.ts
index 1ce3e5546e..baf5c8de8f 100644
--- a/apps/client/src/services/server.spec.ts
+++ b/apps/client/src/services/server.spec.ts
@@ -206,6 +206,16 @@ describe("ajax error handling", () => {
expect((window as any).logError).not.toHaveBeenCalled();
});
+ it("stays silent on 401 when silentUnauthorized is set, still rejecting with the body", async () => {
+ (window as any).$.ajax = (opts: AjaxOptions) => {
+ opts.error({ status: 401, responseText: "The OneNote connection was lost." });
+ };
+ // The caller presents the failure itself, so it must still receive the server's reason.
+ await expect(server.getWithSilentUnauthorized("url")).rejects.toBe("The OneNote connection was lost.");
+ expect(toastMock.showError).not.toHaveBeenCalled();
+ expect((window as any).logError).not.toHaveBeenCalled();
+ });
+
it("reports validation errors (400) and still rejects when reportError throws", async () => {
(window as any).$.ajax = (opts: AjaxOptions) => {
opts.error({ status: 400, responseText: JSON.stringify({ message: "Bad input" }) });
diff --git a/apps/client/src/services/server.ts b/apps/client/src/services/server.ts
index 74a12d6cb4..c7c6be0927 100644
--- a/apps/client/src/services/server.ts
+++ b/apps/client/src/services/server.ts
@@ -49,6 +49,10 @@ async function get<T>(url: string, componentId?: string, raw?: boolean) {
return await call<T>("GET", url, componentId, { raw });
}
+async function getWithSilentUnauthorized<T>(url: string, componentId?: string) {
+ return await call<T>("GET", url, componentId, { silentUnauthorized: true });
+}
+
async function post<T>(url: string, data?: unknown, componentId?: string) {
return await call<T>("POST", url, componentId, { data });
}
@@ -145,6 +149,9 @@ interface CallOptions {
data?: unknown;
silentNotFound?: boolean;
silentInternalServerError?: boolean;
+ /** Suppresses the generic error toast for a 401, for callers that present the failure themselves
+ * (e.g. the OneNote import dialog showing an expired connection inline, with the server's reason). */
+ silentUnauthorized?: boolean;
// If `true`, the value will be returned as a string instead of a JavaScript object if JSON, XMLDocument if XML, etc.
raw?: boolean;
/** Used internally to prevent infinite retry loops on CSRF refresh. */
@@ -226,6 +233,8 @@ function ajax(url: string, method: string, data: unknown, headers: Headers, opts
// report nothing
} else if (opts.silentInternalServerError && jqXhr.status === 500) {
// report nothing
+ } else if (opts.silentUnauthorized && jqXhr.status === 401) {
+ // report nothing
} else {
try {
await reportError(method, url, jqXhr.status, jqXhr.responseText);
@@ -299,6 +308,7 @@ async function reportError(method: string, url: string, statusCode: number, resp
export default {
get,
getWithSilentNotFound,
+ getWithSilentUnauthorized,
post,
postWithSilentInternalServerError,
put,
diff --git a/apps/client/src/widgets/dialogs/import/import_dialog.css b/apps/client/src/widgets/dialogs/import/import_dialog.css
index 937adf1469..1253c33ff6 100644
--- a/apps/client/src/widgets/dialogs/import/import_dialog.css
+++ b/apps/client/src/widgets/dialogs/import/import_dialog.css
@@ -63,6 +63,12 @@
gap: 0.5em;
}
+ /* Secondary explanation under a message (e.g. why an account can look notebook-less). */
+ .onenote-hint {
+ color: var(--muted-text-color);
+ font-size: 0.9em;
+ }
+
.onenote-status {
display: flex;
align-items: center;
diff --git a/apps/client/src/widgets/dialogs/import/onenote.tsx b/apps/client/src/widgets/dialogs/import/onenote.tsx
index 773a3ce5cf..b14084b412 100644
--- a/apps/client/src/widgets/dialogs/import/onenote.tsx
+++ b/apps/client/src/widgets/dialogs/import/onenote.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n.js";
-import onenoteImport, { buildSectionSelections, collectSectionIds, type OneNoteAccount, type OneNoteContainer, type OneNoteDeviceLogin, type OneNoteNotebook, orderedChildren } from "../../../services/onenote_import.js";
+import onenoteImport, { buildSectionSelections, collectSectionIds, extractServerMessage, type OneNoteAccount, type OneNoteContainer, type OneNoteDeviceLogin, type OneNoteNotebook, orderedChildren } from "../../../services/onenote_import.js";
import toast from "../../../services/toast.js";
import { isElectron, randomString } from "../../../services/utils.js";
import Button from "../../react/Button.js";
@@ -20,6 +20,9 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
const [phase, setPhase] = useState<Phase>("checking");
const [account, setAccount] = useState<OneNoteAccount | null>(null);
const [notebooks, setNotebooks] = useState<OneNoteNotebook[]>([]);
+ // Set when listing the notebooks failed, so the panel can say so instead of reporting an empty
+ // account — an expired connection or a Graph error is not "you have no notebooks".
+ const [loadError, setLoadError] = useState<string | null>(null);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
// Set while a user-triggered notebook reload is in flight, to spin and disable the refresh button.
const [refreshing, setRefreshing] = useState(false);
@@ -42,6 +45,7 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
}, []);
const loadNotebooks = useCallback(async () => {
+ setLoadError(null);
try {
const { notebooks } = await onenoteImport.getNotebooks();
setNotebooks(notebooks);
@@ -49,8 +53,13 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
// last load), so a refresh can't leave the import button counting phantom sections.
const validIds = collectSectionIds(notebooks);
setSelectedIds((prev) => new Set([...prev].filter((id) => validIds.has(id))));
- } catch {
- toast.showError(t("onenote_import.load_failed"));
+ } catch (e) {
+ // The server's wording is the useful part (an expired sign-in says to sign in again, a
+ // Graph failure names the Graph error); fall back to the generic message only when the
+ // response carried none. The stale list is cleared: a tree that can't import (the same
+ // dead connection would fail the import too) is worse than the explanation.
+ setNotebooks([]);
+ setLoadError(extractServerMessage(e) ?? t("onenote_import.load_failed"));
}
}, []);
@@ -76,7 +85,7 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
setPhase("disconnected");
}
}).catch((e) => {
- toast.showError(e instanceof Error ? e.message : String(e));
+ toast.showError(extractServerMessage(e) ?? t("onenote_import.load_failed"));
setPhase("disconnected");
});
return stopPolling;
@@ -153,7 +162,7 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
};
pollRef.current = setTimeout(() => void poll(), intervalMs);
} catch (e) {
- toast.showError(e instanceof Error ? e.message : String(e));
+ toast.showError(extractServerMessage(e) ?? String(e));
setPhase("disconnected");
}
}, [loadNotebooks, stopPolling]);
@@ -169,6 +178,7 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
await onenoteImport.disconnect();
setAccount(null);
setNotebooks([]);
+ setLoadError(null);
setSelectedIds(new Set());
setPhase("disconnected");
}, [stopPolling]);
@@ -192,7 +202,7 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
try {
await onenoteImport.runImport({ parentNoteId, sections, taskId: randomString(10), debug, shrinkImages: compressImages && shrinkImages });
} catch (e) {
- toast.showError(e instanceof Error ? e.message : String(e));
+ toast.showError(extractServerMessage(e) ?? String(e));
}
}, [notebooks, selectedIds, parentNoteId, debug, compressImages, shrinkImages, closeDialog]);
@@ -276,32 +286,48 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
</div>
</div>
- {notebooks.length === 0
- ? <p>{t("onenote_import.no_notebooks")}</p>
- : (
- <>
- <OptionsRow name="onenote-sections" label={t("onenote_import.select_sections")} description={t("onenote_import.select_sections_hint")} stacked>
- <div className="onenote-notebooks">
- <CheckboxTree nodes={treeNodes} selectedIds={selectedIds} onChange={setSelectedIds} />
- </div>
- </OptionsRow>
- <OptionsRowWithToggle
- name="onenote-shrink-images"
- label={t("import.shrinkImages")}
- description={t("import.shrinkImagesProviderTooltip")}
- currentValue={compressImages && shrinkImages}
- onChange={setShrinkImages}
- disabled={!compressImages}
- />
- <OptionsRowWithToggle
- name="onenote-debug"
- label={t("onenote_import.attach_source")}
- description={t("onenote_import.attach_source_hint")}
- currentValue={debug}
- onChange={setDebug}
- />
- </>
- )}
+ {loadError && (
+ <NoItems icon="bx bx-error-circle" text={loadError}>
+ <Button
+ text={t("onenote_import.load_retry")}
+ kind="primary"
+ disabled={refreshing}
+ onClick={() => void refresh()}
+ />
+ </NoItems>
+ )}
+
+ {!loadError && notebooks.length === 0 && (
+ <>
+ <p>{t("onenote_import.no_notebooks")}</p>
+ <p className="onenote-hint">{t("onenote_import.no_notebooks_hint")}</p>
+ </>
+ )}
+
+ {!loadError && notebooks.length > 0 && (
+ <>
+ <OptionsRow name="onenote-sections" label={t("onenote_import.select_sections")} description={t("onenote_import.select_sections_hint")} stacked>
+ <div className="onenote-notebooks">
+ <CheckboxTree nodes={treeNodes} selectedIds={selectedIds} onChange={setSelectedIds} />
+ </div>
+ </OptionsRow>
+ <OptionsRowWithToggle
+ name="onenote-shrink-images"
+ label={t("import.shrinkImages")}
+ description={t("import.shrinkImagesProviderTooltip")}
+ currentValue={compressImages && shrinkImages}
+ onChange={setShrinkImages}
+ disabled={!compressImages}
+ />
+ <OptionsRowWithToggle
+ name="onenote-debug"
+ label={t("onenote_import.attach_source")}
+ description={t("onenote_import.attach_source_hint")}
+ currentValue={debug}
+ onChange={setDebug}
+ />
+ </>
+ )}
</CardSection>
</Card>
);