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): 修复 Android 宽屏抽屉切换崩溃与白屏 (#2270)

Chris Zhang25e2632c9cfd
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 3182c9b99e..545ca3a329 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -418,6 +418,10 @@ import { useRemoteScheduleEventSnapshot } from '@/scheduler/remoteScheduleEvents
import { buildSessionNativeShellLayout } from '@/session/mobileNativeShellLayout';
import { buildWideSessionNavLayout } from '@/session/wideSessionNav';
import { SessionListDrawer } from '@/session/SessionListDrawer';
+import {
+ switchDrawerSessionInPlace,
+ type SessionRouteParamsNavigation,
+} from '@/session/sessionDrawerNavigation';
import type { RemoteSessionListItem } from '@/session/sessionList';
import {
findMobileMessageSearchHits,
@@ -733,6 +737,38 @@ function restoreRecoverableItemsToDraft(
}
}
+interface ImmediateComposerDraftScope {
+ document: ComposerDocument;
+ ordered: ReturnType<typeof resolveOrderedQuoteDraft>;
+ quotes: ReturnType<typeof getQuotes>;
+}
+
+/**
+ * 当前任务首帧可同步取得的 composer 真相。AsyncStorage 尚未 hydrate 时宁可返回
+ * 当前任务空态,也不能让复用的 SessionScreen 把上一任务文档交给新任务编辑器。
+ */
+function readImmediateComposerDraftScope(
+ sessionId: string,
+ routeDraft: string | null,
+): ImmediateComposerDraftScope {
+ const visibleText = readComposerDraftSync(sessionId) ?? routeDraft ?? '';
+ const quotes = getQuotes(sessionId);
+ const ordered = resolveOrderedQuoteDraft(sessionId, visibleText, quotes);
+ const storedDocument = readComposerDocumentDraftSync(sessionId);
+ let document = storedDocument
+ ?? migrateLegacyComposerDraft(visibleText, quotes, ordered?.encodedBody);
+ if (storedDocument) {
+ for (const quote of quotes) {
+ document = appendComposerNode(document, { type: 'quote', quote });
+ }
+ }
+ return { document, ordered, quotes };
+}
+
+function composerDraftScopeKey(sessionId: string, routeDraft: string | null): string {
+ return JSON.stringify([sessionId, routeDraft ?? '']);
+}
+
export default function SessionScreen() {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
@@ -768,7 +804,7 @@ export default function SessionScreen() {
const visualFocusComposer = MOBILE_VISUAL_MOCK_ENABLED && readRouteParam(params.visualFocusComposer) === '1';
const visualOpenSearch = MOBILE_VISUAL_MOCK_ENABLED && readRouteParam(params.visualOpenSearch) === '1';
const visualSearchQuery = MOBILE_VISUAL_MOCK_ENABLED ? readRouteParam(params.visualSearchQuery) : null;
- const navigation = useNavigation();
+ const navigation = useNavigation<SessionRouteParamsNavigation & { isFocused(): boolean }>();
const router = useRouter();
const auth = useAuth();
const windowDimensions = useWindowDimensions();
@@ -797,9 +833,33 @@ export default function SessionScreen() {
const makerTurnRunning = useSessionMakerTurnRunning(sessionId);
const remoteSessionRunStatus = useSessionRunStatus(sessionId);
const taskUpdates = useSessionTaskUpdates(sessionId);
- const [draft, setDraft] = useState('');
- const [composerDocument, setComposerDocumentState] = useState<ComposerDocument>(emptyComposerDocument);
+ const activeComposerDraftScopeKey = composerDraftScopeKey(sessionId, routeDraft);
+ const [composerDraftStateKey, setComposerDraftStateKey] = useState(activeComposerDraftScopeKey);
+ const [composerDocument, setComposerDocumentState] = useState<ComposerDocument>(
+ () => readImmediateComposerDraftScope(sessionId, routeDraft).document,
+ );
+ const [draft, setDraft] = useState(() => composerDocumentProjectedText(composerDocument));
const [composerDraftHydrated, setComposerDraftHydrated] = useState(false);
+ const appliedRouteDraftRef = useRef<string | null>(null);
+ const draftRef = useRef(draft);
+ const composerDocumentRef = useRef<ComposerDocument>(composerDocument);
+ // replaceParams 复用同一 SessionScreen。任务参数变化的这次 render 仍拿着 A 的
+ // state;若直接让 key={sessionId} 子树挂载,B 编辑器会先用 A 文档初始化,再等
+ // 被动 effect 水合纠正。沿本页 read-ack 的 render-phase 换代模式同步种入 B 的
+ // 内存快照(冷缓存未 hydrate 时为空),React 会丢弃本次旧输出后重渲。
+ if (composerDraftStateKey !== activeComposerDraftScopeKey) {
+ const nextScope = readImmediateComposerDraftScope(sessionId, routeDraft);
+ const nextDraft = composerDocumentProjectedText(nextScope.document);
+ setComposerDraftStateKey(activeComposerDraftScopeKey);
+ setComposerDocumentState(nextScope.document);
+ setDraft(nextDraft);
+ setComposerDraftHydrated(false);
+ // 旧 A 的 AsyncStorage promise 可能在 effect cleanup 前落定;先让它的 key 失配。
+ // 保持 null 也确保 B 的 effect 仍会继续异步 hydrate 磁盘草稿与冷启动引用。
+ appliedRouteDraftRef.current = null;
+ composerDocumentRef.current = nextScope.document;
+ draftRef.current = nextDraft;
+ }
// chat-text-quote:待随下一条消息发送的选中文字引用(全局 store,消息流选区
// 按钮 / 文件预览页写入;发送时拼进正文,命中本地命令时保留)。
const quotes = useSessionQuotes(sessionId);
@@ -869,7 +929,7 @@ export default function SessionScreen() {
setContextSheetOpen(true);
}
}, [goalError]);
- // goal 接回载荷按任务换代清理(codex review P2):任务抽屉 router.replace 原地
+ // goal 接回载荷按任务换代清理(codex review P2):任务抽屉 replaceParams 原地
// 更新同一 SessionScreen 实例,goalRestore/goalError 只在首次挂载初始化——切
// 任务后残留会让新任务的 Goal 表单预填旧任务的 objective/limits,甚至把旧目标
// 提交到新任务。prevSessionIdRef 与当前 sessionId 同步初始化:首次挂载
@@ -901,6 +961,7 @@ export default function SessionScreen() {
removePendingUpload,
retryPendingUpload,
discardAllPendingUploads,
+ discardAllPendingUploadsForScopeChange,
waitForPendingUploads,
claimActiveUploads,
releaseClaimedUploads,
@@ -908,6 +969,7 @@ export default function SessionScreen() {
hasPastePlaceholders,
getPendingUploadCount,
} = useMobileLocalAttachments({
+ attachmentScopeKey: sessionId,
getAccessToken: () => auth.getAccessToken(),
getAttachmentCount: () => attachmentsRef.current.length,
onUploaded: (rawAttachment, candidate, localId) => {
@@ -1003,12 +1065,61 @@ export default function SessionScreen() {
const [queueEditing, setQueueEditing] = useState<QueueEditingState | null>(null);
const queueEditingRef = useRef<QueueEditingState | null>(null);
// 会话切换 cleanup(声明在前)引用组件后段的回收函数,经 ref 断开声明顺序依赖。
- const discardQueueEditTransientAttachmentsRef = useRef<
- ((editing: QueueEditingState, attachmentsAtExit?: readonly RemoteSerializedAttachment[]) => void) | null
+ const discardQueueEditTransientAttachmentResourcesRef = useRef<
+ ((editing: QueueEditingState, attachmentsAtExit: readonly RemoteSerializedAttachment[]) => void) | null
>(null);
// 排队编辑保存(update-content RPC)在途 promise:会话切换 cleanup 据此把解锁
// 排到保存落定之后,防止 device-link 并发下解锁超车、桌面端用旧内容抢先派发。
const queueEditSaveInFlightRef = useRef<Promise<void> | null>(null);
+ // 保存中的排队编辑切任务时,composer 必须立即清空,但附件回收不能抢在
+ // update-content 落定前。先保存 A 的托盘快照,交给 A 的 cleanup 延后判断。
+ const queueEditScopeExitAttachmentsRef = useRef<{
+ clientId: string;
+ attachments: RemoteSerializedAttachment[];
+ } | null>(null);
+ // 当前 session 的 composer 附件是页面实例级 state;replaceParams 原地切任务不会
+ // 自动卸载它们。状态 / OSS 回收走 ref 读取最新快照;上传代际封口必须由调用方
+ // 使用旧 session render 捕获的方法执行,不能在 cleanup 时误封新 session。
+ const discardSessionComposerAttachmentStateRef = useRef<() => void>(() => undefined);
+ discardSessionComposerAttachmentStateRef.current = () => {
+ // 排队编辑时 composer 正展示队列条目的 files,用户原本未发送的附件在 stash。
+ // 两批都属于 A;切到 B 时都不能恢复或复用。对非 OSS 的队列文件 discard 是 no-op。
+ const editing = queueEditingRef.current;
+ const currentAttachments = [...attachmentsRef.current];
+ const deferQueueEditAttachments = !!editing && !!queueEditSaveInFlightRef.current;
+ if (editing && deferQueueEditAttachments && currentAttachments.length > 0) {
+ queueEditScopeExitAttachmentsRef.current = {
+ clientId: editing.clientId,
+ attachments: currentAttachments,
+ };
+ }
+ const attachmentsById = new Map<string, RemoteSerializedAttachment>();
+ // 保存中的当前托盘可能马上成为队列条目的正式 files;由旧 session cleanup
+ // 等保存落定后再区分“已保存”与“编辑期临时新增”,这里不能提前 DELETE。
+ if (!deferQueueEditAttachments) {
+ for (const attachment of currentAttachments) attachmentsById.set(attachment.id, attachment);
+ }
+ for (const attachment of editing?.stashedAttachments ?? []) {
+ attachmentsById.set(attachment.id, attachment);
+ }
+ attachmentsRef.current = [];
+ setAttachments([]);
+ setAttachmentPreviews({});
+ setMediaAssetAttachments({});
+ setPendingMediaAssets([]);
+ setComposerPreviewAttachmentId(null);
+ setAttachmentError(null);
+ composerAnnotationsRef.current?.forgetAllAttachments();
+ for (const attachment of attachmentsById.values()) {
+ discardMobileUploadedAttachment(attachment, { getToken: () => auth.getAccessToken() });
+ }
+ };
+ // 抽屉入口会在 replaceParams 前同步调用;这里仍保留 sessionId / 卸载兜底,覆盖
+ // 其它原地换代入口。effect 捕获本次 render 的 scope-change 方法,A cleanup 只封 A。
+ useEffect(() => () => {
+ discardAllPendingUploadsForScopeChange();
+ discardSessionComposerAttachmentStateRef.current();
+ }, [discardAllPendingUploadsForScopeChange, sessionId]);
const queueEditLockOwnerRef = useRef<QueueEditLockOwner | null>(null);
const queueEditSaveOwnerRef = useRef<QueueEditLockOwner | null>(null);
// 「已出队、消息尚未回流」的落定中条目:桌面端 drain 会先从 pendingQueue 摘除、
@@ -1247,9 +1358,6 @@ export default function SessionScreen() {
setReadAckSyncedKey(null);
readAckGateGenRef.current += 1;
}
- const appliedRouteDraftRef = useRef<string | null>(null);
- const draftRef = useRef('');
- const composerDocumentRef = useRef<ComposerDocument>(emptyComposerDocument());
// 远程媒体取件队列:屏实例级缓存 + 同 url 去重 + 并发上限(每次取件都让桌面端
// 真实上传一次 OSS,列表缩略图懒取件后必须收敛)。deps 经 ref 透传保持队列实例稳定;
// 队列生命周期 = 单个会话:切 sessionId / 退屏时 releaseAll + 补删 + 换新实例
@@ -2017,7 +2125,7 @@ export default function SessionScreen() {
screenWidth: windowDimensions.width,
}), [windowDimensions.width]);
// 宽屏导航形态(iPad / 安卓折叠屏与横屏大屏机):左上角三条杠 + 任务列表抽屉,
- // 原地 replace 切任务;窄屏保持传统返回键。断点与按平台分闸(iOS 仅 iPad,
+ // 原地替换当前路由参数切任务;窄屏保持传统返回键。断点与按平台分闸(iOS 仅 iPad,
// iPhone 不发)见 wideSessionNav.ts。
const wideSessionNav = useMemo(() => buildWideSessionNavLayout({
iosPad: Platform.OS === 'ios' && Platform.isPad,
@@ -2110,18 +2218,22 @@ export default function SessionScreen() {
Alert.alert(t('devices.list.error.sessionDeviceNotFound'));
return;
}
- // replace 而非 push:抽屉是「原地切换」语义,栈保持 [主页, 会话],返回手势仍回主页。
+ // 不派发 NativeStack REPLACE:它会创建新 route key 并走 Android 原生 Screen 替换,
+ // 上次仅延后到抽屉卸载后仍未消除 crash / 白屏。当前 SessionScreen 已完整支持
+ // sessionId 原地换代,replaceParams 保持栈与 native Screen 不动,并整包替换 params
+ // 以清掉旧任务的 draft / goal / focus 等一次性参数。
queueDrawerNavigation(() => {
- router.replace({
- pathname: '/sessions/[sessionId]',
- params: {
- deviceId: targetDeviceId,
- deviceName: targetSession.deviceLinkDeviceName ?? targetDeviceId,
- sessionId: targetSession.id,
- },
+ // 必须早于 replaceParams:同一同步段先清 A 的附件与在途上传,再让页面看到 B。
+ // 否则上传完成回调会经 optionsRef 的最新闭包把 A 的产物追加进 B 的 composer。
+ discardAllPendingUploadsForScopeChange();
+ discardSessionComposerAttachmentStateRef.current();
+ switchDrawerSessionInPlace(navigation, {
+ deviceId: targetDeviceId,
+ deviceName: targetSession.deviceLinkDeviceName ?? targetDeviceId,
+ sessionId: targetSession.id,
});
});
- }, [closeSessionListDrawer, queueDrawerNavigation, router, sessionId, t]);
+ }, [closeSessionListDrawer, navigation, queueDrawerNavigation, sessionId, t]);
// 前进导航防连点:快速双击「新建」会把 /sessions/new 压栈两层(返回要退两次),
// 与首页各入口同一把 guardedPush 锁。
const guardedPush = useGuardedPush();
@@ -2602,18 +2714,30 @@ export default function SessionScreen() {
// 回收是 no-op;失败时才真正清理。附件快照在此刻捕获:落定回调执行时
// attachmentsRef 可能已属于新会话。
const inFlightSave = queueEditSaveInFlightRef.current;
- const attachmentsSnapshot = [...attachmentsRef.current];
+ const scopeExitSnapshot = queueEditScopeExitAttachmentsRef.current;
+ if (scopeExitSnapshot?.clientId === editing.clientId) {
+ queueEditScopeExitAttachmentsRef.current = null;
+ }
+ const attachmentsSnapshot = scopeExitSnapshot?.clientId === editing.clientId
+ ? scopeExitSnapshot.attachments
+ : [...attachmentsRef.current];
+ // ref 会在 B 的 effect 中更新成 B session 的实现;延迟回调必须捕获 A 的
+ // 资源回收函数值,否则保存落定后会拿 B 的 pendingQueue 判断 A 的附件归属。
+ // 这里只回收 A 的附件快照:A 的 pending uploads 已由 replaceParams 前的
+ // scope-change 封口清掉,迟到 finalize 绝不能再碰组件级 controller 或 B state。
+ const discardQueueEditTransientAttachmentResources =
+ discardQueueEditTransientAttachmentResourcesRef.current;
const finalize = () => {
- discardQueueEditTransientAttachmentsRef.current?.(editing, attachmentsSnapshot);
+ discardQueueEditTransientAttachmentResources?.(editing, attachmentsSnapshot);
};
if (lockOwner) void releaseQueueEditLockAfter(lockOwner, inFlightSave).catch(() => undefined);
if (inFlightSave) void inFlightSave.then(finalize, finalize);
else finalize();
- // 托盘不是 per-session 状态:编辑中切会话若不还原,队列条目的 files 会跟进
- // 新会话、用户原托盘丢失(review P2)。回收目标已在上方快照捕获,这里同步
- // 还原 stash 不影响 finalize 的清理。
- attachmentsRef.current = [...editing.stashedAttachments];
- setAttachments([...editing.stashedAttachments]);
+ // 托盘不是 per-session 状态:编辑中切会话时既不能让队列条目的 files 跟进
+ // 新任务,也不能把 A 的 stash 恢复到 B。A 的两批附件由统一换代入口回收,
+ // 这里仅保持共享托盘为空。
+ attachmentsRef.current = [];
+ setAttachments([]);
}
}, [sessionId]);
@@ -2654,22 +2778,15 @@ export default function SessionScreen() {
}, [composerShowSendButton]);
useEffect(() => {
- const key = `${sessionId}:${routeDraft ?? ''}`;
+ const key = activeComposerDraftScopeKey;
if (appliedRouteDraftRef.current === key) return;
appliedRouteDraftRef.current = key;
setComposerDraftHydrated(false);
let cancelled = false;
- const immediateDraft = readComposerDraftSync(sessionId) ?? routeDraft ?? '';
- const immediateQuotes = getQuotes(sessionId);
- const immediateOrdered = resolveOrderedQuoteDraft(sessionId, immediateDraft, immediateQuotes);
- const immediateStoredDocument = readComposerDocumentDraftSync(sessionId);
- let immediateDocument = immediateStoredDocument
- ?? migrateLegacyComposerDraft(immediateDraft, immediateQuotes, immediateOrdered?.encodedBody);
- if (immediateStoredDocument) {
- for (const quote of immediateQuotes) {
- immediateDocument = appendComposerNode(immediateDocument, { type: 'quote', quote });
- }
- }
+ const immediateScope = readImmediateComposerDraftScope(sessionId, routeDraft);
+ const immediateQuotes = immediateScope.quotes;
+ const immediateDocument = immediateScope.document;
+ const immediateOrdered = immediateScope.ordered;
applyComposerDocument(immediateDocument, { persist: false });
const immediateDocumentSnapshot = immediateDocument;
// Synchronously consumed quote-store items are already in the first paint.
@@ -2730,7 +2847,7 @@ export default function SessionScreen() {
cancelled = true;
void flushComposerDraftWrites(sessionId);
};
- }, [applyComposerDocument, routeDraft, sessionId]);
+ }, [activeComposerDraftScopeKey, applyComposerDocument, routeDraft, sessionId]);
useEffect(() => {
if (!composerDraftHydrated || quotes.length === 0) return;
@@ -6234,17 +6351,10 @@ export default function SessionScreen() {
* 队列条目自身 files 不回收——仍被条目引用,且 enqueue 时已物化为被控端本地
* 路径,discard 对非 OSS 引用本就是 no-op,双保险。
*/
- const discardQueueEditTransientAttachments = useCallback((
+ const discardQueueEditTransientAttachmentResources = useCallback((
editing: QueueEditingState,
- // 会话切换 cleanup 传当时的托盘快照(落定回调执行时 attachmentsRef 可能已属于
- // 新会话);常规退出路径省略,取当前托盘。
- attachmentsAtExit: readonly RemoteSerializedAttachment[] = attachmentsRef.current,
+ attachmentsAtExit: readonly RemoteSerializedAttachment[],
) => {
- // 编辑期间发起、此刻仍在途的上传一并丢弃:进入编辑有 pendingUploads 为空的门槛,
- // 因此退出时的在途任务必然是编辑期新增——不丢弃的话,任务完成后 onUploaded 会把
- // 已被放弃的附件追加进恢复后的原草稿托盘(review P1)。removeAll 语义:不再回调、
- // 完成后回收 OSS。保存路径在 waitForPendingUploads 落定后才走到这里,天然 no-op。
- discardAllPendingUploads();
const stashedIds = new Set(editing.stashedAttachments.map((item) => item.id));
const entryFileIds = new Set(
(remoteSessionStore.getInputProjection(sessionId).pendingQueue
@@ -6257,6 +6367,18 @@ export default function SessionScreen() {
discardMobileUploadedAttachment(attachment, { getToken: () => auth.getAccessToken() });
discardedIds.add(attachment.id);
}
+ return discardedIds;
+ }, [auth, sessionId]);
+
+ const discardQueueEditTransientAttachments = useCallback((
+ editing: QueueEditingState,
+ attachmentsAtExit: readonly RemoteSerializedAttachment[] = attachmentsRef.current,
+ ) => {
+ // 同 session 的正常退出要同步丢弃编辑期在途上传:进入编辑有 pendingUploads
+ // 为空的门槛,因此此刻的任务必然是编辑期新增。会话切换的迟到 finalize 不走
+ // 这里,避免旧 A 回调清掉复用 controller 上 B 刚开始的上传。
+ discardAllPendingUploads();
+ const discardedIds = discardQueueEditTransientAttachmentResources(editing, attachmentsAtExit);
if (discardedIds.size > 0) {
setAttachmentPreviews((current) => Object.fromEntries(
Object.entries(current).filter(([attachmentId]) => !discardedIds.has(attachmentId)),
@@ -6265,10 +6387,11 @@ export default function SessionScreen() {
Object.entries(current).filter(([, attachmentId]) => !discardedIds.has(attachmentId)),
));
}
- }, [auth, discardAllPendingUploads, sessionId]);
+ }, [discardAllPendingUploads, discardQueueEditTransientAttachmentResources]);
useEffect(() => {
- discardQueueEditTransientAttachmentsRef.current = discardQueueEditTransientAttachments;
- }, [discardQueueEditTransientAttachments]);
+ discardQueueEditTransientAttachmentResourcesRef.current =
+ discardQueueEditTransientAttachmentResources;
+ }, [discardQueueEditTransientAttachmentResources]);
/**
* 进入排队消息编辑:把条目的文本/附件载入底部 composer(复用其全部编辑能力),
@@ -8582,6 +8705,7 @@ export default function SessionScreen() {
compactComposer && !composerCardActive && styles.composerSurfaceCompact,
]}>
<MobileComposerInputRow
+ key={sessionId}
accessibilityLabel={t('session.screen.composerPlaceholder')}
accessibilityHint={composerLayout.input.disabledReason ?? undefined}
accessoryAbove={attachments.length > 0 || pendingUploads.length > 0 || pastePlaceholderCount > 0 ? renderComposerAttachmentTray() : null}
diff --git a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
index 8da81bfe57..a7688241e5 100644
--- a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
+++ b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
@@ -138,11 +138,13 @@ describe('createMobileLocalAttachmentUploadController', () => {
expect(uploaded[0]?.uploadedUri).toBe('file:///tmp/downsampled.jpg');
});
- it('resolve 型任务:onUploaded 回传就位后的 candidate(实际上传的 uri),保留 sourceId', async () => {
+ it('resolve 型任务:onUploaded 回传就位后的 candidate,保留来源与 composer 代际', async () => {
const { deps, uploaded } = makeDeps();
const controller = createMobileLocalAttachmentUploadController(deps);
controller.enqueue([{
...candidate('IMG_0001.HEIC'),
+ attachmentScopeGeneration: 7,
+ attachmentScopeKey: 'session-a',
uri: 'ph://asset-1',
sourceId: 'asset-1',
resolve: () => Promise.resolve({ uri: 'file:///tmp/IMG_0001.jpg', name: 'IMG_0001.jpg', skipPreprocess: true }),
@@ -152,6 +154,8 @@ describe('createMobileLocalAttachmentUploadController', () => {
expect(uploaded[0]?.candidate.uri).toBe('file:///tmp/IMG_0001.jpg');
expect(uploaded[0]?.candidate.name).toBe('IMG_0001.jpg');
expect(uploaded[0]?.candidate.sourceId).toBe('asset-1');
+ expect(uploaded[0]?.candidate.attachmentScopeKey).toBe('session-a');
+ expect(uploaded[0]?.candidate.attachmentScopeGeneration).toBe(7);
expect(uploaded[0]?.candidate.kind).toBe('image');
});
@@ -217,7 +221,7 @@ describe('createMobileLocalAttachmentUploadController', () => {
expect(discarded.map((item) => item.name)).toEqual(['slow.jpg']);
});
- it('removeAll:排队任务即刻出队、在途任务完成后回收,controller 仍可继续 enqueue(切换电脑场景)', async () => {
+ it('removeAll:切换任务/电脑时排队任务即刻出队、迟到完成只回收不回调', async () => {
const gate = gatedUpload();
const { deps, pendingSnapshots, uploaded, discarded } = makeDeps({ upload: gate.upload });
const controller = createMobileLocalAttachmentUploadController(deps);
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index def69547e4..04328e8b7d 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -2184,7 +2184,7 @@ describe('submit guard catalog wiring (source locks)', () => {
});
it('goal 接回载荷按 sessionId 换代清理:切任务不残留旧 objective/limits(codex P2)', () => {
- // 任务抽屉 router.replace 原地更新同一 SessionScreen 实例,goalRestore/goalError
+ // 任务抽屉 replaceParams 原地更新同一 SessionScreen 实例,goalRestore/goalError
// 只在首次挂载初始化——sessionId 变化必须清理,否则新任务 Goal 表单预填旧目标、
// 甚至把旧目标提交到新任务(codex review P2)。
const sessionSource = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
diff --git a/apps/mobile/src/__tests__/pastedImageAttachment.test.ts b/apps/mobile/src/__tests__/pastedImageAttachment.test.ts
index 2ecd69387a..1e797f5b5d 100644
--- a/apps/mobile/src/__tests__/pastedImageAttachment.test.ts
+++ b/apps/mobile/src/__tests__/pastedImageAttachment.test.ts
@@ -66,7 +66,8 @@ describe('resolvePastedImageAsset', () => {
describe('粘贴接线源码断言(防重构掉线)', () => {
const mobileRoot = join(__dirname, '..', '..');
- const read = (rel: string) => readFileSync(join(mobileRoot, rel), 'utf8');
+ // Windows checkout 使用 CRLF;源码接线断言统一到 LF,避免把换行风格误判成逻辑缺失。
+ const read = (rel: string) => readFileSync(join(mobileRoot, rel), 'utf8').replace(/\r\n/g, '\n');
it('共享输入行组件包 TextInputWrapper 并只上抛 images', () => {
const source = read('src/session/MobileComposerInputRow.tsx');
@@ -114,7 +115,8 @@ describe('粘贴接线源码断言(防重构掉线)', () => {
// 占位窗口(原生还在读剪贴板 / 编码写盘)任务尚未入队,只等 waitForIdle
// 会让「粘贴后立刻点发送」把图漏在消息外。
expect(source).toContain('await waitForPastePlaceholders();');
- expect(source).toContain('return controller.waitForIdle();');
+ expect(source).toContain('const result = await controller.waitForIdle();');
+ expect(source).toContain('return isAttachmentScopeActive() ? result : { failedCount: 0 };');
// 兜底路径(超时清零 / 卸载)都要放行等待者,防发送永久悬挂。
expect(source).toContain('flushPastePlaceholderWaiters();');
});
@@ -127,7 +129,7 @@ describe('粘贴接线源码断言(防重构掉线)', () => {
// 路径不能绕过占位占坑)。
expect(source).toContain('const getPendingSlotCount = () => controller.pendingCount() + getPastePlaceholderTotal();');
expect(source).toContain('- getPendingSlotCount()');
- expect(source).toContain('getPendingUploadCount: getPendingSlotCount,');
+ expect(source).toContain('getPendingUploadCount: () => (isAttachmentScopeActive() ? getPendingSlotCount() : 0),');
// 批次 FIFO(review P2):兑现 / 失败只出列最早一批,并发粘贴时第一批完成
// 不清掉第二批还在原生处理中的占位;addPastedImages 进限额检查前先出列
// 本批(防双扣)。
@@ -136,6 +138,46 @@ describe('粘贴接线源码断言(防重构掉线)', () => {
expect(source).toContain('shiftPastePlaceholderBatch();');
});
+ it('composer 草稿作废时同步清上传队列、粘贴占位与等待者', () => {
+ const source = read('src/session/useMobileLocalAttachments.ts');
+ const start = source.indexOf('const discardAllPendingUploads = useCallback(() => {');
+ const end = source.indexOf('useEffect(() => () => {', start);
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ const discard = source.slice(start, end);
+ expect(discard).toContain('controller.removeAll();');
+ expect(discard).toContain('pastePlaceholderBatchesRef.current = [];');
+ expect(discard).toContain('setPastePlaceholderCount(0);');
+ expect(discard).toContain('clearTimeout(pastePlaceholderTimerRef.current);');
+ expect(discard).toContain('pastePlaceholderWaitersRef.current = [];');
+ expect(discard).toContain('for (const resolve of waiters) resolve();');
+ expect(source).toContain('attachmentScopeGenerationRef.current += 1;');
+ expect(source).toContain('discardAllPendingUploadsForScopeChange,');
+ });
+
+ it('session 作用域闸拒绝旧 picker / 粘贴入口与迟到上传完成结果', () => {
+ const source = read('src/session/useMobileLocalAttachments.ts');
+ expect(source).toContain('optionsRef.current.attachmentScopeKey === attachmentScopeKey');
+ expect(source).toContain('attachmentScopeGenerationRef.current === attachmentScopeGeneration');
+ expect(source).toContain('if (count <= 0 || !isAttachmentScopeActive()) return;');
+ expect(source).toContain('if (candidates.length === 0 || !isAttachmentScopeActive()) return;');
+ expect(source).toContain('if (!isAttachmentScopeActive()) {\n if (ownedUris.length > 0) void deleteLocalUris(ownedUris);');
+ expect(source).toContain('optionsRef.current.attachmentScopeKey !== candidateScopeKey');
+ expect(source).toContain('candidate.attachmentScopeGeneration !== attachmentScopeGenerationRef.current');
+ expect(source).toContain('discardMobileUploadedAttachment(attachment');
+ expect(source).toContain('onFailed: (err, localId, candidate) => {');
+ expect(source).toContain('if (!isAttachmentScopeActive()) return { failedCount: 0 };');
+ expect(source).toContain('if (!isAttachmentScopeActive()) return [];');
+ const sessionSource = read('app/sessions/[sessionId].tsx');
+ expect(sessionSource).toContain('attachmentScopeKey: sessionId,');
+ });
+
+ it('富文本输入按 session 重挂载时作废旧粘贴批次,迟到写盘不回调新任务', () => {
+ const source = read('src/session/ComposerRichInput.tsx');
+ expect(source).toContain('pendingImagePastesRef.current.clear();');
+ expect(source).toContain('pendingImagePasteOrderRef.current = [];');
+ });
+
it('context-sheet 选图限额走同一占坑真源(直接入队路径不绕过粘贴占位)', () => {
for (const page of ['app/sessions/new.tsx', 'app/sessions/[sessionId].tsx']) {
const source = read(page);
diff --git a/apps/mobile/src/__tests__/sessionDrawerNavigation.test.ts b/apps/mobile/src/__tests__/sessionDrawerNavigation.test.ts
new file mode 100644
index 0000000000..5a06afff5a
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionDrawerNavigation.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it, vi } from 'vitest';
+import { switchDrawerSessionInPlace } from '@/session/sessionDrawerNavigation';
+
+describe('wide session drawer navigation', () => {
+ it('switches the current route in place with only the target session identity', () => {
+ const replaceParams = vi.fn();
+
+ switchDrawerSessionInPlace(
+ { replaceParams },
+ {
+ deviceId: 'device-b',
+ deviceName: 'Desktop B',
+ sessionId: 'session-b',
+ },
+ );
+
+ expect(replaceParams).toHaveBeenCalledOnce();
+ expect(replaceParams).toHaveBeenCalledWith({
+ deviceId: 'device-b',
+ deviceName: 'Desktop B',
+ sessionId: 'session-b',
+ });
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
index 3953fbd0b1..81d6ba5f1c 100644
--- a/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionHeaderDesktopFirst.test.ts
@@ -72,9 +72,11 @@ describe('mobile session header desktop-first surface', () => {
const source = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
// 宽屏(iPad / 折叠屏展开 / 横屏手机)导航形态:断点判定走 wideSessionNav 纯函数,
- // 左上角三条杠替代返回,抽屉原地 replace 切任务;窄屏保持 ScreenBackButton(上一用例已锁)。
+ // 左上角三条杠替代返回,抽屉在当前 native Screen 内切任务;窄屏保持 ScreenBackButton。
expect(source).toContain("import { buildWideSessionNavLayout } from '@/session/wideSessionNav';");
expect(source).toContain("import { SessionListDrawer } from '@/session/SessionListDrawer';");
+ expect(source).toContain('switchDrawerSessionInPlace,');
+ expect(source).toContain("from '@/session/sessionDrawerNavigation';");
// 按平台分闸(发布策略):iOS 只发 iPad,iPhone 横屏也保持返回键;安卓纯宽度闸。
expect(source).toContain('iosPad: Platform.OS === \'ios\' && Platform.isPad,');
expect(source).toContain('platform: Platform.OS,');
@@ -82,11 +84,17 @@ describe('mobile session header desktop-first surface', () => {
expect(source).toContain('icon={Menu}');
expect(source).toContain('testID="session.sessionListButton"');
expect(source).toContain('{onOpenSessionList ? (');
- // 抽屉切任务是「原地切换」:replace 保持导航栈 [主页, 会话],不逐层压栈。
- expect(source).toContain("pathname: '/sessions/[sessionId]'");
+ // 抽屉切任务只替换当前 route params:不压栈,也不派发会创建新 route key 的
+ // NativeStack REPLACE(后者正是 Android crash / 白屏仍存的生命周期入口)。
expect(source).toContain('const handleDrawerSelectSession = useCallback((item: RemoteSessionListItem) => {');
- expect(source).toContain('router.replace({');
- // Android 原生换屏必须等 drawer overlay 完整卸载;三个导航入口共用同一延后队列。
+ const drawerSelectionStart = source.indexOf('const handleDrawerSelectSession = useCallback');
+ const drawerSelectionEnd = source.indexOf('// 前进导航防连点', drawerSelectionStart);
+ const drawerSelectionSource = source.slice(drawerSelectionStart, drawerSelectionEnd);
+ expect(drawerSelectionSource).toContain('switchDrawerSessionInPlace(navigation, {');
+ expect(drawerSelectionSource).not.toContain('router.replace');
+ expect(drawerSelectionSource).not.toContain("pathname: '/sessions/[sessionId]'");
+ // 三个导航入口都等 drawer overlay 完整卸载;新建 / 回主页可能原生换屏,
+ // 切任务虽已改为 replaceParams,也不和 Reanimated 子树退场抢同一帧。
expect(source).toContain('const pendingDrawerNavigationRef = useRef<(() => void) | null>(null);');
expect(source).toContain('const sessionListDrawerClosingRef = useRef(false);');
expect(source).toContain('const [sessionListDrawerOverlayMounted, setSessionListDrawerOverlayMounted] = useState(false);');
@@ -100,7 +108,7 @@ describe('mobile session header desktop-first surface', () => {
expect(source).toContain('onClosed={handleSessionListDrawerClosed}');
expect(source).toContain('const action = pendingDrawerNavigationRef.current;\n sessionListDrawerClosingRef.current = false;\n if (!action) returnDrawerFocusAfterCloseRef.current = true;\n setSessionListDrawerOverlayMounted(false);');
expect(source).toContain('pendingDrawerNavigationRef.current = null;\n action();');
- expect(source).toContain('queueDrawerNavigation(() => {\n router.replace({');
+ expect(source).toContain('queueDrawerNavigation(() => {\n // 必须早于 replaceParams');
expect(source).toContain('queueDrawerNavigation(() => {\n guardedPush({');
expect(source).toContain("queueDrawerNavigation(() => router.dismissTo('/'));");
// 旋转 / 分屏收窄回窄屏时抽屉必须自动收起(没有入口的悬空 overlay)。
@@ -127,7 +135,112 @@ describe('mobile session header desktop-first surface', () => {
expect(source).toContain('if (wideSessionNav.enabled) sessionListDrawerWidthRef.current = wideSessionNav.drawerWidth;');
expect(source).toContain('width={sessionListDrawerWidthRef.current}');
// 选任务失败路径:校验先于关闭动画——先关再弹 Alert 会让焦点归还抢走弹窗焦点。
- expect(source).toContain("Alert.alert(t('devices.list.error.sessionDeviceNotFound'));\n return;\n }\n // replace");
+ expect(source).toContain("Alert.alert(t('devices.list.error.sessionDeviceNotFound'));\n return;\n }\n // 不派发 NativeStack REPLACE");
+ });
+
+ it('clears the complete composer attachment scope before switching session params', () => {
+ const source = readTextLf(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8');
+ const boundaryStart = source.indexOf('discardSessionComposerAttachmentStateRef.current = () => {');
+ const boundaryEnd = source.indexOf('// 抽屉入口会在 replaceParams 前同步调用', boundaryStart);
+ expect(boundaryStart).toBeGreaterThan(-1);
+ expect(boundaryEnd).toBeGreaterThan(boundaryStart);
+ const boundary = source.slice(boundaryStart, boundaryEnd);
+
+ // 一处完整封口:上传控制器 / 已完成附件 / 预览 / 相册映射 / 未提交选择 / lightbox
+ // 与标注本地文件一起退场;排队编辑 stash 也属于旧任务,不能恢复进新任务。
+ expect(boundary).toContain('const currentAttachments = [...attachmentsRef.current];');
+ expect(boundary).toContain('for (const attachment of currentAttachments)');
+ expect(boundary).toContain('for (const attachment of editing?.stashedAttachments ?? [])');
+ expect(boundary).toContain('attachmentsRef.current = [];');
+ expect(boundary).toContain('setAttachments([]);');
+ expect(boundary).toContain('setAttachmentPreviews({});');
+ expect(boundary).toContain('setMediaAssetAttachments({});');
+ expect(boundary).toContain('setPendingMediaAssets([]);');
+ expect(boundary).toContain('setComposerPreviewAttachmentId(null);');
+ expect(boundary).toContain('composerAnnotationsRef.current?.forgetAllAttachments();');
+ expect(boundary).toContain('discardMobileUploadedAttachment(attachment');
+ // 排队编辑保存中的附件不能和 update-content 抢跑回收:界面同步清空,
+ // A 的附件快照交给 A cleanup 等保存落定后再判断。
+ expect(boundary).toContain('const deferQueueEditAttachments = !!editing && !!queueEditSaveInFlightRef.current;');
+ expect(boundary).toContain('queueEditScopeExitAttachmentsRef.current = {');
+ expect(boundary).toContain('if (!deferQueueEditAttachments) {');
+
+ // 抽屉动作必须先封住 A 的迟到上传回调,再让 route params 变成 B。
+ const drawerSelectionStart = source.indexOf('const handleDrawerSelectSession = useCallback');
+ const drawerSelectionEnd = source.indexOf('// 前进导航防连点', drawerSelectionStart);
+ const drawerSelection = source.slice(drawerSelectionStart, drawerSelectionEnd);
+ const invalidateAt = drawerSelection.indexOf('discardAllPendingUploadsForScopeChange();');
+ const discardAt = drawerSelection.indexOf('discardSessionComposerAttachmentStateRef.current();');
+ const switchAt = drawerSelection.indexOf('switchDrawerSessionInPlace(navigation, {');
+ expect(invalidateAt).toBeGreaterThan(-1);
+ expect(discardAt).toBeGreaterThan(invalidateAt);
+ expect(switchAt).toBeGreaterThan(discardAt);
+ expect(source).toContain('discardAllPendingUploadsForScopeChange();\n discardSessionComposerAttachmentStateRef.current();');
+
+ // 复用页面实例时输入原生子树也按 sessionId 换代,旧粘贴异步事件没有新任务入口。
+ expect(source).toContain('<MobileComposerInputRow\n key={sessionId}');
+ // key 重挂载前必须在 render 阶段把 composer state 归属切到 B;不能先拿 A 文档
+ // 创建 B 的 WebView,再等被动 effect 才纠正。同步缓存缺失时 B 首帧为空态。
+ const draftScopeStart = source.indexOf('const activeComposerDraftScopeKey = composerDraftScopeKey(sessionId, routeDraft);');
+ const draftScopeEnd = source.indexOf('// chat-text-quote:', draftScopeStart);
+ const draftScope = source.slice(draftScopeStart, draftScopeEnd);
+ expect(draftScopeStart).toBeGreaterThan(-1);
+ expect(draftScopeEnd).toBeGreaterThan(draftScopeStart);
+ expect(draftScope).toContain('if (composerDraftStateKey !== activeComposerDraftScopeKey) {');
+ expect(draftScope).toContain('const nextScope = readImmediateComposerDraftScope(sessionId, routeDraft);');
+ expect(draftScope).toContain('setComposerDocumentState(nextScope.document);');
+ expect(draftScope).toContain('setDraft(nextDraft);');
+ expect(draftScope).toContain('setComposerDraftHydrated(false);');
+ expect(draftScope).toContain('appliedRouteDraftRef.current = null;');
+ expect(draftScope).toContain('composerDocumentRef.current = nextScope.document;');
+ expect(draftScope).toContain('draftRef.current = nextDraft;');
+
+ const immediateScopeStart = source.indexOf('function readImmediateComposerDraftScope(');
+ const immediateScopeEnd = source.indexOf('function composerDraftScopeKey(', immediateScopeStart);
+ const immediateScope = source.slice(immediateScopeStart, immediateScopeEnd);
+ expect(immediateScope).toContain('readComposerDraftSync(sessionId) ?? routeDraft ??');
+ expect(immediateScope).toContain('readComposerDocumentDraftSync(sessionId);');
+ expect(immediateScope).toContain('const quotes = getQuotes(sessionId);');
+ expect(immediateScope).toContain('resolveOrderedQuoteDraft(sessionId, visibleText, quotes);');
+
+ // render-phase 换代先把旧 promise 的 key 作废,但保留 null 让 B effect 继续读取
+ // 仅磁盘草稿;effect 内原有 live-ref 比对继续保证用户新输入不被迟到读取覆盖。
+ const hydrationStart = source.indexOf('useEffect(() => {\n const key = activeComposerDraftScopeKey;');
+ const hydrationEnd = source.indexOf('useEffect(() => {\n if (!composerDraftHydrated', hydrationStart);
+ const hydration = source.slice(hydrationStart, hydrationEnd);
+ expect(hydration).toContain('const immediateScope = readImmediateComposerDraftScope(sessionId, routeDraft);');
+ expect(hydration).toContain('if (cancelled || appliedRouteDraftRef.current !== key) return;');
+ expect(hydration).toContain('if (!composerDocumentsEqual(composerDocumentRef.current, immediateDocumentSnapshot)) {');
+ const queueCleanupStart = source.indexOf('// 切会话 / 卸载时收尾上一个会话的排队编辑态');
+ const queueCleanupEnd = source.indexOf('useEffect(() => {\n if (canUseComposer)', queueCleanupStart);
+ const queueCleanup = source.slice(queueCleanupStart, queueCleanupEnd);
+ expect(queueCleanup).toContain('attachmentsRef.current = [];\n setAttachments([]);');
+ expect(queueCleanup).not.toContain('setAttachments([...editing.stashedAttachments])');
+ expect(queueCleanup).toContain('const scopeExitSnapshot = queueEditScopeExitAttachmentsRef.current;');
+ expect(queueCleanup).toContain('const discardQueueEditTransientAttachmentResources =\n discardQueueEditTransientAttachmentResourcesRef.current;');
+ expect(queueCleanup).toContain('discardQueueEditTransientAttachmentResources?.(editing, attachmentsSnapshot);');
+
+ // A 保存落定后的迟到 finalize 只能回收 A 的附件快照,不得触碰复用 controller
+ // 或组件级映射;否则 B 在切换后新开的上传会被 A 的 removeAll 一并取消。
+ const scopedCleanupStart = source.indexOf('const discardQueueEditTransientAttachmentResources = useCallback');
+ const scopedCleanupEnd = source.indexOf('const discardQueueEditTransientAttachments = useCallback', scopedCleanupStart);
+ const scopedCleanup = source.slice(scopedCleanupStart, scopedCleanupEnd);
+ expect(scopedCleanupStart).toBeGreaterThan(-1);
+ expect(scopedCleanupEnd).toBeGreaterThan(scopedCleanupStart);
+ expect(scopedCleanup).toContain('remoteSessionStore.getInputProjection(sessionId)');
+ expect(scopedCleanup).toContain('discardMobileUploadedAttachment(attachment');
+ expect(scopedCleanup).not.toContain('discardAllPendingUploads');
+ expect(scopedCleanup).not.toContain('setAttachmentPreviews');
+ expect(scopedCleanup).not.toContain('setMediaAssetAttachments');
+
+ // 同任务内放弃 / 切换编辑目标仍需完整清理自己的在途上传与附件映射。
+ const localCleanupStart = scopedCleanupEnd;
+ const localCleanupEnd = source.indexOf('useEffect(() => {\n discardQueueEditTransientAttachmentResourcesRef.current', localCleanupStart);
+ const localCleanup = source.slice(localCleanupStart, localCleanupEnd);
+ expect(localCleanup).toContain('discardAllPendingUploads();');
+ expect(localCleanup).toContain('discardQueueEditTransientAttachmentResources(editing, attachmentsAtExit);');
+ expect(localCleanup).toContain('setAttachmentPreviews');
+ expect(localCleanup).toContain('setMediaAssetAttachments');
});
it('keeps pending history access as a lightweight control without message counters', () => {
diff --git a/apps/mobile/src/session/ComposerRichInput.tsx b/apps/mobile/src/session/ComposerRichInput.tsx
index a9c558a94c..93306ef559 100644
--- a/apps/mobile/src/session/ComposerRichInput.tsx
+++ b/apps/mobile/src/session/ComposerRichInput.tsx
@@ -245,6 +245,11 @@ export const ComposerRichInput = forwardRef<ComposerRichInputHandle, ComposerRic
disposedRef.current = false;
return () => {
disposedRef.current = true;
+ // sessionId 原地换代时 ComposerRichInput 会重挂载。旧实例的异步图片写盘即使
+ // 随后落定,也不能再沿旧闭包调用新任务的 onPasteImages / load-failed;先摘掉
+ // 批次登记,settlePastedImage 会把迟到结果视为已作废。
+ pendingImagePastesRef.current.clear();
+ pendingImagePasteOrderRef.current = [];
const pendingUris = [...pendingPastedImageFilesRef.current];
pendingPastedImageFilesRef.current.clear();
if (pendingUris.length > 0) void deleteComposerPastedImageUris(pendingUris);
diff --git a/apps/mobile/src/session/SessionListDrawer.tsx b/apps/mobile/src/session/SessionListDrawer.tsx
index 44378ed712..7929739952 100644
--- a/apps/mobile/src/session/SessionListDrawer.tsx
+++ b/apps/mobile/src/session/SessionListDrawer.tsx
@@ -6,10 +6,10 @@
*
* 结构取舍:
* - **树内 overlay 而非 RN Modal**:会话页已有多个 sheet Modal,iOS 同级双 Modal
- * 有 present/dismiss 竞态(见 SheetSurface 头注释);树内层叠没有这些约束。导航动作
- * 仍必须等 overlay 退场并真正卸载后执行:Android 原生 Screen 换页若与
- * GestureDetector/Reanimated 子树卸载挤在同一帧存在崩溃竞态。代价是盖不住原生弹层,
- * 但抽屉打开前页面会先收键盘,且其它 sheet 与抽屉互斥(都由页面状态驱动)。
+ * 有 present/dismiss 竞态(见 SheetSurface 头注释);树内层叠没有这些约束。新建 / 回主页
+ * 仍必须等 overlay 退场并真正卸载后执行;任务切换则在当前原生 Screen 内只替换 route
+ * params,完全绕开 Android NativeStack replace。代价是盖不住原生弹层,但抽屉打开前
+ * 页面会先收键盘,且其它 sheet 与抽屉互斥(都由页面状态驱动)。
* - **数据直读全局 remoteSessionStore**:与首页同一份 store(进会话页前已水合,
* 设备订阅继续推增量),经共享层 buildMobileHomePresentation 复用首页的排序 /
* 置顶 / 自动化折叠口径,不在抽屉里重建首页的设备同步机械。
diff --git a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
index 064f88733b..6bd1145bc7 100644
--- a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
@@ -29,6 +29,10 @@ export interface MobileLocalAttachmentUploadCandidate {
kind: MobileLocalAttachmentKind;
uri: string;
name: string;
+ /** 发起上传的 composer 作用域(sessionId 等);仅供宿主隔离迟到异步结果。 */
+ attachmentScopeKey?: string;
+ /** 同一作用域重复进入时也会递增的代际;避免 A → B → A 后接回最早 A 的旧结果。 */
+ attachmentScopeGeneration?: number;
mimeType?: string;
/** 原文件字节数,0 = 未知(上传前由 statSize 兜底)。 */
size: number;
@@ -119,7 +123,7 @@ export interface MobileLocalAttachmentUploadDeps {
isActive: () => boolean,
): void | Promise<void>;
/** 单个失败(宿主展示错误文案);已被移除 / 丢弃的任务不会回调。localId 语义同 onUploaded。 */
- onFailed(error: unknown, localId: string): void;
+ onFailed(error: unknown, localId: string, candidate: MobileLocalAttachmentUploadCandidate): void;
}
export interface MobileLocalAttachmentUploadController {
@@ -357,7 +361,7 @@ export function createMobileLocalAttachmentUploadController(
if (task.discarded) {
outcome = 'discarded';
} else {
- deps.onFailed(err, task.localId);
+ deps.onFailed(err, task.localId, task.candidate);
outcome = 'failed';
}
} finally {
diff --git a/apps/mobile/src/session/sessionDrawerNavigation.ts b/apps/mobile/src/session/sessionDrawerNavigation.ts
new file mode 100644
index 0000000000..18afeb9f35
--- /dev/null
+++ b/apps/mobile/src/session/sessionDrawerNavigation.ts
@@ -0,0 +1,29 @@
+export interface SessionDrawerRouteTarget {
+ deviceId: string;
+ deviceName: string;
+ sessionId: string;
+}
+
+export interface SessionRouteParamsNavigation {
+ replaceParams(params: SessionDrawerRouteTarget): void;
+}
+
+/**
+ * 在当前 Session 原生 Screen 内切换任务。
+ *
+ * `router.replace('/sessions/[sessionId]')` 会派发 NativeStack REPLACE,Android 上既会
+ * 创建新的 route key,也会触发原生 Screen 的替换生命周期;宽屏抽屉的真实崩溃/白屏
+ * 都发生在这条路径上。SessionScreen 本身已经按 sessionId 做换代与异步结果隔离,因此
+ * 这里只替换当前 route 的完整 params:不创建新 Screen,也不会把旧任务的 draft / goal /
+ * focus 等一次性参数合并进目标任务。
+ */
+export function switchDrawerSessionInPlace(
+ navigation: SessionRouteParamsNavigation,
+ target: SessionDrawerRouteTarget,
+): void {
+ navigation.replaceParams({
+ deviceId: target.deviceId,
+ deviceName: target.deviceName,
+ sessionId: target.sessionId,
+ });
+}
diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.ts
index e26e5123a9..ee14dee4da 100644
--- a/apps/mobile/src/session/useMobileLocalAttachments.ts
+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts
@@ -13,7 +13,7 @@
* - 附件限额计算要把 pendingUploads.length 算进去;
* - 页面卸载时 hook 自动 dispose(在途上传完成后回收 OSS 中转对象)。
*/
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Platform } from 'react-native';
import * as DocumentPicker from 'expo-document-picker';
@@ -53,6 +53,11 @@ import {
import type { RemoteSerializedAttachment } from '@/session/types';
export interface UseMobileLocalAttachmentsOptions {
+ /**
+ * composer 附件作用域。已建任务页传 sessionId;作用域换代后,旧 picker / 粘贴 /
+ * 标注异步入口与上传完成结果不得写入新作用域。省略时保持旧的单作用域行为。
+ */
+ attachmentScopeKey?: string;
getAccessToken: () => Promise<string | null>;
/** 当前已入列附件数(限额用;pending 由 hook 自己计入)。 */
getAttachmentCount: () => number;
@@ -111,8 +116,13 @@ export interface UseMobileLocalAttachmentsResult {
removePendingUpload: (localId: string) => void;
/** 重试一个失败态的上传卡(自动取新鲜 token 重跑完整管线)。 */
retryPendingUpload: (localId: string) => void;
- /** 丢弃全部在途上传(切换目标电脑等草稿整体作废场景;完成后回收 OSS 中转对象)。 */
+ /**
+ * 丢弃 composer 域的全部在途上传与粘贴占位(切换任务 / 目标电脑等草稿整体
+ * 作废场景;完成后回收 OSS 中转对象)。
+ */
discardAllPendingUploads: () => void;
+ /** 切换 attachmentScopeKey 前封住旧作用域;迟到 picker / 粘贴结果也会被拒绝。 */
+ discardAllPendingUploadsForScopeChange: () => void;
/** 等全部在途上传落定;返回期间失败个数(>0 时调用方应中止发送)。 */
waitForPendingUploads: () => Promise<{ failedCount: number }>;
/**
@@ -175,6 +185,16 @@ export function useMobileLocalAttachments(
// 回调经 ref 转发,controller 单例化的同时始终调到最新一次 render 的闭包。
const optionsRef = useRef(options);
optionsRef.current = options;
+ // scope-change discard 与普通 removeAll 不同:除了清当前队列,还要让旧 render
+ // 持有的 picker / 粘贴 / 标注闭包永久过期。不能只比 sessionId:A → B → A 时
+ // 最早 A 的超慢异步结果仍是同 id,必须靠单调 generation 区分两次进入。
+ const attachmentScopeGenerationRef = useRef(0);
+ const attachmentScopeKey = options.attachmentScopeKey;
+ const attachmentScopeGeneration = attachmentScopeGenerationRef.current;
+ const isAttachmentScopeActive = () => attachmentScopeKey == null || (
+ optionsRef.current.attachmentScopeKey === attachmentScopeKey
+ && attachmentScopeGenerationRef.current === attachmentScopeGeneration
+ );
const getPastePlaceholderTotal = () =>
pastePlaceholderBatchesRef.current.reduce((sum, n) => sum + n, 0);
@@ -220,7 +240,7 @@ export function useMobileLocalAttachments(
};
const beginPastePlaceholders = (count: number) => {
- if (count <= 0) return;
+ if (count <= 0 || !isAttachmentScopeActive()) return;
pastePlaceholderBatchesRef.current.push(count);
syncPastePlaceholders();
};
@@ -233,6 +253,7 @@ export function useMobileLocalAttachments(
};
const failPastePlaceholders = () => {
+ if (!isAttachmentScopeActive()) return;
if (pastePlaceholderBatchesRef.current.length === 0) return;
shiftPastePlaceholderBatch();
optionsRef.current.onError(t('composer.upload.clipboardReadFailed'));
@@ -251,6 +272,21 @@ export function useMobileLocalAttachments(
}),
onPendingChange: setPendingUploads,
onUploaded: async (attachment, candidate, uploadedUri, localId, localUris, isActive) => {
+ const candidateScopeKey = candidate.attachmentScopeKey;
+ if (candidateScopeKey != null && (
+ optionsRef.current.attachmentScopeKey !== candidateScopeKey
+ || candidate.attachmentScopeGeneration !== attachmentScopeGenerationRef.current
+ )) {
+ // 防御性代际闸:正常抽屉路径会先 removeAll,把任务标 discarded;若完成结果
+ // 已越过 controller 的最后取消检查点,这里仍按 candidate 的原 owner 拒收。
+ // task 已被 removeAll 标记时由 controller 统一回收,避免这里重复 DELETE。
+ if (!isActive()) return;
+ discardMobileUploadedAttachment(attachment, {
+ getToken: () => optionsRef.current.getAccessToken(),
+ });
+ if (candidate.cleanupLocalUris) await candidate.cleanupLocalUris(localUris);
+ return;
+ }
// 发送后气泡的本地缩略图兜底:消息里持久化的是 cindy-oss-attach:// 中转引用,
// 被控端物化改写前(乐观渲染 / 电脑离线窗口)渲染端没有任何预览路径——把
// 实际上传的文件拷进自有目录记映射,气泡用本地图顶上。
@@ -280,9 +316,59 @@ export function useMobileLocalAttachments(
}
}
},
- onFailed: (err, localId) => optionsRef.current.onError(formatRemoteError(err), { uploadLocalId: localId }),
+ onFailed: (err, localId, candidate) => {
+ const candidateScopeKey = candidate.attachmentScopeKey;
+ if (candidateScopeKey != null && (
+ optionsRef.current.attachmentScopeKey !== candidateScopeKey
+ || candidate.attachmentScopeGeneration !== attachmentScopeGenerationRef.current
+ )) return;
+ optionsRef.current.onError(formatRemoteError(err), { uploadLocalId: localId });
+ },
}), []);
+ const discardAllPendingUploads = useCallback(() => {
+ controller.removeAll();
+ // 粘贴占位尚未进入 controller 队列,但同样属于当前 composer 草稿。任务 / 设备
+ // 换代时若只清 controller,旧占位会继续显示在新目标,且 waitForPendingUploads
+ // 的等待者会一直挂到旧粘贴事件落定或超时。
+ pastePlaceholderBatchesRef.current = [];
+ setPastePlaceholderCount(0);
+ if (pastePlaceholderTimerRef.current) {
+ clearTimeout(pastePlaceholderTimerRef.current);
+ pastePlaceholderTimerRef.current = null;
+ }
+ const waiters = pastePlaceholderWaitersRef.current;
+ pastePlaceholderWaitersRef.current = [];
+ for (const resolve of waiters) resolve();
+ }, [controller]);
+
+ const discardAllPendingUploadsForScopeChange = useCallback(() => {
+ // 同一旧 render 的抽屉同步封口 + effect cleanup 会各调用一次;只有仍是本代时
+ // 才递增,保证新 session render 捕获的 generation 不被旧 cleanup 再作废。
+ if (
+ attachmentScopeKey != null
+ && attachmentScopeGenerationRef.current === attachmentScopeGeneration
+ ) attachmentScopeGenerationRef.current += 1;
+ discardAllPendingUploads();
+ }, [attachmentScopeGeneration, attachmentScopeKey, discardAllPendingUploads]);
+
+ const enqueueUploads = (
+ candidates: readonly MobileLocalAttachmentUploadCandidate[],
+ opts: { token: string | Promise<string | null> },
+ ) => {
+ if (!isAttachmentScopeActive()) return;
+ controller.enqueue(
+ attachmentScopeKey == null
+ ? candidates
+ : candidates.map((candidate) => ({
+ ...candidate,
+ attachmentScopeGeneration,
+ attachmentScopeKey,
+ })),
+ opts,
+ );
+ };
+
useEffect(() => () => {
controller.dispose();
const pastedUris = [...pastedImageLocalUrisRef.current];
@@ -301,6 +387,7 @@ export function useMobileLocalAttachments(
/** 限额检查 + 防重入的公共前奏;返回 null 表示不能继续。 */
const beginPick = (): { remainingSlots: number } | null => {
+ if (!isAttachmentScopeActive()) return null;
if (pickerBusyRef.current) return null;
// 占坑数读同步真源 getPendingSlotCount(上传中 + 粘贴占位),不读 React state:
// 连续入队场景不受 state commit 滞后影响(review P1);占位期间从相册再加图
@@ -330,6 +417,7 @@ export function useMobileLocalAttachments(
const permission = source === 'camera'
? await ImagePicker.requestCameraPermissionsAsync()
: await ImagePicker.requestMediaLibraryPermissionsAsync(false);
+ if (!isAttachmentScopeActive()) return;
if (!permission.granted) {
optionsRef.current.onError(source === 'camera'
? t('composer.upload.cameraPermission')
@@ -349,18 +437,19 @@ export function useMobileLocalAttachments(
quality: 1,
selectionLimit: begun.remainingSlots,
});
+ if (!isAttachmentScopeActive()) return;
if (picked.canceled) return;
const candidates: MobileLocalAttachmentUploadCandidate[] = picked.assets
.slice(0, begun.remainingSlots)
.map((asset, index) => ({ kind: 'image', ...buildMobileImageAttachmentCandidate(asset, index) }));
- if (candidates.length === 0) return;
+ if (candidates.length === 0 || !isAttachmentScopeActive()) return;
// 立即入 pending 托盘(不先 await token):token 等待窗里任务已可被 waitForIdle 看到,
// composer 抢发会等它落定而不是丢图;token 由任务开跑时自行等待(拿不到→该任务失败报错)。
- controller.enqueue(candidates, { token: optionsRef.current.getAccessToken() });
+ enqueueUploads(candidates, { token: optionsRef.current.getAccessToken() });
optionsRef.current.onPicked?.();
} catch (err) {
- optionsRef.current.onError(formatRemoteError(err));
+ if (isAttachmentScopeActive()) optionsRef.current.onError(formatRemoteError(err));
} finally {
pickerBusyRef.current = false;
}
@@ -374,6 +463,7 @@ export function useMobileLocalAttachments(
copyToCacheDirectory: true,
multiple: false,
});
+ if (!isAttachmentScopeActive()) return;
if (picked.canceled) return;
const asset = picked.assets?.[0];
@@ -393,8 +483,9 @@ export function useMobileLocalAttachments(
const size = typeof asset.size === 'number' && Number.isFinite(asset.size) && asset.size > 0
? asset.size
: 0;
+ if (!isAttachmentScopeActive()) return;
// 立即入 pending 托盘(带文件名 chip,不先 await token,同 addImages):大 PDF 不再卡住托盘。
- controller.enqueue([{
+ enqueueUploads([{
kind: 'file',
uri,
name,
@@ -403,7 +494,7 @@ export function useMobileLocalAttachments(
}], { token: optionsRef.current.getAccessToken() });
optionsRef.current.onPicked?.();
} catch (err) {
- optionsRef.current.onError(formatRemoteError(err));
+ if (isAttachmentScopeActive()) optionsRef.current.onError(formatRemoteError(err));
} finally {
pickerBusyRef.current = false;
}
@@ -417,6 +508,10 @@ export function useMobileLocalAttachments(
const addPastedImages = async (uris: string[]): Promise<void> => {
if (uris.length === 0) return;
const ownedUris = uris.filter(isComposerPastedImageUri);
+ if (!isAttachmentScopeActive()) {
+ if (ownedUris.length > 0) void deleteLocalUris(ownedUris);
+ return;
+ }
for (const uri of ownedUris) pastedImageLocalUrisRef.current.add(uri);
// 本批 uris 就是最早一批占位卡的兑现:先按 FIFO 出列本批再做限额检查
//(否则这批会被自己的占位双扣槽位)。出列与下方 enqueue 的 pending 上屏在
@@ -434,7 +529,7 @@ export function useMobileLocalAttachments(
const acceptedUris = uris.slice(0, begun.remainingSlots);
const rejectedUris = uris.slice(begun.remainingSlots).filter(isComposerPastedImageUri);
if (rejectedUris.length > 0) void cleanupPastedImageLocalUris(rejectedUris);
- controller.enqueue(acceptedUris.map((uri, index) => {
+ enqueueUploads(acceptedUris.map((uri, index) => {
const classified = classifyPastedImageUri(uri);
const ownsLocalFile = isComposerPastedImageUri(uri);
return {
@@ -453,7 +548,7 @@ export function useMobileLocalAttachments(
};
}), { token: optionsRef.current.getAccessToken() });
} catch (err) {
- optionsRef.current.onError(formatRemoteError(err));
+ if (isAttachmentScopeActive()) optionsRef.current.onError(formatRemoteError(err));
} finally {
pickerBusyRef.current = false;
}
@@ -467,23 +562,29 @@ export function useMobileLocalAttachments(
addImages,
addDocument,
addPastedImages,
- enqueueUploads: controller.enqueue,
+ enqueueUploads,
removePendingUpload: controller.remove,
retryPendingUpload: (localId) => {
+ if (!isAttachmentScopeActive()) return;
// 重试前清掉上一次失败的错误文案;token 取新鲜值(失败卡可能停留很久)。
optionsRef.current.onError(null);
controller.retry(localId, { token: optionsRef.current.getAccessToken() });
},
- discardAllPendingUploads: controller.removeAll,
+ discardAllPendingUploads,
+ discardAllPendingUploadsForScopeChange,
// 先等粘贴占位落定(images 兑现会把任务同步入队 / 失败与超时直接归零),
// 再等 controller 队列——否则占位窗口内抢发会把刚粘贴的图漏在消息外
//(review P2)。占位失败不计入 failedCount:那张图从未成为附件,语义等同
// 用户手动移除,不应中止发送。
waitForPendingUploads: async () => {
+ if (!isAttachmentScopeActive()) return { failedCount: 0 };
await waitForPastePlaceholders();
- return controller.waitForIdle();
+ if (!isAttachmentScopeActive()) return { failedCount: 0 };
+ const result = await controller.waitForIdle();
+ return isAttachmentScopeActive() ? result : { failedCount: 0 };
},
claimActiveUploads: () => {
+ if (!isAttachmentScopeActive()) return [];
const snapshot = controller.claimableTasks();
controller.claim(snapshot.map((task) => task.localId));
return snapshot;
@@ -493,8 +594,10 @@ export function useMobileLocalAttachments(
// 乐观发送(outbox)在占位窗口内需要它把「尚未入队、无法划归」的粘贴图等成
// 可划归任务,再做同步 claim——不能用 waitForPendingUploads(那会退化回
// 等整个上传完成)。失败 / 超时同样放行(60s 兜底,错误 toast 已由占位路径给出)。
- waitForPastePlaceholdersSettled: waitForPastePlaceholders,
- hasPastePlaceholders: () => getPastePlaceholderTotal() > 0,
- getPendingUploadCount: getPendingSlotCount,
+ waitForPastePlaceholdersSettled: () => (
+ isAttachmentScopeActive() ? waitForPastePlaceholders() : Promise.resolve()
+ ),
+ hasPastePlaceholders: () => isAttachmentScopeActive() && getPastePlaceholderTotal() > 0,
+ getPendingUploadCount: () => (isAttachmentScopeActive() ? getPendingSlotCount() : 0),
};
}