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): reconcile task state with its source host

Chrisf943de5b4558
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 09a76b31a0..a49c8b18c3 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -3887,7 +3887,7 @@ function SessionScreenContent() {
throw error;
}),
commitRead('pending', fetchPendingInteractions, (pendingInteractions) => {
- remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : []);
+ remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : [], { deviceId });
}),
commitRead('projection', fetchProjection, (projectionResult) => {
remoteSessionStore.setInputProjectionIfCurrent(
diff --git a/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx b/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx
index f2a91da287..67a95714be 100644
--- a/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionMessageCard.test.tsx
@@ -264,6 +264,40 @@ it.each(['running', 'completed'] as const)('keeps the owning computer\'s %s stat
expect(openEntry()?.disabled).toBe(false);
});
+// Review regression: a push can beat both task lists during reconnect. Choosing
+// the row must retain same-host evidence and discard a different host's evidence.
+it.each(['home', 'other'])('reconciles %s activity received before the task list', async (source) => {
+ remoteSessionStore.applyRemotePush(source, SESSION_ACTIVITY_CHANNEL, { sessionId: 'child', phase: 'running' });
+ h.invoke.mockRejectedValue(new Error('read failed'));
+ await render();
+ await act(async () => remoteSessionStore.setDeviceSessions('home', 'Mac', [
+ { id: 'child', title: 'Own task', status: 'active' } as RemoteSession,
+ ]));
+ expect(node.textContent).toContain(`devices.companions.status.${source === 'home' ? 'running' : 'unknown'}`);
+ expect(openEntry()?.disabled).toBe(false);
+});
+
+// Detail/reconnect snapshots share this production store entry. Exercise both
+// arrival orders and retain same-host snapshots, including an authoritative clear.
+it.each(['before', 'after'])('scopes pending snapshots received %s the owning row', async (order) => {
+ const row = () => remoteSessionStore.setDeviceSessions('home', 'Mac', [
+ { id: 'child', title: 'Own task', status: 'active' } as RemoteSession,
+ ]);
+ const pending = [{ request: { kind: 'permission' as const, requestId: 'permission-1' } }];
+ if (order === 'after') row();
+ remoteSessionStore.setPendingInteractions('child', pending, { deviceId: 'other', finalizeStreaming: true });
+ if (order === 'before') row();
+ h.invoke.mockRejectedValue(new Error('read failed'));
+ await render();
+ expect(node.textContent).toContain('devices.companions.status.unknown');
+ await act(async () => remoteSessionStore.setPendingInteractions('child', pending, { deviceId: 'home' }));
+ expect(node.textContent).toContain('devices.companions.status.waiting');
+ await act(async () => remoteSessionStore.setPendingInteractions('child', [], { deviceId: 'other' }));
+ expect(node.textContent).toContain('devices.companions.status.waiting');
+ await act(async () => remoteSessionStore.setPendingInteractions('child', [], { deviceId: 'home' }));
+ expect(node.textContent).not.toContain('devices.companions.status.waiting');
+});
+
// A missing activity relay must not hide an interaction already known to the list.
it('shows waiting for pending interactions without activity and clears it after dismissal', async () => {
remoteSessionStore.setDeviceSessions('home', 'Mac', [{ id: 'child', title: 'Own task', status: 'active' } as RemoteSession]);
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index ec6333b17e..bc4d309fcd 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -1859,7 +1859,7 @@ async function rebuildSessionSnapshot(
const applyPending = (value: PendingInteraction[]) => {
if (!isCurrent()) return false;
if (Array.isArray(value)) {
- remoteSessionStore.setPendingInteractions(sessionId, value, { finalizeStreaming: true });
+ remoteSessionStore.setPendingInteractions(sessionId, value, { finalizeStreaming: true, deviceId });
return true;
}
return false;
diff --git a/apps/mobile/src/session/BotGroupSpeakerRow.tsx b/apps/mobile/src/session/BotGroupSpeakerRow.tsx
index b07b6613e4..159a1f4bad 100644
--- a/apps/mobile/src/session/BotGroupSpeakerRow.tsx
+++ b/apps/mobile/src/session/BotGroupSpeakerRow.tsx
@@ -49,7 +49,7 @@ export function BotGroupSpeakerRow({ deviceId, identity, sessionId, activity, on
const offTopic = startFocusedTopicSubscription({ deviceId, owner: `bot-group-speaker:${lane}`, topic: `session:${lane}`, subscribe, unsubscribe });
// Seed prompts raised before this screen subscribed; later ones arrive as pushes.
void invoke<PendingInteraction[]>(deviceId, 'maker:get-pending-interactions', [lane]).then((list) => {
- if (!cancelled && Array.isArray(list)) remoteSessionStore.setPendingInteractions(lane, list);
+ if (!cancelled && Array.isArray(list)) remoteSessionStore.setPendingInteractions(lane, list, { deviceId });
}).catch(() => undefined);
return () => { cancelled = true; offTopic(); };
}, [deviceId, invoke, lane, online, subscribe, unsubscribe]));
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index b1c2744210..eecb714273 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -389,6 +389,10 @@ const INPUT_PROJECTION_REMOTE_EVIDENCE_LIMIT = 256;
const sessionLiveActivity = new Map<string, RemoteSessionLiveActivity>();
const sessionRunning = new Map<string, boolean>();
const sessionRunStatus = new Map<string, RemoteSessionRunStatus>();
+// Pushes can precede the first task list. Keep their provenance until list
+// reconciliation can decide whether they belong to the selected task row.
+const sessionRuntimeSources = new Map<string, string>();
+const sessionInteractionSources = new Map<string, string>();
// `maker:list-active` snapshots race live maker pushes during reconnect hydration. A snapshot
// may clear an older transient reconnect attempt, but must not erase a newer retry event that
// arrived after the request started.
@@ -1081,6 +1085,36 @@ function sessionStateWriteAllowed(sessionId: string, deviceId?: string): boolean
|| mergedSessionById.get(sessionId)?.canonicalDeviceId === deviceId;
}
+function clearSourcedSessionState(sessionId: string, sources: Map<string, string>): void {
+ sources.delete(sessionId);
+ if (sources === sessionInteractionSources) {
+ deletePendingInteractionState(sessionId);
+ pendingInteractionsAuthoritative.delete(sessionId);
+ } else {
+ deleteSessionLiveActivity(sessionId);
+ writeSessionRunStatus(sessionId, EMPTY_SESSION_RUN_STATUS);
+ writeMakerTurnRunning(sessionId, false);
+ sessionMakerActivityEpochs.delete(sessionId);
+ }
+}
+
+function acceptSessionStateSource(
+ sessionId: string,
+ deviceId: string | undefined,
+ sources: Map<string, string>,
+): boolean {
+ if (!sessionStateWriteAllowed(sessionId, deviceId)) return false;
+ if (!deviceId) return true; // Local optimistic updates retain their remote provenance.
+ const previous = sources.get(sessionId);
+ if (previous && previous !== deviceId && !(sessionDeviceIndex.has(sessionId)
+ && sessionStateWriteAllowed(sessionId, previous))) {
+ clearSourcedSessionState(sessionId, sources);
+ emit();
+ }
+ sources.set(sessionId, deviceId);
+ return true;
+}
+
function normalizeWindowForRetention(
sessionId: string,
list: readonly RemoteMessage[],
@@ -1136,6 +1170,8 @@ function invalidateSessionMessageWindowState(
}
function removeSessionRuntimeState(sessionId: string): void {
+ sessionRuntimeSources.delete(sessionId);
+ sessionInteractionSources.delete(sessionId);
protectedQuestions.delete(sessionId);
visibleInteractionCache.delete(sessionId);
void clearHistoryDisk(undefined, sessionId);
@@ -1669,6 +1705,13 @@ function recomputeSessions(): void {
reconcileVisibleSessions();
mergedSessionById.clear();
for (const session of mergedSessions) mergedSessionById.set(session.id, session);
+ for (const sources of [sessionRuntimeSources, sessionInteractionSources]) {
+ for (const [sessionId, deviceId] of sources) {
+ if (sessionDeviceIndex.has(sessionId) && !sessionStateWriteAllowed(sessionId, deviceId)) {
+ clearSourcedSessionState(sessionId, sources);
+ }
+ }
+ }
// Usage-only patches bypass this projection and cannot change Home fields.
// Reuse the list comparison above to skip its scan and allocations entirely.
if (sessionsChanged) reconcileHomeSessions();
@@ -4175,8 +4218,9 @@ export const remoteSessionStore = {
setPendingInteractions(
sessionId: string,
list: readonly PendingInteraction[],
- options: { finalizeStreaming?: boolean } = {},
+ options: { finalizeStreaming?: boolean; deviceId?: string } = {},
): void {
+ if (!acceptSessionStateSource(sessionId, options.deviceId, sessionInteractionSources)) return;
// 已确认 dismiss 的延长抑制条目按「缺席即过期」回收:本轮快照不含该
// requestId = 被控端已确认移除,慢的旧快照此后不可能再带着它(权威读取按
// 请求序返回),条目可以安全解除;仍含 = 这是 resolve 前发出的旧快照,保留
@@ -4369,6 +4413,7 @@ export const remoteSessionStore = {
}
let changed = false;
for (const [sessionId, { running, activityPhase, activityAttention }] of snapshotStates) {
+ acceptSessionStateSource(sessionId, deviceId, sessionRuntimeSources);
if (!running) {
changed = flushAndFinalizeRemoteStreamingMessages(sessionId) || changed;
changed = writeMakerTurnRunning(sessionId, false) || changed;
@@ -4687,7 +4732,7 @@ export const remoteSessionStore = {
if (channel === 'maker:status-changed' && isRecord(payload)) {
const sessionId = readString(payload, 'sessionId');
const status = readString(payload, 'status');
- if (sessionId && status === 'closed' && sessionStateWriteAllowed(sessionId, deviceId)) this.setSessionRunning(sessionId, false);
+ if (sessionId && status === 'closed' && acceptSessionStateSource(sessionId, deviceId, sessionRuntimeSources)) this.setSessionRunning(sessionId, false);
return;
}
if (channel === 'usage:message-turn-cost' && isRecord(payload)) {
@@ -4786,7 +4831,7 @@ export const remoteSessionStore = {
if (channel === 'maker:interaction-request' && isRecord(payload)) {
const sessionId = readString(payload, 'sessionId');
const request = isRecord(payload.request) ? payload.request : null;
- if (sessionId && request && sessionStateWriteAllowed(sessionId, deviceId)) {
+ if (sessionId && request && acceptSessionStateSource(sessionId, deviceId, sessionInteractionSources)) {
this.applyInteractionRequest(sessionId, {
request: request as PendingInteraction['request'],
persistId: readString(payload, 'persistId') ?? undefined,
@@ -4797,7 +4842,7 @@ export const remoteSessionStore = {
if (channel === 'maker:interaction-dismissed' && isRecord(payload)) {
const sessionId = readString(payload, 'sessionId');
const requestId = readString(payload, 'requestId');
- if (sessionId && requestId && sessionStateWriteAllowed(sessionId, deviceId)) {
+ if (sessionId && requestId && acceptSessionStateSource(sessionId, deviceId, sessionInteractionSources)) {
if (payload.reason === 'resolved' && !(isRecord(payload.decision) && payload.decision.dismissed === true)) {
this.confirmProtectedQuestion(sessionId, requestId);
}
@@ -4838,7 +4883,7 @@ export const remoteSessionStore = {
const sessionId = readString(payload, 'sessionId');
const phase = readString(payload, 'phase');
if (!sessionId || !isRemoteSessionLiveActivityPhase(phase)
- || !sessionStateWriteAllowed(sessionId, deviceId)) return;
+ || !acceptSessionStateSource(sessionId, deviceId, sessionRuntimeSources)) return;
markSessionMakerActivity(sessionId);
const compactDetail = typeof payload.compactDetail === 'string' ? payload.compactDetail : '';
let changed = false;
@@ -4906,7 +4951,7 @@ export const remoteSessionStore = {
// Text has its own transport replacement/retention rules; only fence the
// runtime signals here, so reconnecting transports keep their existing data path.
if ((type === 'status' || type === 'done' || type === 'error')
- && !sessionStateWriteAllowed(sessionId, deviceId)) return;
+ && !acceptSessionStateSource(sessionId, deviceId, sessionRuntimeSources)) return;
markSessionMakerActivity(sessionId);
const reconnectCleared = type !== null && type !== 'error' && type !== 'done'
? clearSessionReconnectAttempt(sessionId)
@@ -5358,6 +5403,8 @@ export const remoteSessionStore = {
bumpHomeStatusVersion();
}
sessionRunStatus.clear();
+ sessionRuntimeSources.clear();
+ sessionInteractionSources.clear();
sessionMakerActivityEpochs.clear();
makerActivityEpoch = 0;
sessionMessageSyncMarkers.clear();