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): 安卓发不出消息时不再锁死输入,切电脑不再被坏偏好卡住 (#5306)

unclecloudtxy756db95cb74a
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 463be0c08a..ca82d6c658 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -3194,7 +3194,20 @@ export default function SessionScreen() {
applyComposerDocument(nextDocument);
setComposerDraftHydrated(true);
}).catch((error) => {
- if (!cancelled) setError(formatRemoteError(error));
+ if (cancelled || appliedRouteDraftRef.current !== key) return;
+ const message = error instanceof Error ? error.message : String(error);
+ // A failed draft handoff must keep send() gated: the composer may still
+ // show a message the outbox already owns. Storage failures are different
+ // — they are not a pending handoff, and leaving hydrated false blocks
+ // every conversation.
+ const pendingHandoff = message.includes('COMPOSER_DRAFT_INVALID')
+ || message.includes('OUTBOX_STALE_WRITE')
+ || message.includes('OUTBOX_OWNER_CHANGED');
+ if (!pendingHandoff) {
+ setComposerDraftHydrated(true);
+ return;
+ }
+ setError(formatRemoteError(error));
});
return () => {
cancelled = true;
diff --git a/apps/mobile/src/__tests__/durableOutbox.test.ts b/apps/mobile/src/__tests__/durableOutbox.test.ts
index 26f1e7d61f..a57bdbf0bf 100644
--- a/apps/mobile/src/__tests__/durableOutbox.test.ts
+++ b/apps/mobile/src/__tests__/durableOutbox.test.ts
@@ -281,7 +281,7 @@ describe("durable mobile outbox ownership", () => {
expect(storage.data.size).toBe(1);
expect(deps.cleanup).not.toHaveBeenCalled();
});
- it.each(['keys', 'item', 'json'] as const)('retries failed %s loading through ready and add without losing persisted work', async (failure) => {
+ it.each(['keys', 'item'] as const)('retries failed %s loading through ready and add without losing persisted work', async (failure) => {
const storage = disk();
const seed = createDurableOutbox(storage);
await seed.activate('alice');
@@ -290,7 +290,6 @@ describe("durable mobile outbox ownership", () => {
const readItem = vi.spyOn(storage, 'getItem');
if (failure === 'keys') readKeys.mockRejectedValueOnce(new Error('busy'));
if (failure === 'item') readItem.mockRejectedValueOnce(new Error('busy'));
- if (failure === 'json') readItem.mockResolvedValueOnce('{broken');
const store = createDurableOutbox(storage);
await expect(store.activate('alice')).rejects.toThrow();
expect(store.getSnapshot()).toEqual([]);
@@ -300,16 +299,27 @@ describe("durable mobile outbox ownership", () => {
expect(store.getSnapshot().map((r) => r.item.clientId)).toEqual(['id-1', 'id-2']);
expect(readKeys).toHaveBeenCalledTimes(2);
});
- it('keeps corrupt storage intact across retries and does not allow add to overwrite it', async () => {
+ it('keeps a corrupt outbox row on disk without blocking the rest of the ledger', async () => {
const storage = disk();
const key = 'cindy.mobile.outbox.v1.alice/mac-a/session-a/id-1';
storage.data.set(key, '{broken');
const store = createDurableOutbox(storage);
- await expect(store.activate('alice')).rejects.toThrow();
- await expect(store.add(message())).rejects.toThrow();
- await expect(store.ready()).rejects.toThrow();
+ await store.activate('alice');
+ await store.add(message('id-2'));
+ await store.ready();
expect(storage.data.get(key)).toBe('{broken');
- expect(store.getSnapshot()).toEqual([]);
+ expect(store.getSnapshot().map((r) => r.item.clientId)).toEqual(['id-2']);
+ });
+
+ it('skips a JSON null ledger row instead of failing activation', async () => {
+ const storage = disk();
+ const key = 'cindy.mobile.outbox.v1.alice/mac-a/session-a/id-1';
+ storage.data.set(key, 'null');
+ const store = createDurableOutbox(storage);
+ await store.activate('alice');
+ await store.add(message('id-2'));
+ expect(storage.data.get(key)).toBe('null');
+ expect(store.getSnapshot().map((r) => r.item.clientId)).toEqual(['id-2']);
});
it('does not let an old activation failure invalidate the new account loading', async () => {
const storage = disk();
diff --git a/apps/mobile/src/__tests__/homeViewPreferenceStore.test.ts b/apps/mobile/src/__tests__/homeViewPreferenceStore.test.ts
index ce526f4619..2960b727a5 100644
--- a/apps/mobile/src/__tests__/homeViewPreferenceStore.test.ts
+++ b/apps/mobile/src/__tests__/homeViewPreferenceStore.test.ts
@@ -44,11 +44,20 @@ describe('homeViewPreferenceStore', () => {
expect((await readHomeViewPreferences()).groupDialogue).toBe(true);
});
- it('preserves corrupt stored JSON instead of replacing it with defaults on save', async () => {
- const { __testing, saveHomeViewPreferences } = await import('@/session/homeViewPreferenceStore');
+ it('replaces corrupt stored JSON so a later device switch can still save', async () => {
+ const { __testing, readHomeViewPreferences, saveHomeViewPreferences } = await import('@/session/homeViewPreferenceStore');
store.set(__testing.storageKey, 'broken');
- await expect(saveHomeViewPreferences({ sortBy: 'priority' })).rejects.toThrow();
- expect(store.get(__testing.storageKey)).toBe('broken');
+ await saveHomeViewPreferences({ sortBy: 'priority', selectedDevice: { deviceId: 'devA', name: 'Mac A' } });
+ await expect(readHomeViewPreferences()).resolves.toMatchObject({
+ sortBy: 'priority',
+ selectedDevice: { deviceId: 'devA', name: 'Mac A' },
+ });
+ await saveHomeViewPreferences({
+ selectedDevice: { deviceId: 'devB', name: 12 as unknown as string },
+ });
+ await expect(readHomeViewPreferences()).resolves.toMatchObject({
+ selectedDevice: { deviceId: 'devB', name: 'devB' },
+ });
});
beforeEach(async () => {
vi.clearAllMocks();
diff --git a/apps/mobile/src/__tests__/remoteStatus.test.ts b/apps/mobile/src/__tests__/remoteStatus.test.ts
index b152ae3bfc..135b93d2d0 100644
--- a/apps/mobile/src/__tests__/remoteStatus.test.ts
+++ b/apps/mobile/src/__tests__/remoteStatus.test.ts
@@ -82,6 +82,9 @@ describe('remoteStatus', () => {
expect(describeRemoteComposerBlockingError("[CHANNEL_NOT_ALLOWED] channel 'x'"))
.toContain('版本不支持');
expect(describeRemoteComposerBlockingError(null)).toBeNull();
+ expect(describeRemoteComposerBlockingError('unknown failure')).toBeNull();
+ expect(describeRemoteComposerBlockingError('OUTBOX_STORAGE_INVALID')).toBeNull();
+ expect(describeRemoteComposerBlockingError('[BAD_REQUEST] nope')).toBeNull();
});
it('localizes Stop connection recovery errors without dropping their structured classification', async () => {
diff --git a/apps/mobile/src/device-link/remoteStatus.ts b/apps/mobile/src/device-link/remoteStatus.ts
index a9272e629c..8f25eb9ec2 100644
--- a/apps/mobile/src/device-link/remoteStatus.ts
+++ b/apps/mobile/src/device-link/remoteStatus.ts
@@ -174,7 +174,18 @@ function localizedStableRemoteError(error: string): string | null {
* 只有确定性远端错误才锁 composer;断线、弱网、超时与熔断由本地 outbox 接住,
* 恢复后自动派发。返回 null 表示 composer 可以继续收消息。
*/
+const COMPOSER_BLOCKING_MARKERS = [
+ 'ACCESS_REVOKED',
+ 'REMOTE_DISABLED',
+ 'CHANNEL_NOT_ALLOWED',
+ 'VERSION_MISMATCH',
+] as const;
+
export function describeRemoteComposerBlockingError(error: string | null): string | null {
if (!error || isAutoRecoveringRemoteError(error)) return null;
- return describeRemoteError(error);
+ const agentAuth = describeAgentAuthError(error);
+ if (agentAuth) return agentAuth;
+ if (!COMPOSER_BLOCKING_MARKERS.some((marker) => error.includes(marker))) return null;
+ return localizedStableRemoteError(error);
}
+
diff --git a/apps/mobile/src/session/durableOutbox.ts b/apps/mobile/src/session/durableOutbox.ts
index 2ec3ab50ac..0fd49165fc 100644
--- a/apps/mobile/src/session/durableOutbox.ts
+++ b/apps/mobile/src/session/durableOutbox.ts
@@ -172,29 +172,19 @@ export function createDurableOutbox(storage: OutboxStorage, reconcileDraft?: (
for (const key of keys) {
const raw = await storage.getItem(key);
if (!raw) continue;
- const record = JSON.parse(raw) as DurableOutboxRecord;
- // Corruption must be visible; never overwrite or silently drop unsent work.
- if (
- record.version !== 1 ||
- record.accountId !== owner ||
- !record.deviceId ||
- !record.item?.sessionId ||
- !record.item.clientId ||
- keyFor(record) !== key ||
- !Array.isArray(record.uploads) ||
- (record.cleanupOutcome !== undefined &&
- record.cleanupOutcome !== 'accepted' && record.cleanupOutcome !== 'cancelled') ||
- ![
- "queued",
- "sending",
- "confirming",
- "host-owned",
- "failed",
- ].includes(record.state) ||
- !Number.isFinite(record.createdAt) ||
- !Array.isArray(record.item.attachmentSlots)
- )
- throw new Error("OUTBOX_STORAGE_INVALID");
+ // One corrupt row must not fail the whole ledger. On Android that threw
+ // during every session's draft hydration, and send() returns immediately
+ // while composerDraftHydrated stays false. Leave the bytes in place.
+ let record: unknown;
+ try {
+ record = JSON.parse(raw);
+ } catch {
+ continue;
+ }
+ if (!isLoadableOutboxRecord(record, owner, key)) {
+ console.warn('[outbox] skipped unreadable ledger row', key);
+ continue;
+ }
loaded.push(record);
}
assertOwner(owner, epoch);
@@ -230,6 +220,28 @@ export function createDurableOutbox(storage: OutboxStorage, reconcileDraft?: (
return store;
}
+function isLoadableOutboxRecord(
+ record: unknown,
+ owner: string,
+ key: string,
+): record is DurableOutboxRecord {
+ if (!record || typeof record !== 'object') return false;
+ const row = record as DurableOutboxRecord;
+ return row.version === 1
+ && row.accountId === owner
+ && !!row.deviceId
+ && !!row.item?.sessionId
+ && !!row.item.clientId
+ && keyFor(row) === key
+ && Array.isArray(row.uploads)
+ && (row.cleanupOutcome === undefined
+ || row.cleanupOutcome === 'accepted'
+ || row.cleanupOutcome === 'cancelled')
+ && ["queued", "sending", "confirming", "host-owned", "failed"].includes(row.state)
+ && Number.isFinite(row.createdAt)
+ && Array.isArray(row.item.attachmentSlots);
+}
+
export type DurableOutboxStore = ReturnType<typeof createDurableOutbox>;
/** Synchronous page observer: reserve a transcript slot before the sender's await resumes. */
diff --git a/apps/mobile/src/session/homeViewPreferenceStore.ts b/apps/mobile/src/session/homeViewPreferenceStore.ts
index 6dbb404e20..1dff2c4faa 100644
--- a/apps/mobile/src/session/homeViewPreferenceStore.ts
+++ b/apps/mobile/src/session/homeViewPreferenceStore.ts
@@ -51,10 +51,11 @@ export function saveHomeViewPreferences(patch: HomeViewPreferencePatch): Promise
}
async function writeHomeViewPreferences(patch: HomeViewPreferencePatch): Promise<void> {
- // A failed read (including corrupt JSON) is not an empty preference record.
- // Preserve it rather than replacing unrelated choices with defaults.
+ // A failed read (disk/lock) must reject so we do not replace a still-valid
+ // blob with defaults. Corrupt JSON is different: keeping it makes every
+ // computer switch alert "couldn't save" forever.
const raw = await AsyncStorage.getItem(STORAGE_KEY);
- const current = raw === null ? emptyPreferences() : normalizeStoredPreferences(JSON.parse(raw));
+ const current = raw === null ? emptyPreferences() : parseStoredPreferences(raw);
const next: HomeViewPreferences = {
groupByProject: patch.groupByProject ?? current.groupByProject,
groupDialogue: patch.groupDialogue ?? current.groupDialogue,
@@ -108,13 +109,22 @@ function normalizeStoredPreferences(value: unknown): HomeViewPreferences {
};
}
+function parseStoredPreferences(raw: string): HomeViewPreferences {
+ try {
+ return normalizeStoredPreferences(JSON.parse(raw));
+ } catch {
+ return emptyPreferences();
+ }
+}
+
function normalizeDevice(device: { deviceId: string; name: string } | null): HomeViewPreferences['selectedDevice'] {
if (!device) return null;
- const deviceId = device.deviceId.trim();
+ const deviceId = typeof device.deviceId === 'string' ? device.deviceId.trim() : '';
if (!deviceId) return null;
+ const name = typeof device.name === 'string' ? device.name.trim() : '';
return {
deviceId,
- name: device.name.trim() || deviceId,
+ name: name || deviceId,
};
}