Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(group-chat): add dissolution and personal list removal
zqchrisb76c96f89398
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.tsindex b1fc636035..3cfe796579 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts@@ -415,4 +415,28 @@ describe('bot group remote resources', () => {{ kind: 'navigate', target: { kind: 'resource', ref: ref('g9') } },]);});+ it('forwards explicit dissolution and leave separately from compatibility archive/delete', async () => {+ const group = detail({ serverBacked: true, revision: 5, supportsDissolve: true });+ group.members[0] = { ...group.members[0], actorId: 'self', isSelf: true, isOwned: true, role: 'owner' };+ service.getGroup.mockResolvedValue({ ok: true, group });+ await remoteResourceRegistry.invoke(context, { client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID,+ actionId: 'dissolve', resourceRef: ref('g1'), input: { expectedRevision: 5 } });+ expect(service.chatServer.manage).toHaveBeenLastCalledWith({ groupId: 'g1', action: { type: 'dissolve', expectedRevision: 5 } });+ await remoteResourceRegistry.invoke(context, { client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID,+ actionId: 'leave', resourceRef: ref('g1') });+ expect(service.chatServer.manage).toHaveBeenLastCalledWith({ groupId: 'g1', action: { type: 'member', actorId: 'self', action: 'leave' } });+ expect(service.deleteGroup).not.toHaveBeenCalled();+ });+ it('allows personal removal after leave through the account-authorized server service', async () => {+ service.getGroup.mockResolvedValue({ ok: false, errorCode: 'NOT_FOUND' });+ const listState = { conversationId: 'g1', hidden: true, revision: 4 };+ service.chatServer.manage.mockResolvedValue({ ok: true, listState });+ const result = await remoteResourceRegistry.invoke(context, { client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID,+ actionId: 'hide', resourceRef: ref('g1') });+ expect(result.result).toEqual({ listState });+ expect(service.getGroup).not.toHaveBeenCalled();+ expect(service.chatServer.manage).toHaveBeenLastCalledWith({ groupId: 'g1', action: { type: 'hide' } });+ expect(service.deleteGroup).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.tsindex 07c1ce9919..8ec40d6d3f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMembership.test.ts@@ -141,4 +141,54 @@ describe('Chat Server membership notices', () => {expect((await service.continueRound(roomId)).ok).toBe(false);expect(fixture.handle.mock.calls.some(([route]) => route.endsWith('/continue'))).toBe(false);});+ function lifecycle(options: { supported?: boolean; kind?: string; role?: string; ownedBot?: boolean; failHide?: boolean; left?: boolean } = {}) {+ const previous = fixture.handle.getMockImplementation()!;+ fixture.handle.mockImplementation((route, method, body) => {+ if (route === '/me') return { body: { actor: { id: selfId }, ...(options.supported === false ? {} : { capabilities: { groupLifecycleVersion: 1, conversationListStateVersion: 1 } }) } };+ if (route.startsWith('/conversation-list-state?')) return { body: [] };+ if (route.endsWith('/list-state')) return options.failHide ? { status: 409, body: { error: { code: 'REVISION_CONFLICT' } } }+ : { body: { conversationId: roomId, hidden: true, revision: 1 } };+ if (route.endsWith('/dissolve')) return { body: { revision: 2, dissolvedAt: '2026-10-15T00:00:00Z', dissolvedBy: selfId } };+ if (route.endsWith('/snapshot')) {+ if (options.left) return { status: 403, body: { error: { code: 'NOT_MEMBER' } } };+ const result = previous(route, method, body);+ result.body.room = { ...result.body.room, kind: options.kind ?? 'group', revision: 1 };+ result.body.members = [{ id: options.ownedBot ? memberId : selfId, kind: options.ownedBot ? 'bot' : 'human', name: 'Fixture',+ ownerActorId: selfId, state: 'joined', role: options.role ?? 'owner' }];+ return result;+ }+ return previous(route, method, body);+ });+ }+ it('never substitutes archive or delete on an old server', async () => {+ lifecycle({ supported: false });+ expect(await service.chatServer!.manage({ groupId: roomId, action: { type: 'dissolve', expectedRevision: 1 } })).toMatchObject({ ok: false, errorCode: 'LIFECYCLE_UNAVAILABLE' });+ expect(await service.chatServer!.manage({ groupId: roomId, action: { type: 'hide' } })).toMatchObject({ ok: false, errorCode: 'LIFECYCLE_UNAVAILABLE' });+ expect(fixture.handle.mock.calls.some(([route, method]) => method === 'PATCH' || route.endsWith('/dissolve') || route.endsWith('/list-state'))).toBe(false);+ });+ it.each([false, true])('dissolves only a current owned owner (companion=%s), with the edited revision', async ownedBot => {+ lifecycle({ ownedBot });+ expect(await service.chatServer!.manage({ groupId: roomId, action: { type: 'dissolve', expectedRevision: 1 } })).toMatchObject({ ok: true });+ expect(fixture.handle).toHaveBeenCalledWith(`/conversations/${roomId}/dissolve`, 'POST', expect.objectContaining({ expectedRevision: 1, operationId: expect.any(String) }));+ expect(fixture.handle.mock.calls.some(([, method]) => method === 'PATCH')).toBe(false);+ });+ it.each([{ kind: 'direct', code: 'GROUP_REQUIRED' }, { role: 'admin', code: 'OWNER_REQUIRED' }, { role: 'member', code: 'OWNER_REQUIRED' }])('refuses invalid dissolution %j', async ({ code, ...options }) => {+ lifecycle(options);+ expect(await service.chatServer!.manage({ groupId: roomId, action: { type: 'dissolve', expectedRevision: 1 } })).toMatchObject({ ok: false, errorCode: code });+ expect(fixture.handle.mock.calls.some(([route]) => route.endsWith('/dissolve'))).toBe(false);+ });+ it('removes personal history after leave without reading or deleting its forbidden snapshot', async () => {+ lifecycle({ left: true });+ expect(await service.chatServer!.manage({ groupId: roomId, action: { type: 'hide' } })).toMatchObject({ ok: true, listState: { conversationId: roomId, hidden: true, revision: 1 } });+ expect(fixture.handle.mock.calls.some(([route]) => route.endsWith('/snapshot'))).toBe(false);+ expect(changed).toHaveBeenCalledWith(expect.objectContaining({ groupId: roomId, change: 'list', listState: expect.objectContaining({ hidden: true }) }), undefined);+ expect(await service.listGroups()).toMatchObject({ ok: true, groups: [] });+ });+ it('keeps a failed personal removal visible and retryable', async () => {+ lifecycle({ failHide: true });+ expect(await service.chatServer!.manage({ groupId: roomId, action: { type: 'hide' } })).toMatchObject({ ok: false, errorCode: 'REVISION_CONFLICT' });+ expect(changed.mock.calls.some(([event]) => event.change === 'list')).toBe(false);+ expect((await service.getGroup(roomId)).ok).toBe(true);+ });+});diff --git a/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts b/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.tsindex 84c152bf17..9e4c4e1bc1 100644--- a/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts+++ b/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts@@ -352,6 +352,14 @@ export function registerBotGroupRemoteResourceProvider(service: () => BotGroupCh? request.resourceRef.id: null;if (!groupId) throw new RemoteResourceRegistryError('INVALID_PARAMS', 'INVALID_PARAMS');+ // Personal state is authorized by the account's historical membership, even after leave.+ if (actionId === 'hide') {+ const server = ownerService().chatServer;+ if (!server) throw new RemoteResourceRegistryError('INVALID_PARAMS', 'LIFECYCLE_UNAVAILABLE');+ const hidden = await server.manage({ groupId, action: { type: 'hide' } });+ if (!hidden.ok) refuse(chatGroupFailure(new Error(hidden.errorCode)));+ return { result: { listState: hidden.listState }, effects: [{ kind: 'refresh-collection', collectionId: BOT_GROUP_REMOTE_COLLECTION_ID }] };+ }// Every action re-checks that the phone may still see this group, and any teammate it names.const visibleGroup = await readVisibleGroup(groupId);// New controllers bind a write to the snapshot they edited. Older controllers@@ -423,6 +431,18 @@ export function registerBotGroupRemoteResourceProvider(service: () => BotGroupChcase 'add-member':result = await current.setMembers({ groupId, botIds: [input.botId as string], addOnly: true });break;+ case 'dissolve':+ case 'leave': {+ if (!visibleGroup.serverBacked || !current.chatServer)+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'LIFECYCLE_UNAVAILABLE');+ const self = visibleGroup.members.find(member => member.isSelf);+ if (actionId === 'leave' && !self?.actorId) throw new RemoteResourceRegistryError('INVALID_PARAMS', 'NOT_FOUND');+ const receipt = await current.chatServer.manage({ groupId, action: actionId === 'dissolve'+ ? { type: 'dissolve', expectedRevision: input.expectedRevision as number }+ : { type: 'member', action: 'leave', actorId: self!.actorId! } });+ if (!receipt.ok) refuse(chatGroupFailure(new Error(receipt.errorCode)));+ return { effects: [{ kind: 'refresh-collection', collectionId: BOT_GROUP_REMOTE_COLLECTION_ID }] };+ }case 'delete':if (visibleGroup.serverBacked && input.expectedRevision !== undefined) {if (!current.chatServer || !visibleGroup.members.some(member => member.isOwned && member.role === 'owner'))diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex 8c3d7e28e5..79ceef9bb0 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -1,3 +1,4 @@+import { createConversationListState } from '@cindy/maker-shared/chatConversationList';/** Production chat transport. The server owns messages and execution leases;* local group rows only supply Agent lane metadata and the upgrade source. */import { app, net } from 'electron';@@ -52,7 +53,7 @@ interface Message {}interface Room {id: string; name: string; topic: string; description: string; response_mode: 'all' | 'mentioned'; speaking_mode: 'auto' | 'sequential';- created_at: string; updated_at: string; revision: number; archived: boolean; organizer_id?: string | null; kind?: string;+ created_at: string; updated_at: string; revision: number; archived: boolean; dissolved_at?: string | null; organizer_id?: string | null; kind?: string;}interface Snapshot { room: Room; members: Member[]; messages: Message[]; cursor: string }interface Execution {@@ -175,6 +176,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst executorId = `desktop:${randomUUID()}`;let actors: Actor[] = [];let selfId = '';+ let supportsDissolve = false;+ let supportsListRemoval = false;+ const personalList = createConversationListState();+ const syncPersonalList = async () => { if (supportsListRemoval) await personalList.sync(api); };+ personalList.subscribe(row => {+ if (!current()) return;+ 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);+ });// Cloud companions (cloud-companions.md): inert unless the server announces homes.let selfDeviceId: string | null = null;let companionHome = false;@@ -201,6 +212,11 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDpending.delete(sourceId);if (!pending.size) pendingPlanCancels.delete(roomId);}+ function retirePlanning(roomId: string) {+ acceptedIntentVersions.set(roomId, ++nextIntentVersion);+ planning.get(roomId)?.controller.abort(); planning.delete(roomId);+ planIntents.delete(roomId); pendingPlanCancels.delete(roomId);+ }async function replacePlanIntent(roomId: string, version = ++nextIntentVersion) {acceptedIntentVersions.set(roomId, version);const pending = planning.get(roomId);@@ -442,7 +458,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDrefreshActors = (async () => {actorsStale = false;profiles = await getDbClient().drizzle.select().from(botProfiles).where(undefined);- const me = await api<{ actor: Actor; deviceId?: string | null; capabilities?: { groupDiscussionParity?: number; companionHome?: boolean } }>('/me'); selfId = me.actor.id;+ const me = await api<{ actor: Actor; deviceId?: string | null; capabilities?: { groupDiscussionParity?: number; companionHome?: boolean; groupLifecycleVersion?: number; conversationListStateVersion?: number } }>('/me'); selfId = me.actor.id;+ supportsDissolve = me.capabilities?.groupLifecycleVersion === 1;+ supportsListRemoval = me.capabilities?.conversationListStateVersion === 1;groupDiscussionParity = me.capabilities?.groupDiscussionParity === 1;selfDeviceId = typeof me.deviceId === 'string' && me.deviceId ? me.deviceId : null;companionHome = !!deps.companionCloud && me.capabilities?.companionHome === true && !!selfDeviceId;@@ -550,18 +568,23 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDreconnectDelay = 500; connected = true;ws.send(JSON.stringify({ type: 'subscribe', scope: `actor:${selfId}`, after: '0' }));for (const [roomId, cursor] of rooms) ws.send(JSON.stringify({ type: 'subscribe', scope: `conversation:${roomId}`, after: cursor }));- for (const roomId of rooms.keys()) changed(roomId);+ void syncPersonalList().then(() => { if (current() && socket === ws) { for (const roomId of rooms.keys()) changed(roomId); changed(''); } }).catch(() => ws.close());} else if (event.type === 'changes') {// This adapter stores no client history. Each invalidation re-reads authoritative// state; a reconnect resumes after the last cursor this process has read or acked.if (event.scope.startsWith('conversation:')) {const roomId = event.scope.slice(13);+ if ((event.changes ?? []).some((change: { type?: string; data?: { dissolvedAt?: unknown } }) => change.type === 'conversation.updated' && change.data?.dissolvedAt)) retirePlanning(roomId);if (rooms.has(roomId)) advanceRoom(roomId, event.cursor);changed(roomId);for (const run of running.values()) if (run.execution.conversation_id === roomId) void checkLease(run);}else {- for (const change of event.changes ?? []) if (change.type === 'membership.changed') changed(change.entityId);+ for (const change of event.changes ?? []) {+ if (change.type === 'conversation.list.changed') personalList.merge(change.data);+ if (change.type === 'conversation.updated' && change.data?.dissolvedAt) retirePlanning(change.entityId);+ if (change.type === 'membership.changed' || change.type === 'conversation.updated') changed(change.entityId);+ }if (companionHome && (event.changes ?? []).some((change: { type?: unknown }) => change?.type === 'actor.changed')) void refreshHomes();changed('');}@@ -593,6 +616,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDasync function snapshot(roomId: string) {id.parse(roomId); await register();const value = await api<Snapshot>(`/conversations/${roomId}/snapshot`);+ if (value.room.dissolved_at) retirePlanning(roomId);subscribe(roomId, value.cursor);return value;}@@ -726,7 +750,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst messages = summaryOnly ? [] : (await messageViews(roomId, page, s.members)).sort((a, b) => a.sequence - b.sequence);const last = s.messages[0];const lastView = last ? messageView(last, s.members) : null;- return { serverBacked: true, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), id: s.room.id, name: s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,+ return { serverBacked: true, supportsGroupLeave: true, supportsDissolve, supportsListRemoval, dissolvedAt: s.room.dissolved_at ?? null, migrationPending: [...upgradeErrors.keys()].some(source => upgradedGroups.get(source) === roomId), archived: s.room.archived, selfActorId: selfId, topic: s.room.topic, description: s.room.description, revision: s.room.revision, canInvite: !s.room.dissolved_at && s.members.some(m => m.ownerActorId === selfId && m.state === 'joined' && ['owner', 'admin'].includes(m.role)), id: s.room.id, name: s.room.name, replyMode: s.room.response_mode, speakingMode: s.room.speaking_mode,members: s.members.filter(m => m.state === 'joined').map(m => {const p = localBot(m.id);return { botId: p?.id ?? m.id, actorId: m.id, actorKind: m.kind, isSelf: m.id === selfId,@@ -1309,8 +1333,29 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDactorAction.extend({ type: z.literal('member'), action: z.enum(['invite', 'leave', 'remove', 'ban', 'unban', 'role']), role: z.enum(['admin', 'member']).optional() }).strict(),actorAction.extend({ type: z.literal('transfer') }).strict(),actorAction.extend({ type: z.literal('botAccess'), access: z.enum(['none', 'chat', 'tools']), expectedRevision: z.number().int().positive() }).strict(),+ z.object({ type: z.literal('hide') }).strict(),+ z.object({ type: z.literal('dissolve'), expectedRevision: z.number().int().positive() }).strict(),z.object({ type: z.literal('archive'), archived: z.boolean(), expectedRevision: z.number().int().positive() }).strict(),]).parse(input.action);+ if (action.type === 'hide') {+ if (!supportsListRemoval) throw new Error('LIFECYCLE_UNAVAILABLE');+ // Deliberately no snapshot read: historical members can remove after leaving.+ await personalList.setHidden(api, target, true, randomUUID());+ changed(target); return { listState: personalList.get(target) };+ }+ if (action.type === 'dissolve') {+ if (!supportsDissolve) throw new Error('LIFECYCLE_UNAVAILABLE');+ const s = await snapshot(target);+ if (s.room.kind !== 'group') throw new Error('GROUP_REQUIRED');+ const owner = s.members.find(m => m.state === 'joined' && m.role === 'owner' && (m.id === selfId || m.ownerActorId === selfId));+ if (!owner) throw new Error('OWNER_REQUIRED');+ z.object({ revision: z.number().int().positive(), dissolvedAt: z.string().refine(value => Number.isFinite(Date.parse(value))), dissolvedBy: id })+ .parse(await api(`/conversations/${target}/dissolve`, 'POST', { operationId: randomUUID(), expectedRevision: action.expectedRevision }, owner.id));+ // Server settles executions and plans. Fence local planning without another write.+ retirePlanning(target);+ for (const run of running.values()) if (run.execution.conversation_id === target) void checkLease(run);+ changed(target); return {};+ }const { type, ...payload } = action;const route = type === 'update' || type === 'archive' ? '' : type === 'member' ? '/members' : type === 'botAccess' ? '/bot-access' : `/${type}`;const asManager = type === 'update' || type === 'archive' || type === 'transfer' || (type === 'member' && !['leave', 'invite'].includes(action.action));@@ -1448,19 +1493,25 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDreturn {chatServer,listGroups: () => safe(async () => {- await register(); beginUpgrade();+ await register(); await syncPersonalList(); beginUpgrade();const groups: BotGroupDetail[] = [];let after: string | undefined;do {const page = await api<Array<Room & { state: string }>>(`/conversations?limit=100${after ? `&after=${after}` : ''}`);- const joined = page.filter(r => r.state === 'joined' && r.kind !== 'direct');+ const joined = page.filter(r => r.state === 'joined' && r.kind !== 'direct' && !personalList.hidden(r.id));for (let i = 0; i < joined.length; i += 8)groups.push(...await Promise.all(joined.slice(i, i + 8).map(r => detail(r.id, undefined, true))));after = page.length === 100 ? page.at(-1)!.id : undefined;} while (after);- return { ok: true as const, groups };+ 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 };}),- getGroup: (roomId, options) => safe(async () => ({ ok: true as const, group: await detail(await resolveGroup(id.parse(roomId)), options) })),createGroup: input => safe(async () => {const i = groupInput.parse(input); await register(); beginUpgrade();const participants = i.botIds.map(botId => {diff --git a/apps/desktop/src/main/maker-ipc/chatServerErrors.ts b/apps/desktop/src/main/maker-ipc/chatServerErrors.tsindex 2435d95d06..69b8db2356 100644--- a/apps/desktop/src/main/maker-ipc/chatServerErrors.ts+++ b/apps/desktop/src/main/maker-ipc/chatServerErrors.ts@@ -15,7 +15,7 @@ export function chatGroupFailure(error: unknown): BotGroupFailure {let errorCode: BotGroupErrorCode;if (['PLAN_OPEN', 'PLAN_CLOSED', 'MENTION_UNAVAILABLE', 'MEMBER_LIMIT', 'MEMBER_UNAVAILABLE', 'HOST_NOT_READY','INVALID_ATTACHMENT', 'ATTACHMENT_UNAVAILABLE', 'ATTACHMENT_TOO_LARGE', 'MEDIA_UPLOAD_FAILED',- 'AUTH_REQUIRED', 'IMPORT_PENDING', 'REQUEST_TIMEOUT', 'REVISION_CONFLICT', 'QUOTE_UNAVAILABLE'].includes(code)) errorCode = code as BotGroupErrorCode;+ 'LIFECYCLE_UNAVAILABLE', 'LAST_OWNER', 'AUTH_REQUIRED', 'IMPORT_PENDING', 'REQUEST_TIMEOUT', 'REVISION_CONFLICT', 'QUOTE_UNAVAILABLE'].includes(code)) errorCode = code as BotGroupErrorCode;else if (code === 'CONVERSATION_NOT_FOUND' || code === 'OWNER_CHANGED') errorCode = 'NOT_FOUND';else if (['ROLE_REQUIRED', 'ACTOR_NOT_OWNED', 'OWNER_REQUIRED'].includes(code) || status === 403) errorCode = 'PERMISSION_DENIED';else if (status === 401) errorCode = 'AUTH_REQUIRED';@@ -24,6 +24,7 @@ export function chatGroupFailure(error: unknown): BotGroupFailure {else if (code.startsWith('FILE_PEER_') || code.startsWith('DEVICE_LINK_')) errorCode = 'ATTACHMENT_UNAVAILABLE';else if (['INVALID_MEDIA_URL', 'MEDIA_STORAGE_UNAVAILABLE', 'UPLOAD_QUOTA', 'UPLOAD_MISMATCH', 'MEDIA_NOT_FOUND', 'UPLOAD_EXPIRED'].includes(code)) errorCode = 'MEDIA_UPLOAD_FAILED';else if (code === 'ENOENT' || code === 'EACCES') errorCode = 'INVALID_ATTACHMENT';+ else if (code === 'CONVERSATION_DISSOLVED') errorCode = 'GROUP_DISSOLVED';else if (code === 'CONVERSATION_ARCHIVED') errorCode = 'GROUP_ARCHIVED';else if (code === 'INVALID_INPUT' || code === 'INVALID_PARAMS') errorCode = 'INVALID_PARAMS';else errorCode = 'SERVICE_ERROR';diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsxindex eaa4713efb..aaa85a45da 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx@@ -1,3 +1,4 @@+import { RemoveChatFromListButton } from './RemoveChatFromListButton';import type { ReactNode } from 'react';/*** 群聊页:顶栏(成员头像、群名、成员名单、群设置入口)+ 多作者时间线 + 输入框。@@ -304,7 +305,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {const unsubscribe =botGroupApi()?.onBotGroupChanged?.((payload, ownerStamp) => {if (!isDataOwnerPushCurrent(ownerStamp) || payload.groupId !== groupId) return;- if (payload.change === 'deleted') {+ if (payload.change === 'deleted' || (payload.change === 'list' && payload.listState?.hidden)) {requestVersion += 1;// Unsent attachments go with the group (staged copies included).discardDraft(botGroupAttachmentScope(groupId));@@ -713,6 +714,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {<ArrowLeft size={14} />{t('bots.backToBot')}</Button>+ {!failed && groupId && <RemoveChatFromListButton key={groupId} groupId={groupId} onRemoved={() => navigate('/bots')} />}{failed ? (<Buttonvariant="cta"@@ -918,7 +920,7 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {</div>)}{sharing ? <ShareSelectionBar sessionId={shareScope} barWidth="100%"- getContentWidth={() => contentRef.current?.querySelector('article')?.getBoundingClientRect().width ?? 760} /> : group.archived ? <p className="border-t border-[var(--border-default)] p-4 text-center text-13 text-[var(--text-tertiary)]">{t('bots.groupChat.server.settings.archived')}</p> : <BotGroupComposer+ getContentWidth={() => contentRef.current?.querySelector('article')?.getBoundingClientRect().width ?? 760} /> : group.archived ? <p className="border-t border-[var(--border-default)] p-4 text-center text-13 text-[var(--text-tertiary)]">{t(group.dissolvedAt ? 'bots.groupChat.lifecycle.dissolved' : 'bots.groupChat.server.settings.archived')}</p> : <BotGroupComposergroupId={group.id}members={group.members}running={running}diff --git a/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx b/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsxindex ebe3e0f1dd..743acccc61 100644--- a/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx+++ b/apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx@@ -15,6 +15,7 @@ import { useBotProfiles } from './botStore';import { BotAvatar } from './BotAvatar';import { chatErrorKey } from './ChatServerControls';import { refreshBotGroups } from './botGroupStore';+import { chatGroupMembership } from '@cindy/maker-shared/botGroupPresentation';const key = (name: string) => `bots.groupChat.server.settings.${name}`;const api = () => window.electronAPI.maker.chatServer;@@ -26,9 +27,13 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {const { confirm } = useConfirmDialog();const profiles = useBotProfiles();const companions = group.members.filter(member => member.actorKind === 'bot');- const me = group.members.find(m => m.isSelf);- const owner = group.members.some(m => m.isOwned && m.role === 'owner');- const manager = owner || group.members.some(m => m.isOwned && m.role === 'admin');+ const membership = chatGroupMembership(group);+ const { self: me } = membership;+ const owner = membership.owner && !group.dissolvedAt;+ const manager = membership.manager && !group.dissolvedAt;+ const canLeave = membership.canLeave && !group.dissolvedAt;+ const mounted = useRef(true);+ useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);const [name, setName] = useState(group.name);const [topic, setTopic] = useState(group.topic ?? '');const [description, setDescription] = useState(group.description ?? '');@@ -60,18 +65,18 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {const owner = getDataOwnerGeneration();try {const result = await api().manage({ groupId: group.id, action });- if (!isDataOwnerGenerationCurrent(owner)) return false;- if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); return false; }+ if (!mounted.current || !isDataOwnerGenerationCurrent(owner)) return false;+ if (!result.ok) { setError(t(chatErrorKey(result.errorCode))); if (result.errorCode === 'REVISION_CONFLICT' && action.type !== 'hide') refreshBotGroups(); return false; }refreshBotGroups();if (exit) navigate('/bots');return true;- } catch { if (isDataOwnerGenerationCurrent(owner)) setError(t(chatErrorKey('REQUEST_FAILED'))); return false; }- finally { busyRef.current = false; setBusy(false); }+ } catch { if (mounted.current && isDataOwnerGenerationCurrent(owner)) setError(t(chatErrorKey('REQUEST_FAILED'))); return false; }+ finally { busyRef.current = false; if (mounted.current) setBusy(false); }}async function confirmed(action: ChatGroupAction, title: string, note: string, exit = false) {const owner = getDataOwnerGeneration();if (await confirm({ presentation: 'standard', title, description: note, confirmText: t(key('confirm')),- cancelText: t('bots.cancel'), confirmVariant: 'destructive' }) && isDataOwnerGenerationCurrent(owner)) await mutate(action, exit);+ cancelText: t('bots.cancel'), confirmVariant: 'destructive' }) && mounted.current && isDataOwnerGenerationCurrent(owner)) await mutate(action, exit);}const profileOpenChange = useCallback((open: boolean) => {setEditingProfile(open);@@ -81,7 +86,7 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {if (!isDataOwnerGenerationCurrent(owner)) return;if (!result.ok) setError(t(chatErrorKey(result.errorCode)));else refreshBotGroups();- }).catch(() => { if (isDataOwnerGenerationCurrent(owner)) setError(t(chatErrorKey('REQUEST_FAILED'))); });+ }).catch(() => { if (mounted.current && isDataOwnerGenerationCurrent(owner)) setError(t(chatErrorKey('REQUEST_FAILED'))); });}}, [t]);async function updateWorkSettings(input: { organizerBotId?: string; projectDir?: string | null }) {@@ -94,7 +99,7 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {if (!result.ok) setError(t('bots.groupChat.settings.projectDirSaveFailed'));else refreshBotGroups();} catch { if (isDataOwnerGenerationCurrent(generation)) setError(t(chatErrorKey('REQUEST_FAILED'))); }- finally { busyRef.current = false; setBusy(false); }+ finally { busyRef.current = false; if (mounted.current) setBusy(false); }}async function chooseProjectDir() {const generation = getDataOwnerGeneration();@@ -147,8 +152,8 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {void mutate({ type: 'nickname', actorId: me!.actorId!, nickname: nickname.trim() || null }).then(ok => { if (ok) nicknameDirty.current = false; });}}><FormField className="min-w-0 flex-1" label={t(key('nickname'))} hint={t(key('nicknameHint'))}>{props =>- <Input {...props} value={nickname} maxLength={40} placeholder={me?.displayName} disabled={busy} onChange={event => { nicknameDirty.current = true; setNickname(event); }} />}</FormField>- <Button className="mb-6" type="submit" size="sm" variant="secondary" disabled={busy || !me}>{t(key('save'))}</Button>+ <Input {...props} value={nickname} maxLength={40} placeholder={me?.displayName} disabled={busy || !!group.dissolvedAt} onChange={event => { nicknameDirty.current = true; setNickname(event); }} />}</FormField>+ <Button className="mb-6" type="submit" size="sm" variant="secondary" disabled={busy || !me || !!group.dissolvedAt}>{t(key('save'))}</Button></form></section>{companions.length > 0 && <section className="space-y-4 border-t border-[var(--border-default)] pt-5">@@ -161,7 +166,7 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {<p className="text-12 text-[var(--text-secondary)]">{t(key('companionOf'), { name: member.ownerName })}</p></div></div>- <ChatBotAccessField groupId={group.id} member={member} disabled={busy} />+ <ChatBotAccessField groupId={group.id} member={member} disabled={busy || !!group.dissolvedAt} />{member.isOwned && profiles.some(bot => bot.id === member.botId) && <Button size="sm" variant="secondary"onClick={() => navigate(`/bots/${encodeURIComponent(member.botId)}?settings=1&settingsPage=capabilities`)}>{t(key('configureCapabilities'))}@@ -198,13 +203,19 @@ export function ChatGroupSettings({ group }: { group: BotGroupSummary }) {</div>}</div>;})}- {addable.length > 0 && <Select label={t(key('addCompanion'))} value="" disabled={busy}+ {!group.dissolvedAt && addable.length > 0 && <Select label={t(key('addCompanion'))} value="" disabled={busy}options={addable.map(bot => ({ value: bot.actorId, label: bot.name }))}onValueChange={actorId => void mutate({ type: 'member', actorId, action: 'invite' })} />}</section>+ {group.dissolvedAt && <p className="text-13 text-[var(--text-secondary)]">{t('bots.groupChat.lifecycle.dissolved')}</p>}<div className="flex flex-wrap gap-2 border-t border-[var(--border-default)] pt-5">- <Button variant="secondary" size="sm" disabled={busy || !me} onClick={() => void confirmed({ type: 'member', actorId: me!.actorId!, action: 'leave' }, t(key('leave')), t(key('leaveHint')), true)}>{t(key('leave'))}</Button>+ {canLeave && <Button variant="secondary" size="sm" disabled={busy} onClick={() => void confirmed({ type: 'member', actorId: me!.actorId!, action: 'leave' }, t(key('leave')), t(key('leaveHint')), true)}>{t(key('leave'))}</Button>}{manager && <Button variant="secondary" size="sm" disabled={busy} onClick={() => void confirmed({ type: 'archive', archived: !group.archived, expectedRevision: group.revision! }, t(key(group.archived ? 'unarchive' : 'archive')), t(key(group.archived ? 'unarchiveHint' : 'archiveHint')))}>{t(key(group.archived ? 'unarchive' : 'archive'))}</Button>}+ {owner && <Button variant="secondary" size="sm" disabled={busy || group.supportsDissolve !== true}+ onClick={() => void confirmed({ type: 'dissolve', expectedRevision: group.revision! }, t('bots.groupChat.lifecycle.dissolve'), t('bots.groupChat.lifecycle.dissolveNote'))}>{t('bots.groupChat.lifecycle.dissolve')}</Button>}+ <Button variant="secondary" size="sm" disabled={busy || group.supportsListRemoval !== true}+ onClick={() => void confirmed({ type: 'hide' }, t('bots.groupChat.lifecycle.hide'), t('bots.groupChat.lifecycle.hideNote'), true)}>{t('bots.groupChat.lifecycle.hide')}</Button>+ {((owner && !group.supportsDissolve) || !group.supportsListRemoval) && <p className="w-full text-12 text-[var(--text-secondary)]">{t('bots.groupChat.lifecycle.unavailable')}</p>}</div></div><ProfileEditDialog open={editingProfile} onOpenChange={profileOpenChange} />diff --git a/apps/desktop/src/renderer/features/bots/RemoveChatFromListButton.tsx b/apps/desktop/src/renderer/features/bots/RemoveChatFromListButton.tsxnew file mode 100644index 0000000000..4bdb5266cc--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/RemoveChatFromListButton.tsx@@ -0,0 +1,33 @@+import { useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Button } from '@/components/ui/button';+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';+import { toast } from '@/lib/toast';+import { chatErrorKey } from './chatError';+import { refreshBotGroups } from './botGroupStore';++/** A historical membership may remove its list entry even when the snapshot is forbidden. */+export function RemoveChatFromListButton({ groupId, onRemoved }: { groupId: string; onRemoved(): void }) {+ const { t } = useTranslation();+ const { confirm } = useConfirmDialog();+ const [busy, setBusy] = useState(false);+ const pending = useRef(false);+ const active = useRef(true);+ useEffect(() => { active.current = true; return () => { active.current = false; }; }, [groupId]);+ return <Button variant="secondary" size="lg" compact disabled={busy} onClick={async () => {+ if (pending.current) return;+ pending.current = true; setBusy(true);+ const owner = getDataOwnerGeneration();+ const current = () => active.current && isDataOwnerGenerationCurrent(owner);+ try {+ if (!await confirm({ presentation: 'standard', title: t('bots.groupChat.lifecycle.hide'), description: t('bots.groupChat.lifecycle.hideNote'),+ confirmText: t('bots.groupChat.lifecycle.hide'), cancelText: t('bots.cancel'), confirmVariant: 'destructive' }) || !current()) return;+ const result = await window.electronAPI.maker.chatServer.manage({ groupId, action: { type: 'hide' } });+ if (!current()) return;+ if (!result.ok) toast.error(t(chatErrorKey(result.errorCode)));+ else { refreshBotGroups(); onRemoved(); }+ } catch { if (current()) toast.error(t(chatErrorKey('REQUEST_FAILED'))); }+ finally { pending.current = false; if (current()) setBusy(false); }+ }}>{t('bots.groupChat.lifecycle.hide')}</Button>;+}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsxindex ad11d8bf9d..d3934a5ab4 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/ChatGroupSettings.test.tsx@@ -14,13 +14,14 @@ vi.mock('../botGroupStore', () => ({ refreshBotGroups: mocks.refresh }));vi.mock('@/contexts/dataOwnerGeneration', () => ({ getDataOwnerGeneration: () => 1, isDataOwnerGenerationCurrent: () => true }));const key = (name: string) => `bots.groupChat.server.settings.${name}`;function group(owned = false): BotGroupSummary {- return { id: 'room', name: 'Team', revision: 1, members: [+ return { id: 'room', name: 'Team', serverBacked: true, revision: 1, members: [{ actorId: 'me', botId: 'me', actorKind: 'human', isSelf: true, isOwned: true, name: 'My name', displayName: 'My name', role: 'member' },{ actorId: 'bot', botId: 'bot', actorKind: 'bot', name: 'Partner', role: 'owner', isOwned: owned, guestAccess: 'chat', accessRevision: 1 },] } as BotGroupSummary;}beforeEach(() => {vi.clearAllMocks(); mocks.manage.mockResolvedValue({ ok: true }); mocks.ownedBots.mockResolvedValue({ ok: true, bots: [] });+ mocks.confirm.mockResolvedValue(true);Object.defineProperty(window, 'electronAPI', { configurable: true, value: { maker: { chatServer: mocks } } });});afterEach(cleanup);@@ -42,3 +43,60 @@ it('lets a companion owner manage a group owned by their companion', async () =>expect(screen.getByRole('button', { name: key('transfer') })).toBeTruthy();await waitFor(() => expect(mocks.ownedBots).toHaveBeenCalled());});++it('does not offer leaving when this account owns every group owner, including its companion', async () => {+ render(<MemoryRouter><ChatGroupSettings group={group(true)} /></MemoryRouter>);+ expect(screen.queryByRole('button', { name: key('leave') })).toBeNull();+ expect(screen.getByRole('button', { name: key('archive') })).toBeTruthy();+ await waitFor(() => expect(mocks.ownedBots).toHaveBeenCalled());+});++it('uses the existing member leave action without changing the group archive state', async () => {+ render(<MemoryRouter><ChatGroupSettings group={group()} /></MemoryRouter>);+ fireEvent.click(screen.getByRole('button', { name: key('leave') }));+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledWith({ groupId: 'room', action: { type: 'member', actorId: 'me', action: 'leave' } }));+ expect(mocks.confirm).toHaveBeenCalledWith(expect.objectContaining({ presentation: 'standard', description: key('leaveHint'), confirmVariant: 'destructive' }));+ expect(mocks.refresh).toHaveBeenCalledOnce();+});++it('keeps membership untouched when the leave confirmation is cancelled', async () => {+ mocks.confirm.mockResolvedValue(false);+ render(<MemoryRouter><ChatGroupSettings group={group()} /></MemoryRouter>);+ fireEvent.click(screen.getByRole('button', { name: key('leave') }));+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledOnce());+ expect(mocks.manage).not.toHaveBeenCalled();+ expect(mocks.refresh).not.toHaveBeenCalled();+});++it('keeps the group visible and reports a server rejection of leaving', async () => {+ mocks.manage.mockResolvedValue({ ok: false, errorCode: 'LAST_OWNER' });+ render(<MemoryRouter><ChatGroupSettings group={group()} /></MemoryRouter>);+ fireEvent.click(screen.getByRole('button', { name: key('leave') }));+ await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy());+ expect(screen.getByRole('button', { name: key('leave') })).toBeTruthy();+ expect(mocks.refresh).not.toHaveBeenCalled();+});++it('confirms irreversible dissolution separately from archive and refreshes after success', async () => {+ render(<MemoryRouter><ChatGroupSettings group={{ ...group(true), supportsDissolve: true, supportsListRemoval: true }} /></MemoryRouter>);+ fireEvent.click(screen.getByRole('button', { name: 'bots.groupChat.lifecycle.dissolve' }));+ await waitFor(() => expect(mocks.manage).toHaveBeenCalledWith({ groupId: 'room', action: { type: 'dissolve', expectedRevision: 1 } }));+ expect(mocks.confirm).toHaveBeenCalledWith(expect.objectContaining({ description: 'bots.groupChat.lifecycle.dissolveNote', confirmVariant: 'destructive' }));+});+it('disables unsupported lifecycle actions and terminal edits without offering unarchive', async () => {+ const rendered = render(<MemoryRouter><ChatGroupSettings group={group(true)} /></MemoryRouter>);+ expect((screen.getByRole('button', { name: 'bots.groupChat.lifecycle.dissolve' }) as HTMLButtonElement).disabled).toBe(true);+ expect((screen.getByRole('button', { name: 'bots.groupChat.lifecycle.hide' }) as HTMLButtonElement).disabled).toBe(true);+ rendered.rerender(<MemoryRouter><ChatGroupSettings group={{ ...group(true), archived: true, dissolvedAt: '2026-10-15', supportsListRemoval: true }} /></MemoryRouter>);+ expect(screen.queryByRole('button', { name: key('unarchive') })).toBeNull();+ expect((screen.getByRole('textbox', { name: key('nickname') }) as HTMLInputElement).disabled).toBe(true);+ expect((screen.getByRole('button', { name: 'bots.groupChat.lifecycle.hide' }) as HTMLButtonElement).disabled).toBe(false);+ await waitFor(() => expect(mocks.ownedBots).toHaveBeenCalled());+});+it('does not refresh or remove the list on failed personal removal', async () => {+ mocks.manage.mockResolvedValue({ ok: false, errorCode: 'REVISION_CONFLICT' });+ render(<MemoryRouter><ChatGroupSettings group={{ ...group(), supportsListRemoval: true }} /></MemoryRouter>);+ fireEvent.click(screen.getByRole('button', { name: 'bots.groupChat.lifecycle.hide' }));+ await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy());+ expect(mocks.refresh).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botGroupListRemoval.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botGroupListRemoval.test.tsnew file mode 100644index 0000000000..0185fc1940--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupListRemoval.test.ts@@ -0,0 +1,29 @@+// @vitest-environment jsdom+import { afterEach, expect, it, vi } from 'vitest';+const h = vi.hoisted(() => ({ seed: vi.fn(), generation: 1 }));+vi.mock('../botReadState', () => ({ seedBotGroupReadState: h.seed }));+vi.mock('@/contexts/dataOwnerGeneration', () => ({+ getDataOwnerGeneration: () => h.generation, isDataOwnerGenerationCurrent: (owner: number) => owner === h.generation,+ isDataOwnerPushCurrent: () => true,+}));+let stop = () => {};+afterEach(() => { stop(); vi.resetModules(); vi.clearAllMocks(); });+it('removes an acknowledged personal entry immediately and filters an older in-flight list response', async () => {+ let changed!: (payload: unknown) => void;+ let finish!: (value: unknown) => void;+ const group = { id: 'room' };+ const list = vi.fn().mockResolvedValueOnce({ ok: true, groups: [group] }).mockImplementation(() => new Promise(resolve => { finish = resolve; }));+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { maker: { listBotGroups: list,+ onBotGroupChanged: (fn: typeof changed) => { changed = fn; return () => {}; } } } });+ const store = await import('../botGroupStore');+ stop = store.startBotGroupSync(); await Promise.resolve(); await Promise.resolve();+ expect(store.getBotGroupListSnapshot().groups).toEqual([group]);+ store.refreshBotGroups();+ changed({ groupId: 'room', change: 'list', listState: { hidden: true, revision: 2 } });+ expect(store.getBotGroupListSnapshot().groups).toEqual([]);+ finish({ ok: true, groups: [group] }); await Promise.resolve(); await Promise.resolve();+ expect(store.getBotGroupListSnapshot().groups).toEqual([]);+ changed({ groupId: 'room', change: 'list', listState: { hidden: false, revision: 1 } });+ expect(store.getBotGroupListSnapshot().groups).toEqual([]);+ expect(h.seed).toHaveBeenLastCalledWith([]);+});diff --git a/apps/desktop/src/renderer/features/bots/botGroupStore.ts b/apps/desktop/src/renderer/features/bots/botGroupStore.tsindex 37581c9f28..76f3842fec 100644--- a/apps/desktop/src/renderer/features/bots/botGroupStore.ts+++ b/apps/desktop/src/renderer/features/bots/botGroupStore.ts@@ -36,6 +36,8 @@ const EMPTY_SNAPSHOT: BotGroupListSnapshot = { groups: [], loaded: false };let snapshot: BotGroupListSnapshot = EMPTY_SNAPSHOT;let owner = getDataOwnerGeneration();let generation = 0;+const personalList = new Map<string, { hidden: boolean; revision: number }>();+const visibleGroups = (groups: readonly BotGroupSummary[]) => groups.filter(group => !personalList.get(group.id)?.hidden);let inFlight: Promise<void> | null = null;let refreshQueued = false;let syncUsers = 0;@@ -63,6 +65,7 @@ function ensureOwner(): void {inFlight = null;refreshQueued = false;snapshot = EMPTY_SNAPSHOT;+ personalList.clear();}function applySnapshot(next: BotGroupListSnapshot): void {@@ -88,9 +91,9 @@ 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) seedBotGroupReadState(result.groups);+ if (result.ok) seedBotGroupReadState(visibleGroups(result.groups));// 失败时保留上一份列表:侧栏不因一次读失败把所有群清空。- applySnapshot(result.ok ? { groups: result.groups, loaded: true } : { ...snapshot, loaded: true });+ applySnapshot(result.ok ? { groups: visibleGroups(result.groups), loaded: true } : { ...snapshot, loaded: true });} catch {if (isCurrent()) applySnapshot({ ...snapshot, loaded: true });}@@ -115,8 +118,15 @@ export function startBotGroupSync(): () => void {if (syncUsers === 1) {const api = botGroupApi();if (api && typeof api.onBotGroupChanged === 'function') {- unsubscribePush = api.onBotGroupChanged((_payload, ownerStamp) => {+ unsubscribePush = api.onBotGroupChanged((payload, ownerStamp) => {if (!isDataOwnerPushCurrent(ownerStamp)) return;+ ensureOwner();+ if (payload.change === 'list' && payload.listState && (personalList.get(payload.groupId)?.revision ?? 0) < payload.listState.revision) {+ personalList.set(payload.groupId, payload.listState);+ const groups = visibleGroups(snapshot.groups);+ seedBotGroupReadState(groups);+ applySnapshot({ ...snapshot, groups });+ }refreshBotGroups();});}diff --git a/apps/desktop/src/renderer/features/bots/chatError.ts b/apps/desktop/src/renderer/features/bots/chatError.tsindex 702836fa53..9c9e33ee69 100644--- a/apps/desktop/src/renderer/features/bots/chatError.ts+++ b/apps/desktop/src/renderer/features/bots/chatError.ts@@ -4,6 +4,8 @@ export function chatErrorKey(code: string) {if (code === 'INVITE_REVOKE_UNSUPPORTED') return key('revokeUnsupported');if (['INVITATION_NOT_FOUND', 'INVITATION_UNAVAILABLE', 'INVALID_INPUT'].includes(code)) return key('invalidInvite');if (code === 'MENTION_UNAVAILABLE') return 'bots.groupChat.errors.mentionUnavailable';+ if (code === 'LIFECYCLE_UNAVAILABLE') return 'bots.groupChat.lifecycle.unavailable';+ if (code === 'CONVERSATION_DISSOLVED') return 'bots.groupChat.lifecycle.dissolved';if (code === 'LAST_OWNER') return key('settings.lastOwner');if (code === 'REVISION_CONFLICT') return key('settings.conflict');if (['FORBIDDEN', 'ROLE_REQUIRED', 'OWNER_REQUIRED', 'ACTOR_NOT_OWNED', 'IDENTITY_DOMAIN_MISMATCH'].includes(code)) return key('notAllowed');diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 6063d3f2f9..ae741bce01 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -9137,7 +9137,10 @@"permissionDenied": "You do not have permission to manage this group.","serviceError": "The chat service could not complete the request. Try again later.","groupArchived": "This group is archived. This action is unavailable.",- "quoteUnavailable": "The quoted message was deleted or is no longer visible. The quote was removed. Send again."+ "quoteUnavailable": "The quoted message was deleted or is no longer visible. The quote was removed. Send again.",+ "lifecycleUnavailable": "The current server or computer does not support this action yet.",+ "groupDissolved": "This group has been dissolved. You can still read the available history.",+ "lastOwner": "Transfer ownership or dissolve this group before leaving."},"organizer": "Organizer","plan": {@@ -9237,7 +9240,7 @@"removeHint": "They will lose access to messages. Their companions will also leave.","addCompanion": "Invite my companion","leave": "Leave group",- "leaveHint": "You and your companions will leave. Transfer ownership first if you own the group.",+ "leaveHint": "You and your companions will leave this group. You will no longer receive new messages or have access to its history.","archive": "Archive group","archiveHint": "Keep history, stop new messages and companion activity.","confirm": "Confirm",@@ -9256,6 +9259,18 @@"companionPermissions": "Companion permissions","configureCapabilities": "Tools and access settings"}+ },+ "lifecycle": {+ "dissolve": "Dissolve group",+ "dissolveNote": "This cannot be undone. Messaging will stop for everyone, active work will stop, and invitations will expire. Members keep access to the history they can already read.",+ "hide": "Remove from my list",+ "hideNote": "Remove this chat from your list on all your devices. This does not change membership, delete history, stop ongoing work, or affect other members.",+ "leave": "Leave group",+ "leaveNote": "You and your companions will leave this group. You will no longer receive new messages or have access to its history.",+ "unavailable": "The current server or computer does not support this action yet.",+ "dissolved": "This group has been dissolved. You can still read the available history.",+ "failed": "Could not complete this action. Try again.",+ "lastOwner": "Transfer ownership or dissolve this group before leaving."}},"joined": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 8a3753f2a8..5f535cfe9e 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -9100,7 +9100,10 @@"permissionDenied": "このグループを管理する権限がありません。","serviceError": "チャットサービスで処理を完了できません。しばらくしてから再試行してください。","groupArchived": "このグループはアーカイブ済みのため操作できません。",- "quoteUnavailable": "引用したメッセージは削除されたか、表示できなくなりました。引用を外したので、もう一度送信してください。"+ "quoteUnavailable": "引用したメッセージは削除されたか、表示できなくなりました。引用を外したので、もう一度送信してください。",+ "lifecycleUnavailable": "現在のサーバーまたはコンピューターは、この操作にまだ対応していません。",+ "groupDissolved": "このグループは解散しました。閲覧権限のある履歴は引き続き確認できます。",+ "lastOwner": "退出する前にオーナーを譲渡するか、グループを解散してください。"},"organizer": "まとめ役","plan": {@@ -9200,7 +9203,7 @@"removeHint": "メッセージの閲覧と送信ができなくなります。そのメンバーのパートナーも退出します。","addCompanion": "自分のパートナーを招待","leave": "グループを退出",- "leaveHint": "あなたとあなたのパートナーが退出します。オーナーは先に所有権を譲渡してください。",+ "leaveHint": "あなたとあなたの仲間がグループから退出します。新しいメッセージは届かなくなり、グループの履歴を閲覧できなくなります。","archive": "グループをアーカイブ","archiveHint": "履歴を残し、新しいメッセージとパートナーの実行を停止します。","confirm": "確認",@@ -9219,6 +9222,18 @@"companionPermissions": "仲間の権限","configureCapabilities": "ツールと利用権限の設定"}+ },+ "lifecycle": {+ "dissolve": "グループを解散",+ "dissolveNote": "この操作は取り消せません。全員がメッセージを送信できなくなり、進行中の作業は停止し、招待は無効になります。メンバーはこれまで閲覧できた履歴を引き続き確認できます。",+ "hide": "自分のリストから削除",+ "hideNote": "すべての自分のデバイスでリストからこのチャットを削除します。メンバーの状態、履歴、進行中の作業、他のメンバーには影響しません。",+ "leave": "グループを退出",+ "leaveNote": "あなたとあなたの仲間がグループから退出します。新しいメッセージは届かなくなり、グループの履歴を閲覧できなくなります。",+ "unavailable": "現在のサーバーまたはコンピューターは、この操作にまだ対応していません。",+ "dissolved": "このグループは解散しました。閲覧権限のある履歴は引き続き確認できます。",+ "failed": "操作を完了できませんでした。もう一度お試しください。",+ "lastOwner": "退出する前にオーナーを譲渡するか、グループを解散してください。"}},"joined": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex de433011b8..4d80c22cde 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -9100,7 +9100,10 @@"permissionDenied": "이 그룹을 관리할 권한이 없어요.","serviceError": "채팅 서비스에서 요청을 처리하지 못했어요. 잠시 후 다시 시도해 주세요.","groupArchived": "보관된 그룹에서는 이 작업을 수행할 수 없어요.",- "quoteUnavailable": "인용한 메시지가 삭제되었거나 더 이상 볼 수 없습니다. 인용을 해제했으니 다시 보내세요."+ "quoteUnavailable": "인용한 메시지가 삭제되었거나 더 이상 볼 수 없습니다. 인용을 해제했으니 다시 보내세요.",+ "lifecycleUnavailable": "현재 서버 또는 컴퓨터에서 아직 이 작업을 지원하지 않습니다.",+ "groupDissolved": "이 그룹은 해산되었습니다. 열람 권한이 있는 기록은 계속 볼 수 있습니다.",+ "lastOwner": "나가기 전에 소유권을 이전하거나 그룹을 해산하세요."},"organizer": "담당자","plan": {@@ -9200,7 +9203,7 @@"removeHint": "메시지를 읽거나 보낼 수 없게 됩니다. 해당 멤버의 파트너도 나갑니다.","addCompanion": "내 파트너 초대","leave": "그룹 나가기",- "leaveHint": "본인과 자신의 파트너가 그룹을 나갑니다. 소유자는 먼저 소유권을 이전해야 합니다.",+ "leaveHint": "나와 내 동료가 이 그룹에서 나갑니다. 새 메시지를 받지 못하며 그룹 기록을 볼 수 없게 됩니다.","archive": "그룹 보관","archiveHint": "기록을 보존하고 새 메시지와 파트너 실행을 중단합니다.","confirm": "확인",@@ -9219,6 +9222,18 @@"companionPermissions": "동료 권한","configureCapabilities": "도구 및 사용 권한 설정"}+ },+ "lifecycle": {+ "dissolve": "그룹 해산",+ "dissolveNote": "이 작업은 되돌릴 수 없습니다. 모든 멤버의 메시지 전송이 중단되고 진행 중인 작업이 멈추며 초대가 만료됩니다. 멤버는 기존에 열람할 수 있었던 기록을 계속 볼 수 있습니다.",+ "hide": "내 목록에서 제거",+ "hideNote": "내 모든 기기의 목록에서 이 채팅을 제거합니다. 멤버 자격, 기록, 진행 중인 작업 및 다른 멤버에게 영향을 주지 않습니다.",+ "leave": "그룹 나가기",+ "leaveNote": "나와 내 동료가 이 그룹에서 나갑니다. 새 메시지를 받지 못하며 그룹 기록을 볼 수 없게 됩니다.",+ "unavailable": "현재 서버 또는 컴퓨터에서 아직 이 작업을 지원하지 않습니다.",+ "dissolved": "이 그룹은 해산되었습니다. 열람 권한이 있는 기록은 계속 볼 수 있습니다.",+ "failed": "작업을 완료하지 못했습니다. 다시 시도하세요.",+ "lastOwner": "나가기 전에 소유권을 이전하거나 그룹을 해산하세요."}},"joined": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 05ec077263..8be930ea86 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -9100,7 +9100,10 @@"permissionDenied": "你没有执行此操作的群管理权限。","serviceError": "群聊服务处理失败,请稍后重试。","groupArchived": "本群已归档,不能执行此操作。",- "quoteUnavailable": "引用的消息已删除或不可见,已取消引用,请再发送一次"+ "quoteUnavailable": "引用的消息已删除或不可见,已取消引用,请再发送一次",+ "lifecycleUnavailable": "当前服务器或电脑暂不支持此操作。",+ "groupDissolved": "群聊已解散,仍可查看有权访问的历史消息。",+ "lastOwner": "请先转让群主或解散群聊,再退出。"},"organizer": "负责人","plan": {@@ -9200,7 +9203,7 @@"removeHint": "该成员将无法继续查看或发消息;如果是伙伴的主人,其伙伴也会退出。","addCompanion": "邀请我的伙伴","leave": "退出群",- "leaveHint": "你和你带来的伙伴将退出群。群主需要先转让身份。",+ "leaveHint": "你和你的伙伴将退出此群聊,不再接收新消息,也无法查看群历史。","archive": "归档群","archiveHint": "归档后保留群聊记录,停止新消息和伙伴执行。","confirm": "确认",@@ -9219,6 +9222,18 @@"companionPermissions": "伙伴权限","configureCapabilities": "工具与授权设置"}+ },+ "lifecycle": {+ "dissolve": "解散群聊",+ "dissolveNote": "解散后无法恢复。所有成员将无法发送消息,进行中的工作会停止,邀请会失效。成员仍可查看原本有权访问的历史消息。",+ "hide": "从我的列表移除",+ "hideNote": "从你所有设备的列表中移除此群聊。不改变成员关系,不删除历史消息、不停止进行中的工作,也不影响其他成员。",+ "leave": "退出群聊",+ "leaveNote": "你和你的伙伴将退出此群聊,不再接收新消息,也无法查看群历史。",+ "unavailable": "当前服务器或电脑暂不支持此操作。",+ "dissolved": "群聊已解散,仍可查看有权访问的历史消息。",+ "failed": "操作未完成,请重试。",+ "lastOwner": "请先转让群主或解散群聊,再退出。"}},"joined": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex fce83553d6..23d458241b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -9100,7 +9100,10 @@"permissionDenied": "你沒有執行此操作的群管理權限。","serviceError": "群聊服務處理失敗,請稍後重試。","groupArchived": "本群已封存,無法執行此操作。",- "quoteUnavailable": "引用的訊息已刪除或無法查看,已取消引用,請再傳送一次"+ "quoteUnavailable": "引用的訊息已刪除或無法查看,已取消引用,請再傳送一次",+ "lifecycleUnavailable": "目前伺服器或電腦尚不支援此操作。",+ "groupDissolved": "群聊已解散,仍可查看有權存取的歷史訊息。",+ "lastOwner": "請先轉讓群主或解散群聊,再退出。"},"organizer": "負責人","plan": {@@ -9200,7 +9203,7 @@"removeHint": "該成員將無法繼續查看或傳送訊息;其夥伴也會退出。","addCompanion": "邀請我的夥伴","leave": "退出群組",- "leaveHint": "你和你帶來的夥伴將退出群組。群主需要先轉讓身分。",+ "leaveHint": "你和你的伙伴將退出此群聊,不再接收新訊息,也無法查看群歷史。","archive": "封存群組","archiveHint": "封存後保留群聊記錄,停止新訊息和夥伴執行。","confirm": "確認",@@ -9219,6 +9222,18 @@"companionPermissions": "夥伴權限","configureCapabilities": "工具與授權設定"}+ },+ "lifecycle": {+ "dissolve": "解散群聊",+ "dissolveNote": "解散後無法恢復。所有成員將無法傳送訊息,進行中的工作會停止,邀請會失效。成員仍可查看原本有權存取的歷史訊息。",+ "hide": "從我的列表移除",+ "hideNote": "從你所有裝置的列表中移除此群聊。不改變成員關係,不刪除歷史訊息、不停止進行中的工作,也不影響其他成員。",+ "leave": "退出群聊",+ "leaveNote": "你和你的伙伴將退出此群聊,不再接收新訊息,也無法查看群歷史。",+ "unavailable": "目前伺服器或電腦尚不支援此操作。",+ "dissolved": "群聊已解散,仍可查看有權存取的歷史訊息。",+ "failed": "操作未完成,請重試。",+ "lastOwner": "請先轉讓群主或解散群聊,再退出。"}},"joined": {diff --git a/apps/mobile/src/__tests__/botGroupRemote.test.ts b/apps/mobile/src/__tests__/botGroupRemote.test.tsindex 258c39194f..a51c3ab01d 100644--- a/apps/mobile/src/__tests__/botGroupRemote.test.ts+++ b/apps/mobile/src/__tests__/botGroupRemote.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';+import { chatGroupMembership } from '@cindy/maker-shared/botGroupPresentation';import {botGroupChatDataFromResource,botGroupErrorCode,@@ -10,6 +11,7 @@ import {nextBotGroupSendAttempt,orderedBotGroups,parseBotGroupChatData,+ canManageBotGroup,} from '@/session/botGroupRemote';function chatData(overrides: Record<string, unknown> = {}) {@@ -187,6 +189,20 @@ describe('group rows', () => {});describe('actions', () => {+ it('preserves leave and owner authority through the remote projection without granting management to ordinary members', () => {+ const members = [+ { botId: 'me', actorId: 'me', name: 'Me', isSelf: true, isOwned: true, role: 'member' },+ { botId: 'bot', actorId: 'bot', name: 'Bot', isOwned: true, role: 'owner' },+ ];+ const ownGroup = parseBotGroupChatData(chatData({ serverBacked: true, supportsSettingsManagement: true, revision: 1, members }))!;+ expect(chatGroupMembership(ownGroup)).toMatchObject({ owner: true, manager: true, canLeave: false });+ expect(canManageBotGroup(ownGroup)).toBe(true);+ const memberGroup = parseBotGroupChatData(chatData({ serverBacked: true, supportsSettingsManagement: true, revision: 1,+ members: [members[0], { ...members[1], isOwned: false }] }))!;+ expect(chatGroupMembership(memberGroup)).toMatchObject({ owner: false, manager: false, canLeave: true });+ expect(canManageBotGroup(memberGroup)).toBe(false);+ });+it.each([[Object.assign(new Error('PLAN_OPEN'), { code: 'INVALID_PARAMS' }), 'PLAN_OPEN'],['[INVALID_PARAMS] MEMBER_LIMIT', 'MEMBER_LIMIT'],diff --git a/apps/mobile/src/__tests__/chatServerClient.test.ts b/apps/mobile/src/__tests__/chatServerClient.test.tsindex 09241783ab..c651968f0c 100644--- a/apps/mobile/src/__tests__/chatServerClient.test.ts+++ b/apps/mobile/src/__tests__/chatServerClient.test.ts@@ -221,3 +221,42 @@ describe('direct Chat Server client', () => {});});++describe('group lifecycle contract', () => {+ function lifecycle(options: { supported?: boolean; kind?: string; role?: string; reject?: boolean } = {}) {+ const request = vi.fn().mockImplementation(async (path: string, method?: string) => {+ if (path === '/me') return { actor: { id: id(11), kind: 'human' }, ...(options.supported === false ? {} : { capabilities: { groupLifecycleVersion: 1, conversationListStateVersion: 1 } }) };+ if (path.startsWith('/conversation-list-state?')) return [];+ if (path.endsWith('/snapshot')) return { ...snapshot(), room: { ...room(), kind: options.kind ?? 'group' },+ members: [{ id: id(12), ownerActorId: id(11), state: 'joined', kind: 'bot', role: options.role ?? 'owner' }] };+ if (path.endsWith('/list-state')) {+ if (options.reject) throw new Error('REVISION_CONFLICT');+ return { conversationId: id(1), hidden: true, revision: 1 };+ }+ if (method === 'POST') return { revision: 2, dissolvedAt: '2026-10-15T00:00:00Z', dissolvedBy: id(12) };+ return [];+ });+ return { client: createChatServerClient(request), request };+ }+ it('uses the owned companion owner and an explicit revision for dissolution', async () => {+ const { client, request } = lifecycle();+ await client.dissolve(id(1), 1, 'fixture-dissolve');+ expect(request).toHaveBeenLastCalledWith(`/conversations/${id(1)}/dissolve`, 'POST', { operationId: 'fixture-dissolve', expectedRevision: 1 }, id(12));+ expect(request.mock.calls.some(([, method]) => method === 'PATCH')).toBe(false);+ });+ it.each([{ kind: 'direct', code: 'GROUP_REQUIRED' }, { role: 'admin', code: 'OWNER_REQUIRED' }, { supported: false, code: 'LIFECYCLE_UNAVAILABLE' }])('refuses unsupported or unauthorized dissolution %j', async ({ code, ...options }) => {+ const { client, request } = lifecycle(options);+ await expect(client.dissolve(id(1), 1, 'fixture-dissolve')).rejects.toThrow(code);+ expect(request.mock.calls.some(([, method]) => method === 'POST' || method === 'PATCH')).toBe(false);+ });+ it('hides after leave without snapshot access and does not hide a failed write', async () => {+ const failed = lifecycle({ reject: true });+ await expect(failed.client.hide(id(1), 'fixture-hide')).rejects.toThrow('REVISION_CONFLICT');+ expect(failed.client.personalList.hidden(id(1))).toBe(false);+ const { client, request } = lifecycle();+ await client.hide(id(1), 'fixture-hide');+ expect(client.personalList.hidden(id(1))).toBe(true);+ expect(request.mock.calls.some(([path]) => path.endsWith('/snapshot'))).toBe(false);+ expect(request).toHaveBeenLastCalledWith(`/conversations/${id(1)}/list-state`, 'POST', { operationId: 'fixture-hide', hidden: true, expectedRevision: 0 });+ });+});diff --git a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsxindex e0d9d552cb..fd62621cfe 100644--- a/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx+++ b/apps/mobile/src/__tests__/chatServerMobileEntry.test.tsx@@ -11,6 +11,7 @@ const h = vi.hoisted(() => ({foreground: new Set<(state: string) => void>(),}));vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: vi.fn(async () => null), setItem: vi.fn(async () => {}), removeItem: vi.fn(async () => {}), getAllKeys: vi.fn(async () => []), multiRemove: vi.fn(async () => {}) } }));+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' } }) }));@@ -309,3 +310,66 @@ it('rebuilds realtime after membership returns while the same group page remainsexpect(h.auth.apiFetch.mock.calls.length).toBeGreaterThan(previous);expect(chat.state.kind).toBe('ready');});++it('supports direct leave, then personal removal independently without a readable snapshot', async () => {+ h.auth.accountGeneration = 101;+ const allowed = h.auth.apiFetch.getMockImplementation()!;+ let left = false;+ h.auth.apiFetch.mockImplementation(async (path, options) => {+ options.assertCurrent();+ if (path === '/v1/me') return { actor: { id: self, kind: 'human' }, capabilities: { groupLifecycleVersion: 1, conversationListStateVersion: 1 } };+ if (path.startsWith('/v1/conversation-list-state?')) return [];+ if (path.endsWith('/members') && options.method === 'POST') { left = true; return { revision: 2 }; }+ if (path.endsWith('/list-state')) return { conversationId: id, hidden: true, revision: 1 };+ if (left && path.endsWith('/snapshot')) throw Object.assign(new Error('NOT_MEMBER'), { status: 403 });+ return allowed(path, options);+ });+ showChat = true; await render();+ expect(chat.state.kind).toBe('ready');+ expect(chat.state.kind === 'ready' && chat.state.group.supportsListRemoval).toBe(true);+ await act(async () => { await chat.act('leave'); });+ expect(chat.state.kind).toBe('missing');+ h.auth.apiFetch.mockClear();+ await act(async () => { await chat.act('hide'); });+ expect(h.auth.apiFetch.mock.calls.some(([path]) => path.endsWith('/snapshot'))).toBe(false);+ expect(h.auth.apiFetch.mock.calls.some(([path]) => path.endsWith('/list-state'))).toBe(true);+});+it('keeps a hidden room out of the roster even if an old server list and computer cache contain it', async () => {+ h.auth.accountGeneration = 102;+ const allowed = h.auth.apiFetch.getMockImplementation()!;+ const legacyHost = { deviceId: 'old-computer', deviceName: 'Old' };+ h.targets = [legacyHost]; h.legacy.isOnline.mockReturnValue(true);+ h.legacy.items = [{ host: legacyHost, item: { ref: { id, kind: 'bot-group', collectionId: 'bot-groups' } } }];+ h.auth.apiFetch.mockImplementation(async (path, options) => {+ if (path === '/v1/me') return { actor: { id: self, kind: 'human' }, capabilities: { conversationListStateVersion: 1 } };+ if (path.startsWith('/v1/conversation-list-state?')) return [{ conversationId: id, hidden: true, revision: 4 }];+ return allowed(path, options);+ });+ await render();+ expect(roster.items).toEqual([]);+ expect(h.auth.apiFetch.mock.calls.some(([path]) => path.endsWith('/snapshot'))).toBe(false);+ expect(roster.error).toBeNull();+});++it('merges a computer-confirmed personal removal without requiring direct server access or trusting stale room data', async () => {+ h.auth.accountGeneration = 103;+ h.link.status = 'online';+ h.link.subscribe.mockResolvedValue(undefined); h.link.unsubscribe.mockResolvedValue(undefined);+ h.link.getPresenceAvailability = () => true;+ h.auth.apiFetch.mockRejectedValue(new Error('Offline direct endpoint'));+ const target = { deviceId: 'computer', deviceName: 'Computer' };+ const resource = { ref: { id, collectionId: 'bot-groups', kind: 'bot-group' }, revision: '1', display: { title: 'Fixture' }, links: [],+ blocks: [{ id: 'chat', primitive: 'bot-group-chat', fallbackMarkdown: '', data: { id, name: 'Fixture', serverBacked: true,+ supportsListRemoval: true, members: [], messages: [], plans: [], round: { status: 'idle', speakers: [], canContinue: false } } }] };+ h.link.invoke.mockImplementation(async (_id, channel) => channel === 'maker:remote-resources:get' ? resource+ : { effects: [], result: { listState: { conversationId: id, hidden: true, revision: 7 } } });+ function RemoteProbe() { chat = useBotGroupChat(target, id); return null; }+ root = createRoot(document.createElement('div'));+ await act(async () => root!.render(createElement(RemoteProbe)));+ expect(chat.state.kind).toBe('ready');+ await act(async () => { await chat.act('hide'); });+ expect(chat.state.kind).toBe('missing');+ expect(h.auth.apiFetch).not.toHaveBeenCalled();+ expect(h.link.invoke.mock.calls.find(call => call[1] === 'maker:remote-resources:invoke')?.[2][0]).toMatchObject({ actionId: 'hide', resourceRef: { id } });+ h.link.status = 'offline'; h.link.getPresenceAvailability = () => false;+});diff --git a/apps/mobile/src/__tests__/chatServerSubscription.test.ts b/apps/mobile/src/__tests__/chatServerSubscription.test.tsindex 6a3cf63bcb..095232f2a6 100644--- a/apps/mobile/src/__tests__/chatServerSubscription.test.ts+++ b/apps/mobile/src/__tests__/chatServerSubscription.test.ts@@ -44,3 +44,15 @@ it('does not authenticate or reconnect after owner change or disposal', async ()socket, ready: vi.fn(), changed: vi.fn(), unavailable: vi.fn() });current = false; resolve('old-owner'); await Promise.resolve(); expect(sockets).toHaveLength(0);});++it('subscribes focused history and the human account scope together, forwarding personal state events', async () => {+ const changed = vi.fn();+ stop = subscribeChatServer({ baseUrl: 'https://chat.example.invalid', token: async () => 'fixture', current: () => true, socket,+ ready: async () => [{ scope: 'conversation:room', cursor: '9' }, { scope: `actor:${actorId}`, cursor: '10' }], changed, unavailable: vi.fn() });+ await Promise.resolve(); const ws = sockets[0];+ await receive(ws, { type: 'ready', actorId });+ expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: 'subscribe', scope: 'conversation:room', after: '9' }));+ const changes = [{ type: 'conversation.list.changed', data: { conversationId: actorId, hidden: true, revision: 3 } }];+ await receive(ws, { type: 'changes', scope: `actor:${actorId}`, cursor: '11', changes });+ expect(changed).toHaveBeenCalledWith(changes);+});diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.tsindex 743a8a7ea4..922c5dcfaf 100644--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@ -1,10 +1,11 @@+import { createConversationListState } from '@cindy/maker-shared/chatConversationList';/** The existing Chat Server HTTP contract; no device-link or executor registration. */import { readBotGroupExecutionFailure, readBotGroupQuote, readBotGroupQuoteCard, readImportedBotGroupRuntimeFailureCode, type BotGroupAttachment, type BotGroupMemberView, type BotGroupMessageView, type BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';import { botGroupExecutionFailureBatches, projectBotGroupExecutionFailures } from '@cindy/maker-shared/botGroupPresentation';import type { HostedRemoteCollectionItem } from '@/device-link/remoteResources';export interface ChatRoom {- id: string; name: string; state?: string; kind: string; archived: boolean;+ id: string; name: string; state?: string; kind: string; archived: boolean; dissolved_at?: string | null;created_at: string; updated_at: string; revision: number; head?: string;response_mode: 'all' | 'mentioned'; speaking_mode: 'auto' | 'sequential'; organizer_id?: string | null;}@@ -165,7 +166,7 @@ export function chatGroupView(page: ChatPage, selfId: string): BotGroupRemoteChaconst member = members.find(candidate => candidate.id === failure.botId);return [{ ...failure, botName: member ? memberName(member) : '' }];});- return { id: room.id, name: room.name, serverBacked: true, archived: room.archived, selfActorId: selfId,+ return { id: room.id, name: room.name, serverBacked: true, supportsGroupLeave: true, dissolvedAt: room.dissolved_at ?? null, archived: room.archived, selfActorId: selfId,revision: room.revision, members: memberViews, replyMode: room.response_mode, speakingMode: room.speaking_mode,organizerBotId: room.organizer_id ?? null, projectDir: null, projectDirName: null,createdAt: Date.parse(room.created_at), updatedAt: Date.parse(room.updated_at),@@ -174,7 +175,7 @@ export function chatGroupView(page: ChatPage, selfId: string): BotGroupRemoteChahasMoreBefore: page.before !== null, round: { status: 'idle', speakers: [], canContinue: false }, supportsAttachments: false };}-export function createChatServerClient(request: ChatRequest) {+export function createChatServerClient(request: ChatRequest, personalList = createConversationListState()) {async function failures(roomId: string, messages: ChatMessage[]): Promise<ChatExecutionFailure[]> {const sources = new Set(messages.map(message => chatId(message.id)));let value: ChatExecutionFailure[] = [];@@ -199,7 +200,42 @@ export function createChatServerClient(request: ChatRequest) {if (before && next && BigInt(next) >= BigInt(before)) throw new Error('INVALID_CHAT_PAGE');return { messages, before: next };}+ let supportsDissolve = false;+ let supportsListRemoval = false;+ async function identity() {+ const me = await request<{ actor: { id: string; kind: string }; capabilities?: { groupLifecycleVersion?: number; conversationListStateVersion?: number } }>('/me');+ if (me.actor.kind !== 'human') throw new Error('INVALID_CHAT_IDENTITY');+ supportsDissolve = me.capabilities?.groupLifecycleVersion === 1;+ supportsListRemoval = me.capabilities?.conversationListStateVersion === 1;+ return chatId(me.actor.id);+ }return {+ personalList,+ lifecycleCapabilities: () => ({ supportsDissolve, supportsListRemoval }),+ async syncListState() { await identity(); if (supportsListRemoval) await personalList.sync(request); },+ async hide(roomId: string, operationId: string) {+ await identity();+ if (!supportsListRemoval) throw new Error('LIFECYCLE_UNAVAILABLE');+ await personalList.setHidden(request, chatId(roomId), true, operationId);+ },+ async dissolve(roomId: string, expectedRevision: unknown, operationId: string) {+ const self = await identity();+ if (!supportsDissolve) throw new Error('LIFECYCLE_UNAVAILABLE');+ if (!Number.isSafeInteger(expectedRevision) || Number(expectedRevision) < 1) throw new Error('REVISION_CONFLICT');+ const snapshot = await request<ChatSnapshot>(`/conversations/${chatId(roomId)}/snapshot`);+ if (snapshot.room.kind !== 'group') throw new Error('GROUP_REQUIRED');+ const owner = snapshot.members.find(m => m.state === 'joined' && m.role === 'owner' && (m.id === self || m.ownerActorId === self));+ if (!owner) throw new Error('OWNER_REQUIRED');+ const result = await request<{ revision: number; dissolvedAt: string; dissolvedBy: string }>(`/conversations/${roomId}/dissolve`, 'POST', { operationId, expectedRevision }, owner.id);+ if (!Number.isSafeInteger(result?.revision) || result.revision < 1 || !Number.isFinite(Date.parse(result.dissolvedAt))) throw new Error('INVALID_CHAT_RESPONSE');+ chatId(result.dissolvedBy);+ },+ async leave(roomId: string, operationId: string) {+ const self = await identity();+ const snapshot = await request<ChatSnapshot>(`/conversations/${chatId(roomId)}/snapshot`);+ if (snapshot.room.kind !== 'group') throw new Error('GROUP_REQUIRED');+ await request(`/conversations/${roomId}/members`, 'POST', { operationId, actorId: self, action: 'leave' });+ },async list(): Promise<ChatRoom[]> {const rooms = new Map<string, ChatRoom>();let after: string | undefined;@@ -209,18 +245,16 @@ export function createChatServerClient(request: ChatRequest) {for (const room of page) {chatId(room.id);if (!['direct', 'group', 'channel'].includes(room.kind)) throw new Error('INVALID_CHAT_LIST');- if (room.state === 'joined' && room.kind === 'group') rooms.set(room.id, room);+ if (room.state === 'joined' && room.kind === 'group' && !personalList.hidden(room.id)) rooms.set(room.id, room);}const next = page.length === 100 ? chatId(page.at(-1)!.id) : undefined;if (next && next === after) throw new Error('INVALID_CHAT_PAGE');after = next;} while (after);- return [...rooms.values()];+ return [...rooms.values()].filter(room => !personalList.hidden(room.id));},async me(): Promise<string> {- const { actor } = await request<{ actor: { id: string; kind: string } }>('/me');- if (actor.kind !== 'human') throw new Error('INVALID_CHAT_IDENTITY');- return chatId(actor.id);+ return identity();},/** Server feature switches; an older server without them keeps per-computer companions. */async capabilities(): Promise<ChatCapabilities> {diff --git a/apps/mobile/src/chat/chatServerSubscription.ts b/apps/mobile/src/chat/chatServerSubscription.tsindex d312177e28..89a0344a36 100644--- a/apps/mobile/src/chat/chatServerSubscription.ts+++ b/apps/mobile/src/chat/chatServerSubscription.ts@@ -13,8 +13,8 @@ export interface ChatSocket {export function subscribeChatServer(options: {baseUrl: string; token(): Promise<string | null>; current(): boolean;socket(url: string): ChatSocket;- ready(actorId: string): Promise<{ scope: string; cursor: string }>;- changed(): void; unavailable(): void; available?(): void;+ ready(actorId: string): Promise<{ scope: string; cursor: string } | Array<{ scope: string; cursor: string }>>;+ changed(changes?: Array<{ type: string; data: unknown }>): void; unavailable(): void; available?(): void;}) {let stopped = false;let socket: ChatSocket | undefined;@@ -32,7 +32,7 @@ export function subscribeChatServer(options: {const ws = options.socket(url.href); socket = ws;deadline = setTimeout(() => ws.close(), 15000);ws.onopen = () => { if (current(ws)) ws.send(JSON.stringify({ type: 'auth', token })); else ws.close(); };- let scope: string | undefined;+ const scopes = new Set<string>();ws.onmessage = event => {if (!current(ws)) return;void (async () => {@@ -41,16 +41,19 @@ export function subscribeChatServer(options: {clearTimeout(deadline);const subscription = await options.ready(chatId(value.actorId));if (current(ws) && ws.readyState === 1) {- scope = subscription.scope; delay = 1000;- ws.send(JSON.stringify({ type: 'subscribe', scope, after: chatCursor(subscription.cursor) }));+ delay = 1000;+ for (const entry of Array.isArray(subscription) ? subscription : [subscription]) {+ scopes.add(entry.scope);+ ws.send(JSON.stringify({ type: 'subscribe', scope: entry.scope, after: chatCursor(entry.cursor) }));+ }options.available?.();}- } else if (value.type === 'changes' && scope && value.scope === scope) {- options.changed();+ } else if (value.type === 'changes' && scopes.has(value.scope)) {+ options.changed(value.changes);ws.send(JSON.stringify({ type: 'ack', scope: value.scope, cursor: chatCursor(value.cursor) }));- } else if (value.type === 'scope_error' && scope && value.scope === scope) {+ } else if (value.type === 'scope_error' && scopes.has(value.scope)) {// A full authenticated reload clears removed membership and resets expired cursors.- options.changed();+ options.changed(value.changes);if (value.error?.code === 'RESET_REQUIRED' && value.error?.details?.head) {ws.send(JSON.stringify({ type: 'subscribe', scope: value.scope, after: chatCursor(value.error.details.head) }));} else { stopped = true; options.unavailable(); ws.close(); }diff --git a/apps/mobile/src/chat/useChatServer.ts b/apps/mobile/src/chat/useChatServer.tsindex 90708968d4..537887d37f 100644--- a/apps/mobile/src/chat/useChatServer.ts+++ b/apps/mobile/src/chat/useChatServer.ts@@ -1,3 +1,4 @@+import { createConversationListState } from '@cindy/maker-shared/chatConversationList';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { AppState } from 'react-native';import { useFocusEffect } from 'expo-router';@@ -5,12 +6,20 @@ import type { RemoteActionInvokeResponse } from '@cindy/device-link';import type { BotGroupAttachment, BotGroupRemoteActionId } from '@cindy/maker-shared/botGroupChat';import { useAuth } from '@/auth/AuthContext';import { getActiveMobileSessionRealm, getMobileEndpointForRealm, loadMobileEndpointsForRealm } from '@/config/env';-import { markRemoteResourceRead } from '@/device-link/remoteResourceCache';+import { forgetRemoteResource, markRemoteResourceRead } 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 ChatPage, type ChatRequest, type ChatSnapshot } from './chatServerClient';import { subscribeChatServer } from './chatServerSubscription';+// Shared only within the current authenticated account generation and realm.+let listOwner = '';+let accountList = createConversationListState();+function listFor(owner: string) {+ if (listOwner !== owner) { listOwner = owner; accountList = createConversationListState(); }+ return accountList;+}+/** The account's Chat Server client, fenced to the current account, realm and mount. */export function useChatClient() {const auth = useAuth();@@ -44,7 +53,7 @@ export function useChatClient() {...(actorId ? { headers: { 'X-Chat-Actor': actorId } } : {}), assertCurrent: check });check(); return result;};- const client = createChatServerClient(request);+ const client = createChatServerClient(request, listFor(owner));return { owner, userId: auth.user?.id ?? '', current, baseUrl, endpoint, request, client,token: async () => { check(); await client.me(); const token = await deps.current.getAccessToken(); check(); return token; }, enabled: !!auth.user };}, [owner, !!auth.user]);@@ -61,6 +70,7 @@ export function useChatServerRoster(enabled: boolean) {if (!api.enabled || !enabled) return;setState(old => ({ ...old, refreshing: run.reasons.includes('visible') }));try {+ await api.client.syncListState();const [rooms, self] = await Promise.all([api.client.list(), api.client.me()]);const rows: ReturnType<typeof chatRoomRow>[] = [];const fresh = new Map<string, { owner: string; head: string | undefined; value: ChatSnapshot }>();@@ -91,10 +101,11 @@ export function useChatServerRoster(enabled: boolean) {if (run.isStale() || !api.current()) return;snapshots.current = fresh;for (const room of rooms) known.current.ids.add(room.id);- setState({ owner: api.owner, rooms: rows, loading: false, refreshing: false, error: partial ? 'CHAT_LIST_FAILED' : null });+ for (const id of api.client.personalList.ids()) known.current.ids.add(id);+ setState({ owner: api.owner, rooms: rows.filter(row => !api.client.personalList.hidden(row.item.ref.id)), loading: false, refreshing: false, error: partial ? 'CHAT_LIST_FAILED' : null });}} catch (error) {- if (!run.isStale() && api.current()) setState(old => ({ owner: api.owner, rooms: old.owner === api.owner && !chatAccessLost(error) ? old.rooms : [], loading: false, refreshing: false, error: error instanceof Error && error.message === 'CHAT_ENDPOINT_UNAVAILABLE' ? error.message : 'CHAT_LIST_FAILED' }));+ if (!run.isStale() && api.current()) 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' }));}}, api.owner);const refresh = useCallback(() => read({ reason: 'visible' }), [read]);@@ -125,13 +136,18 @@ export function useChatServerRoster(enabled: boolean) {}await read({ reason: 'connected' });return { scope: `actor:${actorId}`, cursor };- }, changed: () => { void read({ reason: 'changed' }); }, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; } });+ }, changed: changes => { for (const change of changes ?? []) if (change.type === 'conversation.list.changed') api.client.personalList.merge(change.data); void read({ reason: 'changed' }); }, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; } });}).catch(() => {}); // HTTP read presents endpoint errors.};start();const foreground = AppState.addEventListener('change', value => { if (value === 'active') start(); else { stop?.(); clearInterval(poll); } });return () => { stop?.(); clearInterval(poll); foreground.remove(); };}, [api, enabled, read]));+ useEffect(() => api.client.personalList.subscribe(() => {+ if (!api.current()) return;+ for (const id of api.client.personalList.ids()) known.current.ids.add(id);+ setState(old => old.owner !== api.owner ? old : { ...old, rooms: old.rooms.filter(row => !api.client.personalList.hidden(row.item.ref.id)) });+ }), [api]);const own = state.owner === api.owner;return { items: own ? state.rooms : [], serverIds: known.current.ids, loading: api.enabled && (!own || state.loading),refreshing: own && state.refreshing, error: own ? state.error : null, refresh };@@ -152,19 +168,22 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {accessGeneration.current++; freshRead.current = false; page.current = null;setState({ identity, value: { kind: 'missing' }, online: false, loadingOlder: false });};+ const view = (next: ChatPage, self: string) => ({ ...chatGroupView(next, self), ...api.client.lifecycleCapabilities() });const request = useRemoteSyncCoordinator(async run => {if (!enabled || !api.enabled) return;const generation = accessGeneration.current;freshRead.current = false;try {+ await api.client.syncListState();const previous = page.current?.identity === identity ? page.current.page : null;const oldest = previous?.messages.reduce<string | undefined>((oldest, message) => !oldest || BigInt(message.seq) < BigInt(oldest) ? message.seq : oldest, undefined);const [next, self] = await Promise.all([api.client.load(groupId, oldest), api.client.me()]);if (run.isStale() || !valid() || generation !== accessGeneration.current) return;// Replace the reauthorized window; no stale history survives changed access.+ if (api.client.personalList.hidden(groupId)) { loseAccess(); return; }freshRead.current = true;page.current = { identity, page: next, self };- setState({ identity, value: { kind: 'ready', group: chatGroupView(next, self) }, online: true, loadingOlder: false });+ setState({ identity, value: { kind: 'ready', group: view(next, self) }, online: true, loadingOlder: false });} catch (error) {if (run.isStale() || !valid() || generation !== accessGeneration.current) return;if (chatAccessLost(error)) loseAccess();@@ -189,12 +208,18 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {void api.endpoint().then(baseUrl => {if (cancelled || !api.current() || active.current !== identity) return;disposeSocket = subscribeChatServer({ baseUrl, token: api.token, current: () => api.current() && active.current === identity,- socket: url => new WebSocket(url), ready: async () => {+ socket: url => new WebSocket(url), ready: async actorId => {+ const head = api.client.lifecycleCapabilities().supportsListRemoval ? await api.request<{ head: string }>(`/changes?scope=actor:${actorId}&after=0&limit=1`).then(value => chatCursor(value.head)).catch(error => {+ if ((error as { code?: string }).code !== 'RESET_REQUIRED') throw error;+ return '0';+ }) : null;+ await api.client.syncListState();await request({ reason: 'connected' });const latest = page.current;if (!freshRead.current || !latest || latest.identity !== identity) throw new Error('CHAT_READ_FAILED');- return { scope: `conversation:${groupId}`, cursor: latest.page.snapshot.cursor };- }, changed: reload, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; freshRead.current = false; } });+ return head === null ? { scope: `conversation:${groupId}`, cursor: latest.page.snapshot.cursor }+ : [{ scope: `conversation:${groupId}`, cursor: latest.page.snapshot.cursor }, { scope: `actor:${actorId}`, cursor: head }];+ }, changed: changes => { for (const change of changes ?? []) if (change.type === 'conversation.list.changed') api.client.personalList.merge(change.data); reload(); }, available: () => { subscribed = true; }, unavailable: () => { subscribed = false; freshRead.current = false; } });}).catch(() => {}); // Read presents endpoint errors.};start();@@ -210,13 +235,27 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {const next = await api.client.older(groupId, previous.page);if (!valid() || page.current !== previous) return;page.current = { ...previous, page: next };- setState({ identity, value: { kind: 'ready', group: chatGroupView(next, previous.self) }, online: true, loadingOlder: false });+ setState({ identity, value: { kind: 'ready', group: view(next, previous.self) }, online: true, loadingOlder: false });} catch (error) {if (valid() && page.current === previous && chatAccessLost(error)) loseAccess();throw error;} finally { olderPending.current = false; if (valid()) setState(old => ({ ...old, loadingOlder: false })); }};const act = async (action: BotGroupRemoteActionId, input?: Record<string, unknown>): Promise<RemoteActionInvokeResponse> => {+ if (action === 'dissolve' || action === 'leave' || action === 'hide') {+ const operationId = (await import('expo-crypto')).randomUUID();+ 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); }+ } else if (action === 'leave') {+ try { await api.client.leave(groupId, operationId); } catch (error) { if (valid()) reload(); throw error; }+ if (valid()) loseAccess();+ } else {+ try { await api.client.dissolve(groupId, input?.expectedRevision, operationId); } finally { if (valid()) reload(); }+ }+ return { effects: [] };+ }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');@@ -259,6 +298,12 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {throw error;}};+ useEffect(() => api.client.personalList.subscribe(() => {+ if (valid() && api.client.personalList.hidden(groupId)) {+ loseAccess();+ void forgetRemoteResource(api.userId, groupId);+ }+ }), [api, identity, groupId]);const markRead = useCallback(async (messageIds: readonly string[]) => {const latest = page.current;if (!api.current() || active.current !== identity || !latest || latest.identity !== identity) return;@@ -267,6 +312,13 @@ export function useChatServerGroup(groupId: string, enabled: boolean) {const messages = latest.page.messages.filter(message => seen.has(message.id));await markRemoteResourceRead(api.userId, '', groupId, chatLastReplyAt(messages, latest.self), chatLastReplySequence(messages, latest.self));}, [api, groupId, identity]);+ const acceptListState = useCallback(async (value: unknown) => {+ if (!api.current()) throw new Error('OWNER_CHANGED');+ if ((value as { conversationId?: unknown } | null)?.conversationId !== groupId) throw new Error('INVALID_CHAT_LIST_STATE');+ api.client.personalList.merge(value);+ if (api.current() && api.client.personalList.hidden(groupId)) await forgetRemoteResource(api.userId, groupId);+ }, [api, groupId]);return { state: state.identity === identity ? state.value : { kind: 'loading' } as BotGroupChatState,- online: state.identity === identity && state.online, reload, act, loadOlder, loadingOlder: state.loadingOlder, media, markRead };+ online: state.identity === identity && state.online, reload, act,+ acceptListState, isListHidden: () => api.client.personalList.hidden(groupId), loadOlder, loadingOlder: state.loadingOlder, media, markRead };}diff --git a/apps/mobile/src/device-link/remoteResourceCache.ts b/apps/mobile/src/device-link/remoteResourceCache.tsindex 8d1c904b23..4133875537 100644--- a/apps/mobile/src/device-link/remoteResourceCache.ts+++ b/apps/mobile/src/device-link/remoteResourceCache.ts@@ -124,3 +124,11 @@ export async function clearRemoteResourceCache(): Promise<void> {const keys = await AsyncStorage.getAllKeys().catch(() => []);await AsyncStorage.multiRemove(keys.filter((key) => key.startsWith(PREFIX))).catch(() => undefined);}++/** Drop only this account's display/unread mirror after a confirmed personal removal. */+export const forgetRemoteResource = (userId: string, resourceId: string) => update(userId, s => {+ for (const id of Object.keys(s.items)) s.items[id] = s.items[id].filter(row => row.item.ref.id !== resourceId);+ for (const map of [s.read, s.readSequences ?? {}]) for (const key of Object.keys(map)) {+ try { if (JSON.parse(key)[1] === resourceId) delete map[key]; } catch { /* legacy cache key */ }+ }+});diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.jsonindex d73540e01b..840745a57a 100644--- a/apps/mobile/src/i18n/locales/en/groupChat.json+++ b/apps/mobile/src/i18n/locales/en/groupChat.json@@ -214,7 +214,10 @@"permissionDenied": "You do not have permission to manage this group.","serviceError": "The chat service could not complete the request. Try again later.","groupArchived": "This group is archived. This action is unavailable.",- "quoteUnavailable": "The quoted message was deleted or is no longer visible. The quote was removed. Send again."+ "quoteUnavailable": "The quoted message was deleted or is no longer visible. The quote was removed. Send again.",+ "lifecycleUnavailable": "The current server or computer does not support this action yet.",+ "groupDissolved": "This group has been dissolved. You can still read the available history.",+ "lastOwner": "Transfer ownership or dissolve this group before leaving."},"followUp": {"next": "Plan · Next step",@@ -227,5 +230,17 @@"attachmentFailed": "Couldn’t open the attachment. Try again.","previewUnavailable": "Preview unavailable","endpointUnavailable": "Group chat service configuration is unavailable. Please retry."+ },+ "lifecycle": {+ "dissolve": "Dissolve group",+ "dissolveNote": "This cannot be undone. Messaging will stop for everyone, active work will stop, and invitations will expire. Members keep access to the history they can already read.",+ "hide": "Remove from my list",+ "hideNote": "Remove this chat from your list on all your devices. This does not change membership, delete history, stop ongoing work, or affect other members.",+ "leave": "Leave group",+ "leaveNote": "You and your companions will leave this group. You will no longer receive new messages or have access to its history.",+ "unavailable": "The current server or computer does not support this action yet.",+ "dissolved": "This group has been dissolved. You can still read the available history.",+ "failed": "Could not complete this action. Try again.",+ "lastOwner": "Transfer ownership or dissolve this group before leaving."}}diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.jsonindex 4ce63ff62f..977879645d 100644--- a/apps/mobile/src/i18n/locales/ja/groupChat.json+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json@@ -214,7 +214,10 @@"permissionDenied": "このグループを管理する権限がありません。","serviceError": "チャットサービスで処理を完了できません。しばらくしてから再試行してください。","groupArchived": "このグループはアーカイブ済みのため操作できません。",- "quoteUnavailable": "引用したメッセージは削除されたか、表示できなくなりました。引用を外したので、もう一度送信してください。"+ "quoteUnavailable": "引用したメッセージは削除されたか、表示できなくなりました。引用を外したので、もう一度送信してください。",+ "lifecycleUnavailable": "現在のサーバーまたはコンピューターは、この操作にまだ対応していません。",+ "groupDissolved": "このグループは解散しました。閲覧権限のある履歴は引き続き確認できます。",+ "lastOwner": "退出する前にオーナーを譲渡するか、グループを解散してください。"},"followUp": {"next": "分担 · 次のステップ",@@ -227,5 +230,17 @@"attachmentFailed": "添付ファイルを開けませんでした。もう一度お試しください。","previewUnavailable": "プレビューを読み込めません","endpointUnavailable": "グループチャットのサービス設定を利用できません。再試行してください。"+ },+ "lifecycle": {+ "dissolve": "グループを解散",+ "dissolveNote": "この操作は取り消せません。全員がメッセージを送信できなくなり、進行中の作業は停止し、招待は無効になります。メンバーはこれまで閲覧できた履歴を引き続き確認できます。",+ "hide": "自分のリストから削除",+ "hideNote": "すべての自分のデバイスでリストからこのチャットを削除します。メンバーの状態、履歴、進行中の作業、他のメンバーには影響しません。",+ "leave": "グループを退出",+ "leaveNote": "あなたとあなたの仲間がグループから退出します。新しいメッセージは届かなくなり、グループの履歴を閲覧できなくなります。",+ "unavailable": "現在のサーバーまたはコンピューターは、この操作にまだ対応していません。",+ "dissolved": "このグループは解散しました。閲覧権限のある履歴は引き続き確認できます。",+ "failed": "操作を完了できませんでした。もう一度お試しください。",+ "lastOwner": "退出する前にオーナーを譲渡するか、グループを解散してください。"}}diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.jsonindex d3d5d0044e..da4bc20784 100644--- a/apps/mobile/src/i18n/locales/ko/groupChat.json+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json@@ -214,7 +214,10 @@"permissionDenied": "이 그룹을 관리할 권한이 없어요.","serviceError": "채팅 서비스에서 요청을 처리하지 못했어요. 잠시 후 다시 시도해 주세요.","groupArchived": "보관된 그룹에서는 이 작업을 수행할 수 없어요.",- "quoteUnavailable": "인용한 메시지가 삭제되었거나 더 이상 볼 수 없습니다. 인용을 해제했으니 다시 보내세요."+ "quoteUnavailable": "인용한 메시지가 삭제되었거나 더 이상 볼 수 없습니다. 인용을 해제했으니 다시 보내세요.",+ "lifecycleUnavailable": "현재 서버 또는 컴퓨터에서 아직 이 작업을 지원하지 않습니다.",+ "groupDissolved": "이 그룹은 해산되었습니다. 열람 권한이 있는 기록은 계속 볼 수 있습니다.",+ "lastOwner": "나가기 전에 소유권을 이전하거나 그룹을 해산하세요."},"followUp": {"next": "분담 · 다음 단계",@@ -227,5 +230,17 @@"attachmentFailed": "첨부 파일을 열지 못했습니다. 다시 시도해 주세요.","previewUnavailable": "미리보기를 불러올 수 없습니다","endpointUnavailable": "그룹 채팅 서비스 설정을 사용할 수 없습니다. 다시 시도해 주세요."+ },+ "lifecycle": {+ "dissolve": "그룹 해산",+ "dissolveNote": "이 작업은 되돌릴 수 없습니다. 모든 멤버의 메시지 전송이 중단되고 진행 중인 작업이 멈추며 초대가 만료됩니다. 멤버는 기존에 열람할 수 있었던 기록을 계속 볼 수 있습니다.",+ "hide": "내 목록에서 제거",+ "hideNote": "내 모든 기기의 목록에서 이 채팅을 제거합니다. 멤버 자격, 기록, 진행 중인 작업 및 다른 멤버에게 영향을 주지 않습니다.",+ "leave": "그룹 나가기",+ "leaveNote": "나와 내 동료가 이 그룹에서 나갑니다. 새 메시지를 받지 못하며 그룹 기록을 볼 수 없게 됩니다.",+ "unavailable": "현재 서버 또는 컴퓨터에서 아직 이 작업을 지원하지 않습니다.",+ "dissolved": "이 그룹은 해산되었습니다. 열람 권한이 있는 기록은 계속 볼 수 있습니다.",+ "failed": "작업을 완료하지 못했습니다. 다시 시도하세요.",+ "lastOwner": "나가기 전에 소유권을 이전하거나 그룹을 해산하세요."}}diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.jsonindex 525cb2a4aa..7cd1b76e32 100644--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json@@ -214,7 +214,10 @@"permissionDenied": "你没有执行此操作的群管理权限。","serviceError": "群聊服务处理失败,请稍后重试。","groupArchived": "本群已归档,不能执行此操作。",- "quoteUnavailable": "引用的消息已删除或不可见,已取消引用,请再发送一次"+ "quoteUnavailable": "引用的消息已删除或不可见,已取消引用,请再发送一次",+ "lifecycleUnavailable": "当前服务器或电脑暂不支持此操作。",+ "groupDissolved": "群聊已解散,仍可查看有权访问的历史消息。",+ "lastOwner": "请先转让群主或解散群聊,再退出。"},"followUp": {"next": "分工 · 下一步",@@ -227,5 +230,17 @@"attachmentFailed": "附件打开失败,请重试。","previewUnavailable": "暂时无法读取消息预览","endpointUnavailable": "群聊服务配置暂不可用,请重试。"+ },+ "lifecycle": {+ "dissolve": "解散群聊",+ "dissolveNote": "解散后无法恢复。所有成员将无法发送消息,进行中的工作会停止,邀请会失效。成员仍可查看原本有权访问的历史消息。",+ "hide": "从我的列表移除",+ "hideNote": "从你所有设备的列表中移除此群聊。不改变成员关系,不删除历史消息、不停止进行中的工作,也不影响其他成员。",+ "leave": "退出群聊",+ "leaveNote": "你和你的伙伴将退出此群聊,不再接收新消息,也无法查看群历史。",+ "unavailable": "当前服务器或电脑暂不支持此操作。",+ "dissolved": "群聊已解散,仍可查看有权访问的历史消息。",+ "failed": "操作未完成,请重试。",+ "lastOwner": "请先转让群主或解散群聊,再退出。"}}diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.jsonindex c9da227d32..5df08800a9 100644--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json@@ -214,7 +214,10 @@"permissionDenied": "你沒有執行此操作的群管理權限。","serviceError": "群聊服務處理失敗,請稍後重試。","groupArchived": "本群已封存,無法執行此操作。",- "quoteUnavailable": "引用的訊息已刪除或無法查看,已取消引用,請再傳送一次"+ "quoteUnavailable": "引用的訊息已刪除或無法查看,已取消引用,請再傳送一次",+ "lifecycleUnavailable": "目前伺服器或電腦尚不支援此操作。",+ "groupDissolved": "群聊已解散,仍可查看有權存取的歷史訊息。",+ "lastOwner": "請先轉讓群主或解散群聊,再退出。"},"followUp": {"next": "分工 · 下一步",@@ -227,5 +230,17 @@"attachmentFailed": "附件開啟失敗,請重試。","previewUnavailable": "暫時無法讀取訊息預覽","endpointUnavailable": "群聊服務設定暫時無法使用,請重試。"+ },+ "lifecycle": {+ "dissolve": "解散群聊",+ "dissolveNote": "解散後無法恢復。所有成員將無法傳送訊息,進行中的工作會停止,邀請會失效。成員仍可查看原本有權存取的歷史訊息。",+ "hide": "從我的列表移除",+ "hideNote": "從你所有裝置的列表中移除此群聊。不改變成員關係,不刪除歷史訊息、不停止進行中的工作,也不影響其他成員。",+ "leave": "退出群聊",+ "leaveNote": "你和你的伙伴將退出此群聊,不再接收新訊息,也無法查看群歷史。",+ "unavailable": "目前伺服器或電腦尚不支援此操作。",+ "dissolved": "群聊已解散,仍可查看有權存取的歷史訊息。",+ "failed": "操作未完成,請重試。",+ "lastOwner": "請先轉讓群主或解散群聊,再退出。"}}diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsxindex 04ecb29b37..dccf60a864 100644--- a/apps/mobile/src/session/BotGroupChatScreen.tsx+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx@@ -19,6 +19,7 @@ import {type NativeScrollEvent,type NativeSyntheticEvent,} from 'react-native';+import { showConfirm } from '@/platform/chrome';import { Stack, useRouter } from 'expo-router';import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';import { useTranslation } from 'react-i18next';@@ -192,6 +193,24 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceIdAlert.alert(chat.online ? botGroupActionErrorText(t, error, fallbackKey) : t(offlineKey));}, [chat.online, offlineKey, t]);+ const hidePending = useRef(false);+ const hideScope = useRef('');+ const currentHideScope = `${groupId}:${deviceId}:${accountGeneration}`;+ hideScope.current = currentHideScope;+ useEffect(() => () => { hideScope.current = ''; }, []);+ const removeFromList = async () => {+ if (hidePending.current) return;+ hidePending.current = true;+ const captured = currentHideScope;+ try {+ if (!await showConfirm({ title: t('groupChat.lifecycle.hide'), message: t('groupChat.lifecycle.hideNote'),+ cancelLabel: t('devices.common.cancel'), confirmLabel: t('groupChat.lifecycle.hide'), destructive: true }) || hideScope.current !== captured) return;+ await chat.act('hide');+ if (hideScope.current === captured) leave();+ } catch (error) { if (hideScope.current === captured) Alert.alert(botGroupActionErrorText(t, error, 'groupChat.lifecycle.failed')); }+ finally { hidePending.current = false; }+ };+const continueRound = async () => {if (continuing) return;setContinuing(true);@@ -295,6 +314,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceIdcopy={t(errorCopyKey)}><View style={styles.emptyActions}><MainWindowActionButton action={{ label: t('shared.back'), onPress: leave, testID: 'botGroup.leave' }} />+ {!failed ? <MainWindowActionButton action={{ label: t('groupChat.lifecycle.hide'), onPress: () => void removeFromList(), testID: 'botGroup.hide' }} /> : null}{failed ? <MainWindowActionButton action={{ label: t('devices.resources.retry'), tone: 'primary', onPress: chat.reload, testID: 'botGroup.retry' }} /> : null}</View></MainWindowEmptyState>@@ -308,6 +328,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId }: { deviceId)}>{floatingHeader ? null : offlineNote}+ {group.dissolvedAt ? <Text style={styles.offline}>{t('groupChat.lifecycle.dissolved')}</Text> : null}<ScrollView ref={scrollRef} style={styles.flex} contentContainerStyle={[styles.timeline, floatingHeader && { paddingTop: headerHeight + spacing.md }]}scrollIndicatorInsets={floatingHeader ? { top: headerHeight } : undefined} keyboardShouldPersistTaps="handled"keyboardDismissMode="interactive"diff --git a/apps/mobile/src/session/BotGroupSettingsSheet.tsx b/apps/mobile/src/session/BotGroupSettingsSheet.tsxindex a6efab447d..51307ffcc1 100644--- a/apps/mobile/src/session/BotGroupSettingsSheet.tsx+++ b/apps/mobile/src/session/BotGroupSettingsSheet.tsx@@ -13,7 +13,8 @@ import {type BotGroupReplyMode,type BotGroupSpeakingMode,} from '@cindy/maker-shared/botGroupChat';-import { isActiveBotGroupMember } from '@cindy/maker-shared/botGroupPresentation';+import { chatGroupMembership, isActiveBotGroupMember } from '@cindy/maker-shared/botGroupPresentation';+import { useAuth } from '@/auth/AuthContext';import { Text, TextInput } from '@/components/AppText';import { MainWindowOptionButton } from '@/components/MobilePrimitives';import { mobileInteractionStyles } from '@/components/mobileInteractionStyles';@@ -30,7 +31,7 @@ import { BotGroupMenu } from './BotGroupMenu';import { useBotGroupSettingsManagement } from './useBotGroupSettingsManagement';import { canManageBotGroup } from './botGroupRemote';-type Busy = 'name' | 'members' | 'organizer' | 'replyMode' | 'speakingMode' | 'delete' | null;+type Busy = 'name' | 'members' | 'organizer' | 'replyMode' | 'speakingMode' | 'delete' | 'lifecycle' | null;type Act = (actionId: BotGroupRemoteActionId, input?: Record<string, unknown>) => Promise<unknown>;type SettingsProps = {@@ -62,13 +63,21 @@ function ServerGroupSettings(props: SettingsProps) {identityFor={(id, name) => lookup(id, name, group.members.find(member => member.botId === id))}online={!!management.selected && !management.loading} readOnly={!management.selected || management.loading}act={async (action, input) => { const receipt = await management.act(action, input); props.onRefresh?.(); return receipt; }}- management={management} />;+ management={management} lifecycle={props} />;}-function BotGroupSettingsContent({ visible, group, host, identityFor, online, act, onClose, onClosed, onDeleted, readOnly = false, management }: SettingsProps & {+function BotGroupSettingsContent({ visible, group, host, identityFor, online, act, onClose, onClosed, onDeleted, readOnly = false, management, lifecycle }: SettingsProps & {management?: ReturnType<typeof useBotGroupSettingsManagement>;+ lifecycle?: SettingsProps;}) {const { t, i18n } = useTranslation();+ const { accountGeneration } = useAuth();+ const lifecycleProps = lifecycle ?? { visible, group, host, online, act, onDeleted };+ const lifecycleGroup = lifecycleProps.group;+ const membership = chatGroupMembership(lifecycleGroup);+ const scope = `${accountGeneration}:${lifecycleGroup.id}:${lifecycleProps.host.deviceId}:${visible}`;+ const active = useRef(scope); active.current = scope;+ useEffect(() => () => { active.current = ''; }, []);const { colors } = useTheme();const styles = useThemedStyles(makeStyles);const [name, setName] = useState(group.name);@@ -91,14 +100,14 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, acconst memberIds = group.members.map((member) => member.botId);- const owner = group.members.some(member => member.isOwned && member.role === 'owner');+ const { owner } = chatGroupMembership(group);const leavesGroup = group.serverBacked === true && management === undefined && !owner;const archivesGroup = (serverManaged && !leavesGroup) || management !== undefined;const canRemove = serverManaged || group.members.length > BOT_GROUP_MIN_MEMBERS;const canAdd = serverManaged || group.members.length < BOT_GROUP_MAX_MEMBERS;const addable = teammates.rows.filter((row) => !memberIds.includes(row.item.ref.id));const permissionLocked = serverManaged && !canManageBotGroup(group);- const unavailable = readOnly || permissionLocked || !online;+ const unavailable = readOnly || permissionLocked || !online || !!lifecycleGroup.dissolvedAt;const locked = unavailable || busy !== null;const deleteLocked = leavesGroup ? readOnly || !online || busy !== null : locked || (serverManaged && !owner);@@ -149,6 +158,21 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, acif (await run('delete', 'delete', {}, 'groupChat.settings.deleteFailed')) onDeleted();};+ const runLifecycle = async (action: 'dissolve' | 'leave' | 'hide') => {+ if (busyRef.current || !visible || !lifecycleProps.online) return;+ const captured = scope;+ busyRef.current = 'lifecycle'; setBusy('lifecycle');+ try {+ if (!await showConfirm({ title: t(`groupChat.lifecycle.${action}`), message: t(`groupChat.lifecycle.${action}Note`),+ cancelLabel: t('devices.common.cancel'), confirmLabel: t(`groupChat.lifecycle.${action}`), destructive: true }) || active.current !== captured) return;+ await lifecycleProps.act(action, action === 'dissolve' ? { expectedRevision: lifecycleGroup.revision } : undefined);+ if (active.current !== captured) return;+ if (action === 'hide') onDeleted();+ } catch (error) {+ if (active.current === captured) setErrors(current => ({ ...current, lifecycle: botGroupActionErrorText(t, error, 'groupChat.lifecycle.failed') }));+ } finally { busyRef.current = null; if (active.current === captured) setBusy(null); }+ };+const error = (section: Exclude<Busy, null>) => errors[section]? <Text accessibilityRole="alert" style={styles.error}>{errors[section]}</Text>: null;@@ -323,7 +347,7 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, ac</View></View>- <View style={[styles.section, (readOnly || !online) && styles.inheritedInactive]}>+ {(!group.serverBacked || (canManageBotGroup(group) && !group.dissolvedAt)) && <View style={[styles.section, (readOnly || !online) && styles.inheritedInactive]}><Pressable accessibilityRole="button" accessibilityLabel={t(archivesGroup ? 'groupChat.settings.archive' : 'groupChat.settings.delete')} disabled={deleteLocked}onPress={() => void remove()}style={({ pressed }) => [styles.group, styles.memberRow, pressed && mobileInteractionStyles.pressed, !readOnly && online && deleteLocked && styles.inactive]}@@ -333,7 +357,23 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, ac</Pressable><Text style={styles.note}>{t(archivesGroup ? 'groupChat.settings.archiveNote' : 'groupChat.settings.deleteNote')}</Text>{error('delete')}- </View>+ </View>}+ {lifecycleGroup.serverBacked && <View style={styles.section} testID="botGroup.settings.lifecycle">+ {lifecycleGroup.dissolvedAt ? <Text style={styles.note}>{t('groupChat.lifecycle.dissolved')}</Text> : null}+ {(['dissolve', 'leave', 'hide'] as const).filter(action => action === 'hide' || (!lifecycleGroup.dissolvedAt &&+ (action === 'dissolve' ? membership.owner : membership.canLeave))).map(action => {+ const supported = (action === 'leave' ? lifecycleGroup.supportsGroupLeave : action === 'dissolve' ? lifecycleGroup.supportsDissolve : lifecycleGroup.supportsListRemoval) === true;+ const disabled = !supported || !lifecycleProps.online || busy !== null;+ return <Pressable key={action} accessibilityRole="button" disabled={disabled} accessibilityState={{ disabled }}+ onPress={() => void runLifecycle(action)} testID={`botGroup.settings.${action}`}+ style={({ pressed }) => [styles.group, styles.memberRow, pressed && mobileInteractionStyles.pressed, disabled && styles.inactive]}>+ <Text style={[styles.rowTitle, styles.destructive]}>{t(`groupChat.lifecycle.${action}`)}</Text>+ </Pressable>;+ })}+ {((membership.owner && !lifecycleGroup.supportsDissolve) || !lifecycleGroup.supportsListRemoval || (membership.canLeave && !lifecycleGroup.supportsGroupLeave))+ ? <Text style={styles.note}>{t('groupChat.lifecycle.unavailable')}</Text> : null}+ {error('lifecycle')}+ </View>}</View></CompanionSheet>;}diff --git a/apps/mobile/src/session/botGroupCopy.ts b/apps/mobile/src/session/botGroupCopy.tsindex 1faba49add..1979bf5fd5 100644--- a/apps/mobile/src/session/botGroupCopy.ts+++ b/apps/mobile/src/session/botGroupCopy.ts@@ -9,6 +9,7 @@ type Translate = (key: string, options?: Record<string, unknown>) => string;* one the user can act on (PLAN_OPEN, MEMBER_LIMIT, …), otherwise the action's fallback line.*/export function botGroupActionErrorText(t: Translate, error: unknown, fallbackKey: string): string {+ if (/\bCONVERSATION_DISSOLVED\b/.test(formatRemoteError(error))) return t('groupChat.lifecycle.dissolved');if (/\b(?:PRECONDITION_FAILED|REVISION_CONFLICT)\b/.test(formatRemoteError(error))) return t('groupChat.settings.conflict');const timeout = /\bINVOKE_TIMEOUT\b/.test(formatRemoteError(error));const variant = botGroupErrorVariant(timeout ? 'REQUEST_TIMEOUT' : botGroupErrorCode(error));diff --git a/apps/mobile/src/session/botGroupRemote.ts b/apps/mobile/src/session/botGroupRemote.tsindex cc29f47db6..98774e35af 100644--- a/apps/mobile/src/session/botGroupRemote.ts+++ b/apps/mobile/src/session/botGroupRemote.ts@@ -31,6 +31,7 @@ import {} from '@cindy/maker-shared/botGroupChat';import { formatRemoteError } from '@cindy/maker-shared/device-link-contract';import { isPayloadDesktopLocalMediaUrl } from '@cindy/maker-shared/payload-summary';+import { chatGroupMembership } from '@cindy/maker-shared/botGroupPresentation';/** Member links point at the teammates collection; avatars come from its cached rows. */export const BOT_GROUP_TEAMMATES_COLLECTION_ID = 'teammates';@@ -43,7 +44,7 @@ export function botGroupResourceRef(groupId: string): RemoteResourceRef {export function canManageBotGroup(group: BotGroupRemoteChatData) {return group.serverBacked === true && !group.archived && group.supportsSettingsManagement === true- && group.revision !== undefined && group.members.some(member => member.isOwned && (member.role === 'owner' || member.role === 'admin'));+ && group.revision !== undefined && chatGroupMembership(group).manager;}function recordOf(value: unknown): Record<string, unknown> | null {@@ -346,6 +347,10 @@ export function parseBotGroupChatData(value: unknown): BotGroupRemoteChatData |name,serverBacked: record.serverBacked === true,archived: record.archived === true,+ dissolvedAt: text(record.dissolvedAt, 64),+ supportsDissolve: record.supportsDissolve === true,+ supportsGroupLeave: record.supportsGroupLeave === true,+ supportsListRemoval: record.supportsListRemoval === true,...(Number.isSafeInteger(record.revision) && Number(record.revision) > 0 ? { revision: Number(record.revision) } : {}),supportsMemberRemoval: record.supportsMemberRemoval === true,supportsSettingsManagement: record.supportsSettingsManagement === true,@@ -391,6 +396,9 @@ const ERROR_CODES: readonly BotGroupErrorCode[] = ['PERMISSION_DENIED','SERVICE_ERROR','GROUP_ARCHIVED',+ 'GROUP_DISSOLVED',+ 'LIFECYCLE_UNAVAILABLE',+ 'LAST_OWNER','MEMBER_LIMIT','MEMBER_UNAVAILABLE','MENTION_UNAVAILABLE',diff --git a/apps/mobile/src/session/useBotGroupChat.ts b/apps/mobile/src/session/useBotGroupChat.tsindex 2aa4b9c83d..5269622ca7 100644--- a/apps/mobile/src/session/useBotGroupChat.ts+++ b/apps/mobile/src/session/useBotGroupChat.ts@@ -90,20 +90,26 @@ export function useBotGroupChat(host: RemoteResourceHostTarget, groupId: string)const act = useCallback(async (actionId: BotGroupRemoteActionId, input?: Record<string, unknown>): Promise<RemoteActionInvokeResponse> => {try {await openLink(host.deviceId);- return await invokeRemoteResourceAction(invoke, host, {+ if (identityRef.current !== identity) throw new Error('OWNER_CHANGED');+ const receipt = await invokeRemoteResourceAction(<T,>(deviceId: string, channel: string, args?: unknown[]) =>+ invoke<T>(deviceId, channel, args, { preSend: () => { if (identityRef.current !== identity) throw new Error('OWNER_CHANGED'); } }), host, {collectionId: BOT_GROUP_REMOTE_COLLECTION_ID,actionId,resourceRef: botGroupResourceRef(groupId),...(input ? { input } : {}),}, i18n.language);+ if (actionId === 'hide' && identityRef.current === identity) {+ await server.acceptListState((receipt.result as { listState?: unknown } | undefined)?.listState);+ }+ 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' && identityRef.current === identity) reload();}- }, [groupId, host, i18n.language, identity, invoke, openLink, reload]);+ }, [groupId, host, i18n.language, identity, invoke, openLink, reload, server.acceptListState]);- const value: BotGroupChatState = !host.deviceId || !groupId+ const value: BotGroupChatState = !host.deviceId || !groupId || server.isListHidden()? { kind: 'missing' }: state.identity === identity ? state.value : { kind: 'loading' };void presenceVersion;diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 8379f8b4de..2185ec2191 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -24,6 +24,30 @@ Gateway 边界对整块报价校验,非法或无有效币种即整体省略,## 手机直连群的设置管理+### 群解散与个人列表移除++`GET /me` 明确声明 `groupLifecycleVersion: 1` / `conversationListStateVersion: 1` 才启用对应动作。+缺能力或旧副本拒绝时显示不可用,不回退为 archive 或兼容 delete。服务端合同及迁移由+`xindong/cindy-server#921` 提供;该 PR 的实际启动迁移核验与部署仍为独立上线条件。++`POST /conversations/:id/dissolve` 带 operationId 与正整数 expectedRevision,只允许 joined owner+(包括合法伙伴主人代演),且 kind 必须是 group。`dissolved_at` 是不可撤销的终态,归档只是其+旧客户端只读兼容投影。保留原历史权限,停止现有执行与分工、失效邀请均由服务端事务负责;+Desktop 收到终态后还会中止本机未完成的规划,沿原 lease 链停止执行;本机终止规划无需追加取消规划写入。++`POST /conversations/:id/list-state` 带 operationId、hidden 与本人列表 expectedRevision(初始0)。+它只移除本人账号跨设备列表,不退出、不删历史、不停止其他人的执行。已退出者通过+`GET /conversation-list-state` 获取状态,无需先读已无权限的群快照。启动及重连先取个人状态,+只合入更新的修订;成功回包或本人 human actor scope 的 `conversation.list.changed` 才清理本地+列表、选择与未读镜像,失败保留列表。手机同时订阅群和本人 human scope,代演不替换账号订阅。++现有 `bot-group-chat` 投影可选追加 supportsDissolve、supportsListRemoval、supportsGroupLeave、dissolvedAt;远程资源+动作 `dissolve` / `leave` / `hide` 分别转发相同的服务端动作。hide 的 opaque result 返回+`{listState:{conversationId,hidden,revision}}`,手机按修订合入同一账号投影,阻止旧电脑列表复活。+Desktop 既有群变化推送新增 list 类型及可选 listState;旧窗口忽略未知类型仍会刷新列表。+旧客户端与服务端可独立升级;完整行为要求服务端全副本及使用的客户端均支持。无新增 channel、+SQLite schema、Mobile 原生依赖或 fingerprint 输入。+现有 `bot-group-chat` 数据可选追加 `supportsSettingsManagement`。仅服务器群的新版 Host声明该能力,手机读取最新群详情和已有成员角色后才开放管理。设置动作可带`expectedRevision`,Host 在调用服务前核验,群信息 PATCH 和归档继续携带该编辑版本给diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex fea8a8d0a2..2d4caad674 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -6,6 +6,19 @@## 1. 定位与分期+### 服务器群生命周期++群主可以「解散群聊」,普通成员可以「退出群聊」,历史成员可以「从我的列表移除」。+三者独立确认、独立重试:解散不可撤销,停止所有成员的发言、进行中的执行与分工并失效邀请;+退出复用现有成员生命周期(包括带走本人伙伴),最后一个所属账号的群主需先转让或解散;+个人移除只改变本人账号在所有设备的列表,不退出、不删除历史、不影响其他成员或他们的工作。+退出后即使已不能读取群历史,仍可在不可用页面移除本人列表项。++解散仍保留原有权限内的历史;已退出者不会因解散重新取得访问权。归档可恢复,与解散分别呈现,+已解散群不能取消归档。桌面、手机直连和手机经电脑共用角色判断、五语言影响说明及现有破坏性确认。+能力未部署时明确不可用;旧服务器或旧电脑不通过归档/兼容删除冒充解散。服务端合同、部署前置与+兼容细节见 [`protocol-compatibility.md`](../dev-rules/protocol-compatibility.md) 的对应章节。+用户把自己的 2–6 位伙伴放进一个群,用户说一句,伙伴们按规则接话。群聊服务真实工作:一件事可以由几位伙伴讨论,也可以由负责人分好工,从策划、设计到开发一步步做完。diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 7ff2796829..3e30c936ac 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -275,6 +275,10 @@ OAuth 2.0 Device Authorization Grant 中由用户在另一设备验证页输入钉钉机器人连接的产品名称,沿用官方品牌写法;先登记为 proposed,待产品术语评审后再决定是否固化。+### Dissolve group++Irreversible group termination, distinct from archive, leave and personal list removal.+### Doubao模型显示品牌采用官方中文名称,版本号和变体原样保留;仅用于展示与搜索,不改模型 ID 或用户保存的名称。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 7277c364e5..bb04cbd8a3 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -5,6 +5,7 @@"sourceLocale": "en","punctuationExempt": ["desktop:settings.help.qnaFeedbackBodyTemplate"],"terms": [+ {"id": "dissolve-group", "status": "proposed", "en": "Dissolve group", "translations": {"zh-CN": "解散群聊", "zh-TW": "解散群聊", "ja": "グループを解散", "ko": "그룹 해산"}, "checkCase": false, "note": "Irreversible group termination, distinct from archive, leave and personal list removal."},{"id": "input-handoff", "status": "proposed", "en": "Input Handoff", "translations": {"zh-CN": "代输入", "zh-TW": "代輸入", "ja": "代理入力", "ko": "대리 입력"}, "checkCase": false, "note": "Agent 遇到需要主人填写的界面(选择、文本、密码、验证码、授权)时,由宿主读出当前一步,主人在本机或远程设备上填写,值只交给宿主、不进模型与记录。不是远程控制。"},{"id": "wallpaper-blur", "status": "proposed", "en": "Wallpaper Blur", "translations": {"zh-CN": "壁纸模糊", "zh-TW": "桌布模糊", "ja": "壁紙のぼかし", "ko": "배경화면 흐림"}, "note": "仅使应用壁纸柔化,不模糊文字或控件;0 为关闭,按用户选择应用于静态图片和视频。"},{"id": "group-owner", "status": "proposed", "en": "Group Owner", "translations": {"zh-CN": "群主", "zh-TW": "群主", "ja": "グループオーナー", "ko": "그룹 소유자"}, "checkCase": false, "note": "Chat Server 的群角色,可由人或伙伴担任;不要与伙伴主人或分工负责人混同。群设置成员行英文可简写 Owner。"},diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex ddc39830f5..00204857b2 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -88,6 +88,7 @@"./bot-learning": "./src/botLearning.ts","./botCollaboration": "./src/botCollaboration.ts","./botDirectMessage": "./src/botDirectMessage.ts",+ "./chatConversationList": "./src/chatConversationList.ts","./botGroupChat": "./src/botGroupChat.ts","./botGroupMentions": "./src/botGroupMentions.ts","./botGroupPresentation": "./src/botGroupPresentation.ts",diff --git a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts b/packages/maker-shared/src/__tests__/botGroupPresentation.test.tsindex 1d2a5c9d5a..e2062553e2 100644--- a/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts+++ b/packages/maker-shared/src/__tests__/botGroupPresentation.test.ts@@ -8,8 +8,30 @@ import {mergeBotGroupMessages,projectBotGroupExecutionFailures,botGroupExecutionFailureBatches,+ chatGroupMembership,} from '../botGroupPresentation.js';-import { BOT_GROUP_RUNTIME_FAILURE_CODES, readBotGroupExecutionFailure, type BotGroupErrorCode, type BotGroupExecutionFailureView, type BotGroupMessageView, type BotGroupNoticeCode, type BotGroupPlanView } from '../botGroupChat.js';+import { BOT_GROUP_RUNTIME_FAILURE_CODES, readBotGroupExecutionFailure, type BotGroupErrorCode, type BotGroupExecutionFailureView, type BotGroupMemberView, type BotGroupMessageView, type BotGroupNoticeCode, type BotGroupPlanView } from '../botGroupChat.js';++describe('server group membership affordances', () => {+ const self = { actorId: 'self', isSelf: true, isOwned: true, role: 'member' } as BotGroupMemberView;+ const ownBot = { actorId: 'own-bot', actorKind: 'bot', isOwned: true, role: 'owner' } as BotGroupMemberView;+ const otherOwner = { actorId: 'other-owner', isOwned: false, role: 'owner' } as BotGroupMemberView;+ it.each([+ { members: [self, otherOwner], owner: false, manager: false, canLeave: true },+ { members: [{ ...self, role: 'admin' as const }, otherOwner], owner: false, manager: true, canLeave: true },+ { members: [{ ...self, role: 'owner' as const }], owner: true, manager: true, canLeave: false },+ { members: [self, ownBot], owner: true, manager: true, canLeave: false },+ { members: [{ ...self, role: 'owner' as const }, ownBot], owner: true, manager: true, canLeave: false },+ { members: [self, ownBot, otherOwner], owner: true, manager: true, canLeave: true },+ { members: [self, ownBot, { ...otherOwner, isOwned: undefined }], owner: true, manager: true, canLeave: false },+ { members: [otherOwner], owner: false, manager: false, canLeave: false },+ ])('projects owner=$owner, manager=$manager, canLeave=$canLeave for $members', ({ members, ...expected }) => {+ expect(chatGroupMembership({ serverBacked: true, members })).toMatchObject(expected);+ });+ it('does not infer a server permission for a legacy local group', () => {+ expect(chatGroupMembership({ members: [self, ownBot] })).toMatchObject({ owner: false, manager: false, canLeave: false });+ });+});describe('execution failures are a projection of the current snapshot', () => {it('reconciles all loaded sources in bounded deduplicated requests', () => {diff --git a/packages/maker-shared/src/__tests__/chatConversationList.test.ts b/packages/maker-shared/src/__tests__/chatConversationList.test.tsnew file mode 100644index 0000000000..14f3512176--- /dev/null+++ b/packages/maker-shared/src/__tests__/chatConversationList.test.ts@@ -0,0 +1,45 @@+import { expect, it, vi } from 'vitest';+import { createConversationListState } from '../chatConversationList';+const id = '00000000-0000-4000-8000-000000000001';++it('keeps newer account events over a delayed startup/reconnect page', async () => {+ const list = createConversationListState();+ let resolve!: (value: unknown) => void;+ const reading = list.sync(vi.fn().mockImplementation(() => new Promise(done => { resolve = done; })));+ list.merge({ conversationId: id, hidden: true, revision: 3 });+ resolve([{ conversationId: id, hidden: false, revision: 2 }]);+ await reading;+ expect(list.hidden(id)).toBe(true);+ list.merge({ conversationId: id, hidden: false, revision: 4 });+ expect(list.hidden(id)).toBe(false);+});++it('does not hide on failed writes, then retries with the authoritative revision', async () => {+ const list = createConversationListState();+ const request = vi.fn().mockImplementation(async (_path, method) => {+ if (method === 'POST') throw new Error('REVISION_CONFLICT');+ return [{ conversationId: id, hidden: false, revision: 2 }];+ });+ await expect(list.setHidden(request, id, true, 'operation-one')).rejects.toThrow('REVISION_CONFLICT');+ expect(list.hidden(id)).toBe(false);+ expect(request).toHaveBeenLastCalledWith(`/conversations/${id}/list-state`, 'POST', { operationId: 'operation-one', hidden: true, expectedRevision: 2 });+ request.mockImplementation(async (_path, method) => method === 'POST'+ ? { conversationId: id, hidden: true, revision: 3 } : [{ conversationId: id, hidden: false, revision: 2 }]);+ await list.setHidden(request, id, true, 'operation-two');+ expect(list.hidden(id)).toBe(true);+ request.mockClear();+ await list.setHidden(request, id, true, 'operation-three');+ expect(request.mock.calls.every(call => call[1] !== 'POST')).toBe(true);+});++it('isolates accounts, validates write replies and can hide without any room snapshot', async () => {+ const first = createConversationListState();+ const second = createConversationListState();+ const request = vi.fn().mockImplementation(async (_path, method) => method === 'POST' ? { conversationId: id, hidden: true, revision: 1 } : []);+ await first.setHidden(request, id, true, 'operation-one');+ expect(first.hidden(id)).toBe(true);+ expect(second.hidden(id)).toBe(false);+ expect(request.mock.calls.map(call => call[0])).toEqual(['/conversation-list-state?limit=100', `/conversations/${id}/list-state`]);+ await expect(second.setHidden(vi.fn().mockImplementation(async (_path, method) => method === 'POST' ? {} : []), id, true, 'operation-two')).rejects.toThrow('INVALID_CHAT_LIST_STATE');+ expect(second.hidden(id)).toBe(false);+});diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.tsindex a92c6f6b4f..6303ce2c63 100644--- a/packages/maker-shared/src/botGroupChat.ts+++ b/packages/maker-shared/src/botGroupChat.ts@@ -284,6 +284,12 @@ export interface BotGroupRoundView {export interface BotGroupSummary {serverBacked?: boolean;+ /** Explicit server capabilities; absent on old servers/hosts. */+ supportsDissolve?: boolean;+ /** Upgraded host forwards leave explicitly; absent on old compatibility hosts. */+ supportsGroupLeave?: boolean;+ supportsListRemoval?: boolean;+ dissolvedAt?: string | null;archived?: boolean;migrationPending?: boolean;canInvite?: boolean;@@ -335,6 +341,9 @@ export type BotGroupErrorCode =| 'PERMISSION_DENIED'| 'SERVICE_ERROR'| 'GROUP_ARCHIVED'+ | 'GROUP_DISSOLVED'+ | 'LIFECYCLE_UNAVAILABLE'+ | 'LAST_OWNER'| 'INVALID_PARAMS'| 'REVISION_CONFLICT'| 'NOT_FOUND'@@ -424,11 +433,13 @@ export interface BotGroupGetOptions {sourceMessageIds?: string[];}-export type BotGroupChange = 'created' | 'updated' | 'deleted' | 'messages' | 'round' | 'plan';+export type BotGroupChange = 'created' | 'updated' | 'deleted' | 'messages' | 'round' | 'plan' | 'list';export interface BotGroupChangedPayload {groupId: string;change: BotGroupChange;+ /** Personal state, only emitted after an authoritative account-scoped reply/event. */+ listState?: { hidden: boolean; revision: number };}export function isBotGroupNoReplyText(text: string): boolean {@@ -459,7 +470,7 @@ export const BOT_GROUP_MEMBER_LINK_REL = 'member';* Remote actions. `create` is collection-level ({ name, botIds }); the others target a group:* `send` ({ text, mentions, clientId, division? }), `continue`, `stop`, `update`* ({ name?, replyMode?, speakingMode?, organizerBotId? } — never a host path),- * `set-members` ({ botIds }), `remove-member` ({ actorId }, capability-gated), `delete`, `plan-start` / `plan-dismiss` / `plan-continue` /+ * `set-members` ({ botIds }), `dissolve` ({ expectedRevision }), `leave`, `hide`, `remove-member` ({ actorId }, capability-gated), `delete`, `plan-start` / `plan-dismiss` / `plan-continue` /* `plan-retry` ({ planId }) and `plan-edit` ({ planId, position, action, botId? }).* A refused action fails with the `BotGroupErrorCode` as its message.*/@@ -473,6 +484,9 @@ export type BotGroupRemoteActionId =| 'add-member'| 'remove-member'| 'delete'+ | 'dissolve'+ | 'leave'+ | 'hide'| 'plan-start'| 'plan-dismiss'| 'plan-continue'@@ -551,9 +565,11 @@ export type ChatGroupAction =| { type: 'member'; actorId: string; action: 'invite' | 'leave' | 'remove' | 'ban' | 'unban' | 'role'; role?: 'admin' | 'member' }| { type: 'transfer'; actorId: string }| { type: 'botAccess'; actorId: string; access: 'none' | 'chat' | 'tools'; expectedRevision: number }+ | { type: 'dissolve'; expectedRevision: number }+ | { type: 'hide' }| { type: 'archive'; archived: boolean; expectedRevision: number };export interface ChatServerApi {- manage(input: { groupId: string; action: ChatGroupAction }): Promise<ChatServerResult<Record<never, never>>>;+ manage(input: { groupId: string; action: ChatGroupAction }): Promise<ChatServerResult<{ listState?: { conversationId: string; hidden: boolean; revision: number } }>>;ownedBots(): Promise<ChatServerResult<{ bots: Array<{ actorId: string; name: string }> }>>;refreshProfile(): Promise<ChatServerResult<Record<never, never>>>;status(): Promise<{ enabled: boolean; connected: boolean }>;diff --git a/packages/maker-shared/src/botGroupPresentation.ts b/packages/maker-shared/src/botGroupPresentation.tsindex fceead2bba..c66cf98153 100644--- a/packages/maker-shared/src/botGroupPresentation.ts+++ b/packages/maker-shared/src/botGroupPresentation.ts@@ -21,6 +21,19 @@ export function isActiveBotGroupMember(member: Pick<BotGroupMemberView, 'status'return member.status === 'active';}+/** UI affordances only; the server must authorize every mutation against current membership. */+export function chatGroupMembership(group: Pick<BotGroupSummary, 'serverBacked' | 'members'>) {+ const self = group.members.find(member => member.isSelf === true);+ const owned = (member: BotGroupMemberView) => member.isOwned === true || member.isSelf === true;+ const owner = group.serverBacked === true && group.members.some(member => owned(member) && member.role === 'owner');+ const manager = owner || (group.serverBacked === true && group.members.some(member => owned(member) && member.role === 'admin'));+ // Leaving also removes this account's companions. Another owner from this same account+ // therefore cannot satisfy LAST_OWNER, even when the human is only an ordinary member.+ const otherOwner = group.members.some(member => member.isOwned === false && !member.isSelf && member.role === 'owner');+ const canLeave = group.serverBacked === true && !!self?.actorId && (!owner || otherOwner);+ return { self, owner, manager, canLeave };+}+/** Latest activity first, like every other chat list. */export function sortBotGroups(groups: readonly BotGroupSummary[]): BotGroupSummary[] {const activityAt = (group: BotGroupSummary) =>@@ -112,6 +125,9 @@ export type BotGroupErrorVariant =| 'permissionDenied'| 'serviceError'| 'groupArchived'+ | 'groupDissolved'+ | 'lifecycleUnavailable'+ | 'lastOwner'| 'memberLimit'| 'memberUnavailable'| 'mentionUnavailable'@@ -133,6 +149,9 @@ const ERROR_VARIANTS: ReadonlyMap<string, BotGroupErrorVariant> = new Map<BotGro['PERMISSION_DENIED', 'permissionDenied'],['SERVICE_ERROR', 'serviceError'],['GROUP_ARCHIVED', 'groupArchived'],+ ['GROUP_DISSOLVED', 'groupDissolved'],+ ['LIFECYCLE_UNAVAILABLE', 'lifecycleUnavailable'],+ ['LAST_OWNER', 'lastOwner'],['MEMBER_LIMIT', 'memberLimit'],['MEMBER_UNAVAILABLE', 'memberUnavailable'],['MENTION_UNAVAILABLE', 'mentionUnavailable'],diff --git a/packages/maker-shared/src/chatConversationList.ts b/packages/maker-shared/src/chatConversationList.tsnew file mode 100644index 0000000000..685900e1ee--- /dev/null+++ b/packages/maker-shared/src/chatConversationList.ts@@ -0,0 +1,53 @@+/** Account-scoped projection. Never persist messages or turn a failed write into a local hide. */+export interface ConversationListState { conversationId: string; hidden: boolean; revision: number }+type Request = <T>(path: string, method?: 'GET' | 'POST', body?: unknown) => Promise<T>;+const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+function state(value: unknown): ConversationListState {+ const row = value as ConversationListState | null;+ if (!row || !uuid.test(row.conversationId) || typeof row.hidden !== 'boolean'+ || !Number.isSafeInteger(row.revision) || row.revision < 1) throw new Error('INVALID_CHAT_LIST_STATE');+ return row;+}++/** One instance per account/realm, shared by its roster, settings and subscriptions. */+export function createConversationListState() {+ const rows = new Map<string, ConversationListState>();+ const listeners = new Set<(row: ConversationListState) => void>();+ const merge = (value: unknown) => {+ const row = state(value);+ if ((rows.get(row.conversationId)?.revision ?? 0) >= row.revision) return;+ rows.set(row.conversationId, row);+ for (const notify of listeners) notify(row);+ };+ return {+ merge,+ hidden: (id: string) => rows.get(id)?.hidden === true,+ get: (id: string) => rows.get(id),+ revision: (id: string) => rows.get(id)?.revision ?? 0,+ ids: () => [...rows.keys()],+ subscribe(notify: (row: ConversationListState) => void) { listeners.add(notify); return () => { listeners.delete(notify); }; },+ async sync(request: Request) {+ let after: string | undefined;+ do {+ const page = await request<unknown[]>(`/conversation-list-state?limit=100${after ? `&after=${after}` : ''}`);+ if (!Array.isArray(page)) throw new Error('INVALID_CHAT_LIST_STATE');+ for (const value of page) merge(value);+ const next = page.length === 100 ? state(page.at(-1)).conversationId : undefined;+ if (next && after && next <= after) throw new Error('INVALID_CHAT_PAGE');+ after = next;+ } while (after);+ },+ async setHidden(request: Request, id: string, hidden: boolean, operationId: string) {+ if (!uuid.test(id)) throw new Error('INVALID_CHAT_ID');+ // Read first, including after leaving. A lost acknowledgement is safe to retry.+ await this.sync(request);+ if ((rows.get(id)?.hidden ?? false) === hidden) return;+ const result = state(await request(`/conversations/${id}/list-state`, 'POST', {+ operationId, hidden, expectedRevision: rows.get(id)?.revision ?? 0,+ }));+ if (result.conversationId !== id || result.hidden !== hidden) throw new Error('INVALID_CHAT_LIST_STATE');+ merge(result);+ if (rows.get(id)?.hidden !== hidden) throw new Error('REVISION_CONFLICT');+ },+ };+}