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): fence late input projections

Dashdc01d5e85618
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index bfc3e757d4..b9e8ae1e4f 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -3134,19 +3134,27 @@ export default function SessionScreen() {
const activeSessions = await maker.listActiveSessions().catch(() => []);
return { activeSessions, activityEpochAtFetchStart };
};
+ const fetchProjection = async () => {
+ // Capture immediately before every request. Because this helper is invoked inside
+ // withTransientRemoteRetry, each retry receives a fresh projection authority fence.
+ const authorityEpochAtStart =
+ remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);
+ const projection = await maker.input.getProjection(sessionId);
+ return { projection, authorityEpochAtStart };
+ };
if (syncRun.isStale()) return;
setLoading(true);
setError(null);
try {
if (!isReopen) {
// 首开 / 强制替换:A1 全量并行(含整窗 listMessages),不回退。
- const [sessionMeta, history, pendingInteractions, projection, activeSessionSnapshot] = await withTransientRemoteRetry(async () => {
+ const [sessionMeta, history, pendingInteractions, projectionResult, activeSessionSnapshot] = await withTransientRemoteRetry(async () => {
await openAndSubscribe();
return Promise.all([
maker.getSession(sessionId),
listMessagesWithPayloadRetry((limit) => maker.listMessages(sessionId, { limit })),
maker.getPendingInteractions(sessionId),
- maker.input.getProjection(sessionId),
+ fetchProjection(),
fetchActiveSessionSnapshot(),
]);
});
@@ -3172,15 +3180,19 @@ export default function SessionScreen() {
remoteSessionStore.markSessionMessagesSynced(sessionId, sessionMeta);
setHasOlderMessages(moreBeyondWindow);
remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : []);
- remoteSessionStore.setInputProjection(sessionId, projection);
+ remoteSessionStore.setInputProjectionIfCurrent(
+ sessionId,
+ projectionResult.projection,
+ projectionResult.authorityEpochAtStart,
+ );
} else {
// 重开:便宜并行(不含整窗 listMessages)拿 meta + pending + projection + active。
- const [sessionMeta, pendingInteractions, projection, activeSessionSnapshot] = await withTransientRemoteRetry(async () => {
+ const [sessionMeta, pendingInteractions, projectionResult, activeSessionSnapshot] = await withTransientRemoteRetry(async () => {
await openAndSubscribe();
return Promise.all([
maker.getSession(sessionId),
maker.getPendingInteractions(sessionId),
- maker.input.getProjection(sessionId),
+ fetchProjection(),
fetchActiveSessionSnapshot(),
]);
});
@@ -3224,7 +3236,11 @@ export default function SessionScreen() {
}
remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);
remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : []);
- remoteSessionStore.setInputProjection(sessionId, projection);
+ remoteSessionStore.setInputProjectionIfCurrent(
+ sessionId,
+ projectionResult.projection,
+ projectionResult.authorityEpochAtStart,
+ );
}
// 不变量:上面 setHasOlderMessages 的校正(:806/:841/:846)与这里的 setLastSyncedAt 之间必须保持
// 同步尾、无 await —— 否则乐观点亮 effect(依赖 lastSyncedAt===null)会在 await 间隙把刚校正成 false
@@ -5037,9 +5053,16 @@ export default function SessionScreen() {
// 与原路径同口径:先对账分辨「确实没应用」vs「已应用但响应丢了」。
const applied = await (async () => {
try {
+ const projectionEpochAtRequestStart =
+ remoteSessionStore.captureInputProjectionAuthorityEpoch(item.sessionId);
const fresh = await maker.input.getProjection(item.sessionId);
- remoteSessionStore.setInputProjection(item.sessionId, fresh);
- return fresh.pendingQueue.some((entry) => entry.clientId === queued.clientId);
+ const accepted = remoteSessionStore.setInputProjectionIfCurrent(
+ item.sessionId,
+ fresh,
+ projectionEpochAtRequestStart,
+ );
+ const current = accepted ? fresh : remoteSessionStore.getInputProjection(item.sessionId);
+ return current.pendingQueue.some((entry) => entry.clientId === queued.clientId);
} catch {
return remoteSessionStore.getInputProjection(item.sessionId).pendingQueue
.some((entry) => entry.clientId === queued.clientId);
@@ -5777,9 +5800,18 @@ export default function SessionScreen() {
// refetch 也失败再退回本地 store(订阅推送在此窗口内可能已带回该 clientId)。
const applied = await (async () => {
try {
+ const projectionEpochAtRequestStart =
+ remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);
const fresh = await maker.input.getProjection(sessionId);
- remoteSessionStore.setInputProjection(sessionId, fresh);
- return fresh.pendingQueue.some((item) => item.clientId === queued.clientId);
+ const accepted = remoteSessionStore.setInputProjectionIfCurrent(
+ sessionId,
+ fresh,
+ projectionEpochAtRequestStart,
+ );
+ // If a newer push/terminal boundary won the fence, the fetched value is
+ // stale for both the mirror and the applied decision; consult current state.
+ const current = accepted ? fresh : remoteSessionStore.getInputProjection(sessionId);
+ return current.pendingQueue.some((item) => item.clientId === queued.clientId);
} catch {
return remoteSessionStore.getInputProjection(sessionId).pendingQueue
.some((item) => item.clientId === queued.clientId);
@@ -6067,8 +6099,14 @@ export default function SessionScreen() {
deviceId,
);
const accepted = await maker.input.steer(sessionId, prepared, { removeFromQueue: true, touchUserSend: true });
+ const projectionEpochAtRequestStart =
+ remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);
const projection = await maker.input.getProjection(sessionId);
- applyProjection(projection);
+ remoteSessionStore.setInputProjectionIfCurrent(
+ sessionId,
+ projection,
+ projectionEpochAtRequestStart,
+ );
return accepted;
});
};
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 5d94f9b1ca..7e9e339b7d 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -2636,6 +2636,36 @@ describe('remoteSessionStore', () => {
});
});
+ it('rejects a late projection query after a newer push and terminal boundary', () => {
+ const ownerProjection = {
+ ...projection('s1'),
+ continuationTurnClientId: 'resume-1',
+ };
+ const expectedEpoch = remoteSessionStore.captureInputProjectionAuthorityEpoch('s1');
+ remoteSessionStore.setInputProjection('s1', ownerProjection);
+ const queryEpoch = remoteSessionStore.captureInputProjectionAuthorityEpoch('s1');
+
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:input:projection', {
+ ...projection('s1'),
+ continuationTurnClientId: null,
+ });
+ remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {
+ sessionId: 's1',
+ event: { type: 'done', data: {} },
+ });
+
+ expect(remoteSessionStore.setInputProjectionIfCurrent('s1', ownerProjection, queryEpoch)).toBe(false);
+ expect(remoteSessionStore.getInputProjection('s1').continuationTurnClientId).toBeNull();
+ expect(remoteSessionStore.isSessionMakerTurnRunning('s1')).toBe(false);
+ expect(remoteSessionStore.captureInputProjectionAuthorityEpoch('s1')).not.toBe(expectedEpoch);
+ });
+
+ it('accepts a projection query result when no newer authority event arrived', () => {
+ const expectedEpoch = remoteSessionStore.captureInputProjectionAuthorityEpoch('s1');
+ expect(remoteSessionStore.setInputProjectionIfCurrent('s1', projection('s1'), expectedEpoch)).toBe(true);
+ expect(remoteSessionStore.getInputProjection('s1').pendingQueue[0]?.clientId).toBe('q-1');
+ });
+
it('soft-invalidates an offline device without deleting sessions or messages', () => {
const meta = session('s1', {
updatedAt: '2026-01-01T00:00:01.000Z',
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 2a81e23f12..51eae7fee7 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -1127,6 +1127,8 @@ async function rebuildSessionSnapshot(
responsivenessCohort:
opts?.responsivenessCohort ?? createDeviceSendCohort(deviceId),
};
+ const projectionEpochAtRequestStart =
+ remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);
// 四路快照独立拉取、独立落库:断连补齐窗口本就脆弱,一个子请求失败不应拖垮
// 其余(旧实现共用一个 catch,任一失败三份快照全丢)。goal 覆盖断连窗口内
// 丢失的 maker:goal:status-changed push;model-pref / turn-cost 无对应查询通道,
@@ -1170,7 +1172,11 @@ async function rebuildSessionSnapshot(
remoteSessionStore.setPendingInteractions(sessionId, pending.value, { finalizeStreaming: true });
}
if (projection.status === 'fulfilled' && projection.value) {
- remoteSessionStore.setInputProjection(sessionId, projection.value);
+ remoteSessionStore.setInputProjectionIfCurrent(
+ sessionId,
+ projection.value,
+ projectionEpochAtRequestStart,
+ );
}
// undefined = 未拿到/未知(兼容形态的空返回),不能当作权威「无 goal」落库——
// 那会把在世的 goal 卡清掉直到下一条 push;只有显式 null 才代表确认无 goal。
diff --git a/apps/mobile/src/session/newSessionCreation.ts b/apps/mobile/src/session/newSessionCreation.ts
index f5170d31ac..f1cca22a94 100644
--- a/apps/mobile/src/session/newSessionCreation.ts
+++ b/apps/mobile/src/session/newSessionCreation.ts
@@ -714,9 +714,17 @@ async function isFirstMessageApplied(task: InternalTask): Promise<boolean | null
)) return true;
try {
assertTaskOwnerCurrent(task);
+ const projectionEpochAtRequestStart =
+ remoteSessionStore.captureInputProjectionAuthorityEpoch(task.sessionId);
const projection = await maker.input.getProjection(task.sessionId);
assertTaskOwnerCurrent(task);
- if (projection?.pendingQueue?.some((item) => item.clientId === clientId)) return true;
+ const accepted = remoteSessionStore.setInputProjectionIfCurrent(
+ task.sessionId,
+ projection,
+ projectionEpochAtRequestStart,
+ );
+ const current = accepted ? projection : remoteSessionStore.getInputProjection(task.sessionId);
+ if (current.pendingQueue.some((item) => item.clientId === clientId)) return true;
} catch (error) {
if (isStaleNewSessionOwnerError(error)) throw error;
return null;
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 7cf5f67873..e32abbd6e7 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -255,6 +255,12 @@ function interactionsByRequestId(list: readonly PendingInteraction[]): Map<strin
return byId;
}
const inputProjections = new Map<string, InputProjection>();
+// Projection queries can resolve after a newer push or terminal boundary. Keep
+// a monotonic per-session authority epoch so late snapshots cannot overwrite
+// current queue / continuation state (mirrors Desktop makerChatStore).
+const inputProjectionAuthorityEpochs = new Map<string, number>();
+let nextInputProjectionAuthorityEpoch = 0;
+let inputProjectionAuthorityEpochFloor = 0;
const sessionLiveActivity = new Map<string, RemoteSessionLiveActivity>();
const sessionRunning = new Map<string, boolean>();
const sessionRunStatus = new Map<string, RemoteSessionRunStatus>();
@@ -512,6 +518,19 @@ function emit(): void {
for (const sub of subs) sub();
}
+function bumpInputProjectionAuthorityEpoch(sessionId: string): number {
+ const epoch = ++nextInputProjectionAuthorityEpoch;
+ inputProjectionAuthorityEpochs.set(sessionId, epoch);
+ return epoch;
+}
+
+function commitInputProjection(sessionId: string, next: InputProjection): boolean {
+ if (deepValueEqual(inputProjections.get(sessionId) ?? EMPTY_INPUT_PROJECTION, next)) return false;
+ inputProjections.set(sessionId, next);
+ emit();
+ return true;
+}
+
function recomputeSessions(): void {
sessionDeviceIndex.clear();
// 跨 shard 去重 + 设备身份归一化。re-link 后同一 session.id 可能同时存在于 stale / current 两个 shard;
@@ -1836,9 +1855,31 @@ export const remoteSessionStore = {
setInputProjection(sessionId: string, projection: unknown): void {
const next = normalizeInputProjection(projection, sessionId);
- if (deepValueEqual(inputProjections.get(sessionId) ?? EMPTY_INPUT_PROJECTION, next)) return;
- inputProjections.set(sessionId, next);
- emit();
+ bumpInputProjectionAuthorityEpoch(sessionId);
+ commitInputProjection(sessionId, next);
+ },
+
+ captureInputProjectionAuthorityEpoch(sessionId: string): number {
+ return inputProjectionAuthorityEpochs.get(sessionId) ?? inputProjectionAuthorityEpochFloor;
+ },
+
+ setInputProjectionIfCurrent(
+ sessionId: string,
+ projection: unknown,
+ expectedEpoch: number,
+ ): boolean {
+ const currentEpoch = inputProjectionAuthorityEpochs.get(sessionId) ?? inputProjectionAuthorityEpochFloor;
+ if (currentEpoch !== expectedEpoch) {
+ return false;
+ }
+ const next = normalizeInputProjection(projection, sessionId);
+ bumpInputProjectionAuthorityEpoch(sessionId);
+ commitInputProjection(sessionId, next);
+ return true;
+ },
+
+ invalidateInputProjectionAuthority(sessionId: string): void {
+ bumpInputProjectionAuthorityEpoch(sessionId);
},
setSessionRunning(
@@ -1847,6 +1888,9 @@ export const remoteSessionStore = {
boundaryAgentMeta?: Record<string, unknown> | null,
): void {
if (!sessionId) return;
+ // A maker turn boundary supersedes any projection query that started
+ // before it. This is the terminal fence for late owner snapshots.
+ bumpInputProjectionAuthorityEpoch(sessionId);
// 本方法只被 maker 权威信号调用(done / terminal error / status-changed closed),
// 与 maker turn 边界同步;activity / 快照流走 writeSessionRunStatus,不经过这里。
// 边界变化必须独立参与 emit 判定:activity 流可能已把宽 run status 置 false,此时
@@ -2548,6 +2592,7 @@ export const remoteSessionStore = {
// 投影没了,这份(空)列表就不再权威:重连拿到全量快照前不许据此做清理。
changed = pendingInteractionsAuthoritative.delete(sessionId) || changed;
changed = inputProjections.delete(sessionId) || changed;
+ bumpInputProjectionAuthorityEpoch(sessionId);
changed = sessionLiveActivity.delete(sessionId) || changed;
changed = sessionGoalStatus.delete(sessionId) || changed;
changed = sessionTaskUpdates.delete(sessionId) || changed;
@@ -2577,6 +2622,7 @@ export const remoteSessionStore = {
pendingInteractions.delete(sessionId);
pendingInteractionsAuthoritative.delete(sessionId);
inputProjections.delete(sessionId);
+ bumpInputProjectionAuthorityEpoch(sessionId);
sessionLiveActivity.delete(sessionId);
sessionRunning.delete(sessionId);
sessionRunStatus.delete(sessionId);
@@ -2625,6 +2671,10 @@ export const remoteSessionStore = {
confirmedInteractionDismissals.clear();
interactionRevisionFloors.clear();
inputProjections.clear();
+ inputProjectionAuthorityEpochFloor = ++nextInputProjectionAuthorityEpoch;
+ inputProjectionAuthorityEpochs.clear();
+ // Keep authority tombstones monotonic across a global store reset so an
+ // old in-flight query cannot be accepted after the session is recreated.
sessionLiveActivity.clear();
sessionRunning.clear();
sessionRunStatus.clear();