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): keep local workspaces available during server outages

tianma-if0da3cdc24c87
diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsx
index 99d87ce2..2821790f 100644
--- a/apps/web/src/app/App.tsx
+++ b/apps/web/src/app/App.tsx
@@ -12,12 +12,11 @@ import {
cacheDesktopSession,
clearCachedDesktopSession,
getConfiguredDesktopApiBaseUrl,
- getCachedDesktopSession,
+ getWorkspaceSession,
saveDesktopApiBaseUrl,
} from "@/lib/api";
import { classifyLoginError, getLoginProblemMessageKey } from "@/lib/login-error";
import { EVERNOTE_MIGRATION_PATH } from "@/lib/routes";
-import { isBrowserOffline } from "@/lib/network-status";
import { syncPublishedNoteBodyFont } from "@/lib/published-note-body-font";
import { getNoteWindowMemoId } from "@/lib/desktop-note-windows";
import type { AuthSession } from "@edgeever/shared";
@@ -72,17 +71,7 @@ const AuthenticatedWorkspace = ({ siteManagement = false }: { siteManagement?: b
const sessionQuery = useQuery({
queryKey: ["auth", "session"],
- queryFn: async () => {
- try {
- const session = await api.getSession();
- await cacheDesktopSession(session);
- return session;
- } catch (error) {
- const cached = getCachedDesktopSession();
- if (cached?.authenticated && isBrowserOffline()) return cached;
- throw error;
- }
- },
+ queryFn: getWorkspaceSession,
enabled: !desktopBridge?.isAvailable || Boolean(configuredDesktopApiBaseUrl),
retry: false,
});
@@ -150,7 +139,11 @@ const AuthenticatedWorkspace = ({ siteManagement = false }: { siteManagement?: b
const handleUnauthorized = () => {
const current = queryClient.getQueryData<AuthSession>(["auth", "session"]);
clearCachedDesktopSession();
- queryClient.clear();
+ // Keep the observed session query alive so this transition is delivered
+ // even when a background request discovers that the session was revoked.
+ queryClient.removeQueries({
+ predicate: ({ queryKey }) => queryKey[0] !== "auth" || queryKey[1] !== "session",
+ });
queryClient.setQueryData<AuthSession>(["auth", "session"], {
authRequired: current?.authRequired ?? true,
authenticated: false,
diff --git a/apps/web/src/lib/api.test.mjs b/apps/web/src/lib/api.test.mjs
index 9e619b82..63aa977d 100644
--- a/apps/web/src/lib/api.test.mjs
+++ b/apps/web/src/lib/api.test.mjs
@@ -90,6 +90,7 @@ const {
clearCachedDesktopSession,
getConfiguredDesktopApiBaseUrl,
getCachedDesktopSession,
+ getWorkspaceSession,
getOrCreateClientDeviceId,
saveDesktopApiBaseUrl,
} = await import("./api.ts?desktop-ai-routing-test");
@@ -515,7 +516,7 @@ describe("desktop instance setup", () => {
await expect(api.getSession()).resolves.toMatchObject({ authenticated: false });
await Promise.resolve();
expect(secureSessionToken).toBe("");
- expect(events).toEqual(["edgeever:unauthorized"]);
+ expect(events).toEqual([]);
globalThis.fetch = async () => Response.json({
authRequired: true,
@@ -692,3 +693,127 @@ describe("desktop instance setup", () => {
test("infographic authentication errors never invoke instance generation",async()=>{const paths=[];globalThis.fetch=async url=>{paths.push(String(url));return Response.json({error:{code:"unauthorized",message:"Sign in"}},{status:401});};await expect(api.streamInfographicAgent({prompt:"Make a list",currentContent:"",candidates:["list-grid-simple"],history:[]},{onEvent(){}})).rejects.toMatchObject({status:401});expect(paths.filter(path=>path.includes("/ai/"))).toHaveLength(1);expect(paths[0]).toContain("/api/v1/ai/infographic-agent/prepare");});
});
+
+
+describe("desktop workspace during a server outage", () => {
+ const session = {
+ authRequired: true, authenticated: true, demoMode: false,
+ sessionToken: "offline-workspace-token",
+ user: { id: "offline-user", username: "offline", displayName: null, role: "owner" },
+ };
+ const establishSession = async () => {
+ storage.set(DESKTOP_API_BASE_URL_STORAGE_KEY, "https://notes.example.com");
+ globalThis.fetch = async () => Response.json(session);
+ await cacheDesktopSession(await api.login({ username: "offline", password: "test" }));
+ events.length = 0;
+ };
+
+ test("opens the cached desktop account on 500/503, quota, throttling and network failures while online", async () => {
+ await establishSession();
+ for (const status of [500, 502, 503, 504, 408, 429]) {
+ globalThis.fetch = async () => Response.json({ error: { code: "database_daily_quota_exceeded", message: "Unavailable" } }, { status });
+ expect(await getWorkspaceSession()).toMatchObject({ authenticated: true, user: session.user });
+ expect(secureSessionToken).toBe(session.sessionToken);
+ }
+ globalThis.fetch = async () => { throw new TypeError("fetch failed"); };
+ expect(await getWorkspaceSession()).toMatchObject({ authenticated: true, user: session.user });
+ expect(events).toEqual([]);
+ });
+
+ test("failed 401 confirmation never clears the local account or credential", async () => {
+ await establishSession();
+ for (const failure of [500, 503, 429, "network", "invalid-json", "invalid-session"]) {
+ globalThis.fetch = async url => {
+ if (!String(url).endsWith("/api/v1/auth/session")) return Response.json({ error: { code: "unauthorized" } }, { status: 401 });
+ if (failure === "network") throw new TypeError("fetch failed");
+ if (failure === "invalid-json") return new Response("<html>proxy</html>");
+ if (failure === "invalid-session") return Response.json({});
+ return Response.json({ error: { message: "unavailable" } }, { status: failure });
+ };
+ await expect(api.syncBootstrap({ limit: 200 })).rejects.toMatchObject({ status: 401 });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(getCachedDesktopSession()).toMatchObject({ authenticated: true, user: session.user });
+ expect(secureSessionToken).toBe(session.sessionToken);
+ expect(events).toEqual([]);
+ }
+ });
+
+ test("malformed session responses preserve the established account", async () => {
+ await establishSession();
+ for (const response of [{}, { authenticated: false }, null]) {
+ globalThis.fetch = async () => Response.json(response);
+ expect(await getWorkspaceSession()).toMatchObject({ authenticated: true, user: session.user });
+ expect(secureSessionToken).toBe(session.sessionToken);
+ }
+ expect(events).toEqual([]);
+ });
+
+ test("first launch and a different instance cannot borrow an old local identity", async () => {
+ await establishSession();
+ clearCachedDesktopSession();
+ globalThis.fetch = async () => new Response("unavailable", { status: 503 });
+ await expect(getWorkspaceSession()).rejects.toMatchObject({ status: 503 });
+ await establishSession();
+ let rejectRequest;
+ globalThis.fetch = () => new Promise((_, reject) => { rejectRequest = reject; });
+ const pending = getWorkspaceSession();
+ await new Promise(resolve => setTimeout(resolve, 0));
+ storage.set(DESKTOP_API_BASE_URL_STORAGE_KEY, "https://other.example.com");
+ rejectRequest(new TypeError("fetch failed"));
+ await expect(pending).rejects.toBeInstanceOf(TypeError);
+ storage.set(DESKTOP_API_BASE_URL_STORAGE_KEY, "https://notes.example.com");
+ });
+
+ test("a delayed session rejection cannot clear a newly established credential", async () => {
+ await establishSession();
+ let finish;
+ globalThis.fetch = () => new Promise(resolve => { finish = resolve; });
+ const pending = getWorkspaceSession();
+ await new Promise(resolve => setTimeout(resolve, 0));
+ await cacheDesktopSession({ ...session, sessionToken: "newer-offline-token" });
+ finish(Response.json({ error: { code: "unauthorized" } }, { status: 401 }));
+ await expect(pending).rejects.toMatchObject({ status: 401 });
+ expect(secureSessionToken).toBe("newer-offline-token");
+ expect(getCachedDesktopSession()).toMatchObject({ authenticated: true, user: session.user });
+ expect(events).toEqual([]);
+ });
+
+ test("replacement credentials do not reuse an older in-flight rejection confirmation", async () => {
+ await establishSession();
+ let finishOldConfirmation;
+ let probes = 0;
+ globalThis.fetch = async (url, init) => {
+ if (!String(url).endsWith("/api/v1/auth/session")) return Response.json({ error: { code: "unauthorized" } }, { status: 401 });
+ probes++;
+ if (new Headers(init?.headers).get("Authorization") === `Bearer ${session.sessionToken}`) {
+ return new Promise(resolve => { finishOldConfirmation = resolve; });
+ }
+ return new Response("unavailable", { status: 503 });
+ };
+ await expect(api.syncBootstrap({ limit: 200 })).rejects.toMatchObject({ status: 401 });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(finishOldConfirmation).toBeFunction();
+ await cacheDesktopSession({ ...session, sessionToken: "replacement-during-confirmation" });
+ await expect(api.syncBootstrap({ limit: 200 })).rejects.toMatchObject({ status: 401 });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(probes).toBe(2);
+ finishOldConfirmation(Response.json({ authRequired: true, authenticated: false, demoMode: false, user: null }));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(secureSessionToken).toBe("replacement-during-confirmation");
+ expect(getCachedDesktopSession()).toMatchObject({ authenticated: true, user: session.user });
+ expect(events).toEqual([]);
+ });
+
+ test("explicit session rejection still requires login and clears cached credentials", async () => {
+ for (const status of [200, 401]) {
+ await establishSession();
+ globalThis.fetch = async () => status === 200
+ ? Response.json({ authRequired: true, authenticated: false, demoMode: false, user: null })
+ : Response.json({ error: { code: "unauthorized" } }, { status: 401 });
+ expect((await getWorkspaceSession()).authenticated).toBe(false);
+ expect(getCachedDesktopSession()).toBeNull();
+ expect(secureSessionToken).toBe("");
+ expect(events).toEqual([]);
+ }
+ });
+});
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 15117669..2d547e7c 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -157,16 +157,29 @@ export const getOrCreateClientDeviceId = () => {
let desktopSessionRejected = false;
let unauthorizedConfirmPromise: Promise<boolean> | null = null;
+let unauthorizedConfirmContext: string | null = null;
const isDesktopPublicRequest = (path: string) =>
path === "/api/release" || path === "/api/v1/auth/login" || path === "/api/v1/auth/session";
-/** Confirm the current browser or desktop session is lost before signing out. */
+const isAuthSession = (value: unknown): value is AuthSession => {
+ if (!value || typeof value !== "object") return false;
+ const session = value as AuthSession;
+ return typeof session.authRequired === "boolean"
+ && typeof session.authenticated === "boolean"
+ && typeof session.demoMode === "boolean"
+ && (session.authenticated
+ ? Boolean(session.user && typeof session.user.id === "string" && session.user.id.trim())
+ : session.authRequired && session.user === null);
+};
+
+/** Only an explicit authentication rejection confirms that a session is lost. */
const confirmSessionLost = async (): Promise<boolean> => {
if (typeof window === "undefined") return true;
- if (unauthorizedConfirmPromise) return unauthorizedConfirmPromise;
+ const context = JSON.stringify([getConfiguredDesktopApiBaseUrl(), getDesktopSessionToken()]);
+ if (unauthorizedConfirmPromise && unauthorizedConfirmContext === context) return unauthorizedConfirmPromise;
- unauthorizedConfirmPromise = (async () => {
+ const promise = (async () => {
try {
const headers = new Headers();
const isDesktop = Boolean(window.edgeeverDesktop?.isAvailable);
@@ -177,28 +190,35 @@ const confirmSessionLost = async (): Promise<boolean> => {
credentials: "include",
headers,
});
- if (!response.ok) return true;
- const session = await response.json().catch(() => null) as AuthSession | null;
- return !session?.authenticated;
+ if (!response.ok) return response.status === 401;
+ const session: unknown = await response.json().catch(() => null);
+ return isAuthSession(session) && session.authenticated === false;
} catch {
- return true;
+ return false;
} finally {
queueMicrotask(() => {
- unauthorizedConfirmPromise = null;
+ if (unauthorizedConfirmPromise === promise) {
+ unauthorizedConfirmPromise = null;
+ unauthorizedConfirmContext = null;
+ }
});
}
})();
- return unauthorizedConfirmPromise;
+ unauthorizedConfirmPromise = promise;
+ unauthorizedConfirmContext = context;
+ return promise;
};
const notifyUnauthorized = async (isDesktop: boolean, rejectedDesktopSessionToken?: string) => {
+ const baseUrl = getConfiguredDesktopApiBaseUrl();
if (isDesktop && desktopSessionRejected) return;
if (isDesktop && rejectedDesktopSessionToken) {
if (getDesktopSessionToken() !== rejectedDesktopSessionToken) return;
const sessionLost = await confirmSessionLost();
- if (!sessionLost || getDesktopSessionToken() !== rejectedDesktopSessionToken) return;
+ if (!sessionLost || getConfiguredDesktopApiBaseUrl() !== baseUrl
+ || getDesktopSessionToken() !== rejectedDesktopSessionToken) return;
clearCachedDesktopSession();
desktopSessionRejected = true;
window.dispatchEvent(new CustomEvent("edgeever:unauthorized"));
@@ -206,7 +226,7 @@ const notifyUnauthorized = async (isDesktop: boolean, rejectedDesktopSessionToke
}
const sessionLost = await confirmSessionLost();
- if (!sessionLost) return;
+ if (!sessionLost || getConfiguredDesktopApiBaseUrl() !== baseUrl) return;
if (isDesktop) {
clearCachedDesktopSession();
@@ -224,6 +244,9 @@ const beforeRequest = ({ path }: EdgeEverClientRequestContext) => {
const handleUnauthorized = ({ path, token }: EdgeEverClientRequestContext) => {
if (path === "/api/v1/auth/login" || path.startsWith("/api/public/") || typeof window === "undefined") return;
+ // getSession handles its own response. A failed probe is not evidence of
+ // rejection and must not launch a second probe that can race a new login.
+ if (path === "/api/v1/auth/session") return;
const isDesktop = Boolean(window.edgeeverDesktop?.isAvailable);
void notifyUnauthorized(isDesktop, token);
};
@@ -342,7 +365,27 @@ export const api = {
...client,
getSession: async () => {
- const session = await client.getSession();
+ const baseUrl = getConfiguredDesktopApiBaseUrl();
+ const token = getDesktopSessionToken();
+ let session: AuthSession;
+ try {
+ session = await client.getSession();
+ } catch (error) {
+ if (error instanceof ApiRequestError && error.status === 401
+ && getConfiguredDesktopApiBaseUrl() === baseUrl && getDesktopSessionToken() === token) {
+ if (typeof window !== "undefined") {
+ if (window.edgeeverDesktop?.isAvailable) {
+ clearCachedDesktopSession();
+ desktopSessionRejected = true;
+ }
+ }
+ }
+ throw error;
+ }
+ if (!isAuthSession(session)) throw new SyntaxError("Invalid authentication session response");
+ if (getConfiguredDesktopApiBaseUrl() !== baseUrl || getDesktopSessionToken() !== token) {
+ throw new Error("Authentication context changed while checking the session");
+ }
if (
typeof window !== "undefined"
&& window.edgeeverDesktop?.isAvailable
@@ -351,7 +394,6 @@ export const api = {
) {
clearCachedDesktopSession();
desktopSessionRejected = true;
- window.dispatchEvent(new CustomEvent("edgeever:unauthorized"));
}
return session;
},
@@ -362,3 +404,30 @@ export const api = {
return session;
},
};
+
+/** Keep an established desktop account usable when its server is unavailable. */
+export const getWorkspaceSession = async (): Promise<AuthSession> => {
+ const baseUrl = getConfiguredDesktopApiBaseUrl();
+ const token = getDesktopSessionToken();
+ try {
+ const session = await api.getSession();
+ if (session.authenticated) await cacheDesktopSession(session);
+ else clearCachedDesktopSession();
+ return session;
+ } catch (error) {
+ const cached = getCachedDesktopSession();
+ // Let the session query finish normally on an explicit rejection instead
+ // of clearing the very query that is resolving it.
+ if (error instanceof ApiRequestError && error.status === 401
+ && baseUrl === getConfiguredDesktopApiBaseUrl() && !getDesktopSessionToken()) {
+ return { authRequired: true, authenticated: false, demoMode: false, user: null };
+ }
+ const unavailable = error instanceof TypeError || error instanceof SyntaxError
+ || (error instanceof ApiRequestError && (error.status >= 500 || error.status === 408 || error.status === 429));
+ if (unavailable && cached?.authenticated && isAuthSession(cached)
+ && baseUrl === getConfiguredDesktopApiBaseUrl() && token === getDesktopSessionToken()) {
+ return cached;
+ }
+ throw error;
+ }
+};
diff --git a/docs/changes/2026-10-31-desktop-offline-session.md b/docs/changes/2026-10-31-desktop-offline-session.md
new file mode 100644
index 00000000..539cf1b0
--- /dev/null
+++ b/docs/changes/2026-10-31-desktop-offline-session.md
@@ -0,0 +1,33 @@
+# Keep desktop workspaces available during server outages
+
+## Problem and change
+
+Desktop startup previously reused a cached authenticated session only when `navigator.onLine` reported offline. A reachable server returning HTTP 500/503 therefore prevented access to the existing local workspace. A separate session confirmation path treated failed requests and malformed responses as confirmation of session loss and could clear the cached identity and secure token.
+
+`App` now loads its session through one tested workspace loader. An established desktop account remains available on server 5xx, request timeout responses, throttling, network failures and malformed session responses, without relying on the operating system's connectivity flag. Local editing continues through the existing SQLite repository and durable outbox. The server must still authenticate every remote request; this fallback grants no remote permissions.
+
+Startup probes return their own unauthenticated result without clearing their in-flight query. Background revocation retains the observed session query while clearing other account queries, avoiding a stuck startup screen. Session-loss confirmation requires an explicit rejection. Unknown results preserve the cached identity and credential. Confirmation requests are deduplicated per instance/credential, and late responses cannot invalidate replacement credentials or a switched instance. A valid unauthenticated session or explicit session-endpoint 401 still requires login. First launch without a cached account does not gain offline access.
+
+## Risk and rollback
+
+The main risk is using an incorrect account identity or retaining it after confirmed revocation. Instance/credential checks and existing account-scope isolation remain authoritative. Cache format, secure credential storage, local schema, migrations, synchronization protocol and installer/updater code are unchanged. Revert the loader and confirmation changes to roll back; do not delete local profiles or pending outbox records.
+
+## Verification
+
+The reusable native regression runs a real authenticated API on isolated SQLite, a released old desktop application, and a fixed packaged application against the same temporary profile:
+
+```sh
+node tests/desktop-offline-upgrade.integration.mjs /path/to/old/executable /path/to/fixed/executable
+```
+
+It establishes the old client's login and local note through the UI, reproduces the old HTTP 500 login screen, then checks local UI editing after upgrade, persistence across a full native restart with HTTP 503, a route 401 whose session confirmation fails, recovery synchronization of all queued edits, and actual server-side session revocation. The test retains screenshots and a result manifest in its printed temporary evidence directory. It never accesses production services or the owner's profile.
+
+## Executed verification
+
+- macOS arm64, formal v2.16.1 native host and sidecar; Electron 44.7.0 / Node 24.21.0. The candidate changes the production renderer only, retains the released host/sidecar, and is Developer ID signed and Apple notarized. Both bundles still display 2.16.1 because this is a test candidate, not a published release.
+- Seven native scenarios pass on the same old-created profile: login/local persistence; baseline `http_500`; upgrade plus offline UI editing under HTTP 500; full restart and editing under HTTP 503; route 401 with failed confirmation; uploading every queued edit with the unchanged credential after recovery; real session revocation while running and after restart, followed by reauthentication and reading the original local note.
+- The fault responses are real HTTP responses from a loopback fixture with normal CORS headers, around the real authenticated API and SQLite storage. Neither renderer API methods nor the desktop bridge are mocked. No production D1 load or user-profile changes were used.
+- 101 API tests pass, including first-launch denial, invalid responses, instance changes, explicit rejection, and late/concurrent credential replacement. Full non-E2E suites pass: 4,566 + 17 + 24 tests, with one Windows-only cleanup test skipped on macOS. Web/API typecheck, mobile typecheck and production Web build pass.
+- [Native results](evidence/2026-10-31-desktop-offline-session/results.json) record the recovered server content and zero pending/syncing/error/conflict items. Screenshots show the [old 500 login screen](evidence/2026-10-31-desktop-offline-session/old-500-login.png), [local editing during HTTP 500](evidence/2026-10-31-desktop-offline-session/fixed-500-local-edit.png), and [recovered workspace](evidence/2026-10-31-desktop-offline-session/fixed-recovered.png).
+
+Windows/Linux native execution, signed installer replacement and updater transport were not verified in this change. There is no new schema migration, release publication or installation over the owner's application. If an older client already erased its identity and credential, this change cannot safely reconstruct them; successful authentication is required to reopen that account's existing local data.
diff --git a/docs/changes/2026-10-31-desktop-offline-session.zh-CN.md b/docs/changes/2026-10-31-desktop-offline-session.zh-CN.md
new file mode 100644
index 00000000..88df6920
--- /dev/null
+++ b/docs/changes/2026-10-31-desktop-offline-session.zh-CN.md
@@ -0,0 +1,33 @@
+# 服务端故障时保留桌面本地工作区
+
+## 问题与改动
+
+桌面启动此前仅在 `navigator.onLine` 报告断网时使用已认证会话缓存。因此,服务器可达但返回 HTTP 500/503 时,已有本地工作区仍无法打开。另一条会话确认路径把请求失败和无效响应当作会话失效,可能清除缓存身份及安全存储的凭据。
+
+`App` 现在统一通过经过测试的工作区会话加载函数启动。已有桌面账号遇到服务端 5xx、请求超时响应、限流、网络错误及无效会话响应时,保留本地访问,不再依赖操作系统的联网标志。本地编辑仍通过既有 SQLite 仓库和持久化同步队列保存。每个远端请求仍须经过服务端认证,此兜底不授予远端权限。
+
+启动探测直接返回未认证结果,不清除正在执行的查询。后台发现会话撤销时,保留界面观察中的会话查询并清理其他账号查询,避免卡在启动页。只有明确的拒绝结果才确认会话失效;无法判断的结果保留缓存身份和凭据。确认请求按实例及凭据去重,旧请求不得使替换后的凭据或切换后的实例失效。有效的未认证会话响应或会话接口明确返回 401 仍要求重新登录。首次启动且没有缓存账号时,不放行离线访问。
+
+## 风险与回滚
+
+主要风险是使用错误账号身份,或在确认撤销后仍保留身份。实例、凭据检查及既有账号目录隔离继续生效。会话缓存格式、安全凭据存储、本地结构、迁移、同步协议和安装升级代码均未变更。撤回加载函数及确认逻辑即可回滚;不得删除本地数据目录或待同步记录。
+
+## 验证
+
+可重复运行的原生回归测试使用真实认证 API、隔离 SQLite、正式旧版桌面应用,以及修复后的应用包,并共用同一临时数据目录:
+
+```sh
+node tests/desktop-offline-upgrade.integration.mjs /path/to/old/executable /path/to/fixed/executable
+```
+
+测试先通过旧版 UI 登录并保存本地笔记,复现旧版在 HTTP 500 时退回登录页;随后验证升级后 UI 编辑、HTTP 503 下完整退出重启后的持久化、业务接口 401 且会话确认失败、服务恢复后上传全部待同步编辑,以及服务端真正撤销会话。截图和结果清单保留在输出的临时证据目录中,不访问生产服务或所有者的数据目录。
+
+## 已执行的验证
+
+- macOS arm64,正式 v2.16.1 的原生宿主及 sidecar,Electron 44.7.0 / Node 24.21.0。候选包仅替换生产构建的渲染端,保留正式版宿主和 sidecar,并完成 Developer ID 签名及 Apple 公证。两个应用仍显示 2.16.1,因为候选包用于测试,尚未正式发布新版。
+- 同一份旧版创建的数据目录通过七项原生场景:登录与本地持久化;旧版 `http_500` 复现;500 下升级并通过 UI 离线编辑;503 下完整重启后继续编辑;业务接口 401 且会话确认失败;服务恢复后使用原凭据上传全部编辑;运行中及重启后真实会话撤销要求重新登录,重新认证后仍能打开原有本地笔记。
+- 故障由回环地址测试服务返回真实 HTTP 响应,保留正常跨域头,底层使用真实认证 API 和 SQLite。未替换渲染端 API 方法或桌面桥接,不对生产 D1 压测,也不修改用户数据目录。
+- 101 项 API 测试通过,包含首次启动不放行、无效响应、切换实例、明确拒绝,以及凭据替换中的延迟和并发响应。全量非 E2E 测试通过:4,566 + 17 + 24 项,macOS 跳过一项仅适用 Windows 的清理测试。Web/API 类型检查、移动端类型检查和 Web 生产构建通过。
+- [原生结果清单](evidence/2026-10-31-desktop-offline-session/results.json)记录恢复后的服务端正文,及待同步、同步中、错误、冲突均为零。截图包括[旧版 500 登录页](evidence/2026-10-31-desktop-offline-session/old-500-login.png)、[500 故障期间本地编辑](evidence/2026-10-31-desktop-offline-session/fixed-500-local-edit.png)、[恢复后的工作区](evidence/2026-10-31-desktop-offline-session/fixed-recovered.png)。
+
+本次未验证 Windows/Linux 原生执行、签名安装器替换或自动更新传输。没有新增数据库迁移、正式发版或覆盖安装用户应用。如果旧客户端此前已经清除了身份和凭据,本次改动不能安全地重建它们,仍需成功认证后重新打开该账号已有本地数据。
diff --git a/docs/changes/evidence/2026-10-31-desktop-offline-session/fixed-500-local-edit.png b/docs/changes/evidence/2026-10-31-desktop-offline-session/fixed-500-local-edit.png
new file mode 100644
index 00000000..7e6e9f9a
Binary files /dev/null and b/docs/changes/evidence/2026-10-31-desktop-offline-session/fixed-500-local-edit.png differ
diff --git a/docs/changes/evidence/2026-10-31-desktop-offline-session/fixed-recovered.png b/docs/changes/evidence/2026-10-31-desktop-offline-session/fixed-recovered.png
new file mode 100644
index 00000000..1cc165c5
Binary files /dev/null and b/docs/changes/evidence/2026-10-31-desktop-offline-session/fixed-recovered.png differ
diff --git a/docs/changes/evidence/2026-10-31-desktop-offline-session/old-500-login.png b/docs/changes/evidence/2026-10-31-desktop-offline-session/old-500-login.png
new file mode 100644
index 00000000..22d6d408
Binary files /dev/null and b/docs/changes/evidence/2026-10-31-desktop-offline-session/old-500-login.png differ
diff --git a/docs/changes/evidence/2026-10-31-desktop-offline-session/results.json b/docs/changes/evidence/2026-10-31-desktop-offline-session/results.json
new file mode 100644
index 00000000..e0c3af43
--- /dev/null
+++ b/docs/changes/evidence/2026-10-31-desktop-offline-session/results.json
@@ -0,0 +1,79 @@
+{
+ "runtimes": {
+ "old": {
+ "version": "2.16.1",
+ "electron": "44.7.0",
+ "node": "24.21.0",
+ "platform": "darwin"
+ },
+ "fixed": {
+ "version": "2.16.1",
+ "electron": "44.7.0",
+ "node": "24.21.0",
+ "platform": "darwin"
+ }
+ },
+ "observations": {
+ "outageQueue": {
+ "conflict": 0,
+ "cursor": 31,
+ "error": 0,
+ "lastSyncedAt": "1793439413",
+ "pending": 1,
+ "syncIdentity": "2026-10-31T09:36:47.688Z",
+ "syncing": 0
+ },
+ "recoveredContent": "Old version original body old-version-edit fixed-offline-500-edit fixed-offline-503-edit failed-confirmation-edit",
+ "credentialPreserved": true,
+ "recoveredQueue": {
+ "conflict": 0,
+ "cursor": 32,
+ "error": 0,
+ "lastSyncedAt": "1793439428",
+ "pending": 0,
+ "syncIdentity": "2026-10-31T09:36:47.688Z",
+ "syncing": 0
+ },
+ "localDataPreservedAfterReauthentication": true
+ },
+ "results": [
+ {
+ "name": "released old app signs in and persists real local data",
+ "ok": true
+ },
+ {
+ "name": "old version reproduces login-screen failure on HTTP 500 without deleting its local identity",
+ "ok": true
+ },
+ {
+ "name": "fixed app upgrades the same old profile during HTTP 500 and reads/writes offline",
+ "ok": true
+ },
+ {
+ "name": "offline edits survive a full native restart with D1 quota HTTP 503",
+ "ok": true
+ },
+ {
+ "name": "route 401 plus failed session confirmation cannot sign out the local account",
+ "ok": true
+ },
+ {
+ "name": "restoring service uploads all queued edits with the original credential",
+ "ok": true
+ },
+ {
+ "name": "actual session revocation requires login while running and after restart",
+ "ok": true
+ }
+ ],
+ "candidate": {
+ "baseRelease": "v2.16.1",
+ "nativeHostAndSidecar": "unchanged from released macOS arm64 application",
+ "notarizationSubmission": "efe438f6-5cfd-4872-961a-816ac79870ad",
+ "notarizationStatus": "Accepted",
+ "productionServicesAccessed": false,
+ "ownerProfileModified": false,
+ "hostSha256": "15392f5114806a97b115c3a024cf8717ea74bdf14bf95a8a1a7f0fb2d37a20f1",
+ "sidecarSha256": "8b7812e6e9b35f422c51d72f1ac0c9cf52f4836f21f5f7cc6caa9c320f5cad70"
+ }
+}
diff --git a/tests/desktop-offline-api.mjs b/tests/desktop-offline-api.mjs
new file mode 100644
index 00000000..184fb37d
--- /dev/null
+++ b/tests/desktop-offline-api.mjs
@@ -0,0 +1,48 @@
+// Loopback-only real API/storage fixture for desktop offline upgrade verification.
+import { Database } from "bun:sqlite";
+import { readdir, readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { fetchEdgeEverApp } from "../apps/api/src/index.ts";
+import { createSelfHostedStorageAdapter } from "../apps/api/src/self-hosted-storage-adapter.ts";
+
+const directory = process.argv[2];
+if (!directory) throw new Error("Pass an isolated test directory");
+const database = new Database(join(directory, "api.sqlite"));
+for (const name of (await readdir("migrations")).filter(name => name.endsWith(".sql")).sort()) {
+ database.exec(await readFile(join("migrations", name), "utf8"));
+}
+const environment = {
+ storage: createSelfHostedStorageAdapter(database, join(directory, "resources")),
+ EDGE_EVER_AUTH_PASSWORD: "offline-test-password-only",
+ EDGE_EVER_RUNTIME: "self-hosted-bun",
+};
+let mode = "healthy";
+const counters = {};
+const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) {
+ const path = new URL(request.url).pathname;
+ if (path === "/__test/control" && request.method === "POST") {
+ const input = await request.json();
+ mode = input.mode;
+ if (input.revoke) database.exec("DELETE FROM sessions");
+ return Response.json({ mode });
+ }
+ if (path === "/__test/status") return Response.json({ mode, counters });
+ const cors = {
+ "Access-Control-Allow-Origin": request.headers.get("Origin") ?? "null",
+ "Access-Control-Allow-Credentials": "true",
+ "Access-Control-Allow-Headers": "Authorization, Content-Type",
+ "Access-Control-Allow-Methods": "GET, POST, PATCH, PUT, DELETE, OPTIONS",
+ "Vary": "Origin",
+ };
+ if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: cors });
+ counters[path] = (counters[path] ?? 0) + 1;
+ if (mode !== "healthy") {
+ const status = mode === "protected401" && path !== "/api/v1/auth/session" ? 401
+ : mode === "500" ? 500 : 503;
+ return Response.json({ error: { code: status === 401 ? "unauthorized" : "database_daily_quota_exceeded", message: "Test server unavailable" } }, { status, headers: cors });
+ }
+ return fetchEdgeEverApp(request, environment, { waitUntil() {}, passThroughOnException() {} });
+} });
+process.stdin.on("end", () => { server.stop(true); database.close(); process.exit(0); });
+process.stdin.resume();
+console.log(`READY http://127.0.0.1:${server.port}`);
diff --git a/tests/desktop-offline-upgrade.integration.mjs b/tests/desktop-offline-upgrade.integration.mjs
new file mode 100644
index 00000000..43b621b0
--- /dev/null
+++ b/tests/desktop-offline-upgrade.integration.mjs
@@ -0,0 +1,189 @@
+// Real old/new packaged Electron applications, same isolated profile and SQLite.
+// node tests/desktop-offline-upgrade.integration.mjs <old executable> <fixed executable>
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { _electron as electron, expect } from "@playwright/test";
+
+const [oldExecutable, fixedExecutable] = process.argv.slice(2).map(path => resolve(path));
+assert.ok(oldExecutable && fixedExecutable, "Pass old and fixed native executables");
+const directory = await mkdtemp(join(tmpdir(), "edgeever-offline-transition-"));
+const profile = join(directory, "profile");
+const results = [];
+const runtimes = {};
+const observations = {};
+let application, page, baseUrl, token;
+const server = spawn("bun", ["tests/desktop-offline-api.mjs", directory], { stdio: ["pipe", "pipe", "inherit"] });
+const control = async (mode, revoke = false) => {
+ const response = await fetch(`${baseUrl}/__test/control`, { method: "POST", body: JSON.stringify({ mode, revoke }) });
+ assert.equal(response.status, 200);
+};
+const api = async (path, init = {}) => {
+ const response = await fetch(`${baseUrl}${path}`, { ...init, headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) } });
+ assert.ok(response.ok, `${path}: HTTP ${response.status} ${await response.clone().text()}`);
+ return response.json();
+};
+const launch = async executablePath => {
+ application = await electron.launch({ executablePath, args: [`--user-data-dir=${profile}`], env: { ...process.env, EDGE_EVER_DISABLE_AUTO_UPDATE: "1" }, timeout: 60_000 });
+ await expect.poll(() => application.windows().some(w => w.url().startsWith("edgeever-app://app/index.html")), { timeout: 60_000 }).toBe(true);
+ page = application.windows().find(w => w.url().startsWith("edgeever-app://app/index.html"));
+ await page.waitForSelector('[data-edgeever-renderer-ready="true"]', { state: "attached", timeout: 60_000 });
+ const label = executablePath === oldExecutable ? "old" : "fixed";
+ runtimes[label] ??= await application.evaluate(({ app }) => ({ version: app.getVersion(), electron: process.versions.electron, node: process.versions.node, platform: process.platform }));
+};
+const close = async () => {
+ if (application) await application.close();
+ application = undefined;
+};
+const syncNow = () => application.evaluate(({ BrowserWindow }) => {
+ BrowserWindow.getAllWindows().find(w => !w.webContents.getURL().includes("noteWindow="))?.webContents.send("desktop:command", "sync-now");
+});
+const local = id => page.evaluate(id => window.edgeeverDesktop.sidecarRequest("memo.get", { memoId: id }), id);
+const cachedUser = () => page.evaluate(() => JSON.parse(localStorage.getItem("edgeever.desktop.session"))?.user?.id);
+const credential = () => page.evaluate(() => window.edgeeverDesktop.getSessionToken());
+const open = async memo => {
+ await page.getByRole("button", { name: "All notes", exact: true }).click();
+ await page.getByPlaceholder("Search notes").first().fill(memo.title);
+ const card = page.locator(`[data-memo-id="${memo.id}"]`).first();
+ await expect(card).toBeVisible({ timeout: 30_000 });
+ await card.locator("button").first().click();
+ await expect(page.locator('.ProseMirror[contenteditable="true"]')).toBeVisible();
+};
+const edit = async (memo, text) => {
+ await open(memo);
+ await page.locator('.ProseMirror[contenteditable="true"]').click();
+ await page.keyboard.press("ControlOrMeta+End");
+ await page.keyboard.type(` ${text}`);
+ await expect.poll(async () => (await local(memo.id)).memo.contentMarkdown, { timeout: 30_000 }).toContain(text);
+};
+const record = async (name, run) => {
+ await run();
+ results.push({ name, ok: true });
+ console.log(`PASS ${name}`);
+};
+try {
+ baseUrl = await new Promise((resolveUrl, reject) => {
+ let output = "";
+ server.on("error", reject);
+ server.on("exit", code => reject(new Error(`API exited ${code}`)));
+ server.stdout.on("data", chunk => { output += chunk; const match = output.match(/READY (\S+)/); if (match) resolveUrl(match[1]); });
+ });
+ const signedIn = await api("/api/v1/auth/login", { method: "POST", body: JSON.stringify({ username: "admin", password: "offline-test-password-only", deviceId: "offline-upgrade-test-driver" }) });
+ token = signedIn.sessionToken;
+ assert.ok(token);
+ const notebook = (await api("/api/v1/notebooks", { method: "POST", body: JSON.stringify({ name: "Offline upgrade" }) })).notebook;
+ const memo = (await api("/api/v1/memos", { method: "POST", body: JSON.stringify({ notebookId: notebook.id, title: "Offline upgrade note", contentMarkdown: "Old version original body" }) })).memo;
+ await mkdir(profile, { recursive: true });
+ await writeFile(join(profile, "instance-url"), baseUrl);
+ await writeFile(join(profile, "installation-confirmed"), "test");
+ let oldCredential, userId;
+ await record("released old app signs in and persists real local data", async () => {
+ await launch(oldExecutable);
+ await page.evaluate(() => localStorage.setItem("edgeever.locale.preference", "en-US"));
+ await page.reload();
+ await page.locator('input[autocomplete="username"]').fill("admin");
+ await page.locator('input[autocomplete="current-password"]').fill("offline-test-password-only");
+ await page.locator('button[type="submit"]').click();
+ await expect(page.getByPlaceholder("Search notes").first()).toBeVisible({ timeout: 60_000 });
+ await expect.poll(() => local(memo.id).then(result => result.memo.contentMarkdown).catch(() => ""), { timeout: 60_000 }).toContain("Old version original body");
+ await edit(memo, "old-version-edit");
+ await syncNow();
+ await expect.poll(async () => (await api(`/api/v1/memos/${memo.id}`)).memo.contentMarkdown, { timeout: 60_000 }).toContain("old-version-edit");
+ oldCredential = await credential(); userId = await cachedUser();
+ assert.ok(oldCredential && userId);
+ await close();
+ });
+ await record("old version reproduces login-screen failure on HTTP 500 without deleting its local identity", async () => {
+ await control("500");
+ await launch(oldExecutable);
+ await expect(page.locator('input[autocomplete="current-password"]')).toBeVisible({ timeout: 30_000 });
+ await expect(page.getByRole("alert")).toContainText("http_500");
+ assert.equal(await credential(), oldCredential);
+ assert.equal(await cachedUser(), userId);
+ await page.screenshot({ path: join(directory, "old-500-login.png") });
+ await close();
+ });
+ await record("fixed app upgrades the same old profile during HTTP 500 and reads/writes offline", async () => {
+ await launch(fixedExecutable);
+ await edit(memo, "fixed-offline-500-edit");
+ assert.equal(await cachedUser(), userId);
+ assert.equal(await credential(), oldCredential);
+ const queued = await page.evaluate(() => window.edgeeverDesktop.sidecarRequest("sync.status", {}));
+ assert.ok(queued.pending + queued.syncing + queued.error > 0);
+ observations.outageQueue = queued;
+ await page.screenshot({ path: join(directory, "fixed-500-local-edit.png") });
+ await close();
+ });
+ await record("offline edits survive a full native restart with D1 quota HTTP 503", async () => {
+ await control("503");
+ await launch(fixedExecutable);
+ await open(memo);
+ await expect(page.locator('.ProseMirror[contenteditable="true"]')).toContainText("fixed-offline-500-edit");
+ await edit(memo, "fixed-offline-503-edit");
+ assert.equal(await credential(), oldCredential);
+ });
+ await record("route 401 plus failed session confirmation cannot sign out the local account", async () => {
+ const before = (await fetch(`${baseUrl}/__test/status`).then(r => r.json())).counters["/api/v1/auth/session"] ?? 0;
+ await control("protected401");
+ await page.reload();
+ await open(memo);
+ await syncNow();
+ // One startup probe plus at least one real 401 confirmation.
+ await expect.poll(async () => (await fetch(`${baseUrl}/__test/status`).then(r => r.json())).counters["/api/v1/auth/session"], { timeout: 30_000 }).toBeGreaterThan(before + 1);
+ await edit(memo, "failed-confirmation-edit");
+ assert.equal(await cachedUser(), userId);
+ assert.equal(await credential(), oldCredential);
+ await close();
+ });
+ await record("restoring service uploads all queued edits with the original credential", async () => {
+ await control("healthy");
+ await launch(fixedExecutable);
+ await syncNow();
+ await expect.poll(async () => (await api(`/api/v1/memos/${memo.id}`)).memo.contentMarkdown, { timeout: 90_000 }).toContain("failed-confirmation-edit");
+ const remote = (await api(`/api/v1/memos/${memo.id}`)).memo.contentMarkdown;
+ for (const text of ["old-version-edit", "fixed-offline-500-edit", "fixed-offline-503-edit"]) assert.ok(remote.includes(text));
+ assert.equal(await credential(), oldCredential);
+ observations.recoveredContent = remote;
+ observations.credentialPreserved = true;
+ await expect.poll(async () => {
+ const state = await page.evaluate(() => window.edgeeverDesktop.sidecarRequest("sync.status", {}));
+ return state.pending + state.syncing + state.error + state.conflict;
+ }, { timeout: 30_000 }).toBe(0);
+ observations.recoveredQueue = await page.evaluate(() => window.edgeeverDesktop.sidecarRequest("sync.status", {}));
+ await open(memo);
+ await expect(page.locator('.ProseMirror[contenteditable="true"]')).toContainText("failed-confirmation-edit");
+ await page.screenshot({ path: join(directory, "fixed-recovered.png") });
+ });
+ await record("actual session revocation requires login while running and after restart", async () => {
+ await control("healthy", true);
+ await syncNow();
+ await expect(page.locator('input[autocomplete="current-password"]')).toBeVisible({ timeout: 30_000 });
+ assert.equal(await credential(), "");
+ await close();
+ await launch(fixedExecutable);
+ await expect(page.locator('input[autocomplete="current-password"]')).toBeVisible({ timeout: 30_000 });
+ assert.equal(await credential(), "");
+ await page.locator('input[autocomplete="username"]').fill("admin");
+ await page.locator('input[autocomplete="current-password"]').fill("offline-test-password-only");
+ await page.locator('button[type="submit"]').click();
+ await open(memo);
+ await expect(page.locator('.ProseMirror[contenteditable="true"]')).toContainText("failed-confirmation-edit");
+ observations.localDataPreservedAfterReauthentication = true;
+ await close();
+ });
+} catch (error) {
+ if (page) {
+ console.error(await page.locator("body").innerText().catch(() => "No renderer"));
+ await page.screenshot({ path: join(directory, "failure.png") }).catch(() => {});
+ }
+ results.push({ ok: false, error: error.stack });
+ process.exitCode = 1;
+ console.error(error);
+} finally {
+ await close().catch(() => {});
+ server.stdin.end();
+ await writeFile(join(directory, "results.json"), JSON.stringify({ directory, runtimes, observations, results }, null, 2));
+ console.log(`Evidence: ${directory}`);
+}