Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 隔离构建环境并减少任务更新引发的重复渲染

Dash963b3f1e73ff
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index e278716589..7851c23d73 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -672,7 +672,6 @@ import {
sessionMetaWriteQueue,
sessionPendingWrites,
type RemoteSessionRunStatus,
- useRemoteSessions,
useRemoteSessionDetail,
useSessionGoalStatus,
useSessionInputProjection,
@@ -1177,7 +1176,6 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
useEffect(() => {
if (messageScreenFocusedRef.current && messageAppActiveRef.current) historyView.view.setActive(true);
}, [connectionEpoch, messageReloadRevision, historyView.view]);
- const sessions = useRemoteSessions();
const inheritedMessages = useSessionMessages(sessionId, deviceId);
const rawMessages = useMemo(() => sideChatBoundary === undefined ? inheritedMessages
: inheritedMessages.filter(message => Date.parse(message.createdAt) >= sideChatBoundary), [inheritedMessages, sideChatBoundary]);
@@ -6069,9 +6067,9 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
return outboxConnectionBlockedNow() || isRemoteSessionMissing(row) || row?.cacheSeeded === true
|| getNewSessionCreationTask(sessionId) !== null;
};
- const findDurableOutboxRecord = (clientId: string) => getCurrentMobileOutboxRecords().find((r) =>
- r.deviceId === deviceId && r.item.sessionId === sessionId && r.item.clientId === clientId);
- const retryOutboxItem = (clientId: string) => {
+ const findDurableOutboxRecord = useCallback((clientId: string) => getCurrentMobileOutboxRecords().find((r) =>
+ r.deviceId === deviceId && r.item.sessionId === sessionId && r.item.clientId === clientId), [deviceId, sessionId]);
+ const retryOutboxItem = useCallback((clientId: string) => {
const record = findDurableOutboxRecord(clientId);
if (!record || record.state !== 'failed') return;
if (record.creation && !record.prepared && !record.template) {
@@ -6087,8 +6085,8 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
void mobileDurableOutbox.update(record, {
state: record.prepared ? 'confirming' : 'queued', error: undefined,
}).catch((err) => setError(formatRemoteError(err)));
- };
- const removeOutboxItem = (clientId: string) => {
+ }, [deviceId, deviceName, findDurableOutboxRecord, router, sessionId]);
+ const removeOutboxItem = useCallback((clientId: string) => {
const record = findDurableOutboxRecord(clientId);
if (!record) return;
// Until creation succeeds, this row also owns the recovery form for every later message.
@@ -6117,7 +6115,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
{ text: t('session.common.delete'), style: 'destructive', onPress: confirmRemove },
],
);
- };
+ }, [findDurableOutboxRecord, sessionId, t]);
const outboxDisplayItems = useMemo(() => outboxItems.map((item) => {
const record = findDurableOutboxRecord(item.clientId);
return {
@@ -7744,11 +7742,20 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
};
};
+ // Shared by queue receipts and file actions; declared before memoized consumers.
+ const [transientNotice, setTransientNotice] = useState<SessionTransientNoticeValue | null>(null);
+ const transientNoticeSeqRef = useRef(0);
+ const showTransientNotice = useCallback((message: string) => {
+ transientNoticeSeqRef.current += 1;
+ setTransientNotice({ id: transientNoticeSeqRef.current, message });
+ }, []);
+ const dismissTransientNotice = useCallback(() => setTransientNotice(null), []);
+
const resumeQueue = () => {
void runQueueAction(() => maker.input.resume(sessionId));
};
- const steerQueueItem = (item: QueuedRemoteMessage) => {
+ const steerQueueItem = useCallback((item: QueuedRemoteMessage) => {
void runQueueAction(async () => {
// Projections omit trusted bodies. Prefer fresh source data, while allowing the
// target to restore its main-owned snapshot when the source is unavailable.
@@ -7776,7 +7783,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
}
return accepted;
});
- };
+ }, [deviceId, invoke, maker, runQueueAction, sessionId, showTransientNotice, t]);
const moveQueueItem = useCallback((clientId: string, direction: 'up' | 'down') => {
// 菜单打开期间队列可能变化:按最新位置重新判断方向和目标。
@@ -7809,7 +7816,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
});
}, [applyProjectionIfCurrent, maker, sessionId]);
- const removeQueueItem = (clientId: string) => {
+ const removeQueueItem = useCallback((clientId: string) => {
const before = remoteSessionStore.getInputProjection(sessionId);
const index = before.pendingQueue.findIndex((item) => item.clientId === clientId);
const removed = index >= 0 ? before.pendingQueue[index] : undefined;
@@ -7843,7 +7850,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
},
action: () => maker.input.remove(sessionId, clientId),
});
- };
+ }, [maker, runOptimisticQueueAction, runQueueAction, sessionId]);
/**
* 回收某次排队编辑期间"新增"的附件(不在 stash、也不是该队列条目自身 files):
@@ -7901,7 +7908,7 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
* 已在编辑另一条时切换目标:沿用最初的 stash(用户真正的草稿),旧条目解锁,
* 且旧条目编辑期间新增的附件先回收再覆写托盘(否则成为 OSS 孤儿,review P2)。
*/
- const beginQueueEdit = (item: QueuedRemoteMessage) => {
+ const beginQueueEdit = useCallback((item: QueuedRemoteMessage) => {
if (queueAvailabilityReason || queueBusy) return;
// 上一条的保存(update-content)在途时不允许进入/切换编辑:切换路径会立即解锁
// 旧条目并回收其编辑期附件,与在途 RPC 竞争——桌面端可能用旧内容抢先派发,或
@@ -7953,7 +7960,8 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
setQueueEditLock,
);
composerInputRef.current?.applyDocumentAndSetSelectionToEnd(textState.document);
- };
+ }, [applyComposerDocument, discardQueueEditTransientAttachments, pendingUploads.length,
+ queueAvailabilityReason, queueBusy, setQueueEditLock, t]);
/** 放弃排队消息编辑:解锁 + 回收编辑期新增附件 + 恢复进入前的草稿与附件托盘。 */
const pendingSendActions = useMemo<PendingSendBubbleActions>(
@@ -9125,14 +9133,6 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: S
// chip 长按菜单(浮动面板,ContextSheet/模型选择面板同款):target 即开关。
const [chipMenuTarget, setChipMenuTarget] = useState<ChatFilePathTarget | null>(null);
- // 会话页的短暂提示(复制路径等),与文件浏览器「已复制路径」同口径。
- const [transientNotice, setTransientNotice] = useState<SessionTransientNoticeValue | null>(null);
- const transientNoticeSeqRef = useRef(0);
- const showTransientNotice = useCallback((message: string) => {
- transientNoticeSeqRef.current += 1;
- setTransientNotice({ id: transientNoticeSeqRef.current, message });
- }, []);
- const dismissTransientNotice = useCallback(() => setTransientNotice(null), []);
const [chipShareBusy, setChipShareBusy] = useState(false);
// 聊天正文文件 chip 上下文(消息树内 inline chip 经 context 消费,不走多层 prop):
diff --git a/apps/mobile/babel-transformer.js b/apps/mobile/babel-transformer.js
new file mode 100644
index 0000000000..1769f1ef5c
--- /dev/null
+++ b/apps/mobile/babel-transformer.js
@@ -0,0 +1,23 @@
+const expoTransformer = require('@expo/metro-config/babel-transformer');
+
+module.exports = {
+ ...expoTransformer,
+ transform(input) {
+ // Expo preserves the parent NODE_ENV/BABEL_ENV even for --dev false.
+ // Worklets reads those variables and otherwise emits Error stacks in a
+ // Release bundle. Use the same mode as Metro's transform/cache request.
+ const previousNodeEnv = process.env.NODE_ENV;
+ const previousBabelEnv = process.env.BABEL_ENV;
+ const mode = input.options.dev ? 'development' : 'production';
+ process.env.NODE_ENV = mode;
+ process.env.BABEL_ENV = mode;
+ try {
+ return expoTransformer.transform(input);
+ } finally {
+ if (previousNodeEnv === undefined) delete process.env.NODE_ENV;
+ else process.env.NODE_ENV = previousNodeEnv;
+ if (previousBabelEnv === undefined) delete process.env.BABEL_ENV;
+ else process.env.BABEL_ENV = previousBabelEnv;
+ }
+ },
+};
diff --git a/apps/mobile/metro.config.js b/apps/mobile/metro.config.js
index 04e6afdefb..86fbaadc72 100644
--- a/apps/mobile/metro.config.js
+++ b/apps/mobile/metro.config.js
@@ -2,6 +2,7 @@ const path = require('path');
const { getDefaultConfig } = require('expo/metro-config');
const config = getDefaultConfig(__dirname);
+config.transformer.babelTransformerPath = require.resolve('./babel-transformer');
const workspaceRoot = path.resolve(__dirname, '../..');
// Shared endpoint discovery bundles the public manifests from the repository config directory.
config.watchFolders = [...config.watchFolders, path.join(workspaceRoot, 'config')];
diff --git a/apps/mobile/src/__tests__/homeListPatchWhileCovered.test.tsx b/apps/mobile/src/__tests__/homeListPatchWhileCovered.test.tsx
index 560fdf04f5..2b13275816 100644
--- a/apps/mobile/src/__tests__/homeListPatchWhileCovered.test.tsx
+++ b/apps/mobile/src/__tests__/homeListPatchWhileCovered.test.tsx
@@ -2,7 +2,7 @@
import { act, createElement } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-import { RemoteSessionStoreSubscriptionGate, remoteSessionStore, useRemoteSessions } from '@/session/remoteSessionStore';
+import { RemoteSessionStoreSubscriptionGate, remoteSessionStore, useRemoteSessions, useRemoteSessionTitles } from '@/session/remoteSessionStore';
import type { RemoteSession } from '@/session/types';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
@@ -51,3 +51,31 @@ it('shows list patches received while Home was covered as soon as Home returns',
render(true);
expect(container.textContent).toBe('renamed');
});
+
+it('freezes linked titles while covered and catches up on resume without a list pull', () => {
+ remoteSessionStore.setDeviceSessions('mac', 'Mac', [row('a'), row('b')]);
+ const ids = ['a'];
+ const renders = vi.fn();
+ function Link() {
+ renders();
+ return useRemoteSessionTitles(ids)?.a ?? 'missing';
+ }
+ root = createRoot(container);
+ const render = (enabled: boolean) => act(() => root!.render(
+ createElement(RemoteSessionStoreSubscriptionGate, { enabled, children: createElement(Link) }),
+ ));
+ render(true);
+ expect(container.textContent).toBe('a');
+ render(false);
+ renders.mockClear();
+ act(() => remoteSessionStore.applySessionPatch('mac', 'a', { title: 'renamed' }));
+ expect(renders).not.toHaveBeenCalled();
+ expect(container.textContent).toBe('a');
+ render(true);
+ expect(container.textContent).toBe('renamed');
+ let cancelPreview!: () => void;
+ act(() => { cancelPreview = remoteSessionStore.beginSessionListRemovalPreview('a'); });
+ expect(container.textContent).toBe('missing');
+ act(() => cancelPreview());
+ expect(container.textContent).toBe('renamed');
+});
diff --git a/apps/mobile/src/__tests__/markdownBlockContent.test.tsx b/apps/mobile/src/__tests__/markdownBlockContent.test.tsx
index 3f91964988..2170ea48b4 100644
--- a/apps/mobile/src/__tests__/markdownBlockContent.test.tsx
+++ b/apps/mobile/src/__tests__/markdownBlockContent.test.tsx
@@ -4,6 +4,8 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MarkdownBlockContent } from '@/session/MarkdownBlockContent';
import { useMarkdownSessionLinkTitles } from '@/session/useMarkdownSessionLinkTitles';
+import { remoteSessionStore } from '@/session/remoteSessionStore';
+import type { RemoteSession } from '@/session/types';
import {
groupMobileMarkdownSelectableBlocks,
parseMobileMarkdownIncremental,
@@ -49,6 +51,7 @@ function Body({ parse, renderBlock, baseline = false, options }: {
let host: HTMLDivElement;
let root: Root;
beforeEach(() => {
+ remoteSessionStore.clear();
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
host = document.createElement('div');
document.body.append(host);
@@ -162,30 +165,74 @@ describe('streaming Markdown React block boundaries', () => {
const linkedText = `[task](cindy://session/${sessionId})\n\ntail`;
let parse = parseMobileMarkdownIncremental(linkedText);
const renders = vi.fn();
- function LinkedBody({ document, sessions }: {
+ const bodyRenders = vi.fn();
+ function LinkedBody({ document }: {
document: MobileMarkdownParseResult;
- sessions: { id: string; title: string }[];
}) {
- const titles = useMarkdownSessionLinkTitles(document.source, sessions);
+ bodyRenders();
+ const titles = useMarkdownSessionLinkTitles(document.source);
const renderBlock = useCallback<RenderBlock>((block, gap) => {
renders();
return <span data-title={titles?.[sessionId]}>{renderText(block, gap)}</span>;
}, [titles]);
return <Body parse={document} renderBlock={renderBlock} />;
}
- const sessions = [{ id: sessionId, title: 'First title' }];
- act(() => root.render(<LinkedBody document={parse} sessions={sessions} />));
+ const sessions = [{ id: sessionId, title: 'First title' }, { id: 'other', title: 'Other' }] as RemoteSession[];
+ remoteSessionStore.setDeviceSessions('computer', 'Computer', sessions);
+ act(() => root.render(<LinkedBody document={parse} />));
+ bodyRenders.mockClear();
+ // Unit regression: a title-only consumer must not render on other task activity.
+ for (let n = 0; n < 30; n += 1) {
+ act(() => remoteSessionStore.applySessionPatch('computer', 'other', { updatedAt: String(n) }));
+ }
+ expect(bodyRenders).not.toHaveBeenCalled();
renders.mockClear();
for (let n = 0; n < 10; n += 1) {
parse = parseMobileMarkdownIncremental(`${parse.source}x`, parse);
- act(() => root.render(<LinkedBody document={parse} sessions={[...sessions, { id: 'other', title: `Other ${n}` }]} />));
+ act(() => root.render(<LinkedBody document={parse} />));
}
expect(renders).toHaveBeenCalledTimes(10);
renders.mockClear();
- act(() => root.render(<LinkedBody document={parse} sessions={[{ id: sessionId, title: 'Renamed' }]} />));
+ act(() => remoteSessionStore.applySessionPatch('computer', sessionId, { title: 'Renamed' }));
expect(renders).toHaveBeenCalledTimes(2);
expect(host.querySelectorAll('[data-title="Renamed"]')).toHaveLength(2);
- act(() => root.render(<LinkedBody document={parse} sessions={[]} />));
+ act(() => remoteSessionStore.setDeviceSessions('computer', 'Computer', []));
expect(host.querySelector('[data-title]')).toBeNull();
+ act(() => remoteSessionStore.setDeviceSessions('computer', 'Computer', sessions));
+ expect(host.querySelectorAll('[data-title="First title"]')).toHaveLength(2);
+ });
+
+ it('does not subscribe plain text to task changes and follows a changed link target', () => {
+ const first = '03e0c22d-19db-4ac5-814f-1ea04040b471';
+ const second = '03e0c22d-19db-4ac5-814f-1ea04040b472';
+ remoteSessionStore.setDeviceSessions('computer', 'Computer', [
+ { id: first, title: 'First' }, { id: second, title: 'Second' },
+ ] as RemoteSession[]);
+ const subscribe = vi.spyOn(remoteSessionStore, 'subscribe');
+ const renders = vi.fn();
+ function Titles({ text }: { text: string }) {
+ const titles = useMarkdownSessionLinkTitles(text);
+ renders();
+ return <span>{JSON.stringify(titles)}</span>;
+ }
+ try {
+ act(() => root.render(<Titles text="plain text" />));
+ expect(subscribe).not.toHaveBeenCalled();
+ act(() => root.render(<Titles text={`cindy://session/${first}`} />));
+ expect(host.textContent).toContain('First');
+ act(() => root.render(<Titles text={`cindy://session/${second}`} />));
+ renders.mockClear();
+ act(() => remoteSessionStore.applySessionPatch('computer', first, { title: 'Old link renamed' }));
+ expect(renders).not.toHaveBeenCalled();
+ expect(host.textContent).toContain('Second');
+ act(() => remoteSessionStore.applySessionPatch('computer', second, { title: 'New title' }));
+ expect(host.textContent).toContain('New title');
+ act(() => root.render(<Titles text="plain again" />));
+ renders.mockClear();
+ act(() => remoteSessionStore.applySessionPatch('computer', second, { title: 'Later' }));
+ expect(renders).not.toHaveBeenCalled();
+ } finally {
+ subscribe.mockRestore();
+ }
});
});
diff --git a/apps/mobile/src/__tests__/mobileBabelTransform.test.ts b/apps/mobile/src/__tests__/mobileBabelTransform.test.ts
new file mode 100644
index 0000000000..070b0ddf77
--- /dev/null
+++ b/apps/mobile/src/__tests__/mobileBabelTransform.test.ts
@@ -0,0 +1,48 @@
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import { afterEach, expect, it, vi } from 'vitest';
+
+const require = createRequire(import.meta.url);
+const config = require('../../metro.config.js');
+const transformer = require(config.transformer.babelTransformerPath);
+const generate = require('@babel/generator').default;
+const projectRoot = path.resolve(__dirname, '../..');
+
+afterEach(() => vi.unstubAllEnvs());
+
+function compileWorklet(dev: boolean) {
+ const { ast } = transformer.transform({
+ // The Worklets development transform reads this file for its source map.
+ filename: __filename,
+ src: "function calculate() { 'worklet'; return 42; }",
+ options: {
+ dev, platform: 'ios', projectRoot, enableBabelRCLookup: true,
+ customTransformOptions: { engine: 'hermes' },
+ },
+ plugins: [],
+ });
+ return new Function(`${generate(ast).code}; return calculate;`)();
+}
+
+it('release worklets omit debug allocations even when the build inherits development variables', () => {
+ vi.stubEnv('NODE_ENV', 'development');
+ vi.stubEnv('BABEL_ENV', 'development');
+ const worklet = compileWorklet(false);
+ expect(worklet()).toBe(42);
+ expect(worklet.__workletHash).toEqual(expect.any(Number));
+ expect(worklet.__stackDetails).toBeUndefined();
+ expect(worklet.__initData.sourceMap).toBeUndefined();
+ expect(process.env.NODE_ENV).toBe('development');
+ expect(process.env.BABEL_ENV).toBe('development');
+});
+
+it('development worklets retain debugging even when the parent environment says production', () => {
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.stubEnv('BABEL_ENV', 'production');
+ const worklet = compileWorklet(true);
+ expect(worklet()).toBe(42);
+ expect(worklet.__stackDetails[0]).toBeInstanceOf(Error);
+ expect(worklet.__initData.sourceMap).toEqual(expect.any(String));
+ expect(process.env.NODE_ENV).toBe('production');
+ expect(process.env.BABEL_ENV).toBe('production');
+});
diff --git a/apps/mobile/src/__tests__/pendingSendActionsRender.test.tsx b/apps/mobile/src/__tests__/pendingSendActionsRender.test.tsx
new file mode 100644
index 0000000000..a674914dfc
--- /dev/null
+++ b/apps/mobile/src/__tests__/pendingSendActionsRender.test.tsx
@@ -0,0 +1,93 @@
+// @vitest-environment jsdom
+import React, { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { expect, it, vi } from 'vitest';
+import { remoteSessionStore } from '@/session/remoteSessionStore';
+import type { PendingSendBubbleActions } from '@/session/PendingSendBubble';
+
+// Unit regression: execute the page's real callbacks/memo with React. Native
+// transport and composer boundaries are substituted, not the callback bodies.
+const source = ts.createSourceFile('page.tsx', readFileSync(resolve(process.cwd(),
+ 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const names = ['findDurableOutboxRecord', 'retryOutboxItem', 'removeOutboxItem',
+ 'steerQueueItem', 'removeQueueItem', 'beginQueueEdit', 'pendingSendActions'];
+const declarations = new Map<string, ts.VariableDeclaration>();
+function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && names.includes(node.name.getText(source))) {
+ declarations.set(node.name.getText(source), node);
+ }
+ ts.forEachChild(node, visit);
+}
+visit(source);
+const code = names.map(name => {
+ const node = declarations.get(name);
+ if (!node) throw new Error(`Missing production declaration: ${name}`);
+ return `const ${node.getText(source)};`;
+}).join('\n');
+
+it('retains actions on unrelated renders, but uses current task and edit guards after changes', async () => {
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+ const records = [
+ { deviceId: 'pc', state: 'failed', item: { sessionId: 'a', clientId: 'send' } },
+ { deviceId: 'pc', state: 'failed', item: { sessionId: 'b', clientId: 'send' } },
+ ];
+ const setError = vi.fn();
+ const update = vi.fn().mockResolvedValue(undefined);
+ const bindings = {
+ useCallback: React.useCallback, useMemo: React.useMemo, remoteSessionStore,
+ deviceId: 'pc', deviceName: 'Computer', router: {},
+ getCurrentMobileOutboxRecords: () => records, mobileDurableOutbox: { update },
+ setError, formatRemoteError: String, t: (key: string) => key,
+ queueSelectedClientId: null, setQueueSelectedClientId: vi.fn(),
+ moveQueueItem: vi.fn(), maker: {}, invoke: vi.fn(),
+ runQueueAction: vi.fn(), runOptimisticQueueAction: vi.fn(), showTransientNotice: vi.fn(),
+ applyComposerDocument: vi.fn(), discardQueueEditTransientAttachments: vi.fn(),
+ setQueueEditLock: vi.fn(), queueEditSaveInFlightRef: { current: null },
+ };
+ const compiled = ts.transpileModule(`return function Probe({ sessionId, queueBusy, pendingUploads, queueAvailabilityReason, capture }) {
+ ${code}
+ capture(pendingSendActions);
+ return null;
+ }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const Probe = new Function(...Object.keys(bindings), compiled)(...Object.values(bindings));
+ const root = createRoot(document.createElement('div'));
+ let actions!: PendingSendBubbleActions;
+ const capture = (value: PendingSendBubbleActions) => { actions = value; };
+ const show = (sessionId = 'a', queueBusy = false, pendingUploads: unknown[] = [], queueAvailabilityReason: string | null = null) =>
+ act(() => root.render(<Probe {...{ sessionId, queueBusy, pendingUploads, queueAvailabilityReason, capture }} />));
+ remoteSessionStore.clear();
+ try {
+ show();
+ const initial = actions;
+ for (let n = 0; n < 30; n += 1) show();
+ expect(actions).toBe(initial);
+ await act(async () => actions.onRetryOutbox?.('send'));
+ expect(update).toHaveBeenLastCalledWith(records[0], expect.objectContaining({ state: 'queued' }));
+ show('b');
+ await act(async () => actions.onRetryOutbox?.('send'));
+ expect(update).toHaveBeenLastCalledWith(records[1], expect.objectContaining({ state: 'queued' }));
+ remoteSessionStore.setInputProjection('b', {
+ ...remoteSessionStore.getInputProjection('b'),
+ pendingQueue: [{ clientId: 'queued', text: 'message', persistedContent: 'message',
+ model: 'model', workingDir: '/synthetic', createOpts: {}, chatMessage: { role: 'user' } }],
+ });
+ show('b', false, [{}]);
+ actions.onBeginEdit?.('queued');
+ expect(setError).toHaveBeenLastCalledWith('session.screen.attachmentsUploadingBeforeEdit');
+ setError.mockClear();
+ show('b', true, [{}]);
+ expect(actions.busy).toBe(true);
+ actions.onBeginEdit?.('queued');
+ expect(setError).not.toHaveBeenCalled();
+ show('b', false, [{}], 'offline');
+ actions.onBeginEdit?.('queued');
+ expect(setError).not.toHaveBeenCalled();
+ } finally {
+ act(() => root.unmount());
+ remoteSessionStore.clear();
+ Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
+ }
+});
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 5ea18cd7d8..b9e9883643 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -685,6 +685,29 @@ describe('remoteSessionStore', () => {
expect(remoteSessionStore.getHomeSessions()[0].title).toBe('Restored title');
});
+ it('keeps metadata patches on the canonical shard and preserves hidden rows and usage projection', () => {
+ remoteSessionStore.setDeviceIdentity([{ deviceId: 'current', name: 'Mac' }]);
+ remoteSessionStore.setDeviceSessions('stale', 'Mac', [session('s1', { title: 'Stale' })]);
+ remoteSessionStore.setDeviceSessions('current', 'Mac', [session('s1'), session('s2')]);
+ const other = remoteSessionStore.getHomeSessions()[1];
+ const before = remoteSessionStore.getSessions()[0];
+ remoteSessionStore.applySessionPatch('stale', 's1', { title: 'Wrong', updatedAt: '2026-02-01T00:00:00Z' });
+ expect(remoteSessionStore.getSessions()[0]).toBe(before);
+ expect(remoteSessionStore.getSessionDeviceId('s1')).toBe('current');
+ const finishPreview = remoteSessionStore.beginSessionListRemovalPreview('s1');
+ remoteSessionStore.applySessionPatch('current', 's1', {
+ title: 'Renamed', updatedAt: '2026-02-02T00:00:00Z', totalTokenUsage: 500,
+ });
+ expect(remoteSessionStore.getHomeSessions()).toEqual([other]);
+ expect(remoteSessionStore.getSessions()[0]).toMatchObject({ title: 'Renamed', totalTokenUsage: 500 });
+ finishPreview();
+ expect(remoteSessionStore.getHomeSessions()[0]).toMatchObject({
+ title: 'Renamed', updatedAt: '2026-02-02T00:00:00Z', canonicalDeviceId: 'current',
+ });
+ expect(remoteSessionStore.getHomeSessions()[0]).not.toHaveProperty('totalTokenUsage');
+ expect(remoteSessionStore.getHomeSessions()[1]).toBe(other);
+ });
+
it('removes archived sessions from the active mirror', () => {
remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1'), session('s2')]);
remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'archived' });
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 5813ff8ae2..af4ac27319 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -263,7 +263,6 @@ import { ChatPathChipSpan } from '@/session/ChatPathChipSpan';
import {
useRemoteDeviceIdentity,
useRemoteSessionMessages,
- useRemoteSessions,
} from '@/session/remoteSessionStore';
import {
isCrossDeviceSourceSessionId,
@@ -5997,8 +5996,7 @@ function MarkdownBodyBase({
}, [layout, managedImagePreviewUrl, onOpenPayload, openMarkdownImage, resolveMarkdownMedia]);
// Preserve the inline renderer while streaming or unrelated task metadata
// changes; referenced task title changes still refresh every affected chip.
- const remoteSessions = useRemoteSessions();
- const sessionLinkTitles = useMarkdownSessionLinkTitles(text, remoteSessions);
+ const sessionLinkTitles = useMarkdownSessionLinkTitles(text);
const renderInlines = useCallback(
(
inlines: readonly MobileMarkdownInline[],
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index aa71053370..1b93e86f84 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -1436,6 +1436,9 @@ const mergedSessionById = new Map<string, RemoteSession>();
// live usage. Usage pushes must not rebuild Home's grouping/localization tree.
let homeSessions: RemoteSession[] = [];
const SESSION_USAGE_FIELDS = new Set(['totalMoney', 'totalCostUsd', 'totalTokenUsage']);
+// These fields cannot change shard ownership, visibility or retention. Timestamps
+// still update this task's live-row anchor; titles still reconcile local previews.
+const SESSION_METADATA_FIELDS = new Set([...SESSION_USAGE_FIELDS, 'title', 'updatedAt', 'userSendAt']);
const homeSessionProjectionCache = new Map<string, {
source: RemoteSession;
projected: RemoteSession;
@@ -3731,6 +3734,26 @@ export const remoteSessionStore = {
emit();
return;
}
+ if (Object.keys(patch).every((key) => SESSION_METADATA_FIELDS.has(key))) {
+ const previous = mergedSessionById.get(sessionId);
+ if (previous && sessionDeviceIndex.get(sessionId) === deviceId) {
+ const updated = applyPendingTitlePreview({ ...patched, canonicalDeviceId: previous.canonicalDeviceId });
+ if (!remoteSessionEqual(previous, updated)) {
+ mergedSessions = mergedSessions.map((session) => session.id === sessionId ? updated : session);
+ mergedSessionById.set(sessionId, updated);
+ pendingMessagePreviewSessionIds.add(sessionId);
+ reconcileVisibleSessions();
+ reconcileHomeSessions();
+ }
+ bindPendingHostAnchorSendAt(sessionId, updated.userSendAt);
+ if (reanchorPendingLiveAssistantRows(sessionId,
+ updated.userSendAt ?? updated.updatedAt ?? updated.createdAt, { consumePending: false })) {
+ bumpMessageVersion();
+ }
+ }
+ emit();
+ return;
+ }
shouldReseedAfterPatch = wasPinned && unpinned;
}
recomputeSessions();
@@ -6287,6 +6310,26 @@ export function useRemoteSessions(): RemoteSession[] {
return usePausableRemoteSessionStoreSnapshot('sessions', remoteSessionStore.getVisibleSessions);
}
+/** Link chips observe only their visible targets, not every task's activity. */
+export function useRemoteSessionTitles(ids: readonly string[]): Record<string, string> | undefined {
+ const read = useCallback(() => {
+ if (ids.length === 0) return undefined;
+ const sessions = remoteSessionStore.getVisibleSessions();
+ const titles: Record<string, string> = {};
+ for (const id of ids) {
+ const title = sessions.find((session) => session.id === id)?.title?.trim();
+ if (title) titles[id] = title;
+ }
+ return Object.keys(titles).length > 0 ? JSON.stringify(titles) : undefined;
+ }, [ids]);
+ // A primitive snapshot stays equal on unrelated pushes. Reuse the route's
+ // subscription gate so covered conversations remain frozen until resumed.
+ const json = usePausableRemoteSessionStoreSnapshot(
+ read, read, ids.length > 0 ? remoteSessionStore.subscribe : NOOP_SUBSCRIBE,
+ );
+ return useMemo(() => json === undefined ? undefined : JSON.parse(json) as Record<string, string>, [json]);
+}
+
/** A hidden child can be opened without making it an ordinary Home list row. */
export function useRemoteSessionDetail(deviceId: string, sessionId: string): RemoteSession | null {
const read = useCallback(() => remoteSessionStore.getSessions().find(session =>
diff --git a/apps/mobile/src/session/useMarkdownSessionLinkTitles.ts b/apps/mobile/src/session/useMarkdownSessionLinkTitles.ts
index 1a41d68a20..ca042971ad 100644
--- a/apps/mobile/src/session/useMarkdownSessionLinkTitles.ts
+++ b/apps/mobile/src/session/useMarkdownSessionLinkTitles.ts
@@ -1,23 +1,12 @@
import { useMemo } from 'react';
import { extractSessionLinkIds } from '@/session/sessionLinks';
+import { useRemoteSessionTitles } from '@/session/remoteSessionStore';
/** Stable render context: only a referenced title changing invalidates spans. */
export function useMarkdownSessionLinkTitles(
text: string,
- sessions: readonly { id: string; title?: string | null }[],
): Record<string, string> | undefined {
const idsJson = useMemo(() => JSON.stringify(extractSessionLinkIds(text)), [text]);
- const titlesJson = useMemo(() => {
- const ids = JSON.parse(idsJson) as string[];
- if (ids.length === 0) return undefined;
- const titles: Record<string, string> = {};
- for (const id of ids) {
- const title = sessions.find((session) => session.id === id)?.title?.trim();
- if (title) titles[id] = title;
- }
- return Object.keys(titles).length > 0 ? JSON.stringify(titles) : undefined;
- }, [idsJson, sessions]);
- return useMemo(() => titlesJson === undefined
- ? undefined
- : JSON.parse(titlesJson) as Record<string, string>, [titlesJson]);
+ const ids = useMemo(() => JSON.parse(idsJson) as string[], [idsJson]);
+ return useRemoteSessionTitles(ids);
}
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index 26398db5e1..de98af658e 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -91,6 +91,12 @@ JSON 已包含 `worktree` / `expectedSource`、`region` / `bundleId`、目标设
## 分层验证
+Release 构建必须使用 `NODE_ENV=production BABEL_ENV=production`,包括手动调用
+`xcodebuild`、Gradle 或 `expo export:embed --dev false`。Expo 会保留父进程的环境变量,
+因此 `__DEV__=false` 或 Xcode 的 Release 配置本身不能证明 Worklets 已按生产模式编译。
+仓库 iOS/Android 构建脚本会固定这两个变量;Metro 的 Babel transformer 另按每次请求的
+`dev` 标志统一编译模式,防止外部开发环境把动画调试堆栈编进 Release 包,同时保留开发包调试能力。
+
```bash
pnpm --filter mobile typecheck
pnpm --filter mobile exec vitest run <测试文件路径>
diff --git a/scripts/__tests__/client-endpoint-build-env.test.mjs b/scripts/__tests__/client-endpoint-build-env.test.mjs
index 299932159e..2db9fd1f04 100644
--- a/scripts/__tests__/client-endpoint-build-env.test.mjs
+++ b/scripts/__tests__/client-endpoint-build-env.test.mjs
@@ -66,6 +66,8 @@ test('Mobile bundling 进程环境只在 CindyDev 保留 Release 清单基址',
const repoRoot = writeRepoFixtures();
const staleBaseEnv = {
KEEP_ME: '1',
+ NODE_ENV: 'development',
+ BABEL_ENV: 'development',
EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL:
'https://stale-release.example.invalid/app',
};
@@ -76,6 +78,9 @@ test('Mobile bundling 进程环境只在 CindyDev 保留 Release 清单基址',
repoRoot,
});
assert.equal(cn.KEEP_ME, '1');
+ assert.equal(cn.NODE_ENV, 'production');
+ assert.equal(cn.BABEL_ENV, 'production');
+ assert.equal(staleBaseEnv.NODE_ENV, 'development');
assert.equal(
Object.hasOwn(
cn,
@@ -89,6 +94,8 @@ test('Mobile bundling 进程环境只在 CindyDev 保留 Release 清单基址',
baseEnv: staleBaseEnv,
repoRoot,
});
+ assert.equal(dev.NODE_ENV, 'production');
+ assert.equal(dev.BABEL_ENV, 'production');
assert.equal(
dev.EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL,
'https://hotfix-cn.example.invalid/app',
diff --git a/scripts/shared/client-endpoint-build-env.mjs b/scripts/shared/client-endpoint-build-env.mjs
index 99124c6a93..5d433b3394 100644
--- a/scripts/shared/client-endpoint-build-env.mjs
+++ b/scripts/shared/client-endpoint-build-env.mjs
@@ -156,7 +156,10 @@ export function mobileClientBundleProcessEnv({
repoRoot,
} = {}) {
const bundleEnv = mobileClientBundleEnv({ authRegion, repoRoot });
- const env = { ...baseEnv, ...bundleEnv };
+ // These callers build installable iOS/Android Release bundles. Region "dev"
+ // selects endpoints, not Babel's build mode. Do not inherit an agent/server's
+ // development environment into the production Worklets transform.
+ const env = { ...baseEnv, ...bundleEnv, NODE_ENV: 'production', BABEL_ENV: 'production' };
if (bundleEnv.EXPO_PUBLIC_CINDY_AUTH_REGION !== 'dev') {
delete env.EXPO_PUBLIC_CINDY_DEV_RELEASE_ENDPOINT_MANIFEST_BASE_URL;
}