Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(desktop): expose global sync failures (#356)

tianma-if84683d97aebb
diff --git a/apps/web/src/components/DesktopSyncIssuesDialog.tsx b/apps/web/src/components/DesktopSyncIssuesDialog.tsx
index c4bcf9d9..efc5bf0d 100644
--- a/apps/web/src/components/DesktopSyncIssuesDialog.tsx
+++ b/apps/web/src/components/DesktopSyncIssuesDialog.tsx
@@ -13,6 +13,7 @@ import {
getDesktopSyncIssues,
recoverDesktopMemoUpdate,
retryDesktopSyncIssue,
+ type DesktopGlobalSyncIssue,
} from "@/lib/desktop-sync";
const isRecoverableMissingMemo = (item: DesktopOutboxItem) => item.kind === "memo.update"
@@ -34,8 +35,10 @@ export const DesktopSyncIssuesDialog = ({
}) => {
const { i18n, t } = useTranslation();
const [items, setItems] = useState<DesktopOutboxItem[]>([]);
+ const [globalIssue, setGlobalIssue] = useState<DesktopGlobalSyncIssue | null>(null);
const [loading, setLoading] = useState(false);
const [workingId, setWorkingId] = useState<number | null>(null);
+ const [workingGlobal, setWorkingGlobal] = useState(false);
const [error, setError] = useState<string | null>(null);
const [recovering, setRecovering] = useState<DesktopOutboxItem | null>(null);
const [discarding, setDiscarding] = useState<DesktopOutboxItem | null>(null);
@@ -52,14 +55,14 @@ export const DesktopSyncIssuesDialog = ({
diagnostics: {
heading: t("notebookPane.syncDetails.reportDiagnosticsHeading"),
notice: t("notebookPane.syncDetails.reportDiagnosticsNotice"),
- text: createDesktopSyncDiagnosticText(items),
+ text: createDesktopSyncDiagnosticText(items, globalIssue),
},
privacyNotice: t("feedback.privacyNotice"),
systemInfo: getWebSystemInfoItems(t, i18n.language),
systemInfoHeading: t("feedback.systemInfoHeading"),
systemInfoNotice: t("feedback.systemInfoNotice"),
titlePrefix: t("notebookPane.syncDetails.reportTitlePrefix"),
- }), [i18n.language, items, t]);
+ }), [globalIssue, i18n.language, items, t]);
const formatTime = (value: string | null | undefined) => {
if (!value) return null;
const time = new Date(value);
@@ -70,7 +73,9 @@ export const DesktopSyncIssuesDialog = ({
setLoading(true);
setError(null);
try {
- setItems(await getDesktopSyncIssues());
+ const details = await getDesktopSyncIssues();
+ setItems(details.items);
+ setGlobalIssue(details.globalIssue);
} catch (loadError) {
setError(loadError instanceof Error ? loadError.message : String(loadError));
} finally {
@@ -110,9 +115,22 @@ export const DesktopSyncIssuesDialog = ({
void runAction(item, () => discardDesktopSyncIssue(item));
};
+ const retryGlobalIssue = async () => {
+ setWorkingGlobal(true);
+ setError(null);
+ try {
+ await onSyncNow();
+ await load();
+ } catch (actionError) {
+ setError(actionError instanceof Error ? actionError.message : String(actionError));
+ } finally {
+ setWorkingGlobal(false);
+ }
+ };
+
return (
<>
- <Dialog open={open && !recovering && !discarding} onOpenChange={(nextOpen) => { if (workingId === null) onOpenChange(nextOpen); }}>
+ <Dialog open={open && !recovering && !discarding} onOpenChange={(nextOpen) => { if (workingId === null && !workingGlobal) onOpenChange(nextOpen); }}>
<DialogContent className="max-h-[min(720px,calc(100vh-2rem))] max-w-2xl overflow-y-auto">
<DialogHeader>
<DialogTitle>{t("notebookPane.syncDetails.title")}</DialogTitle>
@@ -121,9 +139,28 @@ export const DesktopSyncIssuesDialog = ({
{error ? <p className="rounded-md bg-rose-50 px-3 py-2 text-sm text-rose-700" role="alert">{error}</p> : null}
{loading ? <p className="py-8 text-center text-sm text-slate-500">{t("common.loading")}</p> : null}
- {!loading && items.length === 0 ? <p className="py-8 text-center text-sm text-slate-500">{t("notebookPane.syncDetails.empty")}</p> : null}
+ {!loading && items.length === 0 && !globalIssue ? <p className="py-8 text-center text-sm text-slate-500">{t("notebookPane.syncDetails.empty")}</p> : null}
<div className="space-y-3">
+ {globalIssue ? (
+ <section className="rounded-lg border border-amber-200 bg-amber-50/60 p-4">
+ <div className="flex items-start gap-3">
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-700" />
+ <div className="min-w-0 flex-1">
+ <p className="text-sm font-semibold text-slate-900">{t("notebookPane.syncDetails.globalFailure")}</p>
+ <p className="mt-1 break-words text-sm text-amber-900">{globalIssue.message || t("notebookPane.syncDetails.unknownError")}</p>
+ <p className="mt-1 text-xs text-slate-500">{t("notebookPane.syncDetails.errorCode", { code: globalIssue.errorCode ?? globalIssue.phase })}</p>
+ {formatTime(globalIssue.occurredAt) ? <p className="mt-1 text-xs text-slate-500">{t("notebookPane.syncDetails.lastAttempt", { time: formatTime(globalIssue.occurredAt) })}</p> : null}
+ </div>
+ </div>
+ <div className="mt-3 flex justify-end">
+ <Button size="sm" variant="outline" disabled={workingGlobal} onClick={() => void retryGlobalIssue()}>
+ <RefreshCw className="mr-1.5 h-3.5 w-3.5" />
+ {t("notebookPane.syncDetails.retry")}
+ </Button>
+ </div>
+ </section>
+ ) : null}
{items.map((item) => {
const recoverable = isRecoverableMissingMemo(item);
const working = workingId === item.id;
@@ -170,8 +207,8 @@ export const DesktopSyncIssuesDialog = ({
</div>
<DialogFooter className="gap-2 sm:justify-between">
- <Button variant="outline" disabled={items.length === 0} asChild={items.length > 0}>
- {items.length > 0 ? (
+ <Button variant="outline" disabled={items.length === 0 && !globalIssue} asChild={items.length > 0 || Boolean(globalIssue)}>
+ {items.length > 0 || globalIssue ? (
<a href={reportIssueUrl} target="_blank" rel="noopener noreferrer">
<ExternalLink className="mr-1.5 h-4 w-4" />
{t("notebookPane.syncDetails.reportIssue")}
diff --git a/apps/web/src/lib/desktop-sync.test.mjs b/apps/web/src/lib/desktop-sync.test.mjs
index fc6d3598..aa702a9b 100644
--- a/apps/web/src/lib/desktop-sync.test.mjs
+++ b/apps/web/src/lib/desktop-sync.test.mjs
@@ -2,7 +2,9 @@ import { describe, expect, test } from "bun:test";
const {
classifyDesktopSyncFailure,
+ createDesktopSyncIssueDetails,
createDesktopSyncDiagnosticText,
+ createDesktopSyncSummary,
isStagedResourceReferenced,
hasDesktopSyncStateReset,
mergeMemoIdMappings,
@@ -11,6 +13,7 @@ const {
orderBootstrapNotebooks,
resolveDesktopMemoSyncBase,
rewriteStagedResource,
+ shouldAttemptDesktopRecoveryPull,
shouldPullDesktopChanges,
} = await import("./desktop-sync.ts");
const { ApiRequestError } = await import("./api.ts");
@@ -153,6 +156,26 @@ describe("desktop sync failure handling", () => {
expect(diagnostic).not.toContain("private.example.test");
});
+ test("keeps a global failure visible in both the summary and details", () => {
+ const globalIssue = {
+ phase: "pull_remote_changes",
+ message: "Request failed at https://private.example.test/api/v1/sync/changes",
+ errorCode: "http_500",
+ occurredAt: "2026-09-05T00:00:00.000Z",
+ };
+
+ expect(createDesktopSyncSummary({ pending: 0, syncing: 0, conflict: 0, error: 0 }, globalIssue)).toEqual({
+ total: 1,
+ pending: 0,
+ syncing: 0,
+ conflict: 0,
+ error: 1,
+ });
+ expect(createDesktopSyncIssueDetails([], globalIssue)).toEqual({ globalIssue, items: [] });
+ expect(createDesktopSyncDiagnosticText([], globalIssue)).toContain("pull_remote_changes");
+ expect(createDesktopSyncDiagnosticText([], globalIssue)).not.toContain("private.example.test");
+ });
+
test("bounds diagnostics for a prefilled GitHub Issue URL", () => {
const items = Array.from({ length: 200 }, (_, id) => ({
id,
@@ -178,4 +201,13 @@ describe("desktop sync failure handling", () => {
expect(shouldPullDesktopChanges({ pending: 1, syncing: 0, error: 0, conflict: 0 }, true)).toBe(false);
expect(shouldPullDesktopChanges({ pending: 0, syncing: 0, error: 0, conflict: 0 }, false)).toBe(false);
});
+
+ test("attempts a recovery pull only when no local upload can be overwritten", () => {
+ expect(shouldAttemptDesktopRecoveryPull("sync_staged_resources", { pending: 0, syncing: 0 }, true)).toBe(true);
+ expect(shouldAttemptDesktopRecoveryPull("sync_staged_resources", { pending: 1, syncing: 0 }, true)).toBe(false);
+ expect(shouldAttemptDesktopRecoveryPull("sync_staged_resources", { pending: 0, syncing: 1 }, true)).toBe(false);
+ expect(shouldAttemptDesktopRecoveryPull("pull_remote_changes", { pending: 0, syncing: 0 }, true)).toBe(false);
+ expect(shouldAttemptDesktopRecoveryPull("finalize_resource_remap", { pending: 0, syncing: 0 }, true)).toBe(false);
+ expect(shouldAttemptDesktopRecoveryPull("sync_staged_resources", { pending: 0, syncing: 0 }, false)).toBe(false);
+ });
});
diff --git a/apps/web/src/lib/desktop-sync.ts b/apps/web/src/lib/desktop-sync.ts
index ff5f681f..df157a77 100644
--- a/apps/web/src/lib/desktop-sync.ts
+++ b/apps/web/src/lib/desktop-sync.ts
@@ -15,7 +15,24 @@ import { isDesktopResourceRuntime, mapMarkdownResourceUrls, mapTiptapResourceUrl
import { notifyMemoIdRemapped, notifyMemoSyncAcknowledged } from "@/lib/sync-events";
type StagedResourceRewrite = { memoId: string; placeholder: string; url: string };
-let lastSyncFailed = false;
+
+export type DesktopSyncPhase =
+ | "sync_creates"
+ | "remap_created_resources"
+ | "sync_staged_resources"
+ | "sync_outbox"
+ | "read_status"
+ | "pull_remote_changes"
+ | "finalize_resource_remap";
+
+export type DesktopGlobalSyncIssue = {
+ phase: DesktopSyncPhase;
+ message: string;
+ errorCode: string | null;
+ occurredAt: string;
+};
+
+let lastGlobalSyncIssue: DesktopGlobalSyncIssue | null = null;
const STAGED_RESOURCE_ID_CHARACTER = /[A-Za-z0-9_-]/;
@@ -171,6 +188,13 @@ const request = async <M extends keyof DesktopRpcResponses>(method: M, params: D
return bridge.sidecarRequest<DesktopRpcResponses[M]>(method, params);
};
+const toDesktopGlobalSyncIssue = (phase: DesktopSyncPhase, error: unknown): DesktopGlobalSyncIssue => ({
+ phase,
+ message: error instanceof Error ? error.message : String(error),
+ errorCode: error instanceof ApiRequestError ? error.code ?? `http_${error.status}` : error instanceof TypeError ? "network_error" : null,
+ occurredAt: new Date().toISOString(),
+});
+
const applyRemoteNotebook = async (notebook: DesktopRpcResponses["notebook.list"]["notebooks"][number]) => {
await request("sync.apply", {
changes: [{ entityType: "notebook", operation: "upsert", entityId: notebook.id, notebook, memo: null }],
@@ -463,6 +487,14 @@ export const shouldPullDesktopChanges = (
online: boolean,
) => online && status.pending === 0 && status.syncing === 0;
+export const shouldAttemptDesktopRecoveryPull = (
+ phase: DesktopSyncPhase,
+ status: Pick<DesktopRpcResponses["sync.status"], "pending" | "syncing">,
+ online: boolean,
+) => phase !== "pull_remote_changes"
+ && phase !== "finalize_resource_remap"
+ && shouldPullDesktopChanges(status, online);
+
export const orderBootstrapNotebooks = (notebooks: SyncBootstrapResponse["notebooks"]) => {
const remaining = new Map(notebooks.map((notebook) => [notebook.id, notebook]));
const ordered: SyncBootstrapResponse["notebooks"] = [];
@@ -561,25 +593,34 @@ export const syncDesktopData = () => {
if (typeof navigator !== "undefined" && !navigator.onLine) {
return { attempted: 0, synced: 0, failed: 0, conflicted: 0, memoIdMappings, syncedMemos };
}
+ let phase: DesktopSyncPhase = "sync_creates";
try {
const creates = await syncOutbox([], new Set(["memo.create"]));
mergeMemoIdMappings(memoIdMappings, creates.memoIdMappings);
mergeSyncedMemos(syncedMemos, creates.syncedMemos);
+ phase = "remap_created_resources";
await remapStagedResourceMemoIds(creates.memoIdMappings);
+ phase = "sync_staged_resources";
const stagedResources = await syncStagedResources(creates.memoIdMappings);
+ phase = "sync_outbox";
const outbox = await syncOutbox(stagedResources.rewrites);
mergeMemoIdMappings(memoIdMappings, outbox.memoIdMappings);
mergeSyncedMemos(syncedMemos, outbox.syncedMemos);
if (stagedResources.failed === 0 && outbox.failed === 0 && outbox.conflicted === 0 && creates.conflicted === 0) {
await removeSyncedStagedResources(stagedResources.stagedIds);
}
+ phase = "read_status";
const remaining = await request("sync.status", {});
// A durable failed or conflicted outbox item must not freeze unrelated
// remote changes. The payload remains recoverable while pulls continue.
- if (shouldPullDesktopChanges(remaining, typeof navigator === "undefined" || navigator.onLine)) await pullRemoteChanges();
+ if (shouldPullDesktopChanges(remaining, typeof navigator === "undefined" || navigator.onLine)) {
+ phase = "pull_remote_changes";
+ await pullRemoteChanges();
+ }
// Catch resources staged while the network sync itself was running.
+ phase = "finalize_resource_remap";
await remapStagedResourceMemoIds(creates.memoIdMappings);
- lastSyncFailed = false;
+ lastGlobalSyncIssue = null;
return {
attempted: creates.attempted + outbox.attempted + stagedResources.attempted,
synced: creates.synced + outbox.synced + stagedResources.synced,
@@ -589,8 +630,22 @@ export const syncDesktopData = () => {
syncedMemos,
};
} catch (error) {
- lastSyncFailed = true;
+ lastGlobalSyncIssue = toDesktopGlobalSyncIssue(phase, error);
console.error("[desktop-sync] Sync failed", error);
+ // Resource preparation and other peripheral desktop phases must not
+ // freeze cloud downloads. Pull only after the sidecar proves there is no
+ // local upload in progress; pending drafts continue to block the pull.
+ try {
+ const online = typeof navigator === "undefined" || navigator.onLine;
+ const remaining = await request("sync.status", {});
+ if (shouldAttemptDesktopRecoveryPull(phase, remaining, online)) {
+ await pullRemoteChanges();
+ }
+ } catch (pullError) {
+ if (phase !== "pull_remote_changes") {
+ console.error("[desktop-sync] Recovery pull failed", pullError);
+ }
+ }
// A create may already have been acknowledged before a later upload or
// pull failed. Preserve its id mapping so the UI cannot keep editing an
// obsolete temporary id merely because the overall sync was partial.
@@ -600,15 +655,30 @@ export const syncDesktopData = () => {
return activeSync;
};
-export const getDesktopSyncSummary = async () => {
- const status = await request("sync.status", {});
- const error = status.error + (lastSyncFailed ? 1 : 0);
+export const createDesktopSyncSummary = (
+ status: Pick<DesktopRpcResponses["sync.status"], "pending" | "syncing" | "conflict" | "error">,
+ globalIssue: DesktopGlobalSyncIssue | null,
+) => {
+ const error = status.error + (globalIssue ? 1 : 0);
return { total: status.pending + status.syncing + status.conflict + error, pending: status.pending, syncing: status.syncing, conflict: status.conflict, error };
};
+export const getDesktopSyncSummary = async () => createDesktopSyncSummary(
+ await request("sync.status", {}),
+ lastGlobalSyncIssue,
+);
+
+export const createDesktopSyncIssueDetails = (
+ items: DesktopOutboxItem[],
+ globalIssue: DesktopGlobalSyncIssue | null,
+) => ({
+ globalIssue,
+ items: items.filter((item) => item.status === "error" || item.status === "conflict"),
+});
+
export const getDesktopSyncIssues = async () => {
const response = await request("sync.outbox.list", { limit: 200, includeConflicts: true });
- return response.items.filter((item) => item.status === "error" || item.status === "conflict");
+ return createDesktopSyncIssueDetails(response.items, lastGlobalSyncIssue);
};
export const retryDesktopSyncIssue = async (item: DesktopOutboxItem) => {
@@ -636,8 +706,12 @@ const sanitizeDesktopSyncDiagnosticError = (value: string | null | undefined) =>
.replace(/\bBearer\s+[^\s,;]+/gi, "Bearer [redacted]")
: value;
-export const createDesktopSyncDiagnosticText = (items: DesktopOutboxItem[]) => JSON.stringify({
+export const createDesktopSyncDiagnosticText = (items: DesktopOutboxItem[], globalIssue: DesktopGlobalSyncIssue | null = null) => JSON.stringify({
generatedAt: new Date().toISOString(),
+ globalIssue: globalIssue ? {
+ ...globalIssue,
+ message: sanitizeDesktopSyncDiagnosticError(globalIssue.message),
+ } : null,
totalItemCount: items.length,
includedItemCount: Math.min(items.length, 5),
items: items.slice(0, 5).map((item) => ({
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index afa68868..f1650ee3 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -358,6 +358,7 @@ export const enUS = {
title: "Sync details",
description: "Failed items remain safely stored on this device and no longer prevent changes from other devices from reaching the desktop app.",
empty: "There are no sync items that need attention.",
+ globalFailure: "Desktop sync process failed",
attempts: "Attempted {{count}} times",
unknownError: "Unknown sync error",
errorCode: "Error code: {{code}}",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index a73367a1..4778ed4c 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -358,6 +358,7 @@ export const zhCN = {
title: "同步详情",
description: "失败项会安全保留在本地;它们不会再阻止其他设备上的更改同步到此桌面端。",
empty: "当前没有需要处理的同步项。",
+ globalFailure: "桌面同步流程失败",
attempts: "已尝试 {{count}} 次",
unknownError: "未知同步错误",
errorCode: "错误代码:{{code}}",