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(chat): restore saved conversations before syncing and persist pending sends

Chris5fd7c38ec153
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatPersistence.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatPersistence.test.ts
new file mode 100644
index 0000000000..8daf290685
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatPersistence.test.ts
@@ -0,0 +1,71 @@
+// Unit tier: real files cover restart/owner boundaries absent from transport mocks.
+// Minimal failure: save one unacknowledged send, recreate the service, then retry it.
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+const state = vi.hoisted(() => ({ root: '', owner: { dataOwnerId: 'a', generation: 1 }, pin: vi.fn(), add: vi.fn(), remove: vi.fn() }));
+vi.mock('../../appSessionState.js', () => ({
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(state.root, state.owner.dataOwnerId, ...parts),
+ getActiveAppSession: () => state.owner, isAppSessionBoundaryPending: () => false,
+}));
+vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://chat.example' }));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: {} }) }));
+vi.mock('../../cindy-media/blobStore.js', () => ({ parseBlobUrl: (url: string) => url === 'cindy-media://blob/held.png' ? { hash: 'held' } : null }));
+vi.mock('../../cindy-media/ledger.js', () => ({ hasRef: async () => false, pinBlob: state.pin, addRef: state.add,
+ removeRefById: state.remove, removeRefs: state.remove }));
+import { chatSendJournal } from '../chatSendJournal.js';
+import { accessBotGroupOutbox } from '../botGroupOutboxStorage.js';
+import { accessChatDisplayCache } from '../chatDisplayCache.js';
+
+beforeEach(() => {
+ state.root = mkdtempSync(path.join(tmpdir(), 'cindy-chat-persistence-'));
+ state.owner = { dataOwnerId: 'a', generation: 1 };
+ state.pin.mockReset().mockResolvedValue(undefined); state.add.mockReset().mockResolvedValue('ref'); state.remove.mockReset().mockResolvedValue(1);
+});
+afterEach(() => rmSync(state.root, { recursive: true, force: true }));
+
+it('restores display snapshots, removes them durably and rejects late writes from another login', () => {
+ const owner = state.owner;
+ const value = { messages: [{ id: 'saved-message', text: 'saved' }] };
+ accessChatDisplayCache({ action: 'write', key: 'companion:bot', owner, value });
+ expect(accessChatDisplayCache({ action: 'read', key: 'companion:bot', owner })).toEqual(value);
+ accessChatDisplayCache({ action: 'remove', key: 'companion:bot', owner });
+ expect(accessChatDisplayCache({ action: 'read', key: 'companion:bot', owner })).toBeNull();
+ state.owner = { dataOwnerId: 'b', generation: 2 };
+ expect(() => accessChatDisplayCache({ action: 'write', key: 'groups', owner, value })).toThrow('OWNER_CHANGED');
+ expect(accessChatDisplayCache({ action: 'read', key: 'groups', owner: state.owner })).toBeNull();
+});
+
+it('replays the frozen intent after restart, compacts its receipt and fences another owner', () => {
+ const owner = state.owner;
+ const current = () => state.owner === owner;
+ const journal = chatSendJournal('https://chat.example', current);
+ const intent = { route: '/conversations/room/messages', body: { operationId: 'client-a', mentions: ['original-recipient'], content: [{ type: 'text', text: 'saved' }] } };
+ journal.save('send', 'signature', intent);
+ const restarted = chatSendJournal('https://chat.example', current);
+ expect(restarted.read('send', 'signature')).toMatchObject({ intent });
+ expect(() => restarted.read('send', 'changed')).toThrow('INVALID_INPUT');
+ restarted.confirm('send', 'signature', 'server-message');
+ expect(chatSendJournal('https://chat.example', current).read('send', 'signature')).toMatchObject({ receipt: 'server-message' });
+ state.owner = { dataOwnerId: 'b', generation: 2 };
+ expect(() => restarted.save('late', 'signature', intent)).toThrow('OWNER_CHANGED');
+ expect(chatSendJournal('https://chat.example', () => true).read('send', 'signature')).toBeNull();
+});
+
+it('restores independent queued messages and holds media until a durable removal', async () => {
+ const owner = state.owner;
+ const entry = { input: { groupId: 'room', clientId: 'client-a', text: 'saved', mentions: { all: false, botIds: [] } }, createdAt: 1,
+ draft: 'saved', signature: 'saved', attachmentScope: 'room', after: 0, tracked: [], attachments: [],
+ status: 'sending' as const, files: [{ url: 'cindy-media://blob/held.png' }] };
+ await accessBotGroupOutbox({ action: 'put', owner, entry });
+ await accessBotGroupOutbox({ action: 'put', owner, entry: { ...entry, input: { ...entry.input, clientId: 'client-b' }, files: [] } });
+ expect(state.pin).toHaveBeenCalledWith('held', expect.anything());
+ expect(await accessBotGroupOutbox({ action: 'list', owner })).toHaveLength(2);
+ await accessBotGroupOutbox({ action: 'remove', owner, groupId: 'room', clientId: 'client-a' });
+ expect((await accessBotGroupOutbox({ action: 'list', owner })).map(row => row.input.clientId)).toEqual(['client-b']);
+ expect(state.remove).toHaveBeenCalled();
+ state.owner = { dataOwnerId: 'b', generation: 2 };
+ await expect(accessBotGroupOutbox({ action: 'put', owner, entry })).rejects.toThrow('OUTBOX_OWNER_CHANGED');
+ expect(await accessBotGroupOutbox({ action: 'list', owner: state.owner })).toEqual([]);
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
index 4a98828cb5..a780f959dc 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -24,6 +24,15 @@ vi.mock('../chatServerWorkspaces.js', () => ({ chatServerWorkspaces: () => ({
}) }));
beforeEach(() => workspaceSettings.clear());
const migration = vi.hoisted(() => ({ read: vi.fn<(_groupId: string) => { roomId: string; sequence: number; version: 2 } | null>(() => null) }));
+const sendJournal = vi.hoisted(() => ({ enabled: false, rows: new Map<string, { intent?: unknown; receipt?: string }>() }));
+vi.mock('../chatSendJournal.js', () => ({ chatSendJournal: () => ({
+ read: (key: string) => sendJournal.enabled ? sendJournal.rows.get(key) ?? null : null,
+ save: (key: string, _signature: string, intent: unknown) => { if (sendJournal.enabled) sendJournal.rows.set(key, { intent: structuredClone(intent) }); },
+ confirm: (key: string, _signature: string, receipt: string) => { if (sendJournal.enabled) sendJournal.rows.set(key, { receipt }); },
+ forgetRoom: vi.fn(),
+}) }));
+beforeEach(() => { sendJournal.enabled = false; sendJournal.rows.clear(); });
+vi.mock('../chatLocalHistory.js', () => ({ chatLocalHistory: () => ({ read: () => null, save: vi.fn(), forget: vi.fn() }) }));
vi.mock('../chatMigrationReceipts.js', () => ({ chatMigrationReceipts: () => ({ read: migration.read, save: vi.fn() }) }));
vi.mock('electron', () => ({ app: { get isPackaged() { return fixture.packaged; }, getPath: () => '/isolated' },
nativeImage: { createFromBuffer: () => ({ isEmpty: () => false, getSize: () => ({ width: 1, height: 1 }) }) } }));
@@ -543,7 +552,8 @@ describe('Chat Server result delivery and refresh', () => {
expect(posts()).toHaveLength(0);
});
- it('retries a send whose answer was lost with the same quote, even after the original is gone', async () => {
+ it.each([false, true])('retries a lost send with the same quote after deletion (restart=%s)', async restart => {
+ sendJournal.enabled = restart;
let original: unknown = quoted();
let lost = true;
fixture.handle.mockImplementation((route, method) => {
@@ -554,6 +564,10 @@ describe('Chat Server result delivery and refresh', () => {
expect(await service.sendMessage(input)).toMatchObject({ ok: false });
// The original is deleted before the user retries the same send.
original = null;
+ if (restart) {
+ service.dispose();
+ service = withChatServer({ listGroups: vi.fn(async () => ({ ok: true, groups: [] })), dispose: vi.fn() } as unknown as BotGroupChatService, deps);
+ }
expect(await service.sendMessage(input)).toEqual({ ok: true, messageId: 'saved-quote' });
const [first, retry] = posts().map(([, , body]) => body);
expect(retry.operationId).toBe(first.operationId);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts
index 44067497ac..8fba6deaad 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerGroupOpen.test.ts
@@ -17,6 +17,8 @@ vi.mock('../../authManager.js', () => ({ getAccessToken: () => 'isolated-test-to
vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://chat.cindy.app' }));
vi.mock('../chatServerMedia.js', () => ({ createChatMedia: () => ({ upload: vi.fn(async () => []), download: fixture.download }) }));
vi.mock('../chatServerWorkspaces.js', () => ({ chatServerWorkspaces: () => ({ read: () => null, save: vi.fn() }) }));
+vi.mock('../chatSendJournal.js', () => ({ chatSendJournal: () => ({ read: () => null, save: vi.fn(), confirm: vi.fn(), forgetRoom: vi.fn() }) }));
+vi.mock('../chatLocalHistory.js', () => ({ chatLocalHistory: () => ({ read: () => null, save: vi.fn(), forget: vi.fn() }) }));
vi.mock('../chatMigrationReceipts.js', () => ({ chatMigrationReceipts: () => ({ read: () => null, save: vi.fn() }) }));
vi.mock('electron', () => ({ app: { isPackaged: false, getPath: () => '/isolated' } }));
vi.mock('node:fs', () => ({ existsSync: () => true, readFileSync: () => '{"baseUrl":"http://127.0.0.1:3018","auth":"cindy"}' }));
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts
index 0570c0125d..20b5362df7 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts
@@ -4,6 +4,8 @@ vi.mock('../../authManager.js', () => ({ getAccessToken: () => 'isolated-test-to
vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => 'https://chat.cindy.app' }));
vi.mock('../chatServerMedia.js', () => ({ createChatMedia: () => ({ upload: vi.fn(async () => []), download: fixture.download }) }));
vi.mock('../chatServerWorkspaces.js', () => ({ chatServerWorkspaces: () => ({ read: () => null, save: vi.fn() }) }));
+vi.mock('../chatSendJournal.js', () => ({ chatSendJournal: () => ({ read: () => null, save: vi.fn(), confirm: vi.fn(), forgetRoom: vi.fn() }) }));
+vi.mock('../chatLocalHistory.js', () => ({ chatLocalHistory: () => ({ read: () => null, save: vi.fn(), forget: vi.fn() }) }));
vi.mock('../chatMigrationReceipts.js', () => ({ chatMigrationReceipts: () => ({ read: () => null, save: vi.fn() }) }));
vi.mock('electron', () => ({ app: { isPackaged: false, getPath: () => '/isolated' } }));
vi.mock('node:fs', () => ({ existsSync: () => true, readFileSync: () => '{"baseUrl":"http://127.0.0.1:3018","auth":"cindy"}' }));
diff --git a/apps/desktop/src/main/maker-ipc/botGroupOutboxStorage.ts b/apps/desktop/src/main/maker-ipc/botGroupOutboxStorage.ts
new file mode 100644
index 0000000000..ec57d09029
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botGroupOutboxStorage.ts
@@ -0,0 +1,86 @@
+import { createHash } from 'node:crypto';
+import { mkdirSync, readdirSync, rmSync } from 'node:fs';
+import path from 'node:path';
+import { z } from 'zod';
+import { getActiveAppSession, isAppSessionBoundaryPending, ownerScopedUserDataPath } from '../appSessionState.js';
+import { getDbClient } from '../localDb/client/current.js';
+import { parseBlobUrl } from '../cindy-media/blobStore.js';
+import * as ledger from '../cindy-media/ledger.js';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+import type { BotGroupOutboxStoredEntry } from '../../shared/botGroupOutboxStorage.js';
+
+const identifier = z.string().min(1).max(200);
+const entrySchema = z.object({ input: z.object({ groupId: identifier, clientId: identifier, text: z.string().max(8000),
+ mentions: z.object({ all: z.boolean(), botIds: z.array(z.string()) }) }).passthrough(),
+ createdAt: z.number().finite(), status: z.enum(['sending', 'sent', 'failed']),
+ draft: z.string(), signature: z.string(), attachmentScope: z.string(), after: z.number().finite(),
+ tracked: z.array(z.unknown()), attachments: z.array(z.unknown()),
+ files: z.array(z.object({ url: z.string().optional(), annotationSourceUrl: z.string().optional() }).passthrough()).max(32),
+ prepared: z.array(z.object({ url: z.string().optional(), annotationSourceUrl: z.string().optional() }).passthrough()).max(32).optional(),
+}).passthrough();
+const requestSchema = z.intersection(z.object({ owner: z.object({ dataOwnerId: identifier, generation: z.number().int() }) }),
+ z.discriminatedUnion('action', [z.object({ action: z.literal('list') }), z.object({ action: z.literal('put'), entry: entrySchema }),
+ z.object({ action: z.literal('remove'), groupId: identifier, clientId: identifier })]));
+const hash = (value: string) => createHash('sha256').update(value).digest('hex');
+let chain = Promise.resolve<unknown>(undefined);
+
+/** Serialized per-record writes preserve other windows' messages and fence account changes. */
+export function accessBotGroupOutbox(input: unknown): Promise<BotGroupOutboxStoredEntry[]> {
+ const request = requestSchema.parse(input);
+ const operation = async () => {
+ const current = () => !isAppSessionBoundaryPending() && getActiveAppSession().dataOwnerId === request.owner.dataOwnerId
+ && getActiveAppSession().generation === request.owner.generation;
+ const check = () => { if (!current()) throw new Error('OUTBOX_OWNER_CHANGED'); };
+ check();
+ const root = ownerScopedUserDataPath('bot-group-outbox');
+ const file = (groupId: string, clientId: string) => path.join(root, `${hash(JSON.stringify([groupId, clientId]))}.json`);
+ const read = (filename: string) => {
+ const raw = readAtomicFileSync(filename);
+ if (!raw) return null;
+ if (Buffer.byteLength(raw) > 8 * 1024 * 1024) throw new Error('OUTBOX_TOO_LARGE');
+ const parsed = JSON.parse(raw);
+ return parsed === null ? null : entrySchema.parse(parsed);
+ };
+ if (request.action === 'list') {
+ let names: string[];
+ try { names = readdirSync(root); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw error; }
+ const files = new Set(names.filter(name => /^[a-f0-9]{64}\.json(?:\.bak)?$/.test(name)).map(name => name.replace(/\.bak$/, '')));
+ return [...files].flatMap(name => { const value = read(path.join(root, name)); return value ? [value] : []; }).sort((a, b) => a.createdAt - b.createdAt);
+ }
+ const identity = request.action === 'put' ? request.entry.input : request;
+ const filename = file(identity.groupId, identity.clientId);
+ const refId = `outbox:${hash(JSON.stringify([identity.groupId, identity.clientId]))}`;
+ const db = getDbClient().drizzle;
+ if (request.action === 'remove') {
+ // Tombstone before reference release; a .bak recovery must never resend it.
+ mkdirSync(root, { recursive: true, mode: 0o700 });
+ atomicWriteFileSync(filename, 'null');
+ await ledger.removeRefs({ refKind: 'bot-group-attachment', refId }, db); check();
+ rmSync(`${filename}.bak`, { force: true }); rmSync(filename, { force: true });
+ return [];
+ }
+ const raw = JSON.stringify(request.entry);
+ if (Buffer.byteLength(raw) > 8 * 1024 * 1024) throw new Error('OUTBOX_TOO_LARGE');
+ const added: string[] = [];
+ try {
+ const urls = [...request.entry.files, ...(request.entry.prepared ?? [])].flatMap(item => [item.url, item.annotationSourceUrl]);
+ for (const url of new Set(urls)) {
+ const blob = url && parseBlobUrl(url);
+ if (!blob) continue;
+ check();
+ if (!await ledger.hasRef({ hash: blob.hash, refKind: 'bot-group-attachment', refId }, db)) {
+ await ledger.pinBlob(blob.hash, db); check();
+ added.push(await ledger.addRef({ hash: blob.hash, refKind: 'bot-group-attachment', refId, originKind: 'user' }, db));
+ }
+ }
+ check(); mkdirSync(root, { recursive: true, mode: 0o700 }); atomicWriteFileSync(filename, raw);
+ } catch (error) {
+ await Promise.all(added.map(id => ledger.removeRefById(id, db).catch(() => undefined)));
+ throw error;
+ }
+ return [];
+ };
+ const pending = chain.then(operation);
+ chain = pending.catch(() => undefined);
+ return pending;
+}
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index a856cb220b..8f74f54e50 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -851,6 +851,8 @@ export const MAKER_INVOKE = {
BOT_GROUP_SET_MEMBERS: 'maker:bot-group:set-members',
BOT_GROUP_DELETE: 'maker:bot-group:delete',
BOT_GROUP_SEND: 'maker:bot-group:send',
+ CHAT_DISPLAY_CACHE: 'maker:chat:display-cache',
+ BOT_GROUP_OUTBOX: 'maker:bot-group:outbox',
BOT_GROUP_CONTINUE: 'maker:bot-group:continue',
BOT_GROUP_STOP: 'maker:bot-group:stop',
BOT_GROUP_PLAN_START: 'maker:bot-group:plan-start',
diff --git a/apps/desktop/src/main/maker-ipc/chatDisplayCache.ts b/apps/desktop/src/main/maker-ipc/chatDisplayCache.ts
new file mode 100644
index 0000000000..86d94223d1
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/chatDisplayCache.ts
@@ -0,0 +1,33 @@
+import { createHash } from 'node:crypto';
+import { mkdirSync, rmSync } from 'node:fs';
+import path from 'node:path';
+import { z } from 'zod';
+import { getActiveAppSession, isAppSessionBoundaryPending, ownerScopedUserDataPath } from '../appSessionState.js';
+import { getClientEndpoint } from '../clientEndpointsService.js';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+
+const schema = z.intersection(z.object({ owner: z.object({ dataOwnerId: z.string().min(1), generation: z.number().int() }),
+ key: z.string().max(250).refine(key => key === 'groups' || key === 'cloud-homes' || key.startsWith('companion:')) }),
+ z.discriminatedUnion('action', [z.object({ action: z.literal('read') }),
+ z.object({ action: z.literal('write'), value: z.unknown() }), z.object({ action: z.literal('remove') })]));
+const MAX_BYTES = 8 * 1024 * 1024;
+/** Bounded, owner/endpoint-scoped snapshots behind the trusted local renderer boundary. */
+export function accessChatDisplayCache(input: unknown): unknown {
+ const request = schema.parse(input);
+ const active = getActiveAppSession();
+ if (isAppSessionBoundaryPending() || active.dataOwnerId !== request.owner.dataOwnerId || active.generation !== request.owner.generation)
+ throw new Error('OWNER_CHANGED');
+ const digest = createHash('sha256').update(JSON.stringify([getClientEndpoint('chatApiBaseUrl'), request.key])).digest('hex');
+ const root = ownerScopedUserDataPath('chat-display');
+ const file = path.join(root, `${digest}.json`);
+ if (request.action === 'read') {
+ const raw = readAtomicFileSync(file);
+ return raw && Buffer.byteLength(raw) <= MAX_BYTES ? JSON.parse(raw) : null;
+ }
+ const raw = JSON.stringify(request.action === 'remove' ? null : request.value);
+ if (!raw || Buffer.byteLength(raw) > MAX_BYTES) throw new Error('CACHE_TOO_LARGE');
+ mkdirSync(root, { recursive: true, mode: 0o700 }); atomicWriteFileSync(file, raw);
+ rmSync(`${file}.bak`, { force: true });
+ if (request.action === 'remove') rmSync(file, { force: true });
+ return null;
+}
diff --git a/apps/desktop/src/main/maker-ipc/chatLocalHistory.ts b/apps/desktop/src/main/maker-ipc/chatLocalHistory.ts
new file mode 100644
index 0000000000..be7863d003
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/chatLocalHistory.ts
@@ -0,0 +1,46 @@
+import { createHash } from 'node:crypto';
+import { mkdirSync, rmSync } from 'node:fs';
+import path from 'node:path';
+import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+import type { BotGroupDetail } from '../../shared/botGroupChat.js';
+
+const MAX_BYTES = 8 * 1024 * 1024;
+/** Display snapshots only; every write/action still uses current server authority. */
+export function chatLocalHistory(endpoint: string, current: () => boolean) {
+ const root = ownerScopedUserDataPath('chat-history', createHash('sha256').update(endpoint).digest('hex'));
+ const revoked = new Set<string>();
+ const file = (roomId: string) => path.join(root, `${createHash('sha256').update(roomId).digest('hex')}.json`);
+ return {
+ read(roomId: string): BotGroupDetail | null {
+ if (!current() || revoked.has(roomId)) return null;
+ try {
+ const raw = readAtomicFileSync(file(roomId));
+ if (!raw || Buffer.byteLength(raw) > MAX_BYTES) return null;
+ const value = JSON.parse(raw);
+ if (value.version !== 1 || value.group?.id !== roomId || !Array.isArray(value.group.messages)
+ || !Array.isArray(value.group.members) || !Array.isArray(value.group.plans) || !value.group.round) return null;
+ return current() ? value.group : null;
+ } catch { return null; }
+ },
+ save(roomId: string, group: BotGroupDetail): void {
+ if (!current()) return;
+ const raw = JSON.stringify({ version: 1, group });
+ if (Buffer.byteLength(raw) > MAX_BYTES) return;
+ try {
+ mkdirSync(root, { recursive: true, mode: 0o700 });
+ atomicWriteFileSync(file(roomId), raw);
+ revoked.delete(roomId);
+ } catch { /* Best-effort history never changes the result of a server read. */ }
+ },
+ forget(roomId: string): void {
+ if (!current()) return;
+ revoked.add(roomId);
+ try {
+ // Replace first so a recoverable Windows backup cannot resurrect a revoked page.
+ atomicWriteFileSync(file(roomId), JSON.stringify({ version: 1, group: null }));
+ rmSync(`${file(roomId)}.bak`, { force: true }); rmSync(file(roomId), { force: true });
+ } catch { /* The current process never serves the revoked page. */ }
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/chatSendJournal.ts b/apps/desktop/src/main/maker-ipc/chatSendJournal.ts
new file mode 100644
index 0000000000..4d79bfbb59
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/chatSendJournal.ts
@@ -0,0 +1,60 @@
+import { createHash } from 'node:crypto';
+import { mkdirSync, readdirSync, rmSync, statSync } from 'node:fs';
+import path from 'node:path';
+import { ownerScopedUserDataPath } from '../appSessionState.js';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+
+/** Immutable HTTP intent survives a lost response and a client restart. */
+export function chatSendJournal<T>(endpoint: string, current: () => boolean) {
+ const hash = (text: string) => createHash('sha256').update(text).digest('hex');
+ const root = ownerScopedUserDataPath('chat-send-journal', hash(endpoint));
+ const file = (key: string) => path.join(root, `${hash(key)}.json`);
+ const check = () => { if (!current()) throw new Error('OWNER_CHANGED'); };
+ const write = (key: string, value: unknown) => {
+ check(); const raw = JSON.stringify(value);
+ if (Buffer.byteLength(raw) > 8 * 1024 * 1024) throw new Error('OUTBOX_TOO_LARGE');
+ mkdirSync(root, { recursive: true, mode: 0o700 }); atomicWriteFileSync(file(key), raw);
+ };
+ return {
+ read(key: string, signature: string): { intent?: T; receipt?: string } | null {
+ check(); const raw = readAtomicFileSync(file(key));
+ if (!raw) return null;
+ const value = JSON.parse(raw);
+ if (value.version !== 1 || value.signature !== signature) throw new Error('INVALID_INPUT');
+ return value;
+ },
+ save(key: string, signature: string, intent: T, roomId?: string) { write(key, { version: 1, signature, intent, roomId }); },
+ forgetRoom(roomId: string) {
+ check();
+ if (!roomId) return;
+ let names: string[];
+ try { names = readdirSync(root); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error; }
+ for (const name of names.filter(name => /^[a-f0-9]{64}\.json$/.test(name))) {
+ const filename = path.join(root, name);
+ const value = JSON.parse(readAtomicFileSync(filename) ?? '{}');
+ if (value.roomId !== roomId) continue;
+ // No background process replays this journal. Remove private request content
+ // when its room is hidden/deleted or access is revoked, including atomic backups.
+ atomicWriteFileSync(filename, JSON.stringify({ version: 1, signature: value.signature }));
+ rmSync(`${filename}.bak`, { force: true }); rmSync(filename, { force: true });
+ }
+ },
+ confirm(key: string, signature: string, receipt: string) {
+ write(key, { version: 1, signature, receipt });
+ // The atomic backup otherwise retains the full message after compaction.
+ rmSync(`${file(key)}.bak`, { force: true });
+ // A byte budget for old receipts; unconfirmed user intent is never evicted.
+ try {
+ const files = readdirSync(root).filter(name => /^[a-f0-9]{64}\.json$/.test(name)).map(name => {
+ const filename = path.join(root, name); const stat = statSync(filename); return { filename, size: stat.size, at: stat.mtimeMs };
+ }).sort((a, b) => a.at - b.at);
+ let bytes = files.reduce((sum, entry) => sum + entry.size, 0);
+ for (const entry of files) {
+ if (bytes <= 64 * 1024 * 1024) break;
+ if (entry.filename === file(key) || !JSON.parse(readAtomicFileSync(entry.filename) ?? '{}').receipt) continue;
+ rmSync(`${entry.filename}.bak`, { force: true }); rmSync(entry.filename, { force: true }); bytes -= entry.size;
+ }
+ } catch { /* Receipt collection must not change an acknowledged send. */ }
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index ba19aa364e..38ac84a264 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -26,6 +26,8 @@ import { chatServerWorkspaces } from './chatServerWorkspaces.js';
import { buildPlanStepBrief, draftPlanSteps, type PlanStepDraft } from './botGroupDivision.js';
import { splitBotGroupRelaySteps } from '@cindy/maker-shared/botGroupMentions';
import { chatMigrationReceipts } from './chatMigrationReceipts.js';
+import { chatLocalHistory } from './chatLocalHistory.js';
+import { chatSendJournal } from './chatSendJournal.js';
import { prepareBotGroupTaskPost, type BotGroupTaskPostSnapshot } from './botGroupTaskPostSnapshot.js';
import { registerGroupToolAuthority, GroupToolAuthorizationError } from './botGroupToolAuthorization.js';
import path from 'node:path';
@@ -77,6 +79,12 @@ interface Room {
}
/** `reads`: this reader's read position per Thread (`thread_key` = root ID, `main` for the main timeline); older servers omit it. */
interface Snapshot { room: Room; members: Member[]; messages: Message[]; cursor: string; reads?: Array<{ thread_key: string; read_seq: string; following?: boolean; muted?: boolean }> }
+interface SavedChatSend {
+ snapshot: Snapshot; plans: ServerPlan[]; members: Member[];
+ quote: (BotGroupQuoteView & { recipientActorId?: string }) | null;
+ mentions: { all: boolean; botIds: string[] };
+ shouldPlan: boolean; route: string; body: unknown; attachments: BotGroupAttachment[];
+}
interface Execution {
id: string; conversation_id: string; source_message_id: string; bot_id: string;
requester_id?: string;
@@ -333,6 +341,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
let savedShadows = JSON.stringify(deps.companionCloud?.homes.persistedShadows() ?? []);
let connected = false;
const current = () => !disposed && (!scope || !deps.isOwnerScopeCurrent || deps.isOwnerScopeCurrent(scope));
+ const history = chatLocalHistory(config.baseUrl, current);
+ const sendJournal = chatSendJournal<SavedChatSend>(config.baseUrl, current);
const executorId = `desktop:${randomUUID()}`;
let actors: Actor[] = [];
let selfId = '';
@@ -345,6 +355,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
};
personalList.subscribe(row => {
if (!current()) return;
+ if (row.hidden) { history.forget(row.conversationId); sendJournal.forgetRoom(row.conversationId); }
deps.onChanged?.({ groupId: row.conversationId, change: 'list', listState: row }, scope);
for (const [source, target] of upgradedGroups) if (target === row.conversationId)
deps.onChanged?.({ groupId: source, change: 'list', listState: row }, scope);
@@ -1004,6 +1015,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
}).catch(() => ws.close());
} else {
rooms.delete(roomId);
+ history.forget(roomId); sendJournal.forgetRoom(roomId);
// Access may come back with a narrower history; re-read every reference.
threads.reset();
changed(roomId);
@@ -2622,33 +2634,42 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const i = z.object({ conversationKind: z.literal('direct').optional(), groupId: id, text: z.string().max(8000), clientId: z.string().min(8).max(160),
mentions: z.object({ all: z.boolean(), botIds: z.array(z.string()) }), division: z.boolean().optional(), attachments: z.array(z.unknown()).optional(),
quote: z.object({ messageId: id }).strict().optional() }).parse(input);
- i.groupId = await resolveGroup(i.groupId);
+ const journalKey = JSON.stringify([i.groupId, i.clientId, origin?.controllerDeviceId ?? null]);
+ const signature = createHash('sha256').update(JSON.stringify({ ...i, attachments: undefined })).digest('hex');
+ const journal = sendJournal.read(journalKey, signature);
+ if (journal?.receipt) return { ok: true as const, messageId: journal.receipt };
+ const recovered = journal?.intent;
+ i.groupId = recovered?.snapshot.room.id ?? await resolveGroup(i.groupId);
+ if (recovered) {
+ await ensureRegistered(); await syncPersonalList();
+ if (personalList.hidden(i.groupId)) throw new Error('CONVERSATION_NOT_FOUND');
+ }
const direct = i.conversationKind === 'direct';
if (direct && i.division) throw new Error('INVALID_INPUT');
if (!i.text.trim() && !i.attachments?.length) throw new Error('INVALID_INPUT');
// A single-speaker server cannot release a held request (no cancel-planning): a newer message
// replacing a 分工 still being arranged would leave it to be queued two minutes later. Wait for its card.
- if (singleSpeaker && planIntents.get(i.groupId)?.sourceId) throw new Error('PLAN_OPEN');
+ if (!recovered && singleSpeaker && planIntents.get(i.groupId)?.sourceId) throw new Error('PLAN_OPEN');
// An attempted send must not cancel a valid decision until its message exists.
const intentVersion = ++nextIntentVersion;
// The reads a send needs share one round trip (none for a snapshot the live subscription
// vouches for). Each is awaited in the former order, so the first failure reported is the
// one the serial version reported.
- const snapshotRead = direct ? directSnapshot(i.groupId) : recentSnapshot(i.groupId, true);
+ const snapshotRead = recovered ? Promise.resolve(recovered.snapshot) : direct ? directSnapshot(i.groupId) : recentSnapshot(i.groupId, true);
// An unopened room must be confirmed as a group before reading its other resources.
if (!rooms.has(i.groupId)) await snapshotRead;
const quoteKey = i.quote ? JSON.stringify([i.groupId, i.clientId, i.quote.messageId, i.text, i.mentions, i.division]) : '';
const knownQuote = i.quote ? postedQuotes.get(quoteKey) : undefined;
const snapshotMembers = snapshotRead.then(value => value.members);
- const quoteRead = i.quote && !knownQuote ? quoteSnapshot(i.groupId, i.quote.messageId, snapshotMembers, direct) : undefined;
- const plansRead = direct ? Promise.resolve([] as ServerPlan[]) : api<ServerPlan[]>(`/conversations/${i.groupId}/plans`);
- const membersRead = namesNobody(i.mentions) && !i.quote ? undefined : api<Member[]>(`/conversations/${i.groupId}/members`);
+ const quoteRead = i.quote && !knownQuote && !recovered ? quoteSnapshot(i.groupId, i.quote.messageId, snapshotMembers, direct) : undefined;
+ const plansRead = recovered ? Promise.resolve(recovered.plans) : direct ? Promise.resolve([] as ServerPlan[]) : api<ServerPlan[]>(`/conversations/${i.groupId}/plans`);
+ const membersRead = recovered ? Promise.resolve(recovered.members) : namesNobody(i.mentions) && !i.quote ? undefined : api<Member[]>(`/conversations/${i.groupId}/members`);
for (const read of [snapshotMembers, quoteRead, plansRead, membersRead]) read?.catch(() => undefined);
const s = await snapshotRead;
// Read before preparing attachments: an unavailable quote must not stage files.
- const quote = i.quote ? knownQuote?.quote ?? await quoteRead! : null;
+ const quote = recovered ? recovered.quote : i.quote ? knownQuote?.quote ?? await quoteRead! : null;
const members = membersRead ? await membersRead : [];
- i.mentions = knownQuote?.mentions ?? withReplyRecipient(members, i.mentions, quote?.recipientActorId);
+ i.mentions = recovered?.mentions ?? knownQuote?.mentions ?? withReplyRecipient(members, i.mentions, quote?.recipientActorId);
const plans = await plansRead;
const openPlan = plans.find(p => ['proposed','running','waiting'].includes(p.status));
const proposed = openPlan?.status === 'proposed' && openPlan.creator_id === selfId;
@@ -2665,12 +2686,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const commentPlan = canTrigger && openPlan && openPlan.status !== 'proposed' && !(singleSpeaker && openPlan.kind === 'talk' && openPlan.status === 'waiting') && !i.mentions.botIds.length && !i.mentions.all && mayAdd ? openPlan : undefined;
// Single-speaker servers queue turns themselves; only a 分工, or words about your proposed card,
// wait for the arrangement. A 分工 that writes out its steps needs no helper model.
- const shouldPlan = !direct && (singleSpeaker
+ const shouldPlan = recovered?.shouldPlan ?? (!direct && (singleSpeaker
? i.division || (canTrigger && proposed && namesNobody(i.mentions) && !!deps.decidePlan)
: canTrigger && !!deps.decidePlan && (i.division || (!i.mentions.botIds.length && (!proposed || !i.mentions.all)))
- && (!openPlan || proposed));
- const prepared = i.attachments?.length ? await deps.prepareAttachments?.({ groupId: i.groupId, attachments: i.attachments, controllerDeviceId: origin?.controllerDeviceId }) : undefined;
- if (i.attachments?.length && (!prepared || !prepared.ok)) {
+ && (!openPlan || proposed)));
+ const prepared = !recovered && i.attachments?.length ? await deps.prepareAttachments?.({ groupId: i.groupId, attachments: i.attachments, controllerDeviceId: origin?.controllerDeviceId }) : undefined;
+ if (!recovered && i.attachments?.length && (!prepared || !prepared.ok)) {
const error = new Error(prepared && !prepared.ok ? prepared.errorCode === 'INVALID_PARAMS' ? 'INVALID_ATTACHMENT' : prepared.errorCode : 'INVALID_ATTACHMENT');
deps.log?.warn('Chat attachment preparation failed', { groupId: i.groupId, trace: createHash('sha256').update(i.clientId).digest('hex').slice(0, 16), ...chatErrorDiagnostic(prepared && !prepared.ok ? new Error(prepared.message) : error) });
throw error;
@@ -2678,18 +2699,22 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
let result: { id: string };
let posting = false;
try {
- const mentions = knownQuote?.recipients ?? (membersRead ? resolveMentions(members, i.mentions) : []);
- const uploaded = await media.upload(i.groupId, i.clientId, prepared?.ok ? prepared.attachments : [], selfId);
+ const mentions = recovered ? [] : knownQuote?.recipients ?? (membersRead ? resolveMentions(members, i.mentions) : []);
+ const uploaded = recovered ? [] : await media.upload(i.groupId, i.clientId, prepared?.ok ? prepared.attachments : [], selfId);
// Cached only once the message may reach the server; a failure before this stored nothing.
if (quote) {
postedQuotes.set(quoteKey, { quote, mentions: i.mentions, recipients: mentions });
if (postedQuotes.size > 128) postedQuotes.delete(postedQuotes.keys().next().value!);
}
- posting = true;
- result = await api<{ id: string }>(`/conversations/${i.groupId}/${commentPlan ? `plans/${commentPlan.id}/messages` : 'messages'}`, 'POST', {
+ const route = recovered?.route ?? `/conversations/${i.groupId}/${commentPlan ? `plans/${commentPlan.id}/messages` : 'messages'}`;
+ const body = recovered?.body ?? {
operationId: i.clientId, content: [ ...(quote ? [buildBotGroupQuoteCard(quote)] : []), ...(i.text ? [{ type: 'text', text: i.text }] : []),
...uploaded ], mentions, deferExecution: shouldPlan, ...(!direct && groupDiscussionParity ? { mentionsAll: i.mentions.all, planningMode: i.division || proposed ? 'explicit' : 'auto' } : {}),
- });
+ };
+ if (!recovered) sendJournal.save(journalKey, signature, { snapshot: s, plans, members, quote, mentions: i.mentions,
+ shouldPlan: !!shouldPlan, route, body, attachments: prepared?.ok ? prepared.attachments : [] }, i.groupId);
+ posting = true;
+ result = await api<{ id: string }>(route, 'POST', body);
} catch (error) {
if (prepared?.ok) await prepared.discard();
// A definite refusal of this post stored nothing; a lost answer, or a failure before an
@@ -2698,6 +2723,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
throw error;
}
if (prepared?.ok) prepared.commit();
+ sendJournal.confirm(journalKey, signature, result.id);
deps.log?.info?.('Chat group send confirmed', { groupId: i.groupId, messageId: result.id,
trace: createHash('sha256').update(i.clientId).digest('hex').slice(0, 16), durationMs: Date.now() - started });
// The message exists: the send is answered now and its receipt answers any retry, so the
@@ -2725,7 +2751,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
.catch(error => deps.log?.warn('Waiting queue could not be ended', { groupId: roomId, ...chatErrorDiagnostic(error) }));
const written = singleSpeaker && i.division && !i.mentions.all ? writtenPlanSteps(s, i.text, i.mentions.botIds) : null;
if (written) await openWrittenPlan(s, messageId, planRequest(i.text, quote), written, intent);
- else await decideArrangement(s, messageId, i.text, i.division === true, prepared?.ok ? prepared.attachments : [], intent, quote);
+ else await decideArrangement(s, messageId, i.text, i.division === true, recovered?.attachments ?? (prepared?.ok ? prepared.attachments : []), intent, quote);
};
void arrange().catch(error => deps.log?.warn('Group arrangement failed', { groupId: roomId, ...chatErrorDiagnostic(error) }));
}
@@ -2754,11 +2780,27 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
return { ok: true as const, groups: groups.filter(group => !personalList.hidden(group.id)) };
}),
getGroup: (roomId, options) => safe(async () => {
- const target = await resolveGroup(id.parse(roomId)); await syncPersonalList();
- if (personalList.hidden(target)) throw new Error('CONVERSATION_NOT_FOUND');
- const group = await detail(target, options);
- if (personalList.hidden(target)) throw new Error('CONVERSATION_NOT_FOUND');
- return { ok: true as const, group };
+ if ((options as { cacheOnly?: boolean } | undefined)?.cacheOnly === true) {
+ const group = history.read(id.parse(roomId));
+ if (!group || personalList.hidden(group.id)) throw new Error('CONVERSATION_NOT_FOUND');
+ return { ok: true as const, group };
+ }
+ let target = id.parse(roomId);
+ try {
+ target = await resolveGroup(target); await syncPersonalList();
+ if (personalList.hidden(target)) throw new Error('CONVERSATION_NOT_FOUND');
+ const group = await detail(target, options);
+ if (personalList.hidden(target)) throw new Error('CONVERSATION_NOT_FOUND');
+ if (!(options as { beforeSequence?: number } | undefined)?.beforeSequence) history.save(target, group);
+ return { ok: true as const, group };
+ }
+ catch (error) {
+ const failure = chatGroupFailure(error);
+ if (['NOT_FOUND', 'PERMISSION_DENIED'].includes(failure.errorCode)) {
+ history.forget(id.parse(roomId)); history.forget(target); sendJournal.forgetRoom(target);
+ }
+ throw error;
+ }
}),
createGroup: input => safe(async () => {
const i = groupInput.parse(input); await register(); beginUpgrade();
@@ -2956,6 +2998,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if (s.members.some(m => m.ownerActorId === selfId && m.role === 'owner')) await api(`/conversations/${room}`, 'PATCH', { operationId: randomUUID(), expectedRevision: s.room.revision, archived: true }, managementActor(s));
else await api(`/conversations/${room}/members`, 'POST', { operationId: randomUUID(), actorId: selfId, action: 'leave' });
resolvedGroups.delete(id.parse(groupId));
+ history.forget(room); history.forget(id.parse(groupId)); sendJournal.forgetRoom(room);
changed(room); return { ok: true as const };
}),
continueRound: groupId => safe(async () => {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index f57db17e03..9e53ea2510 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -226,6 +226,8 @@ import { applyScheduledModelSelection, createScheduledModelScope, createSchedule
import { parseScheduledModelBaseline } from '../../shared/scheduledModelBaseline';
import { recordTurnModelChange, type TurnModelIdentity } from './turnModelChange';
import { app, BrowserWindow, dialog, ipcMain, shell, type IpcMainInvokeEvent } from 'electron';
+import { accessChatDisplayCache } from './chatDisplayCache.js';
+import { accessBotGroupOutbox } from './botGroupOutboxStorage.js';
import {
activeOwnerScopeKey,
getActiveAppSession,
@@ -13496,6 +13498,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
assertTrustedAppRendererEvent(event);
return botGroupChatServiceHolder ? botGroupChatServiceHolder.sendMessage(input) : botGroupNotReady;
});
+ ipcMain.handle(MAKER_INVOKE.CHAT_DISPLAY_CACHE, (event, input: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ return accessChatDisplayCache(input);
+ });
+ ipcMain.handle(MAKER_INVOKE.BOT_GROUP_OUTBOX, async (event, input: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ return accessBotGroupOutbox(input);
+ });
ipcMain.handle(MAKER_INVOKE.BOT_GROUP_CONTINUE, async (event, groupId: unknown) => {
assertTrustedAppRendererEvent(event);
return botGroupChatServiceHolder ? botGroupChatServiceHolder.continueRound(groupId) : botGroupNotReady;
@@ -13544,9 +13554,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
throwIpcError('INVALID_PARAMS', 'Invalid cursor');
const runtime = activeCompanionCloud();
if (!runtime) throwIpcError('PRECONDITION_FAILED', 'Cloud companions are not available');
+ const owner = getActiveAppSession();
try {
return await runtime.transcript(id, typeof before === 'string' ? before : undefined);
} catch (error) {
+ const status = (error as { status?: number } | null)?.status;
+ const removed = error instanceof Error && error.message === 'COMPANION_NOT_FOUND' && currentCompanionHomes().snapshot().enabled;
+ if ((status === 403 || status === 404 || removed) && getActiveAppSession().generation === owner.generation) {
+ try { accessChatDisplayCache({ action: 'remove', key: `companion:${id}`, owner }); } catch { /* Current view is still invalidated. */ }
+ throwIpcError('PERMISSION_DENIED', 'Companion conversation is not available');
+ }
log.warn('companion transcript read failed', { error: error instanceof Error ? error.message.slice(0, 80) : 'UNKNOWN' });
throwIpcError('PRECONDITION_FAILED', 'Companion conversation is not available');
}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b89d19b397..1d5b196924 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -6342,6 +6342,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
input: import('../shared/botGroupChat').BotGroupSendInput,
): Promise<import('../shared/botGroupChat').BotGroupSendResult> =>
ipcRenderer.invoke('maker:bot-group:send', input),
+ chatDisplayCache: (request: import('../shared/chatDisplayCache').ChatDisplayCacheRequest): Promise<unknown> =>
+ ipcRenderer.invoke('maker:chat:display-cache', request),
+ botGroupOutbox: (input: import('../shared/botGroupOutboxStorage').BotGroupOutboxStorageRequest): Promise<import('../shared/botGroupOutboxStorage').BotGroupOutboxStoredEntry[]> =>
+ ipcRenderer.invoke('maker:bot-group:outbox', input),
continueBotGroupRound: (groupId: string): Promise<import('../shared/botGroupChat').BotGroupMutationResult> =>
ipcRenderer.invoke('maker:bot-group:continue', groupId),
/** Stops your own work; `all` (owners/admins of server groups) stops everyone's. */
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index c6946d66fe..58aae4ded0 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -295,6 +295,11 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boo
return;
}
const displayed = stateRef.current;
+ if (!hasTimeline) void api.getBotGroup(groupId, { cacheOnly: true, ...(direct ? { conversationKind: 'direct' } : {}) }).then(cached => {
+ if (!cached.ok || hasTimeline || !isCurrent()) return;
+ hasTimeline = true;
+ setState({ kind: 'ready', group: cached.group, older: [], olderPlans: [], olderHasMore: cached.group.hasMoreBefore, readToken: 0 });
+ }).catch(() => undefined);
const shown = displayed.kind === 'ready' && displayed.group.id === groupId;
const sourceMessageIds = [...new Set([...(shown
? mergeBotGroupMessages(displayed.older, displayed.group.messages).map(message => message.id) : []), ...additionalSources])];
@@ -339,7 +344,10 @@ function BotGroupChatContent({ groupId, direct }: { groupId: string; direct: boo
: previous);
}
}
- } else if (result.errorCode === 'NOT_FOUND') {
+ } else if (result.errorCode === 'NOT_FOUND' || result.errorCode === 'PERMISSION_DENIED') {
+ // A disk read started beside this request may finish after the rejection.
+ // It must never restore a conversation whose access was just revoked.
+ version += 1;
hasTimeline = false;
discardOutbox();
setState({ kind: 'missing' });
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
index eb21e93059..38155f37f5 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx
@@ -392,10 +392,10 @@ export function BotGroupComposer({
[groupId, thread],
);
- const send = () => {
+ const send = async () => {
if (thread) { void sendThreadReply(); return; }
// A second Enter before the cleared input has rendered must not send the same draft twice.
- if (!canSend || textRef.current !== text || attachmentsRef.current !== attachmentState.attachments) return;
+ if (!canSend || sendingRef.current || textRef.current !== text || attachmentsRef.current !== attachmentState.attachments) return;
if (!botGroupApi()) {
toast.error(t('bots.groupChat.composer.sendFailed'));
return;
@@ -418,7 +418,8 @@ export function BotGroupComposer({
const clientId = groupAttemptRef.current?.signature === signature ? groupAttemptRef.current.clientId : crypto.randomUUID();
// The outbox owns this attempt now; a failure hands it back through `restore`.
groupAttemptRef.current = null;
- enqueueBotGroupSend({
+ sendingRef.current = true; setSending(true);
+ try { const saved = enqueueBotGroupSend({
input: { ...fields, clientId },
signature,
draft: text,
@@ -427,6 +428,12 @@ export function BotGroupComposer({
files,
attachmentScope,
});
+ if (botGroupApi()?.botGroupOutbox) await saved;
+ else void saved.catch(() => undefined);
+ } catch {
+ toast.error(t('bots.groupChat.composer.sendFailed'));
+ return;
+ } finally { sendingRef.current = false; setSending(false); }
// Clear at once like any chat, so the next message can be written while this one
// goes out. The batch leaves the tray without deleting its files: the message has them.
textRef.current = '';
@@ -591,6 +598,7 @@ export function BotGroupComposer({
// The Chat Server caps a 话题 reply; the field enforces it as typing does (a pick obeys it too).
maxLength={thread ? BOT_GROUP_MESSAGE_MAX_CHARS : undefined}
{...mention.textareaProps}
+ readOnly={sending}
placeholder={placeholder}
onChange={(event) => mention.onChange(event.target.value)}
onPaste={handlePaste}
diff --git a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
index 80144fffff..44b862e5b2 100644
--- a/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotSessionView.tsx
@@ -13,7 +13,7 @@ import { useCompanionArrivalNotice } from './useCompanionArrivalNotice';
import { CompanionShadowBanner } from './CompanionShadowBanner';
import type { ComposerBotMention } from '@/lib/fileTypes';
import { getBotLastReadAt, markBotRead } from './botReadState';
-import { useBotProfiles } from './botStore';
+import { getBotProfiles, useBotProfiles } from './botStore';
import type { BotChatIdentity } from './BotSessionContentHeader';
import type { BotChatBinding } from './botChatPresentation';
import { useBotIslandVisibleSession } from './useBotIslandVisibleSession';
@@ -30,6 +30,7 @@ type BotSessionGate =
isCanonical: boolean;
/** Read position captured before opening advances it; null when entry had no unread replies. */
unreadBoundaryAt: number | null;
+ verified: boolean;
}
| { kind: 'unavailable' }
| { kind: 'error'; message: string };
@@ -78,7 +79,8 @@ function readBotMention(value: unknown, currentBotId: string): ComposerBotMentio
*/
export function BotSessionView() {
const { botId, sessionId } = useParams();
- return <BotSessionGateView key={JSON.stringify([botId, sessionId])} />;
+ const owner = getDataOwnerGeneration();
+ return <BotSessionGateView key={JSON.stringify([owner.dataOwnerId, owner.generation, botId, sessionId])} />;
}
function BotSessionGateView() {
@@ -87,7 +89,17 @@ function BotSessionGateView() {
const navigate = useNavigate();
const { botId, sessionId } = useParams();
const [reloadVersion, setReloadVersion] = useState(0);
- const [gate, setGate] = useState<BotSessionGate>({ kind: 'loading' });
+ const [gate, setGate] = useState<BotSessionGate>(() => {
+ const profiles = getBotProfiles();
+ const profile = profiles.find(bot => bot.id === botId && bot.status === 'active');
+ const projection = profile?.sessions.find(row => row.id === sessionId && row.kind === 'chat' && row.status === 'active');
+ if (!profile || !projection || !sessionId) return { kind: 'loading' };
+ // The already-read local roster selects a display; fresh validation still
+ // controls writes and read receipts. Mount the existing message cache now.
+ return { kind: 'ready', verified: false, identity: { ...readBotChatIdentity(profile, profile.id), sessionId },
+ isCanonical: projection.role === 'canonical', unreadBoundaryAt: projection.role === 'canonical' && ((profile as { unreadCount?: number }).unreadCount ?? 0) > 0 ? getBotLastReadAt(profile.id) : null,
+ mentions: profiles.map(bot => readBotMention(bot, profile.id)).filter((bot): bot is ComposerBotMention => bot !== null) };
+ });
// The companion now runs on its main computer: this copy's main task is read only.
const cloud = useCompanionCloud();
const shadowed = cloud.demotedBotIds.includes(botId ?? '');
@@ -120,7 +132,7 @@ function BotSessionGateView() {
[gateIdentity, liveName, liveAvatar, liveAvatarColor],
);
// A read-only demoted copy offers no add-to-group entry, like its settings.
- const canonicalChat = gate.kind === 'ready' && gate.isCanonical && !shadowed;
+ const canonicalChat = gate.kind === 'ready' && gate.verified && gate.isCanonical && !shadowed;
const chatIdentity = useMemo(
() => (gateIdentity ? { ...(identity ?? gateIdentity), canonicalChat } : null),
[gateIdentity, identity, canonicalChat],
@@ -128,6 +140,7 @@ function BotSessionGateView() {
useEffect(() => {
let cancelled = false;
+ let retry: ReturnType<typeof setTimeout> | undefined;
const owner = getDataOwnerGeneration();
if (!botId || !sessionId) {
setGate({ kind: 'unavailable' });
@@ -135,7 +148,7 @@ function BotSessionGateView() {
cancelled = true;
};
}
- setGate({ kind: 'loading' });
+ setGate(previous => previous.kind === 'ready' ? { ...previous, verified: false } : { kind: 'loading' });
const lastReadAt = getBotLastReadAt(botId);
void Promise.all([
window.electronAPI.localDb.bots.get(botId),
@@ -183,6 +196,7 @@ function BotSessionGateView() {
readOwner.current = owner;
setGate({
kind: 'ready',
+ verified: true,
// 欢迎语只属于主任务:渠道路由任务是「别处的对话被接进来」,
// 在那里冒出一句自我介绍是插话,不是打招呼。
isCanonical: activeProjection?.role === 'canonical',
@@ -198,18 +212,20 @@ function BotSessionGateView() {
})
.catch((error: unknown) => {
if (cancelled || !isDataOwnerGenerationCurrent(owner)) return;
- setGate({
- kind: 'error',
- message: error instanceof Error ? error.message : String(error),
- });
+ const message = error instanceof Error ? error.message : String(error);
+ const denied = /NOT_FOUND|FORBIDDEN|PERMISSION_DENIED/.test(message);
+ setGate(previous => denied ? { kind: 'unavailable' } : previous.kind === 'ready'
+ ? { ...previous, verified: false } : { kind: 'error', message });
+ if (!denied) retry = setTimeout(() => { if (isDataOwnerGenerationCurrent(owner)) setReloadVersion(value => value + 1); }, 5_000);
});
return () => {
cancelled = true;
+ clearTimeout(retry);
};
}, [botId, reloadVersion, sessionId]);
const onReadThrough = useCallback((at: number) => {
- if (isDataOwnerGenerationCurrent(readOwner.current) && gate.kind === 'ready' && gate.isCanonical && botId && gate.identity.sessionId === sessionId) markBotRead(botId, at);
+ if (isDataOwnerGenerationCurrent(readOwner.current) && gate.kind === 'ready' && gate.verified && gate.isCanonical && botId && gate.identity.sessionId === sessionId) markBotRead(botId, at);
}, [botId, gate, sessionId]);
if (gate.kind === 'loading') {
@@ -269,20 +285,20 @@ function BotSessionGateView() {
</main>
);
}
- const readOnly = shadowed && gate.isCanonical;
+ const readOnly = !gate.verified || (shadowed && gate.isCanonical);
return (
<main className="relative flex h-full min-w-0 overflow-hidden bg-[var(--surface)]">
{/* 私聊话题只属于本机的伙伴主对话;只读副本没有话题。 */}
<BotDmThreadHost enabled={gate.isCanonical && !readOnly} bot={identity ?? gate.identity}
rootSessionId={sessionId} mentions={mentions}>
- {readOnly && botId ? <CompanionShadowBanner botId={botId} name={(identity ?? gate.identity).name} /> : null}
+ {shadowed && gate.isCanonical && botId ? <CompanionShadowBanner botId={botId} name={(identity ?? gate.identity).name} /> : null}
<div className="min-h-0 flex-1">
<CCAgentSessionView
botMentions={mentions}
botIdentity={chatIdentity ?? gate.identity}
botInvitationStage={gate.isCanonical ? liveInvitationStage : undefined}
botUnreadBoundaryAt={gate.unreadBoundaryAt}
- onBotReadThrough={gate.isCanonical ? onReadThrough : undefined}
+ onBotReadThrough={gate.verified && gate.isCanonical ? onReadThrough : undefined}
{...(readOnly ? { readOnly: true } : {})}
/>
</div>
diff --git a/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx b/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx
index f5ea0da83d..9b0ad96b12 100644
--- a/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx
+++ b/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx
@@ -13,7 +13,7 @@ import { Spinner } from '@/components/ui/spinner';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';
import { toast } from '@/lib/toast';
-import type { CompanionTranscriptMessage } from '../../../shared/companionCloud';
+import type { CompanionTranscriptMessage, CompanionTranscriptPage } from '../../../shared/companionCloud';
import type { BotGroupAttachment } from '../../../shared/botGroupChat';
import { BotAvatar } from './BotAvatar';
import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';
@@ -39,15 +39,22 @@ type TakeOverState =
| { kind: 'conflict'; device: string }
| { kind: 'error'; key: string };
-export function CloudCompanionOfflineView({ botId, deviceId, name, avatar, avatarColor, deviceName, controlOff = false }: CloudCompanionOfflineViewProps) {
+let transcriptOwner = getDataOwnerGeneration();
+const transcriptPages = new Map<string, CompanionTranscriptPage>();
+export function CloudCompanionOfflineView(props: CloudCompanionOfflineViewProps) {
+ const owner = getDataOwnerGeneration();
+ if (!owner.dataOwnerId || !isDataOwnerGenerationCurrent(transcriptOwner)) { transcriptOwner = owner; transcriptPages.clear(); }
+ return <CloudCompanionOfflineContent key={JSON.stringify([owner, props.botId, props.deviceId])} {...props} />;
+}
+function CloudCompanionOfflineContent({ botId, deviceId, name, avatar, avatarColor, deviceName, controlOff = false }: CloudCompanionOfflineViewProps) {
const { t } = useTranslation();
const navigate = useNavigate();
const devices = useDeviceLinkDeviceList();
const device = deviceName.trim() || t('bots.cloud.unknownDevice');
const identity = useMemo<BotChatIdentity>(() => ({ id: botId, deviceId, deviceName: device, name, avatar, avatarColor, sessionId: null }),
[botId, deviceId, device, name, avatar, avatarColor]);
- const [messages, setMessages] = useState<CompanionTranscriptMessage[]>([]);
- const [nextBefore, setNextBefore] = useState<string | undefined>();
+ const [messages, setMessages] = useState<CompanionTranscriptMessage[]>(() => transcriptPages.get(botId)?.messages ?? []);
+ const [nextBefore, setNextBefore] = useState<string | undefined>(() => transcriptPages.get(botId)?.nextBefore);
const [loading, setLoading] = useState(true);
const [loadFailed, setLoadFailed] = useState(false);
const [state, setState] = useState<TakeOverState>({ kind: 'idle' });
@@ -55,6 +62,10 @@ export function CloudCompanionOfflineView({ botId, deviceId, name, avatar, avata
const anchor = useRef<{ height: number; top: number } | null>(null);
const stickToBottom = useRef(true);
const loadingRef = useRef(false);
+ const revision = useRef(0);
+ const alive = useRef(true);
+ const latest = useRef({ messages, nextBefore }); latest.current = { messages, nextBefore };
+ useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
const load = useCallback(async (before?: string) => {
const api = companionCloudApi();
@@ -65,12 +76,30 @@ export function CloudCompanionOfflineView({ botId, deviceId, name, avatar, avata
const owner = getDataOwnerGeneration();
try {
const page = await api.getCompanionTranscript(botId, before);
- if (!isDataOwnerGenerationCurrent(owner)) return;
+ while (!before && page.nextBefore && page.messages.length < latest.current.messages.length) {
+ if (!alive.current || !isDataOwnerGenerationCurrent(owner)) return;
+ const cursor = page.nextBefore;
+ const older = await api.getCompanionTranscript(botId, cursor);
+ const ids = new Set(page.messages.map(row => row.id));
+ page.messages = [...older.messages.filter(row => !ids.has(row.id)), ...page.messages];
+ page.nextBefore = older.nextBefore;
+ if (page.nextBefore === cursor) throw new Error('INVALID_CHAT_PAGE');
+ }
+ if (!alive.current || !isDataOwnerGenerationCurrent(owner)) return;
+ revision.current++;
if (before && scroller.current) anchor.current = { height: scroller.current.scrollHeight, top: scroller.current.scrollTop };
- setMessages((current) => before ? [...page.messages.filter((m) => !current.some((c) => c.id === m.id)), ...current] : page.messages);
- setNextBefore(page.nextBefore);
- } catch {
- if (isDataOwnerGenerationCurrent(owner)) setLoadFailed(true);
+ const next = { messages: before ? [...page.messages.filter(m => !latest.current.messages.some(c => c.id === m.id)), ...latest.current.messages] : page.messages,
+ nextBefore: page.nextBefore };
+ transcriptPages.set(botId, next);
+ void api.chatDisplayCache?.({ action: 'write', key: `companion:${botId}`, owner, value: next }).catch(() => undefined);
+ setMessages(next.messages); setNextBefore(next.nextBefore);
+ } catch (error) {
+ if (alive.current && isDataOwnerGenerationCurrent(owner)) {
+ if (/FORBIDDEN|PERMISSION_DENIED/.test(String(error))) {
+ revision.current++; transcriptPages.delete(botId); setMessages([]); setNextBefore(undefined);
+ }
+ setLoadFailed(true);
+ }
} finally {
loadingRef.current = false;
setLoading(false);
@@ -78,11 +107,17 @@ export function CloudCompanionOfflineView({ botId, deviceId, name, avatar, avata
}, [botId]);
useEffect(() => {
- setMessages([]);
- setNextBefore(undefined);
+ const owner = getDataOwnerGeneration();
+ const version = revision.current;
+ void companionCloudApi()?.chatDisplayCache?.({ action: 'read', key: `companion:${botId}`, owner }).then(value => {
+ const page = value as CompanionTranscriptPage | null;
+ if (!alive.current || !isDataOwnerGenerationCurrent(owner) || revision.current !== version
+ || !page || !Array.isArray(page.messages) || !page.messages.every(row => row && typeof row.id === 'string' && typeof row.text === 'string' && Number.isFinite(row.createdAt))) return;
+ transcriptPages.set(botId, page); setMessages(page.messages); setNextBefore(page.nextBefore);
+ }).catch(() => undefined);
stickToBottom.current = true;
void load();
- }, [load]);
+ }, [botId, load]);
useLayoutEffect(() => {
const node = scroller.current;
diff --git a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
index 8488bedbf1..939105516e 100644
--- a/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
+++ b/apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx
@@ -1,7 +1,7 @@
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { Button } from '@/components/ui/button';
import { REMOTE_RESOURCE_GET_CHANNEL, type RemoteResourceGetRequest } from '@cindy/device-link';
-import { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react';
+import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { CCAgentSessionView } from '@/features/cc-agent/CCAgentSessionView';
@@ -25,6 +25,12 @@ export const CLOUD_HOME_GRACE_MS = 15_000;
/** The session id comes from the host's collection, never from an arbitrary URL. */
export function RemoteBotSessionView() {
+ const { deviceId, botId } = useParams();
+ const owner = getDataOwnerGeneration();
+ return <RemoteBotSessionGate key={JSON.stringify([owner.dataOwnerId, owner.generation, deviceId, botId])} />;
+}
+
+function RemoteBotSessionGate() {
const { deviceId, botId } = useParams();
const { t } = useTranslation();
const bots = useRemoteBots();
@@ -32,7 +38,11 @@ export function RemoteBotSessionView() {
const cloud = useCompanionCloud();
const deviceList = useDeviceLinkDeviceList();
const cloudActor = cloudCompanionAt(cloud, deviceId, botId);
- const [ready, setReady] = useState<(RemoteBot & { sessionId: string; canonicalChat: true }) | null>(null);
+ const [ready, setReady] = useState<(RemoteBot & { sessionId: string; canonicalChat: true }) | null>(() => {
+ if (!bot?.sessionId || !deviceId || remoteProjectsStore.getSessionDeviceId(bot.sessionId) !== deviceId) return null;
+ const session = remoteProjectsStore.getDeviceSessions(deviceId).find(row => row.id === bot.sessionId);
+ return session?.source === 'bot' && session.status === 'active' ? { ...bot, sessionId: bot.sessionId, canonicalChat: true } : null;
+ });
const [validatedSessionId, setValidatedSessionId] = useState<string | null | undefined>(null);
const [failed, setFailed] = useState(false);
const [retry, setRetry] = useState(0);
@@ -43,6 +53,7 @@ export function RemoteBotSessionView() {
const owner = getDataOwnerGeneration();
setFailed(false);
if (!deviceId || !bot?.online) return;
+ setValidatedSessionId(null);
const request: RemoteResourceGetRequest = {
client: { protocolVersion: 1, primitives: ['status', 'session-link'] },
ref: { collectionId: 'teammates', kind: 'bot', id: bot.id },
@@ -54,12 +65,13 @@ export function RemoteBotSessionView() {
[request],
);
if (disposed || !isDataOwnerGenerationCurrent(owner)) return;
+ if (!resource) { setReady(null); throw new Error('Companion is not ready'); }
const [resolved] = parseRemoteBots(
{ collectionId: 'teammates', items: [resource] },
deviceId,
bot.deviceName,
);
- if (resolved.id !== bot.id || !resolved.sessionId) throw new Error('Companion is not ready');
+ if (!resolved || resolved.id !== bot.id || !resolved.sessionId) { setReady(null); throw new Error('Companion is not ready'); }
const canonicalId = resolved.sessionId;
const existingOrigin = remoteProjectsStore.getSessionDeviceId(canonicalId);
if (existingOrigin && existingOrigin !== deviceId)
@@ -79,21 +91,34 @@ export function RemoteBotSessionView() {
if (!session || session.id !== canonicalId || session.source !== 'bot' ||
session.status !== 'active' ||
(!readIsCurrent && session.deviceLinkConnectionStatus !== 'connected'))
- throw new Error('Invalid remote companion session');
+ { setReady(null); throw new Error('Invalid remote companion session'); }
if (readIsCurrent) remoteProjectsStore.mergeDeviceSessions(deviceId, currentMirror?.deviceLinkDeviceName ?? bot.deviceName, [
isSessionReadCurrent.mergeActivity(session),
]);
readOwner.current = owner;
setReady({ ...resolved, sessionId: canonicalId, canonicalChat: true });
setValidatedSessionId(sessionId);
- })().catch(() => {
- if (!disposed) setFailed(true);
+ })().catch((error: unknown) => {
+ if (!disposed && isDataOwnerGenerationCurrent(owner)) {
+ const code = (error as { code?: string })?.code;
+ const denied = ['NOT_FOUND', 'FORBIDDEN', 'PERMISSION_DENIED', 'ACCESS_REVOKED', 'DEVICE_REVOKED', 'AUTH_REQUIRED'];
+ if (denied.includes(code ?? '') || denied.some(value => String(error).includes(`[${value}]`))) setReady(null);
+ setFailed(true);
+ }
});
return () => {
disposed = true;
};
}, [deviceId, botId, sessionId, bot?.online, bot?.deviceName, retry]);
+ useEffect(() => {
+ if (!failed || !bot?.online || !ready) return;
+ const timer = setTimeout(() => setRetry(value => value + 1), 5_000);
+ return () => clearTimeout(timer);
+ }, [failed, bot?.online, ready]);
+ const identity = useMemo(() => ready ? { ...ready, canonicalChat: !failed && validatedSessionId === bot?.sessionId } : null,
+ [ready, failed, validatedSessionId, bot?.sessionId]);
+
const acknowledge = useCallback((at: number) => {
if (isDataOwnerGenerationCurrent(readOwner.current) && bot?.online && !failed && ready?.id === bot.id && ready.deviceId === bot.deviceId
&& validatedSessionId === bot.sessionId) {
@@ -101,7 +126,7 @@ export function RemoteBotSessionView() {
}
}, [bot, failed, ready, validatedSessionId]);
- const liveChat = !!bot && !failed && !!ready?.sessionId && ready.id === botId && ready.deviceId === deviceId;
+ const liveChat = !!bot && !!ready?.sessionId && ready.id === botId && ready.deviceId === deviceId;
// Like a local companion chat: once the chat is shown, the island card for this Session is read.
useBotIslandVisibleSession(liveChat ? ready!.sessionId : null);
const homeAway = !!cloudActor && !!deviceId && !!botId && cloudActor.homeDeviceId !== cloud.selfDeviceId
@@ -126,13 +151,13 @@ export function RemoteBotSessionView() {
</Suspense>
);
}
- if (bot && !failed && ready?.sessionId && ready.id === botId && ready.deviceId === deviceId) {
+ if (bot && ready?.sessionId && ready.id === botId && ready.deviceId === deviceId) {
return (
<CCAgentSessionView
key={`${deviceId}:${ready.sessionId}`}
sessionIdProp={ready.sessionId}
routeOwner
- botIdentity={ready}
+ botIdentity={identity!}
onBotReadThrough={acknowledge}
readOnly={!bot.online || validatedSessionId !== bot.sessionId || failed}
/>
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
index 582acdca9b..d0722ec6ac 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -324,7 +324,7 @@ beforeEach(() => {
maker: {
chatServer: { thread: mocks.thread, reply: mocks.reply, shareToMain: mocks.shareToMain, reactors: vi.fn(async () => ({ ok: true, reactors: [] })) },
listBotGroups: vi.fn(async () => ({ ok: true, groups: [] })),
- getBotGroup: (...args: unknown[]) => mocks.getBotGroup(...args),
+ getBotGroup: (...args: unknown[]) => (args[1] as { cacheOnly?: boolean } | undefined)?.cacheOnly ? Promise.resolve({ ok: false, errorCode: 'NOT_FOUND' }) : mocks.getBotGroup(...args),
sendBotGroupMessage: (...args: unknown[]) => mocks.sendBotGroupMessage(...args),
stopBotGroupRound: (...args: unknown[]) => mocks.stopBotGroupRound(...args),
continueBotGroupRound: (...args: unknown[]) => mocks.continueBotGroupRound(...args),
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts
index d25cd775fe..741515d483 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts
@@ -23,6 +23,7 @@ import {
mergeBotGroupLocalAttachments,
projectBotGroupOutbox,
retryBotGroupSend,
+ startBotGroupOutbox,
type BotGroupOutboxDraft,
type BotGroupOutboxSendInput,
} from '../botGroupOutbox';
@@ -38,6 +39,7 @@ const mocks = vi.hoisted(() => ({
getBotGroup: vi.fn(),
list: { groups: [] as Array<{ id: string }>, loaded: false },
listListeners: new Set<() => void>(),
+ storage: undefined as undefined | ((request: any) => Promise<any[]>),
}));
vi.mock('@/contexts/dataOwnerGeneration', () => ({
@@ -46,7 +48,7 @@ vi.mock('@/contexts/dataOwnerGeneration', () => ({
owner.dataOwnerId === (mocks.owner === null ? null : `account-${mocks.owner}`) && owner.generation === mocks.generation,
}));
vi.mock('../botGroupStore', () => ({
- botGroupApi: () => ({ sendBotGroupMessage: mocks.send, getBotGroup: mocks.getBotGroup }),
+ botGroupApi: () => ({ sendBotGroupMessage: mocks.send, getBotGroup: mocks.getBotGroup, botGroupOutbox: mocks.storage }),
getBotGroupListSnapshot: () => mocks.list,
subscribeBotGroups: (listener: () => void) => {
mocks.listListeners.add(listener);
@@ -144,6 +146,7 @@ function project(groupId: string, messages: BotGroupMessageView[]) {
beforeEach(() => {
mocks.owner = 1;
mocks.generation = 0;
+ mocks.storage = undefined;
mocks.send.mockReset();
mocks.materialize.mockReset().mockImplementation(async (files: readonly AttachedFile[]) => [...files]);
mocks.protectedUrls = [];
@@ -946,3 +949,40 @@ describe('botGroupOutbox', () => {
});
});
});
+
+// Unit regression: a restart between local enqueue and the HTTP response used to lose
+// ownership. The production outbox must save first, then restore the same clientId FIFO.
+it('durably restores a failed send and the next queued message, settling only actual receipts', async () => {
+ vi.useFakeTimers();
+ const saved = new Map<string, unknown>();
+ mocks.storage = async request => {
+ if (request.action === 'put') saved.set(request.entry.input.clientId, structuredClone(request.entry));
+ if (request.action === 'remove') saved.delete(request.clientId);
+ return request.action === 'list' ? [...saved.values()] : [];
+ };
+ mocks.send.mockRejectedValueOnce(new Error('offline'));
+ await enqueueBotGroupSend(draft({ clientId: 'first' }));
+ await enqueueBotGroupSend(draft({ clientId: 'second' }));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.send).toHaveBeenCalledTimes(1);
+ expect(saved.size).toBe(2);
+ resetBotGroupOutboxForTests();
+ mocks.send.mockImplementation(async input => ({ ok: true, messageId: `server-${input.clientId}` }));
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: { messages: [] } });
+ const events = new EventTarget();
+ vi.stubGlobal('window', events);
+ const stop = startBotGroupOutbox();
+ try {
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(mocks.send.mock.calls.map(([input]) => input.clientId)).toEqual(['first', 'first', 'second']);
+ expect(getBotGroupOutbox('g1').map(row => row.status)).toEqual(['sent', 'sent']);
+ noteBotGroupTimeline('g1', [msg({ id: 'unrelated', sequence: 20 })], beginBotGroupTimelineRead());
+ expect(saved.size).toBe(2);
+ mocks.getBotGroup.mockImplementation(async (_id, options) => ({ ok: true, group: options?.beforeSequence
+ ? { messages: [msg({ id: 'server-first', sequence: 1 }), msg({ id: 'server-second', sequence: 2 })], hasMoreBefore: false }
+ : { messages: [msg({ id: 'newer', sequence: 20 })], hasMoreBefore: true } }));
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(mocks.getBotGroup).toHaveBeenCalledWith('g1', { beforeSequence: 20 });
+ expect(saved.size).toBe(0);
+ } finally { stop(); vi.unstubAllGlobals(); vi.useRealTimers(); }
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts
index 2020d269c2..240f7e303a 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupStore.test.ts
@@ -6,8 +6,8 @@ import { getBotGroupListSnapshot, refreshBotGroups, resetBotGroupStoreForTests,
const dataOwner = vi.hoisted(() => ({ generation: 1 }));
vi.mock('@/contexts/dataOwnerGeneration', () => ({
- getDataOwnerGeneration: () => dataOwner.generation,
- isDataOwnerGenerationCurrent: (owner: number) => owner === dataOwner.generation,
+ getDataOwnerGeneration: () => ({ dataOwnerId: 'owner', generation: dataOwner.generation }),
+ isDataOwnerGenerationCurrent: (owner: { generation: number }) => owner.generation === dataOwner.generation,
isDataOwnerPushCurrent: () => true,
}));
@@ -18,15 +18,17 @@ const summary = (name: string): BotGroupSummary => ({
let push: (payload: BotGroupChangedPayload, stamp?: unknown) => void = () => {};
const listBotGroups = vi.fn();
+const chatDisplayCache = vi.fn();
beforeEach(() => {
vi.useFakeTimers();
dataOwner.generation = 1;
resetBotGroupStoreForTests();
listBotGroups.mockReset().mockResolvedValue({ ok: true, groups: [summary('周末出游')] });
+ chatDisplayCache.mockReset().mockResolvedValue(null);
Object.defineProperty(window, 'electronAPI', {
configurable: true,
- value: { maker: { listBotGroups, onBotGroupChanged: (cb: typeof push) => { push = cb; return () => {}; } } },
+ value: { maker: { listBotGroups, chatDisplayCache, onBotGroupChanged: (cb: typeof push) => { push = cb; return () => {}; } } },
});
});
@@ -36,6 +38,27 @@ afterEach(() => {
});
describe('group list mirror', () => {
+ // Integration tier: disk and server can resolve in either order at cold startup.
+ it('shows saved groups during a pending refresh and does not resurrect a fresh deletion', async () => {
+ let finish!: (value: unknown) => void;
+ listBotGroups.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ chatDisplayCache.mockResolvedValueOnce([summary('Saved group')]);
+ refreshBotGroups();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(getBotGroupListSnapshot().groups[0]?.name).toBe('Saved group');
+ finish({ ok: true, groups: [] });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(getBotGroupListSnapshot().groups).toEqual([]);
+ resetBotGroupStoreForTests();
+ let disk!: (value: unknown) => void;
+ chatDisplayCache.mockImplementationOnce(() => new Promise(resolve => { disk = resolve; }));
+ listBotGroups.mockResolvedValueOnce({ ok: true, groups: [] });
+ refreshBotGroups();
+ await vi.advanceTimersByTimeAsync(0);
+ disk([summary('Deleted group')]);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(getBotGroupListSnapshot().groups).toEqual([]);
+ });
// Unit regression: the public sync entry must recover a completed companion's
// sidebar state after its final push triggers a failed read. Previously only
// successful push bursts were covered; no later push should be required.
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx
index 8da6690314..26b6a430e0 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionRead.test.tsx
@@ -13,7 +13,9 @@ const mocks = vi.hoisted(() => ({
read: undefined as undefined | ((at: number) => void),
params: { botId: 'bot-1', sessionId: 'session-1' } as Record<string, string | undefined>,
demoted: [] as string[],
+ cached: [] as unknown[],
}));
+vi.mock('../botStore', () => ({ useBotProfiles: () => mocks.cached, getBotProfiles: () => mocks.cached }));
vi.mock('../companionCloudStore', () => ({ useCompanionCloud: () => ({ enabled: false, selfDeviceId: null, humanActorId: null, actors: [], demotedBotIds: mocks.demoted }) }));
vi.mock('../CompanionShadowBanner', () => ({ CompanionShadowBanner: ({ botId }: { botId: string }) => <div data-testid="shadow-banner">{botId}</div> }));
@@ -78,6 +80,7 @@ beforeEach(() => {
setBotReadStateOwner('owner-1');
mocks.params = { botId: 'bot-1', sessionId: 'session-1' };
mocks.demoted = [];
+ mocks.cached = [];
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(10_000);
installElectronApi(readyBot);
@@ -90,6 +93,19 @@ afterEach(() => {
});
describe('Bot conversation read position', () => {
+ // Reopening must render the existing local chat before delayed metadata returns.
+ // Existing tests only observed the final resolved gate. Unit: a cached binding + pending IPC.
+ it('shows the cached chat read-only during validation and removes it on a revoked binding', async () => {
+ mocks.cached = [readyBot];
+ let resolve!: (value: unknown) => void;
+ vi.mocked(window.electronAPI.localDb.bots.get).mockImplementation(() => new Promise(r => { resolve = r; }) as any);
+ const view = render(<BotSessionView />);
+ expect(view.getByTestId('chat').dataset.readonly).toBe('yes');
+ expect(mocks.read).toBeUndefined();
+ await act(async () => resolve({ ...readyBot, status: 'deleted' }));
+ expect(view.queryByTestId('chat')).toBeNull();
+ });
+
it('waits for a rendered reply rather than marking a mounted chat read to wall-clock time', async () => {
const view = render(<BotSessionView />);
await waitFor(() => expect(view.getByTestId('chat')).toBeTruthy());
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/companionCloudUi.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/companionCloudUi.test.tsx
index b24b1dd6e7..b96064b45b 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/companionCloudUi.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/companionCloudUi.test.tsx
@@ -4,12 +4,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { CompanionCloudSnapshot } from '../../../../shared/companionCloud';
const h = vi.hoisted(() => ({
+ owner: { dataOwnerId: 'test-owner', generation: 0 },
navigate: vi.fn(),
toast: vi.fn(),
ensureLoaded: vi.fn(async (): Promise<Array<{ id: string; status: string }>> => []),
profiles: [] as Array<{ id: string; status: string }>,
devices: [{ deviceId: 'tablet', name: 'Tablet', isSelf: false }],
}));
+vi.mock('@/contexts/dataOwnerGeneration', () => ({
+ getDataOwnerGeneration: () => h.owner,
+ isDataOwnerGenerationCurrent: (owner: unknown) => owner === h.owner,
+ isDataOwnerPushCurrent: () => true,
+}));
vi.mock('react-router-dom', () => ({ useNavigate: () => h.navigate }));
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string, opts?: Record<string, unknown>) => opts ? `${key}:${JSON.stringify(opts)}` : key }),
@@ -32,6 +38,7 @@ import { cloudOnlyRemoteBots, cloudRemoteBots, isCloudCompanionRemote, withoutCl
import { BotConnectionStatus } from '../BotConnectionStatus';
const maker = {
+ chatDisplayCache: vi.fn(),
getCompanionCloudState: vi.fn(),
onCompanionCloudChanged: vi.fn(() => () => undefined),
getCompanionTranscript: vi.fn(),
@@ -48,7 +55,9 @@ const snapshot = (home: string | null, enabled = true): CompanionCloudSnapshot =
});
beforeEach(() => {
+ h.owner = { dataOwnerId: 'test-owner', generation: h.owner.generation + 1 };
for (const fn of Object.values(maker)) fn.mockReset();
+ maker.chatDisplayCache.mockResolvedValue(null);
maker.onCompanionCloudChanged.mockImplementation(() => () => undefined);
h.navigate.mockReset();
h.toast.mockReset();
@@ -56,6 +65,17 @@ beforeEach(() => {
});
afterEach(() => { cleanup(); });
+// Integration tier: slow/failing IPC must not obscure a locally saved transcript.
+it('renders the saved cloud transcript before the remote read and preserves it on failure', async () => {
+ maker.chatDisplayCache.mockResolvedValue({ messages: [{ id: 'saved', seq: '1', text: 'Saved cloud chat', role: 'user', createdAt: 1 }] });
+ let fail!: (error: Error) => void;
+ maker.getCompanionTranscript.mockImplementation(() => new Promise((_resolve, reject) => { fail = reject; }));
+ render(<CloudCompanionOfflineView botId="mia" deviceId="laptop" name="Mia" deviceName="Laptop" />);
+ expect(await screen.findByText('Saved cloud chat')).toBeTruthy();
+ await act(async () => fail(new Error('offline')));
+ expect(screen.getByText('Saved cloud chat')).toBeTruthy();
+});
+
describe('presentation helpers', () => {
it('hides demoted copies and adds unseen cloud homes as offline rows', () => {
const cloud = { ...snapshot('laptop'), demotedBotIds: ['mia'] };
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
index 9621c3e574..3e6c4340ad 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/remoteBotSession.test.tsx
@@ -12,6 +12,7 @@ const h = vi.hoisted(() => ({
view: vi.fn(),
online: true,
listed: true,
+ cached: false,
lastReplyAt: 0,
devices: null as Array<{ deviceId: string; online: boolean; remoteControlEnabled: boolean }> | null,
cloud: { enabled: false, selfDeviceId: null, humanActorId: null, actors: [], demotedBotIds: [] } as import('../../../../shared/companionCloud').CompanionCloudSnapshot,
@@ -43,9 +44,9 @@ vi.mock('../useRemoteBots', () => ({
vi.mock('@/features/device-link/remoteProjectsStore', () => ({
remoteProjectsStore: {
pinSessionOrigin: h.pin,
- getSessionDeviceId: () => undefined,
+ getSessionDeviceId: (id: string) => h.cached && id === 'old-canonical' ? 'home' : undefined,
mergeDeviceSessions: h.merge,
- getDeviceSessions: () => [],
+ getDeviceSessions: () => h.cached ? [{ id: 'old-canonical', source: 'bot', status: 'active' }] : [],
captureSessionRead: () => Object.assign(() => true, { mergeActivity: <T,>(detail: T) => detail }),
},
}));
@@ -60,6 +61,7 @@ beforeEach(() => {
h.markRead.mockClear();
h.online = true;
h.listed = true;
+ h.cached = false;
h.lastReplyAt = 0;
h.cloud = { enabled: false, selfDeviceId: null, humanActorId: null, actors: [], demotedBotIds: [] };
h.devices = null;
@@ -195,3 +197,21 @@ it('reads "control off" from the live device list, so a stale snapshot neither h
rerender(<RemoteBotSessionView />);
expect(h.cloudView).toHaveBeenLastCalledWith(expect.objectContaining({ controlOff: false }));
});
+
+// Unit: saved host identity opens its existing history before an unresolved RPC;
+// a later definitive removal must still close it. Covers the former two-RPC entry gate.
+it.each(['missing', 'ACCESS_REVOKED'])('mounts the cached remote task read-only and closes it on %s', async rejection => {
+ h.cached = true;
+ let finish!: (value: unknown) => void;
+ let fail!: (error: Error) => void;
+ h.invoke.mockImplementation(() => new Promise((resolve, reject) => { finish = resolve; fail = reject; }));
+ render(<RemoteBotSessionView />);
+ expect(screen.getByText('remote-conversation')).toBeTruthy();
+ expect(h.view).toHaveBeenLastCalledWith(expect.objectContaining({ sessionIdProp: 'old-canonical', readOnly: true,
+ botIdentity: expect.objectContaining({ canonicalChat: false }) }));
+ await act(async () => {
+ if (rejection === 'missing') finish(null);
+ else fail(Object.assign(new Error('revoked'), { code: rejection }));
+ });
+ expect(screen.queryByText('remote-conversation')).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts b/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts
index 2ffc4857fc..89e84f3a40 100644
--- a/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts
+++ b/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts
@@ -1,36 +1,10 @@
/**
- * 群聊发件箱:用户点发送后立即在时间线末尾显示自己的消息,不等 main / 服务器回执。
- *
- * 只是 renderer 内存里的展示状态,不持久化,也不替代 main 的幂等与服务器的权威时间线:
- * - 每条消息保存 composer 交来的完整发送输入(`BotGroupSendInput`,附件除外——附件在
- * 入队时就开始烧录标注,提交时序列化),提交与重试都原样发出,这里不挑字段;新增发送字段只需
- * composer 放进 `input`,显示、回执与重试自动带上。
- * - `input.clientId` 是身份,失败重试沿用同一个 clientId,main 与服务器据此去重,
- * 所以这里绝不自动重发。
- * - 同一个群的提交按发出顺序一条一条交给 main,保持用户看到的先后。
- * - 回执带回的 `messageId` 是替换依据:时间线读到这条消息就收起临时气泡;回执之后开始的
- * 一次重读即使没读到(被挤出最新一页),也说明它已进历史,同样收起。
- * - 推送重读可能先于回执到达。此时只对正在提交的那一条(同群同时最多一条)做显示上的
- * 去重:基线之后出现、未被任何回执认领、正文与附件数一致的自己的消息视为它,回执到达后
- * 仍以 messageId 为准。
- * - 附件:临时消息从输入的附件生成列表;带手绘标注的图片烧录完成后改用烧录后的本地预览
- * (同一份烧录结果也用于提交与重试,不重复烧录;放回输入框的仍是带笔迹的原件)。真实消息到了
- * 而服务器副本还没下载好(没有 url / path,或还没出现在列表里——main 只列已下载的副本)时,按同一 messageId
- * 把本地预览接到真实消息上,直到副本可用(见 `mergeBotGroupLocalAttachments`)。
- * - 离开输入框的附件不再受草稿保护:发件箱条目持有的图片地址(含标注原图与烧录副本)登记进
- * 存储清理的保护清单,条目移除时同步撤下;已确认消息的本地预览不登记——发送时 main 已在群的
- * `bot-group-attachment` 引用下固定这些图片。尚未进入消息的暂存文件按归属回收:还没开始提交的条目
- * (排队中、已失败)归发件箱,群被删除(含不在当前页的群:列表里消失且读取确认已不存在)时
- * 立即回收;已开始提交的条目归它的那次请求,条目在烧录期间被丢弃就不再发出并回收,
- * 已交给 main 的等结果——成功(已进入消息)不碰,失败才回收。main 的发送在 IPC 返回前读完
- * 全部本地文件,失败时不留任何引用暂存路径的本地记录(服务端只引用已上传的副本)。
- * 切换账号时同样按此发出回收,但 main 只删当前账号暂存目录里的副本,而 renderer 看到切换时
- * main 已在新账号(或边界)下:前一账号的副本留在它自己的暂存目录,renderer 无法再删,
- * 不在发件箱范围内(main 的暂存副本按账号划界)。
- * - 失败时交还输入框(输入框空着才交还,见 `registerBotGroupComposer`),否则留在时间线上
- * 显示没发出去,可重试或编辑;失败时输入框不在(切群、分享模式),回来注册输入框时同样交还。
- * - 切换到另一个账号时整体清空,旧账号的迟到回执一律丢弃;同账号的 generation 修复、认证边界
- * 短暂发布的 null、退出后重新登录同一账号都不清空。群被删除时丢弃该群的条目。
+ * Existing group-chat outbox: immediate timeline projection, per-room FIFO and stable clientId.
+ * Main persists each entry and its media references before the composer relinquishes the draft.
+ * Startup restores queued/failed/sent entries; transport failures retry, content/access refusals
+ * remain available for editing. A receipt remains until its canonical message is read back.
+ * Annotation materialization and local preview replacement reuse the same send attempt.
+ * Owner changes clear this window's projection without deleting the previous owner's ledger.
*/
import { useCallback, useSyncExternalStore } from 'react';
@@ -39,6 +13,7 @@ import { isAnnotationBurnInError, materializeAnnotatedAttachmentsForSend } from
import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';
import { setBotGroupOutboxAttachmentUrls } from '@/lib/composerDraftStore';
import type { AttachedFile } from '@/lib/fileTypes';
+import type { BotGroupOutboxStoredEntry } from '../../../shared/botGroupOutboxStorage';
import type {
BotGroupAttachment,
BotGroupErrorCode,
@@ -186,6 +161,67 @@ function releaseStaged(files: readonly AttachedFile[]): void {
/** Entries whose `submit` has started: that request owns their files until it settles. */
const submitting = new Set<string>();
const entryKey = (groupId: string, clientId: string) => `${groupId}\n${clientId}`;
+const durable = () => botGroupApi()?.botGroupOutbox;
+function persist(entry: BotGroupOutboxEntry): Promise<unknown> {
+ return durable()?.({ action: 'put', owner: getDataOwnerGeneration(), entry: entry as unknown as BotGroupOutboxStoredEntry }) ?? Promise.resolve();
+}
+function forgetSaved(groupId: string, clientId: string): void {
+ void durable()?.({ action: 'remove', owner: getDataOwnerGeneration(), groupId, clientId }).catch(() => undefined);
+}
+
+/** Main-window lifetime: restore once per owner and retry transport failures in room order. */
+export function startBotGroupOutbox(): () => void {
+ ensureOwner();
+ const owner = getDataOwnerGeneration();
+ let stopped = false;
+ let ready = false;
+ const current = () => !stopped && isDataOwnerGenerationCurrent(owner);
+ const run = async () => {
+ if (!current() || !owner.dataOwnerId || !durable()) return;
+ if (!ready) {
+ const saved = await durable()!({ action: 'list', owner });
+ if (!current()) return;
+ for (const value of saved) {
+ const entry = value as unknown as BotGroupOutboxEntry;
+ const group = groupOf(entry.input.groupId);
+ if (!group.entries.some(row => row.input.clientId === entry.input.clientId)) group.entries = [...group.entries, entry];
+ }
+ ready = true; emit();
+ }
+ for (const [groupId, group] of groups) {
+ const first = group.entries.find(entry => entry.status !== 'sent');
+ if (first && first.retryable !== false && !submitting.has(entryKey(groupId, first.input.clientId))) {
+ if (first.status === 'failed') retryBotGroupSend(groupId, first.input.clientId);
+ else schedule(groupId, first.input.clientId);
+ }
+ if (group.entries.some(entry => entry.status === 'sent')) {
+ const token = beginBotGroupTimelineRead();
+ let result = await botGroupApi()!.getBotGroup(groupId);
+ if (!current()) return;
+ if (result.ok) {
+ noteBotGroupTimeline(groupId, result.group.messages, token);
+ // A restart may happen after many newer messages. Reconcile receipts outside
+ // the newest page without moving or discarding the displayed timeline.
+ while (result.ok && result.group.hasMoreBefore && group.entries.some(entry => entry.status === 'sent')) {
+ const before = Math.min(...result.group.messages.map(message => message.sequence));
+ if (!Number.isFinite(before)) break;
+ result = await botGroupApi()!.getBotGroup(groupId, { beforeSequence: before });
+ if (!current()) return;
+ if (!result.ok) break;
+ noteBotGroupTimeline(groupId, result.group.messages, token);
+ if (!result.group.messages.some(message => message.sequence < before)) break;
+ }
+ }
+ else if (result.errorCode === 'NOT_FOUND' || result.errorCode === 'PERMISSION_DENIED') discardBotGroupOutbox(groupId);
+ }
+ }
+ };
+ let running = false;
+ const tick = () => { if (!running) { running = true; void run().catch(() => undefined).finally(() => { running = false; }); } };
+ const timer = setInterval(tick, 5_000);
+ window.addEventListener('online', tick); window.addEventListener('focus', tick); tick();
+ return () => { stopped = true; clearInterval(timer); window.removeEventListener('online', tick); window.removeEventListener('focus', tick); };
+}
/** Drop entries the outbox still owns; a request in progress settles its own (see `submit`). */
function releaseUnsubmitted(groupId: string, entries: readonly BotGroupOutboxEntry[]): void {
@@ -202,7 +238,7 @@ function ensureOwner(): void {
if (previous === null) return;
generation += 1;
// The previous account's queued and failed sends go with it; one being submitted settles itself.
- for (const [groupId, group] of groups) releaseUnsubmitted(groupId, group.entries);
+ if (!durable()) for (const [groupId, group] of groups) releaseUnsubmitted(groupId, group.entries);
groups.clear();
preparing.clear();
protectHeldMedia();
@@ -225,6 +261,7 @@ function update(groupId: string, clientId: string, patch: Partial<BotGroupOutbox
if (!group || index < 0) return null;
const next = { ...group.entries[index]!, ...patch };
group.entries = group.entries.map((entry, at) => (at === index ? next : entry));
+ void persist(next).catch(() => undefined);
emit();
return next;
}
@@ -233,6 +270,7 @@ function remove(groupId: string, clientId: string): void {
const group = groups.get(groupId);
if (!group || !group.entries.some((entry) => entry.input.clientId === clientId)) return;
group.entries = group.entries.filter((entry) => entry.input.clientId !== clientId);
+ forgetSaved(groupId, clientId);
emit();
}
@@ -250,7 +288,7 @@ function displayAttachments(files: readonly AttachedFile[]): BotGroupAttachment[
}
/** Show the message at once and queue it behind the group's earlier sends. */
-export function enqueueBotGroupSend(draft: BotGroupOutboxDraft): void {
+export async function enqueueBotGroupSend(draft: BotGroupOutboxDraft): Promise<void> {
const { groupId, clientId } = draft.input;
const group = groupOf(groupId);
const entry: BotGroupOutboxEntry = {
@@ -267,6 +305,12 @@ export function enqueueBotGroupSend(draft: BotGroupOutboxDraft): void {
// Sent again after 编辑 (same clientId): a burn that failed before is tried afresh.
preparing.delete(entryKey(groupId, clientId));
emit();
+ if (durable()) {
+ const owner = getDataOwnerGeneration();
+ try { await persist(entry); }
+ catch (error) { if (isDataOwnerGenerationCurrent(owner)) remove(groupId, clientId); throw error; }
+ if (!isDataOwnerGenerationCurrent(owner)) throw new Error('OUTBOX_OWNER_CHANGED');
+ }
schedule(groupId, clientId);
// Burn annotations in now, not when the message's turn comes: the bubble shows the result.
if (entry.files.length > 0) void prepare(groupId, clientId).catch(() => undefined);
@@ -285,10 +329,11 @@ function prepare(groupId: string, clientId: string): Promise<readonly AttachedFi
const existing = preparing.get(key);
if (existing) return existing;
const requestGeneration = generation;
+ const requestOwner = getDataOwnerGeneration();
const pending = materializeAnnotatedAttachmentsForSend(entry.files, entry.attachmentScope, { burnFailure: 'abort' })
.then((files) => {
const prepared = files ?? [];
- if (requestGeneration === generation) {
+ if (requestGeneration === generation && isDataOwnerGenerationCurrent(requestOwner)) {
update(groupId, clientId, { prepared, attachments: displayAttachments(prepared) });
}
if (preparing.get(key) === pending) preparing.delete(key);
@@ -322,9 +367,10 @@ export function editBotGroupSend(groupId: string, clientId: string): boolean {
function schedule(groupId: string, clientId: string): void {
const group = groupOf(groupId);
const requestGeneration = generation;
+ const requestOwner = getDataOwnerGeneration();
// Kept by the request itself: after an account switch the entry is gone but its files are not.
const files = group.entries.find((entry) => entry.input.clientId === clientId)?.files ?? [];
- group.chain = group.chain.then(() => submit(groupId, clientId, requestGeneration, files)).catch(() => undefined);
+ group.chain = group.chain.then(() => submit(groupId, clientId, requestGeneration, files, requestOwner)).catch(() => undefined);
}
async function submit(
@@ -332,15 +378,19 @@ async function submit(
clientId: string,
requestGeneration: number,
files: readonly AttachedFile[],
+ requestOwner: ReturnType<typeof getDataOwnerGeneration>,
): Promise<void> {
// An account switch nothing else noticed yet (no group open) settles the outbox here.
ensureOwner();
- const isCurrent = () => requestGeneration === generation && !accountChanged();
+ const isCurrent = () => requestGeneration === generation && !accountChanged()
+ && (!durable() || isDataOwnerGenerationCurrent(requestOwner));
// Dropped before its turn (account switch, deleted group): whoever dropped it released its files.
if (!isCurrent()) return;
const group = groups.get(groupId);
const entry = group?.entries.find((candidate) => candidate.input.clientId === clientId);
if (!group || !entry || entry.status !== 'sending') return;
+ // A retryable earlier send must not be overtaken after a transport failure.
+ if (durable() && group.entries.slice(0, group.entries.indexOf(entry)).some(row => row.status !== 'sent')) return;
// From here this request owns the files. Still the outbox's message: same account, still listed.
const owned = () =>
isCurrent() && (groups.get(groupId)?.entries.some((candidate) => candidate.input.clientId === clientId) ?? false);
@@ -370,9 +420,12 @@ async function submitOwned(
const prepared = await prepare(groupId, clientId);
// Dropped while annotations were burning in: it never reaches main.
if (!owned()) {
- releaseStaged(files);
+ if (!durable()) releaseStaged(files);
return;
}
+ const saved = groups.get(groupId)?.entries.find(row => row.input.clientId === clientId);
+ if (saved) await persist(saved);
+ if (!owned()) return;
const result: BotGroupSendResult = await api.sendBotGroupMessage({
...entry.input,
...(prepared.length > 0 ? { attachments: toBotGroupAttachmentInputs(prepared) } : {}),
@@ -380,7 +433,7 @@ async function submitOwned(
if (!owned()) {
// A late answer for a dropped message: keep what went out, release what did not. Main has
// read the files by the time it answers.
- if (!result.ok) releaseStaged(files);
+ if (!result.ok && !durable()) releaseStaged(files);
return;
}
if (result.ok) {
@@ -390,7 +443,7 @@ async function submitOwned(
}
// An original that is no longer available is not put back with the draft.
if (result.errorCode === 'QUOTE_UNAVAILABLE') update(groupId, clientId, { quote: null });
- retryable = !CONTENT_REFUSALS.has(result.errorCode);
+ retryable = !CONTENT_REFUSALS.has(result.errorCode) && !['NOT_FOUND', 'PERMISSION_DENIED'].includes(result.errorCode);
errorKey =
result.errorCode === 'INVALID_PARAMS' && prepared.length > 0
? 'bots.groupChat.composer.attachmentsFailed'
@@ -398,7 +451,7 @@ async function submitOwned(
} catch (error) {
// Burn-in failed (never sent) or the call failed without an answer from main's handler.
if (!owned()) {
- releaseStaged(files);
+ if (!durable()) releaseStaged(files);
return;
}
if (isAnnotationBurnInError(error)) errorKey = 'chat.media.annotateBurnFailedNotSent';
@@ -406,8 +459,8 @@ async function submitOwned(
const failed = update(groupId, clientId, { status: 'failed', errorKey, retryable, baseline: undefined });
if (!failed) return;
const composer = composers.get(groupId);
- if (composer?.restore(failed)) remove(groupId, clientId);
- composer?.notifyFailed(errorKey);
+ if (!durable() && composer?.restore(failed)) remove(groupId, clientId);
+ if (!durable() || !retryable) composer?.notifyFailed(errorKey);
}
/** Mark the start of a timeline read; pass the token to `noteBotGroupTimeline` when it lands. */
@@ -425,7 +478,7 @@ export function noteBotGroupTimeline(groupId: string, messages: readonly BotGrou
const byId = new Map(messages.map((message) => [message.id, message]));
const settled = (entry: BotGroupOutboxEntry) =>
entry.status === 'sent' &&
- ((entry.messageId !== undefined && byId.has(entry.messageId)) || (entry.receiptTick ?? Infinity) < readToken);
+ ((entry.messageId !== undefined && byId.has(entry.messageId)) || (!durable() && (entry.receiptTick ?? Infinity) < readToken));
const previews = new Map(group.previews);
let changed = false;
// A settled message keeps its local previews until the timeline has a usable copy of each.
@@ -451,6 +504,7 @@ export function noteBotGroupTimeline(groupId: string, messages: readonly BotGrou
continue;
}
const sequence = entry.messageId ? byId.get(entry.messageId)?.sequence : undefined;
+ forgetSaved(groupId, entry.input.clientId);
if (sequence !== undefined) floor = Math.max(floor, sequence);
}
group.entries = kept;
@@ -519,6 +573,7 @@ export function discardBotGroupOutbox(groupId: string): void {
const group = groups.get(groupId);
if (!group) return;
groups.delete(groupId);
+ for (const entry of group.entries) forgetSaved(groupId, entry.input.clientId);
releaseUnsubmitted(groupId, group.entries);
emit();
}
@@ -582,7 +637,7 @@ function verifyGroupGone(groupId: string, attempt: number): void {
export function registerBotGroupComposer(groupId: string, handle: BotGroupComposerHandle): () => void {
composers.set(groupId, handle);
const failed = groups.get(groupId)?.entries.find((entry) => entry.status === 'failed');
- if (failed && handle.restore(failed)) {
+ if (failed && !durable() && handle.restore(failed)) {
remove(groupId, failed.input.clientId);
handle.notifyFailed(failed.errorKey ?? 'bots.groupChat.composer.sendFailed');
}
diff --git a/apps/desktop/src/renderer/features/bots/botGroupStore.ts b/apps/desktop/src/renderer/features/bots/botGroupStore.ts
index a609d7c100..6bea0c67a2 100644
--- a/apps/desktop/src/renderer/features/bots/botGroupStore.ts
+++ b/apps/desktop/src/renderer/features/bots/botGroupStore.ts
@@ -46,6 +46,8 @@ let pushTimer: ReturnType<typeof setTimeout> | null = null;
let retryTimer: ReturnType<typeof setTimeout> | null = null;
let readFailures = 0;
let syncUsers = 0;
+let hydratedOwner = '';
+let listReadVersion = 0;
/** Pushes within this window collapse into one list read. */
const PUSH_REFRESH_DELAY_MS = 300;
let unsubscribePush: (() => void) | null = null;
@@ -115,11 +117,30 @@ function applySnapshot(next: BotGroupListSnapshot): void {
emit();
}
+function persistList(): void {
+ if (!owner.dataOwnerId) return;
+ void botGroupApi()?.chatDisplayCache?.({ action: 'write', key: 'groups', owner, value: snapshot.groups }).catch(() => undefined);
+}
+
+function restoreList(): void {
+ const key = JSON.stringify(owner);
+ if (!owner.dataOwnerId || hydratedOwner === key) return;
+ hydratedOwner = key;
+ const requestOwner = owner;
+ const version = listReadVersion;
+ void botGroupApi()?.chatDisplayCache?.({ action: 'read', key: 'groups', owner }).then(value => {
+ if (!isDataOwnerGenerationCurrent(requestOwner) || listReadVersion !== version || !Array.isArray(value)) return;
+ if (!value.every(row => row && typeof row.id === 'string' && typeof row.name === 'string' && Array.isArray(row.members))) return;
+ applySnapshot({ groups: visibleGroups(value as BotGroupSummary[]), loaded: false });
+ }).catch(() => undefined);
+}
+
/** Re-read the list from main; concurrent calls collapse into one follow-up. */
export function refreshBotGroups(): void {
ensureOwner();
const api = botGroupApi();
if (!api) return;
+ restoreList();
if (inFlight) {
refreshQueued = true;
return;
@@ -134,13 +155,14 @@ export function refreshBotGroups(): void {
// Every change kind re-reads the list, including 'plan' (open-plan status in the row).
const result = await api.listBotGroups();
if (!isCurrent()) return;
- if (result.ok) readFailures = 0;
+ if (result.ok) { readFailures = 0; listReadVersion++; }
else scheduleRetryRefresh();
if (result.ok) seedBotGroupReadState(visibleGroups(result.groups));
// An unchanged list keeps its snapshot: subscribers (sidebar, Dock badge) do not re-render.
if (result.ok && snapshot.loaded && JSON.stringify(visibleGroups(result.groups)) === JSON.stringify(snapshot.groups)) return;
// 失败时保留上一份列表:侧栏不因一次读失败把所有群清空。
applySnapshot(result.ok ? { groups: visibleGroups(result.groups), loaded: true } : { ...snapshot, loaded: true });
+ if (result.ok) persistList();
} catch {
if (isCurrent()) {
scheduleRetryRefresh();
@@ -173,9 +195,11 @@ export function startBotGroupSync(): () => void {
ensureOwner();
if (payload.change === 'list' && payload.listState && (personalList.get(payload.groupId)?.revision ?? 0) < payload.listState.revision) {
personalList.set(payload.groupId, payload.listState);
+ listReadVersion++;
const groups = visibleGroups(snapshot.groups);
seedBotGroupReadState(groups);
applySnapshot({ ...snapshot, groups });
+ persistList();
}
schedulePushRefresh();
});
@@ -268,6 +292,7 @@ async function settlePlanMutation(
/** Test-only reset of the module state. */
export function resetBotGroupStoreForTests(): void {
+ hydratedOwner = ''; listReadVersion++;
unsubscribePush?.();
unsubscribePush = null;
syncUsers = 0;
diff --git a/apps/desktop/src/renderer/features/bots/companionCloudStore.ts b/apps/desktop/src/renderer/features/bots/companionCloudStore.ts
index f5b85c754a..8dedddce13 100644
--- a/apps/desktop/src/renderer/features/bots/companionCloudStore.ts
+++ b/apps/desktop/src/renderer/features/bots/companionCloudStore.ts
@@ -22,6 +22,7 @@ let snapshot: CompanionCloudSnapshot = EMPTY_COMPANION_CLOUD_SNAPSHOT;
let owner = getDataOwnerGeneration();
// Counts pushes: a refresh answered after a push may carry the older snapshot.
let pushes = 0;
+let hydratedOwner = '';
let users = 0;
let unsubscribePush: (() => void) | null = null;
const listeners = new Set<() => void>();
@@ -37,6 +38,36 @@ function apply(next: CompanionCloudSnapshot): void {
for (const listener of listeners) listener();
}
+function accept(next: CompanionCloudSnapshot): void {
+ // A process starts with an empty registry before /me and /actors return.
+ // That is not an authoritative deletion of the saved companion list.
+ if (!next.enabled && !next.humanActorId && snapshot.actors.length) return;
+ if (next.enabled) {
+ const ids = new Set(next.actors.map(actor => actor.externalId));
+ for (const actor of snapshot.actors) if (!ids.has(actor.externalId)) {
+ void companionCloudApi()?.chatDisplayCache?.({ action: 'remove', key: `companion:${actor.externalId}`, owner }).catch(() => undefined);
+ }
+ }
+ apply(next);
+ if (next.enabled || next.humanActorId) {
+ void companionCloudApi()?.chatDisplayCache?.({ action: 'write', key: 'cloud-homes', owner, value: next }).catch(() => undefined);
+ }
+}
+
+function hydrate(): void {
+ const stamp = JSON.stringify(owner);
+ if (!owner.dataOwnerId || hydratedOwner === stamp) return;
+ hydratedOwner = stamp;
+ const requestOwner = owner;
+ void companionCloudApi()?.chatDisplayCache?.({ action: 'read', key: 'cloud-homes', owner }).then(value => {
+ const cached = value as CompanionCloudSnapshot | null;
+ if (!isDataOwnerGenerationCurrent(requestOwner) || snapshot.enabled || snapshot.humanActorId
+ || !cached || !Array.isArray(cached.actors) || !Array.isArray(cached.demotedBotIds)
+ || !cached.actors.every(actor => actor && typeof actor.id === 'string' && typeof actor.externalId === 'string' && typeof actor.name === 'string')) return;
+ apply(cached);
+ }).catch(() => undefined);
+}
+
function ensureOwner(): void {
if (isDataOwnerGenerationCurrent(owner)) return;
owner = getDataOwnerGeneration();
@@ -48,10 +79,11 @@ export function refreshCompanionCloudSettled(): Promise<void> {
ensureOwner();
const api = companionCloudApi();
if (!api) return Promise.resolve();
+ hydrate();
const requestOwner = owner;
const requestPushes = pushes;
return Promise.resolve().then(() => api.getCompanionCloudState()).then((next) => {
- if (isDataOwnerGenerationCurrent(requestOwner) && pushes === requestPushes && next) apply(next);
+ if (isDataOwnerGenerationCurrent(requestOwner) && pushes === requestPushes && next) accept(next);
}).catch(() => undefined);
}
@@ -68,7 +100,7 @@ function start(): () => void {
if (!isDataOwnerPushCurrent(ownerStamp)) return;
ensureOwner();
pushes += 1;
- apply(next);
+ accept(next);
});
}
refreshCompanionCloud();
@@ -106,5 +138,6 @@ export function getCompanionCloudSnapshot(): CompanionCloudSnapshot {
/** Test-only reset of the module mirror. */
export function resetCompanionCloudStoreForTests(next: CompanionCloudSnapshot = EMPTY_COMPANION_CLOUD_SNAPSHOT): void {
owner = getDataOwnerGeneration();
+ hydratedOwner = '';
apply(next);
}
diff --git a/apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts b/apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts
index 6decfaf039..7c348cf4b3 100644
--- a/apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts
+++ b/apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts
@@ -4,6 +4,7 @@ import { refreshBotProfiles, useBotProfiles } from './botStore';
import { subscribeBotReadState } from './botReadState';
import { makerChatStore } from '@/lib/makerChatStore';
import { startBotGroupSync } from './botGroupStore';
+import { startBotGroupOutbox } from './botGroupOutbox';
/** Main-window lifetime: entering a section is never a read receipt. */
export function useBotUnreadSync(): void {
@@ -26,6 +27,7 @@ export function useBotUnreadSync(): void {
maker?.onBotLifecycleChanged?.((_payload, stamp) => { if (isDataOwnerPushCurrent(stamp)) refresh(); }),
subscribeBotReadState(refresh),
startBotGroupSync(),
+ startBotGroupOutbox(),
];
window.addEventListener('focus', refresh);
return () => {
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 5d88643943..75753006a3 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5569,6 +5569,8 @@ interface ElectronAPI {
sendBotGroupMessage: (
input: import('../shared/botGroupChat').BotGroupSendInput,
) => Promise<import('../shared/botGroupChat').BotGroupSendResult>;
+ chatDisplayCache: (request: import('../shared/chatDisplayCache').ChatDisplayCacheRequest) => Promise<unknown>;
+ botGroupOutbox: (input: import('../shared/botGroupOutboxStorage').BotGroupOutboxStorageRequest) => Promise<import('../shared/botGroupOutboxStorage').BotGroupOutboxStoredEntry[]>;
continueBotGroupRound: (groupId: string) => Promise<import('../shared/botGroupChat').BotGroupMutationResult>;
stopBotGroupRound: (groupId: string, scope?: 'all') => Promise<import('../shared/botGroupChat').BotGroupMutationResult>;
startBotGroupPlan: (
diff --git a/apps/desktop/src/shared/botGroupOutboxStorage.ts b/apps/desktop/src/shared/botGroupOutboxStorage.ts
new file mode 100644
index 0000000000..2e90bca25d
--- /dev/null
+++ b/apps/desktop/src/shared/botGroupOutboxStorage.ts
@@ -0,0 +1,11 @@
+/** Local main/renderer contract; never exposed through device-link. */
+export interface BotGroupOutboxStoredEntry {
+ input: { groupId: string; clientId: string; text: string };
+ createdAt: number;
+ status: 'sending' | 'sent' | 'failed';
+ [key: string]: unknown;
+}
+export type BotGroupOutboxStorageRequest = {
+ owner: { dataOwnerId: string | null; generation: number };
+} & ({ action: 'list' } | { action: 'put'; entry: BotGroupOutboxStoredEntry }
+ | { action: 'remove'; groupId: string; clientId: string });
diff --git a/apps/desktop/src/shared/chatDisplayCache.ts b/apps/desktop/src/shared/chatDisplayCache.ts
new file mode 100644
index 0000000000..ffda32c9e0
--- /dev/null
+++ b/apps/desktop/src/shared/chatDisplayCache.ts
@@ -0,0 +1,5 @@
+/** Local display snapshots. They never authorize sends, controls or read receipts. */
+export type ChatDisplayCacheRequest = {
+ owner: { dataOwnerId: string | null; generation: number };
+ key: 'groups' | 'cloud-homes' | `companion:${string}`;
+} & ({ action: 'read' } | { action: 'write'; value: unknown } | { action: 'remove' });
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
index a51e8813af..b90f6a99bb 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -1524,15 +1524,19 @@ describe('group settings', () => {
describe('offline computer', () => {
it('says the computer is offline instead of spinning, and disables actions on a loaded group', async () => {
+ vi.useFakeTimers();
h.chat = { ...h.chat, online: false };
await render(null, 'loading');
expect(byId('botGroup.offline')?.textContent).toContain('devices.resources.hostOffline');
expect(byId('spinner')).toBeNull();
await render();
+ expect(byId('botGroup.offlineNote')).toBeNull();
+ await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
expect(byId('botGroup.offlineNote')).not.toBeNull();
expect(byId('botGroup.plan.start')?.disabled).toBe(true);
expect(byId('botGroup.continue')?.disabled).toBe(true);
expect(h.row.editable).toBe(false);
+ vi.useRealTimers();
});
});
diff --git a/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx b/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
index 48eee375b5..f1ac3fe1f3 100644
--- a/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
+++ b/apps/mobile/src/__tests__/HomeTeammatesSection.test.tsx
@@ -2,7 +2,7 @@
import { act, createContext, createElement as el } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-const h = vi.hoisted(() => ({ cloudRefresh: vi.fn(async () => {}), push: vi.fn(),
+const h = vi.hoisted(() => ({ cloudRefresh: vi.fn(async () => {}), cloudError: null as string | null, push: vi.fn(),
openTeammate: vi.fn(async (_row: unknown) => {}),
cloudActor: null as null | { id: string }, createOptions: null as any, collapsed: false, unread: false,
cacheRevision: 0, cacheListeners: new Set<() => void>(), unreadIds: new Set<string>(),
@@ -33,7 +33,7 @@ vi.mock('@/components/RemoteCompanionAvatar', () => ({ RemoteCompanionAvatar: ({
vi.mock('@/chat/cloudCompanion', () => ({ CLOUD_ROW_REVISION: 'cloud', cloudActorForRow: () => h.cloudActor, cloudCompanionRows: (items: unknown) => items }));
vi.mock('@/session/teammateNavigation', () => ({ cloudCompanionRoute: () => '/cloud-chat' }));
vi.mock('@/session/botGroupNavigation', () => ({ botGroupRoute: () => '/group-chat' }));
-vi.mock('@/chat/useCloudCompanion', () => ({ useCloudCompanionHome: () => ({ supported: true, actors: [], deviceNames: {}, refresh: h.cloudRefresh }) }));
+vi.mock('@/chat/useCloudCompanion', () => ({ useCloudCompanionHome: () => ({ supported: true, actors: [], deviceNames: {}, error: h.cloudError, refresh: h.cloudRefresh }) }));
vi.mock('@/device-link/remoteResourceCache', () => ({
isRemoteResourceUnread: (_owner: string, _device: string, id: string) => h.unread || h.unreadIds.has(id),
remoteResourceCacheRevision: () => h.cacheRevision,
@@ -66,6 +66,7 @@ vi.mock('@/session/useTeammateNavigation', () => ({ useTeammateNavigation: () =>
owner: 'owner', teammatesCollapsed: h.collapsed, lastTeammate: null,
setTeammatesCollapsed: async () => {}, openTeammate: h.openTeammate, openCreatedTeammate: async () => {} }) }));
import { HomeTeammatesSection } from '../session/HomeTeammatesSection';
+import { getHomeViewSession } from '../session/homeViewSession';
import { CONNECTION_NOTICE_DELAY_MS } from '../components/connectionNoticeDelay';
const item = { key: 'host:bot', host: { deviceId: 'host', deviceName: 'Mac' }, item: {
@@ -76,6 +77,7 @@ const groups = { items: [] as any[], supported: true, refreshing: false, error:
let root: Root; let node: HTMLDivElement;
beforeEach(() => { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); node = document.createElement('div'); root = createRoot(node); vi.clearAllMocks(); h.cloudActor = null; vi.useFakeTimers(); roster.error = 'LIST_FAILED'; h.collapsed = false; h.unread = false; groups.items = [];
h.cacheRevision = 0; h.unreadIds.clear(); h.stripRenders = []; h.avatarRenders = []; h.identityReads = 0;
+ h.cloudError = null; getHomeViewSession().write('teammatesShowAll', false);
});
afterEach(async () => { await act(async () => root.unmount()); vi.useRealTimers(); });
const render = (refreshKey: number, overrides: Partial<Parameters<typeof HomeTeammatesSection>[0]> = {}) => act(async () => root.render(el(HomeTeammatesSection, {
@@ -98,8 +100,8 @@ it('keeps cached teammates and offers a quiet header retry only for a lasting fa
h.cloudRefresh.mockClear();
await act(async () => byId('home.teammatesRetry')!.click());
expect(roster.refresh).toHaveBeenCalledTimes(1);
- expect(groups.refresh).toHaveBeenCalledTimes(1);
- expect(h.cloudRefresh).toHaveBeenCalledTimes(1);
+ expect(groups.refresh).not.toHaveBeenCalled();
+ expect(h.cloudRefresh).not.toHaveBeenCalled();
roster.error = null;
await render(0);
expect(byId('home.teammatesRetry')).toBeNull();
@@ -208,3 +210,26 @@ it('keeps a 50-companion strip quiet through ten refreshes and updates only the
await act(async () => byId('home.teammatesStrip.bot.host.bot17')!.click());
expect(h.openTeammate).toHaveBeenCalledExactlyOnceWith(latest[17]);
});
+
+// Integration: leaving the full home and mounting its sidebar used to collapse the
+// expanded roster and invalidate the retained scroll offset.
+it('keeps the expanded roster when the home presentation remounts', async () => {
+ const original = roster.items;
+ roster.items = Array.from({ length: 5 }, (_, index) => ({ ...item, key: String(index), item: { ...item.item, display: { title: `Teammate ${index}` } } }));
+ try {
+ await render(0);
+ await act(async () => byId('home.teammatesShowAll')!.click());
+ expect(node.querySelectorAll('[data-testid="row.bot"]')).toHaveLength(5);
+ await act(async () => root.unmount()); root = createRoot(node);
+ await render(0);
+ expect(node.querySelectorAll('[data-testid="row.bot"]')).toHaveLength(5);
+ } finally { roster.items = original; }
+});
+it('retries a cloud roster failure without restarting healthy computer or group lists', async () => {
+ roster.error = null; h.cloudError = 'CLOUD_ROSTER_FAILED';
+ await render(0); h.cloudRefresh.mockClear();
+ await act(async () => vi.advanceTimersByTimeAsync(CONNECTION_NOTICE_DELAY_MS));
+ await act(async () => byId('home.teammatesRetry')!.click());
+ expect(h.cloudRefresh).toHaveBeenCalledTimes(1);
+ expect(roster.refresh).not.toHaveBeenCalled(); expect(groups.refresh).not.toHaveBeenCalled();
+});
diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
index eec9f6a4d3..15074bb879 100644
--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx
@@ -9,13 +9,26 @@ const h = vi.hoisted(() => ({
legacy: { items: [] as any[], loading: false, refreshing: false, error: null as string | null, isOnline: vi.fn(() => false), refresh: vi.fn() },
targets: [] as { deviceId: string; deviceName: string }[],
disk: new Map<string, string>(),
+ history: new Map<string, string>(),
foreground: new Set<(state: string) => void>(),
}));
+vi.mock('@/session/historyDiskStoreExpo', () => ({ createHistoryDiskIO: () => ({
+ read: async (key: string) => h.history.get(key) ?? null,
+ write: async (key: string, value: string) => { h.history.set(key, value); },
+ remove: async (key: string) => { h.history.delete(key); },
+ files: async () => [...h.history.keys()],
+}) }));
vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(async (key: string) => h.disk.get(key) ?? null), setItem: vi.fn(async (key: string, value: string) => { h.disk.set(key, value); }), removeItem: vi.fn(async (key: string) => { h.disk.delete(key); }), getAllKeys: vi.fn(async () => [...h.disk.keys()]), multiRemove: vi.fn(async (keys: string[]) => { keys.forEach(key => h.disk.delete(key)); }) } }));
+vi.mock('@/session/mobileDurableOutbox', async () => {
+ const { createDurableOutbox } = await import('@/session/durableOutbox');
+ const { default: storage } = await import('@react-native-async-storage/async-storage');
+ return { mobileDurableOutbox: createDurableOutbox(storage) };
+});
vi.mock('expo-crypto', () => ({ randomUUID: () => 'fixture-operation-id' }));
vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: (_: string, fn: (state: string) => void) => { h.foreground.add(fn); return { remove: () => h.foreground.delete(fn) }; } } }));
vi.mock('expo-router', async () => { const { useEffect } = await import('react'); return { useFocusEffect: (fn: any) => useEffect(fn, [fn]) }; });
vi.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'en' } }) }));
+vi.mock('@/i18n', () => ({ default: { t: (key: string) => key } }));
vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));
vi.mock('@/config/env', () => ({ getActiveMobileSessionRealm: () => 'global', getMobileEndpointForRealm: () => 'https://chat.example.invalid', loadMobileEndpointsForRealm: vi.fn() }));
vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));
@@ -25,6 +38,15 @@ vi.mock('@/device-link/remoteStatus', () => ({ formatRemoteError: String }));
import { useBotGroupChat } from '@/session/useBotGroupChat';
import { useBotGroupRoster } from '@/session/useBotGroupRoster';
import { botGroupRoute } from '@/session/botGroupNavigation';
+import { mobileDurableOutbox } from '@/session/mobileDurableOutbox';
+import { createDurableOutbox } from '@/session/durableOutbox';
+import { enqueueChatMessage } from '@/chat/chatOutbox';
+import { createChatOutboxDelivery } from '@/chat/chatOutbox';
+import { createChatServerClient } from '@/chat/chatServerClient';
+import { forgetChatMessages } from '@/chat/chatMessageCache';
+import { getMobileAuthOwner, setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { clearHistoryDisk } from '@/session/remoteHistoryDiskCache';
+import { peekChatMessages } from '@/chat/chatMessageCache';
import { isRemoteResourceUnread, clearRemoteResourceCache, readCachedChatRoster } from '@/device-link/remoteResourceCache';
const id = '00000000-0000-4000-8000-000000000001';
const self = '00000000-0000-4000-8000-000000000002';
@@ -37,9 +59,19 @@ let chat: ReturnType<typeof useBotGroupChat>;
let showChat = false;
function Probe() { roster = useBotGroupRoster(h.targets, !showChat); chat = useBotGroupChat(host, showChat ? id : ''); return null; }
async function render() { root ??= createRoot(document.createElement('div')); await act(async () => root!.render(createElement(Probe))); }
+async function send(input: Record<string, unknown>) {
+ await chat.act('send', input);
+ const runner = createChatOutboxDelivery({ store: mobileDurableOutbox,
+ client: createChatServerClient((path, method = 'GET', body) => h.auth.apiFetch(`/v1${path}`, { method, body, baseUrl: 'https://chat.example.invalid', assertCurrent() {} })),
+ current: () => true, canRun: () => true, accessLost: forgetChatMessages });
+ await runner.run();
+}
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
beforeEach(async () => {
+ setMobileAuthOwner(null); peekChatMessages(id); await clearHistoryDisk();
await clearRemoteResourceCache(); h.auth.user.id = 'owner';
+ await mobileDurableOutbox.activate(''); h.disk.clear(); setMobileAuthOwner('owner');
+ await mobileDurableOutbox.activate(getMobileAuthOwner().accountKey);
vi.clearAllMocks(); h.foreground.clear(); showChat = false; h.auth.accountGeneration = 1; h.legacy.items = []; h.targets = []; h.legacy.isOnline.mockReturnValue(false);
vi.stubGlobal('WebSocket', class { close() {} });
h.auth.apiFetch.mockImplementation(async (path: string, options: any) => {
@@ -54,6 +86,39 @@ beforeEach(async () => {
throw new Error('Unexpected request');
});
});
+// Regression: entering a saved group must not depend on Chat Server latency.
+// Integration tier: real hook, real disk store, controlled native IO / HTTP.
+it('reopens saved history offline from memory and disk, and purges it after membership loss', async () => {
+ setMobileAuthOwner('owner'); showChat = true; await render();
+ expect(chat.state).toMatchObject({ kind: 'ready', group: { messages: [{ content: 'Fixture message' }] } });
+ await act(async () => { root!.unmount(); root = undefined; });
+ h.auth.apiFetch.mockImplementation(() => new Promise(() => {}));
+ await render();
+ expect(chat.state.kind).toBe('ready');
+ await act(async () => { root!.unmount(); root = undefined; });
+ // A new account generation drops the JS cache; the same account can still read its disk.
+ setMobileAuthOwner(null); peekChatMessages(id); setMobileAuthOwner('owner');
+ await render();
+ expect(chat.state).toMatchObject({ kind: 'ready', group: { messages: [{ content: 'Fixture message' }] } });
+ h.auth.apiFetch.mockRejectedValue({ status: 403 });
+ // Restart the mounted request too, since its earlier HTTP read intentionally never resolves.
+ await act(async () => { root!.unmount(); root = undefined; });
+ await render();
+ expect(chat.state.kind).toBe('missing');
+ await act(async () => { root!.unmount(); root = undefined; });
+ setMobileAuthOwner(null); peekChatMessages(id); setMobileAuthOwner('owner');
+ h.auth.apiFetch.mockImplementation(() => new Promise(() => {}));
+ await render();
+ expect(chat.state.kind).toBe('loading');
+});
+it('does not show one account\'s saved group to another account', async () => {
+ setMobileAuthOwner('owner'); showChat = true; await render();
+ await act(async () => { root!.unmount(); root = undefined; });
+ setMobileAuthOwner('other'); h.auth.user.id = 'other'; h.auth.accountGeneration++;
+ h.auth.apiFetch.mockImplementation(() => new Promise(() => {}));
+ await render();
+ expect(chat.state.kind).toBe('loading');
+});
afterEach(() => { act(() => root?.unmount()); root = undefined; vi.unstubAllGlobals(); vi.useRealTimers(); });
it('shows safe execution failures through the direct phone entry and removes them after retry', async () => {
const original = h.auth.apiFetch.getMockImplementation()!;
@@ -83,7 +148,7 @@ it('lists and opens an existing joined server group with all computers and the r
expect(chat.online).toBe(true);
expect(h.link.invoke).not.toHaveBeenCalled(); expect(h.link.openLink).not.toHaveBeenCalled();
expect(h.auth.apiFetch.mock.calls.every(([, options]) => options.baseUrl === 'https://chat.example.invalid')).toBe(true);
- await act(async () => { await chat.act('send', { text: 'hello', clientId: 'fixture-operation', mentions: { all: false, botIds: [] } }); });
+ await act(async () => { await send({ text: 'hello', clientId: 'fixture-operation', mentions: { all: false, botIds: [] } }); });
expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({ method: 'POST', body: { operationId: 'fixture-operation', content: [{ type: 'text', text: 'hello' }], mentions: [] } }));
});
// #6907: the hook must pass direct-room scope to the real client's quote projection (unit tier).
@@ -102,7 +167,7 @@ it('keeps the account owner label when quoting from a direct phone entry', async
});
showChat = true; await render();
expect(chat.state.kind).toBe('ready');
- await act(async () => { await chat.act('send', { text: 'Agreed', clientId: 'direct-quote-scope', quote: { messageId: self }, mentions: { all: false, botIds: [] } }); });
+ await act(async () => { await send({ text: 'Agreed', clientId: 'direct-quote-scope', quote: { messageId: self }, mentions: { all: false, botIds: [] } }); });
expect(h.auth.apiFetch).toHaveBeenCalledWith('/v1/conversations/' + id + '/messages', expect.objectContaining({ method: 'POST', body: expect.objectContaining({
mentions: [botId], content: [expect.objectContaining({ data: expect.objectContaining({ authorName: 'Companion X (Account B)' }) }), { type: 'text', text: 'Agreed' }],
}) }));
@@ -117,7 +182,7 @@ it('never includes the current human actor in explicit or everyone server mentio
});
showChat = true; await render();
for (const all of [false, true]) {
- await act(async () => { await chat.act('send', { text: 'hello', clientId: `fixture-${all}`, mentions: { all, botIds: [self, other] } }); });
+ await act(async () => { await send({ text: 'hello', clientId: `fixture-${all}`, mentions: { all, botIds: [self, other] } }); });
expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({ method: 'POST', body: { operationId: `fixture-${all}`, content: [{ type: 'text', text: 'hello' }], mentions: [other] } }));
}
});
@@ -163,7 +228,7 @@ it('resolves everyone using authorized members at send time instead of the displ
return original(path, options);
});
showChat = true; await render();
- await act(async () => { await chat.act('send', { text: 'everyone', clientId: 'fixture-new-member', mentions: { all: true, botIds: [] } }); });
+ await act(async () => { await send({ text: 'everyone', clientId: 'fixture-new-member', mentions: { all: true, botIds: [] } }); });
expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({ method: 'POST', body: { operationId: 'fixture-new-member', content: [{ type: 'text', text: 'everyone' }], mentions: [joined] } }));
});
@@ -185,8 +250,9 @@ it.each([
for (membership of ['left', 'removed', 'banned', 'invited', 'missing']) {
for (const botIds of [[target], [available, target]]) {
await act(async () => {
- await expect(chat.act('send', { text: '@Ann hello', clientId: 'fixture-stale-target', mentions: { all, botIds } }))
- .rejects.toThrow('MENTION_UNAVAILABLE');
+ await send({ text: '@Ann hello', clientId: 'fixture-stale-target', mentions: { all, botIds } });
+ expect(mobileDurableOutbox.getSnapshot()[0]).toMatchObject({ state: 'failed', error: 'MENTION_UNAVAILABLE' });
+ await mobileDurableOutbox.remove(mobileDurableOutbox.getSnapshot()[0]);
});
expect(chat.online).toBe(true);
expect(chat.state.kind).toBe('ready');
@@ -194,7 +260,7 @@ it.each([
}
}
await act(async () => {
- await chat.act('send', { text: '@Available hello', clientId: 'fixture-reselected', mentions: { all, botIds: [available] } });
+ await send({ text: '@Available hello', clientId: 'fixture-reselected', mentions: { all, botIds: [available] } });
});
expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({
method: 'POST', body: { operationId: 'fixture-reselected', content: [{ type: 'text', text: '@Available hello' }], mentions: [available] },
@@ -213,7 +279,7 @@ it('keeps REST sending available after the group WebSocket disconnects', async (
expect(chat.online).toBe(true);
await act(async () => { sockets[0].close(); });
expect(chat.online).toBe(true);
- await act(async () => { await chat.act('send', { text: 'REST works', clientId: 'fixture-ws-offline', mentions: { all: false, botIds: [] } }); });
+ await act(async () => { await send({ text: 'REST works', clientId: 'fixture-ws-offline', mentions: { all: false, botIds: [] } }); });
expect(h.auth.apiFetch).toHaveBeenCalledWith(`/v1/conversations/${id}/messages`, expect.objectContaining({ method: 'POST' }));
h.auth.apiFetch.mockRejectedValue(new Error('REST offline'));
await act(async () => { chat.reload(); });
@@ -229,11 +295,12 @@ it.each([403, 404])('clears revoked access immediately when a send returns %s',
return original(path, options);
});
await act(async () => {
- await expect(chat.act('send', { text: 'fixture', clientId: 'fixture-revoked', mentions: { all: false, botIds: [] } })).rejects.toMatchObject({ status });
+ await send({ text: 'fixture', clientId: 'fixture-revoked', mentions: { all: false, botIds: [] } });
+ expect(mobileDurableOutbox.getSnapshot()[0]).toMatchObject({ state: 'failed', suspended: true });
});
expect(chat.state.kind).toBe('missing');
expect(chat.online).toBe(false);
- await expect(chat.act('send', { text: 'again', clientId: 'fixture-no-page', mentions: { all: false, botIds: [] } })).rejects.toThrow('CHAT_READ_FAILED');
+ await expect(send({ text: 'again', clientId: 'fixture-no-page', mentions: { all: false, botIds: [] } })).rejects.toThrow('CHAT_READ_FAILED');
});
it.each([403, 404])('clears revoked access when attachment authorization returns %s', async (status) => {
showChat = true; await render();
@@ -264,7 +331,8 @@ it('clears access on everyone member-read rejection and ignores an older authori
});
await act(async () => { chat.reload(); });
await act(async () => {
- await expect(chat.act('send', { text: 'everyone', clientId: 'fixture-member-rejected', mentions: { all: true, botIds: [] } })).rejects.toMatchObject({ status: 403 });
+ await send({ text: 'everyone', clientId: 'fixture-member-rejected', mentions: { all: true, botIds: [] } });
+ expect(mobileDurableOutbox.getSnapshot()[0]).toMatchObject({ state: 'failed', suspended: true });
});
expect(chat.state.kind).toBe('missing');
expect(h.auth.apiFetch.mock.calls.some(([, options]) => options.method === 'POST')).toBe(false);
@@ -550,3 +618,30 @@ it.each(['missing', 'empty', 'read-error'] as const)('keeps initial loading corr
await act(async () => finish([]));
expect(roster.loading).toBe(false);
});
+
+// Integration: the actual ledger and HTTP adapter survive a process restart after
+// a committed POST loses its response. Existing direct-send tests cannot cover it.
+it('persists the exact uncertain send across restart and never rebuilds its recipients', async () => {
+ const storage = { getAllKeys: async () => [...h.disk.keys()], getItem: async (key: string) => h.disk.get(key) ?? null,
+ setItem: async (key: string, value: string) => { h.disk.set(key, value); }, removeItem: async (key: string) => { h.disk.delete(key); } };
+ const account = getMobileAuthOwner().accountKey;
+ let store = createDurableOutbox(storage); await store.activate(account);
+ await enqueueChatMessage(store, account, id, { clientId: 'lost-response', text: 'saved offline', mentions: { all: true, botIds: [] } }, 1);
+ expect(store.getSnapshot()[0]).toMatchObject({ state: 'queued', item: { text: 'saved offline' } });
+ const posted: unknown[] = [];
+ let memberReads = 0;
+ const client = createChatServerClient(async <T,>(path: string, method?: string, body?: unknown): Promise<T> => {
+ if (path === '/me') return { actor: { id: self, kind: 'human' } } as T;
+ if (path.endsWith('/members')) { memberReads++; return [{ id: self, state: 'joined' }, { id, state: 'joined' }] as T; }
+ if (method === 'POST') { posted.push(body); if (posted.length === 1) throw new Error('response lost'); return { id: self } as T; }
+ throw new Error('Unexpected request');
+ });
+ const delivery = () => createChatOutboxDelivery({ store, client, current: () => true, canRun: () => true, accessLost: async () => {} });
+ await delivery().run();
+ expect(store.getSnapshot()[0]).toMatchObject({ state: 'queued', enqueueStarted: true, chat: { body: { operationId: 'lost-response', mentions: [id] } } });
+ store = createDurableOutbox(storage); await store.activate(account);
+ await delivery().run();
+ expect(posted).toHaveLength(2); expect(posted[1]).toEqual(posted[0]); expect(memberReads).toBe(1);
+ expect(store.getSnapshot()[0]).toMatchObject({ state: 'confirming', chat: { messageId: self } });
+ await store.activate('other-account'); expect(store.getSnapshot()).toEqual([]);
+});
diff --git a/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx b/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx
index 641fab0ef7..3ce522b8c1 100644
--- a/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx
+++ b/apps/mobile/src/__tests__/cindyMakeSessionGate.test.tsx
@@ -8,6 +8,7 @@ import type { NewSessionCreationTask } from '@/session/newSessionCreation';
import type { MainWindowAction } from '@/components/MobilePrimitives';
const state = vi.hoisted(() => ({
+ cachedCompanion: false,
sessions: [] as Array<{ id: string; source?: string; deviceLinkDeviceId?: string }>,
listeners: new Set<() => void>(),
maker: { getSession: vi.fn() },
@@ -23,6 +24,8 @@ const state = vi.hoisted(() => ({
task: null as NewSessionCreationTask | null,
router: { canGoBack: vi.fn(() => true), back: vi.fn(), replace: vi.fn() },
}));
+vi.mock('@/session/useCachedCompanionSession', () => ({ useCachedCompanionSession: () => state.cachedCompanion ? { ref: { id: 'bot-a' } } : null }));
+vi.mock('@/device-link/remoteResourceCache', () => ({ forgetRemoteResource: vi.fn() }));
vi.mock('@/session/newSessionCreation', () => ({
useNewSessionCreationTask: () => state.task,
}));
@@ -78,7 +81,7 @@ let originalActEnvironment: boolean | undefined;
beforeEach(() => {
originalActEnvironment = reactActEnvironment.IS_REACT_ACT_ENVIRONMENT;
reactActEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
- state.sessions = [];
+ state.sessions = []; state.cachedCompanion = false;
state.maker.getSession.mockReset().mockResolvedValue(null);
state.openLink.mockReset().mockResolvedValue(undefined);
state.unsubscribe.mockReset().mockResolvedValue(undefined);
@@ -125,6 +128,27 @@ describe('mobile Cindy Make links', () => {
// Cold notification regression: the gate used to read before relay startup and
// permanently fail on a transient peer/metadata error. Existing tests only
// covered a ready relay and retries after a new connection epoch. Unit tier.
+ // Cached notification entry must paint history before its computer reconnects; unit tier.
+ it.each(['missing', 'ACCESS_REVOKED'])('mounts a saved companion chat during startup, then removes it on %s', async rejection => {
+ state.cachedCompanion = true;
+ state.status = 'stopped';
+ await renderGate();
+ expect(container.textContent).toBe('Composer');
+ expect(state.maker.getSession).not.toHaveBeenCalled();
+ state.status = 'online';
+ if (rejection === 'missing') state.maker.getSession.mockResolvedValue(null);
+ else state.maker.getSession.mockRejectedValue(Object.assign(new Error('revoked'), { code: rejection }));
+ await renderGate();
+ expect(container.textContent).toContain('session.entry.missing');
+ expect(container.textContent).not.toContain('Composer');
+ });
+
+ it('does not use a saved companion to open file routes before source verification', async () => {
+ state.cachedCompanion = true; state.status = 'stopped';
+ await act(async () => root.render(<CindyMakeSessionGate sessionId="new-task" deviceId="device-a"><Content /></CindyMakeSessionGate>));
+ expect(container.textContent).toContain('session.entry.loading');
+ });
+
it('waits for cold startup and recovers a transient metadata read in the same connection', async () => {
vi.useFakeTimers();
state.status = 'stopped';
@@ -228,7 +252,7 @@ describe('mobile Cindy Make links', () => {
state.openLink.mockRejectedValue(Object.assign(new Error(code), { code }));
await renderGate();
await act(async () => vi.advanceTimersByTimeAsync(SESSION_ENTRY_LOOKUP_TIMEOUT_MS));
- expect(container.textContent).toContain('session.entry.failed');
+ expect(container.textContent).toContain(code === 'ACCESS_REVOKED' ? 'session.entry.missing' : 'session.entry.failed');
expect(state.openLink).toHaveBeenCalledOnce();
expect(state.maker.getSession).not.toHaveBeenCalled();
});
@@ -352,7 +376,7 @@ describe('mobile Cindy Make links', () => {
expect(state.maker.getSession).not.toHaveBeenCalled();
const input = container.querySelector('input')!;
input.value = 'draft edited before reconnect';
- state.sessions = [];
+ state.sessions = []; state.cachedCompanion = false;
state.connectionEpoch += 1;
if (result === 'missing') state.maker.getSession.mockResolvedValue(null);
else if (result === 'failed') state.maker.getSession.mockRejectedValue(new Error('offline'));
@@ -368,7 +392,7 @@ describe('mobile Cindy Make links', () => {
state.sessions = [{ id: 'new-task', deviceLinkDeviceId: 'device-a', source: 'desktop' }];
await renderGate();
expect(container.textContent).toBe('Composer');
- state.sessions = [];
+ state.sessions = []; state.cachedCompanion = false;
if (changed === 'account') state.accountGeneration += 1;
state.maker.getSession.mockReturnValue(new Promise(() => {}));
await act(async () => root.render(
@@ -388,7 +412,7 @@ describe('mobile Cindy Make links', () => {
state.sessions = [{ id: 'new-task', deviceLinkDeviceId: 'device-a', source: 'cindy-make' }];
await renderGate();
expect(container.textContent).toBe('redirect:/');
- state.sessions = [];
+ state.sessions = []; state.cachedCompanion = false;
state.connectionEpoch += 1;
state.maker.getSession.mockReturnValue(new Promise(() => {}));
await renderGate();
diff --git a/apps/mobile/src/__tests__/useBotGroupChat.test.tsx b/apps/mobile/src/__tests__/useBotGroupChat.test.tsx
index 840cda39c4..c926bfd01b 100644
--- a/apps/mobile/src/__tests__/useBotGroupChat.test.tsx
+++ b/apps/mobile/src/__tests__/useBotGroupChat.test.tsx
@@ -4,6 +4,7 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
const h = vi.hoisted(() => ({
+ disk: new Map<string, unknown>(),
accountGeneration: 1, focused: true,
appState: { currentState: 'active', listeners: new Set<(state: string) => void>() },
listeners: new Set<(deviceId: string, payload: { collectionId: string; resourceRefs?: { id: string; kind: string; collectionId: string }[] }) => void>(),
@@ -20,6 +21,22 @@ vi.mock('expo-router', async () => { const { useEffect } = await import('react')
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'zh-CN' } }) }));
vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ user: { id: 'owner' }, accountGeneration: h.accountGeneration }) }));
vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));
+vi.mock('@/chat/useChatServer', () => ({ useChatServerGroup: () => ({ isListHidden: () => false, acceptListState: async () => {} }) }));
+vi.mock('@/auth/authOwnerGeneration', () => ({
+ getMobileAuthOwner: () => ({ accountId: 'owner', generation: h.accountGeneration }),
+ isMobileAuthOwnerCurrent: (owner: { generation: number }) => owner.generation === h.accountGeneration,
+}));
+vi.mock('@/session/remoteHistoryDiskCache', () => ({
+ historyDiskAuthority: (device: string, group: string) => {
+ const generation = h.accountGeneration;
+ return { key: `${generation}:${device}:${group}`, current: () => generation === h.accountGeneration };
+ },
+ readConversationDisk: async (authority: { key: string }, valid: (value: unknown) => boolean) => {
+ const value = h.disk.get(authority.key); return valid(value) ? value : null;
+ },
+ writeConversationDisk: async (authority: { key: string }, value: unknown) => { h.disk.set(authority.key, value); return true; },
+ clearHistoryDisk: async () => { h.disk.clear(); },
+}));
vi.mock('@/device-link/remoteStatus', async () => ({ formatRemoteError: (await import('@cindy/maker-shared/device-link-contract')).formatRemoteError }));
import { useBotGroupChat } from '@/session/useBotGroupChat';
@@ -47,7 +64,7 @@ async function push(payload: Parameters<typeof h.listeners extends Set<infer L>
}
beforeEach(() => {
- h.focused = true; h.accountGeneration = 1; h.appState.currentState = 'active'; h.appState.listeners.clear();
+ h.focused = true; h.accountGeneration++; h.disk.clear(); h.appState.currentState = 'active'; h.appState.listeners.clear();
vi.clearAllMocks(); h.listeners.clear(); h.link.status = 'online';
h.link.getPresenceAvailability.mockReturnValue(true);
h.link.onRemoteResourceChanged.mockImplementation((listener) => { h.listeners.add(listener); return () => h.listeners.delete(listener); });
@@ -77,6 +94,17 @@ it('reads the group with the chat primitive and follows its change pushes', asyn
expect(result.state).toMatchObject({ kind: 'ready', group: { name: '新名字' } });
});
+// Integration tier: reopen the real hook with an unavailable host; the saved
+// conversation must render before the pending remote read can settle.
+it('reopens a saved legacy group while the computer read remains pending', async () => {
+ await render();
+ expect(result.state).toMatchObject({ kind: 'ready', group: { name: '官网' } });
+ act(() => root?.unmount()); root = undefined;
+ h.link.invoke.mockReturnValue(new Promise(() => {}));
+ await render();
+ expect(result.state).toMatchObject({ kind: 'ready', group: { name: '官网' } });
+});
+
it('keeps the conversation on a failed re-read, and reports a missing group', async () => {
await render();
h.link.invoke.mockRejectedValue(new Error('[NOT_CONNECTED] offline'));
diff --git a/apps/mobile/src/__tests__/useCloudCompanion.test.tsx b/apps/mobile/src/__tests__/useCloudCompanion.test.tsx
index 2a600eae68..cfa26e4674 100644
--- a/apps/mobile/src/__tests__/useCloudCompanion.test.tsx
+++ b/apps/mobile/src/__tests__/useCloudCompanion.test.tsx
@@ -6,7 +6,15 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';
const h = vi.hoisted(() => ({
owner: 'owner:1:global', current: true, readDeviceList: vi.fn(),
capabilities: vi.fn(), actors: vi.fn(),
+ disk: new Map<string, string>(),
}));
+vi.mock('@react-native-async-storage/async-storage', () => ({ default: {
+ getItem: async (key: string) => h.disk.get(key) ?? null,
+ setItem: async (key: string, value: string) => { h.disk.set(key, value); },
+ removeItem: async (key: string) => { h.disk.delete(key); },
+ getAllKeys: async () => [...h.disk.keys()],
+ multiRemove: async (keys: string[]) => { keys.forEach(key => h.disk.delete(key)); },
+} }));
vi.mock('react-native', () => ({ AppState: { addEventListener: () => ({ remove() {} }) } }));
vi.mock('expo-router', async () => {
const { useEffect } = await import('react');
@@ -15,10 +23,12 @@ vi.mock('expo-router', async () => {
vi.mock('@/chat/useChatServer', async () => {
const { useMemo } = await import('react');
return { useChatClient: () => useMemo(() => ({ owner: h.owner, enabled: true,
+ userId: h.owner.split(':')[0], realm: h.owner.split(':')[2],
current: () => h.current, client: { capabilities: h.capabilities, actors: h.actors } }), [h.owner]) };
});
vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ readDeviceList: h.readDeviceList }) }));
import { useCloudCompanionHome } from '@/chat/useCloudCompanion';
+import { clearRemoteResourceCache } from '@/device-link/remoteResourceCache';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root;
@@ -26,7 +36,8 @@ let result: ReturnType<typeof useCloudCompanionHome>;
function Probe() { result = useCloudCompanionHome(true); return null; }
const render = () => act(async () => root.render(createElement(Probe)));
const actor = { id: 'actor', kind: 'bot', externalId: 'writer', name: 'Writer', avatar: null, homeDeviceId: 'studio' };
-beforeEach(() => {
+beforeEach(async () => {
+ await clearRemoteResourceCache();
vi.resetAllMocks(); h.owner = 'owner:1:global'; h.current = true;
h.capabilities.mockResolvedValue({ companionHome: true }); h.actors.mockResolvedValue([actor]);
h.readDeviceList.mockResolvedValue({ devices: [{ deviceId: 'studio', name: 'Mac Studio' }] });
@@ -34,6 +45,24 @@ beforeEach(() => {
});
afterEach(() => act(() => root.unmount()));
+it('keeps the whole cloud roster on remount while HTTP and the optional directory are unavailable', async () => {
+ await render();
+ expect(result.actors).toEqual([actor]);
+ act(() => root.unmount()); root = createRoot(document.createElement('div'));
+ h.capabilities.mockImplementation(() => new Promise(() => {}));
+ await render();
+ expect(result.supported).toBe(true);
+ expect(result.actors).toEqual([actor]);
+ expect(result.deviceNames.get('studio')).toBe('Mac Studio');
+});
+
+it('publishes the companion roster before a slow optional computer-name request completes', async () => {
+ h.readDeviceList.mockImplementation(() => new Promise(() => {}));
+ await render();
+ expect(result.actors).toEqual([actor]);
+ expect(result.error).toBeNull();
+});
+
// Tier: behavior. A successful actor refresh plus a failed optional directory read
// previously replaced a known computer name with its ID. Pure row tests miss this
// async failure path; drive the actual hook and its account fence.
diff --git a/apps/mobile/src/__tests__/useCloudCompanionRoom.test.tsx b/apps/mobile/src/__tests__/useCloudCompanionRoom.test.tsx
index 0cfe2846be..8d10b50acb 100644
--- a/apps/mobile/src/__tests__/useCloudCompanionRoom.test.tsx
+++ b/apps/mobile/src/__tests__/useCloudCompanionRoom.test.tsx
@@ -3,7 +3,13 @@ import { act, createElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
-const h = vi.hoisted(() => ({ owner: 'owner:1:global', current: true, companionRoom: vi.fn(), history: vi.fn(), media: vi.fn() }));
+const h = vi.hoisted(() => ({ owner: 'owner:1:global', current: true, companionRoom: vi.fn(), history: vi.fn(), media: vi.fn(), disk: new Map<string, string>() }));
+vi.mock('@/session/historyDiskStoreExpo', () => ({ createHistoryDiskIO: () => ({
+ read: async (key: string) => h.disk.get(key) ?? null,
+ write: async (key: string, value: string) => { h.disk.set(key, value); },
+ remove: async (key: string) => { h.disk.delete(key); }, files: async () => [...h.disk.keys()],
+}) }));
+vi.mock('@/config/env', () => ({ getActiveMobileSessionRealm: () => 'global' }));
vi.mock('react-native', () => ({ AppState: { addEventListener: () => ({ remove() {} }) } }));
vi.mock('expo-crypto', () => ({ digestStringAsync: vi.fn(async () => 'hash'), CryptoDigestAlgorithm: { SHA256: 'SHA-256' }, CryptoEncoding: { HEX: 'hex' } }));
vi.mock('expo-router', async () => {
@@ -15,6 +21,9 @@ vi.mock('@/chat/useChatServer', async () => {
return { useChatClient: () => useMemo(() => ({ owner: h.owner, enabled: true, current: () => h.current,
client: { companionRoom: h.companionRoom, history: h.history, media: h.media } }), [h.owner]) };
});
+import { setMobileAuthOwner } from '@/auth/authOwnerGeneration';
+import { clearHistoryDisk } from '@/session/remoteHistoryDiskCache';
+import { peekCloudConversation } from '@/chat/cloudConversationCache';
import { useCloudCompanionRoom } from '@/chat/useCloudCompanionRoom';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
@@ -24,7 +33,8 @@ let root: Root;
let result: ReturnType<typeof useCloudCompanionRoom>;
function Probe() { result = useCloudCompanionRoom('actor', 'Writer', true); return null; }
const render = () => act(async () => root.render(createElement(Probe)));
-beforeEach(() => {
+beforeEach(async () => {
+ setMobileAuthOwner(null); peekCloudConversation('actor'); await clearHistoryDisk(); setMobileAuthOwner('owner');
vi.resetAllMocks(); h.owner = 'owner:1:global'; h.current = true;
h.companionRoom.mockResolvedValue(ROOM); h.history.mockResolvedValue({ messages: [], before: null });
root = createRoot(document.createElement('div'));
@@ -53,3 +63,19 @@ it('has no address to fetch before the room is known', async () => {
await expect(result.media(MEDIA)).rejects.toThrow('OWNER_CHANGED');
expect(h.media).not.toHaveBeenCalled();
});
+
+// Integration: the cloud-only route must hydrate before resolving the companion room.
+// Existing coverage tested signed attachment access but never reopened this route offline.
+it('restores a saved cloud transcript across remount and process-cache loss, then purges revoked access', async () => {
+ const message = { id: 'message', seq: '1', authorId: 'actor', author: { name: 'Writer', kind: 'bot' }, content: [{ type: 'text', text: 'Saved reply' }] };
+ h.history.mockResolvedValue({ messages: [message], before: null });
+ await render(); expect(result.messages).toEqual([message]);
+ await act(async () => root.unmount());
+ setMobileAuthOwner(null); peekCloudConversation('actor'); setMobileAuthOwner('owner');
+ h.companionRoom.mockImplementation(() => new Promise(() => {}));
+ root = createRoot(document.createElement('div')); await render();
+ expect(result.status).toBe('ready'); expect(result.messages).toEqual([message]);
+ h.history.mockRejectedValue({ status: 403 });
+ await act(async () => result.reload());
+ expect(result.messages).toEqual([]); expect(peekCloudConversation('actor')).toBeNull();
+});
diff --git a/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx b/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx
index 59a49faf89..f568f0b029 100644
--- a/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx
+++ b/apps/mobile/src/__tests__/useRemoteResourceList.test.tsx
@@ -22,6 +22,7 @@ vi.mock('@/device-link/remoteStatus', async () => ({ ...await vi.importActual<ty
vi.mock('@/device-link/focusedTopicSubscription', () => ({ startFocusedTopicSubscription: () => () => {} }));
vi.mock('@/device-link/remoteResourceCache', () => ({
readRemoteResourceSnapshot: h.snapshot, cacheRemoteResourceItems: h.persist,
+ peekRemoteResourceSnapshot: () => undefined,
subscribeRemoteResourceCache: () => () => {}, remoteResourceCacheRevision: () => 0,
}));
vi.mock('@/device-link/remoteResourceAvailability', async (original) => ({
@@ -47,6 +48,18 @@ beforeEach(() => {
});
afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });
describe('shared real resource list', () => {
+ it('fills a slow disk shard after another computer replied, without reviving its deleted rows', async () => {
+ vi.useFakeTimers();
+ let finish!: (snapshot: unknown) => void;
+ h.snapshot.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ h.list.mockImplementation(async (_invoke, host) => host.deviceId === 'mac'
+ ? { items: [] } : new Promise(() => {}));
+ await render();
+ await act(async () => vi.advanceTimersByTimeAsync(2000));
+ await act(async () => finish({ home: [], items: { teammates: [cached(targets[0], 'deleted'), cached(targets[1], 'saved-pc')] }, read: {} }));
+ expect(result.items.map(row => row.item.ref.id)).toEqual(['saved-pc']);
+ expect(result.isOnline(targets[1])).toBe(false);
+ });
// Regression: one sleeping computer raised a section-wide warning on a healthy phone.
// Unit: real roster hook, cached offline shard + a successful online shard.
it('keeps known offline computers without reporting a failed refresh and reads them on return', async () => {
diff --git a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx
index 7c952f7afd..f3e41179a2 100644
--- a/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx
+++ b/apps/mobile/src/__tests__/useRemoteResourceSession.test.tsx
@@ -13,12 +13,13 @@ const h = vi.hoisted(() => ({
language: "en", focused: true,
t: (key: string) => key, metadataVerified: true,
resourceId: 'bot-1', sessionId: 'task-1', openSearch: '', resourceHistorySessionId: '',
- markRead: vi.fn(),
+ markRead: vi.fn(), forget: vi.fn(),
store: { getSessionDeviceId: vi.fn(), upsertDeviceSession: vi.fn() },
router: { replace: vi.fn(), setParams: vi.fn() },
auth: { user: { id: 'owner' }, accountGeneration: 1 },
link: { openLink: vi.fn(), invoke: vi.fn(), connectionEpoch: 1, status: 'online', onRemoteResourceChanged: vi.fn(() => () => {}), subscribe: vi.fn(), unsubscribe: vi.fn() },
}));
+vi.mock('@/session/useCachedCompanionSession', () => ({ useCachedCompanionSession: () => null }));
vi.mock('@/i18n', () => ({ i18n: { t: (key: string) => key } }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: h.t, i18n: { language: h.language } }) }));
vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) } }));
@@ -35,7 +36,7 @@ vi.mock('@/auth/AuthContext', () => ({ useAuth: () => h.auth }));
vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => h.link }));
vi.mock('@/device-link/remoteStatus', async () => ({ ...await vi.importActual<typeof import('@/device-link/remoteStatus')>('@/device-link/remoteStatus'), formatRemoteError: String }));
vi.mock('@/device-link/remoteResources', () => ({ getRemoteResource: h.get }));
-vi.mock('@/device-link/remoteResourceCache', () => ({ markRemoteResourceRead: h.markRead }));
+vi.mock('@/device-link/remoteResourceCache', () => ({ markRemoteResourceRead: h.markRead, forgetRemoteResource: h.forget }));
vi.mock('@/device-link/focusedTopicSubscription', () => ({ startFocusedTopicSubscription: () => () => {} }));
vi.mock('@/session/remoteSessionStore', () => ({ remoteSessionStore: h.store }));
import { useRemoteResourceSession } from '@/session/useRemoteResourceSession';
@@ -126,17 +127,21 @@ describe('companion task visibility refresh', () => {
expect(h.router.setParams).toHaveBeenCalledWith({ sessionId: 'task-2' });
expect(h.markRead).not.toHaveBeenCalled();
});
- it.each([Object.assign(new Error('gone'), { code: 'NOT_FOUND' }), new Error('[NOT_FOUND] resource missing')])('leaves the cached task when the host rejects the resource', async (error) => {
+ // Persisted notification identities must not reopen a task after an explicit access rejection (unit).
+ it.each([Object.assign(new Error('gone'), { code: 'NOT_FOUND' }), new Error('[NOT_FOUND] resource missing'),
+ Object.assign(new Error('revoked'), { code: 'ACCESS_REVOKED' }), new Error('[PERMISSION_DENIED] resource revoked')])('leaves the cached task when the host rejects the resource', async (error) => {
h.get.mockRejectedValue(error);
await render();
expect(h.router.replace).toHaveBeenCalledWith({ pathname: '/resources/[collectionId]/[resourceId]', params: {
collectionId: 'teammates', resourceId: 'bot-1', resourceKind: 'bot', deviceId: 'mac', deviceName: 'My Mac',
} });
+ expect(h.forget).toHaveBeenCalledWith('owner', 'bot-1');
});
it('retains recovery for a transient connection failure', async () => {
h.get.mockRejectedValue(new Error('NOT_CONNECTED'));
await render();
expect(h.router.replace).not.toHaveBeenCalled();
+ expect(h.forget).not.toHaveBeenCalled();
});
it('ignores a visibility rejection belonging to the previous account', async () => {
let reject!: (error: Error) => void;
diff --git a/apps/mobile/src/chat/chatMessageCache.ts b/apps/mobile/src/chat/chatMessageCache.ts
new file mode 100644
index 0000000000..d80b8cc277
--- /dev/null
+++ b/apps/mobile/src/chat/chatMessageCache.ts
@@ -0,0 +1,65 @@
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { clearConversationDisk, historyDiskAuthority, readConversationDisk, writeConversationDisk } from '@/session/remoteHistoryDiskCache';
+import type { ChatActor, ChatPage } from './chatServerClient';
+
+export interface CachedChatPage { version: 1; page: ChatPage; self: string; actors: ChatActor[] }
+const device = 'chat-server';
+let owner = getMobileAuthOwner();
+const memory = new Map<string, CachedChatPage>();
+const revisions = new Map<string, number>();
+const invalidated = new Set<(roomId: string) => void>();
+export function subscribeChatInvalidation(listener: (roomId: string) => void) {
+ invalidated.add(listener); return () => { invalidated.delete(listener); };
+}
+function own() {
+ if (!isMobileAuthOwnerCurrent(owner)) { owner = getMobileAuthOwner(); memory.clear(); revisions.clear(); }
+}
+const keyFor = (roomId: string, threadRootId?: string) => JSON.stringify([roomId, threadRootId ?? null]);
+function valid(value: unknown): value is CachedChatPage {
+ const entry = value as CachedChatPage | null;
+ return entry?.version === 1 && typeof entry.self === 'string' && Array.isArray(entry.actors)
+ && entry.actors.every(actor => actor && typeof actor.id === 'string')
+ && typeof entry.page?.snapshot?.room?.id === 'string' && typeof entry.page.snapshot.room.name === 'string'
+ && Array.isArray(entry.page.snapshot.members) && entry.page.snapshot.members.every(member => member
+ && typeof member.id === 'string' && typeof member.name === 'string' && typeof member.state === 'string')
+ && (entry.page.before === null || typeof entry.page.before === 'string')
+ && Array.isArray(entry.page.messages) && entry.page.messages.every(message => message
+ && typeof message.id === 'string' && /^\d{1,30}$/.test(message.seq) && typeof message.authorId === 'string'
+ && typeof message.author?.kind === 'string' && typeof message.author.name === 'string'
+ && Array.isArray(message.content) && message.content.every(block => block && typeof block.type === 'string'));
+}
+export function peekChatMessages(roomId: string, threadRootId?: string): CachedChatPage | null {
+ own(); return owner.accountId ? memory.get(keyFor(roomId, threadRootId)) ?? null : null;
+}
+export async function readChatMessages(roomId: string, threadRootId?: string): Promise<CachedChatPage | null> {
+ own();
+ const key = keyFor(roomId, threadRootId);
+ if (memory.has(key)) return memory.get(key)!;
+ const revision = revisions.get(key) ?? 0;
+ revisions.set(key, revision);
+ const authority = historyDiskAuthority(device, key);
+ const value = await readConversationDisk(authority, valid);
+ if (!authority.current() || revision !== (revisions.get(key) ?? 0)) return null;
+ if (value && value.page.snapshot.room.id === roomId && value.page.threadRootId === threadRootId) memory.set(key, value);
+ return peekChatMessages(roomId, threadRootId);
+}
+export async function cacheChatMessages(roomId: string, value: CachedChatPage): Promise<boolean> {
+ own();
+ const key = keyFor(roomId, value.page.threadRootId);
+ const authority = historyDiskAuthority(device, key);
+ if (!authority.current()) return false;
+ revisions.set(key, (revisions.get(key) ?? 0) + 1);
+ memory.set(key, value);
+ return writeConversationDisk(authority, value);
+}
+/** Membership loss clears every opened thread too, and invalidates delayed hydration. */
+export async function forgetChatMessages(roomId: string): Promise<void> {
+ own();
+ const keys = new Set([...memory.keys(), ...revisions.keys(), keyFor(roomId)]);
+ for (const key of keys) {
+ if (JSON.parse(key)[0] !== roomId) continue;
+ revisions.set(key, (revisions.get(key) ?? 0) + 1); memory.delete(key);
+ }
+ invalidated.forEach(listener => listener(roomId));
+ await clearConversationDisk(roomId);
+}
diff --git a/apps/mobile/src/chat/chatOutbox.ts b/apps/mobile/src/chat/chatOutbox.ts
new file mode 100644
index 0000000000..96320e306a
--- /dev/null
+++ b/apps/mobile/src/chat/chatOutbox.ts
@@ -0,0 +1,117 @@
+import type { BotGroupMessageView, BotGroupQuoteView } from '@cindy/maker-shared/botGroupChat';
+import type { DurableOutboxRecord, DurableOutboxStore } from '@/session/durableOutbox';
+import { buildOutboxItem } from '@/session/sessionOutbox';
+import { chatAccessLost, type ChatSendInput, type createChatServerClient } from './chatServerClient';
+import { cacheChatMessages, peekChatMessages } from './chatMessageCache';
+
+export async function enqueueChatMessage(store: DurableOutboxStore, accountId: string, roomId: string,
+ input: ChatSendInput, after: number, quote?: BotGroupQuoteView, afterServerSequence?: string): Promise<void> {
+ if (!accountId || store.getAccountId() !== accountId) throw new Error('OUTBOX_OWNER_CHANGED');
+ await store.add({ version: 1, accountId, deviceId: '', createdAt: Date.now(), state: 'queued', uploads: [],
+ enqueueStarted: false, chat: { roomId, input, after, afterServerSequence, ...(quote ? { quote } : {}) },
+ item: buildOutboxItem({ clientId: input.clientId, sessionId: roomId, text: input.text,
+ permissionModeAtSend: 'default', readyAttachments: [], claimedUploads: [] }) });
+}
+
+export function pendingChatMessage(record: DurableOutboxRecord): BotGroupMessageView {
+ return { id: `local:${record.item.clientId}`, sequence: record.chat!.after, kind: 'message',
+ authorKind: 'user', authorBotId: null, authorName: '', isSelf: true,
+ content: record.chat!.input.text, mentions: record.chat!.input.mentions,
+ quote: record.chat!.quote, threadRootId: record.chat!.input.threadRootId,
+ noticeCode: null, planId: null, files: [], attachments: [], createdAt: record.createdAt };
+}
+
+/** Remove a receipt only after its canonical message is durable on this phone. */
+export async function settleChatOutbox(store: DurableOutboxStore, roomId: string, messageIds: ReadonlySet<string>) {
+ for (const row of store.getSnapshot()) {
+ if (row.chat?.roomId === roomId && row.chat.messageId && messageIds.has(row.chat.messageId)) await store.remove(row);
+ }
+}
+
+/** A later rejoin must not silently send drafts written before access was removed. */
+export async function suspendChatOutbox(store: DurableOutboxStore, roomId: string) {
+ for (const row of store.getSnapshot()) {
+ if (row.chat?.roomId === roomId && !row.suspended) {
+ await store.update(row, { state: 'failed', suspended: true, error: 'CONVERSATION_NOT_FOUND' });
+ }
+ }
+}
+
+/** One account runner; uses the existing durable ledger, never the computer/session transport. */
+export function createChatOutboxDelivery(deps: {
+ store: DurableOutboxStore; client: ReturnType<typeof createChatServerClient>;
+ current(): boolean; canRun(): boolean; accessLost(roomId: string): Promise<void>;
+}) {
+ let running: Promise<void> | undefined;
+ const { store, client } = deps;
+ const current = (row: DurableOutboxRecord) => deps.current() && store.getAccountId() === row.accountId
+ && store.getSnapshot().includes(row);
+ const run = async () => {
+ const blocked = new Set<string>();
+ for (let row of store.getSnapshot()) {
+ if (!deps.canRun() || !deps.current()) return;
+ if (!row.chat || !current(row)) continue;
+ const room = row.chat.roomId;
+ if (blocked.has(room)) continue;
+ if (row.suspended || row.state === 'failed') { blocked.add(room); continue; }
+ const guard = () => {
+ if (!current(row) || !deps.canRun()) throw new Error('OUTBOX_OWNER_CHANGED');
+ if (client.personalList.hidden(room)) throw Object.assign(new Error('CONVERSATION_NOT_FOUND'), { status: 404 });
+ };
+ try {
+ await client.syncListState(); guard();
+ if (client.personalList.hidden(room)) {
+ row = await store.update(row, { state: 'failed', suspended: true, error: 'CONVERSATION_NOT_FOUND' });
+ blocked.add(room); await deps.accessLost(room); continue;
+ }
+ if (row.chat!.messageId) {
+ const previous = peekChatMessages(room, row.chat!.input.threadRootId);
+ const oldest = previous?.page.messages.reduce<string | undefined>((seq, message) => !seq || BigInt(message.seq) < BigInt(seq) ? message.seq : seq, undefined)
+ ?? row.chat!.afterServerSequence;
+ const [page, self, actors] = await Promise.all([client.load(room, oldest, row.chat!.input.threadRootId), client.me(), client.actors().catch(() => [])]);
+ guard();
+ if (await cacheChatMessages(room, { version: 1, page, self, actors })) {
+ guard(); await settleChatOutbox(store, room, new Set(page.messages.map(message => message.id)));
+ }
+ continue;
+ }
+ let input = row.chat!.input;
+ if (!row.chat!.body) {
+ const [members, self] = await Promise.all([client.members(room), client.me()]); guard();
+ const joined = members.filter(member => member.state === 'joined');
+ if (input.mentions.botIds.some(id => !joined.some(member => member.id === id))) throw new Error('MENTION_UNAVAILABLE');
+ const recipients = input.mentions.all ? joined.map(member => member.id) : input.mentions.botIds;
+ input = { ...input, mentions: { all: false, botIds: [...new Set(recipients.filter(id => id !== self))] } };
+ }
+ row = await store.update(row, { state: 'sending', error: undefined }); guard();
+ const receipt = await client.send(room, input, { body: row.chat!.body, save: async body => {
+ guard(); row = await store.update(row, { chat: { ...row.chat!, body }, enqueueStarted: true }); guard();
+ } });
+ guard();
+ if (!receipt || typeof receipt.id !== 'string' || !receipt.id) throw new Error('INVALID_CHAT_RECEIPT');
+ // Keep the receipt until a durable history page contains the actual message.
+ // This closes the restart gap between POST success and the next history read.
+ await store.update(row, { state: 'confirming', chat: { ...row.chat!, messageId: receipt.id } });
+ } catch (error) {
+ if (!current(row) || !deps.current()) return;
+ const status = (error as { status?: number })?.status;
+ const message = error instanceof Error ? error.message : 'CHAT_SEND_FAILED';
+ const refused = (status !== undefined && status >= 400 && status < 500 && ![401, 408, 429].includes(status))
+ || ['MENTION_UNAVAILABLE', 'QUOTE_UNAVAILABLE'].includes(message);
+ blocked.add(room);
+ try {
+ await store.update(row, { state: refused ? 'failed' : 'queued', error: message,
+ ...(chatAccessLost(error) ? { suspended: true } : {}) });
+ if (chatAccessLost(error)) {
+ await suspendChatOutbox(store, room);
+ await deps.accessLost(room);
+ }
+ } catch { /* A failed disk write retains the last committed intent for the next foreground retry. */ }
+ }
+ }
+ };
+ return { run: () => {
+ if (!running) running = run().finally(() => { running = undefined; });
+ return running;
+ } };
+}
diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.ts
index 90a0d6658b..1435afeecd 100644
--- a/apps/mobile/src/chat/chatServerClient.ts
+++ b/apps/mobile/src/chat/chatServerClient.ts
@@ -50,6 +50,15 @@ export function chatGroupManager(snapshot: ChatSnapshot, self: string) {
return managers.find(member => member.role === 'owner') ?? managers.find(member => member.id === self) ?? managers[0];
}
+export interface ChatSendInput {
+ conversationKind?: 'direct';
+ clientId: string; text: string; mentions: { all: boolean; botIds: string[] };
+ quote?: { messageId: string }; threadRootId?: string;
+}
+export interface ChatSendBody {
+ operationId: string; content: ChatMessage['content']; mentions: string[]; threadRootId?: string;
+}
+
export function chatId(value: string): string {
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw new Error('INVALID_CHAT_ID');
return value;
@@ -450,7 +459,11 @@ export function createChatServerClient(request: ChatRequest, personalList = crea
if (current) { if (BigInt(readSeq) > BigInt(current.read_seq)) current.read_seq = readSeq; }
else page.snapshot.reads.push({ thread_key: key, read_seq: readSeq });
},
- async send(roomId: string, input: { conversationKind?: 'direct'; clientId: string; text: string; mentions: { all: boolean; botIds: string[] }; quote?: { messageId: string }; threadRootId?: string }) {
+ async send(roomId: string, input: ChatSendInput, durable?: {
+ body?: ChatSendBody;
+ save(body: ChatSendBody): Promise<void>;
+ }) {
+ if (durable?.body) return request<ChatMessage>(`/conversations/${chatId(roomId)}/messages`, 'POST', durable.body);
const key = JSON.stringify([roomId, input.clientId, input.text, input.mentions, input.quote?.messageId, input.threadRootId]);
const known = input.quote ? postedQuotes.get(key) : undefined;
const content: ChatMessage['content'] = known?.content ?? [{ type: 'text', text: input.text }];
@@ -475,8 +488,12 @@ export function createChatServerClient(request: ChatRequest, personalList = crea
if (postedQuotes.size > 128) postedQuotes.delete(postedQuotes.keys().next().value!);
}
try {
- const result = await request(`/conversations/${chatId(roomId)}/messages`, 'POST', { operationId: input.clientId,
- content, mentions: [...mentions], ...(input.threadRootId ? { threadRootId: chatId(input.threadRootId) } : {}) });
+ const body: ChatSendBody = { operationId: input.clientId,
+ content, mentions: [...mentions], ...(input.threadRootId ? { threadRootId: chatId(input.threadRootId) } : {}) };
+ // The exact body is durable before POST. A lost response/restart must not
+ // rebuild its quote or recipients under the same operationId.
+ await durable?.save(body);
+ const result = await request<ChatMessage>(`/conversations/${chatId(roomId)}/messages`, 'POST', body);
postedQuotes.delete(key);
return result;
} catch (error) {
diff --git a/apps/mobile/src/chat/cloudConversationCache.ts b/apps/mobile/src/chat/cloudConversationCache.ts
new file mode 100644
index 0000000000..39cae8c3be
--- /dev/null
+++ b/apps/mobile/src/chat/cloudConversationCache.ts
@@ -0,0 +1,41 @@
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { clearHistoryDisk, historyDiskAuthority, readConversationDisk, writeConversationDisk } from '@/session/remoteHistoryDiskCache';
+import type { ChatMessage } from './chatServerClient';
+
+export interface CachedCloudConversation { roomId: string; messages: ChatMessage[]; before: string | null }
+const namespace = 'cloud-companion';
+let owner = getMobileAuthOwner();
+const pages = new Map<string, CachedCloudConversation>();
+const invalidated = new Set<(actorId: string) => void>();
+export function subscribeCloudConversationInvalidation(listener: (actorId: string) => void) {
+ invalidated.add(listener); return () => { invalidated.delete(listener); };
+}
+function own() { if (!isMobileAuthOwnerCurrent(owner)) { owner = getMobileAuthOwner(); pages.clear(); } }
+export function peekCloudConversation(actorId: string) { own(); return owner.accountId ? pages.get(actorId) ?? null : null; }
+export async function readCloudConversation(actorId: string) {
+ own();
+ const cached = peekCloudConversation(actorId);
+ if (cached) return cached;
+ const authority = historyDiskAuthority(namespace, actorId);
+ const saved = await readConversationDisk(authority, (value): value is CachedCloudConversation => {
+ const page = value as CachedCloudConversation | null;
+ return !!page && typeof page.roomId === 'string' && (page.before === null || typeof page.before === 'string')
+ && Array.isArray(page.messages) && page.messages.every(message => message && typeof message.id === 'string'
+ && /^\d{1,30}$/.test(message.seq) && typeof message.authorId === 'string' && !!message.author
+ && typeof message.author.name === 'string' && Array.isArray(message.content));
+ });
+ if (saved && authority.current() && !pages.has(actorId)) pages.set(actorId, saved);
+ return authority.current() ? peekCloudConversation(actorId) : null;
+}
+export async function cacheCloudConversation(actorId: string, page: CachedCloudConversation) {
+ own();
+ const authority = historyDiskAuthority(namespace, actorId);
+ if (!authority.current()) return;
+ pages.set(actorId, page);
+ await writeConversationDisk(authority, page);
+}
+export function forgetCloudConversation(actorId: string) {
+ own(); pages.delete(actorId);
+ invalidated.forEach(listener => listener(actorId));
+ return clearHistoryDisk(namespace, actorId);
+}
diff --git a/apps/mobile/src/chat/useChatOutboxDelivery.ts b/apps/mobile/src/chat/useChatOutboxDelivery.ts
new file mode 100644
index 0000000000..52426051c7
--- /dev/null
+++ b/apps/mobile/src/chat/useChatOutboxDelivery.ts
@@ -0,0 +1,35 @@
+import { useEffect } from 'react';
+import { AppState } from 'react-native';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { mobileDurableOutbox } from '@/session/mobileDurableOutbox';
+import { forgetRemoteResource } from '@/device-link/remoteResourceCache';
+import { createChatOutboxDelivery, suspendChatOutbox } from './chatOutbox';
+import { forgetChatMessages, subscribeChatInvalidation } from './chatMessageCache';
+import { useChatClient } from './useChatServer';
+
+/** Mounted with MobileOutboxBridge so leaving a group does not stop its saved sends. */
+export function useChatOutboxDelivery(accountId: string) {
+ const api = useChatClient();
+ useEffect(() => {
+ if (!accountId || !api.enabled) return;
+ const owner = getMobileAuthOwner();
+ let active = true;
+ const current = () => active && api.current() && isMobileAuthOwnerCurrent(owner)
+ && owner.accountKey === accountId && owner.accountId === api.userId;
+ const runner = createChatOutboxDelivery({ store: mobileDurableOutbox, client: api.client, current,
+ canRun: () => AppState.currentState === 'active',
+ accessLost: async roomId => {
+ if (!current()) return;
+ await Promise.all([forgetChatMessages(roomId), forgetRemoteResource(api.userId, roomId)]);
+ } });
+ const run = () => { if (current()) void runner.run().catch(() => undefined); };
+ const off = mobileDurableOutbox.subscribe(run);
+ const offInvalidation = subscribeChatInvalidation(roomId => {
+ if (current()) void suspendChatOutbox(mobileDurableOutbox, roomId).catch(() => undefined);
+ });
+ const timer = setInterval(run, 5_000);
+ const app = AppState.addEventListener('change', state => { if (state === 'active') run(); });
+ run();
+ return () => { active = false; off(); offInvalidation(); clearInterval(timer); app.remove(); };
+ }, [accountId, api]);
+}
diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.ts
index 60ce9ec3be..c37573a504 100644
--- a/apps/mobile/src/chat/useChatServer.ts
+++ b/apps/mobile/src/chat/useChatServer.ts
@@ -1,16 +1,21 @@
import { createConversationListState } from '@cindy/maker-shared/chatConversationList';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { AppState } from 'react-native';
import { useFocusEffect } from 'expo-router';
import type { RemoteActionInvokeResponse } from '@cindy/device-link';
import type { BotGroupAttachment, BotGroupRemoteActionId } from '@cindy/maker-shared/botGroupChat';
import { useAuth } from '@/auth/AuthContext';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { mobileDurableOutbox } from '@/session/mobileDurableOutbox';
+import { enqueueChatMessage, settleChatOutbox } from './chatOutbox';
import { getActiveMobileSessionRealm, getMobileEndpointForRealm, loadMobileEndpointsForRealm } from '@/config/env';
-import { cacheChatRoster, forgetRemoteResource, hideCachedChatRooms, markRemoteResourceRead, readCachedChatRoster } from '@/device-link/remoteResourceCache';
+import { cacheChatRoster, forgetRemoteResource, hideCachedChatRooms, markRemoteResourceRead, peekCachedChatRoster, readCachedChatRoster } from '@/device-link/remoteResourceCache';
import { useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';
import type { BotGroupChatState } from '@/session/useBotGroupChat';
import { chatAccessLost, chatCursor, chatGroupView, chatHttpsUrl, chatRoomRow, chatReadAt, chatReadSequence, chatLastReplyAt, chatLastReplySequence, createChatServerClient, type ChatActor, type ChatPage, type ChatRequest, type ChatSnapshot } from './chatServerClient';
import { subscribeChatServer } from './chatServerSubscription';
+import { cacheChatMessages, forgetChatMessages, peekChatMessages, readChatMessages, subscribeChatInvalidation } from './chatMessageCache';
// Shared only within the current authenticated account generation and realm.
let listOwner = '';
@@ -30,7 +35,9 @@ export function useChatClient() {
const deps = useRef(auth); deps.current = auth;
return useMemo(() => {
const realm = getActiveMobileSessionRealm();
- const current = () => mounted.current && active.current === owner && getActiveMobileSessionRealm() === realm;
+ const authOwner = getMobileAuthOwner();
+ const current = () => mounted.current && active.current === owner && getActiveMobileSessionRealm() === realm
+ && isMobileAuthOwnerCurrent(authOwner);
const check = () => { if (!current()) throw new Error('OWNER_CHANGED'); };
const baseUrl = () => {
try { return chatHttpsUrl(getMobileEndpointForRealm(realm, 'chatApiBaseUrl')).replace(/\/$/, ''); }
@@ -62,12 +69,15 @@ export function useChatClient() {
/** Direct server roster, independent of device discovery and presence. */
export function useChatServerRoster(enabled: boolean) {
const api = useChatClient();
- const known = useRef({ owner: api.owner, ids: new Set<string>() });
- if (known.current.owner !== api.owner) known.current = { owner: api.owner, ids: new Set() };
+ const saved = peekCachedChatRoster(api.userId, api.realm);
+ const known = useRef({ owner: api.owner, ids: new Set(saved?.ids) });
+ if (known.current.owner !== api.owner) known.current = { owner: api.owner, ids: new Set(saved?.ids) };
// A remounted roster must suppress already-known hidden rooms even if HTTP is offline.
for (const id of api.client.personalList.ids()) known.current.ids.add(id);
const snapshots = useRef(new Map<string, { owner: string; head: string | undefined; value: ChatSnapshot }>());
- const [state, setState] = useState({ owner: api.owner, rooms: [] as ReturnType<typeof chatRoomRow>[], loading: true, refreshing: false, error: null as string | null });
+ const [state, setState] = useState(() => ({ owner: api.owner,
+ rooms: saved?.items.filter(row => !api.client.personalList.hidden(row.item.ref.id)) ?? [] as ReturnType<typeof chatRoomRow>[],
+ loading: !saved, refreshing: false, error: null as string | null }));
const read = useRemoteSyncCoordinator(async run => {
if (!api.enabled || !enabled) return;
setState(old => ({ ...old, refreshing: run.reasons.includes('visible') }));
@@ -99,6 +109,7 @@ export function useChatServerRoster(enabled: boolean) {
if (!value.room.archived) rows.push(chatRoomRow(room, value, self));
} catch (error) {
if (!chatAccessLost(error)) {
+ mobileDebugLog('warn', 'recovery', 'companion-roster-refresh', { source: 'group-detail', status: (error as { status?: number })?.status });
partial = true;
const previous = cached.items.find(row => row.item.ref.id === room.id);
const row = chatRoomRow(room);
@@ -126,6 +137,7 @@ export function useChatServerRoster(enabled: boolean) {
}
} catch (error) {
if (!run.isStale() && api.current()) {
+ mobileDebugLog('warn', 'recovery', 'companion-roster-refresh', { source: 'group-list', status: (error as { status?: number })?.status });
setState(old => ({ owner: api.owner, rooms: old.owner === api.owner && !chatAccessLost(error) ? old.rooms.filter(row => !api.client.personalList.hidden(row.item.ref.id)) : [], loading: false, refreshing: false, error: error instanceof Error && error.message === 'CHAT_ENDPOINT_UNAVAILABLE' ? error.message : 'CHAT_LIST_FAILED' }));
if (chatAccessLost(error)) await cacheChatRoster(api.userId, api.realm, [], known.current.ids);
}
@@ -182,18 +194,44 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
const api = useChatClient();
const identity = `${api.owner}:${groupId}:${threadRootId ?? 'main'}`;
const active = useRef(identity); active.current = identity;
- const [state, setState] = useState<{ identity: string; value: BotGroupChatState; online: boolean; loadingOlder: boolean }>({ identity, value: { kind: 'loading' }, online: true, loadingOlder: false });
- const page = useRef<{ identity: string; page: ChatPage; self: string; actors: ChatActor[] } | null>(null);
+ const ledger = useSyncExternalStore(mobileDurableOutbox.subscribe, mobileDurableOutbox.getSnapshot);
+ const pending = ledger.filter(row => enabled && api.current() && row.accountId === getMobileAuthOwner().accountKey
+ && row.chat?.roomId === groupId && row.chat.input.threadRootId === threadRootId);
+ const cached = enabled && api.enabled && !api.client.personalList.hidden(groupId) ? peekChatMessages(groupId, threadRootId) : null;
+ const [state, setState] = useState<{ identity: string; value: BotGroupChatState; online: boolean; loadingOlder: boolean }>(() => ({ identity,
+ value: cached ? { kind: 'ready', group: chatGroupView(cached.page, cached.self, cached.actors) } : { kind: 'loading' },
+ online: true, loadingOlder: false }));
+ const page = useRef<{ identity: string; page: ChatPage; self: string; actors: ChatActor[] } | null>(cached ? { identity, ...cached } : null);
const accessGeneration = useRef(0);
const freshRead = useRef(false);
const olderPending = useRef(false);
const valid = () => api.current() && active.current === identity;
const loseAccess = () => {
accessGeneration.current++; freshRead.current = false; page.current = null;
- if (valid()) void forgetRemoteResource(api.userId, groupId);
+ if (valid()) { void forgetRemoteResource(api.userId, groupId); void forgetChatMessages(groupId); }
setState({ identity, value: { kind: 'missing' }, online: false, loadingOlder: false });
};
const view = (next: ChatPage, self: string, actors: ChatActor[]) => ({ ...chatGroupView(next, self, actors), ...api.client.lifecycleCapabilities() });
+ useEffect(() => subscribeChatInvalidation(roomId => {
+ if (roomId !== groupId || !valid()) return;
+ accessGeneration.current++; freshRead.current = false; page.current = null;
+ setState({ identity, value: { kind: 'missing' }, online: false, loadingOlder: false });
+ }), [api, identity, groupId]);
+ useEffect(() => {
+ if (!enabled || !api.enabled || api.client.personalList.hidden(groupId)) return;
+ let cancelled = false;
+ const generation = accessGeneration.current;
+ const before = page.current;
+ // Disk hydration never waits for endpoint discovery, authentication or HTTP.
+ void readChatMessages(groupId, threadRootId).then(saved => {
+ if (cancelled || !saved || !valid() || generation !== accessGeneration.current
+ || page.current !== before) return;
+ page.current = { identity, ...saved };
+ setState(old => ({ identity, value: { kind: 'ready', group: view(saved.page, saved.self, saved.actors) },
+ online: old.identity === identity && old.online, loadingOlder: false }));
+ });
+ return () => { cancelled = true; };
+ }, [api, identity, enabled, groupId, threadRootId]);
const request = useRemoteSyncCoordinator(async run => {
if (!enabled || !api.enabled) return;
const generation = accessGeneration.current;
@@ -210,6 +248,9 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
if (api.client.personalList.hidden(groupId)) { loseAccess(); return; }
freshRead.current = true;
page.current = { identity, page: next, self, actors };
+ void cacheChatMessages(groupId, { version: 1, page: next, self, actors }).then(saved => {
+ if (saved && valid() && generation === accessGeneration.current) return settleChatOutbox(mobileDurableOutbox, groupId, new Set(next.messages.map(message => message.id)));
+ }).catch(() => undefined);
setState({ identity, value: { kind: 'ready', group: view(next, self, actors) }, online: true, loadingOlder: false });
} catch (error) {
if (run.isStale() || !valid() || generation !== accessGeneration.current) return;
@@ -252,6 +293,18 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
const foreground = AppState.addEventListener('change', value => { if (value === 'active') start(); else { stop?.(); clearInterval(recovery); } });
return () => { stop?.(); clearInterval(recovery); foreground.remove(); };
}, [api, enabled, groupId, identity, reload, request]));
+ const receipts = pending.map(row => row.chat?.messageId ?? '').join('|');
+ useEffect(() => { if (receipts.replaceAll('|', '')) reload(); }, [receipts, reload]);
+ const pendingAction = async (clientId: string, action: 'retry' | 'cancel') => {
+ const row = pending.find(row => row.item.clientId === clientId);
+ if (!row || !valid()) return;
+ if (action === 'cancel') {
+ if (row.enqueueStarted || row.state === 'sending') throw new Error('MESSAGE_ALREADY_SENDING');
+ await mobileDurableOutbox.remove(row);
+ } else if (row.state === 'failed' && !row.suspended) {
+ await mobileDurableOutbox.update(row, { state: 'queued', error: undefined });
+ }
+ };
const loadOlder = async () => {
const previous = page.current;
if (!previous || previous.identity !== identity || olderPending.current) return;
@@ -261,6 +314,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
const next = await api.client.older(groupId, previous.page);
if (!valid() || page.current !== previous) return;
page.current = { ...previous, page: next };
+ void cacheChatMessages(groupId, { version: 1, page: next, self: previous.self, actors: previous.actors });
setState({ identity, value: { kind: 'ready', group: view(next, previous.self, previous.actors) }, online: true, loadingOlder: false });
} catch (error) {
if (valid() && page.current === previous && chatAccessLost(error)) loseAccess();
@@ -273,7 +327,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
if (action === 'hide') {
await api.client.hide(groupId, operationId);
if (valid()) { accessGeneration.current++; page.current = null; setState({ identity, value: { kind: 'missing' }, online: true, loadingOlder: false });
- await forgetRemoteResource(api.userId, groupId); }
+ await forgetRemoteResource(api.userId, groupId); await forgetChatMessages(groupId); }
} else if (action === 'leave') {
try { await api.client.leave(groupId, operationId); } catch (error) { if (valid()) reload(); throw error; }
if (valid()) loseAccess();
@@ -285,35 +339,22 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
if (action !== 'send' || !input || input.division || (Array.isArray(input.attachments) && input.attachments.length)) throw new Error('UNSUPPORTED_CHAT_ACTION');
const latest = page.current;
if (!latest || latest.identity !== identity) throw new Error('CHAT_READ_FAILED');
- try {
- const mentions = input.mentions as { all: boolean; botIds: string[] };
- const joined = mentions.all || mentions.botIds.length
- ? (await api.client.members(groupId)).filter(member => member.state === 'joined') : [];
- if (!valid() || page.current?.identity !== identity) throw new Error('OWNER_CHANGED');
- // Validate every explicit pick before Everyone expansion; never discard a
- // departed target or submit only the remaining part of the intended list.
- if (mentions.botIds.some(id => !joined.some(member => member.id === id))) throw new Error('MENTION_UNAVAILABLE');
- const recipients = mentions.all
- ? joined.map(member => member.id)
- : [...mentions.botIds];
- const root = threadRootId ? latest.page.messages.find(message => message.id === threadRootId) : undefined;
- if (root && joined.some(member => member.id === root.authorId && member.kind === 'bot')) recipients.push(root.authorId);
- await api.client.send(groupId, { ...(latest.page.snapshot.room.kind === 'direct' ? { conversationKind: 'direct' as const } : {}), clientId: String(input.clientId), text: String(input.text), threadRootId,
- ...(input.quote && typeof input.quote === 'object' && 'messageId' in input.quote
- ? { quote: { messageId: String(input.quote.messageId) } } : {}),
- mentions: { all: false, botIds: recipients.filter(id => id !== latest.self) } });
- if (valid()) reload();
- return { effects: [] };
- } catch (error) {
- // An unavailable mention is a draft correction, not a connectivity failure.
- if (error instanceof Error && ['MENTION_UNAVAILABLE', 'QUOTE_UNAVAILABLE'].includes(error.message)) throw error;
- if (valid()) {
- freshRead.current = false;
- if (chatAccessLost(error)) loseAccess();
- else setState(old => ({ ...old, online: false }));
- }
- throw error;
- }
+ const owner = getMobileAuthOwner();
+ if (!valid() || owner.accountId !== api.userId || mobileDurableOutbox.getAccountId() !== owner.accountKey) throw new Error('OWNER_CHANGED');
+ const mentions = input.mentions as { all: boolean; botIds: string[] };
+ const root = threadRootId ? latest.page.messages.find(message => message.id === threadRootId) : undefined;
+ const recipients = [...mentions.botIds];
+ if (root && latest.page.snapshot.members.some(member => member.id === root.authorId && member.kind === 'bot' && member.state === 'joined')) recipients.push(root.authorId);
+ await enqueueChatMessage(mobileDurableOutbox, owner.accountKey, groupId, {
+ ...(latest.page.snapshot.room.kind === 'direct' ? { conversationKind: 'direct' as const } : {}),
+ clientId: String(input.clientId), text: String(input.text), threadRootId,
+ ...(input.quote && typeof input.quote === 'object' && 'messageId' in input.quote
+ ? { quote: { messageId: String(input.quote.messageId) } } : {}),
+ mentions: { all: mentions.all, botIds: [...new Set(recipients)] },
+ }, latest.page.messages.length, input.quote as import('@cindy/maker-shared/botGroupChat').BotGroupQuoteView | undefined,
+ latest.page.messages.reduce<string | undefined>((seq, message) => !seq || BigInt(message.seq) > BigInt(seq) ? message.seq : seq, undefined));
+ if (!isMobileAuthOwnerCurrent(owner)) throw new Error('OWNER_CHANGED');
+ return { effects: [] };
};
const media = async (mediaId: string, signal?: AbortSignal): Promise<BotGroupAttachment> => {
const generation = accessGeneration.current;
@@ -356,6 +397,7 @@ export function useChatServerGroup(groupId: string, enabled: boolean, threadRoot
}, [api, groupId]);
return { state: state.identity === identity ? state.value : { kind: 'loading' } as BotGroupChatState,
listHidden: api.current() && api.client.personalList.hidden(groupId),
- online: state.identity === identity && state.online, reload, act,
+ online: state.identity === identity && state.online, reload, act, pending, pendingAction,
+ canQueue: enabled && api.enabled && state.identity === identity && state.value.kind === 'ready' && !api.client.personalList.hidden(groupId),
acceptListState, isListHidden: () => api.client.personalList.hidden(groupId), loadOlder, loadingOlder: state.loadingOlder, media, markRead };
}
diff --git a/apps/mobile/src/chat/useCloudCompanion.ts b/apps/mobile/src/chat/useCloudCompanion.ts
index eab37672ed..225d9225d9 100644
--- a/apps/mobile/src/chat/useCloudCompanion.ts
+++ b/apps/mobile/src/chat/useCloudCompanion.ts
@@ -1,9 +1,13 @@
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { AppState } from 'react-native';
import { useFocusEffect } from 'expo-router';
import type { ChatActor, ChatSetHomeResult } from './chatServerClient';
import { useChatClient } from './useChatServer';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { cacheCloudHome, peekCachedCloudHome, readCachedCloudHome,
+ remoteResourceCacheRevision, subscribeRemoteResourceCache } from '@/device-link/remoteResourceCache';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
+import { forgetCloudConversation } from './cloudConversationCache';
const NO_ACTORS: ChatActor[] = [];
const NO_NAMES: ReadonlyMap<string, string> = new Map();
@@ -17,24 +21,42 @@ const NO_NAMES: ReadonlyMap<string, string> = new Map();
export function useCloudCompanionHome(enabled: boolean) {
const api = useChatClient();
const { readDeviceList } = useDeviceLink();
- const [state, setState] = useState({ owner: api.owner, supported: false, actors: NO_ACTORS, deviceNames: NO_NAMES });
+ useSyncExternalStore(subscribeRemoteResourceCache, remoteResourceCacheRevision);
+ const cached = peekCachedCloudHome(api.userId, api.realm);
+ const deviceNames = useMemo(() => cached ? new Map(cached.deviceNames) : NO_NAMES, [cached]);
+ const [failure, setFailure] = useState<{ owner: string; error: string } | null>(null);
const generation = useRef(0);
+ useEffect(() => { if (api.enabled) void readCachedCloudHome(api.userId, api.realm); }, [api]);
const refresh = useCallback(async () => {
if (!enabled || !api.enabled) return;
const run = ++generation.current;
+ const current = () => run === generation.current && api.current();
try {
const { companionHome } = await api.client.capabilities();
const actors = companionHome ? await api.client.actors() : NO_ACTORS;
- const deviceNames = companionHome && actors.length
- ? await readDeviceList().then(({ devices }) => new Map(devices.map(device => [device.deviceId, device.name] as const)), () => null)
- : NO_NAMES;
- if (run !== generation.current || !api.current()) return;
- // A failed optional directory read is not a rename. Retain only this
- // account's last labels; the successful actor response still owns homes.
- setState(previous => ({ owner: api.owner, supported: companionHome, actors,
- deviceNames: deviceNames ?? (previous.owner === api.owner ? previous.deviceNames : NO_NAMES) }));
- } catch {
- // Keep the previous answer: rows simply behave as before when the server cannot be read.
+ if (!current()) return;
+ const previous = peekCachedCloudHome(api.userId, api.realm);
+ const previousNames = previous?.deviceNames ?? [];
+ // A capability/network failure is not a deletion. A successful roster is authoritative.
+ if (companionHome) {
+ const ids = new Set(actors.map(actor => actor.id));
+ await Promise.all((previous?.actors ?? []).filter(actor => !ids.has(actor.id)).map(actor => forgetCloudConversation(actor.id)));
+ if (!current()) return;
+ }
+ await cacheCloudHome(api.userId, api.realm, { supported: companionHome, actors, deviceNames: previousNames }, current);
+ if (!current()) return;
+ setFailure(null);
+ // Optional computer labels never delay the companion roster itself.
+ if (companionHome && actors.length) {
+ const names = await readDeviceList().then(({ devices }) => devices.map(device => [device.deviceId, device.name] as [string, string]), () => null);
+ if (names && current()) await cacheCloudHome(api.userId, api.realm, { supported: companionHome, actors, deviceNames: names }, current);
+ }
+ } catch (error) {
+ if (!current()) return;
+ const candidate = (error as { code?: unknown })?.code;
+ const code = typeof candidate === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(candidate) ? candidate : 'CLOUD_ROSTER_FAILED';
+ mobileDebugLog('warn', 'recovery', 'companion-roster-refresh', { source: 'cloud', code, status: (error as { status?: number })?.status });
+ setFailure({ owner: api.owner, error: code });
}
}, [api, enabled, readDeviceList]);
useFocusEffect(useCallback(() => {
@@ -43,13 +65,12 @@ export function useCloudCompanionHome(enabled: boolean) {
const foreground = AppState.addEventListener('change', value => { if (value === 'active') void refresh(); });
return () => { generation.current += 1; foreground.remove(); };
}, [api.enabled, enabled, refresh]));
- const own = state.owner === api.owner;
// Never move the home before its profile snapshot is in the cloud: the new computer could not
// build the companion, and the old one would already be demoted (cloud-companions.md).
const setHome = useCallback(async (actorId: string, homeDeviceId: string, expected: string | null): Promise<ChatSetHomeResult> => {
if (!(await api.client.hasProfileSnapshot(actorId))) throw new Error('PROFILE_SNAPSHOT_MISSING');
return api.client.setHome(actorId, homeDeviceId, expected);
}, [api]);
- return { supported: own && state.supported, actors: own ? state.actors : NO_ACTORS,
- deviceNames: own ? state.deviceNames : NO_NAMES, refresh, setHome };
+ return { supported: cached?.supported === true, actors: cached?.actors ?? NO_ACTORS,
+ deviceNames, error: failure?.owner === api.owner ? failure.error : null, refresh, setHome };
}
diff --git a/apps/mobile/src/chat/useCloudCompanionRoom.ts b/apps/mobile/src/chat/useCloudCompanionRoom.ts
index bdc61235b0..30a9b442d2 100644
--- a/apps/mobile/src/chat/useCloudCompanionRoom.ts
+++ b/apps/mobile/src/chat/useCloudCompanionRoom.ts
@@ -1,10 +1,11 @@
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { AppState } from 'react-native';
import { useFocusEffect } from 'expo-router';
import * as Crypto from 'expo-crypto';
import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';
import { chatAccessLost, type ChatMessage } from './chatServerClient';
import { useChatClient } from './useChatServer';
+import { peekCloudConversation, readCloudConversation, cacheCloudConversation, forgetCloudConversation, subscribeCloudConversationInvalidation } from './cloudConversationCache';
/** Same name-keyed room operation as the desktop (sha256 hex of the room name). */
const sha256Hex = (text: string) => Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, text, { encoding: Crypto.CryptoEncoding.HEX });
@@ -20,11 +21,26 @@ export function useCloudCompanionRoom(actorId: string, name: string, enabled: bo
const identity = `${api.owner}:${actorId}`;
const active = useRef(identity); active.current = identity;
const initial = (): RoomState => ({ identity, roomId: null, messages: [], before: null, status: 'loading', loadingOlder: false });
- const [state, setState] = useState<RoomState>(initial);
+ const [state, setState] = useState<RoomState>(() => { const saved = enabled ? peekCloudConversation(actorId) : null;
+ return saved ? { ...initial(), ...saved, status: 'ready' } : initial(); });
const latest = useRef(state); latest.current = state;
const generation = useRef(0);
const olderPending = useRef(false);
const valid = () => api.current() && active.current === identity;
+ useEffect(() => subscribeCloudConversationInvalidation(id => {
+ if (id !== actorId || !valid()) return;
+ generation.current++;
+ setState({ ...initial(), status: 'error' });
+ }), [api, actorId, identity]);
+ useEffect(() => {
+ if (!enabled || !api.enabled) return;
+ let cancelled = false;
+ const before = latest.current;
+ void readCloudConversation(actorId).then(saved => {
+ if (!cancelled && saved && valid() && latest.current === before) setState({ ...initial(), ...saved, status: 'ready' });
+ });
+ return () => { cancelled = true; };
+ }, [api, actorId, enabled, identity]);
const reload = useCallback(async () => {
if (!enabled || !api.enabled || !actorId) return;
const run = ++generation.current;
@@ -32,15 +48,25 @@ export function useCloudCompanionRoom(actorId: string, name: string, enabled: bo
try {
const roomId = previous?.roomId ?? await api.client.companionRoom(actorId, name, sha256Hex);
const page = await api.client.history(roomId);
+ const oldest = previous?.roomId === roomId ? previous.messages.reduce<string | undefined>((seq, message) =>
+ !seq || BigInt(message.seq) < BigInt(seq) ? message.seq : seq, undefined) : undefined;
+ while (page.before && oldest && BigInt(page.before) > BigInt(oldest)) {
+ const before = page.before;
+ const older = await api.client.history(roomId, before);
+ if (run !== generation.current || !valid()) return;
+ const known = new Set(page.messages.map(message => message.id));
+ page.messages.push(...older.messages.filter(message => !known.has(message.id)));
+ page.before = older.before;
+ if (page.before === before) throw new Error('INVALID_CHAT_PAGE');
+ }
if (run !== generation.current || !valid()) return;
- // Keep pages already loaded above the refreshed newest page.
- const fresh = new Set(page.messages.map(message => message.id));
- const kept = previous?.roomId === roomId && previous.messages.length > page.messages.length
- ? previous.messages.filter(message => !fresh.has(message.id)) : [];
- setState({ identity, roomId, messages: [...page.messages, ...kept], before: kept.length ? previous!.before : page.before,
- status: 'ready', loadingOlder: false });
+ // Revalidate the opened window too: old edits/deletions must not survive hydration.
+ const next = { identity, roomId, messages: page.messages, before: page.before,
+ status: 'ready' as const, loadingOlder: false };
+ void cacheCloudConversation(actorId, next); setState(next);
} catch (error) {
if (run !== generation.current || !valid()) return;
+ if (chatAccessLost(error)) void forgetCloudConversation(actorId);
setState(old => old.identity === identity && old.status === 'ready' && !chatAccessLost(error)
? old : { ...initial(), status: 'error' });
}
@@ -59,8 +85,14 @@ export function useCloudCompanionRoom(actorId: string, name: string, enabled: bo
try {
const page = await api.client.history(current.roomId, current.before);
if (!valid() || latest.current.roomId !== current.roomId) return;
- setState(old => ({ ...old, messages: [...old.messages, ...page.messages], before: page.before, loadingOlder: false }));
- } catch {
+ if (latest.current.messages !== current.messages) {
+ setState(old => ({ ...old, loadingOlder: false })); return;
+ }
+ const ids = new Set(current.messages.map(message => message.id));
+ const next = { ...current, messages: [...current.messages, ...page.messages.filter(message => !ids.has(message.id))], before: page.before, loadingOlder: false };
+ void cacheCloudConversation(actorId, { ...next, roomId: current.roomId }); setState(next);
+ } catch (error) {
+ if (valid() && chatAccessLost(error)) { void forgetCloudConversation(actorId); setState({ ...initial(), status: 'error' }); }
if (valid()) setState(old => ({ ...old, loadingOlder: false }));
} finally { olderPending.current = false; }
}, [api, identity]);
diff --git a/apps/mobile/src/device-link/remoteResourceCache.ts b/apps/mobile/src/device-link/remoteResourceCache.ts
index 0e3e532121..76e7f45d93 100644
--- a/apps/mobile/src/device-link/remoteResourceCache.ts
+++ b/apps/mobile/src/device-link/remoteResourceCache.ts
@@ -1,11 +1,13 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
+import type { ChatActor } from '@/chat/chatServerClient';
import { resolveRemoteText } from '@cindy/device-link';
import { isMobileRemoteCollectionSupported, normalizeRemoteCollectionItems, parseRemoteResourceTargets, type HostedRemoteCollectionItem, type RemoteHomeCollection } from './remoteResources';
const PREFIX = 'cindy.remoteResources.v1.';
const MAX_CHARS = 256 * 1024;
type ChatRoster = { items: HostedRemoteCollectionItem[]; ids: string[] };
-type Snapshot = { home: RemoteHomeCollection[]; items: Record<string, HostedRemoteCollectionItem[]>; read: Record<string, number>; readSequences?: Record<string, string>; chatRosters?: Record<string, ChatRoster> };
+export type CachedCloudHome = { supported: boolean; actors: ChatActor[]; deviceNames: Array<[string, string]> };
+type Snapshot = { home: RemoteHomeCollection[]; items: Record<string, HostedRemoteCollectionItem[]>; read: Record<string, number>; readSequences?: Record<string, string>; chatRosters?: Record<string, ChatRoster>; cloudHomes?: Record<string, CachedCloudHome> };
const empty = (): Snapshot => ({ home: [], items: {}, read: {}, readSequences: {} });
const validSequence = (value: unknown): value is string => typeof value === 'string' && /^\d{1,30}$/.test(value);
let epoch = 0;
@@ -24,6 +26,16 @@ function normalize(raw: unknown): Snapshot {
const out = empty();
if (!raw || typeof raw !== 'object') return out;
const value = raw as Partial<Snapshot>;
+ if (value.cloudHomes && typeof value.cloudHomes === 'object') for (const realm of ['cn', 'global']) {
+ const home = value.cloudHomes[realm];
+ if (!home || typeof home.supported !== 'boolean' || !Array.isArray(home.actors) || !Array.isArray(home.deviceNames)) continue;
+ (out.cloudHomes ??= {})[realm] = { supported: home.supported,
+ actors: home.actors.filter(actor => actor && typeof actor.id === 'string' && typeof actor.name === 'string'
+ && typeof actor.kind === 'string' && typeof actor.externalId === 'string'
+ && (actor.homeDeviceId === null || typeof actor.homeDeviceId === 'string')
+ && (actor.avatar === null || typeof actor.avatar === 'string')),
+ deviceNames: home.deviceNames.filter(pair => Array.isArray(pair) && pair.length === 2 && pair.every(part => typeof part === 'string')) };
+ }
if (Array.isArray(value.home)) for (const row of value.home.slice(0, 32)) {
if (!row || typeof row.id !== 'string' || row.id.length > 160 || typeof row.title !== 'string' || typeof row.resourceKind !== 'string') continue;
if (!isMobileRemoteCollectionSupported(row.id)) continue;
@@ -89,6 +101,16 @@ export async function readRemoteResourceSnapshot(userId: string): Promise<Snapsh
return snapshots.get(userId)!;
}
+/** Reopening a page paints the same saved rows in its first render, without an async blank frame. */
+export const peekRemoteResourceSnapshot = (userId: string): Snapshot | undefined => snapshots.get(userId);
+export const peekCachedChatRoster = (userId: string, realm: string): ChatRoster | null => snapshots.get(userId)?.chatRosters?.[realm] ?? null;
+export const peekCachedCloudHome = (userId: string, realm: string): CachedCloudHome | null => snapshots.get(userId)?.cloudHomes?.[realm] ?? null;
+export const readCachedCloudHome = async (userId: string, realm: string): Promise<CachedCloudHome | null> =>
+ (await readRemoteResourceSnapshot(userId)).cloudHomes?.[realm] ?? null;
+export const cacheCloudHome = (userId: string, realm: string, value: CachedCloudHome, current: () => boolean = () => true) => update(userId, s => {
+ if (current()) (s.cloudHomes ??= {})[realm] = value;
+});
+
/** Trim only the disposable disk mirror; live rows and read positions stay intact. */
function diskSnapshot(raw: string): string {
if (raw.length <= MAX_CHARS) return raw;
@@ -120,6 +142,10 @@ function diskSnapshot(raw: string): string {
remaining -= JSON.stringify(roster.ids.shift()).length;
}
while (remaining > 0 && copy.home.length) remaining -= JSON.stringify(copy.home.shift()).length;
+ for (const home of Object.values(copy.cloudHomes ?? {})) {
+ while (remaining > 0 && home.actors.length) remaining -= JSON.stringify(home.actors.pop()).length;
+ while (remaining > 0 && home.deviceNames.length) remaining -= JSON.stringify(home.deviceNames.pop()).length;
+ }
return JSON.stringify(copy);
}
diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsx
index b7d6d892c3..4bd8ad4747 100644
--- a/apps/mobile/src/session/BotGroupChatScreen.tsx
+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx
@@ -1,3 +1,6 @@
+import { pendingChatMessage } from '@/chat/chatOutbox';
+import { useDelayedConnectionNotice } from '@/components/ConnectionNoticeOverlay';
+import type { DurableOutboxRecord } from './durableOutbox';
import Reanimated from 'react-native-reanimated';
import { useSmoothMessageFollow } from './useSmoothMessageFollow';
import { AnimatedContentHeight } from './AnimatedContentHeight';
@@ -440,8 +443,9 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
onOpenSettings={direct ? undefined : () => setSettings(true)}
settingsLabel={t('groupChat.settings.open')} />;
- const offlineNote = <AnimatedContentHeight open={!!group && !chat.online}>
- <Text accessibilityRole="alert" style={styles.offline} testID="botGroup.offlineNote">{t(offlineKey)}</Text>
+ const showOffline = useDelayedConnectionNotice(!!group && !chat.online);
+ const offlineNote = <AnimatedContentHeight open={showOffline}>
+ <Text accessibilityRole="alert" style={styles.offline} testID="botGroup.offlineNote">{t(chat.canQueue ? 'message.queue.waitingForNetwork' : offlineKey)}</Text>
</AnimatedContentHeight>;
let body;
if (chat.state.kind === 'loading' && !chat.online) {
@@ -534,6 +538,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
testID="botGroup.timeline">
<BotGroupTimeline group={group} deviceId={deviceId} online={chat.online} identityFor={identityFor}
highlightId={highlightId} onLocateMessage={locateMessage}
+ pending={chat.pending} onPendingAction={(id, action) => { void chat.pendingAction?.(id, action).catch(error => report(error, 'groupChat.composer.sendFailed')); }}
onReply={(chat.server || group.serverBacked) && !group.archived && !group.dissolvedAt ? message => setReplyTo(botGroupQuoteFromMessage(message)) : undefined}
onMessageLayout={(id, y, height) => {
previewVisibility.setLayout(id, { y, height });
@@ -573,7 +578,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
<View style={styles.flex}><BotGroupQuote display={resolveBotGroupQuote(replyTo, group.messages)} onPress={() => locateMessage(replyTo.messageId)} /></View>
<MainWindowActionButton density="compact" action={{ label: t('message.quote.remove'), onPress: () => setReplyTo(null), testID: 'botGroup.cancelReply' }} />
</View> : null}
- <BotGroupComposer members={group.members} identityFor={identityFor} deviceId={deviceId} online={chat.online && !group.archived && !group.dissolvedAt}
+ <BotGroupComposer members={group.members} identityFor={identityFor} deviceId={deviceId} online={(chat.online || !!chat.canQueue) && !group.archived && !group.dissolvedAt}
focusKey={replyTo?.messageId}
running={group.round.status === 'running'} planState={botGroupComposerPlanState(openBotGroupPlan(group), group.replyMode)}
divisionSupported={!chat.server && (!group.singleSpeaker || group.supportsDivision === true)} attachmentsSupported={group.supportsAttachments === true} onSend={send} onStop={stop} />
@@ -616,9 +621,11 @@ function followUpPending(action: PlanPending['action'] | null): BotGroupFollowUp
export function BotGroupTimeline({
group, deviceId, online, identityFor, resolveMedia, resolveServerMedia, loadOlder, loadingOlder, continuing, planPending, onContinue, onPlanAction, onEditStep, onInteractionError,
- onMessageLayout, onLocateMessage, highlightId, onReply,
+ onMessageLayout, onLocateMessage, highlightId, onReply, pending = [], onPendingAction,
}: {
group: BotGroupRemoteChatData;
+ pending?: readonly DurableOutboxRecord[];
+ onPendingAction?: (id: string, action: 'retry' | 'cancel') => void;
deviceId: string;
online: boolean;
identityFor: BotGroupIdentityLookup;
@@ -640,8 +647,15 @@ export function BotGroupTimeline({
}) {
const { t, i18n } = useTranslation();
const styles = useThemedStyles(makeStyles);
- const messages = group.messages;
- const entranceSignature = messages.map(message => message.id).join('\0');
+ const canonicalIds = new Set(group.messages.map(message => message.id));
+ const rowIdentity = useRef({ groupId: group.id, ids: new Map<string, string>() });
+ if (rowIdentity.current.groupId !== group.id) rowIdentity.current = { groupId: group.id, ids: new Map() };
+ for (const row of pending) if (row.chat?.messageId) rowIdentity.current.ids.set(row.chat.messageId, `local:${row.item.clientId}`);
+ const rowKey = (id: string) => rowIdentity.current.ids.get(id) ?? id;
+ const local = pending.filter(row => !row.chat?.messageId || !canonicalIds.has(row.chat.messageId));
+ const pendingById = new Map(local.map(row => [`local:${row.item.clientId}`, row]));
+ const messages = [...group.messages, ...local.map(pendingChatMessage)];
+ const entranceSignature = messages.map(message => rowKey(message.id)).join('\0');
const entranceKeys = useMemo(() => entranceSignature ? entranceSignature.split('\0') : [], [entranceSignature]);
const enteringMessageKeys = useMessageEntrances(entranceKeys, group.id);
const planById = new Map(group.plans.map((plan) => [plan.id, plan]));
@@ -662,14 +676,16 @@ export function BotGroupTimeline({
{messages.length === 0 && !running ? <MainWindowEmptyState centered testID="botGroup.empty"
title={t('groupChat.timeline.emptyTitle')} copy={t('groupChat.timeline.emptyDescription')} /> : null}
{messages.map((message, index) => {
+ const queued = pendingById.get(message.id);
const groupTime = timeGroups.get(message.id);
const previous = index > 0 ? messages[index - 1] : undefined;
// G2: the same teammate speaking again inside one time group keeps its avatar and name once.
const continued = groupTime === undefined && message.kind === 'message' && message.authorKind === 'bot'
&& previous?.kind === 'message' && previous.authorKind === 'bot' && previous.authorBotId === message.authorBotId;
- return <View key={message.id} style={highlightId === message.id && styles.locatedMessage}
+ const key = rowKey(message.id);
+ return <View key={key} style={highlightId === message.id && styles.locatedMessage}
onLayout={event => onMessageLayout?.(message.id, event.nativeEvent.layout.y, event.nativeEvent.layout.height)}>
- <CompanionEntering id={message.id} arrivedAt={enteringMessageKeys.get(message.id)}>
+ <CompanionEntering id={key} arrivedAt={enteringMessageKeys.get(key)}>
<View style={[styles.item, (index > 0 || group.hasMoreBefore) && { paddingTop: spacing.lg }]}>
{groupTime !== undefined ? <Text style={styles.time}>{formatBotMessageGroupTime(groupTime, i18n.language)}</Text> : null}
<BotGroupTimelineItem message={message} continued={continued} member={message.authorBotId ? memberById.get(message.authorBotId) : undefined}
@@ -684,7 +700,12 @@ export function BotGroupTimeline({
planPending={planCardPending(pendingFor(message.planId))}
onPlanAction={(action) => { if (message.planId) onPlanAction(action, message.planId); }}
onEditStep={(step, action, botId) => { if (message.planId) onEditStep(message.planId, step, action, botId); }} />
- {onReply && isBotGroupMessageQuotable(message) ? <Pressable
+ {queued ? <View style={styles.pendingRow} testID={`botGroup.pending.${queued.item.clientId}`}>
+ <Text style={styles.pendingText}>{t(queued.state === 'failed' ? 'message.queue.notSent' : !online ? 'message.queue.waitingForNetwork' : 'message.queue.queued')}</Text>
+ {queued.state === 'failed' && !queued.suspended ? <MainWindowActionButton density="compact" action={{ label: t('message.queue.retry'), onPress: () => onPendingAction?.(queued.item.clientId, 'retry') }} /> : null}
+ {!queued.enqueueStarted && queued.state !== 'sending' ? <MainWindowActionButton density="compact" action={{ label: t('message.queue.cancelSend'), onPress: () => onPendingAction?.(queued.item.clientId, 'cancel') }} /> : null}
+ </View> : null}
+ {!queued && onReply && isBotGroupMessageQuotable(message) ? <Pressable
accessibilityRole="button" accessibilityLabel={t('message.renderer.reply')}
testID={`botGroup.reply.${message.id}`} onPress={() => onReply(message)}
style={[styles.replyAction, message.isSelf === true && styles.ownReplyAction]}>
@@ -835,6 +856,8 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({
locatedMessage: { backgroundColor: colors.surfaceElevated, borderRadius: radius.container },
replyDraft: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, paddingHorizontal: spacing.md, paddingVertical: spacing.sm },
replyAction: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center', marginLeft: BOT_GROUP_MESSAGE_AVATAR_SIZE + REPLY_AVATAR_GAP },
+ pendingRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', flexWrap: 'wrap', gap: spacing.sm },
+ pendingText: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },
ownReplyAction: { alignSelf: 'flex-end', marginLeft: 0 },
replyIcon: { color: colors.textSecondary },
floatingHeader: { position: 'absolute', top: 0, left: 0, right: 0, zIndex: 10 },
diff --git a/apps/mobile/src/session/CindyMakeSessionGate.tsx b/apps/mobile/src/session/CindyMakeSessionGate.tsx
index 39fcdc55b9..76d5a56782 100644
--- a/apps/mobile/src/session/CindyMakeSessionGate.tsx
+++ b/apps/mobile/src/session/CindyMakeSessionGate.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState, useSyncExternalStore, type ReactNode } from 'react';
+import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';
import { Redirect, useIsFocused } from 'expo-router';
import { AppState } from 'react-native';
import { useTranslation } from 'react-i18next';
@@ -12,6 +12,8 @@ import { remoteSessionStore } from './remoteSessionStore';
import { MainWindowActionButton } from '@/components/MobilePrimitives';
import { useNewSessionCreationTask } from './newSessionCreation';
import { SessionEntryStatus } from './SessionEntryRecovery';
+import { useCachedCompanionSession } from './useCachedCompanionSession';
+import { forgetRemoteResource } from '@/device-link/remoteResourceCache';
export const SESSION_ENTRY_LOOKUP_TIMEOUT_MS = 20_000;
type Lookup = { key: string; status: 'loading' | 'failed' | 'missing' | 'timedOut' | 'loaded' };
@@ -25,7 +27,7 @@ export function CindyMakeSessionGate({ sessionId, deviceId: routeDeviceId, child
ownsSessionSubscription?: boolean;
}) {
const { t } = useTranslation();
- const { accountGeneration } = useAuth();
+ const { user, accountGeneration } = useAuth();
const { openLink, connectionEpoch, unsubscribe, status: relayStatus, getPresenceAvailability } = useDeviceLink();
const focused = useIsFocused();
const [foreground, setForeground] = useState(AppState.currentState === 'active');
@@ -35,6 +37,8 @@ export function CindyMakeSessionGate({ sessionId, deviceId: routeDeviceId, child
}, []);
const sessions = useSyncExternalStore(remoteSessionStore.subscribe, remoteSessionStore.getSessions);
const deviceId = routeDeviceId ?? remoteSessionStore.getSessionDeviceId(sessionId) ?? '';
+ const cachedCompanion = useCachedCompanionSession(deviceId, sessionId);
+ const cachedRef = useRef(cachedCompanion); cachedRef.current = cachedCompanion;
const maker = useMobileMakerTransport(deviceId);
const presence = getPresenceAvailability(deviceId);
// The creation pipeline registers this owner before navigating here. The gate
@@ -54,12 +58,13 @@ export function CindyMakeSessionGate({ sessionId, deviceId: routeDeviceId, child
const scope = JSON.stringify([sessionId, deviceId, accountGeneration]);
const key = JSON.stringify([sessionId, deviceId, accountGeneration, connectionEpoch, relayStatus, presence, focused, foreground, attempt]);
const [lookup, setLookup] = useState<Lookup | null>(null);
+ const [blockedScope, setBlockedScope] = useState<string | null>(null);
// Reconnecting must not unmount content whose source was already confirmed for this owner.
const [loaded, setLoaded] = useState<{ scope: string; source: string | null } | null>(null);
useEffect(() => {
if (CINDY_MAKE_ENABLED) return;
- if (knownSource !== undefined) {
+ if (knownSource !== undefined && blockedScope !== scope) {
// A mirror confirmation is as authoritative as a direct lookup. Preserve
// the latest source for this scope when reconnecting clears the mirror.
setLoaded({ scope, source: knownSource });
@@ -94,12 +99,26 @@ export function CindyMakeSessionGate({ sessionId, deviceId: routeDeviceId, child
})
.then(session => {
if (cancelled()) return;
- if (session?.id === sessionId) setLoaded({ scope, source: session.source ?? null });
+ if (session?.id === sessionId) { setBlockedScope(null); setLoaded({ scope, source: session.source ?? null }); }
+ else if (cachedRef.current) {
+ setBlockedScope(scope);
+ if (user?.id) void forgetRemoteResource(user.id, cachedRef.current.ref.id);
+ }
setLookup(session?.id === sessionId
? { key, status: 'loaded' }
: { key, status: 'missing' });
})
- .catch(() => { if (!cancelled()) setLookup({ key, status: 'failed' }); })
+ .catch(error => {
+ if (cancelled()) return;
+ const code = (error as { code?: string })?.code;
+ const deniedCodes = ['NOT_FOUND', 'FORBIDDEN', 'PERMISSION_DENIED', 'ACCESS_REVOKED', 'DEVICE_REVOKED'];
+ const denied = deniedCodes.includes(code ?? '') || deniedCodes.some(value => String(error).includes(`[${value}]`));
+ if (denied) {
+ setBlockedScope(scope);
+ if (user?.id && cachedRef.current) void forgetRemoteResource(user.id, cachedRef.current.ref.id);
+ }
+ setLookup({ key, status: denied ? 'missing' : 'failed' });
+ })
.finally(() => clearTimeout(timeout));
return () => { controller.abort(); clearTimeout(timeout); };
}, [key, scope, sessionId, deviceId, knownSource, maker, openLink, creationBlocked, focused, foreground, relayStatus, presence]);
@@ -112,8 +131,13 @@ export function CindyMakeSessionGate({ sessionId, deviceId: routeDeviceId, child
// 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) {
- const status = lookup?.key === key ? lookup.status : 'loading';
+ // Notification routes can precede the home/session mirror on a cold launch.
+ // Mount the real chat so its history cache hydrates while metadata is checked.
+ // A raw push resourceId never grants this path: the saved device/session link must match.
+ if (ownsSessionSubscription && cachedCompanion && source === undefined && blockedScope !== scope
+ && !(lookup?.key === key && lookup.status === 'missing')) return children;
+ if (blockedScope === scope || (!CINDY_MAKE_ENABLED && source === undefined)) {
+ const status = blockedScope === scope ? 'missing' : lookup?.key === key ? lookup.status : 'loading';
return <SessionEntryStatus title={t('session.entry.title')}
copy={t(`session.entry.${status}`)} loading={status === 'loading'}>
{status !== 'loading' ? <MainWindowActionButton action={{
diff --git a/apps/mobile/src/session/HomeTeammatesSection.tsx b/apps/mobile/src/session/HomeTeammatesSection.tsx
index 3db578c5c2..070c5b2db1 100644
--- a/apps/mobile/src/session/HomeTeammatesSection.tsx
+++ b/apps/mobile/src/session/HomeTeammatesSection.tsx
@@ -40,6 +40,7 @@ import { useTeammateCreateController } from './TeammateCreateController';
import { useTeammateEntries, useTeammateRowRenderer, type TeammateListEntry } from './TeammateList';
import { cloudCompanionRoute } from './teammateNavigation';
import { useTeammateNavigation } from './useTeammateNavigation';
+import { getHomeViewSession, useRetainedHomeState } from './homeViewSession';
/** Desktop previews five in a 260px sidebar; three keeps the first screen of tasks on a phone. */
export const HOME_TEAMMATE_PREVIEW_LIMIT = 3;
@@ -127,13 +128,13 @@ function SectionContent({ shared, active, refreshKey, visible, query, showFooter
const stored = local?.owner === owner ? local.collapsed : navigation.teammatesCollapsed;
// Search results are always rows; the stored fold returns with the search cleared.
const collapsed = stored && !search;
- const [showAll, setShowAll] = useState(false);
+ const [showAll, setShowAll] = useRetainedHomeState(getHomeViewSession(), 'teammatesShowAll', false);
const setTeammatesCollapsed = navigation.setTeammatesCollapsed;
const toggleCollapsed = useCallback(() => {
const next = !stored;
runDisclosure(() => { setLocal({ owner, collapsed: next }); if (next) setShowAll(false); });
void setTeammatesCollapsed(next);
- }, [stored, owner, runDisclosure, setTeammatesCollapsed]);
+ }, [stored, owner, runDisclosure, setTeammatesCollapsed, setShowAll]);
const createTargets = useStableValue(roster.createTargets, sameHosts);
const groupCreateTargets = useStableValue(roster.groupTargets.filter(groups.isOnline), sameHosts);
const canCreate = createTargets.length > 0 || groupCreateTargets.length > 0;
@@ -146,16 +147,16 @@ function SectionContent({ shared, active, refreshKey, visible, query, showFooter
onGroupCreated: (host, groupId) => push(botGroupRoute(host, groupId)) });
// Keep cached rows during recovery. A lasting failure only adds a header action,
// never a notice row that changes the list's height.
- const error = groups.error ?? roster.error;
+ const error = groups.error ?? roster.error ?? cloud.error;
const errorKey = error === 'CHAT_ENDPOINT_UNAVAILABLE' ? 'groupChat.server.endpointUnavailable'
: error === 'CHAT_LIST_FAILED' ? 'groupChat.server.loadFailed'
: entries.length ? 'devices.companions.stale' : 'devices.resources.loadFailed';
const retrying = roster.refreshing || groups.refreshing;
const showError = useDelayedConnectionNotice(!!error && focused && visible && !search);
const retry = () => {
- void roster.refresh();
- if (groups.supported) void groups.refresh();
- if (cloud.supported) void refreshCloud();
+ if (roster.error) void roster.refresh();
+ if (groups.error) void groups.refresh();
+ if (cloud.error) void refreshCloud();
};
// A first read with nothing cached stays out of the way instead of flashing an empty section.
const shown = visible && (search ? entries.length > 0 : !!error || !(!entries.length && (!canCreate || roster.loading)));
diff --git a/apps/mobile/src/session/MobileOutboxBridge.tsx b/apps/mobile/src/session/MobileOutboxBridge.tsx
index 8944c38e8c..e477dbcab0 100644
--- a/apps/mobile/src/session/MobileOutboxBridge.tsx
+++ b/apps/mobile/src/session/MobileOutboxBridge.tsx
@@ -1,4 +1,5 @@
import { readChatReplyQuote } from '@cindy/maker-shared/chat-reply-quote';
+import { useChatOutboxDelivery } from '@/chat/useChatOutboxDelivery';
import { useEffect, useRef, useSyncExternalStore } from "react";
import { Alert, AppState } from "react-native";
import { useAuth } from "@/auth/AuthContext";
@@ -75,6 +76,7 @@ export function MobileOutboxBridge() {
const runnerRef = useRef<ReturnType<
typeof createDurableOutboxDelivery
> | null>(null);
+ useChatOutboxDelivery(accountId);
useEffect(() => {
try {
initializeComposerAttachmentStage();
diff --git a/apps/mobile/src/session/TeammateList.tsx b/apps/mobile/src/session/TeammateList.tsx
index 5f700ddab5..eb620f9f6e 100644
--- a/apps/mobile/src/session/TeammateList.tsx
+++ b/apps/mobile/src/session/TeammateList.tsx
@@ -63,7 +63,8 @@ export function useTeammateEntries(items: readonly HostedRemoteCollectionItem[],
const bots = orderedTeammates(items, query, i18n.language).map((row) => ({ kind: 'bot' as const, row }));
if (!groups) return bots;
const chats = orderedBotGroups(groups, query, i18n.language).map((row) => ({ kind: 'group' as const, row }));
- return [...bots, ...chats].sort((a, b) => (b.row.item.display.timestamp ?? 0) - (a.row.item.display.timestamp ?? 0));
+ return [...bots, ...chats].sort((a, b) => (b.row.item.display.timestamp ?? 0) - (a.row.item.display.timestamp ?? 0)
+ || a.row.key.localeCompare(b.row.key));
}, [groups, items, query, i18n.language]);
}
diff --git a/apps/mobile/src/session/durableOutbox.ts b/apps/mobile/src/session/durableOutbox.ts
index 1da3f6c715..5bf201e6ad 100644
--- a/apps/mobile/src/session/durableOutbox.ts
+++ b/apps/mobile/src/session/durableOutbox.ts
@@ -21,6 +21,17 @@ export interface DurableOutboxRecord {
/** Canonical realm-qualified auth accountKey; unqualified pre-release rows are never claimed. */
accountId: string;
deviceId: string;
+ /** Direct Chat Server destination; an empty deviceId never routes to a computer. */
+ chat?: {
+ roomId: string;
+ input: import('../chat/chatServerClient').ChatSendInput;
+ body?: import('../chat/chatServerClient').ChatSendBody;
+ messageId?: string;
+ quote?: import('@cindy/maker-shared/botGroupChat').BotGroupQuoteView;
+ after: number;
+ /** Server cursor; `after` above is only the local displayed row position. */
+ afterServerSequence?: string;
+ };
/** Permanent resource identity for sends queued from a companion, including after page exit/restart. */
resourceRef?: import('@cindy/device-link').RemoteResourceRef;
/** Stable disk/file identity when a cancelled creation is retried with a fresh session ID. */
@@ -244,7 +255,7 @@ export function createDurableOutbox(storage: OutboxStorage, reconcileDraft?: (
return ready;
},
async add(record: DurableOutboxRecord) {
- if (!record.accountId || !record.deviceId)
+ if (!record.accountId || (!record.deviceId && !validChatDestination(record)))
throw new Error("OUTBOX_OWNER_REQUIRED");
await store.ready();
if (records.some((r) => keyFor(r) === keyFor(record)))
@@ -279,7 +290,7 @@ function isLoadableOutboxRecord(
const row = record as DurableOutboxRecord;
return row.version === 1
&& row.accountId === owner
- && !!row.deviceId
+ && (row.chat === undefined ? !!row.deviceId : validChatDestination(row))
&& !!row.item?.sessionId
&& !!row.item.clientId
&& (row.resourceRef === undefined || (row.resourceRef !== null
@@ -299,6 +310,18 @@ function isLoadableOutboxRecord(
&& Array.isArray(row.item.attachmentSlots);
}
+function validChatDestination(row: DurableOutboxRecord): boolean {
+ const chat = row.chat;
+ if (chat?.afterServerSequence !== undefined && !/^[1-9][0-9]{0,18}$/.test(chat.afterServerSequence)) return false;
+ return !!chat && row.deviceId === '' && typeof chat.roomId === 'string' && !!chat.roomId
+ && row.item?.sessionId === chat.roomId && chat.input?.clientId === row.item.clientId
+ && typeof chat.input.text === 'string' && typeof chat.input.mentions?.all === 'boolean'
+ && Array.isArray(chat.input.mentions.botIds) && chat.input.mentions.botIds.every(id => typeof id === 'string')
+ && (chat.input.threadRootId === undefined || typeof chat.input.threadRootId === 'string')
+ && (!chat.body || (chat.body.operationId === row.item.clientId
+ && Array.isArray(chat.body.content) && Array.isArray(chat.body.mentions)));
+}
+
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/mobileOutboxSessionAdapter.ts b/apps/mobile/src/session/mobileOutboxSessionAdapter.ts
index ffdccd026f..f2e8f9e004 100644
--- a/apps/mobile/src/session/mobileOutboxSessionAdapter.ts
+++ b/apps/mobile/src/session/mobileOutboxSessionAdapter.ts
@@ -80,7 +80,7 @@ export function createOutboxSessionAccess(deps: OutboxSessionAccessDeps) {
return read;
};
const canRun = (record: DurableOutboxRecord) =>
- deps.isForeground() &&
+ !record.chat && deps.isForeground() &&
(hidden(record) ||
isDurableOutboxSettled(record) ||
(!record.suspended &&
@@ -115,6 +115,7 @@ export function createOutboxMessageLeases(deps: OutboxMessageLeaseDeps) {
if (!deps.isCurrent()) return;
const keys = new Set<string>();
for (const record of deps.getRecords()) {
+ if (record.chat) continue;
if (isDurableOutboxSettled(record) || deps.hidden(record)) continue;
if (deps.restoreEditable(record)) continue;
if (record.creation?.cancelled) {
diff --git a/apps/mobile/src/session/remoteHistoryDiskCache.ts b/apps/mobile/src/session/remoteHistoryDiskCache.ts
index 565cf9b8cd..6d5ece6ee1 100644
--- a/apps/mobile/src/session/remoteHistoryDiskCache.ts
+++ b/apps/mobile/src/session/remoteHistoryDiskCache.ts
@@ -27,6 +27,35 @@ export function historyDiskAuthority(deviceId: string, sessionId: string) {
}
type Authority = ReturnType<typeof historyDiskAuthority>;
+/** Chat Server pages share the same account-scoped disk and logout/delete fences. */
+export async function readConversationDisk<T>(authority: Authority, validate: (value: unknown) => value is T): Promise<T | null> {
+ if (!authority.current()) return null;
+ try {
+ const text = await (await disk()).read(authority.key, authority.current);
+ const value: unknown = text ? JSON.parse(text) : null;
+ return authority.current() && validate(value) ? value : null;
+ } catch { return null; }
+}
+
+export async function writeConversationDisk(authority: Authority, value: unknown): Promise<boolean> {
+ if (!authority.current()) return false;
+ if (historyValueBytes(value, HISTORY_DISK_ITEM_BYTES) > HISTORY_DISK_ITEM_BYTES) return false;
+ try { return await (await disk()).write(authority.key, JSON.stringify(value), authority.current); }
+ catch { return false; }
+}
+
+export function clearConversationDisk(roomId: string): Promise<void> {
+ const owner = getMobileAuthOwner();
+ const realm = getActiveMobileSessionRealm();
+ const matches = (key: string) => {
+ try { const [region, account, device, session] = JSON.parse(key); return region === realm && account === owner.accountId
+ && device === 'chat-server' && JSON.parse(session)[0] === roomId; }
+ catch { return false; }
+ };
+ for (const [key, value] of keyEpochs) if (matches(key)) keyEpochs.set(key, value + 1);
+ return disk().then(cache => cache.clear(matches)).catch(() => undefined);
+}
+
function validSummary(value: unknown, depth = 0): boolean {
if (!value || typeof value !== 'object' || depth > 32) return false;
const s = value as Record<string, unknown>;
diff --git a/apps/mobile/src/session/teammateNavigation.ts b/apps/mobile/src/session/teammateNavigation.ts
index 3eb0cc94ab..dd8225bffb 100644
--- a/apps/mobile/src/session/teammateNavigation.ts
+++ b/apps/mobile/src/session/teammateNavigation.ts
@@ -94,5 +94,6 @@ export function orderedTeammates(items: readonly HostedRemoteCollectionItem[], q
if (needle && !title.normalize('NFKC').toLocaleLowerCase(locale).includes(needle)) continue;
unique.set(JSON.stringify(identity), row);
}
- return [...unique.values()].sort((a, b) => (b.item.display.timestamp ?? 0) - (a.item.display.timestamp ?? 0));
+ return [...unique.values()].sort((a, b) => (b.item.display.timestamp ?? 0) - (a.item.display.timestamp ?? 0)
+ || a.key.localeCompare(b.key));
}
diff --git a/apps/mobile/src/session/useBotGroupChat.ts b/apps/mobile/src/session/useBotGroupChat.ts
index 476c93f8f5..332f8e7fb8 100644
--- a/apps/mobile/src/session/useBotGroupChat.ts
+++ b/apps/mobile/src/session/useBotGroupChat.ts
@@ -1,9 +1,12 @@
import { useChatServerGroup } from '@/chat/useChatServer';
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { AppState } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { useTranslation } from 'react-i18next';
-import type { RemoteActionInvokeResponse } from '@cindy/device-link';
+import type { RemoteActionInvokeResponse, RemoteResource } from '@cindy/device-link';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { useRevokedDevices } from '@/device-link/revokedDevicesStore';
+import { clearHistoryDisk, historyDiskAuthority, readConversationDisk, writeConversationDisk } from './remoteHistoryDiskCache';
import { BOT_GROUP_REMOTE_COLLECTION_ID, type BotGroupRemoteActionId, type BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';
import { useAuth } from '@/auth/AuthContext';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
@@ -23,6 +26,8 @@ export type BotGroupChatState =
/** Pushes for one change arrive in bursts (messages, round, plan); read once per burst. */
const PUSH_COALESCE_MS = 150;
const READ_RECOVERY_MS = 30_000;
+let cacheOwner = getMobileAuthOwner();
+const cachedGroups = new Map<string, BotGroupRemoteChatData>();
/**
* One group as the computer sees it (docs/product-rules/bot-group-chat.md §8). Every change
@@ -34,18 +39,45 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,
const server = useChatServerGroup(groupId, !host.deviceId, threadRootId);
const { invoke, openLink, status, connectionEpoch, presenceVersion, getPresenceAvailability, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();
const { accountGeneration } = useAuth();
+ const revoked = useRevokedDevices().has(host.deviceId);
+ if (!isMobileAuthOwnerCurrent(cacheOwner)) { cacheOwner = getMobileAuthOwner(); cachedGroups.clear(); }
+ const namespace = `remote-group:${host.deviceId}`;
+ const cacheKey = JSON.stringify([host.deviceId, groupId]);
const { i18n } = useTranslation();
const identity = JSON.stringify([accountGeneration, host.deviceId, groupId]);
const identityRef = useRef(identity); identityRef.current = identity;
- const [state, setState] = useState<{ identity: string; value: BotGroupChatState }>({ identity, value: { kind: 'loading' } });
+ const [state, setState] = useState<{ identity: string; value: BotGroupChatState }>(() => ({ identity,
+ value: !revoked && cachedGroups.has(cacheKey) ? { kind: 'ready', group: cachedGroups.get(cacheKey)! } : { kind: 'loading' } }));
// A queued read may fail before React commits the previous successful snapshot.
const recovery = useRef({ identity, hasGroup: false });
if (recovery.current.identity !== identity) recovery.current = { identity, hasGroup: false };
const recoveryControl = useRef<{ identity: string; clear: () => void; schedule: () => void } | null>(null);
+ const fresh = useRef(0);
+ useEffect(() => {
+ if (!host.deviceId || !groupId) return;
+ if (revoked) {
+ fresh.current++; cachedGroups.delete(cacheKey); void clearHistoryDisk(namespace, groupId);
+ setState({ identity, value: { kind: 'missing' } }); return;
+ }
+ let cancelled = false;
+ const revision = fresh.current;
+ const authority = historyDiskAuthority(namespace, groupId);
+ void readConversationDisk(authority, (value): value is RemoteResource => {
+ if (!value || typeof value !== 'object' || !('blocks' in value)) return false;
+ return botGroupChatDataFromResource(value as RemoteResource)?.id === groupId;
+ }).then(resource => {
+ if (!resource || cancelled || !authority.current() || revision !== fresh.current || identityRef.current !== identity) return;
+ const group = botGroupChatDataFromResource(resource)!;
+ cachedGroups.set(cacheKey, group); recovery.current.hasGroup = true;
+ setState({ identity, value: { kind: 'ready', group } });
+ });
+ return () => { cancelled = true; };
+ }, [cacheKey, namespace, groupId, host.deviceId, identity, revoked]);
const read = useCallback(async (isStale: () => boolean) => {
const owner = identity;
- const valid = () => !isStale() && identityRef.current === owner;
+ const authority = historyDiskAuthority(namespace, groupId);
+ const valid = () => !isStale() && identityRef.current === owner && authority.current();
if (recoveryControl.current?.identity === owner) recoveryControl.current.clear();
if (!host.deviceId || !groupId) {
setState({ identity: owner, value: { kind: 'missing' } });
@@ -57,11 +89,14 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,
if (!valid()) return;
const group = botGroupChatDataFromResource(resource);
if (!group || group.id !== groupId) throw new Error('INVALID_GROUP_DATA');
+ fresh.current++; cachedGroups.set(cacheKey, group);
+ void writeConversationDisk(authority, resource);
recovery.current.hasGroup = true;
setState({ identity: owner, value: { kind: 'ready', group } });
} catch (error) {
if (!valid()) return;
- if (botGroupErrorCode(error) === 'NOT_FOUND') {
+ if (['NOT_FOUND', 'PERMISSION_DENIED'].includes(botGroupErrorCode(error) ?? '')) {
+ fresh.current++; cachedGroups.delete(cacheKey); void clearHistoryDisk(namespace, groupId);
recovery.current.hasGroup = false;
setState({ identity: owner, value: { kind: 'missing' } });
return;
@@ -75,7 +110,7 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,
|| code === 'SERVICE_ERROR' || code === 'CHAT_UNAVAILABLE' || code === 'HOST_NOT_READY')
&& recoveryControl.current?.identity === owner) recoveryControl.current.schedule();
}
- }, [groupId, host, i18n.language, identity, invoke, openLink]);
+ }, [cacheKey, namespace, groupId, host, i18n.language, identity, invoke, openLink]);
const request = useRemoteSyncCoordinator((run) => read(run.isStale), identity);
const reload = useCallback(() => { void request({ reason: 'changed' }); }, [request]);
@@ -134,15 +169,19 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,
if (actionId === 'hide' && identityRef.current === identity) {
await server.acceptListState((receipt.result as { listState?: unknown } | undefined)?.listState);
}
+ if (['hide', 'delete', 'leave'].includes(actionId) && identityRef.current === identity) {
+ fresh.current++; cachedGroups.delete(cacheKey); void clearHistoryDisk(namespace, groupId);
+ setState({ identity, value: { kind: 'missing' } });
+ }
return receipt;
} finally {
// A refused action usually means the phone's copy is stale (PLAN_CLOSED, PLAN_OPEN): re-read either way.
// A deleted group is left by the screen instead.
if (actionId !== 'delete' && actionId !== 'read' && identityRef.current === identity) reload();
}
- }, [groupId, host, i18n.language, identity, invoke, openLink, reload, server.acceptListState]);
+ }, [cacheKey, namespace, groupId, host, i18n.language, identity, invoke, openLink, reload, server.acceptListState]);
- const value: BotGroupChatState = !host.deviceId || !groupId || server.isListHidden()
+ const value: BotGroupChatState = !host.deviceId || !groupId || server.isListHidden() || revoked
? { kind: 'missing' }
: state.identity === identity ? state.value : { kind: 'loading' };
const markRead = useCallback(async (messageIds: string[]) => {
@@ -155,5 +194,6 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string,
void presenceVersion;
// Unknown presence still allows actions; the host answers or the link reports offline.
const online = status === 'online' && !!host.deviceId && getPresenceAvailability(host.deviceId) !== false;
- return !host.deviceId ? { ...server, server: true } : { state: value, reload, act, online, server: false, listHidden: server.listHidden, loadOlder: undefined, loadingOlder: false, media: undefined, markRead };
+ return !host.deviceId ? { ...server, server: true } : { state: value, reload, act, online, server: false, listHidden: server.listHidden, loadOlder: undefined, loadingOlder: false, media: undefined, markRead,
+ pending: [], pendingAction: undefined, canQueue: false };
}
diff --git a/apps/mobile/src/session/useCachedCompanionSession.ts b/apps/mobile/src/session/useCachedCompanionSession.ts
new file mode 100644
index 0000000000..21bdb7c147
--- /dev/null
+++ b/apps/mobile/src/session/useCachedCompanionSession.ts
@@ -0,0 +1,20 @@
+import { useEffect, useSyncExternalStore } from 'react';
+import { useAuth } from '@/auth/AuthContext';
+import { getMobileAuthOwner, isMobileAuthOwnerCurrent } from '@/auth/authOwnerGeneration';
+import { useRevokedDevices } from '@/device-link/revokedDevicesStore';
+import { cachedBotIdForSession, cachedBotItem, readRemoteResourceSnapshot,
+ remoteResourceCacheRevision, subscribeRemoteResourceCache } from '@/device-link/remoteResourceCache';
+
+/** An exact saved conversation link supplies presentation, never dispatch authority. */
+export function useCachedCompanionSession(deviceId: string, sessionId: string) {
+ const { user, accountGeneration } = useAuth();
+ const owner = getMobileAuthOwner();
+ const revoked = useRevokedDevices();
+ useSyncExternalStore(subscribeRemoteResourceCache, remoteResourceCacheRevision);
+ useEffect(() => {
+ if (user?.id && isMobileAuthOwnerCurrent(owner)) void readRemoteResourceSnapshot(user.id);
+ }, [user?.id, accountGeneration]);
+ if (!user?.id || !isMobileAuthOwnerCurrent(owner) || owner.accountId !== user.id || !deviceId || !sessionId || revoked.has(deviceId)) return null;
+ const botId = cachedBotIdForSession(user.id, 'teammates', deviceId, sessionId);
+ return botId ? cachedBotItem(user.id, 'teammates', deviceId, botId) : null;
+}
diff --git a/apps/mobile/src/session/useRemoteResourceList.ts b/apps/mobile/src/session/useRemoteResourceList.ts
index f860308313..a32a519820 100644
--- a/apps/mobile/src/session/useRemoteResourceList.ts
+++ b/apps/mobile/src/session/useRemoteResourceList.ts
@@ -1,12 +1,14 @@
-import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { AppState } from 'react-native';
import { useFocusEffect } from 'expo-router';
import { useTranslation } from 'react-i18next';
import { useAuth } from '@/auth/AuthContext';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
+import { useRevokedDevices, revokedDevicesStore } from '@/device-link/revokedDevicesStore';
import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';
import {
- cacheRemoteResourceItems, readRemoteResourceSnapshot,
+ cacheRemoteResourceItems, peekRemoteResourceSnapshot, readRemoteResourceSnapshot,
remoteResourceCacheRevision, subscribeRemoteResourceCache,
} from '@/device-link/remoteResourceCache';
import { REMOTE_RESOURCE_STARTUP_TIMEOUT_MS, remoteResourceConnectionState, hasRemoteCollectionCache, isRemoteResourceHostOnline, readRemoteCollectionCache, writeRemoteCollectionCache } from '@/device-link/remoteResourceAvailability';
@@ -20,6 +22,7 @@ import { startBoundedStartupRead } from './mobileHomeStartup';
/** One roster reader for resource routes, home and the picker. Host shards reconcile independently. */
export function useRemoteResourceList(collectionId: string, targets: readonly RemoteResourceHostTarget[], enabled = true) {
const { user, accountGeneration } = useAuth();
+ const revoked = useRevokedDevices();
const { t, i18n } = useTranslation();
const { connectionEpoch, status, presenceVersion, getPresenceAvailability, invoke, openLink,
onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();
@@ -27,11 +30,15 @@ export function useRemoteResourceList(collectionId: string, targets: readonly Re
const owner = `${user?.id ?? ''}:${accountGeneration}`;
const binding = JSON.stringify([owner, collectionId]);
const bindingRef = useRef(binding); bindingRef.current = binding;
+ const freshHosts = useRef<{ binding: string; ids: Set<string> }>({ binding, ids: new Set() });
+ if (freshHosts.current.binding !== binding) freshHosts.current = { binding, ids: new Set() };
+ const localItems = () => hasRemoteCollectionCache(owner, collectionId)
+ ? readRemoteCollectionCache(owner, collectionId) : peekRemoteResourceSnapshot(user?.id ?? '')?.items[collectionId] ?? [];
const [hydrated, setHydrated] = useState('');
const [state, setState] = useState<{
binding: string; items: HostedRemoteCollectionItem[]; replies: Record<string, number>;
settled: boolean; loading: boolean; refreshing: boolean; error: string | null;
- }>(() => ({ binding, items: readRemoteCollectionCache(owner, collectionId), replies: {}, settled: hasRemoteCollectionCache(owner, collectionId), loading: true, refreshing: false, error: null }));
+ }>(() => ({ binding, items: localItems(), replies: {}, settled: hasRemoteCollectionCache(owner, collectionId), loading: true, refreshing: false, error: null }));
const generation = useRef(0);
const active = useRef(false);
const focusController = useRef(new AbortController());
@@ -44,14 +51,26 @@ export function useRemoteResourceList(collectionId: string, targets: readonly Re
useEffect(() => {
generation.current += 1;
let cancelled = false;
- const cached = readRemoteCollectionCache(owner, collectionId);
+ const cached = localItems();
setState({ binding, items: cached, replies: {}, settled: hasRemoteCollectionCache(owner, collectionId), loading: true, refreshing: false, error: null });
const cacheRead = startBoundedStartupRead(readRemoteResourceSnapshot(user?.id ?? ''), { home: [], items: {}, read: {} });
// A slow local cache must not hold up live reads. A late cache never replaces a fresh roster.
- void cacheRead.initial.then(({ value: snapshot }) => {
+ const restore = (snapshot: Awaited<ReturnType<typeof readRemoteResourceSnapshot>>) => {
if (cancelled || bindingRef.current !== binding) return;
- setState((current) => ({ ...current, items: current.items.length ? current.items : snapshot.items[collectionId] ?? [] }));
+ setState(current => {
+ // A fast computer must not suppress the saved rows of a slower one.
+ // Conversely, a fresh empty shard is a deletion and must never be restored.
+ const present = new Set(current.items.map(row => row.host.deviceId));
+ const missing = (snapshot.items[collectionId] ?? []).filter(row => !revokedDevicesStore.has(row.host.deviceId) && !present.has(row.host.deviceId)
+ && !freshHosts.current.ids.has(row.host.deviceId));
+ return missing.length ? { ...current, items: [...current.items, ...missing] } : current;
+ });
+ };
+ void cacheRead.initial.then(({ value: snapshot, timedOut }) => {
+ if (cancelled || bindingRef.current !== binding) return;
+ restore(snapshot);
setHydrated(binding);
+ if (timedOut) void cacheRead.completion.then(result => { if (result.ok) restore(result.value); });
});
return () => { cancelled = true; generation.current += 1; };
}, [binding, collectionId, owner, user?.id]);
@@ -100,12 +119,14 @@ export function useRemoteResourceList(collectionId: string, targets: readonly Re
if (!response || !Array.isArray(response.items)) throw new Error(t('devices.resources.loadFailed'));
const next = normalizeRemoteCollectionItems(response, collectionId).map(item => ({ host, item,
key: JSON.stringify([host.deviceId, item.ref.collectionId, item.ref.kind, item.ref.id]) }));
+ freshHosts.current.ids.add(host.deviceId);
setState(old => ({ ...old,
items: mergeRemoteCollectionHostShards(old.items, next, new Set([host.deviceId]), targets),
replies: { ...old.replies, [host.deviceId]: connectionEpoch },
}));
} catch (error) {
if (!current()) return;
+ mobileDebugLog('warn', 'recovery', 'companion-roster-refresh', { source: 'computer-list', collectionId });
failures.push(error);
if (isAutoRecoveringRemoteError(error)) failedHosts.current.add(host.deviceId);
}
@@ -159,11 +180,12 @@ export function useRemoteResourceList(collectionId: string, targets: readonly Re
return () => { stop(); foreground.remove(); off(); cleanups.forEach((cleanup) => cleanup()); };
}, [collectionId, enabled, onRemoteResourceChanged, refresh, requestRefresh, status, subscribe, targets, unsubscribe]));
const ownState = state.binding === binding;
+ const visibleItems = useMemo(() => revoked.size ? state.items.filter(row => !revoked.has(row.host.deviceId)) : state.items, [state.items, revoked]);
const isOnline = useCallback((host: RemoteResourceHostTarget) => ownState && isRemoteResourceHostOnline(
status, getPresenceAvailability(host.deviceId), state.replies[host.deviceId], connectionEpoch,
), [connectionEpoch, getPresenceAvailability, ownState, presenceKey, state.replies, status]);
return {
- items: ownState ? state.items : [],
+ items: ownState ? visibleItems : [],
// A disk snapshot is still unverified on a cold mount. Keep the first
// screen in its loading state until a live collection read settles; after
// that, background refreshes continue to leave the current rows visible.
diff --git a/apps/mobile/src/session/useRemoteResourceSession.ts b/apps/mobile/src/session/useRemoteResourceSession.ts
index b81f79a678..9c92ad0f25 100644
--- a/apps/mobile/src/session/useRemoteResourceSession.ts
+++ b/apps/mobile/src/session/useRemoteResourceSession.ts
@@ -10,17 +10,19 @@ import { readRemoteCollectionCache } from '@/device-link/remoteResourceAvailabil
import { createRemoteReadRecovery } from '@/device-link/remoteReadRecovery';
import { createRemoteSyncCoordinator, retryRemoteSyncRead, type RemoteSyncRun } from '@/device-link/remoteSyncTask';
import { isAutoRecoveringRemoteError, formatRemoteError } from '@/device-link/remoteStatus';
-import { markRemoteResourceRead } from '@/device-link/remoteResourceCache';
+import { forgetRemoteResource, markRemoteResourceRead } from '@/device-link/remoteResourceCache';
import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';
import { remoteSessionStore } from './remoteSessionStore';
import type { RemoteSession } from './types';
+import { useCachedCompanionSession } from './useCachedCompanionSession';
/** Follow a companion's current host-owned task on focus/reconnect, retaining its permanent identity. */
export function useRemoteResourceSession(deviceId: string, deviceName: string, sessionId: string, canMarkRead: boolean, metadataVerified = false) {
const params = useLocalSearchParams<{ resourceCollectionId?: string; resourceId?: string; resourceKind?: string; openSearch?: string; resourceHistorySessionId?: string }>();
- const collectionId = typeof params.resourceCollectionId === 'string' ? params.resourceCollectionId : '';
- const resourceId = typeof params.resourceId === 'string' ? params.resourceId : '';
- const resourceKind = typeof params.resourceKind === 'string' ? params.resourceKind : '';
+ const savedCompanion = useCachedCompanionSession(deviceId, sessionId);
+ const collectionId = typeof params.resourceCollectionId === 'string' ? params.resourceCollectionId : savedCompanion ? 'teammates' : '';
+ const resourceId = typeof params.resourceId === 'string' ? params.resourceId : savedCompanion?.ref.id ?? '';
+ const resourceKind = typeof params.resourceKind === 'string' ? params.resourceKind : savedCompanion?.ref.kind ?? '';
const historyEntry = params.openSearch === '1';
const transcriptEntry = params.resourceHistorySessionId === sessionId;
const { invoke, openLink, connectionEpoch, status, onRemoteResourceChanged, subscribe, unsubscribe } = useDeviceLink();
@@ -39,7 +41,8 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, s
const retry = useCallback(() => setAttempt(value => value + 1), []);
const cached = readRemoteCollectionCache(`${user?.id ?? ''}:${accountGeneration}`, collectionId)
.find(row => row.host.deviceId === deviceId && row.item.ref.id === resourceId && row.item.ref.kind === resourceKind)?.item;
- const resource = display?.identity === identity ? display.resource : cached ?? null;
+ const savedMatches = savedCompanion?.ref.id === resourceId && savedCompanion.ref.kind === resourceKind && collectionId === 'teammates';
+ const resource = display?.identity === identity ? display.resource : cached ?? (savedMatches ? savedCompanion : null);
const stage = (display?.identity === identity
? display.resource.blocks?.find(block => block.id === 'invitation' && block.primitive === 'status')?.data as { stage?: string } | undefined
: undefined)?.stage;
@@ -122,8 +125,10 @@ export function useRemoteResourceSession(deviceId: string, deviceName: string, s
setFailure({ binding, message: formatRemoteError(error) });
recovery.failed(error);
const code = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;
- if (code === 'NOT_FOUND' || /\[NOT_FOUND\]/.test(String(error))) {
+ const denied = ['NOT_FOUND', 'FORBIDDEN', 'PERMISSION_DENIED', 'ACCESS_REVOKED', 'DEVICE_REVOKED'];
+ if (denied.includes(String(code)) || denied.some(value => String(error).includes(`[${value}]`))) {
setDisplay(null);
+ if (user?.id) void forgetRemoteResource(user.id, resourceId);
// A removed/hidden resource must leave the cached task view immediately.
// The resolver displays the existing unavailable/retry state.
router.replace({ pathname: '/resources/[collectionId]/[resourceId]', params: {
diff --git a/apps/mobile/src/session/useTeammateRoster.ts b/apps/mobile/src/session/useTeammateRoster.ts
index 5d57dec2fa..6b1513ebaa 100644
--- a/apps/mobile/src/session/useTeammateRoster.ts
+++ b/apps/mobile/src/session/useTeammateRoster.ts
@@ -4,6 +4,7 @@ import { REMOTE_RESOURCE_MANIFEST_CHANNEL, type RemoteResourceManifestResponse }
import { useFocusEffect } from 'expo-router';
import { useTranslation } from 'react-i18next';
import { useAuth } from '@/auth/AuthContext';
+import { mobileDebugLog } from '@/debug/mobileDebugLog';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
import { toDeviceListItems } from '@/device-link/devices';
import { useRevokedDevices } from '@/device-link/revokedDevicesStore';
@@ -120,6 +121,7 @@ export function useTeammateRoster(enabled = true) {
});
} catch (cause) {
if (current()) {
+ mobileDebugLog('warn', 'recovery', 'companion-roster-refresh', { source: 'computer-manifest' });
failures.push(cause);
if (isAutoRecoveringRemoteError(cause)) failedHosts.current.add(deviceId);
}
@@ -143,7 +145,10 @@ export function useTeammateRoster(enabled = true) {
groupTargets = targets.filter((target) => advertisingGroups.has(target.deviceId)
|| (!answered.has(target.deviceId) && previousGroupTargets.some((host) => host.deviceId === target.deviceId)));
void cacheRemoteResourceHome(user?.id ?? '', collections);
- } catch (cause) { error = formatRemoteError(cause); failures.push(cause); }
+ } catch (cause) {
+ mobileDebugLog('warn', 'recovery', 'companion-roster-refresh', { source: 'computer-directory' });
+ error = formatRemoteError(cause); failures.push(cause);
+ }
if (!current()) return;
lastCollections.current = { binding, home: collections };
if (!failures.length) recovery.current?.succeeded();
diff --git a/docs/dev-rules/chat-server-local-test.md b/docs/dev-rules/chat-server-local-test.md
index 04e4aed038..7619dc4f8f 100644
--- a/docs/dev-rules/chat-server-local-test.md
+++ b/docs/dev-rules/chat-server-local-test.md
@@ -63,6 +63,30 @@ XDT_CDP_PORT=9239 pnpm restart:desktop:remote --region=global -- --isolated=chat
## 已验证与限制
+### 本地聊天恢复与待发消息
+
+当前客户端在服务器历史之外保存账号隔离的显示快照,不将服务器群时间线写入旧的
+`bot_group_messages`。手机复用现有 HistoryDiskStore 和 durableOutbox;桌面群历史、列表、
+云端伙伴记录与待发消息写入当前账号的本地目录。历史按字节预算保留,未确认的用户待发
+内容不参与历史淘汰。显示快照不能授予发送、读回执或远程控制权限;删除、退群、隐藏及
+已确认的撤权会使相关快照失效,旧账号的迟到请求不能写入新账号。
+
+首页先恢复已知伙伴、群和任务,后台按来源更新。可选电脑名称查询不阻挡云端伙伴列表;
+局部错误只重试失败来源。通知命中当前账号保存的精确伙伴、电脑和任务关系时,直接挂载
+原有聊天页面,由后台验证补齐状态;没有这层记录时保留首次进入检查。
+
+Chat Server 群发送先保存本地待发消息,再交出输入框内容。同一条消息在重试和重启后使用
+同一个 clientId,首次可能发送前冻结 HTTP 内容;收到回执后继续保留记录,直到读到实际
+服务器消息。桌面附件继续使用原有媒体引用,手机群仍沿用当前支持的文本发送能力。
+旧版电脑远程群入口补充了历史恢复,发送仍使用该电脑已有的在线能力;普通伙伴任务继续
+复用其原有持久发送队列。
+
+验收时使用仅测试账号参与的群:发送在线基线,阻断 HTTP 后通过实际输入框发送,确认
+待发气泡与草稿交接;正常退出并重开应用,恢复网络后核对服务器中 clientId 对应消息只有
+一份。再验证返回首页、重新进入、迟到磁盘读与实时删除竞争、切换账号及撤权。通知分别
+检查前台、后台和新进程冷启动,重复同一个通知不能重复入栈。仅注入 HTTP 失败不等于
+设备完全离线;本地系统通知只能验证点击链路,不能证明 APNs/FCM 投递成功。
+
2026-10-03:真实账号的 DEV 界面建群、生成邀请链接、文本消息、真实伙伴回复、Thread 内人和伙伴的回复、表情回应均已操作验证,回复面板亮暗模式已目检。自动集成测试覆盖不同账号的邀请预览/接受、未加入不可读取、一次使用、过期、封禁、入群历史边界,以及 Bot 作为群主/受邀成员。
本次两个真实 DEV 所登录账号分别来自中国大陆企业与 Global 个人身份,已在不切换账号的情况下完成:生成邀请 → 预览 → 接受加入;国内账号群消息实时出现在 Global 窗口,Global 的真实伙伴接话;Global 账号在同一 Thread 回复,国内窗口实时显示本人和伙伴两条回复;同一消息两人点 👍 后两端显示 2 人。真实窗口操作及 API 回读相互核对,不以伙伴自行宣称“连通”作为证据。
diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.ts
index 578abbe786..7dbd0f0256 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -630,6 +630,8 @@ export interface BotGroupPlanEditInput extends BotGroupPlanActionInput {
}
export interface BotGroupGetOptions {
+ /** Local display snapshot only; callers separately request current server state. */
+ cacheOnly?: boolean;
conversationKind?: 'direct';
/** Load messages with a smaller sequence (older page). */
beforeSequence?: number;