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): preserve title ordering after note edits (#750) (#754)

LuoQianhongc2e874587e7e
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index 2494edeb..867f8749 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -85,7 +85,7 @@ import {
resolveSelectionMoveTargetNotebookId,
} from "@/lib/app-helpers";
import { useBrowserBackLayer } from "@/lib/app-hooks";
-import { updateMemoSummaryInLists } from "@/lib/memo-list-cache";
+import { sortDesktopTitleMemoSummaries, updateMemoSummaryInLists } from "@/lib/memo-list-cache";
import {
cacheMemoDetail,
evictIdleMemoDetails,
@@ -1152,8 +1152,11 @@ export const WorkspaceApp = ({
}
}
- return Array.from(memoMap.values());
- }, [memosQuery.data?.pages, mobileEditorReturnPreview]);
+ const loadedMemos = Array.from(memoMap.values());
+ return window.edgeeverDesktop?.isAvailable && (memoSortMode === "title-asc" || memoSortMode === "title-desc")
+ ? sortDesktopTitleMemoSummaries(loadedMemos, memoSortMode)
+ : loadedMemos;
+ }, [memosQuery.data?.pages, mobileEditorReturnPreview, memoSortMode]);
const totalMemoCount = memosQuery.data?.pages[0]?.totalCount ?? memos.length;
const handleLoadMoreMemos = useCallback(() => {
if (!memosQuery.hasNextPage || memosQuery.isFetchingNextPage) {
diff --git a/apps/web/src/lib/memo-list-cache.ts b/apps/web/src/lib/memo-list-cache.ts
index 820b82bf..262c6bc6 100644
--- a/apps/web/src/lib/memo-list-cache.ts
+++ b/apps/web/src/lib/memo-list-cache.ts
@@ -1,5 +1,6 @@
import type { QueryClient } from "@tanstack/react-query";
import { DEFAULT_MEMO_TITLE, type MemoSummary } from "@edgeever/shared";
+import { isNativeDesktopRuntime } from "./runtime";
export type MemoListQueryData = {
pages: Array<{
@@ -55,8 +56,44 @@ const memoMatchesStaticListConstraints = (memo: MemoSummary, queryKey: readonly
const hasSearchConstraint = (queryKey: readonly unknown[]) =>
typeof queryKey[3] === "string" && queryKey[3].trim().length > 0;
+// SQLite UTF-8 text follows scalar order, unlike UTF-16 for astral characters.
+// NOCASE additionally folds ASCII case and stops at NUL before comparing lengths.
+const compareDesktopText = (left: string, right: string, noCase = false) => {
+ let leftIndex = 0;
+ let rightIndex = 0;
+ while (leftIndex < left.length && rightIndex < right.length) {
+ const leftCode = left.codePointAt(leftIndex)!;
+ const rightCode = right.codePointAt(rightIndex)!;
+ const leftFolded = noCase && leftCode >= 65 && leftCode <= 90 ? leftCode + 32 : leftCode;
+ const rightFolded = noCase && rightCode >= 65 && rightCode <= 90 ? rightCode + 32 : rightCode;
+ if (leftFolded !== rightFolded) return leftFolded - rightFolded;
+ if (noCase && leftCode === 0) {
+ // SQLite NOCASE stops at NUL, then compares the original UTF-8 lengths.
+ const encoder = new TextEncoder();
+ return encoder.encode(left).length - encoder.encode(right).length;
+ }
+ leftIndex += leftCode > 0xffff ? 2 : 1;
+ rightIndex += rightCode > 0xffff ? 2 : 1;
+ }
+ return left.length - right.length;
+};
+
+const compareDesktopTitleMemoSummaries = (left: MemoSummary, right: MemoSummary, sortMode: "title-asc" | "title-desc") => {
+ const direction = sortMode === "title-desc" ? -1 : 1;
+ const titleCompare = compareDesktopText(left.title ?? left.excerpt, right.title ?? right.excerpt, true);
+ if (titleCompare !== 0) return titleCompare * direction;
+ if (left.updatedAt !== right.updatedAt) return left.updatedAt > right.updatedAt ? -1 : 1;
+ return compareDesktopText(right.id, left.id);
+};
+
+export const sortDesktopTitleMemoSummaries = (memos: MemoSummary[], sortMode: "title-asc" | "title-desc") =>
+ [...memos].sort((left, right) => compareDesktopTitleMemoSummaries(left, right, sortMode));
+
const sortMemoSummariesForList = (memos: MemoSummary[], queryKey: readonly unknown[]) => {
const sortMode = queryKey[5];
+ if ((sortMode === "title-asc" || sortMode === "title-desc") && isNativeDesktopRuntime()) {
+ return sortDesktopTitleMemoSummaries(memos, sortMode);
+ }
const sorted = [...memos];
if (sortMode === "title-asc" || sortMode === "title-desc") {
@@ -112,6 +149,40 @@ const reflowMemoListPages = (current: MemoListQueryData, memos: MemoSummary[], t
};
};
+const rewindDesktopTitleCursor = (
+ next: MemoListQueryData,
+ before: MemoSummary[],
+ queryKey: readonly unknown[],
+ replacement: (memo: MemoSummary) => MemoSummary | null,
+) => {
+ const sortMode = queryKey[5];
+ if (!isNativeDesktopRuntime() || (sortMode !== "title-asc" && sortMode !== "title-desc")) return next;
+ const cursor = next.pages.at(-1)?.nextCursor;
+ const offset = Number(cursor);
+ if (cursor == null || !Number.isSafeInteger(offset) || offset <= 0) return next;
+
+ // The offset marks a conservative source prefix. Cached tail notes beyond
+ // it must not rewind it again on each subsequent title edit.
+ const prefix = sortDesktopTitleMemoSummaries(deduplicateMemoSummaries(before), sortMode).slice(0, offset);
+ const boundary = prefix.at(-1);
+ if (!boundary) return next;
+ const seen = new Set<string>();
+ let removed = 0;
+ for (const previous of prefix) {
+ const memo = replacement(previous);
+ if (!memo || seen.has(memo.id)) { removed++; continue; }
+ seen.add(memo.id);
+ if (compareDesktopTitleMemoSummaries(memo, boundary, sortMode) > 0) removed++;
+ }
+ if (!removed) return next;
+ return {
+ ...next,
+ pages: next.pages.map((page, index) => index === next.pages.length - 1
+ ? { ...page, nextCursor: String(Math.max(0, offset - removed)) }
+ : page),
+ };
+};
+
export const remapMemoIdsInLists = (
queryClient: QueryClient,
memoIdMappings: ReadonlyMap<string, string>,
@@ -148,7 +219,13 @@ export const remapMemoIdsInLists = (
queryClient.setQueryData(
queryKey,
- reflowMemoListPages(current, sortMemoSummariesForList(nextMemos, queryKey), totalCount),
+ rewindDesktopTitleCursor(
+ reflowMemoListPages(current, sortMemoSummariesForList(nextMemos, queryKey), totalCount),
+ flatMemos, queryKey, memo => {
+ const id = memoIdMappings.get(memo.id);
+ return id && id !== memo.id ? { ...memo, id } : memo;
+ },
+ ),
);
}
};
@@ -160,17 +237,21 @@ export const updateMemoSummaryInLists = (queryClient: QueryClient, summary: Memo
}
const flatMemos = current.pages.flatMap((page) => page.memos);
- const memoExists = flatMemos.some((item) => item.id === summary.id);
+ const existingMemo = flatMemos.find((item) => item.id === summary.id);
const matchesStaticConstraints = memoMatchesStaticListConstraints(summary, queryKey);
const currentTotalCount = current.pages[0]?.totalCount ?? flatMemos.length;
- if (memoExists) {
+ if (existingMemo) {
const nextMemos = matchesStaticConstraints
? deduplicateMemoSummaries(flatMemos.map((item) => (item.id === summary.id ? { ...item, ...summary } : item)))
: deduplicateMemoSummaries(flatMemos.filter((item) => item.id !== summary.id));
const totalCount = matchesStaticConstraints ? currentTotalCount : Math.max(0, currentTotalCount - 1);
- queryClient.setQueryData(queryKey, reflowMemoListPages(current, sortMemoSummariesForList(nextMemos, queryKey), totalCount));
+ const next = reflowMemoListPages(current, sortMemoSummariesForList(nextMemos, queryKey), totalCount);
+ const titleChanged = (existingMemo.title ?? existingMemo.excerpt) !== (summary.title ?? summary.excerpt);
+ queryClient.setQueryData(queryKey, titleChanged || summary.updatedAt < existingMemo.updatedAt || !matchesStaticConstraints
+ ? rewindDesktopTitleCursor(next, flatMemos, queryKey, memo => memo.id === summary.id ? (matchesStaticConstraints ? summary : null) : memo)
+ : next);
continue;
}
@@ -181,14 +262,20 @@ export const updateMemoSummaryInLists = (queryClient: QueryClient, summary: Memo
}
const [firstPage, ...restPages] = current.pages;
+ const sortAcrossLoadedPages = isNativeDesktopRuntime() && restPages.length > 0
+ && (queryKey[5] === "title-asc" || queryKey[5] === "title-desc");
+ const firstPageMemos = deduplicateMemoSummaries([summary, ...(firstPage?.memos ?? [])]);
const nextFirstPage = firstPage
? {
...firstPage,
- memos: sortMemoSummariesForList(deduplicateMemoSummaries([summary, ...firstPage.memos]), queryKey),
+ memos: sortAcrossLoadedPages ? firstPageMemos : sortMemoSummariesForList(firstPageMemos, queryKey),
totalCount: firstPage.totalCount + 1,
}
: { memos: [summary], totalCount: 1, nextCursor: null };
- queryClient.setQueryData(queryKey, { ...current, pages: [nextFirstPage, ...restPages] });
+ const next = { ...current, pages: [nextFirstPage, ...restPages] };
+ queryClient.setQueryData(queryKey, sortAcrossLoadedPages
+ ? reflowMemoListPages(next, sortMemoSummariesForList(deduplicateMemoSummaries([summary, ...flatMemos]), queryKey), nextFirstPage.totalCount)
+ : next);
}
};
diff --git a/docs/changes/2026-11-01-memo-sort-after-save.md b/docs/changes/2026-11-01-memo-sort-after-save.md
new file mode 100644
index 00000000..d33ef13f
--- /dev/null
+++ b/docs/changes/2026-11-01-memo-sort-after-save.md
@@ -0,0 +1,41 @@
+# Keep note ordering after editing
+
+[简体中文](2026-11-01-memo-sort-after-save.zh-CN.md) · [Issue #750](https://github.com/tianma-if/edgeever/issues/750)
+
+## Problem and outcome
+
+The report describes Windows v2.16.1 moving an edited note to the top of a notebook sorted by title A–Z. The desktop query uses SQLite `NOCASE`, whereas cache updates use Chinese locale comparison. An isolated source-level reproduction changes the order of distinct Chinese titles after a body-only edit. Confirm the actual behavior in the latest official desktop release before changing product code.
+
+## Allowed changes and acceptance
+
+1. Install the latest official macOS release on the available machine through the built-in updater or the official installer. Keep an official installer available for recovery. Use an isolated application profile and local test instance; do not edit or migrate the user's real notes. Reproduce title A–Z → edit body → return through the packaged application's UI and retain the relevant before/after evidence. Report Windows-specific verification separately.
+2. If reproduced, correct list updates so editing a body does not change the relative order of distinct, unchanged titles. Keep the active sort selection. Actual title changes, equal-title tie breaks, new notes and ID remapping must remain consistent with the ordering used by that list's repository. Cover title A–Z and Z–A and retain the existing created/updated ordering, filters, notebook/tag constraints, counts and pagination entry points.
+3. Do not introduce full-library reads, full-library client sorting, extra network calls on body-only saves, migrations, indexes or new dependencies. Work with the loaded list/cache or the existing bounded repository query. Compare the affected save/update work with the baseline using representative cached-list sizes, and verify page boundaries and query counts.
+4. Before implementation, extend the existing cache regression coverage to fail for the reproduced behavior. Verify the fixed edit-and-return flow in the desktop runtime, including a title change and a multi-page list. Reuse the existing focused tests and run `bun run typecheck`, `bun run typecheck:mobile` and `bun run build:web` once for the final candidate.
+
+## Boundaries, risk and recovery
+
+This change restores the selected list ordering; it does not redefine locale sorting, pinning priority or untitled-note display. Native Android/iOS clients, storage/authentication/synchronization mechanisms, installation/update mechanisms, server deployment, releases and version numbers remain unchanged. Keep unrelated sharing and backup behavior unchanged.
+
+The value is predictable navigation after editing. The main risk is disagreement between cache ordering and repository pagination, causing misplaced or duplicated visible notes. Keep query parameter formats and paged-loading entry points intact and verify the loaded page boundary. Roll back the affected list-update code if needed; no data migration is planned. The retained official installer can reinstall v2.16.1 if application recovery is needed. Windows and other unavailable platforms require their own runtime verification.
+
+## Implementation decisions and completion
+
+The installed official v2.16.1 reproduces the defect: `中文笔记 → 笔记整理 → 阿尔法` changes to `阿尔法 → 笔记整理 → 中文笔记` after a body-only save. The title is unchanged. See the before/after screenshots in [evidence](evidence/2026-11-01-memo-sort-after-save/).
+
+Keep the existing repository's ordering authoritative. Desktop title-cache ordering will match the sidecar's SQLite `COALESCE(title, excerpt) COLLATE NOCASE`, then descending update timestamp and ID. SQLite folds ASCII case only; do not substitute language-aware ordering or trim/fallback rules that differ from the query. Browser cache behavior and the sidecar query remain unchanged. Only already-loaded summaries are sorted, as before; no additional repository/network request or full-library read is introduced. This avoids changing indexed queries, pagination or desktop native code to repair a renderer-cache mismatch.
+
+The ID tie break must also use SQLite's UTF-8 binary ordering: restored memo IDs accept non-ASCII strings, whose UTF-16 JavaScript ordering can differ. Share the scalar comparison implementation between binary IDs and ASCII-case-insensitive titles without changing accepted inputs. For a newly seen note in a multi-page desktop title list, order it with all loaded pages, not just the first page. Preserve the existing extra insertion slot in the first page so the newly created/selected note stays in the cache, retain page parameters, and update cached totals consistently. Do not discard notes or eagerly fetch unloaded pages; existing overlapping-page deduplication remains in use.
+
+Newly fetched pages can arrive after a cached title edit/insertion, bypassing the cache-update helper. Apply the same desktop title sorter to the already-loaded, deduplicated display list so the following page cannot reintroduce an out-of-order edited note. This changes only the desktop title-list projection in `WorkspaceApp`; other browser/sort projections remain unchanged. It adds no data read and does not sort unloaded notes.
+
+Always preserving offset cursors was superseded by a real pagination counterexample: changing a prefix note's title to sort last can make the next offset skip the following source note entirely. For desktop title lists only, move the last-page offset back for prefix entries removed, deduplicated or sorted beyond the previous prefix boundary by a title edit, backdated update timestamp or ID remap. Infer the conservative prefix from that offset, so repeatedly editing a note already outside it does not keep rewinding. Ordinary body saves with nondecreasing timestamps and changes within the prefix keep the cursor; other cursors/page parameters remain unchanged. The next ordinary page load fills the gap with bounded overlap; do not trigger a fetch, retry, count or full-library scan. The overlap can require an additional bounded page when the source ends exactly on a page boundary. The 100-note/50-note-page regression fetches 51 remaining rows in two pages, versus 50 in one without the edit; repeated edits of the same outlier do not add more overlap.
+
+## Completion check
+
+- Official v2.16.1 was installed through the existing updater and reproduced the edit-body → upper-left Back flow in an isolated macOS profile. The original reproduction screenshots and official installer remain available.
+- Desktop title order now matches SQLite `NOCASE` plus UTF-8 binary ID ties, including non-ASCII restored IDs. Cached insertion orders all loaded pages. Cache updates and the loaded-list display share one sorter, so subsequent pages cannot reintroduce an out-of-order edited note. Conditional offset overlap prevents skipped source rows after a prefix note moves out through renaming, backdated timestamps or ID remapping; repeated edits outside the prefix do not keep rewinding. No input limit, proxy/retry/fallback, immediate data request, migration or dependency was added.
+- All **27** focused cache/runtime tests pass, with SQLite executing the actual sidecar ORDER BY as the oracle. Tests that exposed the review findings failed before their corresponding repairs. Coverage includes both directions, title fallback/NUL/Unicode, equal-title timestamp and ID ties, insertion, remapping, active-cache updates without query-function calls, and loading through to the complete source after cursor repair. Final Web type checking and the desktop Web build pass. Web/mobile type checks and the desktop Web build also passed on the isolated PR branch based on current upstream `main`.
+- Original A–Z/Z–A body-edit, rename and 120-note loaded-page evidence remains applicable to those inputs. A final native macOS candidate using Electron 44.7 and the unchanged official sidecar also exercised the newly found failure: rename a first-page note to sort near the end, then continue scrolling. The completed list showed **123 / 123** fixture notes rather than losing a source row; see [the final pagination screenshot](evidence/2026-11-01-memo-sort-after-save/fixed-cursor-after-next-page.png). All operations used the isolated local fixture, not the user's Cloudflare data.
+- The final local microbenchmark includes cache update plus the loaded-list Map/display projection, 20% duplicate titles, increasing save timestamps, 50-summary pages, 10 warm-ups and 100 samples. For 5,000 loaded summaries, median body-update/projection time was **6.704 → 1.101 ms**; new insertion/projection took **2.977 ms**. This excludes React rendering, native/database/network work and production latency. The full series is in [performance evidence](evidence/2026-11-01-memo-sort-after-save/performance.json). Normal body saves add no cursor work or data read. A moved-out prefix member adds bounded overlap to the next ordinary page, not an immediate read or per-page full scan.
+- Correctness, simplification and design-fit review of the final affected paths has no unresolved substantive finding within this scope. One comparison implementation serves both cache and display; no additional sorting algorithm or data source was introduced. The product diff is limited to `memo-list-cache.ts` and the desktop-title projection in `WorkspaceApp.tsx`; tests/documentation/evidence cover that change. Sharing and backup behavior remain unchanged. Release/installer validation is outside this source change; Windows-specific UI verification requires a Windows environment.
diff --git a/docs/changes/2026-11-01-memo-sort-after-save.zh-CN.md b/docs/changes/2026-11-01-memo-sort-after-save.zh-CN.md
new file mode 100644
index 00000000..4e384886
--- /dev/null
+++ b/docs/changes/2026-11-01-memo-sort-after-save.zh-CN.md
@@ -0,0 +1,41 @@
+# 编辑笔记后保持列表排序
+
+[English](2026-11-01-memo-sort-after-save.md) · [Issue #750](https://github.com/tianma-if/edgeever/issues/750)
+
+## 问题与目标
+
+反馈描述 Windows v2.16.1 在笔记本选择标题 A–Z 后,编辑的笔记会跳到首位。桌面查询使用 SQLite `NOCASE`,缓存更新使用中文区域比较;源码级隔离复现已出现仅修改正文就改变不同中文标题顺序的现象。修改产品代码前,先在最新官方桌面版确认实际行为。
+
+## 允许变更与验收
+
+1. 在现有机器通过应用内更新或官方安装包安装最新 macOS 正式版,保留官方安装包作为恢复来源。使用独立应用配置和本地测试实例,不编辑或迁移用户真实笔记。通过安装包的界面复现“标题 A–Z → 修改正文 → 返回”,保留必要的前后证据;Windows 专属验证单独说明。
+2. 确认复现后,修复列表更新:仅修改正文时,不改变不同且未改名的标题之间的相对顺序,并保留当前排序选项。实际改名、同名次序、新建笔记和 ID 映射应与该列表的数据仓库排序保持一致。覆盖标题 A–Z、Z–A,保留创建/更新时间排序、筛选、笔记本/标签约束、数量和分页入口。
+3. 不增加全库读取、客户端全库排序、正文保存时的额外网络请求、迁移、索引或新依赖。只处理已加载的列表/缓存,或复用现有有界查询。用代表性的缓存列表规模比较保存/更新开销,核对分页边界和查询次数。
+4. 实现前扩展现有缓存回归用例,使其能暴露已复现的缺陷。修复后在桌面运行时验证编辑返回、改名和跨页列表;复用相关测试,并对最终候选执行一次 `bun run typecheck`、`bun run typecheck:mobile`、`bun run build:web`。
+
+## 保持不变的边界、风险与恢复
+
+本次恢复已选列表排序,不重新定义语言排序、置顶优先级或无标题笔记的展示。原生 Android/iOS 客户端、存储/认证/同步机制、安装/升级机制、服务端部署、Release 和版本号均不变。分享及备份等无关行为保持不变。
+
+功能价值是编辑后仍能按预期定位笔记。主要风险是缓存顺序与仓库分页不一致,导致位置错误或重复展示;保持查询参数格式和分页入口,并验证已加载页面交界。需要回滚时撤回列表更新代码,不计划迁移数据;需要恢复应用时,可用保留的官方安装包重装 v2.16.1。Windows 等不可用平台仍需各自运行验证。
+
+## 实施决策与完成核对
+
+已安装的官方 v2.16.1 复现了缺陷:仅保存正文后,`中文笔记 → 笔记整理 → 阿尔法` 变成 `阿尔法 → 笔记整理 → 中文笔记`,标题未改动。前后截图见[验收证据](evidence/2026-11-01-memo-sort-after-save/)。
+
+以现有仓库排序为准。桌面标题缓存排序对齐 sidecar 的 SQLite `COALESCE(title, excerpt) COLLATE NOCASE`,再按更新时间和 ID 降序排列。SQLite 只折叠 ASCII 大小写,不替换成语言排序,也不套用与查询不同的去空白或回退规则。浏览器缓存行为和 sidecar 查询保持不变;和原来一样只排序已加载摘要,不增加仓库/网络请求或全库读取。这样无需为渲染缓存不一致而改变索引查询、分页或桌面原生代码。
+
+ID 次序也须使用 SQLite 的 UTF-8 二进制顺序:恢复笔记允许非 ASCII ID,JavaScript 的 UTF-16 顺序可能不同。标题和 ID 共用码点比较实现,分别保留 ASCII 忽略大小写和二进制语义,不改变可接受的输入。桌面标题列表插入未见过的笔记时,应与所有已加载页面一起排序,而非只排序首页。保留既有的首页新增一个位置,使新建/已选笔记仍留在缓存,保留分页参数,并一致更新缓存数量。不丢弃笔记、不主动读取未加载页面,继续使用原有的重叠页去重。
+
+缓存中的标题编辑/插入之后,继续加载的页面不会经过缓存更新辅助函数。展示列表须在已加载、去重的摘要上复用同一个桌面标题排序器,避免续页又把已编辑笔记显示到错误位置。仅改变 `WorkspaceApp` 的桌面标题列表投影,浏览器及其他排序的投影不变;不增加读取,不排序未加载笔记。
+
+“始终保留 offset 游标”的原决定已被真实分页反例替代:已知前缀中的笔记改名后排到末尾,旧 offset 会直接跳过下一条源笔记。仅对桌面标题列表,当标题编辑、回退的更新时间或 ID 映射使前缀成员被移除、去重或移到原前缀边界之后时,向前回退最后一页的 offset。用该 offset 推断保守的已知前缀,避免反复编辑已在前缀外的同一笔记时持续回退。更新时间不回退的普通正文保存、以及仍在前缀内的变化保留游标,其他游标和分页参数不变。下一次正常翻页用有界重叠补齐缺口;不主动发起读取、重试、计数或全库扫描。源记录数恰好落在整页边界时,重叠可能需要额外一页:100 条记录、每页 50 条的回归中,改名前剩余 50 条/1 页,修复后读取 51 条/2 页,只有 1 条重叠;同一前缀外笔记反复改名不会继续增加重叠。
+
+## 完成核对
+
+- 已通过现有应用内更新安装官方 v2.16.1,并在独立 macOS 配置中复现“修改正文 → 左上角返回列表”;原始复现截图和官方恢复安装包继续保留。
+- 桌面标题顺序对齐 SQLite `NOCASE` 及 UTF-8 二进制 ID 次序,覆盖恢复笔记的非 ASCII ID。插入笔记时排序所有已加载页面;缓存更新和列表展示共用同一排序器,防止续页再次把已编辑笔记放错位置。当前缀笔记因改名、更新时间回退或 ID 映射移出前缀时,通过有条件的 offset 重叠防止遗漏源记录;反复编辑已在前缀外的笔记不会持续回退。未新增输入限制、代理/重试/fallback、立即读取、迁移或依赖。
+- **27 项**缓存/运行时相关测试全部通过,以实际 sidecar ORDER BY 在 SQLite 中执行的结果为准。本轮发现对应的回归用例在相应修复前均已暴露问题。覆盖双向排序、标题回退/NUL/Unicode、同名更新时间与 ID 次序、插入、映射、活动缓存更新不调用查询函数,以及修正游标后继续加载直至完整源记录。最终 Web 类型检查和桌面 Web 构建通过;基于当前上游 `main` 的独立 PR 分支也通过了 Web/移动端类型检查及桌面 Web 构建。
+- 原有 A–Z/Z–A 正文编辑、改名及 120 条笔记跨页证据对原输入仍有效。另用 Electron 44.7 和未修改的官方 sidecar 运行最终 macOS 原生候选,验证本轮发现的路径:将首页笔记改名到接近末尾后继续滚动,最终完整显示 **123 / 123** 条测试笔记,不再漏掉源记录;见[最终分页截图](evidence/2026-11-01-memo-sort-after-save/fixed-cursor-after-next-page.png)。所有操作均在隔离的本地测试实例中完成,未操作用户 Cloudflare 数据。
+- 最终本地微基准包含缓存更新及已加载列表的 Map/展示投影,使用 20% 同名标题、递增的保存时间、每页 50 条、预热 10 次、计时 100 次。5,000 条已加载摘要的正文更新/展示处理中位耗时 **6.704 → 1.101 ms**,新笔记插入/展示为 **2.977 ms**。结果不含 React 绘制、原生/数据库/网络工作,也不是生产延迟;完整系列见[性能证据](evidence/2026-11-01-memo-sort-after-save/performance.json)。普通正文保存不增加游标工作或读取;移出前缀只让下一次正常分页产生有界重叠,不立即读取或逐页全库扫描。
+- 最终受影响路径的正确性、简化和设计适配性审查无范围内待处理的实质问题。缓存和展示共用比较实现,未增加另一套排序算法或数据来源。产品 diff 仅涉及 `memo-list-cache.ts` 及 `WorkspaceApp.tsx` 的桌面标题列表投影,测试/文档/证据验证对应行为;分享和备份行为保持不变。Release/安装器验证不属于此次源码改动,Windows 专属界面验证待具备对应环境后完成。
diff --git a/docs/changes/evidence/2026-11-01-memo-sort-after-save/fixed-after-return.png b/docs/changes/evidence/2026-11-01-memo-sort-after-save/fixed-after-return.png
new file mode 100644
index 00000000..40b743de
Binary files /dev/null and b/docs/changes/evidence/2026-11-01-memo-sort-after-save/fixed-after-return.png differ
diff --git a/docs/changes/evidence/2026-11-01-memo-sort-after-save/fixed-cursor-after-next-page.png b/docs/changes/evidence/2026-11-01-memo-sort-after-save/fixed-cursor-after-next-page.png
new file mode 100644
index 00000000..57350424
Binary files /dev/null and b/docs/changes/evidence/2026-11-01-memo-sort-after-save/fixed-cursor-after-next-page.png differ
diff --git a/docs/changes/evidence/2026-11-01-memo-sort-after-save/fixed-paging-after-return.png b/docs/changes/evidence/2026-11-01-memo-sort-after-save/fixed-paging-after-return.png
new file mode 100644
index 00000000..b0258edc
Binary files /dev/null and b/docs/changes/evidence/2026-11-01-memo-sort-after-save/fixed-paging-after-return.png differ
diff --git a/docs/changes/evidence/2026-11-01-memo-sort-after-save/performance.json b/docs/changes/evidence/2026-11-01-memo-sort-after-save/performance.json
new file mode 100644
index 00000000..c0e1de6d
--- /dev/null
+++ b/docs/changes/evidence/2026-11-01-memo-sort-after-save/performance.json
@@ -0,0 +1,38 @@
+{
+ "kind": "Local cache update plus loaded-summary display projection microbenchmark; excludes React/native/database/network work",
+ "runtime": "1.3.14",
+ "additionalQueries": 0,
+ "cacheAndDisplayProjection": {
+ "kind": "Local cache update plus loaded-list Map projection and desktop title sorter; excludes React render, native/DB/network work",
+ "runtime": "1.3.14",
+ "warmups": 10,
+ "samples": 100,
+ "results": [
+ {
+ "loadedSummaries": 50,
+ "pageSize": 50,
+ "duplicateTitleFraction": 0.2,
+ "samples": 100,
+ "baselineCacheAndProjectionMedianMs": 0.076,
+ "fixedCacheAndProjectionMedianMs": 0.022
+ },
+ {
+ "loadedSummaries": 500,
+ "pageSize": 50,
+ "duplicateTitleFraction": 0.2,
+ "samples": 100,
+ "baselineCacheAndProjectionMedianMs": 0.65,
+ "fixedCacheAndProjectionMedianMs": 0.111
+ },
+ {
+ "loadedSummaries": 5000,
+ "pageSize": 50,
+ "duplicateTitleFraction": 0.2,
+ "samples": 100,
+ "baselineCacheAndProjectionMedianMs": 6.704,
+ "fixedCacheAndProjectionMedianMs": 1.101,
+ "newInsertionAndProjectionMedianMs": 2.977
+ }
+ ]
+ }
+}
diff --git a/docs/changes/evidence/2026-11-01-memo-sort-after-save/release-after-return.png b/docs/changes/evidence/2026-11-01-memo-sort-after-save/release-after-return.png
new file mode 100644
index 00000000..1ce134c9
Binary files /dev/null and b/docs/changes/evidence/2026-11-01-memo-sort-after-save/release-after-return.png differ
diff --git a/docs/changes/evidence/2026-11-01-memo-sort-after-save/release-before-return-flow.png b/docs/changes/evidence/2026-11-01-memo-sort-after-save/release-before-return-flow.png
new file mode 100644
index 00000000..bbcbe046
Binary files /dev/null and b/docs/changes/evidence/2026-11-01-memo-sort-after-save/release-before-return-flow.png differ
diff --git a/docs/changes/evidence/2026-11-01-memo-sort-after-save/results.json b/docs/changes/evidence/2026-11-01-memo-sort-after-save/results.json
new file mode 100644
index 00000000..c2a7cc7f
--- /dev/null
+++ b/docs/changes/evidence/2026-11-01-memo-sort-after-save/results.json
@@ -0,0 +1,118 @@
+{
+ "issue": 750,
+ "releaseReproduction": {
+ "version": "2.16.1",
+ "platform": "macOS arm64",
+ "runtime": "official installed application and bundled renderer",
+ "setup": "isolated profile and loopback-only test server",
+ "sort": "title-asc",
+ "titleChanged": false,
+ "action": "edit body, click upper-left Back to list",
+ "before": [
+ "中文笔记",
+ "笔记整理",
+ "阿尔法"
+ ],
+ "after": [
+ "阿尔法",
+ "笔记整理",
+ "中文笔记"
+ ],
+ "screenshots": [
+ "release-before-return-flow.png",
+ "release-after-return.png"
+ ]
+ },
+ "fixedVerification": {
+ "runtime": "same official executable and native sidecar, with locally built desktop renderer through the existing development URL override",
+ "titleAscBodyEdit": [
+ "中文笔记",
+ "笔记整理",
+ "阿尔法"
+ ],
+ "titleRename": [
+ "A renamed note",
+ "中文笔记",
+ "笔记整理"
+ ],
+ "titleDescBodyEdit": [
+ "笔记整理",
+ "中文笔记",
+ "A renamed note"
+ ],
+ "paging": {
+ "totalNotes": 120,
+ "pageSize": 50,
+ "loadedBeforeEdit": 100,
+ "editedTitle": "笔记整理 015",
+ "editedOneBasedIndex": 56,
+ "after": "Edited note remains between 笔记整理 014 and 笔记整理 016; normal pagination can continue to the final page."
+ },
+ "screenshots": [
+ "fixed-after-return.png",
+ "fixed-paging-after-return.png"
+ ]
+ },
+ "automated": {
+ "focusedTests": 27,
+ "failures": 0,
+ "webTypecheck": "passed",
+ "mobileTypecheck": "passed",
+ "desktopWebBuild": "passed",
+ "newDesktopOrderingTestsFailedBeforeFix": 5,
+ "reviewRegressionFailuresBeforeRepairs": {
+ "loadedInsertionAndUnicodeIds": 4,
+ "cursorMovement": 4,
+ "backdatedUpdateTimestamp": 2
+ },
+ "mobileTypecheckEvidence": "passed again on the isolated PR branch"
+ },
+ "completionReview": {
+ "date": "2026-11-02",
+ "productFiles": [
+ "apps/web/src/lib/memo-list-cache.ts",
+ "apps/web/src/components/WorkspaceApp.tsx"
+ ],
+ "fixed": [
+ "SQLite binary non-ASCII ID ties",
+ "insertion order across loaded pages",
+ "display order after a following page arrives",
+ "offset holes after rename, ID remap or backdated update time"
+ ],
+ "cursorRepeatedOutlierEdit": "no repeated rewind",
+ "ordinaryBodySaveAdditionalQueries": 0,
+ "unresolvedSubstantiveFindingsInReviewedScope": 0,
+ "nativeCandidate": {
+ "platform": "macOS arm64",
+ "engine": "Electron 44.7.0",
+ "sidecar": "unchanged installed official sidecar",
+ "profileAndServer": "isolated loopback fixture",
+ "scenario": "rename a prefix note to a late title, then scroll through all pages",
+ "sourceNotes": 123,
+ "loadedUniqueNotes": 123,
+ "screenshot": "fixed-cursor-after-next-page.png"
+ },
+ "performance": "performance.json / cacheAndDisplayProjection",
+ "boundedOverlapRegression": {
+ "sourceNotes": 100,
+ "pageSize": 50,
+ "remainingRowsWithoutEdit": 50,
+ "remainingPagesWithoutEdit": 1,
+ "remainingRowsAfterOutlierEdit": 51,
+ "remainingPagesAfterOutlierEdit": 2,
+ "repeatedOutlierRenameAddsOverlap": false
+ }
+ },
+ "validationLimitations": {
+ "windowsRuntimeVerified": false,
+ "candidateDesktopRenderer": "locally built, not a published release"
+ },
+ "submissionValidation": {
+ "upstreamBase": "feff718afa08d8dfed5c05e85d6287d87f4e0a08",
+ "isolatedFromUnrelatedChanges": true,
+ "focusedTests": 27,
+ "webTypecheck": "passed",
+ "mobileTypecheck": "passed",
+ "desktopWebBuild": "passed"
+ }
+}
diff --git a/tests/web-memo-list-cache.test.ts b/tests/web-memo-list-cache.test.ts
index 2b27c6a6..80c0fd4e 100644
--- a/tests/web-memo-list-cache.test.ts
+++ b/tests/web-memo-list-cache.test.ts
@@ -1,7 +1,9 @@
-import { describe, expect, test } from "bun:test";
-import { QueryClient } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { Database } from "bun:sqlite";
+import { readFileSync } from "node:fs";
+import { QueryClient, QueryObserver } from "@tanstack/react-query";
import type { MemoSummary } from "@edgeever/shared";
-import { remapMemoIdsInLists, updateMemoSummaryInLists, type MemoListQueryData } from "../apps/web/src/lib/memo-list-cache";
+import { remapMemoIdsInLists, sortDesktopTitleMemoSummaries, updateMemoSummaryInLists, type MemoListQueryData } from "../apps/web/src/lib/memo-list-cache";
const memo = (overrides: Partial<MemoSummary> = {}): MemoSummary => ({
id: "memo-apple",
@@ -105,3 +107,231 @@ describe("memo list cache updates", () => {
expect(cached?.pages[0]?.totalCount).toBe(0);
});
});
+
+describe("desktop title list cache ordering (#750)", () => {
+ const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
+ const sidecarSource = readFileSync(new URL("../crates/desktop-sidecar/src/memo.rs", import.meta.url), "utf8");
+
+ beforeEach(() => {
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: { edgeeverDesktop: { isAvailable: true } },
+ });
+ });
+
+ afterEach(() => {
+ if (originalWindow) Object.defineProperty(globalThis, "window", originalWindow);
+ else Reflect.deleteProperty(globalThis, "window");
+ });
+
+ // Use the actual sidecar ORDER BY as the oracle, including its title fallback
+ // and tie breaks, rather than copying the renderer's comparator into tests.
+ const desktopOrder = (memos: MemoSummary[], sort: "title-asc" | "title-desc") => {
+ const order = sidecarSource.match(new RegExp(`Some\\("${sort}"\\) => \\{\\s*"([^"]+)"`))?.[1];
+ expect(order).toBeDefined();
+ const database = new Database(":memory:");
+ try {
+ database.exec("CREATE TABLE memos (id TEXT, title TEXT, excerpt TEXT, updated_at TEXT)");
+ const insert = database.prepare("INSERT INTO memos VALUES (?, ?, ?, ?)");
+ for (const item of memos) insert.run(item.id, item.title, item.excerpt, item.updatedAt);
+ const byId = new Map(memos.map((item) => [item.id, item]));
+ return database.query<{ id: string }, []>(`SELECT m.id FROM memos m ORDER BY ${order}`).all()
+ .map((row) => byId.get(row.id)!);
+ } finally {
+ database.close();
+ }
+ };
+
+ for (const sort of ["title-asc", "title-desc"] as const) {
+ test(`keeps distinct Chinese titles in sidecar order after a body-only save (${sort})`, () => {
+ const queryClient = new QueryClient();
+ const queryKey = ["memos", "notebook", "nb-inbox", "", "all", sort] as const;
+ const notes = ["中文笔记", "笔记整理", "阿尔法"].map((title, index) => memo({ id: `memo-${index}`, title }));
+ const ordered = desktopOrder(notes, sort);
+ queryClient.setQueryData(queryKey, queryData([ordered]));
+
+ updateMemoSummaryInLists(queryClient, { ...notes[2]!, excerpt: "Only the body changed", revision: 2, updatedAt: "2026-11-01T12:00:00.000Z" });
+
+ const cached = queryClient.getQueryData<MemoListQueryData>(queryKey)!;
+ expect(cached.pages[0]!.memos.map((item) => item.id)).toEqual(ordered.map((item) => item.id));
+ expect(cached.pages[0]!.memos.find((item) => item.id === "memo-2")?.excerpt).toBe("Only the body changed");
+ queryClient.clear();
+ });
+
+ test(`matches SQLite case, Unicode, empty titles and equal-title tie breaks (${sort})`, () => {
+ const queryClient = new QueryClient();
+ const queryKey = ["memos", "notebook", "nb-inbox", "", "all", sort] as const;
+ const notes = [null, "", " Alpha ", "alpha", "ALPHA", "Éclair", "éclair", "\uE000", "😀", "Alpha", "\0a", "\0b"].map((title, index) => memo({
+ id: `memo-${index}`, title, excerpt: `Excerpt ${index}`, isPinned: index === 6,
+ }));
+ const updated = { ...notes[3]!, updatedAt: "2026-11-01T12:00:00.000Z", revision: 2 };
+ queryClient.setQueryData(queryKey, queryData([desktopOrder(notes, sort)]));
+
+ updateMemoSummaryInLists(queryClient, updated);
+
+ expect(queryClient.getQueryData<MemoListQueryData>(queryKey)!.pages[0]!.memos.map((item) => item.id))
+ .toEqual(desktopOrder(notes.map((item) => item.id === updated.id ? updated : item), sort).map((item) => item.id));
+
+ const added = memo({ id: "new-note", title: "阿里" });
+ updateMemoSummaryInLists(queryClient, added);
+ expect(queryClient.getQueryData<MemoListQueryData>(queryKey)!.pages[0]!.memos.map((item) => item.id))
+ .toEqual(desktopOrder([...notes.map((item) => item.id === updated.id ? updated : item), added], sort).map((item) => item.id));
+ queryClient.clear();
+ });
+
+ test(`keeps SQLite binary ID ties for restored non-ASCII IDs (${sort})`, () => {
+ const queryClient = new QueryClient();
+ const queryKey = ["memos", "notebook", "nb-inbox", "", "all", sort] as const;
+ const notes = ["memo_\uE000", "memo_😀", "memo_a", "memo_A", "memo_a\0z"].map(id => memo({ id, title: "Same title" }));
+ queryClient.setQueryData(queryKey, queryData([desktopOrder(notes, sort)]));
+
+ updateMemoSummaryInLists(queryClient, { ...notes[0]!, revision: 2 });
+
+ expect(queryClient.getQueryData<MemoListQueryData>(queryKey)!.pages[0]!.memos.map(item => item.id))
+ .toEqual(desktopOrder(notes, sort).map(item => item.id));
+ remapMemoIdsInLists(queryClient, new Map([["memo_a", "memo_📝"]]));
+ expect(queryClient.getQueryData<MemoListQueryData>(queryKey)!.pages[0]!.memos.map(item => item.id))
+ .toEqual(desktopOrder(notes.map(item => item.id === "memo_a" ? { ...item, id: "memo_📝" } : item), sort).map(item => item.id));
+ queryClient.clear();
+ });
+
+ test(`inserts a new note in the order of all loaded pages without refetching (${sort})`, async () => {
+ const queryClient = new QueryClient();
+ const queryKey = ["memos", "notebook", "nb-inbox", "", "all", sort] as const;
+ const notes = Array.from({ length: 120 }, (_, index) => memo({ id: `memo-${index}`, title: `标题 ${String(index).padStart(3, "0")}` }));
+ const loaded = desktopOrder(notes, sort).slice(0, 100);
+ const data = queryData([loaded.slice(0, 50), loaded.slice(50)], 120);
+ data.pages[0]!.nextCursor = "50";
+ data.pages[1]!.nextCursor = "100";
+ data.pageParams = [null, "50"];
+ let reads = 0;
+ const observer = new QueryObserver(queryClient, {
+ queryKey, initialData: data, staleTime: Infinity,
+ queryFn: async () => { reads++; return data; },
+ });
+ const unsubscribe = observer.subscribe(() => {});
+ try {
+ const added = memo({ id: "memo-new", title: sort === "title-asc" ? "标题 075a" : "标题 045a" });
+ updateMemoSummaryInLists(queryClient, added);
+
+ const cached = queryClient.getQueryData<MemoListQueryData>(queryKey)!;
+ expect(cached.pages.flatMap(page => page.memos.map(item => item.id)))
+ .toEqual(desktopOrder([...loaded, added], sort).map(item => item.id));
+ expect(cached.pages.map(page => page.memos.length)).toEqual([51, 50]);
+ expect(cached.pages.map(page => page.totalCount)).toEqual([121, 121]);
+ expect(cached.pages.map(page => page.nextCursor)).toEqual(["50", "100"]);
+ expect(cached.pageParams).toEqual([null, "50"]);
+ await Promise.resolve();
+ expect(reads).toBe(0);
+ } finally { unsubscribe(); queryClient.clear(); }
+ });
+
+ test(`keeps an edited tail ordered when another page arrives (${sort})`, () => {
+ const notes = Array.from({ length: 120 }, (_, index) => memo({ id: `memo-${index}`, title: `标题 ${String(index).padStart(3, "0")}` }));
+ const ordered = desktopOrder(notes, sort);
+ const tail = { ...ordered[10]!, title: sort === "title-asc" ? "龥 changed tail" : "A changed tail" };
+ const changed = notes.map(item => item.id === tail.id ? tail : item);
+ const cached = sortDesktopTitleMemoSummaries(ordered.slice(0, 50).map(item => item.id === tail.id ? tail : item), sort);
+ const incoming = desktopOrder(changed, sort).slice(50, 100);
+ const displayed = [...new Map([...cached, ...incoming].map(item => [item.id, item])).values()];
+ const previousIds = displayed.map(item => item.id);
+
+ const sorted = sortDesktopTitleMemoSummaries(displayed, sort);
+
+ expect(sorted.map(item => item.id)).toEqual(desktopOrder(displayed, sort).map(item => item.id));
+ expect(sorted.at(-1)?.id).toBe(tail.id);
+ expect(displayed.map(item => item.id)).toEqual(previousIds);
+ expect(sorted).toHaveLength(displayed.length);
+ });
+
+ for (const mutation of ["rename", "remap", "older-timestamp"] as const) {
+ test(`does not skip a source note after a prefix ${mutation} sorts beyond the next-page cursor (${sort})`, () => {
+ const queryClient = new QueryClient();
+ const queryKey = ["memos", "notebook", "nb-inbox", "", "all", sort] as const;
+ let source = Array.from({ length: 100 }, (_, index) => memo({
+ id: `memo_${String(index).padStart(3, "0")}`,
+ title: mutation === "rename" ? `标题 ${String(index).padStart(3, "0")}` : "Same",
+ ...(mutation === "older-timestamp" ? { updatedAt: "2030-01-01T00:00:00.000Z" } : {}),
+ }));
+ const first = desktopOrder(source, sort).slice(0, 50);
+ const data = queryData([first], 100);
+ data.pages[0]!.nextCursor = "50";
+ queryClient.setQueryData(queryKey, data);
+ const selected = first[10]!;
+ const changed = mutation === "rename"
+ ? { ...selected, title: sort === "title-asc" ? "龥 tail" : "A tail" }
+ : mutation === "remap" ? { ...selected, id: "memo_000-a" }
+ : { ...selected, updatedAt: "2026-11-02T00:00:00.000Z", revision: 2 };
+ source = source.map(item => item.id === selected.id ? changed : item);
+ if (mutation === "remap") remapMemoIdsInLists(queryClient, new Map([[selected.id, changed.id]]));
+ else updateMemoSummaryInLists(queryClient, changed);
+
+ expect(queryClient.getQueryData<MemoListQueryData>(queryKey)!.pages.at(-1)!.nextCursor).toBe("49");
+ if (mutation === "rename") {
+ const changedAgain = { ...changed, title: `${changed.title}x`, revision: 3 };
+ updateMemoSummaryInLists(queryClient, changedAgain);
+ source = source.map(item => item.id === changed.id ? changedAgain : item);
+ expect(queryClient.getQueryData<MemoListQueryData>(queryKey)!.pages.at(-1)!.nextCursor).toBe("49");
+ }
+ const expected = desktopOrder(source, sort);
+ let loadedPages = 0;
+ let returnedRows = 0;
+ for (let page = 0; page < 3; page++) {
+ const current = queryClient.getQueryData<MemoListQueryData>(queryKey)!;
+ const cursor = current.pages.at(-1)!.nextCursor;
+ if (cursor === null) break;
+ const offset = Number(cursor);
+ const next = expected.slice(offset, offset + 50);
+ loadedPages++; returnedRows += next.length;
+ queryClient.setQueryData(queryKey, {
+ pages: [...current.pages, { memos: next, totalCount: 100, nextCursor: offset + next.length < expected.length ? String(offset + next.length) : null }],
+ pageParams: [...current.pageParams, cursor],
+ });
+ }
+ const completed = queryClient.getQueryData<MemoListQueryData>(queryKey)!;
+ const unique = [...new Map(completed.pages.flatMap(page => page.memos).map(item => [item.id, item])).values()];
+ expect(sortDesktopTitleMemoSummaries(unique, sort).map(item => item.id)).toEqual(expected.map(item => item.id));
+ expect(completed.pages.at(-1)!.nextCursor).toBeNull();
+ expect(loadedPages).toBe(2);
+ expect(returnedRows).toBe(51);
+ expect(completed.pages[0]!.totalCount).toBe(100);
+ queryClient.clear();
+ });
+ }
+ }
+
+ test("renames across loaded pages and remaps IDs without reading or refetching the library", async () => {
+ const queryClient = new QueryClient();
+ const queryKey = ["memos", "notebook", "nb-inbox", "", "all", "title-asc"] as const;
+ const notes = Array.from({ length: 120 }, (_, index) => memo({ id: `memo-${index}`, title: `中文笔记 ${String(index).padStart(3, "0")}` }));
+ const ordered = desktopOrder(notes, "title-asc");
+ const data = queryData([ordered.slice(0, 50), ordered.slice(50, 100)], 120);
+ data.pages[0]!.nextCursor = "50";
+ data.pages[1]!.nextCursor = "100";
+ data.pageParams = [null, "50"];
+ let reads = 0;
+ const observer = new QueryObserver(queryClient, {
+ queryKey, initialData: data, staleTime: Infinity,
+ queryFn: async () => { reads++; return data; },
+ });
+ const unsubscribe = observer.subscribe(() => {});
+
+ const updated = { ...notes[90]!, title: "A renamed note", revision: 2 };
+ updateMemoSummaryInLists(queryClient, updated);
+ let cached = queryClient.getQueryData<MemoListQueryData>(queryKey)!;
+ expect(cached.pages.flatMap((page) => page.memos.map((item) => item.id)))
+ .toEqual(desktopOrder(notes.map((item) => item.id === updated.id ? updated : item), "title-asc").slice(0, 100).map((item) => item.id));
+
+ remapMemoIdsInLists(queryClient, new Map([[updated.id, "memo-remote-90"]]));
+ cached = queryClient.getQueryData<MemoListQueryData>(queryKey)!;
+ expect(cached.pages[0]!.memos[0]!.id).toBe("memo-remote-90");
+ expect(cached.pages.map((page) => page.memos.length)).toEqual([50, 50]);
+ expect(cached.pages.map((page) => page.totalCount)).toEqual([120, 120]);
+ expect(cached.pages.map((page) => page.nextCursor)).toEqual(["50", "100"]);
+ expect(cached.pageParams).toEqual([null, "50"]);
+ await Promise.resolve();
+ expect(reads).toBe(0);
+ unsubscribe();
+ queryClient.clear();
+ });
+});