Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(clients): reduce repeated rendering, cache writes and polling
elfcve500a7f0d972
diff --git a/apps/desktop/src/renderer/__tests__/useRemoteSessionBackgroundTasks.test.ts b/apps/desktop/src/renderer/__tests__/useRemoteSessionBackgroundTasks.test.tsindex ee39b3e284..c30d3c039a 100644--- a/apps/desktop/src/renderer/__tests__/useRemoteSessionBackgroundTasks.test.ts+++ b/apps/desktop/src/renderer/__tests__/useRemoteSessionBackgroundTasks.test.ts@@ -221,17 +221,45 @@ describe('useRemoteSessionBackgroundTasks', () => {expect(result.current.stopping).toBe(false);});- it('慢的旧读取晚到时不覆盖更新的快照', async () => {+ // Unit: slow device links must not accumulate another request pair every tick.+ it('上一轮仍在途时跳过轮询,返回后恢复复查', async () => {+ let release!: (value: { tasks: [] }) => void;+ mocks.list.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ }),+ );+ const { result } = renderHook(() => useRemoteSessionBackgroundTasks('s1', 'dev-1', false));+ await act(async () => {+ await vi.advanceTimersByTimeAsync(45_000);+ });+ expect(mocks.activity).toHaveBeenCalledTimes(1);+ expect(mocks.list).toHaveBeenCalledTimes(1);+ await act(async () => {+ release({ tasks: [] });+ });+ mocks.activity.mockResolvedValue({ active: true });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(15_000);+ });+ expect(mocks.activity).toHaveBeenCalledTimes(2);+ expect(result.current.active).toBe(true);+ });++ it('旧视图的慢读取晚到时不覆盖新视图的快照', async () => {let releaseSlow!: (value: { active: boolean }) => void;mocks.activity.mockImplementationOnce(() => new Promise((resolve) => (releaseSlow = resolve)));mocks.activity.mockResolvedValue({ active: false });mocks.list.mockResolvedValue({ tasks: [] });- const { result } = renderHook(() => useRemoteSessionBackgroundTasks('s1', 'dev-1', false));+ const { result, rerender } = renderHook(+ ({ sid }) => useRemoteSessionBackgroundTasks(sid, 'dev-1', false),+ { initialProps: { sid: 's1' } },+ );+ await flush();+ // 切换会话后立即读新视图,旧视图的慢读取不能阻止或覆盖它。+ rerender({ sid: 's2' });await flush();- // 第二轮(更新)先返回:无后台任务。- await act(async () => {- await vi.advanceTimersByTimeAsync(15_000);- });expect(result.current.active).toBe(false);// 第一轮(更旧)此时才返回「有活动」,必须被丢弃。await act(async () => {diff --git a/apps/desktop/src/renderer/components/chat/__tests__/rehypeHighlightShared.test.ts b/apps/desktop/src/renderer/components/chat/__tests__/rehypeHighlightShared.test.tsindex d55f4b8caa..1c0feae014 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/rehypeHighlightShared.test.ts+++ b/apps/desktop/src/renderer/components/chat/__tests__/rehypeHighlightShared.test.ts@@ -1,7 +1,32 @@import { createElement } from 'react';import { renderToStaticMarkup } from 'react-dom/server';import ReactMarkdown from 'react-markdown';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import type { Element, Root } from 'hast';+import { unified, type Plugin } from 'unified';++const calls = vi.hoisted(() => ({ highlighted: 0 }));+vi.mock('rehype-highlight', async (importOriginal) => {+ const original = await importOriginal<typeof import('rehype-highlight')>();+ return {+ default: () => {+ const transform = original.default();+ return (...args: Parameters<typeof transform>) => {+ const visit = (node: Root | Element) => {+ if (+ node.type === 'element' &&+ node.tagName === 'code' &&+ !node.properties.className?.toString().includes('no-highlight')+ )+ calls.highlighted++;+ for (const child of node.children) if (child.type === 'element') visit(child);+ };+ visit(args[0]);+ return transform(...args);+ };+ },+ };+});import { rehypeHighlightShared } from '../rehypeHighlightShared';@@ -22,4 +47,62 @@ describe('rehypeHighlightShared', () => {'<pre><code class="hljs language-unknown-lang">x',);});++ // Unit: full-document streaming reparses stable code; the upstream highlighter+ // must not repeat that work, and downstream AST mutations must remain isolated.+ it('reuses stable code while keeping downstream mutations out of future documents', () => {+ const code = '```ts\nconst cachedValue = 123;\n```';+ const before = calls.highlighted;+ const mutate: Plugin<[], Root> = () => (tree) => {+ const pre = tree.children.find(+ (node) => node.type === 'element' && node.tagName === 'pre',+ ) as Element;+ (pre.children[0] as Element).children = [{ type: 'text', value: 'mutated downstream' }];+ };+ renderToStaticMarkup(+ createElement(ReactMarkdown, { rehypePlugins: [rehypeHighlightShared, mutate] }, code),+ );+ const html = render(code + '\n\nstreaming tail');+ expect(html).toContain('cachedValue');+ expect(html).not.toContain('mutated downstream');+ expect(calls.highlighted - before).toBe(1);+ expect(render('```ts\nconst cachedValue = 456;\n```')).toContain('456');+ expect(calls.highlighted - before).toBe(2);+ });++ it('preserves unknown-language diagnostics and explicit opt-outs on repeated documents', () => {+ for (let i = 0; i < 2; i++) {+ const node: Element = {+ type: 'element',+ tagName: 'code',+ properties: { className: ['language-not-a-language'] },+ children: [{ type: 'text', value: 'sample' }],+ };+ const tree: Root = {+ type: 'root',+ children: [{ type: 'element', tagName: 'pre', properties: {}, children: [node] }],+ };+ const file = unified()+ .use(function () {+ this.parser = () => tree;+ this.compiler = () => '';+ })+ .use(rehypeHighlightShared)+ .processSync('');+ expect(file.messages).toHaveLength(1);+ expect(node.children).toEqual([{ type: 'text', value: 'sample' }]);+ }+ expect(render('```no-highlight\nconst a = 1;\n```')).not.toContain('hljs-keyword');+ });++ it('does not reuse results across languages or retain oversized blocks', () => {+ const source = 'const languageSpecificValue = true;';+ expect(render('```ts\n' + source + '\n```')).toContain('hljs-keyword');+ expect(render('```plaintext\n' + source + '\n```')).not.toContain('hljs-keyword');+ const large = '```plaintext\n' + 'x'.repeat(70_000) + '\n```';+ const before = calls.highlighted;+ render(large);+ render(large);+ expect(calls.highlighted - before).toBe(2);+ });});diff --git a/apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts b/apps/desktop/src/renderer/components/chat/rehypeHighlightShared.tsindex b51ef8d50c..e6bd3f2228 100644--- a/apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts+++ b/apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts@@ -1,20 +1,95 @@+import type { Element } from 'hast';import rehypeHighlight from 'rehype-highlight';+import { visit } from 'unist-util-visit';type HighlightTransformer = ReturnType<typeof rehypeHighlight>;+interface HighlightEntry {+ children: string;+ classes: string[];+ bytes: number;+}+// Bound retained message content independently of the number of mounted bubbles.+const MAX_CACHE_BYTES = 2 * 1024 * 1024;+const MAX_CACHE_ENTRIES = 128;+const cache = new Map<string, HighlightEntry>();+let cacheBytes = 0;let sharedTransformer: HighlightTransformer | undefined;+function remember(key: string, node: Element): void {+ const children = JSON.stringify(node.children);+ const classes = node.properties.className;+ if (!Array.isArray(classes)) return;+ const bytes = 2 * (key.length + children.length + JSON.stringify(classes).length);+ if (bytes > MAX_CACHE_BYTES) return;+ const previous = cache.get(key);+ if (previous) cacheBytes -= previous.bytes;+ cache.delete(key);+ cache.set(key, { children, classes: [...classes], bytes });+ cacheBytes += bytes;+ while (cacheBytes > MAX_CACHE_BYTES || cache.size > MAX_CACHE_ENTRIES) {+ const oldest = cache.keys().next().value!;+ cacheBytes -= cache.get(oldest)!.bytes;+ cache.delete(oldest);+ }+}+/**- * rehype-highlight with one lowlight instance for the whole renderer.- *- * react-markdown builds a new processor and re-attaches plugins on every- * render, and rehype-highlight's attacher calls createLowlight(common) each- * time, re-registering about forty languages. Switching back to a long task- * re-renders every bubble at once, so that registration is pure repeated work.- * The returned transformer only reads the lowlight registry and never touches- * the processor, so one instance can serve every processor.+ * Share the language registry and bounded results for unchanged fenced code.+ * Full-document parsing still handles heading IDs and reference links. Cached+ * children are deserialized afresh so downstream plugins cannot mutate them.*/export function rehypeHighlightShared(): HighlightTransformer {- sharedTransformer ??= rehypeHighlight();+ if (sharedTransformer) return sharedTransformer;+ const highlight = rehypeHighlight();+ sharedTransformer = (tree, file) => {+ const misses: Array<{ key: string; node: Element }> = [];+ const hits: Array<{ node: Element; entry: HighlightEntry }> = [];+ visit(tree, 'element', (node, _index, parent) => {+ if (node.tagName !== 'code' || parent?.type !== 'element' || parent.tagName !== 'pre') return;+ const classes = node.properties.className;+ if (+ !Array.isArray(classes) ||+ classes.includes('no-highlight') ||+ classes.includes('nohighlight')+ )+ return;+ if (!classes.some((value) => typeof value === 'string' && /^(lang|language)-./.test(value)))+ return;+ // Already transformed trees and large, unfinished blocks use the upstream path.+ if (+ node.children.length !== 1 ||+ node.children[0].type !== 'text' ||+ node.children[0].value.length > 64 * 1024+ )+ return;+ const key = JSON.stringify([classes, node.children[0].value]);+ const entry = cache.get(key);+ if (!entry) {+ misses.push({ key, node });+ return;+ }+ cache.delete(key);+ cache.set(key, entry);+ hits.push({ node, entry });+ // Skip just this node during the upstream walk; remove the marker afterward.+ node.properties.className = [...entry.classes, 'no-highlight'];+ });+ const messagesBefore = file.messages.length;+ try {+ highlight(tree, file);+ } finally {+ // Restore after the walk: traversing cached token spans would cost almost+ // as much as highlighting them again for long code blocks.+ for (const { node, entry } of hits) {+ node.children = JSON.parse(entry.children) as Element['children'];+ node.properties.className = [...entry.classes];+ }+ }+ // Preserve upstream diagnostics (e.g. unknown languages) on every document.+ if (file.messages.length === messagesBefore) {+ for (const { key, node } of misses) remember(key, node);+ }+ };return sharedTransformer;}diff --git a/apps/desktop/src/renderer/hooks/useRemoteSessionBackgroundTasks.ts b/apps/desktop/src/renderer/hooks/useRemoteSessionBackgroundTasks.tsindex b8cef131fc..4d1b7a6e12 100644--- a/apps/desktop/src/renderer/hooks/useRemoteSessionBackgroundTasks.ts+++ b/apps/desktop/src/renderer/hooks/useRemoteSessionBackgroundTasks.ts@@ -88,7 +88,7 @@ export function useRemoteSessionBackgroundTasks(EMPTY_STATE,);const [stoppingViewKey, setStoppingViewKey] = useState<string | null>(null);- // 读取序号:定时器不等上一轮返回,慢的旧读取只能被更新的结果取代,不能反过来覆盖;+ // 读取序号:同一视图不叠加轮询,切换视图后的旧读取也不能覆盖新结果;// 停止成功时把已发出的读取整体作废,避免在途旧快照重新点亮已熄灭的提示。const issuedSeqRef = useRef(0);const appliedSeqRef = useRef(0);@@ -100,22 +100,29 @@ export function useRemoteSessionBackgroundTasks(return;}let disposed = false;+ let inFlight = false;const read = () => {+ if (inFlight) return;+ inFlight = true;const seq = ++issuedSeqRef.current;void Promise.all([sessionBackgroundActivityFor(sessionId),listSessionBackgroundTasksFor(sessionId),- ]).then(([activity, list]) => {- if (disposed || seq <= appliedSeqRef.current) return;- appliedSeqRef.current = seq;- const next = {- active: activity?.active === true,- tasks: pickRemoteBashTasks(Array.isArray(list?.tasks) ? list.tasks : []),- };- setSnapshot((prev) =>- prev.viewKey === viewKey && sameState(prev, next) ? prev : { ...next, viewKey },- );- });+ ])+ .then(([activity, list]) => {+ if (disposed || seq <= appliedSeqRef.current) return;+ appliedSeqRef.current = seq;+ const next = {+ active: activity?.active === true,+ tasks: pickRemoteBashTasks(Array.isArray(list?.tasks) ? list.tasks : []),+ };+ setSnapshot((prev) =>+ prev.viewKey === viewKey && sameState(prev, next) ? prev : { ...next, viewKey },+ );+ })+ .finally(() => {+ inFlight = false;+ });};read();const timer = setInterval(read, POLL_MS);diff --git a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.tsindex bf70f1bd13..9d49b43e0d 100644--- a/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts+++ b/apps/mobile/src/__tests__/mobileSessionMessageCache.test.ts@@ -178,9 +178,11 @@ describe('mobileSessionMessageCache', () => {});it('merges list messages without losing earlier history and serializes rapid updates', async () => {+ const storage = (await import('@/session/messageCacheStorage')).messageCacheStorage;const { cacheSessionMessages, cacheSessionListMessage, getCachedSessionMessages } = await import('@/session/mobileSessionMessageCache');await cacheSessionMessages('host-a', 'session-1', [makeMessage({ id: 'old', clientId: 'old', createdAt: isoAt(1) })]);const content = '未截断的聊天正文。'.repeat(2000);+ vi.mocked(storage.setItem).mockClear();await Promise.all([cacheSessionListMessage('host-a', 'session-1', makeMessage({ id: 'new', clientId: 'new', createdAt: isoAt(2), content: 'first' })),cacheSessionListMessage('host-a', 'session-1', makeMessage({ id: 'new', clientId: 'new', createdAt: isoAt(2), content })),@@ -188,6 +190,55 @@ describe('mobileSessionMessageCache', () => {const rows = await getCachedSessionMessages('host-a', 'session-1');expect(rows.map(row => row.id)).toEqual(['old', 'new']);expect(rows[1].content).toBe(content);+ // Burst pushes share one durable snapshot instead of rewriting the window per row.+ expect(storage.setItem).toHaveBeenCalledTimes(1);+ });++ it('seals a batch before disk I/O and persists later arrivals in the next batch', async () => {+ const storage = (await import('@/session/messageCacheStorage')).messageCacheStorage;+ const { cacheSessionListMessage, getCachedSessionMessages } = await import('@/session/mobileSessionMessageCache');+ let release!: (value: null) => void;+ let entered!: () => void;+ const started = new Promise<void>(resolve => { entered = resolve; });+ vi.mocked(storage.getItem).mockImplementationOnce(() => {+ entered();+ return new Promise(resolve => { release = resolve; });+ });+ vi.mocked(storage.setItem).mockClear();+ const first = cacheSessionListMessage('host-a', 'disk-boundary', makeMessage({ id: 'first', createdAt: isoAt(1) }));+ await started;+ const second = cacheSessionListMessage('host-a', 'disk-boundary', makeMessage({ id: 'second', createdAt: isoAt(2) }));+ release(null);+ await Promise.all([first, second]);+ expect(storage.setItem).toHaveBeenCalledTimes(2);+ expect((await getCachedSessionMessages('host-a', 'disk-boundary')).map(row => row.id)).toEqual(['first', 'second']);+ });++ // Unit: batching must not cross an intervening read, replacement, or account generation.+ it('keeps a queued read between two list pushes at its original position', async () => {+ const { cacheSessionListMessage, getCachedSessionMessages } = await import('@/session/mobileSessionMessageCache');+ const first = cacheSessionListMessage('host-a', 'read-boundary', makeMessage({ id: 'first', createdAt: isoAt(1) }));+ const between = getCachedSessionMessages('host-a', 'read-boundary');+ const second = cacheSessionListMessage('host-a', 'read-boundary', makeMessage({ id: 'second', createdAt: isoAt(2) }));+ expect((await between).map(row => row.id)).toEqual(['first']);+ await Promise.all([first, second]);+ expect((await getCachedSessionMessages('host-a', 'read-boundary')).map(row => row.id)).toEqual(['first', 'second']);+ });++ it('does not merge pushes across a replacement or an owner switch', async () => {+ const { cacheSessionListMessage, getCachedSessionMessages, replaceCachedSessionMessages } = await import('@/session/mobileSessionMessageCache');+ const { setMobileAuthOwner } = await import('@/auth/authOwnerGeneration');+ const first = cacheSessionListMessage('host-a', 'replace-boundary', makeMessage({ id: 'deleted', createdAt: isoAt(1) }));+ const clear = replaceCachedSessionMessages('host-a', 'replace-boundary', []);+ const second = cacheSessionListMessage('host-a', 'replace-boundary', makeMessage({ id: 'retained', createdAt: isoAt(2) }));+ await Promise.all([first, clear, second]);+ expect((await getCachedSessionMessages('host-a', 'replace-boundary')).map(row => row.id)).toEqual(['retained']);++ const oldOwner = cacheSessionListMessage('host-a', 'owner-boundary', makeMessage({ id: 'old-owner', createdAt: isoAt(1) }));+ setMobileAuthOwner('account-b');+ const newOwner = cacheSessionListMessage('host-a', 'owner-boundary', makeMessage({ id: 'new-owner', createdAt: isoAt(2) }));+ await Promise.all([oldOwner, newOwner]);+ expect((await getCachedSessionMessages('host-a', 'owner-boundary')).map(row => row.id)).toEqual(['new-owner']);});// Unit regression: a blurred page's deferred write must not erase list pushesdiff --git a/apps/mobile/src/__tests__/useMobileModelQuotas.test.tsx b/apps/mobile/src/__tests__/useMobileModelQuotas.test.tsxnew file mode 100644index 0000000000..38a4b32c07--- /dev/null+++ b/apps/mobile/src/__tests__/useMobileModelQuotas.test.tsx@@ -0,0 +1,137 @@+// @vitest-environment jsdom+// Unit: the real hook must not repaint model lists for unchanged countdowns,+// must expire model-specific buckets, and must suspend work when not active.+// Existing picker tests replace this hook, so they cannot cover its timers.+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import type { ProviderView } from "@cindy/model-providers/registry";++const h = vi.hoisted(() => ({+ invoke: vi.fn(),+ status: "online",+ connectionEpoch: 1,+ app: "active",+ listeners: new Set<(state: string) => void>(),+}));+vi.mock("react-native", () => ({+ AppState: {+ get currentState() {+ return h.app;+ },+ addEventListener: (_name: string, listener: (state: string) => void) => {+ h.listeners.add(listener);+ return { remove: () => h.listeners.delete(listener) };+ },+ },+}));+vi.mock("@/device-link/DeviceLinkContext", () => ({ useDeviceLink: () => h }));+import { useMobileModelQuotas } from "@/session/useMobileModelQuotas";+import {+ mobileWeeklyQuota,+ quotaCountdown,+} from "@/session/mobileModelRowPresentation";++Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+const providers = [+ { id: "openai", connected: true, auth: { method: "oauth", native: "codex" } },+] as ProviderView[];+let root: Root;+let view: ReturnType<typeof useMobileModelQuotas>;+let renders: number;+function Probe({ sources = providers }: { sources?: ProviderView[] }) {+ view = useMobileModelQuotas('["account","host"]', true, sources);+ renders++;+ return null;+}+const window = (reset: number) => ({+ windowMinutes: 10080,+ usedPercent: 20,+ resetsAt: reset,+});+beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(0);+ h.app = "active";+ h.listeners.clear();+ renders = 0;+ h.invoke+ .mockReset()+ .mockResolvedValue({+ providerId: "openai",+ rateLimits: { secondary: window(4 * 86400) },+ });+ root = createRoot(document.createElement("div"));+});+afterEach(() => {+ act(() => root.unmount());+ vi.useRealTimers();+});+const mount = async (sources = providers) => {+ await act(async () => root.render(createElement(Probe, { sources })));+};+const advance = async (ms: number) => {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(ms);+ });+};++it("keeps the same rendered snapshot while a days-long countdown is unchanged", async () => {+ await mount();+ const count = renders;+ const snapshot = view;+ await advance(10000);+ expect(renders).toBe(count);+ expect(view).toBe(snapshot);+ expect(h.invoke).toHaveBeenCalledTimes(1);+});++it("does not start quota work when no provider has a subscription", async () => {+ await mount([]);+ const count = renders;+ await advance(60000);+ expect(renders).toBe(count);+ expect(h.invoke).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+});++it("updates and expires a model-specific countdown even while the generic quota stays stable", async () => {+ const generic = { secondary: window(4 * 86400) };+ h.invoke.mockResolvedValue({+ providerId: "openai",+ rateLimits: generic,+ rateLimitsByLimitId: {+ codex: generic,+ special: { limitName: "special-model", secondary: window(2) },+ },+ });+ await mount();+ await advance(1000);+ const q = view.quotas.openai;+ const special = mobileWeeklyQuota(q.source, q.raw, view.now, "special-model");+ expect(quotaCountdown(special!.resetsAt!, view.now)).toBe("1s");+ await advance(1000);+ expect(+ mobileWeeklyQuota(q.source, q.raw, view.now, "special-model"),+ ).toBeNull();+ expect(view.quotas.openai.remaining).toBe(80);+});++it("stops clocks and polling while inactive, then refreshes on resume", async () => {+ await mount();+ act(() => {+ h.app = "inactive";+ h.listeners.forEach((fn) => fn(h.app));+ });+ const count = renders;+ await advance(60000);+ expect(renders).toBe(count);+ expect(h.invoke).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ await act(async () => {+ h.app = "active";+ h.listeners.forEach((fn) => fn(h.app));+ });+ expect(h.invoke).toHaveBeenCalledTimes(2);+ expect(view.now).toBe(60000);+});diff --git a/apps/mobile/src/session/mermaidWebViewHtml.ts b/apps/mobile/src/session/mermaidWebViewHtml.tsindex ded715e2e8..7f71c47539 100644--- a/apps/mobile/src/session/mermaidWebViewHtml.ts+++ b/apps/mobile/src/session/mermaidWebViewHtml.ts@@ -15,6 +15,10 @@ export { MOBILE_MERMAID_VERSION } from '@/session/richContentAssets.generated';/** 本地资源执行超时;异常时停留在源码降级。 */const MERMAID_LOCAL_TIMEOUT_MS = 1000;+// The bundled runtime is immutable. Escape it once on first use, not on startup+// or for every diagram/theme; only source and callbacks vary between documents.+let serializedMermaidRuntime: string | undefined;+/** Mermaid 本地动态加载器,只在页面含图表时注入。 */export function buildMermaidLoaderJs(onReadyJs: string,@@ -32,7 +36,7 @@ export function buildMermaidLoaderJs(}try {var script = document.createElement('script');- script.textContent = ${serializeForScript(MOBILE_MERMAID_JS)};+ script.textContent = ${serializedMermaidRuntime ??= serializeForScript(MOBILE_MERMAID_JS)};document.head.appendChild(script);if (!window.mermaid) { fail(); return; }try { ${onReadyJs} } catch (error) { fail(); return; }diff --git a/apps/mobile/src/session/mobileSessionMessageCache.ts b/apps/mobile/src/session/mobileSessionMessageCache.tsindex 9ab453c34e..d7f702467f 100644--- a/apps/mobile/src/session/mobileSessionMessageCache.ts+++ b/apps/mobile/src/session/mobileSessionMessageCache.ts@@ -45,7 +45,17 @@ export interface SessionMessageCacheWriteAuthority {readonly keyEpoch: number;}+interface PendingListWrite {+ authority: SessionMessageCacheWriteAuthority;+ messages: RemoteMessage[];+ completion: Promise<void>;+}+const pendingListWrites = new Map<string, PendingListWrite>();+function enqueueCacheOperation(key: string, operation: () => Promise<void>): Promise<void> {+ // A read, replacement or other write is an ordering barrier. Later pushes+ // must never join a batch ahead of that operation.+ pendingListWrites.delete(key);const previous = pendingOperations.get(key) ?? Promise.resolve();const next = previous.catch(() => undefined).then(operation).catch(() => undefined);pendingOperations.set(key, next);@@ -174,17 +184,31 @@ export async function cacheSessionMessages(export async function cacheSessionListMessage(deviceId: string, sessionId: string, message: RemoteMessage): Promise<void> {const authority = captureSessionMessageCacheWriteAuthority(deviceId, sessionId);if (!authority) return;- await enqueueCacheOperation(authority.key, async () => {+ const pending = pendingListWrites.get(authority.key);+ if (pending && isSessionMessageCacheWriteAuthorityCurrent(pending.authority)) {+ pending.messages.push(message);+ return pending.completion;+ }+ const batch: PendingListWrite = { authority, messages: [message], completion: Promise.resolve() };+ batch.completion = enqueueCacheOperation(authority.key, async () => {+ // Seal before the first await: arrivals during disk I/O form the next batch,+ // so a busy session cannot indefinitely delay a completed durable snapshot.+ if (pendingListWrites.get(authority.key) === batch) pendingListWrites.delete(authority.key);if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;const raw = await messageCacheStorage.getItem(authority.key);const parsed: unknown = raw ? JSON.parse(raw) : null;- const previous = normalizeCachedMessages(isRecord(parsed) && Array.isArray(parsed.messages)+ let messages = normalizeCachedMessages(isRecord(parsed) && Array.isArray(parsed.messages)? parsed.messages : Array.isArray(parsed) ? parsed : []);- const messages = normalizeCachedMessages([...previous.filter(row =>- row.id !== message.id && (!message.clientId || row.clientId !== message.clientId)), message]);+ for (const incoming of batch.messages) {+ // Keep per-arrival alias replacement and window trimming semantics.+ messages = normalizeCachedMessages([...messages.filter(row =>+ row.id !== incoming.id && (!incoming.clientId || row.clientId !== incoming.clientId)), incoming]);+ }if (!isSessionMessageCacheWriteAuthorityCurrent(authority)) return;await messageCacheStorage.setItem(authority.key, JSON.stringify({ version: 1, updatedAt: Date.now(), messages }));});+ pendingListWrites.set(authority.key, batch);+ return batch.completion;}// 登出清空:遍历所有本前缀的 key 一次性删除(AsyncStorage 支持枚举,无需手动维护 host 索引)。diff --git a/apps/mobile/src/session/useMobileModelQuotas.ts b/apps/mobile/src/session/useMobileModelQuotas.tsindex f187307e7b..f2c339a60a 100644--- a/apps/mobile/src/session/useMobileModelQuotas.ts+++ b/apps/mobile/src/session/useMobileModelQuotas.ts@@ -1,13 +1,51 @@-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { AppState } from "react-native";import type { ProviderView } from "@cindy/model-providers/registry";+import { isCodexBucketStale } from "@cindy/maker-shared/codex-usage-buckets";+import type { MobileCodexRateLimitsResult } from "@cindy/maker-shared/device-link-contract";import { useDeviceLink } from "@/device-link/DeviceLinkContext";import {mobileQuotaSource,mobileWeeklyQuota,+ quotaCountdown,type QuotaSource,} from "./mobileModelRowPresentation";+type QuotaValues = Record<string, { source: QuotaSource; raw: unknown }>;++/** Compare time-dependent presentation per account/bucket, never per model row. */+function quotaTimeKey(values: QuotaValues, now: number): string {+ const present = (source: QuotaSource, raw: unknown) => {+ const quota = mobileWeeklyQuota(source, raw, now);+ return (+ quota && [+ quota.remaining,+ quota.resetsAt,+ quota.resetsAt === null+ ? null+ : quotaCountdown(quota.resetsAt, now, undefined, quota.windowMinutes),+ ]+ );+ };+ return JSON.stringify(+ Object.values(values).map(({ source, raw }) => {+ if (source !== "codex") return present(source, raw);+ const data = raw as MobileCodexRateLimitsResult | null;+ if (!data?.rateLimits) return null;+ // The generic provider quota alone would miss model-specific reset times.+ return Object.values(+ data.rateLimitsByLimitId ?? { codex: data.rateLimits },+ ).map((bucket) => [+ isCodexBucketStale(bucket, now),+ present("codex", {+ rateLimits: bucket,+ rateLimitsByLimitId: { codex: bucket },+ }),+ ]);+ }),+ );+}+/** One read per account, never one per model. Responses are fenced by device/account/connection. */export function useMobileModelQuotas(scope: string,@@ -39,15 +77,20 @@ export function useMobileModelQuotas(]);const [state, setState] = useState<{binding: string;- values: Record<string, { source: QuotaSource; raw: unknown }>;+ values: QuotaValues;}>();const [now, setNow] = useState(Date.now);+ const clockSnapshot = useRef({ values: {} as QuotaValues, now });+ clockSnapshot.current = {+ values: state?.binding === binding ? state.values : {},+ now,+ };useEffect(() => {- if (!visible || status !== "online") return;+ if (!visible || status !== "online" || sources === "[]") return;let active = true;let pending = false;const refresh = async () => {- if (pending || AppState.currentState === "background") return;+ if (pending || AppState.currentState !== "active") return;pending = true;const items = JSON.parse(sources) as {id: string;@@ -81,35 +124,63 @@ export function useMobileModelQuotas(}}),);- if (active) {+ if (active && AppState.currentState === "active") {setState((previous) => ({binding,// 短暂的 IPC/网络失败不应抹掉同一 binding 下最近一次成功额度。- values: previous?.binding === binding ? { ...previous.values, ...values } : values,+ values:+ previous?.binding === binding+ ? { ...previous.values, ...values }+ : values,}));setNow(Date.now());}pending = false;};- void refresh();- const clock = setInterval(() => { if(AppState.currentState !== "background") setNow(Date.now()); },1000);- const timer = setInterval(() => {- setNow(Date.now());+ let clock: ReturnType<typeof setInterval> | undefined;+ let timer: ReturnType<typeof setInterval> | undefined;+ const stopTimers = () => {+ clearInterval(clock);+ clearInterval(timer);+ clock = timer = undefined;+ };+ const resume = () => {+ stopTimers();+ if (AppState.currentState !== "active") return;void refresh();- }, 30000);+ clock = setInterval(() => {+ if (AppState.currentState !== "active") return;+ const next = Date.now();+ const previous = clockSnapshot.current;+ if (+ quotaTimeKey(previous.values, previous.now) !==+ quotaTimeKey(previous.values, next)+ )+ setNow(next);+ }, 1000);+ timer = setInterval(() => void refresh(), 30000);+ };+ resume();const app = AppState.addEventListener("change", (value) => {- if (value === "active") void refresh();+ if (value === "active") resume();+ else stopTimers();});return () => {active = false;- clearInterval(timer);- clearInterval(clock);+ stopTimers();app.remove();};}, [binding, invoke]);const quotas = Object.fromEntries(Object.entries(state?.binding === binding ? state.values : {}).map(- ([id, v]) => [id, { ...mobileWeeklyQuota(v.source, v.raw, now), source: v.source, raw: v.raw }],+ ([id, v]) => [+ id,+ {+ ...mobileWeeklyQuota(v.source, v.raw, now),+ source: v.source,+ raw: v.raw,+ },+ ],),);return { quotas, now };