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): 恢复新建任务乐观交互并清理失败恢复残留

Dashb52bd0eff63b
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index 0f5d16dccc..593da5e617 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -1,4 +1,5 @@
import { useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';
+import { withNewSessionCreationRemoval } from '@/session/newSessionCreation';
import { useHeaderHeight } from 'expo-router/react-navigation';
import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { useSharedValue } from 'react-native-reanimated';
@@ -597,7 +598,8 @@ function DeviceDetailScreenContent() {
const failed: typeof rows = [];
await Promise.all(rows.map(async (row) => {
try {
- const updated = await maker.patchSessionMeta(row.session.id, patch);
+ const updated = await withNewSessionCreationRemoval(row.session.id, deviceId, patch.status,
+ () => maker.patchSessionMeta(row.session.id, patch));
if (updated) remoteSessionStore.applySessionPatch(row.rowDeviceId, row.session.id, updated);
} catch (err) {
if (isExplicitRemoteNotFoundError(err) && patch.status !== undefined) {
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index c89cc3f98f..adb266f47f 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -77,7 +77,7 @@ import {
addScreenshotListener,
renderConversationShareHtmlToPng,
} from 'xdt-screenshot-monitor';
-import { Stack, useFocusEffect, useLocalSearchParams, useNavigation, useRouter } from 'expo-router';
+import { Stack, useFocusEffect, useIsFocused, useLocalSearchParams, useNavigation, useRouter } from 'expo-router';
import { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode, type RefObject, type SetStateAction } from 'react';
import {
ActivityIndicator,
@@ -290,10 +290,10 @@ import { pickWriteFields, retryPatchWhileLatest, writeGuardFields } from '@/sess
import {
dismissNewSessionCreation,
getNewSessionCreationTask,
- retryNewSessionCreation,
shouldBlockSessionSync,
stashNewSessionDraftForEdit,
useNewSessionCreationTask,
+ withNewSessionCreationRemoval,
} from '@/session/newSessionCreation';
import {
useComposerImageAnnotations,
@@ -649,7 +649,7 @@ import {
useSessionTaskUpdates,
} from '@/session/remoteSessionStore';
import { CindyMakeSessionGate } from '@/session/CindyMakeSessionGate';
-import { returnNewSessionToEdit } from '@/session/returnNewSessionToEdit';
+import { useFailedCreationReturnToEdit } from '@/session/useFailedCreationReturnToEdit';
import type {
MobileGoalLimitsInput,
MobileGoalStatusPayload,
@@ -4093,11 +4093,54 @@ function SessionScreenContent() {
// 新建会话乐观管线的收口响应:
// - running → task 移除(成功):守卫解除,补一轮完整同步(权威 meta / 交互 / projection);
- // - create-failed:Alert 重试面(重试 = 同 id 重跑管线,幂等安全;返回编辑 = 草稿
- // stash 回新建页并移除合成行)+ 常驻错误条兜底(Alert 被系统关掉时仍有指引);
+ // - create-failed:带回草稿与附件并自动返回编辑,不要求用户选择恢复方式;
// - enqueue-failed:会话已建成,首条消息文本 / 附件回填 composer,用户走正常发送
// (新桌面有 clientId 幂等去重,重复风险已兜)。
const creationTask = useNewSessionCreationTask(sessionId);
+ const creationScreenFocused = useIsFocused();
+ useFailedCreationReturnToEdit({
+ task: creationTask?.deviceId === deviceId ? creationTask : null,
+ focused: creationScreenFocused,
+ connectionEpoch,
+ onReady: params => router.replace({ pathname: '/sessions/new', params: {
+ ...params,
+ creationError: creationTask?.error ?? t('session.screen.createFailedDefault'),
+ } }),
+ onError: err => setError(t('session.screen.createFailedNotice', { message: formatRemoteError(err) })),
+ stashDraft: prepared => {
+ // 创建期间发出的后续消息必须一起带回新建页(review P1):它们此刻在 outbox 里,
+ // 而下一行 dismiss 会连同合成会话行一起删掉——会话页 unmount 时 cleanup 会把它们
+ // 写进那个已经不存在的会话的草稿,用户在新建页看不到、也再也找不回来。
+ // 新建页只有一个首条消息输入框,所以按序拼成文本、附件按 id 去重合并后一起 stash。
+ // 上传任务保不住:本页(连同 upload controller)马上要销毁,只能取消
+ // 并回收,再把「没能带回多少」告知用户(review P1:静默丢等于偷走内容)。
+ const { items: followUps, cancelledUploadCount } = takeOutboxForSession(sessionId, 'cancel');
+ if (followUps.length > 0) {
+ const { merged, dropped } = mergeAttachmentsWithinLimit(
+ prepared.attachments,
+ followUps.flatMap(outboxItemAttachments),
+ );
+ // 装不下的中转对象在这里回收:草稿带不走它们,留着就是没人认领的垃圾。
+ discardRecoveredAttachments(dropped);
+ const unrecoveredCount = dropped.length + cancelledUploadCount;
+ stashNewSessionDraftForEdit(prepared, {
+ draft: {
+ ...prepared.draft,
+ firstMessage: [
+ prepared.draft.firstMessage,
+ ...followUps.map(outboxItemDraftText),
+ ].filter(Boolean).join('\n\n'),
+ },
+ attachments: merged,
+ notice: unrecoveredCount > 0
+ ? t('session.screen.attachmentsNotCarriedBack', { count: unrecoveredCount })
+ : null,
+ });
+ } else {
+ stashNewSessionDraftForEdit(prepared);
+ }
+ },
+ });
const prevCreationStatusRef = useRef<string | null>(null);
useEffect(() => {
const prev = prevCreationStatusRef.current;
@@ -4111,90 +4154,6 @@ function SessionScreenContent() {
}
return;
}
- if (status === 'create-failed') {
- const message = creationTask?.error ?? t('session.screen.createFailedDefault');
- setError(t('session.screen.createFailedNotice', { message }));
- Alert.alert(t('session.screen.createFailedTitle'), message, [
- {
- text: t('session.screen.backToEdit'),
- style: 'cancel',
- onPress: () => {
- if (!creationTask) return;
- const owner = getMobileAuthOwner();
- const isCurrent = () => isMobileAuthOwnerCurrent(owner)
- && outboxSessionAliveRef.current === sessionId && navigation.isFocused();
- void returnNewSessionToEdit({
- sessionId, deviceId,
- isCurrent,
- onReady: params => router.replace({ pathname: '/sessions/new', params }),
- stashDraft: prepared => {
- // 创建期间发出的后续消息必须一起带回新建页(review P1):它们此刻在 outbox 里,
- // 而下一行 dismiss 会连同合成会话行一起删掉——会话页 unmount 时 cleanup 会把它们
- // 写进那个已经不存在的会话的草稿,用户在新建页看不到、也再也找不回来。
- // 新建页只有一个首条消息输入框,所以按序拼成文本、附件按 id 去重合并后一起 stash。
- // 上传任务保不住:本页(连同 upload controller)马上要销毁,只能取消
- // 并回收,再把「没能带回多少」告知用户(review P1:静默丢等于偷走内容)。
- const { items: followUps, cancelledUploadCount } = takeOutboxForSession(sessionId, 'cancel');
- if (followUps.length > 0) {
- const { merged, dropped } = mergeAttachmentsWithinLimit(
- prepared.attachments,
- followUps.flatMap(outboxItemAttachments),
- );
- // 装不下的中转对象在这里回收:草稿带不走它们,留着就是没人认领的垃圾。
- discardRecoveredAttachments(dropped);
- const unrecoveredCount = dropped.length + cancelledUploadCount;
- stashNewSessionDraftForEdit(prepared, {
- draft: {
- ...prepared.draft,
- firstMessage: [
- prepared.draft.firstMessage,
- ...followUps.map(outboxItemDraftText),
- ].filter(Boolean).join('\n\n'),
- },
- attachments: merged,
- notice: unrecoveredCount > 0
- ? t('session.screen.attachmentsNotCarriedBack', { count: unrecoveredCount })
- : null,
- });
- } else {
- stashNewSessionDraftForEdit(prepared);
- }
- },
- })
- .catch((err: unknown) => {
- // Recovery continues after leaving, but its error UI belongs to this page.
- if (!isCurrent()) return;
- // 补偿回收失败时保留 task + 合成行,绝不先跳回表单再创建第二个孤儿
- // worktree。用户可取消等待连接恢复,或直接复用同 sessionId 重试创建。
- const cleanupError = formatRemoteError(err);
- setError(t('session.screen.createFailedNotice', { message: cleanupError }));
- Alert.alert(t('session.screen.createFailedTitle'), cleanupError, [
- {
- text: t('session.common.cancel'),
- style: 'cancel',
- },
- {
- text: t('session.screen.retry'),
- onPress: () => {
- if (!isCurrent()) return;
- setError(null);
- retryNewSessionCreation(sessionId);
- },
- },
- ]);
- });
- },
- },
- {
- text: t('session.screen.retry'),
- onPress: () => {
- setError(null);
- retryNewSessionCreation(sessionId);
- },
- },
- ]);
- return;
- }
if (status === 'enqueue-failed') {
const durableFirst = getCurrentMobileOutboxRecords().find((r) => r.item.sessionId === sessionId && r.deviceId === deviceId && r.creation);
if (durableFirst) {
@@ -9158,7 +9117,8 @@ function SessionScreenContent() {
const releasePending = sessionPendingWrites.track(sessionId, fields);
void (async () => {
try {
- const updated = await sessionMetaWriteQueue.enqueue(sessionId, fields, () => retryPatchWhileLatest(
+ const updated = await withNewSessionCreationRemoval(sessionId, rpcDeviceId, patch.status,
+ () => sessionMetaWriteQueue.enqueue(sessionId, fields, () => retryPatchWhileLatest(
write.isLatest,
// preSend:重连等待(最长 1.5s)之后、真正出网之前再查一次让位——本页同
// 字段连续两次操作时,前笔在等待中被取代不得再发出(review P2)。
@@ -9168,7 +9128,7 @@ function SessionScreenContent() {
[sessionId, patch],
{ preSend: assertStillLatest },
),
- ));
+ )), write.isLatest);
if (updated && write.isLatest()) {
// 字段级对账 + updatedAt 单调下限(同首页):整对象覆盖会冲掉其它字段
// 上并发写的乐观值。
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index ec19ed5f79..d0305974a0 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -246,6 +246,7 @@ import {
createNewSessionId,
completeNewSessionDurableEdit,
drainStashedNewSessionDraft,
+ findNewSessionEditDraft,
hasLiveNewSessionCreation,
holdNewSessionCreationDraft,
startNewSessionCreation,
@@ -507,6 +508,7 @@ export default function NewRemoteSessionScreen() {
draft?: string;
recoverySessionId?: string;
editSessionId?: string;
+ creationError?: string;
}>();
const routeDeviceId = String(params.deviceId ?? '');
const routeDeviceName = String(params.deviceName ?? routeDeviceId);
@@ -611,7 +613,10 @@ export default function NewRemoteSessionScreen() {
const [creating, setCreating] = useState(false);
const [createStartedAt, setCreateStartedAt] = useState<number | null>(null);
const [createPhase, setCreatePhase] = useState<SlowSendPhase>('preparing');
- const [error, setError] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(() => {
+ const creationError = readRouteString(params.creationError);
+ return creationError ? t('session.screen.createFailedNotice', { message: creationError }) : null;
+ });
const [capabilities, setCapabilities] = useState<MobileAgentCapabilities | null>(null);
const [capabilitiesLoading, setCapabilitiesLoading] = useState(false);
const [, setCapabilitiesError] = useState<string | null>(null);
@@ -811,7 +816,7 @@ export default function NewRemoteSessionScreen() {
// composer 托盘里正被全屏查看的图片附件 id(null = 关闭)。
const [composerPreviewAttachmentId, setComposerPreviewAttachmentId] = useState<string | null>(null);
const [attachmentError, setAttachmentError] = useState<string | null>(null);
- // 创建失败后返回编辑:只领取路由指定任务与设备的草稿,普通新建页不领取。
+ // 创建失败后返回编辑;再次打开空白新建页时,继续同设备/项目的草稿。
// 附件是已上传完成的引用,原样回列即可继续使用;notice 是「有内容没能带回」的告知
// (创建期间发出的消息可能超出单条上限,装不下的只能丢,但不能静默丢,review P1)。
// 声明在 attachmentError 之后:notice 就落在附件错误行上。
@@ -851,6 +856,25 @@ export default function NewRemoteSessionScreen() {
router.replace('/devices');
return true;
}, [router]);
+ useEffect(() => {
+ if (params.recoverySessionId || params.editSessionId || params.draft || params.suggestion
+ || visualInitialDraft || !newSessionPreferencesLoaded || !selectedDeviceId) return;
+ const owner = outboxOwner;
+ let active = true;
+ const resume = () => {
+ if (!active || !isMobileAuthOwnerCurrent(owner) || outboxRecoveryRef.current
+ || firstMessageRef.current || attachmentsRef.current.length
+ || userTouchedRuntimeRef.current || userTouchedWorkspaceRef.current) return;
+ const saved = findNewSessionEditDraft(selectedDeviceId, initialWorkingDir);
+ if (!saved) return;
+ active = false;
+ router.setParams({ recoverySessionId: saved.item.sessionId, deviceId: saved.deviceId });
+ };
+ const unsubscribe = mobileDurableOutbox.subscribe(resume);
+ void mobileDurableOutbox.ready().then(resume);
+ return () => { active = false; unsubscribe(); };
+ }, [params.recoverySessionId, params.editSessionId, params.draft, params.suggestion, visualInitialDraft,
+ newSessionPreferencesLoaded, selectedDeviceId, initialWorkingDir, outboxOwner, router]);
useEffect(() => {
const owner = outboxOwner;
if (leaveForeignOutboxRecovery()) return;
diff --git a/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx b/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx
index 5f23f880e6..63aef3a8b6 100644
--- a/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx
+++ b/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx
@@ -15,15 +15,11 @@ const state = vi.hoisted(() => ({
connectionEpoch: 0,
accountGeneration: 1,
task: null as NewSessionCreationTask | null,
- retryCreation: vi.fn(),
- returnToEdit: vi.fn(),
router: { canGoBack: vi.fn(() => true), back: vi.fn(), replace: vi.fn() },
}));
vi.mock('@/session/newSessionCreation', () => ({
useNewSessionCreationTask: () => state.task,
- retryNewSessionCreation: state.retryCreation,
}));
-vi.mock('@/session/returnNewSessionToEdit', () => ({ returnNewSessionToEdit: state.returnToEdit }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: (error: Error) => error.message }));
vi.mock('@/theme', () => ({ useTheme: () => ({ colors: {} }), useThemedStyles: () => ({}) }));
@@ -73,8 +69,6 @@ beforeEach(() => {
state.connectionEpoch = 0;
state.accountGeneration = 1;
state.task = null;
- state.retryCreation.mockReset();
- state.returnToEdit.mockReset();
state.router.canGoBack.mockReset().mockReturnValue(true);
state.router.back.mockReset();
state.router.replace.mockReset();
@@ -140,23 +134,6 @@ describe('mobile Cindy Make links', () => {
expect(state.unsubscribe).not.toHaveBeenCalled();
});
- it('keeps retry and edit locked after remounting while task recovery is still pending', async () => {
- state.task = { ...failedCreation(), returningToEdit: true };
- await renderGate();
- await act(async () => root.render(null));
- await renderGate();
- for (const id of ['session.creationRetry', 'session.creationEdit']) {
- expect(container.querySelector<HTMLButtonElement>(`[data-testid="${id}"]`)?.disabled).toBe(true);
- await click(id);
- }
- expect(state.retryCreation).not.toHaveBeenCalled();
- expect(state.returnToEdit).not.toHaveBeenCalled();
- state.task = { ...state.task!, returningToEdit: false };
- await renderGate();
- await click('session.creationRetry');
- expect(state.retryCreation).toHaveBeenCalledOnce();
- });
-
it('offers a manual metadata retry after an empty response without reconnecting', async () => {
await renderGate();
expect(container.textContent).toContain('session.entry.missing');
@@ -168,17 +145,14 @@ describe('mobile Cindy Make links', () => {
expect(container.textContent).toBe('Composer');
});
- it.each(['memory', 'durable'] as const)('keeps a prepared %s draft reachable after remount without retrying its cancelled creation', async readyForEdit => {
+ it.each(['memory', 'durable'] as const)('mounts the recovery owner for a prepared %s draft without a choice screen', async readyForEdit => {
state.task = { ...failedCreation(), readyForEdit };
await renderGate();
await act(async () => root.render(null));
await renderGate();
- expect(container.querySelector<HTMLButtonElement>('[data-testid="session.creationRetry"]')?.disabled).toBe(true);
- expect(container.querySelector<HTMLButtonElement>('[data-testid="session.creationEdit"]')?.disabled).toBe(false);
- await click('session.creationRetry');
- expect(state.retryCreation).not.toHaveBeenCalled();
- await click('session.creationEdit');
- expect(state.returnToEdit).toHaveBeenCalledOnce();
+ expect(container.textContent).toBe('Composer');
+ expect(container.querySelector('button')).toBeNull();
+ expect(state.maker.getSession).not.toHaveBeenCalled();
});
it('shows link failures and returns home when a cold link has no back stack', async () => {
@@ -289,100 +263,30 @@ describe('mobile Cindy Make links', () => {
expect(container.textContent).toBe('redirect:/');
});
- it('does not navigate after leaving a pending return-to-edit operation', async () => {
- state.task = failedCreation();
- let finish!: () => void;
- state.returnToEdit.mockImplementation(({ onReady, isCurrent }) => new Promise<void>(resolve => {
- finish = () => {
- if (isCurrent()) onReady({ deviceId: 'device-a', deviceName: 'PC' });
- resolve();
- };
- }));
- await renderGate();
- await click('session.creationEdit');
- await act(async () => root.render(null));
- await act(async () => finish());
- expect(state.router.replace).not.toHaveBeenCalled();
- });
-
- it('shows creation failure before metadata exists, retries the same task and opens after success', async () => {
- state.task = failedCreation();
+ it.each(['running', 'create-failed'] as const)('keeps the optimistic task mounted during %s without remote metadata', async status => {
+ state.task = { ...failedCreation(), status };
state.sessions = [{ id: 'new-task', deviceLinkDeviceId: 'device-a' }];
await renderGate();
- expect(container.textContent).toContain('REMOTE_AGENT_GROUP_UNAVAILABLE');
- expect(container.textContent).not.toContain('Composer');
- expect(state.maker.getSession).not.toHaveBeenCalled();
- state.retryCreation.mockImplementation(() => { state.task = { ...state.task!, status: 'running' }; });
- await click('session.creationRetry');
- expect(state.retryCreation).toHaveBeenCalledWith('new-task');
- await renderGate();
- expect(container.textContent).toContain('session.new.slowSend.creating');
+ expect(container.textContent).toBe('Composer');
+ expect(container.querySelector('button')).toBeNull();
expect(state.maker.getSession).not.toHaveBeenCalled();
- state.task = null;
- state.maker.getSession.mockResolvedValue({ id: 'new-task', source: 'desktop' });
+ state.connectionEpoch += 1;
await renderGate();
expect(container.textContent).toBe('Composer');
});
- it.each(['durable', 'cleanup-ack'] as const)('keeps %s recovery accessible with known metadata and blocks retries after remount', async stateKind => {
- state.task = { ...failedCreation(), ...(stateKind === 'durable'
- ? { readyForEdit: 'durable' as const } : { worktreeCleanupAcknowledged: true }) };
- state.sessions = [{ id: 'new-task', deviceLinkDeviceId: 'device-a', source: 'desktop' }];
- await renderGate();
- await act(async () => root.render(null));
- await renderGate();
- expect(container.textContent).not.toContain('Composer');
- await click('session.creationRetry');
- expect(state.retryCreation).not.toHaveBeenCalled();
- await click('session.creationEdit');
- expect(state.returnToEdit).toHaveBeenCalled();
- });
-
- it('keeps recovery available after leaving and reopening a failed creation', async () => {
- state.task = failedCreation();
- await renderGate();
- await act(async () => root.render(null));
- await renderGate();
- expect(container.textContent).toContain('REMOTE_AGENT_GROUP_UNAVAILABLE');
- expect(container.querySelector('[data-testid="session.creationEdit"]')).not.toBeNull();
- });
-
- it('uses shared edit recovery and prevents duplicate edits or concurrent creation retries', async () => {
- state.task = failedCreation();
- let finish!: () => void;
- state.returnToEdit.mockImplementation(({ onReady, isCurrent }) => new Promise<void>(resolve => {
- finish = () => {
- if (isCurrent()) onReady({ deviceId: 'device-a', deviceName: 'PC', recoverySessionId: 'new-task' });
- resolve();
- };
- }));
- await renderGate();
- await click('session.creationEdit');
- await click('session.creationEdit');
- await click('session.creationRetry');
- expect(state.returnToEdit).toHaveBeenCalledTimes(1);
- expect(state.retryCreation).not.toHaveBeenCalled();
- await act(async () => finish());
- expect(state.router.replace).toHaveBeenCalledWith({ pathname: '/sessions/new', params: {
- deviceId: 'device-a', deviceName: 'PC', recoverySessionId: 'new-task',
- } });
- });
-
- it('keeps the failure page and retry actions when worktree recovery fails', async () => {
- state.task = failedCreation();
- state.returnToEdit.mockRejectedValue(new Error('worktree cleanup pending'));
- await renderGate();
- await click('session.creationEdit');
- expect(container.textContent).toContain('worktree cleanup pending');
- expect(state.router.replace).not.toHaveBeenCalled();
- await click('session.creationRetry');
- expect(state.retryCreation).toHaveBeenCalledWith('new-task');
+ it('does not extend optimistic entry to file routes', async () => {
+ state.task = { ...failedCreation(), status: 'running' };
+ await act(async () => root.render(
+ <CindyMakeSessionGate sessionId="new-task" deviceId="device-a"><span>Files</span></CindyMakeSessionGate>,
+ ));
+ expect(container.textContent).not.toContain('Files');
});
it('does not show another device creation recovery or bypass a known Make source', async () => {
state.task = { ...failedCreation(), deviceId: 'device-b' };
await renderGate();
- expect(container.textContent).not.toContain('REMOTE_AGENT_GROUP_UNAVAILABLE');
+ expect(container.textContent).not.toContain('Composer');
state.task = failedCreation();
state.sessions = [{ id: 'new-task', deviceLinkDeviceId: 'device-a', source: 'cindy-make' }];
await renderGate();
diff --git a/apps/mobile/src/__tests__/newSessionCreation.test.ts b/apps/mobile/src/__tests__/newSessionCreation.test.ts
index bcebea61b1..a9df30ef3a 100644
--- a/apps/mobile/src/__tests__/newSessionCreation.test.ts
+++ b/apps/mobile/src/__tests__/newSessionCreation.test.ts
@@ -59,6 +59,7 @@ import {
shouldBlockSessionSync,
stashNewSessionDraftForEdit,
startNewSessionCreation,
+ withNewSessionCreationRemoval,
type NewSessionCreationParams,
} from '@/session/newSessionCreation';
import { remoteSessionStore } from '@/session/remoteSessionStore';
@@ -205,6 +206,30 @@ async function flushPipeline(): Promise<void> {
}
describe('newSessionCreation pipeline', () => {
+ it.each([false, true])('deletes a failed local task only after worktree cleanup (cleanup fails: %s)', async fails => {
+ const maker = makeMaker();
+ startNewSessionCreation(makeParams('s1', maker, {
+ draft: { ...DRAFT, workingDir: '/repo/.cindy-worktrees/a' },
+ precreatedWorktree: { path: '/repo/.cindy-worktrees/a', recoveryKey: 'cleanup-a', originalWorkingDir: '/repo' },
+ confirmUnauthenticated: async () => ({ unauthenticated: true, fresh: null }),
+ }));
+ await flushPipeline();
+ if (fails) maker.worktree.discardPrecreated.mockRejectedValueOnce(new Error('cleanup refused'));
+ const remove = vi.fn();
+ const removal = withNewSessionCreationRemoval('s1', 'dev-1', 'deleted', remove);
+ if (fails) {
+ await expect(removal).rejects.toThrow('cleanup refused');
+ expect(getNewSessionCreationTask('s1')).toMatchObject({ status: 'create-failed', returningToEdit: false });
+ expect(remoteSessionStore.getSessions().some(row => row.id === 's1')).toBe(true);
+ } else {
+ await removal;
+ expect(getNewSessionCreationTask('s1')).toBeNull();
+ expect(remoteSessionStore.getSessions()).toEqual([]);
+ }
+ expect(maker.worktree.discardPrecreated).toHaveBeenCalledOnce();
+ expect(remove).not.toHaveBeenCalled();
+ });
+
beforeEach(async () => {
persistCancelledDraft.mockReset();
editOutbox.records.mockReset().mockReturnValue([]);
@@ -307,7 +332,7 @@ describe('newSessionCreation pipeline', () => {
editOutbox.records.mockImplementation(() => [...afterRestart.getSnapshot()]);
const bridge = outboxLeaseHarness([...afterRestart.getSnapshot()]);
bridge.refresh();
- expect(remoteSessionStore.getSessions().some(row => row.id === 's1')).toBe(true);
+ expect(remoteSessionStore.getSessions()).toEqual([]);
expect(bridge.leases.size).toBe(0);
expect(getNewSessionCreationTask('s1')).toMatchObject({ readyForEdit: 'durable', draft: DRAFT });
expect(getNewSessionCreationTask('s1')).toBe(getNewSessionCreationTask('s1'));
@@ -360,7 +385,7 @@ describe('newSessionCreation pipeline', () => {
expect(remoteSessionStore.getSessions()).toEqual([]);
releaseSecond!();
expect(getNewSessionCreationTask('s1')?.readyForEdit).toBe('durable');
- expect(remoteSessionStore.getSessions().some(row => row.id === 's1')).toBe(true);
+ expect(remoteSessionStore.getSessions()).toEqual([]);
const releaseReopened = completeNewSessionDurableEdit('s1', 'dev-1');
releaseSecond!();
expect(getNewSessionCreationTask('s1')).toBeNull();
@@ -531,75 +556,6 @@ describe('newSessionCreation pipeline', () => {
expect(drainStashedNewSessionDraft('s1', 'dev-1')).toBeNull();
});
- it.each(['current', 'unmount', 'another-task', 'blur', 'account'] as const)(
- 'only reports a delayed edit-save failure on its current task page: %s', async pageState => {
- const maker = makeMaker({ createSession: vi.fn(async () => { throw new Error('MODEL_UNAVAILABLE'); }) });
- startNewSessionCreation(makeParams('s1', maker));
- await flushPipeline();
- const record = { ...recoveryOutboxRecord('s1'), accountId: getMobileAuthOwner().accountKey };
- editOutbox.records.mockReturnValue([record]);
- let failSave!: (error: Error) => void;
- editOutbox.update.mockImplementationOnce(() => new Promise<void>((_resolve, reject) => { failSave = reject; }));
- const alive = { current: 's1' as string | null };
- const navigation = { isFocused: vi.fn(() => true) };
- const alert = vi.fn();
- const setError = vi.fn();
- const replace = vi.fn();
- const retry = vi.fn(retryNewSessionCreation);
- const bindings = {
- creationTask: getNewSessionCreationTask('s1'), sessionId: 's1', deviceId: 'dev-1',
- getMobileAuthOwner, isMobileAuthOwnerCurrent, outboxSessionAliveRef: alive, navigation,
- returnNewSessionToEdit, router: { replace }, Alert: { alert }, setError,
- t: (key: string, options?: { message: string }) => options?.message ?? key,
- formatRemoteError: (error: Error) => error.message, retryNewSessionCreation: retry,
- };
- // Execute the actual Alert action, including its asynchronous catch, rather
- // than reproducing the page's lifecycle guard in the test.
- const screen = ts.createSourceFile('session.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'),
- ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
- let action: string | undefined;
- const findAction = (node: ts.Node) => {
- if (ts.isObjectLiteralExpression(node) && node.properties.some(property => ts.isPropertyAssignment(property)
- && property.name.getText(screen) === 'text' && property.initializer.getText(screen) === "t('session.screen.backToEdit')")) {
- const handler = node.properties.find(property => ts.isPropertyAssignment(property) && property.name.getText(screen) === 'onPress');
- if (handler && ts.isPropertyAssignment(handler)) action = handler.initializer.getText(screen);
- }
- ts.forEachChild(node, findAction);
- };
- findAction(screen);
- if (!action) throw new Error('Missing return-to-edit alert action');
- const code = ts.transpileModule(`const onPress = ${action};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
- const onPress = new Function(...Object.keys(bindings), `${code}; return onPress;`)(...Object.values(bindings));
- onPress();
- await flushPipeline();
- expect(editOutbox.update).toHaveBeenCalledOnce();
- expect(getNewSessionCreationTask('s1')?.returningToEdit).toBe(true);
- if (pageState === 'unmount') alive.current = null;
- if (pageState === 'another-task') alive.current = 's2';
- if (pageState === 'blur') navigation.isFocused.mockReturnValue(false);
- if (pageState === 'account') setMobileAuthOwner('owner-b');
- failSave(new Error('disk full'));
- await flushPipeline();
- expect(replace).not.toHaveBeenCalled();
- if (pageState === 'current') {
- expect(setError).toHaveBeenCalledWith('disk full');
- expect(alert).toHaveBeenCalledOnce();
- // A dialog already shown must not let its retry act on a page that subsequently left.
- alive.current = null;
- alert.mock.calls[0][2][1].onPress();
- expect(retry).not.toHaveBeenCalled();
- expect(setError).toHaveBeenCalledTimes(1);
- } else {
- expect(setError).not.toHaveBeenCalled();
- expect(alert).not.toHaveBeenCalled();
- }
- expect(editOutbox.records()).toEqual([record]);
- if (pageState !== 'account') {
- expect(getNewSessionCreationTask('s1')).toMatchObject({ status: 'create-failed', returningToEdit: false });
- expect(remoteSessionStore.getSessions().some(session => session.id === 's1')).toBe(true);
- }
- });
-
it('keeps a cancelled durable worktree recovery visible until its form accepts it', async () => {
const maker = makeMaker();
startNewSessionCreation(makeParams('s1', maker, {
@@ -685,7 +641,7 @@ describe('newSessionCreation pipeline', () => {
cleanup();
if (scope === 'matching') {
expect(getNewSessionCreationTask('s1')?.readyForEdit).toBe('durable');
- expect(remoteSessionStore.getSessions().some(row => row.id === 's1')).toBe(true);
+ expect(remoteSessionStore.getSessions()).toEqual([]);
}
});
diff --git a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
index 34facd3ae5..d985cb1069 100644
--- a/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
+++ b/apps/mobile/src/__tests__/newSessionCreationPersistence.test.ts
@@ -26,6 +26,7 @@ import { completeNewSessionDurableEdit, getNewSessionCreationTask, hasLiveNewSes
import { remoteSessionStore } from '../session/remoteSessionStore';
import { listPendingPrecreatedWorktrees, recoverPendingPrecreatedWorktrees, registerPendingPrecreatedWorktree } from '../session/precreatedWorktreeRecovery';
import { completePrecreatedWorktreeRecovery } from '../session/completePrecreatedWorktreeRecovery';
+import { findNewSessionEditDraft, withNewSessionCreationRemoval } from '../session/newSessionCreation';
// Run the page's actual recovery -> durable save -> worktree creation statements.
// Extract AST nodes, as in newSessionWorktreeSync, so ordering is tested without
@@ -137,7 +138,7 @@ it.each(['reservation-fails', 'create-rejected', 'reply-lost', 'leaves-during-cr
expect(getNewSessionCreationTask(previous.item.sessionId)).toBeNull();
expect(getNewSessionCreationTask('replacement-session')).toMatchObject({ readyForEdit: 'durable',
draft: { firstMessage: 'updated input before retry' }, attachments: [{ id: 'photo' }] });
- expect(remoteSessionStore.getSessions().map(row => row.id)).toEqual(['replacement-session']);
+ expect(remoteSessionStore.getSessions()).toEqual([]);
expect(hasLiveNewSessionCreation('replacement-session')).toBe(false);
if (scenario === 'reply-lost') {
@@ -378,3 +379,59 @@ it('preserves a directory explicitly selected by the user while cancellation com
}));
expect(getCurrentMobileOutboxRecords()[0].creation?.originalWorkingDir).toBe('/other-repo');
});
+
+// Regression: deleting only the mirror let the durable bridge recreate an
+// undeletable task. Exercise the production removal with real persisted bytes.
+it.each(['deleted', 'archived'])('retires saved recovery on %s, including editor release and cold reload', async status => {
+ await harness().run();
+ const original = getCurrentMobileOutboxRecords()[0];
+ const saved = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
+ expect(findNewSessionEditDraft('pc', '/repo')).toEqual(saved);
+ expect(findNewSessionEditDraft('other-pc')).toBeUndefined();
+ expect(findNewSessionEditDraft('pc', '/other-repo')).toBeUndefined();
+ const leave = completeNewSessionDurableEdit(saved.item.sessionId, 'pc')!;
+ expect(findNewSessionEditDraft('pc')).toBeUndefined();
+ const remote = vi.fn();
+ await withNewSessionCreationRemoval(saved.item.sessionId, 'pc', status, remote);
+ leave();
+ expect(remote).not.toHaveBeenCalled();
+ expect(getCurrentMobileOutboxRecords()).toEqual([]);
+ expect(mobileDurableOutbox.getSnapshot()[0].cleanupOutcome).toBe('cancelled');
+ await mobileDurableOutbox.activate('');
+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
+ expect(restoreNewSessionDurableEdit(mobileDurableOutbox.getSnapshot()[0])).toBe(false);
+ expect(findNewSessionEditDraft('pc')).toBeUndefined();
+ expect(remoteSessionStore.getSessions()).toEqual([]);
+});
+
+it('keeps a saved draft if durable deletion fails', async () => {
+ await harness().run();
+ const original = getCurrentMobileOutboxRecords()[0];
+ const saved = await mobileDurableOutbox.update(original, cancelledCreationDraft(original));
+ disk.fail = true;
+ await expect(withNewSessionCreationRemoval(saved.item.sessionId, 'pc', 'deleted', vi.fn())).rejects.toThrow('disk unavailable');
+ disk.fail = false;
+ expect(findNewSessionEditDraft('pc')).toEqual(saved);
+});
+
+it.each(['success', 'not-found', 'network-error', 'superseded', 'account-change'] as const)(
+ 'retires outbox recovery only after authoritative removal: %s', async outcome => {
+ await harness().run();
+ const saved = await mobileDurableOutbox.update(getCurrentMobileOutboxRecords()[0], { state: 'failed' });
+ let current = true;
+ const remove = vi.fn(async () => {
+ if (outcome === 'superseded') current = false;
+ if (outcome === 'account-change') setMobileAuthOwner('bob', 'global');
+ if (outcome === 'not-found') throw new Error('[NOT_FOUND] missing');
+ if (outcome === 'network-error') throw new Error('offline');
+ return { id: saved.item.sessionId };
+ });
+ const result = withNewSessionCreationRemoval(saved.item.sessionId, 'pc', 'deleted', remove, () => current);
+ if (outcome === 'not-found') await expect(result).rejects.toThrow('NOT_FOUND');
+ else if (outcome === 'network-error') await expect(result).rejects.toThrow('offline');
+ else if (outcome === 'account-change') await expect(result).rejects.toThrow('STALE_AUTH_OWNER');
+ else await result;
+ expect(remove).toHaveBeenCalledOnce();
+ expect(mobileDurableOutbox.getSnapshot()[0].cleanupOutcome).toBe(
+ outcome === 'success' || outcome === 'not-found' ? 'cancelled' : undefined);
+ });
diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
index e6d535d6d3..5f97194053 100644
--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
@@ -312,12 +312,14 @@ describe('mobile optimistic composer while session is not ready', () => {
// create-failed 的「返回编辑」会连合成会话行一起删掉:不把 outbox 一并 stash,
// unmount cleanup 会把那些消息写进一个即将消失的会话草稿,用户再也找不回(review P1)。
const source = readSource(SCREEN);
- const backToEditStart = source.indexOf("text: t('session.screen.backToEdit')");
- const backToEditEnd = source.indexOf("text: t('session.screen.retry')", backToEditStart);
+ const backToEditStart = source.indexOf("useFailedCreationReturnToEdit({");
+ const backToEditEnd = source.indexOf("const prevCreationStatusRef", backToEditStart);
const branch = source.slice(backToEditStart, backToEditEnd);
// 跨页导航:upload controller 随会话页销毁,在途上传保不住,只能取消 + 告知。
expect(branch).toContain("takeOutboxForSession(sessionId, 'cancel')");
- expect(branch).toContain('returnNewSessionToEdit({');
+ expect(branch).toContain('useFailedCreationReturnToEdit({');
+ expect(branch).not.toContain('Alert.alert');
+ expect(source).not.toContain('retryNewSessionCreation');
expect(branch).toContain('stashDraft: prepared => {');
const recovery = readSource('src/session/returnNewSessionToEdit.ts');
const stash = recovery.indexOf('stashDraft(prepared);');
diff --git a/apps/mobile/src/__tests__/orphanSessionActions.test.ts b/apps/mobile/src/__tests__/orphanSessionActions.test.ts
index dd81d1942e..2f0542f2b7 100644
--- a/apps/mobile/src/__tests__/orphanSessionActions.test.ts
+++ b/apps/mobile/src/__tests__/orphanSessionActions.test.ts
@@ -44,6 +44,7 @@ function fixture() {
remoteSessionStore: store, isExplicitRemoteNotFoundError, pickWriteFields, writeGuardFields,
goBackToHome: vi.fn(), Alert: { alert: vi.fn() }, humanizeRemoteError: String,
animateListChange: undefined, t: (key: string) => key,
+ withNewSessionCreationRemoval: (_sid: string, _device: string, _status: string, remove: () => Promise<unknown>) => remove(),
};
return { bindings, reject, store, release, isLatest };
}
diff --git a/apps/mobile/src/__tests__/useFailedCreationReturnToEdit.test.tsx b/apps/mobile/src/__tests__/useFailedCreationReturnToEdit.test.tsx
new file mode 100644
index 0000000000..32fb83eeda
--- /dev/null
+++ b/apps/mobile/src/__tests__/useFailedCreationReturnToEdit.test.tsx
@@ -0,0 +1,152 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useFailedCreationReturnToEdit } from '@/session/useFailedCreationReturnToEdit';
+import type { NewSessionCreationTask } from '@/session/newSessionCreation';
+import type { returnNewSessionToEdit } from '@/session/returnNewSessionToEdit';
+
+const state = vi.hoisted(() => ({ recover: vi.fn(), owner: 1 }));
+vi.mock('@/session/returnNewSessionToEdit', () => ({ returnNewSessionToEdit: state.recover }));
+vi.mock('@/auth/authOwnerGeneration', () => ({
+ getMobileAuthOwner: () => state.owner,
+ isMobileAuthOwnerCurrent: (owner: number) => owner === state.owner,
+}));
+const failedTask = (): NewSessionCreationTask => ({
+ sessionId: 'task', deviceId: 'device', deviceName: 'PC', status: 'create-failed',
+ startedAt: 1, phase: 'creating', error: 'Model unavailable',
+ firstMessageClientId: 'first', attachments: [],
+ draft: { agentKind: 'codex', workspaceKind: 'dialogue', model: 'model', effort: 'medium',
+ permissionMode: 'auto', workingDir: '', providerId: 'openai', fastMode: false, firstMessage: 'My draft' },
+});
+type Props = Parameters<typeof useFailedCreationReturnToEdit>[0];
+type Recovery = Parameters<typeof returnNewSessionToEdit>[0];
+function Screen(props: Props) {
+ useFailedCreationReturnToEdit(props);
+ return <span>Chat</span>;
+}
+let root: Root;
+let container: HTMLDivElement;
+let props: Props;
+let pending: Recovery;
+let finish: () => void;
+const actEnvironment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
+let previousActEnvironment: boolean | undefined;
+const render = () => act(async () => root.render(<Screen {...props} />));
+beforeEach(() => {
+ previousActEnvironment = actEnvironment.IS_REACT_ACT_ENVIRONMENT;
+ actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
+ state.owner = 1;
+ state.recover.mockReset().mockImplementation((options: Recovery) => {
+ pending = options;
+ return new Promise<void>(resolve => { finish = resolve; });
+ });
+ props = { task: failedTask(), focused: true, connectionEpoch: 1,
+ stashDraft: vi.fn(), onReady: vi.fn(), onError: vi.fn() };
+ container = document.createElement('div');
+ document.body.append(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ actEnvironment.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment;
+});
+
+it.each(['running', 'enqueue-failed'] as const)('keeps %s in chat without returning to edit', async status => {
+ props.task = { ...failedTask(), status };
+ await render();
+ expect(container.textContent).toBe('Chat');
+ expect(state.recover).not.toHaveBeenCalled();
+});
+
+it('automatically recovers creation failure once and hands the saved draft to the form', async () => {
+ await render();
+ props.task = { ...props.task!, returningToEdit: true };
+ await render();
+ expect(state.recover).toHaveBeenCalledTimes(1);
+ expect(pending.stashDraft).toBe(props.stashDraft);
+ const params = { deviceId: 'device', deviceName: 'PC', recoverySessionId: 'task' };
+ await act(async () => { pending.onReady(params); finish(); });
+ expect(props.onReady).toHaveBeenCalledExactlyOnceWith(params);
+ props.task = { ...props.task!, readyForEdit: 'durable', returningToEdit: false };
+ await render();
+ expect(state.recover).toHaveBeenCalledTimes(1);
+});
+
+it.each(['leave', 'blur', 'account', 'task'] as const)('ignores late navigation after %s', async change => {
+ await render();
+ const old = pending;
+ if (change === 'leave') await act(async () => root.render(null));
+ if (change === 'blur') { props.focused = false; await render(); }
+ if (change === 'account') state.owner += 1;
+ if (change === 'task') { props.task = { ...failedTask(), sessionId: 'other' }; await render(); }
+ expect(old.isCurrent()).toBe(false);
+ old.onReady({ deviceId: 'device', deviceName: 'PC', editSessionId: 'task' });
+ expect(props.onReady).not.toHaveBeenCalled();
+});
+
+it('starts recovery only when the failed task is focused', async () => {
+ props.focused = false;
+ await render();
+ expect(state.recover).not.toHaveBeenCalled();
+ props.focused = true;
+ await render();
+ expect(state.recover).toHaveBeenCalledTimes(1);
+});
+
+it('resumes a prepared draft after recovery started on an earlier mount', async () => {
+ props.task = { ...failedTask(), returningToEdit: true };
+ state.recover.mockResolvedValue(undefined);
+ await render();
+ props.task = { ...failedTask(), readyForEdit: 'memory' };
+ state.recover.mockImplementation(async (options: Recovery) => {
+ options.onReady({ deviceId: 'device', deviceName: 'PC', editSessionId: 'task' });
+ });
+ await render();
+ expect(props.onReady).toHaveBeenCalledExactlyOnceWith({
+ deviceId: 'device', deviceName: 'PC', editSessionId: 'task',
+ });
+});
+
+it('reports cleanup failure without a retry loop and resumes after reconnect', async () => {
+ const error = new Error('cleanup pending');
+ state.recover.mockRejectedValue(error);
+ await render();
+ expect(props.onError).toHaveBeenCalledExactlyOnceWith(error);
+ expect(props.onReady).not.toHaveBeenCalled();
+ props.task = { ...failedTask(), returningToEdit: true };
+ await render();
+ props.task = { ...failedTask(), returningToEdit: false };
+ await render();
+ expect(state.recover).toHaveBeenCalledTimes(1);
+ props.connectionEpoch += 1;
+ await render();
+ expect(state.recover).toHaveBeenCalledTimes(2);
+});
+
+// Replaces the former Alert-action lifecycle cases: recovery now starts automatically.
+it.each(['current', 'leave', 'blur', 'account', 'task'] as const)('reports a delayed recovery error only on its current page: %s', async change => {
+ let reject!: (error: Error) => void;
+ state.recover.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));
+ await render();
+ if (change === 'leave') await act(async () => root.render(null));
+ if (change === 'blur') { props.focused = false; await render(); }
+ if (change === 'account') state.owner += 1;
+ if (change === 'task') { props.task = { ...failedTask(), sessionId: 'other' }; await render(); }
+ await act(async () => reject(new Error('cleanup pending')));
+ expect(props.onError).toHaveBeenCalledTimes(change === 'current' ? 1 : 0);
+ expect(props.onReady).not.toHaveBeenCalled();
+});
+
+it('does not lose an in-flight recovery result when the connection changes', async () => {
+ let reject!: (error: Error) => void;
+ state.recover.mockImplementationOnce(() => new Promise((_resolve, fail) => { reject = fail; }));
+ await render();
+ state.recover.mockResolvedValue(undefined); // the shared helper holds the existing recovery
+ props.connectionEpoch += 1;
+ await render();
+ const error = new Error('disk full');
+ await act(async () => reject(error));
+ expect(props.onError).toHaveBeenCalledExactlyOnceWith(error);
+});
diff --git a/apps/mobile/src/session/CindyMakeSessionGate.tsx b/apps/mobile/src/session/CindyMakeSessionGate.tsx
index e1fef6dedc..b1621279b2 100644
--- a/apps/mobile/src/session/CindyMakeSessionGate.tsx
+++ b/apps/mobile/src/session/CindyMakeSessionGate.tsx
@@ -8,7 +8,7 @@ import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';
import { remoteSessionStore } from './remoteSessionStore';
import { MainWindowActionButton } from '@/components/MobilePrimitives';
import { useNewSessionCreationTask } from './newSessionCreation';
-import { LocalSessionCreationRecovery, SessionEntryStatus } from './SessionEntryRecovery';
+import { SessionEntryStatus } from './SessionEntryRecovery';
export const SESSION_ENTRY_LOOKUP_TIMEOUT_MS = 20_000;
type Lookup = { key: string; status: 'loading' | 'failed' | 'missing' | 'timedOut' | 'loaded' };
@@ -37,7 +37,7 @@ export function CindyMakeSessionGate({ sessionId, deviceId: routeDeviceId, child
&& (!deviceId || session.deviceLinkDeviceId === deviceId));
const knownSource = knownSession?.source;
const task = useNewSessionCreationTask(sessionId);
- const localCreation = task?.deviceId === deviceId
+ const localCreation = task?.sessionId === sessionId && task.deviceId === deviceId
&& (task.status === 'running' || task.status === 'create-failed') ? task : null;
const creationBlocked = localCreation !== null;
const [attempt, setAttempt] = useState(0);
@@ -85,15 +85,11 @@ export function CindyMakeSessionGate({ sessionId, deviceId: routeDeviceId, child
loaded?.scope === scope ? loaded.source : undefined
);
if (!CINDY_MAKE_ENABLED && isCindyMakeSource(source)) return <Redirect href="/" />;
- if (localCreation && (localCreation.readyForEdit || localCreation.worktreeCleanupAcknowledged)) {
- return <LocalSessionCreationRecovery
- key={JSON.stringify([sessionId, deviceId, accountGeneration, localCreation.startedAt, localCreation.status])}
- task={localCreation} />;
- }
+ // Locally initiated tasks already have an optimistic message/composer. Keep
+ // that screen mounted; it also owns automatic draft recovery after failure.
+ // File routes still require confirmed remote metadata.
+ if (localCreation && ownsSessionSubscription) return children;
if (!CINDY_MAKE_ENABLED && source === undefined) {
- if (localCreation) return <LocalSessionCreationRecovery
- key={JSON.stringify([sessionId, deviceId, accountGeneration, localCreation.startedAt, localCreation.status])}
- task={localCreation} />;
const status = lookup?.key === key ? lookup.status : 'loading';
return <SessionEntryStatus title={t('session.entry.title')}
copy={t(`session.entry.${status}`)} loading={status === 'loading'}>
diff --git a/apps/mobile/src/session/SessionEntryRecovery.tsx b/apps/mobile/src/session/SessionEntryRecovery.tsx
index 87738692ea..9afafcb123 100644
--- a/apps/mobile/src/session/SessionEntryRecovery.tsx
+++ b/apps/mobile/src/session/SessionEntryRecovery.tsx
@@ -1,15 +1,12 @@
-import { useEffect, useRef, useState, type ReactNode } from 'react';
+import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { useRouter } from 'expo-router';
import { ActivityIndicator, ScrollView, StyleSheet, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { MainWindowActionButton, MainWindowEmptyState } from '@/components/MobilePrimitives';
-import { formatRemoteError } from '@/device-link/remoteStatus';
import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
import { spacing } from '@/theme/tokens';
import { goBackGuarded } from '@/utils/backGuard';
-import { retryNewSessionCreation, type NewSessionCreationTask } from './newSessionCreation';
-import { returnNewSessionToEdit } from './returnNewSessionToEdit';
/** Local entry chrome stays available even when remote task content cannot mount. */
export function SessionEntryStatus({ title, copy, loading, children }: {
@@ -37,56 +34,6 @@ export function SessionEntryStatus({ title, copy, loading, children }: {
);
}
-/** Render creation progress/recovery without granting access to unknown remote content. */
-export function LocalSessionCreationRecovery({ task }: { task: NewSessionCreationTask }) {
- const { t } = useTranslation();
- const router = useRouter();
- const alive = useRef(true);
- const editing = useRef(false);
- const [pending, setPending] = useState(false);
- const busy = pending || task.returningToEdit === true;
- const [editError, setEditError] = useState<string | null>(null);
- useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
- const failed = task.status === 'create-failed';
- const backToEdit = async () => {
- if (editing.current || busy) return;
- editing.current = true;
- setPending(true);
- setEditError(null);
- try {
- await returnNewSessionToEdit({
- sessionId: task.sessionId, deviceId: task.deviceId, isCurrent: () => alive.current,
- onReady: params => router.replace({ pathname: '/sessions/new', params }),
- });
- } catch (error) {
- if (alive.current) setEditError(formatRemoteError(error));
- } finally {
- editing.current = false;
- if (alive.current) setPending(false);
- }
- };
- return (
- <SessionEntryStatus
- title={t(failed ? 'session.screen.createFailedTitle' : 'session.new.slowSend.creating')}
- copy={editError ?? (failed
- ? task.error ?? t('session.screen.createFailedDefault')
- : t(`session.new.slowSend.${task.phase}`))}
- loading={!failed || busy}
- >
- {failed ? <>
- <MainWindowActionButton action={{
- label: t('session.screen.retry'), testID: 'session.creationRetry', disabled: busy || !!task.readyForEdit || !!task.worktreeCleanupAcknowledged,
- onPress: () => { if (!editing.current && !busy && !task.readyForEdit && !task.worktreeCleanupAcknowledged) retryNewSessionCreation(task.sessionId); },
- }} numberOfLines={0} />
- <MainWindowActionButton action={{
- label: t('session.screen.backToEdit'), testID: 'session.creationEdit', busy,
- onPress: () => { void backToEdit(); },
- }} numberOfLines={0} />
- </> : null}
- </SessionEntryStatus>
- );
-}
-
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
root: { flex: 1, backgroundColor: colors.surface },
content: { flexGrow: 1, justifyContent: 'center', padding: spacing.xl },
diff --git a/apps/mobile/src/session/newSessionCreation.ts b/apps/mobile/src/session/newSessionCreation.ts
index 06e537cd8e..aa0c1a910d 100644
--- a/apps/mobile/src/session/newSessionCreation.ts
+++ b/apps/mobile/src/session/newSessionCreation.ts
@@ -8,7 +8,7 @@
* openLink / createSession / 首条消息 enqueue 全部在本模块后台串行完成。
*
* 状态机:running → done(task 移除)
- * → create-failed(会话页横幅:重试[同 id 幂等安全] / 返回编辑[草稿回填])
+ * → create-failed(保留草稿与附件,自动返回编辑)
* → enqueue-failed(会话已建成:乐观气泡摘除、草稿+附件回填 composer,
* 用户走正常 handleSend 重发)
*
@@ -52,6 +52,7 @@ import type { DeviceProvidersPayload } from '@/device-link/deviceProvidersCache'
import { remoteSessionStore } from '@/session/remoteSessionStore';
import { getCurrentMobileOutboxRecords, holdDurableOutboxCreation, isDurableOutboxCreationHeld, mobileDurableOutbox, persistCancelledCreationDraft, suspendCreationDraftForCleanup } from './mobileDurableOutbox';
import { isDurableOutboxSettled, type DurableOutboxRecord } from './durableOutbox';
+import { isExplicitRemoteNotFoundError } from './newSessionWorktree';
import {
forgetPendingPrecreatedWorktree,
parseDiscardPrecreatedAck,
@@ -599,21 +600,88 @@ function getDurableEditTask(sessionId: string): NewSessionCreationTask | null {
return task;
}
-/** Rebuild only the local recovery entry, never restart a cancelled pipeline. */
+/** Saved editor drafts are not tasks. Keep them out of the task list. */
export function restoreNewSessionDurableEdit(record: DurableOutboxRecord): boolean {
if (!isDurableEditRecord(record) || !record.creation) return false;
// Claiming already removes the synthetic row. Do not repeatedly delete a
// later authoritative mirror row while the editor still holds this record.
if (hasLiveNewSessionCreation(record.item.sessionId) || claimedDurableEdits.has(durableEditKey(record))) return true;
- if (!remoteSessionStore.getSessions().some(session => session.id === record.item.sessionId)) {
- remoteSessionStore.upsertDeviceSession(record.deviceId, record.creation.deviceName, {
- ...sessionFromCreateResult({ sessionId: record.item.sessionId }, record.creation.draft),
- pendingLocalCreation: true,
- });
+ const row = remoteSessionStore.getSessions().find(session => session.id === record.item.sessionId);
+ if (row?.pendingLocalCreation && row.deviceLinkDeviceId === record.deviceId) {
+ dismissRecoveredPrecreatedSession({ sessionId: record.item.sessionId, deviceId: record.deviceId });
}
return true;
}
+/** A blank new-task form resumes the latest saved draft for its own device/project. */
+export function findNewSessionEditDraft(deviceId: string, workingDir?: string | null): DurableOutboxRecord | undefined {
+ return getCurrentMobileOutboxRecords().filter(record => record.deviceId === deviceId
+ && isDurableEditRecord(record) && !hasLiveNewSessionCreation(record.item.sessionId)
+ && !claimedDurableEdits.has(durableEditKey(record))
+ && (!workingDir || record.creation?.draft.workingDir === workingDir))
+ .sort((a, b) => b.createdAt - a.createdAt)[0];
+}
+
+/** All removal entry points retire recovery data as well as the visible row. */
+export async function withNewSessionCreationRemoval<T>(
+ sessionId: string,
+ deviceId: string,
+ status: string | undefined,
+ remove: () => Promise<T>,
+ isCurrent: () => boolean = () => true,
+): Promise<T | undefined> {
+ if ((status !== 'deleted' && status !== 'archived') || !isCurrent()) return remove();
+ const owner = getMobileAuthOwner();
+ const task = tasks.get(sessionId);
+ const localFailure = task?.deviceId === deviceId && task.status === 'create-failed' && isTaskOwnerCurrent(task);
+ const savedDraft = getCurrentMobileOutboxRecords().some(record => record.deviceId === deviceId
+ && record.item.sessionId === sessionId && isDurableEditRecord(record));
+ const failedDraft = getCurrentMobileOutboxRecords().some(record => record.deviceId === deviceId
+ && record.item.sessionId === sessionId && record.creation && record.state === 'failed');
+ if (!localFailure && !savedDraft && !failedDraft) return remove();
+ const release = localFailure ? beginNewSessionReturnToEdit(sessionId) : null;
+ if (localFailure && !release) throw new Error(i18n.t('session.new.worktreeCleanupPending'));
+ const retire = async () => {
+ if (!isCurrent()) return;
+ let hasRecovery = localFailure || savedDraft;
+ for (const record of getCurrentMobileOutboxRecords()) {
+ if (!isMobileAuthOwnerCurrent(owner)) throw new Error('STALE_AUTH_OWNER');
+ if (!isCurrent()) return;
+ if (record.deviceId !== deviceId || record.item.sessionId !== sessionId) continue;
+ hasRecovery = true;
+ await mobileDurableOutbox.update(record, {
+ suspended: true, state: 'host-owned', cleanupOutcome: 'cancelled', cancelRequested: true, error: undefined,
+ });
+ }
+ if (!isMobileAuthOwnerCurrent(owner)) throw new Error('STALE_AUTH_OWNER');
+ if (!hasRecovery || !isCurrent()) return;
+ dismissNewSessionCreation(sessionId, { removeSyntheticRow: true });
+ dismissRecoveredPrecreatedSession({ sessionId, deviceId });
+ };
+ try {
+ const prepared = localFailure ? await prepareNewSessionCreationForEdit(sessionId) : null;
+ if (!isMobileAuthOwnerCurrent(owner)) throw new Error('STALE_AUTH_OWNER');
+ if (!isCurrent()) return;
+ if (prepared || (!task && savedDraft)) {
+ await retire();
+ return;
+ }
+ let result: T;
+ try {
+ result = await remove();
+ } catch (error) {
+ // An exact host NOT_FOUND is also an authoritative removal. Preserve the
+ // existing callers' mirror reconciliation, but end outbox resurrection.
+ if (isExplicitRemoteNotFoundError(error)) await retire();
+ throw error;
+ }
+ await retire();
+ return result;
+ } finally {
+ release?.();
+ }
+}
+
/** Host cancellation ACK is authoritative; keep the durable outbox draft for editing. */
export function dismissRecoveredPrecreatedSession(record: { sessionId: string; deviceId: string }): void {
if (tasks.has(record.sessionId)) return;
@@ -767,7 +835,7 @@ export function completeNewSessionDurableEdit(sessionId: string, deviceId: strin
claims.delete(key);
if (!isMobileAuthOwnerCurrent(owner)) return;
// Follow the stable durable identity through draft updates and cancelled-ID
- // rotation. Only its latest, still-paused edit record may regain an entry.
+ // rotation. The draft remains available to the new-task form, never a row.
const latest = getCurrentMobileOutboxRecords().find(record => durableEditKey(record) === key);
if (latest && restoreNewSessionDurableEdit(latest)) emit();
};
diff --git a/apps/mobile/src/session/useFailedCreationReturnToEdit.ts b/apps/mobile/src/session/useFailedCreationReturnToEdit.ts
new file mode 100644
index 0000000000..c6af465a65
--- /dev/null
+++ b/apps/mobile/src/session/useFailedCreationReturnToEdit.ts
@@ -0,0 +1,54 @@
+import { useEffect, useRef } from 'react';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import type { NewSessionCreationTask } from './newSessionCreation';
+import { returnNewSessionToEdit } from './returnNewSessionToEdit';
+
+type RecoveryOptions = Parameters<typeof returnNewSessionToEdit>[0];
+
+/** A failed creation has one next step: restore its draft in the new-task form. */
+export function useFailedCreationReturnToEdit({ task, focused, connectionEpoch, stashDraft, onReady, onError }: {
+ task: NewSessionCreationTask | null;
+ focused: boolean;
+ connectionEpoch: number;
+ stashDraft: RecoveryOptions['stashDraft'];
+ onReady: RecoveryOptions['onReady'];
+ onError: (error: unknown) => void;
+}) {
+ const callbacks = useRef({ stashDraft, onReady, onError });
+ callbacks.current = { stashDraft, onReady, onError };
+ const navigated = useRef<string | null>(null);
+ const sessionId = task?.sessionId;
+ const deviceId = task?.deviceId;
+ const failed = task?.status === 'create-failed';
+ const startedAt = task?.startedAt;
+ const readyForEdit = task?.readyForEdit;
+ const current = useRef({ sessionId, deviceId, startedAt, focused });
+ current.current = { sessionId, deviceId, startedAt, focused };
+ const mounted = useRef(false);
+ useEffect(() => {
+ mounted.current = true;
+ return () => { mounted.current = false; };
+ }, []);
+ useEffect(() => {
+ if (!failed || !focused || !sessionId || !deviceId) return;
+ const identity = JSON.stringify([deviceId, sessionId, startedAt]);
+ if (navigated.current === identity) return;
+ const owner = getMobileAuthOwner();
+ const isCurrent = () => mounted.current && current.current.focused
+ && current.current.sessionId === sessionId && current.current.deviceId === deviceId
+ && current.current.startedAt === startedAt && isMobileAuthOwnerCurrent(owner);
+ void returnNewSessionToEdit({
+ sessionId, deviceId, isCurrent,
+ stashDraft: callbacks.current.stashDraft,
+ onReady: params => {
+ if (!isCurrent() || navigated.current === identity) return;
+ navigated.current = identity;
+ callbacks.current.onReady(params);
+ },
+ }).catch(error => {
+ if (isCurrent()) callbacks.current.onError(error);
+ });
+ // Recovery itself continues after leaving. Re-entry (or restored connection)
+ // can resume the existing recovery; ordinary store updates never retry it.
+ }, [sessionId, deviceId, failed, startedAt, focused, connectionEpoch, readyForEdit]);
+}
diff --git a/apps/mobile/src/session/useSessionListActions.ts b/apps/mobile/src/session/useSessionListActions.ts
index 37d92371cd..3578bcec57 100644
--- a/apps/mobile/src/session/useSessionListActions.ts
+++ b/apps/mobile/src/session/useSessionListActions.ts
@@ -24,6 +24,7 @@ import {
type SessionSwipeAction,
} from '@/session/swipeRowRegistry';
import type { RemoteSession } from '@/session/types';
+import { withNewSessionCreationRemoval } from '@/session/newSessionCreation';
/**
* 首页与设备详情共用的任务行写回 / 滑动 / 选项菜单 / 重命名。
@@ -59,7 +60,8 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()
}
const releasePending = sessionPendingWrites.track(session.id, fields);
try {
- const updated = await sessionMetaWriteQueue.enqueue(session.id, fields, () => retryPatchWhileLatest(
+ const updated = await withNewSessionCreationRemoval(session.id, rpcDeviceId, patch.status,
+ () => sessionMetaWriteQueue.enqueue(session.id, fields, () => retryPatchWhileLatest(
write.isLatest,
(assertStillLatest) => invoke<RemoteSession>(
rpcDeviceId,
@@ -67,7 +69,7 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()
[session.id, patch],
{ preSend: assertStillLatest },
),
- ));
+ )), write.isLatest);
if (updated && write.isLatest()) {
const currentUpdatedAt = remoteSessionStore.getSessions()
.find((s) => s.id === session.id)?.updatedAt ?? null;
diff --git a/docs/dev-rules/mobile-development.md b/docs/dev-rules/mobile-development.md
index b35f438974..f7d94f059b 100644
--- a/docs/dev-rules/mobile-development.md
+++ b/docs/dev-rules/mobile-development.md
@@ -83,26 +83,31 @@ pnpm --filter mobile test:smoke
### 任务入口与创建失败恢复
-- 来源未确认时不挂载远端任务内容,但必须显示读取状态和返回入口;读取失败、空记录或
+- 非本机发起的任务来源未确认时不挂载远端任务内容,但必须显示读取状态和返回入口;读取失败、空记录或
超时允许手动重读当前任务,不重置共享设备连接。账号或设备切换后忽略旧读取结果。
-- 本地创建进行中或失败时,来源门禁显示创建进度或失败原因;失败时直接提供重试和返回编辑,
- 不依赖尚不存在的远端任务记录。返回编辑复用 worktree 补偿和持久草稿恢复流程;
+- 本地新建任务立即显示乐观消息与输入框,不因远端来源尚未返回而显示整页等待卡。
+ 仅创建失败时自动带回草稿与附件并返回编辑,不提供重试、返回编辑等选择菜单;
+ 已建成任务的首条消息发送失败仍在原任务内恢复,不退回新建页。失败原因带到编辑页。
+ 返回编辑复用 worktree 补偿和持久草稿恢复流程;
回收或保存失败保留原任务与草稿。回收开始后离页仍完成同账号的草稿恢复,
仅取消跳转;账号切换后停止旧账号操作,并移除旧代次的内存创建记录及同步阻挡,
避免切回原账号后阻塞发件箱恢复;保留持久发件箱草稿,不执行远端删除。
同一账号代次内,非持久化草稿留在对应失败任务中,
只有带匹配任务与设备标识、同账号代次的新建表单可领取;领取后才清理原任务。
- 领取前保留返回编辑入口,禁止重试已回收的创建;不写全局单槽,不混入普通新建表单。
+ 领取前保留失败任务,重新进入时自动返回编辑,禁止重试已回收的创建;不写全局单槽,不混入普通新建表单。
持久发件箱保存完成后同样保留失败任务与恢复入口,直到匹配账号、设备和任务的新建
表单实际恢复内容才清理任务;离页重进不重复回收或保存,也不解除暂停自动发送。
- 返回编辑意图写入持久发件箱;应用重启后按该标记或已确认回收的记录重建本地恢复入口,
- 不启动创建管线。表单领取只在表单存续期间抑制重复入口;未提交就离开时释放领取,
- 恢复仍待编辑的记录入口,重启也可找回。认领按持久存储身份跟随草稿更新与取消后的任务 ID
+ 返回编辑意图写入持久发件箱;退出编辑或应用重启后保留草稿,不重建任务列表行,
+ 不启动创建管线。空白新建页自动恢复当前设备(项目入口还须匹配目录)的最新未领取草稿;
+ 不覆盖用户已输入的文字、附件、模型或目录选择,也不覆盖带预设内容的新建入口。
+ 明确删除或归档失败任务时复用 worktree 回收,并持久结束发件箱恢复;列表、详情与批量入口一致,
+ 离页、重启和后台恢复均不能复活已删除记录。回收或持久保存失败时保留恢复材料。
+ 认领按持久存储身份跟随草稿更新与取消后的任务 ID
轮换;重新提交保留恢复标记及发送暂停,直到后台创建管线接管。未交接就失败或离页时,恢复
- 最新文字与附件,不复活旧记录。提交仍在进行时保持互斥;合成恢复入口不阻塞 worktree
+ 最新文字与附件,不复活旧记录。提交仍在进行时保持互斥;保存的草稿不阻塞 worktree
账本对账。已交接、移除或换账号的记录不由旧表单恢复。
worktree 回收成功确认一到达即禁止重试原创建;后续持久保存失败时保留返回编辑,
- 再次操作只补做保存与恢复账本收尾,不重复回收或重用已删除目录。
+ 重新进入任务或连接恢复后自动补做保存与恢复账本收尾,不重复回收或重用已删除目录。
远端回收前必须先持久暂停匹配发件箱记录;写入失败不发回收请求。回收中切换账号
仍保留该暂停和恢复账本,切回后先对账,不自动向可能已删除的目录投递。
已确认来源的任务在重连时保持内容挂载。
@@ -111,7 +116,8 @@ pnpm --filter mobile test:smoke
正常内容时保留订阅,最终离页时清理。
实现与回归:`CindyMakeSessionGate.tsx`、`SessionEntryRecovery.tsx`、
-`returnNewSessionToEdit.ts`、`cindyMakeSessionGate.test.tsx` 与 `newSessionCreation.test.ts`。
+`useFailedCreationReturnToEdit.ts`、`returnNewSessionToEdit.ts`、`cindyMakeSessionGate.test.tsx`、
+`useFailedCreationReturnToEdit.test.tsx` 与 `newSessionCreation.test.ts`。
### 消息缓存与首页偏好