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): 存档预检保留详情与此前元数据写入

Dasha5c947419c3f
diff --git a/apps/mobile/src/__tests__/orphanSessionActions.test.ts b/apps/mobile/src/__tests__/orphanSessionActions.test.ts
index dfb6bc3291..1ff12eaef2 100644
--- a/apps/mobile/src/__tests__/orphanSessionActions.test.ts
+++ b/apps/mobile/src/__tests__/orphanSessionActions.test.ts
@@ -3,7 +3,8 @@ import { resolve } from 'node:path';
import ts from 'typescript';
import { describe, expect, it, vi } from 'vitest';
import { isExplicitRemoteNotFoundError } from '@/session/newSessionWorktree';
-import { pickWriteFields, writeGuardFields } from '@/session/swipeRowRegistry';
+import { createLatestWriteGuard, pickWriteFields, retryPatchWhileLatest, writeGuardFields } from '@/session/swipeRowRegistry';
+import { createDisclosureController, commitRegisteredLevel, detachDisclosureScope, runDisclosure } from '@/session/listDisclosureController';
// Execute the production callbacks without mounting the entire native screen.
function callback(file: string, name: string, bindings: Record<string, unknown>) {
@@ -31,6 +32,7 @@ function fixture() {
const pending = new Promise((_resolve, fail) => { reject = fail; });
const store = {
applySessionPatch: vi.fn(), upsertDeviceSession: vi.fn(), requestReseed: vi.fn(),
+ beginSessionListRemovalPreview: vi.fn(() => vi.fn()),
getSessions: () => [session],
};
const release = vi.fn();
@@ -62,7 +64,8 @@ describe('orphan task status actions', () => {
const preparation = new Promise<boolean>((resolve, reject) => { finish = resolve; fail = reject; });
const patch = callback('src/session/useSessionListActions.ts', 'patchSession', f.bindings);
const request = patch(session, { status: 'archived' }, () => preparation);
- expect(f.store.applySessionPatch).toHaveBeenCalledWith('shard', 's1', { status: 'archived' }, { deferRemovalCleanup: true });
+ expect(f.store.beginSessionListRemovalPreview).toHaveBeenCalledWith('s1');
+ expect(f.store.applySessionPatch).not.toHaveBeenCalled();
expect(f.bindings.sessionMetaWriteQueue.enqueue).not.toHaveBeenCalled();
if (outcome === 'superseded') f.isLatest.mockReturnValue(false);
if (outcome === 'fail') {
@@ -73,8 +76,85 @@ describe('orphan task status actions', () => {
await request;
}
expect(f.bindings.sessionMetaWriteQueue.enqueue).not.toHaveBeenCalled();
- expect(f.store.upsertDeviceSession).toHaveBeenCalledTimes(outcome === 'superseded' ? 0 : 1);
+ expect(f.store.upsertDeviceSession).not.toHaveBeenCalled();
expect(f.release).toHaveBeenCalled();
+ expect(f.store.beginSessionListRemovalPreview.mock.results[0].value).toHaveBeenCalledOnce();
+ });
+
+ // PR #6863 review r4353650369: the real field guard used to invalidate a
+ // pending title/pin write before archive confirmation. Existing fixtures only
+ // mocked isLatest, so they could not observe the lost retry eligibility.
+ it.each(['title', 'pinnedAt', 'status'] as const)('cancelled archive preserves a pending %s write', async (field) => {
+ const f = fixture();
+ const guard = createLatestWriteGuard();
+ const prior = guard.begin(session.id, [field]);
+ let finish!: (confirmed: boolean) => void;
+ const preparation = new Promise<boolean>(resolve => { finish = resolve; });
+ const patch = callback('src/session/useSessionListActions.ts', 'patchSession', {
+ ...f.bindings, sessionMetaWriteGuard: guard,
+ });
+ const request = patch(session, { status: 'archived' }, () => preparation);
+ expect(prior.isLatest()).toBe(true);
+ finish(false);
+ await request;
+ const send = vi.fn(async () => ({ [field]: 'saved' }));
+ expect(await retryPatchWhileLatest(prior.isLatest, send)).toEqual({ [field]: 'saved' });
+ expect(send).toHaveBeenCalledOnce();
+ expect(f.store.upsertDeviceSession).not.toHaveBeenCalled();
+ });
+
+ it('a later status write prevents delayed archive confirmation from committing', async () => {
+ const f = fixture();
+ const guard = createLatestWriteGuard();
+ let finish!: (confirmed: boolean) => void;
+ const preparation = new Promise<boolean>(resolve => { finish = resolve; });
+ const patch = callback('src/session/useSessionListActions.ts', 'patchSession', {
+ ...f.bindings, sessionMetaWriteGuard: guard,
+ });
+ const request = patch(session, { status: 'archived' }, () => preparation);
+ guard.begin(session.id, ['status']);
+ finish(true);
+ await request;
+ expect(f.bindings.sessionMetaWriteQueue.enqueue).not.toHaveBeenCalled();
+ expect(f.store.applySessionPatch).not.toHaveBeenCalled();
+ expect(f.store.beginSessionListRemovalPreview.mock.results[0].value).toHaveBeenCalledOnce();
+ });
+
+ it('confirmed archive supersedes old writes and rolls back to metadata saved during preflight', async () => {
+ const f = fixture();
+ const guard = createLatestWriteGuard();
+ const prior = guard.begin(session.id, ['title']);
+ const updatedRow = { ...session, title: 'Saved during preflight' };
+ f.store.getSessions = () => [updatedRow];
+ const patch = callback('src/session/useSessionListActions.ts', 'patchSession', {
+ ...f.bindings, sessionMetaWriteGuard: guard,
+ });
+ const request = patch(session, { status: 'archived' }, async () => true);
+ await tick();
+ expect(prior.isLatest()).toBe(false);
+ expect(f.store.applySessionPatch).toHaveBeenCalledWith('shard', 's1', { status: 'archived' });
+ f.reject(new Error('network unavailable'));
+ await expect(request).rejects.toThrow('network unavailable');
+ expect(f.store.upsertDeviceSession).toHaveBeenCalledWith('shard', 'PC', updatedRow);
+ });
+
+ // Production list transitions may defer their callback until a layout effect.
+ // A fast confirmation must not leave an unpaired hidden-row preview behind.
+ it('pairs a cancelled preview with its release when list animation defers the mutation', async () => {
+ const f = fixture();
+ const controller = createDisclosureController();
+ controller.setLevel = vi.fn();
+ const prepare = vi.fn(async () => false);
+ const patch = callback('src/session/useSessionListActions.ts', 'patchSession', {
+ ...f.bindings, animateListChange: (apply: () => void) => runDisclosure(controller, apply, 1, true),
+ });
+ const request = patch(session, { status: 'archived' }, prepare);
+ expect(prepare).not.toHaveBeenCalled();
+ commitRegisteredLevel(controller, 1);
+ await request;
+ expect(f.store.beginSessionListRemovalPreview.mock.results[0].value).toHaveBeenCalledOnce();
+ expect(f.store.applySessionPatch).not.toHaveBeenCalled();
+ detachDisclosureScope(controller);
});
it.each(['archived', 'deleted', 'active'])('list status %s retires the mirror without rollback', async (status) => {
const f = fixture();
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 3c6353d714..5ea18cd7d8 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -41,9 +41,10 @@ function message(id: string, sessionId: string): RemoteMessage {
};
}
-// Unit regression: preflight now runs after optimistic removal. Cancellation
-// must retain conversation content; successful removal must still release it.
-it('keeps messages through archive preflight cancellation and cleans up after success', () => {
+// Unit, PR #6863 r4353650385: existing removal coverage retained messages but
+// lost the raw metadata read by useRemoteSessionDetail. A preview must hide only
+// the visible/Home projections, retaining title, status and messages for details.
+it('keeps detail metadata and messages while an archive preview hides only the list row', () => {
remoteSessionStore.clear();
const row = session('s1');
remoteSessionStore.setDeviceSessions('dev-1', 'Computer', [row]);
@@ -51,19 +52,43 @@ it('keeps messages through archive preflight cancellation and cleans up after su
const removed = vi.fn();
const off = remoteSessionStore.onSessionRemoved(removed);
try {
- remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'archived' }, { deferRemovalCleanup: true });
- expect(remoteSessionStore.getSessions()).toEqual([]);
+ const finishPreview = remoteSessionStore.beginSessionListRemovalPreview('s1');
+ expect(remoteSessionStore.getVisibleSessions()).toEqual([]);
+ expect(remoteSessionStore.getHomeSessions()).toEqual([]);
+ expect(remoteSessionStore.getSessions()[0]).toMatchObject({ id: 's1', title: 's1', status: 'active' });
expect(remoteSessionStore.getMessages('s1')).toHaveLength(1);
expect(removed).not.toHaveBeenCalled();
- remoteSessionStore.upsertDeviceSession('dev-1', 'Computer', row);
+ remoteSessionStore.setDeviceSessions('dev-1', 'Computer', [row]);
+ expect(remoteSessionStore.getVisibleSessions()).toEqual([]);
+ remoteSessionStore.applySessionPatch('dev-1', 's1', { title: 'Saved rename' });
+ finishPreview();
+ expect(remoteSessionStore.getHomeSessions()[0].title).toBe('Saved rename');
expect(remoteSessionStore.getMessages('s1')[0].content).toBe('hello');
- remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'archived' }, { deferRemovalCleanup: true });
+ const finishConfirmedPreview = remoteSessionStore.beginSessionListRemovalPreview('s1');
remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'archived' });
+ finishConfirmedPreview();
+ expect(remoteSessionStore.getSessions()).toEqual([]);
expect(remoteSessionStore.getMessages('s1')).toEqual([]);
expect(removed).toHaveBeenCalledExactlyOnceWith('dev-1', 's1');
} finally { off(); remoteSessionStore.clear(); }
});
+it('finishing an older archive preview keeps a newer preview hidden and cannot revive a removed row', () => {
+ remoteSessionStore.clear();
+ remoteSessionStore.setDeviceSessions('dev-1', 'Computer', [session('s1')]);
+ const older = remoteSessionStore.beginSessionListRemovalPreview('s1');
+ const newer = remoteSessionStore.beginSessionListRemovalPreview('s1');
+ older();
+ older();
+ expect(remoteSessionStore.getHomeSessions()).toEqual([]);
+ expect(remoteSessionStore.getSessions()).toHaveLength(1);
+ remoteSessionStore.applySessionPatch('dev-1', 's1', { status: 'deleted' });
+ newer();
+ expect(remoteSessionStore.getSessions()).toEqual([]);
+ expect(remoteSessionStore.getHomeSessions()).toEqual([]);
+ remoteSessionStore.clear();
+});
+
// Unit: side-chat details are omitted by the Host list. A list refresh must
// retain opened details without leaking them into Home, and deletion must still
// remove them. Existing tests only cover ordinary listed task reconciliation.
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 00a72d7c7a..aa71053370 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -114,6 +114,9 @@ export type RemoteNewMakerWorktreeBranchPreference = {
* 字段,防止同字段旧写的 push 回流把本机更新的乐观意图滚回(review P2)。
*/
export const sessionPendingWrites = createPendingWriteTracker();
+// List-only previews reuse the existing counted tracker. Raw rows remain available
+// to details and metadata reconciliation until archive is actually confirmed.
+let sessionListRemovalPreviews = createPendingWriteTracker();
/**
* 会话元数据写序守卫与出网队列(app 级单例):首页滑动操作与会话详情页菜单是同一组
@@ -1778,6 +1781,7 @@ function sameElementRefs<T>(a: readonly T[], b: readonly T[]): boolean {
function reconcileVisibleSessions(): void {
const next = mergedSessions.filter((session) => session.source !== 'side-chat'
+ && sessionListRemovalPreviews.pendingFields(session.id).length === 0
&& (CINDY_MAKE_ENABLED || !isCindyMakeSource(session.source)));
if (!sameElementRefs(visibleSessions, next)) visibleSessions = next;
}
@@ -3669,12 +3673,19 @@ export const remoteSessionStore = {
recomputeSessions();
},
- applySessionPatch(
- deviceId: string,
- sessionId: string,
- patch: Partial<RemoteSession>,
- options?: { deferRemovalCleanup?: boolean },
- ): void {
+ /** Hide only the list projection; release never restores an old metadata snapshot. */
+ beginSessionListRemovalPreview(sessionId: string): () => void {
+ const release = sessionListRemovalPreviews.track(sessionId, ['status']);
+ const refresh = () => {
+ reconcileVisibleSessions();
+ reconcileHomeSessions();
+ emit();
+ };
+ refresh();
+ return () => { release(); refresh(); };
+ },
+
+ applySessionPatch(deviceId: string, sessionId: string, patch: Partial<RemoteSession>): void {
// Local optimistic removals must fence a late startup cache just like remote pushes,
// even when the removed row has not reached this shard yet.
if (patch.status === 'deleted' || patch.status === 'archived') bumpDeviceSessionListMutationEpoch(deviceId);
@@ -3682,10 +3693,7 @@ export const remoteSessionStore = {
const idx = shard?.sessions.findIndex((s) => s.id === sessionId) ?? -1;
if (!shard || idx === -1) {
if (patch.status === 'deleted' || patch.status === 'archived') {
- if (!options?.deferRemovalCleanup) {
- cleanupRemovedSession(deviceId, sessionId, patch.status === 'deleted');
- sessionRemovalListeners.forEach(listener => listener(deviceId, sessionId));
- }
+ sessionRemovalListeners.forEach(listener => listener(deviceId, sessionId));
}
// Separate host-owned lists can include children never opened in this mirror.
// Terminal changes invalidate those lists just as unseen creations do.
@@ -3698,9 +3706,7 @@ export const remoteSessionStore = {
const turnEnded = historyTurnEnded(shard.sessions[idx], patch);
if (patch.status === 'deleted' || patch.status === 'archived') {
shard.sessions = shard.sessions.filter((s) => s.id !== sessionId);
- if (!options?.deferRemovalCleanup) {
- cleanupRemovedSession(deviceId, sessionId, patch.status === 'deleted');
- }
+ cleanupRemovedSession(deviceId, sessionId, patch.status === 'deleted');
} else {
const wasPinned = shard.sessions[idx].pinnedAt != null;
const unpinned = Object.prototype.hasOwnProperty.call(patch, 'pinnedAt') && patch.pinnedAt == null;
@@ -3728,7 +3734,7 @@ export const remoteSessionStore = {
shouldReseedAfterPatch = wasPinned && unpinned;
}
recomputeSessions();
- if ((patch.status === 'deleted' || patch.status === 'archived') && !options?.deferRemovalCleanup) {
+ if (patch.status === 'deleted' || patch.status === 'archived') {
sessionRemovalListeners.forEach(listener => listener(deviceId, sessionId));
}
if (turnEnded && patch.status !== 'deleted' && patch.status !== 'archived') {
@@ -5542,6 +5548,7 @@ export const remoteSessionStore = {
sessionListRefreshArmed.clear();
sessionListRefreshSeen.clear();
pendingTitlePreview.clear();
+ sessionListRemovalPreviews = createPendingWriteTracker();
mergedSessions = [];
visibleSessions = [];
mergedSessionById.clear();
diff --git a/apps/mobile/src/session/swipeRowRegistry.ts b/apps/mobile/src/session/swipeRowRegistry.ts
index d38e8f0f78..5094b2b706 100644
--- a/apps/mobile/src/session/swipeRowRegistry.ts
+++ b/apps/mobile/src/session/swipeRowRegistry.ts
@@ -54,9 +54,10 @@ export interface LatestWriteGuard {
/**
* 开始一笔写:立即把本笔登记为该 key 下 fields 各字段的最新写。返回的 isLatest()
* 实时判断本笔是否仍是全部字段的最新(后续对同 key 的**交集字段**再 begin 才会使
- * 旧笔过期;字段无交集的写互不取代)。
+ * 旧笔过期;字段无交集的写互不取代)。observeFields 只观察当前代次、不使旧写过期,
+ * 用于确认前预检:后续 status 写能取消预检,取消预检不能丢弃此前的 status 写。
*/
- begin(key: string, fields: readonly string[]): { isLatest(): boolean };
+ begin(key: string, fields: readonly string[], observeFields?: readonly string[]): { isLatest(): boolean };
}
/**
@@ -75,15 +76,19 @@ export interface LatestWriteGuard {
export function createLatestWriteGuard(): LatestWriteGuard {
const seqs = new Map<string, number>();
return {
- begin(key, fields) {
+ begin(key, fields, observeFields = []) {
const mine = fields.map((field) => {
const slot = `${key} ${field}`;
const seq = (seqs.get(slot) ?? 0) + 1;
seqs.set(slot, seq);
return [slot, seq] as const;
});
+ const observed = observeFields.map((field) => {
+ const slot = `${key} ${field}`;
+ return [slot, seqs.get(slot)] as const;
+ });
return {
- isLatest: () => mine.every(([slot, seq]) => seqs.get(slot) === seq),
+ isLatest: () => [...mine, ...observed].every(([slot, seq]) => seqs.get(slot) === seq),
};
},
};
diff --git a/apps/mobile/src/session/useSessionListActions.ts b/apps/mobile/src/session/useSessionListActions.ts
index 29c27173d1..b2a79a09dc 100644
--- a/apps/mobile/src/session/useSessionListActions.ts
+++ b/apps/mobile/src/session/useSessionListActions.ts
@@ -56,16 +56,26 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()
if (!devices) throw new Error(t('devices.list.error.sessionDeviceNotFound'));
const { rpcDeviceId, shardId } = devices;
const fields = Object.keys(patch);
- const write = sessionMetaWriteGuard.begin(session.id, writeGuardFields(patch));
- // 查询/确认期间只移走行,取消不应清掉已有消息与历史缓存。
- const applyOptimistic = () => remoteSessionStore.applySessionPatch(
- shardId, session.id, patch, prepare ? { deferRemovalCleanup: true } : undefined,
- );
- if ((patch.status !== undefined || patch.pinnedAt !== undefined) && animateListChange) {
- animateListChange(applyOptimistic);
- } else {
- applyOptimistic();
- }
+ // 预检只取代旧预检、观察 status;取消时不能作废此前仍在重试的元数据写。
+ let write = prepare
+ ? sessionMetaWriteGuard.begin(session.id, ['archive-preflight'], ['status'])
+ : sessionMetaWriteGuard.begin(session.id, writeGuardFields(patch));
+ let rollbackSession = session;
+ let applied = false;
+ let finishPreview: (() => void) | undefined;
+ const updateList = (apply: () => void): Promise<void> => new Promise((resolve, reject) => {
+ const commit = () => {
+ try { apply(); resolve(); } catch (err) { reject(err); }
+ };
+ if (animateListChange) animateListChange(commit);
+ else commit();
+ });
+ const applyOptimistic = () => {
+ if (!write.isLatest()) return;
+ rollbackSession = remoteSessionStore.getSessions().find((s) => s.id === session.id) ?? session;
+ remoteSessionStore.applySessionPatch(shardId, session.id, patch);
+ applied = true;
+ };
const releasePending = sessionPendingWrites.track(session.id, fields);
const restoreSession = () => {
const shardName = remoteSessionStore.getSessions()
@@ -74,7 +84,7 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()
?? shardId;
releasePending();
const rollback = () => {
- remoteSessionStore.upsertDeviceSession(shardId, shardName, session);
+ remoteSessionStore.upsertDeviceSession(shardId, shardName, rollbackSession);
remoteSessionStore.requestReseed(shardId);
};
if (animateListChange) animateListChange(rollback);
@@ -82,13 +92,23 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()
};
try {
if (prepare) {
+ await updateList(() => {
+ if (write.isLatest()) finishPreview = remoteSessionStore.beginSessionListRemovalPreview(session.id);
+ });
+ if (!write.isLatest()) return;
const confirmed = await prepare(write.isLatest);
if (!write.isLatest()) return;
if (!confirmed) {
- restoreSession();
+ releasePending();
+ remoteSessionStore.requestReseed(shardId);
return;
}
+ // 只有确认后才取代全部元数据写,并真正移除详情/清理消息。
+ write = sessionMetaWriteGuard.begin(session.id, writeGuardFields(patch));
}
+ if (patch.status !== undefined || patch.pinnedAt !== undefined) await updateList(applyOptimistic);
+ else applyOptimistic();
+ if (!applied) return;
const updated = await withNewSessionCreationRemoval(session.id, rpcDeviceId, patch.status,
() => sessionMetaWriteQueue.enqueue(session.id, fields, () => retryPatchWhileLatest(
write.isLatest,
@@ -112,7 +132,10 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()
}
}
} catch (err) {
- if (write.isLatest()) {
+ if (!applied) {
+ releasePending();
+ remoteSessionStore.requestReseed(shardId);
+ } else if (write.isLatest()) {
if (fields.includes('status')) {
if (isExplicitRemoteNotFoundError(err)) {
remoteSessionStore.applySessionPatch(shardId, session.id, { status: 'deleted' });
@@ -142,6 +165,7 @@ export function useSessionListActions(options?: { animateListChange?: (apply: ()
throw err;
} finally {
releasePending();
+ if (finishPreview) await updateList(finishPreview);
}
}, [animateListChange, invoke, t]);
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 1161dd86cf..8a8b62e482 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -45,7 +45,9 @@ Cindy 的产品形态不止本地桌面单机。同一个功能可能运行在
桌面与手机的远程任务列表在点击存档后立即乐观移走任务行,不能等待远程预检或写入
返回才更新。既有的运行态、接管、worktree 与自动化确认仍在真正写入前执行;取消、
拦截或失败恢复列表,迟到的预检不能覆盖用户后续的恢复操作。预检期间保留任务内容,
-不提前清理消息或草稿;详情页在确认通过后再退出。手机详情菜单先收起,关闭动画结束后
+不提前清理消息或草稿;手机只从列表投影隐藏行,保留详情元数据和此前重命名、置顶的
+在途写入,确认后才取代这些写入并真正移除行。取消时解除隐藏,不拿旧快照覆盖期间
+已经保存的元数据。详情页在确认通过后再退出。手机详情菜单先收起,关闭动画结束后
再查询并弹确认,避免远程等待卡住菜单或原生弹窗被关闭动画吞掉。
实现与回归:Desktop `useSessionLifecycleActions`、`sharedTaskArchiveGuard.test.ts`;