Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): manage cloud group settings without a computer
Chris8f770851e561
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsxindex 545698c765..0768e9a68b 100644--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx@@ -243,8 +243,8 @@ vi.mock('@/session/useBotGroupRemoteMedia', () => ({ useBotGroupRemoteMedia: ()vi.mock('@/session/useHostTeammates', () => ({ useHostTeammates: (_host: unknown, _enabled: boolean, query = '') => { h.teammateQuery = query; return h.teammates; } }));vi.mock('@/session/useBotGroupChat', () => ({ useBotGroupChat: () => h.chat }));vi.mock('@/session/useBotGroupSettingsManagement', () => ({ useBotGroupSettingsManagement: () => h.management ?? ({- selected: undefined, managers: [], loading: false, reason: 'noHost', act: vi.fn(), select: vi.fn(), refresh: vi.fn(),-}) }));+ group: undefined, editable: false, loading: false, reason: 'unavailable', act: vi.fn(), refresh: vi.fn(),+}), useCloudGroupCandidates: () => ({ ...h.teammates, rows: h.teammates.rows.map(row => ({ id: row.item.ref.id, name: row.item.display.title, avatar: null })) }) }));vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }));vi.mock('@/session/CompanionPresenceRing', () => ({ CompanionPresenceRing: () => null }));@@ -1274,20 +1274,20 @@ describe('group settings', () => {expect(h.chat.act).toHaveBeenLastCalledWith('update', { name: '保留草稿' });});- it('edits a direct server group through the management host while chat stays direct', async () => {+ it('edits a direct server group without management computer UI while chat stays direct', async () => {const data = group({ serverBacked: true, supportsSettingsManagement: true, supportsMemberRemoval: true, revision: 5 });data.members[0] = { ...data.members[0], isOwned: true, role: 'owner' };h.chat.server = true;const manage = vi.fn(async () => ({ effects: [] }));- h.management = { displayHost: { deviceId: 'pc', deviceName: 'PC' }, selected: { host: { deviceId: 'pc', deviceName: 'PC' }, group: data }, managers: [], loading: false, reason: null,+ h.management = { group: data, editable: true, loading: false, reason: null,act: manage, refresh: vi.fn(), select: vi.fn() };h.teammates = { rows: [{ key: 'new', host: { deviceId: 'pc', deviceName: 'PC' }, item: {ref: { collectionId: 'teammates', kind: 'bot', id: 'new-bot' }, revision: '1', display: { title: 'New bot' }, links: [],} }], loading: false, failed: false };await openSettings(data);expect(h.inputs['botGroup.settings.name'].editable).toBe(true);- expect(byId('botGroup.settings.managementStatus')?.textContent).toBe('groupChat.settings.managementStatus.ready');- expect(byId('botGroup.settings.connectedDot')).not.toBeNull();+ expect(byId('botGroup.settings.management')).toBeNull();+ expect(byId('botGroup.settings.connectedDot')).toBeNull();expect(byId('botGroup.settings.retry')).toBeNull();expect(byId('botGroup.settings.body')?.style.opacity).toBe('');await act(async () => { h.inputs['botGroup.settings.name'].onChangeText('Managed'); });@@ -1298,15 +1298,39 @@ describe('group settings', () => {expect(manage).toHaveBeenLastCalledWith('add-member', { botId: 'new-bot', expectedRevision: 5 });});+ // Cloud description drafts must survive a concurrent edit; role changes use the selected member.+ it('preserves a conflicted cloud description and changes a member role', async () => {+ const data = group({ serverBacked: true, supportsSettingsManagement: true, revision: 5, description: 'Original' });+ data.members[0] = { ...data.members[0], isOwned: true, role: 'owner' };+ data.members[1] = { ...data.members[1], actorId: 'member-actor', role: 'member' };+ const manage = vi.fn(async () => ({ effects: [] }));+ h.chat.server = true;+ h.management = { group: data, editable: true, loading: false, reason: null, act: manage, refresh: vi.fn() };+ await openSettings(data);+ await act(async () => { h.inputs['botGroup.settings.description'].onChangeText('My draft'); });+ manage.mockRejectedValueOnce(new Error('REVISION_CONFLICT'));+ await act(async () => { h.inputs['botGroup.settings.description'].onBlur(); });+ expect(manage).toHaveBeenLastCalledWith('update', { description: 'My draft', expectedRevision: 5 });+ expect(h.inputs['botGroup.settings.description'].value).toBe('My draft');+ expect(byId('botGroup.settings')?.textContent).toContain('groupChat.settings.conflict');+ h.management.group = { ...data, description: 'Other edit', revision: 6 };+ await render(h.management.group);+ expect(h.inputs['botGroup.settings.description'].value).toBe('My draft');+ await act(async () => { h.inputs['botGroup.settings.description'].onBlur(); });+ expect(manage).toHaveBeenLastCalledWith('update', { description: 'My draft', expectedRevision: 6 });+ await click(`botGroup.settings.memberMenu.${data.members[1].botId}.action.role:${data.members[1].botId}`);+ expect(manage).toHaveBeenLastCalledWith('set-member-role', { actorId: 'member-actor', role: 'admin' });+ });+it('explains unavailable management and offers retry without enabling edits', async () => {const refresh = vi.fn();- h.management = { displayHost: { deviceId: 'pc', deviceName: 'PC' }, selected: undefined, managers: [], loading: false, reason: 'noHost', act: vi.fn(), select: vi.fn(), refresh };+ h.management = { editable: false, loading: false, reason: 'unavailable', act: vi.fn(), refresh };h.chat.server = true; await openSettings(group({ serverBacked: true }));expect(h.inputs['botGroup.settings.name'].editable).toBe(false);expect(byId('botGroup.settings.body')?.style.opacity).toBe('0.6');- expect(byId('botGroup.settings.managementStatus')?.textContent).toBe('groupChat.settings.managementStatus.noHost');- expect(byId('botGroup.settings.computerName')?.textContent).toBe('PC');- expect(byId('botGroup.settings.retry')?.textContent).toBe('groupChat.settings.reconnect');+ expect(byId('botGroup.settings.managementStatus')?.textContent).toBe('groupChat.settings.cloudStatus.unavailable');+ expect(byId('botGroup.settings.computerName')).toBeNull();+ expect(byId('botGroup.settings.retry')?.textContent).toBe('groupChat.settings.retry');expect((byId('botGroup.settings.member.mimi') as HTMLButtonElement)?.disabled).toBe(true);await click('botGroup.settings.add');expect(byId('botGroup.settings.addable')).toBeNull();@@ -1318,13 +1342,13 @@ describe('group settings', () => {expect(byId('botGroup.settings')?.textContent).not.toContain('groupChat.settings.deleteNote');});- it.each(['upgrade', 'permission', 'unavailable', 'loading'])('keeps the %s reason explicit in the compact status row', async reason => {+ it.each(['permission', 'unavailable', 'loading'])('keeps the %s reason explicit in the compact status row', async reason => {const refresh = vi.fn();h.chat.server = true;- h.management = { selected: undefined, managers: [], loading: reason === 'loading', reason: reason === 'loading' ? null : reason,+ h.management = { editable: false, loading: reason === 'loading', reason: reason === 'loading' ? null : reason,act: vi.fn(), select: vi.fn(), refresh };await openSettings(group({ serverBacked: true }));- expect(byId('botGroup.settings.managementStatus')?.textContent).toBe(`groupChat.settings.managementStatus.${reason}`);+ expect(byId('botGroup.settings.managementStatus')?.textContent).toBe(`groupChat.settings.cloudStatus.${reason}`);expect(h.inputs['botGroup.settings.name'].editable).toBe(false);if (reason === 'loading') {expect(byId('botGroup.settings.connecting')).not.toBeNull();@@ -1407,8 +1431,8 @@ describe('group settings', () => {const data = group({ serverBacked: true, supportsSettingsManagement: true, revision: 5 });data.members[0] = { ...data.members[0], isOwned: true, role: 'admin' };h.chat.server = true;- h.management = { selected: { host: { deviceId: 'pc', deviceName: 'PC' }, group: data }, managers: [], loading: false, reason: null,- act: vi.fn(), refresh: vi.fn(), select: vi.fn() };+ h.management = { group: data, editable: true, loading: false, reason: null,+ act: vi.fn(), refresh: vi.fn() };await openSettings(data);expect(byId('botGroup.settings.delete')?.disabled).toBe(true);await click('botGroup.settings.delete');diff --git a/apps/mobile/src/__tests__/useBotGroupSettingsManagement.test.tsx b/apps/mobile/src/__tests__/useBotGroupSettingsManagement.test.tsxindex 34442d2ab6..b3517bafe1 100644--- a/apps/mobile/src/__tests__/useBotGroupSettingsManagement.test.tsx+++ b/apps/mobile/src/__tests__/useBotGroupSettingsManagement.test.tsx@@ -1,273 +1,155 @@// @vitest-environment jsdom+// Regression: cloud group settings used to require an online computer. Unit tier exercises+// the production hook + HTTP client with no device-link provider, including account fences,+// server role revocation, edit conflicts and uncertain write receipts. Existing tests covered hosts only.import { act, createElement } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, beforeEach, expect, it, vi } from 'vitest';--const h = vi.hoisted(() => ({- generation: 1, enabled: true, revoked: new Set<string>(), online: true, listOnline: true, syncing: false, listError: null as string | null,- targets: [{ deviceId: 'mac', deviceName: 'Mac' }, { deviceId: 'pc', deviceName: 'PC' }],- items: [] as any[], listeners: new Set<(id: string, payload: any) => void>(),- invoke: vi.fn(), openLink: vi.fn(async () => {}), epoch: 1,-}));-vi.mock('react-native', () => ({ AppState: {} }));-vi.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'en' } }) }));-vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: h.generation }) }));-vi.mock('@/device-link/revokedDevicesStore', () => ({ useRevokedDevices: () => h.revoked }));-vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({- invoke: h.invoke, openLink: h.openLink, status: 'online', connectionEpoch: h.epoch,- getPresenceAvailability: () => h.online,- onRemoteResourceChanged: onChanged,-}) }));-function onChanged(listener: (id: string, payload: any) => void) { h.listeners.add(listener); return () => h.listeners.delete(listener); }-vi.mock('@/session/useTeammateRoster', () => ({ useTeammateRoster: () => ({ groupTargets: h.targets, loading: h.syncing, error: h.listError, refresh: vi.fn() }) }));-vi.mock('@/session/useRemoteResourceList', () => ({ useRemoteResourceList: () => ({- items: h.items, syncing: h.syncing, isOnline: () => h.online && h.listOnline, error: h.listError, refresh: vi.fn(),-}) }));--import { useBotGroupSettingsManagement } from '@/session/useBotGroupSettingsManagement';--const host = { deviceId: 'mac', deviceName: 'Mac' };-const row = (id = 'g1', target = host) => ({ host: target, item: { ref: { collectionId: 'bot-groups', kind: 'bot-group', id }, revision: 'v1' } });-const resource = (role = 'owner', extra: Record<string, unknown> = {}) => ({- ref: { collectionId: 'bot-groups', kind: 'bot-group', id: 'g1' }, revision: 'v1', display: { title: 'Group' }, links: [],- blocks: [{ id: 'chat', primitive: 'bot-group-chat', fallbackMarkdown: '', data: {- id: 'g1', name: 'Group', serverBacked: true, supportsSettingsManagement: true, revision: 4,- members: [{ botId: 'bot', name: 'Bot', isOwned: true, role, status: 'active' }],- messages: [], plans: [], round: { status: 'idle', speakers: [], canContinue: false }, ...extra,- } }],-});+import { chatGroupView, createChatServerClient, type ChatSnapshot } from '@/chat/chatServerClient';+const h = vi.hoisted(() => ({ api: null as any, enabled: true, uuid: 0 }));+vi.mock('expo-crypto', () => ({ randomUUID: () => `operation-${++h.uuid}` }));+vi.mock('@/chat/useChatServer', () => ({ useChatClient: () => h.api }));+import { useBotGroupSettingsManagement, useCloudGroupCandidates } from '@/session/useBotGroupSettingsManagement';+const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;+let snapshot: ChatSnapshot;let root: Root | undefined;let result: ReturnType<typeof useBotGroupSettingsManagement>;-function Probe() { result = useBotGroupSettingsManagement('g1', h.enabled); return null; }+let candidates: ReturnType<typeof useCloudGroupCandidates>;+let source: ReturnType<typeof chatGroupView>;+const request = vi.fn();+const writes = () => request.mock.calls.filter(call => call[1] === 'POST' || call[1] === 'PATCH');+function Probe() { result = useBotGroupSettingsManagement(source, h.enabled); candidates = useCloudGroupCandidates(h.enabled); return null; }async function render() { root ??= createRoot(document.createElement('div')); await act(async () => root!.render(createElement(Probe))); }-const reads = () => h.invoke.mock.calls.filter(call => call[1] === 'maker:remote-resources:get');-const writes = () => h.invoke.mock.calls.filter(call => call[1] === 'maker:remote-resources:invoke');+function api(owner = 'account-1') {+ return { owner, enabled: true, current: () => h.api.owner === owner, client: createChatServerClient(request) };+}Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });beforeEach(() => {- vi.clearAllMocks(); h.enabled = true; h.generation = 1; h.epoch = 1; h.online = true; h.syncing = false; h.revoked = new Set(); h.listeners.clear();- h.listOnline = true; h.listError = null;- h.targets = [{ deviceId: 'mac', deviceName: 'Mac' }];- h.items = [row()]; h.openLink.mockResolvedValue();- h.invoke.mockImplementation(async (_id, channel) => channel === 'maker:remote-resources:get' ? resource() : { effects: [] });-});-afterEach(() => { act(() => root?.unmount()); root = undefined; });--it('reads the exact room and sends settings only to its verified host with a revision', async () => {- h.targets.push({ deviceId: 'pc', deviceName: 'PC' });- h.invoke.mockImplementation(async (id, channel) => channel === 'maker:remote-resources:get'- ? resource('owner', id === 'pc' ? { id: 'other' } : {}) : { effects: [] });- await render();- expect(reads()).toHaveLength(2);- expect(result.selected?.host.deviceId).toBe('mac');- expect(result.reason).toBeNull();- await act(async () => { await result.act('update', { name: 'New name' }); });- expect(writes()[0]?.slice(0, 2)).toEqual(['mac', 'maker:remote-resources:invoke']);- expect(writes()[0]?.[2][0]).toMatchObject({ actionId: 'update', resourceRef: { id: 'g1' }, input: { name: 'New name', expectedRevision: 4 } });-});--it('probes the exact room even when it is absent from a truncated group list', async () => {- h.targets = [host];- h.items = Array.from({ length: 200 }, (_, index) => row(`other-${index}`));- await render();- expect(reads()).toHaveLength(1);- expect(reads()[0]?.[2][0].ref.id).toBe('g1');- expect(result.selected?.host.deviceId).toBe('mac');-});--it('blocks consecutive edits until the successful write is read back with its new revision', async () => {- await render();- let revision = 4; let finishRead!: (value: unknown) => void;- h.invoke.mockImplementation(async (_id, channel, args) => {- if (channel === 'maker:remote-resources:get') return new Promise(resolve => { finishRead = resolve; });- if (args[0].input.expectedRevision !== revision) throw new Error('PRECONDITION_FAILED');- revision += 1;- return { effects: [] };- });- await act(async () => {- await result.act('update', { name: 'Renamed' });- // Also exercise the interval before React commits the refreshed controls.- await expect(result.act('update', { organizerBotId: 'bot' })).rejects.toThrow('PERMISSION_DENIED');+ vi.clearAllMocks(); h.enabled = true; h.uuid = 0;+ snapshot = { room: { id: id(1), name: 'Group', description: 'Original', kind: 'group', archived: false, revision: 4,+ response_mode: 'all', speaking_mode: 'auto', created_at: '2026-10-01', updated_at: '2026-10-01' }, cursor: '1', messages: [], members: [+ { id: id(2), kind: 'human', ownerActorId: id(2), ownerName: '', name: 'Me', avatar: null, state: 'joined', role: 'owner' },+ { id: id(3), kind: 'bot', ownerActorId: id(2), ownerName: '', name: 'Bot', avatar: null, state: 'joined', role: 'member' },+ ] };+ source = chatGroupView({ snapshot, messages: [], before: null }, id(2));+ request.mockImplementation(async (path, method, body) => {+ if (path === '/me') return { actor: { id: id(2), kind: 'human' }, capabilities: { groupSingleSpeaker: 1 } };+ if (path === '/actors') return [{ id: id(4), kind: 'bot', externalId: 'offline-bot', name: 'Offline bot', avatar: null, homeDeviceId: null }];+ if (path.endsWith('/snapshot')) return structuredClone(snapshot);+ if (method === 'PATCH') {+ if (!['owner', 'admin'].includes(snapshot.members[0].role)) throw Object.assign(new Error('ROLE_REQUIRED'), { status: 403 });+ if (body.expectedRevision !== snapshot.room.revision) throw Object.assign(new Error('REVISION_CONFLICT'), { status: 409 });+ if (body.name !== undefined) snapshot.room.name = body.name;+ if (body.description !== undefined) snapshot.room.description = body.description;+ snapshot.room.revision++;+ return { revision: snapshot.room.revision };+ }+ if (method === 'POST') return { state: 'joined' };+ throw new Error(`Unexpected ${path}`);});- expect(writes()).toHaveLength(1); expect(result.selected).toBeUndefined(); expect(result.loading).toBe(true);- await act(async () => { finishRead(resource('owner', { name: 'Renamed', revision })); });- expect(result.selected?.group.revision).toBe(5);- await act(async () => { await result.act('update', { organizerBotId: 'bot' }); });- expect(writes()[1]?.[2][0].input.expectedRevision).toBe(5);-});--it('does not restore the pre-write revision from an already pending background read', async () => {- await render(); const finishes: ((value: unknown) => void)[] = [];- h.invoke.mockImplementation(async (_id, channel) => channel === 'maker:remote-resources:get'- ? new Promise(resolve => { finishes.push(resolve); }) : { effects: [] });- await act(async () => { result.refresh(); });- await act(async () => { await result.act('update', { name: 'Renamed' }); });- await act(async () => { finishes.shift()!(resource()); });- expect(result.selected).toBeUndefined(); expect(finishes).toHaveLength(1);- await expect(result.act('add-member', { botId: 'other' })).rejects.toThrow('PERMISSION_DENIED');- await act(async () => { finishes.shift()!(resource('owner', { revision: 5, name: 'Renamed' })); });- expect(result.selected?.group.revision).toBe(5); expect(writes()).toHaveLength(1);+ h.api = api();});+afterEach(() => { act(() => root?.unmount()); root = undefined; });-it('keeps a confirmed save successful but disables further edits if readback fails', async () => {+it('reads and saves cloud settings and offers offline companions without any host connection', async () => {await render();- h.invoke.mockImplementation(async (_id, channel) => {- if (channel === 'maker:remote-resources:get') throw new Error('Read failed');- return { effects: [] };+ expect(result.editable).toBe(true);+ expect(result.group).toMatchObject({ description: 'Original', singleSpeaker: true });+ expect(candidates.rows.map(row => row.id)).toEqual([id(4)]);+ await act(async () => { await result.act('update', { name: 'Renamed', description: 'Shared background', replyMode: 'mentioned', organizerBotId: id(3) }); });+ expect(writes()[0]).toEqual([`/conversations/${id(1)}`, 'PATCH', { operationId: 'operation-1', expectedRevision: 4, name: 'Renamed', description: 'Shared background', responseMode: 'mentioned', organizerId: id(3) }, id(2)]);+ expect(result.group).toMatchObject({ name: 'Renamed', description: 'Shared background', revision: 5 });+ await act(async () => { await result.act('add-member', { botId: id(4) }); await result.act('set-member-role', { actorId: id(3), role: 'admin' }); await result.act('remove-member', { actorId: id(3) }); });+ expect(writes().slice(1).map(call => call[2])).toEqual([+ { operationId: 'operation-2', actorId: id(4), action: 'invite' },+ { operationId: 'operation-3', actorId: id(3), action: 'role', role: 'admin' },+ { operationId: 'operation-4', actorId: id(3), action: 'remove' },+ ]);+});++it.each(['member', 'guest'] as const)('keeps %s read-only based on account membership', async role => {+ snapshot.members[0].role = role; await render();+ expect(result.reason).toBe('permission');+ await expect(result.act('update', { name: 'Denied' })).rejects.toThrow('PERMISSION_DENIED');+ expect(writes()).toHaveLength(0);+});++it('selects only an owned manager, never a foreign owner', async () => {+ snapshot.members[0].role = 'member'; snapshot.members[1].role = 'admin';+ snapshot.members.push({ ...snapshot.members[0], id: id(9), ownerActorId: id(9), role: 'owner' });+ await render(); await act(async () => { await result.act('add-member', { botId: id(4) }); });+ expect(writes()[0][3]).toBe(id(3));+});++it('reloads revoked roles after a rejected write without reporting it saved', async () => {+ await render(); snapshot.members[0].role = 'member';+ await act(async () => { await expect(result.act('update', { name: 'Denied' })).rejects.toThrow('ROLE_REQUIRED'); });+ expect(result.editable).toBe(false); expect(result.reason).toBe('permission');+ expect(result.group?.name).toBe('Group');+});++it('preserves the edit revision and returns conflicts instead of overwriting a newer value', async () => {+ await render(); snapshot.room.revision = 5; snapshot.room.name = 'Other edit';+ await act(async () => { await expect(result.act('update', { name: 'My draft', expectedRevision: 4 })).rejects.toThrow('REVISION_CONFLICT'); });+ expect(result.group).toMatchObject({ revision: 5, name: 'Other edit' });+ await act(async () => { await result.act('update', { name: 'Reviewed draft', expectedRevision: 5 }); });+ expect(writes()[1][2].operationId).not.toBe(writes()[0][2].operationId);+});++it('reuses the operation receipt on an explicit retry after an uncertain network result', async () => {+ await render(); const original = request.getMockImplementation()!; let fail = true;+ request.mockImplementation(async (...args) => { if (args[1] === 'POST' && fail) { fail = false; throw new Error('Network lost'); } return original(...args); });+ await act(async () => { await expect(result.act('add-member', { botId: id(4) })).rejects.toThrow('Network lost'); });+ await act(async () => { await result.act('add-member', { botId: id(4) }); });+ expect(writes()).toHaveLength(2); expect(writes()[0]).toEqual(writes()[1]);+});++it('replays the original write after a lost acknowledgement advances the readback revision', async () => {+ await render(); const original = request.getMockImplementation()!;+ let receipt: unknown;+ request.mockImplementation(async (...args) => {+ if (args[1] !== 'PATCH') return original(...args);+ if (receipt) return receipt;+ receipt = await original(...args);+ throw new Error('Acknowledgement lost');});- await act(async () => { await expect(result.act('update', { name: 'Renamed' })).resolves.toEqual({ effects: [] }); });- expect(result.selected).toBeUndefined(); expect(result.reason).toBe('unavailable');- await expect(result.act('add-member', { botId: 'other' })).rejects.toThrow('PERMISSION_DENIED');- h.invoke.mockResolvedValue(resource('owner', { revision: 5 }));- await act(async () => { result.refresh(); });- expect(result.selected?.group.revision).toBe(5); expect(writes()).toHaveLength(1);-});--it.each(['member', 'guest'])('keeps %s read-only even on an online matching computer', async role => {- h.invoke.mockResolvedValue(resource(role)); await render();- expect(result.selected).toBeUndefined(); expect(result.reason).toBe('permission');- await expect(result.act('update', { name: 'Denied' })).rejects.toThrow('PERMISSION_DENIED'); expect(writes()).toHaveLength(0);-});--it.each([{ supportsSettingsManagement: false }, { revision: undefined }, { archived: true }, { members: [{ botId: 'foreign', name: 'Foreign', role: 'owner', isOwned: false }] }])('does not grant management for an unsupported or unauthorized projection: %j', async extra => {- h.invoke.mockResolvedValue(resource('owner', extra)); await render(); expect(result.selected).toBeUndefined();-});--it('never uses offline or revoked cached rows as authority', async () => {- h.online = false; await render(); expect(reads()).toHaveLength(0); expect(result.selected).toBeUndefined();- h.online = true; h.revoked = new Set(['mac']); await render(); expect(reads()).toHaveLength(0);-});--it('allows choosing among multiple independently verified computers', async () => {- h.targets.push({ deviceId: 'pc', deviceName: 'PC' });- h.items = [row(), row('g1', h.targets[1])]; await render(); expect(result.managers).toHaveLength(2);- await act(async () => { result.select('pc'); });- await act(async () => { await result.act('add-member', { botId: 'local-pc-bot' }); });- expect(writes()[0]?.[0]).toBe('pc');-});--it('does not send a write if the account changes while opening its link', async () => {- await render(); let finish!: () => void;- h.openLink.mockImplementation(() => new Promise<void>(resolve => { finish = resolve; }));- let pending!: Promise<unknown>; await act(async () => { pending = result.act('update', { name: 'Late' }); });- h.generation = 2; h.enabled = false; await render(); finish();- await expect(pending).rejects.toThrow('PERMISSION_DENIED'); expect(writes()).toHaveLength(0);-});--it('ignores a late read after closing settings', async () => {- let finish!: (value: unknown) => void;- h.invoke.mockImplementation(() => new Promise(resolve => { finish = resolve; })); await render();- h.enabled = false; await render(); await act(async () => { finish(resource()); });- expect(result.selected).toBeUndefined(); expect(writes()).toHaveLength(0);-});--it('preserves the revision of a name draft when sending it', async () => {- await render(); await act(async () => { await result.act('update', { name: 'Draft', expectedRevision: 2 }); });- expect(writes()[0]?.[2][0].input.expectedRevision).toBe(2);-});--it('disables a previously verified computer when presence goes offline', async () => {- await render(); expect(result.selected).toBeDefined();- h.online = false; await render(); expect(result.selected).toBeUndefined();- await expect(result.act('update')).rejects.toThrow('PERMISSION_DENIED');-});--it('keeps the selected device name through reconnecting without retaining write authority', async () => {- h.targets.push({ deviceId: 'pc', deviceName: 'PC' });- h.items = [row(), row('g1', h.targets[1])]; await render();- await act(async () => { result.select('pc'); });- h.online = false; h.items = []; await render();- expect(result.displayHost?.deviceName).toBe('PC');- expect(result.selected).toBeUndefined();- await expect(result.act('update')).rejects.toThrow('PERMISSION_DENIED');- h.enabled = false; await render(); h.enabled = true; h.syncing = true; await render();- expect(result.loading).toBe(true);- expect(result.displayHost?.deviceName).toBe('PC');- h.generation = 2; await render();- expect(result.displayHost).toBeUndefined();-});--it('does not reuse the previous authorization while a reopened sheet is being verified', async () => {- await render(); h.enabled = false; await render();- let finish!: (value: unknown) => void;- h.invoke.mockImplementation(() => new Promise(resolve => { finish = resolve; }));- h.enabled = true; await render();- expect(result.loading).toBe(true); expect(result.selected).toBeUndefined();- await act(async () => { finish(resource('member')); });- expect(result.selected).toBeUndefined(); expect(result.reason).toBe('permission');-});--it('rejects a receipt from an earlier opening of the same sheet', async () => {- await render(); let finish!: (value: unknown) => void;- h.invoke.mockImplementation(async (_id, channel) => channel === 'maker:remote-resources:invoke'- ? new Promise(resolve => { finish = resolve; }) : resource());- let pending!: Promise<unknown>;- await act(async () => { pending = result.act('update', { name: 'Late' }); });- h.enabled = false; await render(); h.enabled = true; await render();- await act(async () => { finish({ effects: [] }); await expect(pending).rejects.toThrow('PERMISSION_DENIED'); });-});--it('checks the sheet identity again when a queued write actually leaves the transport', async () => {- await render(); let send!: () => void; let sent = false;- h.invoke.mockImplementation(async (_id, channel, _args, opts) => channel === 'maker:remote-resources:invoke'- ? new Promise((resolve, reject) => { send = () => { try { opts?.preSend?.(); sent = true; resolve({ effects: [] }); } catch (error) { reject(error); } }; }) : resource());- let pending!: Promise<unknown>;- await act(async () => { pending = result.act('update', { name: 'Queued' }); });- h.enabled = false; await render(); h.enabled = true; await render();- await act(async () => { send(); await expect(pending).rejects.toThrow('PERMISSION_DENIED'); });- expect(sent).toBe(false);- expect(writes()[0]?.[3]?.preSend).toBeTypeOf('function');-});--it.each(['reading', 'refreshed'])('keeps a queued write authorized through a content refresh (%s)', async phase => {- await render(); let send!: () => void; let finishRead!: (value: unknown) => void;- h.invoke.mockImplementation(async (_id, channel, _args, opts) => channel === 'maker:remote-resources:invoke'- ? new Promise((resolve, reject) => { send = () => { try { opts?.preSend?.(); resolve({ effects: [] }); } catch (error) { reject(error); } }; })- : new Promise(resolve => { finishRead = resolve; }));- let pending!: Promise<unknown>;- await act(async () => { pending = result.act('update', { name: 'Queued' }); });- h.syncing = true; await render();- if (phase === 'refreshed') {- h.items = [{ ...row(), item: { ...row().item, revision: 'v2' } }];- h.syncing = false; await render();- await act(async () => { result.refresh(); });- await act(async () => { finishRead(resource()); });- }- await act(async () => { send(); await expect(pending).resolves.toEqual({ effects: [] }); });- expect(writes()[0]?.[2][0].input.expectedRevision).toBe(4);-});--it.each(['permission', 'revoked', 'host removed', 'room removed', 'offline', 'epoch'])('rejects a queued write after authorization changes: %s', async change => {- await render(); let send!: () => void;- h.invoke.mockImplementation(async (_id, channel, _args, opts) => channel === 'maker:remote-resources:invoke'- ? new Promise((resolve, reject) => { send = () => { try { opts?.preSend?.(); resolve({ effects: [] }); } catch (error) { reject(error); } }; })- : change === 'room removed' ? null : resource(change === 'permission' ? 'member' : 'owner'));- let pending!: Promise<unknown>;- await act(async () => { pending = result.act('update', { name: 'Denied' }); });- if (change === 'permission') await act(async () => { result.refresh(); });- if (change === 'revoked') h.revoked = new Set(['mac']);- if (change === 'host removed') h.targets = h.targets.filter(target => target.deviceId !== 'mac');- if (change === 'room removed') await act(async () => { result.refresh(); });- if (change === 'offline') h.online = false;- if (change === 'epoch') h.epoch += 1;- await render();- await act(async () => { send(); await expect(pending).rejects.toThrow('PERMISSION_DENIED'); });-});--it('coalesces refreshes while an earlier detail read is still in flight', async () => {- const finishes: ((value: unknown) => void)[] = [];- h.invoke.mockImplementation(() => new Promise(resolve => { finishes.push(resolve); }));- await render(); expect(reads()).toHaveLength(1);- h.syncing = true; await render(); h.syncing = false; await render();- await act(async () => { result.refresh(); result.refresh(); });- expect(reads()).toHaveLength(1);- await act(async () => { finishes.shift()!(resource()); });- expect(reads()).toHaveLength(2);- await act(async () => { finishes.shift()!(resource()); });- expect(result.selected).toBeDefined(); expect(result.loading).toBe(false);-});--it('distinguishes a failed online roster read from a disconnected computer', async () => {- h.listError = 'Read failed'; h.invoke.mockRejectedValue(new Error('Read failed')); await render();- expect(result.reason).toBe('unavailable'); expect(result.selected).toBeUndefined();- h.online = false; await render(); expect(result.reason).toBe('noHost');+ await act(async () => { await expect(result.act('update', { description: 'Saved once', expectedRevision: 4 })).rejects.toThrow('Acknowledgement lost'); });+ expect(result.group?.revision).toBe(5);+ await act(async () => { await result.act('update', { description: 'Saved once', expectedRevision: 5 }); });+ expect(writes()).toHaveLength(2); expect(writes()[0]).toEqual(writes()[1]);+ expect(result.group?.revision).toBe(5);+});++it('keeps a confirmed save successful but blocks edits until failed readback recovers', async () => {+ await render(); const original = request.getMockImplementation()!;+ request.mockImplementation(async (...args) => { if (args[0].endsWith('/snapshot')) throw new Error('Unavailable'); return original(...args); });+ await act(async () => { await expect(result.act('update', { name: 'Saved' })).resolves.toEqual({ effects: [] }); });+ expect(result.editable).toBe(false); expect(result.reason).toBe('unavailable');+ request.mockImplementation(original); await act(async () => { await result.refresh(); });+ expect(result.group?.name).toBe('Saved'); expect(result.editable).toBe(true);+});++it('ignores pre-write snapshots and blocks duplicate edits while the write is pending', async () => {+ await render(); const original = request.getMockImplementation()!; let finishRead!: (value: unknown) => void; let first = true;+ request.mockImplementation(async (...args) => { if (args[0].endsWith('/snapshot') && first) { first = false; return new Promise(resolve => { finishRead = resolve; }); } return original(...args); });+ let oldRead!: Promise<void>; await act(async () => { oldRead = result.refresh(); });+ await expect(result.act('update', { name: 'Unverified' })).rejects.toThrow('PERMISSION_DENIED');+ await act(async () => { finishRead(structuredClone(snapshot)); await oldRead; });+ let finishWrite!: () => void;+ request.mockImplementation(async (...args) => { if (args[1] === 'PATCH') await new Promise<void>(resolve => { finishWrite = resolve; }); return original(...args); });+ let write!: Promise<unknown>; await act(async () => { write = result.act('update', { name: 'One write' }); });+ await expect(result.act('update', { name: 'Duplicate' })).rejects.toThrow('PERMISSION_DENIED');+ await act(async () => { finishWrite(); await write; });+ expect(writes()).toHaveLength(1);+});++it('discards account and closed-sheet read results and never revives their authorization', async () => {+ let finish!: (value: unknown) => void; const original = request.getMockImplementation()!;+ request.mockImplementation(async (...args) => args[0].endsWith('/snapshot') ? new Promise(resolve => { finish = resolve; }) : original(...args));+ await render(); const oldAct = result.act;+ h.enabled = false; h.api = api('account-2'); await render();+ await act(async () => { finish(structuredClone(snapshot)); });+ expect(result.group).toBeUndefined(); expect(result.editable).toBe(false);+ await expect(oldAct('update', { name: 'Late' })).rejects.toThrow('PERMISSION_DENIED');+ expect(writes()).toHaveLength(0);});diff --git a/apps/mobile/src/chat/chatServerClient.ts b/apps/mobile/src/chat/chatServerClient.tsindex 680b9467c0..8563ec9c4b 100644--- a/apps/mobile/src/chat/chatServerClient.ts+++ b/apps/mobile/src/chat/chatServerClient.ts@@ -10,6 +10,7 @@ import { botGroupQuoteFromMessage, buildBotGroupQuoteCard } from '@cindy/maker-sexport interface ChatRoom {id: string; name: string; state?: string; kind: string; archived: boolean; dissolved_at?: string | null;+ topic?: string; description?: string;created_at: string; updated_at: string; revision: number; head?: string;response_mode: 'all' | 'mentioned'; speaking_mode: 'auto' | 'sequential'; organizer_id?: string | null;}@@ -38,6 +39,16 @@ export interface ChatCapabilities { companionHome: boolean }/** Compare-and-set result: a conflict carries the main computer another device already chose. */export type ChatSetHomeResult = { ok: true; homeDeviceId: string } | { ok: false; homeDeviceId: string | null };export interface ChatHistoryPage { messages: ChatMessage[]; before: string | null }+export type ChatGroupSettingsAction =+ | { type: 'update'; expectedRevision: number; name?: string; description?: string; responseMode?: 'all' | 'mentioned'; speakingMode?: 'auto' | 'sequential'; organizerId?: string | null; archived?: boolean }+ | { type: 'member'; actorId: string; action: 'invite' | 'remove' | 'role'; role?: 'admin' | 'member' };++/** Prefer an owned owner, then the human's admin role, as on Desktop. */+export function chatGroupManager(snapshot: ChatSnapshot, self: string) {+ const managers = snapshot.members.filter(member => member.state === 'joined'+ && (member.id === self || member.ownerActorId === self) && ['owner', 'admin'].includes(member.role));+ return managers.find(member => member.role === 'owner') ?? managers.find(member => member.id === self) ?? managers[0];+}export function chatId(value: string): string {if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) throw new Error('INVALID_CHAT_ID');@@ -145,7 +156,7 @@ export function chatReadAt(snapshot: ChatSnapshot, selfId: string): number {}/** Public profile images never enter the computer's local media resolver. */-function chatMemberAvatar(value: string | null): Pick<BotGroupMemberView, 'avatar' | 'avatarUrl'> {+export function chatMemberAvatar(value: string | null): Pick<BotGroupMemberView, 'avatar' | 'avatarUrl'> {const raw = value ?? '';try { return { avatar: '', avatarUrl: chatHttpsUrl(raw) }; } catch { /* Not a public HTTPS image. */ }// The server also accepts the existing bundled presets and short emoji identities.@@ -207,6 +218,8 @@ export function chatGroupView(page: ChatPage, selfId: string, actors: readonly Creturn { id: room.id, conversationKind: room.kind === 'direct' ? 'direct' : 'group',name: room.kind === 'direct' ? active.filter(member => member.id !== selfId).map(memberName).join(', ') || room.name : room.name,serverBacked: true, supportsGroupLeave: room.kind !== 'direct', dissolvedAt: room.dissolved_at ?? null, archived: room.archived, selfActorId: selfId,+ topic: room.topic, description: room.description,+ supportsSettingsManagement: room.kind === 'group', supportsMemberRemoval: room.kind === 'group',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),@@ -245,16 +258,32 @@ export function createChatServerClient(request: ChatRequest, personalList = crea}let supportsDissolve = false;let supportsListRemoval = false;+ let singleSpeaker = false;async function identity() {- const me = await request<{ actor: { id: string; kind: string }; capabilities?: { groupLifecycleVersion?: number; conversationListStateVersion?: number } }>('/me');+ const me = await request<{ actor: { id: string; kind: string }; capabilities?: { groupLifecycleVersion?: number; conversationListStateVersion?: number; groupSingleSpeaker?: number } }>('/me');if (me.actor.kind !== 'human') throw new Error('INVALID_CHAT_IDENTITY');supportsDissolve = me.capabilities?.groupLifecycleVersion === 1;supportsListRemoval = me.capabilities?.conversationListStateVersion === 1;+ singleSpeaker = me.capabilities?.groupSingleSpeaker === 1;return chatId(me.actor.id);}return {personalList,- lifecycleCapabilities: () => ({ supportsDissolve, supportsListRemoval }),+ lifecycleCapabilities: () => ({ supportsDissolve, supportsListRemoval, singleSpeaker }),+ async groupSettings(roomId: string) {+ const [snapshot, self] = await Promise.all([+ request<ChatSnapshot>(`/conversations/${chatId(roomId)}/snapshot`), identity(),+ ]);+ if (snapshot.room.id !== roomId || snapshot.room.kind !== 'group' || !Array.isArray(snapshot.members)) throw new Error('INVALID_CHAT_SNAPSHOT');+ return { snapshot, self, manager: chatGroupManager(snapshot, self) };+ },+ /** The server rechecks the selected owned actor's live role for every write. */+ async manageGroup(roomId: string, managerId: string, action: ChatGroupSettingsAction, operationId: string) {+ const path = `/conversations/${chatId(roomId)}`;+ const { type, ...body } = action;+ return request(type === 'member' ? `${path}/members` : path, type === 'member' ? 'POST' : 'PATCH',+ { operationId, ...body }, chatId(managerId));+ },async syncListState(force = false) {await identity();if (supportsListRemoval) await (force ? personalList.sync(request) : personalList.ensureSynced(request));diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.jsonindex 5cd5c83111..773617f382 100644--- a/apps/mobile/src/i18n/locales/en/groupChat.json+++ b/apps/mobile/src/i18n/locales/en/groupChat.json@@ -197,20 +197,25 @@"add": "Add teammate","projectDirOnComputer": "Choose or change it on your computer","memberActions": "Actions for {{name}}",- "managementComputer": "Management computer","retry": "Retry",- "reconnect": "Reconnect","conflict": "Group settings changed. Review them before saving again. Your input was kept.","archive": "Archive group chat","archiveConfirmTitle": "Archive “{{name}}”?","archiveNote": "Only a group owner can archive it. This stops new messages and keeps the history.",- "managementStatus": {- "ready": "Connected",- "loading": "Connecting…",- "noHost": "Disconnected",- "permission": "Read-only",- "upgrade": "Update needed",- "unavailable": "Settings unavailable"+ "description": "Group Description",+ "descriptionSaveFailed": "Couldn’t save the group description.",+ "makeAdmin": "Make Admin",+ "removeAdmin": "Remove Admin Role",+ "roles": {+ "owner": "Owner",+ "admin": "Admin",+ "member": "Member",+ "guest": "Guest"+ },+ "cloudStatus": {+ "loading": "Loading settings…",+ "permission": "Only group owners and admins can change these settings.",+ "unavailable": "Couldn’t load group settings. Try again."}},"errors": {diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.jsonindex 4116aa8ef4..12655f629c 100644--- a/apps/mobile/src/i18n/locales/ja/groupChat.json+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json@@ -197,20 +197,25 @@"add": "仲間を追加","projectDirOnComputer": "パソコンで選択・変更できます","memberActions": "{{name}} の操作",- "managementComputer": "管理用コンピュータ","retry": "再試行",- "reconnect": "再接続","conflict": "グループ設定が更新されました。内容を確認してから再保存してください。入力内容は保持されています。","archive": "グループチャットをアーカイブ","archiveConfirmTitle": "「{{name}}」をアーカイブしますか?","archiveNote": "アーカイブできるのは所有者のみです。新しいメッセージは送信できなくなりますが、履歴は保持されます。",- "managementStatus": {- "ready": "接続済み",- "loading": "接続中…",- "noHost": "未接続",- "permission": "読み取り専用",- "upgrade": "更新が必要",- "unavailable": "設定を取得できません"+ "description": "グループの説明",+ "descriptionSaveFailed": "グループの説明を保存できませんでした。",+ "makeAdmin": "管理者にする",+ "removeAdmin": "管理者を解除",+ "roles": {+ "owner": "オーナー",+ "admin": "管理者",+ "member": "メンバー",+ "guest": "ゲスト"+ },+ "cloudStatus": {+ "loading": "設定を読み込み中…",+ "permission": "この設定を変更できるのはグループのオーナーと管理者だけです。",+ "unavailable": "グループ設定を読み込めませんでした。もう一度お試しください。"}},"errors": {diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.jsonindex 60409e0034..2c1087f444 100644--- a/apps/mobile/src/i18n/locales/ko/groupChat.json+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json@@ -197,20 +197,25 @@"add": "동료 추가","projectDirOnComputer": "컴퓨터에서 선택하거나 바꿀 수 있습니다","memberActions": "{{name}} 작업",- "managementComputer": "관리 컴퓨터","retry": "다시 시도",- "reconnect": "재연결","conflict": "그룹 설정이 변경되었습니다. 확인한 후 다시 저장해 주세요. 입력 내용은 유지됩니다.","archive": "그룹 채팅 보관","archiveConfirmTitle": "“{{name}}” 그룹을 보관할까요?","archiveNote": "그룹 소유자만 보관할 수 있습니다. 새 메시지를 보낼 수 없게 되지만 기록은 유지됩니다.",- "managementStatus": {- "ready": "연결됨",- "loading": "연결 중…",- "noHost": "연결 끊김",- "permission": "읽기 전용",- "upgrade": "업데이트 필요",- "unavailable": "설정을 읽을 수 없음"+ "description": "그룹 소개",+ "descriptionSaveFailed": "그룹 소개를 저장하지 못했습니다.",+ "makeAdmin": "관리자로 지정",+ "removeAdmin": "관리자 해제",+ "roles": {+ "owner": "소유자",+ "admin": "관리자",+ "member": "멤버",+ "guest": "게스트"+ },+ "cloudStatus": {+ "loading": "설정 불러오는 중…",+ "permission": "그룹 소유자와 관리자만 이 설정을 변경할 수 있습니다.",+ "unavailable": "그룹 설정을 불러오지 못했습니다. 다시 시도하세요."}},"errors": {diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.jsonindex 5e00f11c36..afbb4460b3 100644--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json@@ -197,20 +197,25 @@"add": "添加伙伴","projectDirOnComputer": "在电脑上选择或更换","memberActions": "{{name}} 的操作",- "managementComputer": "管理电脑","retry": "重试",- "reconnect": "重连","conflict": "群设置已更新,请核对后再保存。输入已保留。","archive": "归档群聊","archiveConfirmTitle": "归档「{{name}}」?","archiveNote": "仅群主可归档。归档后不能继续发消息,历史消息保留。",- "managementStatus": {- "ready": "已连接",- "loading": "连接中…",- "noHost": "已断开",- "permission": "无管理权限",- "upgrade": "需更新电脑端",- "unavailable": "设置读取失败"+ "description": "群简介",+ "descriptionSaveFailed": "群简介未保存",+ "makeAdmin": "设为管理员",+ "removeAdmin": "取消管理员",+ "roles": {+ "owner": "群主",+ "admin": "管理员",+ "member": "成员",+ "guest": "访客"+ },+ "cloudStatus": {+ "loading": "正在读取群设置…",+ "permission": "只有群主和管理员可以修改这些设置",+ "unavailable": "群设置读取失败,请重试"}},"errors": {diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.jsonindex 8a2bdcd473..d56355beb2 100644--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json@@ -197,20 +197,25 @@"add": "新增夥伴","projectDirOnComputer": "在電腦上選擇或更換","memberActions": "{{name}} 的操作",- "managementComputer": "管理電腦","retry": "重試",- "reconnect": "重連","conflict": "群設定已更新,請核對後再儲存。輸入已保留。","archive": "封存群聊","archiveConfirmTitle": "封存「{{name}}」?","archiveNote": "僅群主可封存。封存後無法繼續傳送訊息,歷史訊息會保留。",- "managementStatus": {- "ready": "已連線",- "loading": "連線中…",- "noHost": "已中斷",- "permission": "無管理權限",- "upgrade": "需更新電腦端",- "unavailable": "設定讀取失敗"+ "description": "群組簡介",+ "descriptionSaveFailed": "群組簡介未儲存",+ "makeAdmin": "設為管理員",+ "removeAdmin": "取消管理員",+ "roles": {+ "owner": "群主",+ "admin": "管理員",+ "member": "成員",+ "guest": "訪客"+ },+ "cloudStatus": {+ "loading": "正在讀取群組設定…",+ "permission": "只有群主和管理員可以修改這些設定",+ "unavailable": "群組設定讀取失敗,請重試"}},"errors": {diff --git a/apps/mobile/src/session/BotGroupSettingsSheet.tsx b/apps/mobile/src/session/BotGroupSettingsSheet.tsxindex 60c08dc007..f41d44bf3c 100644--- a/apps/mobile/src/session/BotGroupSettingsSheet.tsx+++ b/apps/mobile/src/session/BotGroupSettingsSheet.tsx@@ -1,7 +1,7 @@-/** 群设置由管理电脑保存;项目文件夹仅可查看。 */+/** 云端群设置直连聊天服务;旧电脑入口保留原有资源协议。 */import { useEffect, useMemo, useRef, useState } from 'react';import { ActivityIndicator, Pressable, StyleSheet, View } from 'react-native';-import { ChevronDown, Ellipsis, Folder, Plus } from 'lucide-react-native';+import { Ellipsis, Folder, Plus } from 'lucide-react-native';import { useTranslation } from 'react-i18next';import { resolveRemoteText } from '@cindy/device-link';import {@@ -28,10 +28,11 @@ import { botGroupActionErrorText } from './botGroupCopy';import { CompanionSheet } from './CompanionSheet';import { useHostTeammates } from './useHostTeammates';import { BotGroupMenu } from './BotGroupMenu';-import { useBotGroupSettingsManagement } from './useBotGroupSettingsManagement';-import { canManageBotGroup } from './botGroupRemote';+import { useBotGroupSettingsManagement, useCloudGroupCandidates, type GroupSettingsActionId } from './useBotGroupSettingsManagement';+import { chatMemberAvatar } from '@/chat/chatServerClient';+import { botGroupMemberAvatar, canManageBotGroup } from './botGroupRemote';-type Busy = 'name' | 'members' | 'organizer' | 'replyMode' | 'speakingMode' | 'delete' | 'lifecycle' | null;+type Busy = 'description' | 'name' | 'members' | 'organizer' | 'replyMode' | 'speakingMode' | 'delete' | 'lifecycle' | null;type Act = (actionId: BotGroupRemoteActionId, input?: Record<string, unknown>) => Promise<unknown>;type SettingsProps = {@@ -49,19 +50,20 @@ type SettingsProps = {onRefresh?(): void;};-/** Server chat remains direct; only the open settings sheet resolves a management host. */+/** Direct server groups use the same account connection for chat and settings. */export function BotGroupSettingsSheet(props: SettingsProps) {- return props.readOnly ? <ServerGroupSettings {...props} /> : <BotGroupSettingsContent {...props} />;+ const { accountGeneration } = useAuth();+ const key = `${accountGeneration}:${props.group.id}`;+ return props.readOnly ? <ServerGroupSettings key={key} {...props} /> : <BotGroupSettingsContent key={key} {...props} />;}function ServerGroupSettings(props: SettingsProps) {- const management = useBotGroupSettingsManagement(props.group.id, props.visible);- const host = management.selected?.host ?? props.host;- const group = management.selected?.group ?? props.group;- const lookup = useBotGroupIdentities(host.deviceId);- return <BotGroupSettingsContent {...props} group={group} host={host}+ const management = useBotGroupSettingsManagement(props.group, props.visible);+ const group = management.group ?? props.group;+ const lookup = useBotGroupIdentities('');+ return <BotGroupSettingsContent {...props} group={group}identityFor={(id, name) => lookup(id, name, group.members.find(member => member.botId === id))}- online={!!management.selected && !management.loading} readOnly={!management.selected || management.loading}+ online={management.editable} readOnly={!management.editable}act={async (action, input) => { const receipt = await management.act(action, input); props.onRefresh?.(); return receipt; }}management={management} lifecycle={props} />;}@@ -92,7 +94,20 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, acconst nameFocused = useRef(false);const nameDirty = useRef(false);const nameRevision = useRef(group.revision);- const teammates = useHostTeammates(host, visible && picking && !readOnly, serverManaged ? memberQuery : '');+ const teammates = useHostTeammates(host, !management && visible && picking && !readOnly, serverManaged ? memberQuery : '');+ const cloudCandidates = useCloudGroupCandidates(!!management && visible && picking && !readOnly);+ const choices = management ? cloudCandidates.rows.filter(row => row.name.toLocaleLowerCase().includes(memberQuery.trim().toLocaleLowerCase()))+ .map(row => {+ const avatar = chatMemberAvatar(row.avatar);+ return { id: row.id, name: row.name, avatar: botGroupMemberAvatar({ ...avatar, name: row.name, avatarColor: '' }), avatarUrl: avatar.avatarUrl };+ })+ : teammates.rows.map(row => ({ id: row.item.ref.id, name: resolveRemoteText(row.item.display.title, i18n.language), avatar: row.item.display.avatar, avatarUrl: undefined }));+ const candidatesLoading = management ? cloudCandidates.loading : teammates.loading;+ const candidatesFailed = management ? cloudCandidates.failed : teammates.failed;+ const [description, setDescription] = useState(group.description ?? '');+ const descriptionDirty = useRef(false);+ const descriptionRevision = useRef(group.revision);+ useEffect(() => { if (!descriptionDirty.current) setDescription(group.description ?? ''); }, [group.description]);// Follow renames that land from the computer while the field is not being edited.useEffect(() => { if (!nameFocused.current && !nameDirty.current) setName(group.name); }, [group.name]);@@ -107,13 +122,13 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, acconst 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 addable = choices.filter(row => !memberIds.includes(row.id));const permissionLocked = serverManaged && !canManageBotGroup(group);const unavailable = readOnly || permissionLocked || !online || !!lifecycleGroup.dissolvedAt;const locked = unavailable || busy !== null;const deleteLocked = leavesGroup ? readOnly || !online || busy !== null : locked || (serverManaged && !owner);- const run = async (section: Exclude<Busy, null>, actionId: BotGroupRemoteActionId, input: Record<string, unknown>, fallbackKey: string) => {+ const run = async (section: Exclude<Busy, null>, actionId: GroupSettingsActionId, input: Record<string, unknown>, fallbackKey: string) => {const leaving = actionId === 'delete' && leavesGroup;if (readOnly || (permissionLocked && !leaving) || !online || busyRef.current) return false;const captured = scope;@@ -121,7 +136,10 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, acsetBusy(section);setErrors((current) => ({ ...current, [section]: undefined }));try {- await act(actionId, serverManaged && !leaving ? { expectedRevision: group.revision, ...input } : input);+ if (actionId === 'set-member-role') {+ if (!management) return false;+ await management.act(actionId, input);+ } else await act(actionId, serverManaged && !leaving ? { expectedRevision: group.revision, ...input } : input);// Legacy deletion reports success to the owning screen even if this sheet unmounted.return true;} catch (error) {@@ -190,27 +208,14 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, acreturn <CompanionSheet visible={visible} title={t('groupChat.settings.title')} onClose={onClose} onClosed={onClosed}preventDismiss={busy !== null} testID="botGroup.settings"><View style={styles.content}>- {management ? <View style={styles.managementRow} testID="botGroup.settings.management">- {management.managers.length > 1 ? <View style={styles.computerSlot}><BotGroupMenu title={t('groupChat.settings.managementComputer')} disabled={busy !== null}- testID="botGroup.settings.computerMenu" sections={[{ id: 'computers', options: management.managers.map(manager => ({- id: manager.host.deviceId, title: manager.host.deviceName,- })) }]} onSelect={management.select}>- {open => <Pressable accessibilityRole="button" disabled={busy !== null} onPress={open} style={styles.computerPicker}>- <Text numberOfLines={1} style={[styles.managementText, styles.flex]}>{management.selected?.host.deviceName}</Text>- <ChevronDown size={iconSize.sm} color={colors.textSecondary} />- </Pressable>}- </BotGroupMenu></View> : <Text numberOfLines={1} style={[styles.managementText, styles.flex]} testID="botGroup.settings.computerName">- {management.displayHost?.deviceName ?? t('groupChat.settings.managementComputer')}- </Text>}- {management.loading ? <ActivityIndicator size="small" color={colors.textSecondary} testID="botGroup.settings.connecting" />- : !unavailable ? <View style={styles.connectedDot} testID="botGroup.settings.connectedDot" /> : null}- <Text style={styles.managementText} testID="botGroup.settings.managementStatus">- {t(`groupChat.settings.managementStatus.${management.loading ? 'loading' : !unavailable ? 'ready' : management.reason ?? 'unavailable'}`)}+ {management && (management.loading || management.reason) ? <View style={styles.managementRow} testID="botGroup.settings.management">+ {management.loading ? <ActivityIndicator size="small" color={colors.textSecondary} testID="botGroup.settings.connecting" /> : null}+ <Text style={[styles.managementText, styles.flex]} testID="botGroup.settings.managementStatus">+ {t(`groupChat.settings.cloudStatus.${management.loading ? 'loading' : management.reason}`)}</Text>- {unavailable && !management.loading ? <Pressable accessibilityRole="button" onPress={management.refresh}+ {!management.loading ? <Pressable accessibilityRole="button" onPress={() => void management.refresh()}style={styles.reconnect} testID="botGroup.settings.retry">- <Text style={styles.reconnectText}>{t(management.reason === 'noHost' || management.reason === 'unavailable'- ? 'groupChat.settings.reconnect' : 'groupChat.settings.retry')}</Text>+ <Text style={styles.reconnectText}>{t('groupChat.settings.retry')}</Text></Pressable> : null}</View> : null}<View style={[styles.settingsBody, unavailable && styles.inactive]} testID="botGroup.settings.body">@@ -227,6 +232,20 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, ac{error('name')}</View>+ {management ? <View style={styles.section}>+ <Text style={styles.sectionTitle}>{t('groupChat.settings.description')}</Text>+ <TextInput accessibilityLabel={t('groupChat.settings.description')} value={description} maxLength={2000} multiline+ editable={!locked} style={[styles.input, styles.description]} testID="botGroup.settings.description"+ onChangeText={value => { if (!descriptionDirty.current || errors.description) descriptionRevision.current = group.revision;+ descriptionDirty.current = true; setDescription(value); setErrors(current => ({ ...current, description: undefined })); }}+ onBlur={() => { if (descriptionDirty.current) {+ if (errors.description) descriptionRevision.current = group.revision;+ void run('description', 'update', { description, expectedRevision: descriptionRevision.current }, 'groupChat.settings.descriptionSaveFailed')+ .then(saved => { if (saved) descriptionDirty.current = false; });+ } }} />+ {error('description')}+ </View> : null}+<View style={styles.section}><Text style={styles.sectionTitle}>{t('groupChat.settings.members')}</Text><View style={styles.group}>@@ -238,6 +257,8 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, ac&& (!serverManaged || (!member.isSelf && (owner || member.role !== 'owner')));const organizer = member.botId === group.organizerBotId;const options = [+ ...(management && active && member.actorId && member.role !== 'owner' && !member.isSelf+ ? [{ id: `role:${member.botId}`, title: t(member.role === 'admin' ? 'groupChat.settings.removeAdmin' : 'groupChat.settings.makeAdmin') }] : []),...(!organizer && canOrganize ? [{ id: `organizer:${member.botId}`, title: t('groupChat.settings.setOrganizer') }] : []),{id: `remove:${member.botId}`, title: t('groupChat.settings.remove'), destructive: true, disabled: !removable,@@ -250,7 +271,8 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, actestID={`botGroup.settings.memberMenu.${member.botId}`}sections={[{ id: 'member', options }]}onSelect={(id) => {- if (id.startsWith('organizer:')) void run('organizer', 'update', { organizerBotId: member.botId }, 'groupChat.settings.organizerSaveFailed');+ if (id.startsWith('role:')) void run('members', 'set-member-role', { actorId: member.actorId, role: member.role === 'admin' ? 'member' : 'admin' }, 'groupChat.settings.membersSaveFailed');+ else if (id.startsWith('organizer:')) void run('organizer', 'update', { organizerBotId: member.botId }, 'groupChat.settings.organizerSaveFailed');else if (id.startsWith('remove:')) {if (group.supportsMemberRemoval && member.actorId)void run('members', 'remove-member', { actorId: member.actorId }, 'groupChat.settings.membersSaveFailed');@@ -267,6 +289,7 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, ac<View style={styles.memberName}><Text numberOfLines={1} style={styles.rowTitle}>{identity.name}</Text>{organizer ? <BotGroupOrganizerTag /> : null}+ {management && member.role ? <Text style={styles.rowMeta}>{t(`groupChat.settings.roles.${member.role}`)}</Text> : null}{!active ? <Text numberOfLines={1} style={styles.rowMeta}>{t(member.status === 'paused' ? 'groupChat.memberStatus.paused' : 'groupChat.memberStatus.unavailable')}</Text> : null}@@ -291,18 +314,18 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, acaccessibilityLabel={t('devices.companions.search')} placeholder={t('devices.companions.search')}placeholderTextColor={colors.textPlaceholder} autoCorrect={false} returnKeyType="search"style={[styles.input, styles.searchInput]} testID="botGroup.settings.memberSearch" /> : null}- {teammates.loading && addable.length === 0 ? <ActivityIndicator color={colors.textSecondary} style={styles.spinner} /> : null}- {!teammates.loading && addable.length === 0- ? <Text style={styles.note}>{t(teammates.failed ? 'devices.resources.loadFailed' : 'groupChat.settings.noMoreBots')}</Text>+ {candidatesLoading && addable.length === 0 ? <ActivityIndicator color={colors.textSecondary} style={styles.spinner} /> : null}+ {!candidatesLoading && addable.length === 0+ ? <Text style={styles.note}>{t(candidatesFailed ? 'devices.resources.loadFailed' : 'groupChat.settings.noMoreBots')}</Text>: null}{addable.map((row, index) => {- const title = resolveRemoteText(row.item.display.title, i18n.language);- return <Pressable key={row.key} accessibilityRole="button" accessibilityLabel={title} disabled={locked}- onPress={() => { if (serverManaged) void run('members', 'add-member', { botId: row.item.ref.id }, 'groupChat.settings.membersSaveFailed').then(saved => { if (saved) setPicking(false); });- else void setMembers([...memberIds, row.item.ref.id]); }}+ const title = row.name;+ return <Pressable key={row.id} accessibilityRole="button" accessibilityLabel={title} disabled={locked}+ onPress={() => { if (serverManaged) void run('members', 'add-member', { botId: row.id }, 'groupChat.settings.membersSaveFailed').then(saved => { if (saved) setPicking(false); });+ else void setMembers([...memberIds, row.id]); }}style={({ pressed }) => [styles.memberRow, pressed && mobileInteractionStyles.pressed]}- testID={`botGroup.settings.addable.${row.item.ref.id}`}>- <BotGroupAvatar deviceId={host.deviceId} identity={{ botId: row.item.ref.id, name: title, avatar: row.item.display.avatar }}+ testID={`botGroup.settings.addable.${row.id}`}>+ <BotGroupAvatar deviceId={host.deviceId} identity={{ botId: row.id, name: title, avatar: row.avatar, avatarUrl: row.avatarUrl }}size={BOT_GROUP_ROW_AVATAR_SIZE} online={online} /><Text numberOfLines={1} style={[styles.rowTitle, styles.flex]}>{title}</Text><Plus size={iconSize.sm} color={colors.textTertiary} />@@ -316,7 +339,7 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, ac{error('organizer')}</View>- <View style={styles.section}>+ {!management ? <View style={styles.section}><Text style={styles.sectionTitle}>{t('groupChat.settings.projectDir')}</Text><View style={[styles.group, styles.memberRow]} testID="botGroup.settings.projectDir"><Folder size={iconSize.md} color={colors.textSecondary} />@@ -324,7 +347,7 @@ function BotGroupSettingsContent({ visible, group, host, identityFor, online, ac<Text numberOfLines={1} style={styles.rowMeta}>{t('groupChat.settings.projectDirOnComputer')}</Text></View><Text style={styles.note}>{t('groupChat.settings.projectDirNote')}</Text>- </View>+ </View> : null}<View style={styles.section}><Text style={styles.sectionTitle}>{t('groupChat.settings.replyMode')}</Text>@@ -386,15 +409,13 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({settingsBody: { gap: spacing.xl },managementRow: { minHeight: 44, flexDirection: 'row', alignItems: 'center', gap: spacing.sm },managementText: { color: colors.textSecondary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },- computerSlot: { flex: 1, minWidth: 0 },- computerPicker: { flex: 1, minWidth: 0, minHeight: 44, flexDirection: 'row', alignItems: 'center', gap: spacing.xs },- connectedDot: { width: 6, height: 6, borderRadius: radius.pill, backgroundColor: colors.statusDone },reconnect: { minHeight: 44, minWidth: 44, justifyContent: 'center', alignItems: 'center' },reconnectText: { color: colors.textPrimary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption },section: { gap: spacing.sm },sectionTitle: { color: colors.textTertiary, fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.semibold },input: { minHeight: 44, borderRadius: radius.pill, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,paddingHorizontal: spacing.lg, color: colors.textPrimary, backgroundColor: colors.surfaceElevated, fontSize: typeScale.body },+ description: { minHeight: 100, borderRadius: radius.control, paddingVertical: spacing.md, textAlignVertical: 'top', lineHeight: lineHeight.body },searchInput: { fontSize: typeScale.bodySmall },group: { backgroundColor: colors.surfaceElevated, borderColor: colors.border, borderWidth: StyleSheet.hairlineWidth,borderRadius: radius.container, overflow: 'hidden' },diff --git a/apps/mobile/src/session/useBotGroupSettingsManagement.ts b/apps/mobile/src/session/useBotGroupSettingsManagement.tsindex 33b66240f7..362c621f73 100644--- a/apps/mobile/src/session/useBotGroupSettingsManagement.ts+++ b/apps/mobile/src/session/useBotGroupSettingsManagement.ts@@ -1,131 +1,115 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';-import { BOT_GROUP_REMOTE_COLLECTION_ID, type BotGroupRemoteActionId, type BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';-import { useAuth } from '@/auth/AuthContext';-import { useDeviceLink } from '@/device-link/DeviceLinkContext';-import { useRemoteSyncCoordinator } from '@/device-link/remoteSyncTask';-import { useRevokedDevices } from '@/device-link/revokedDevicesStore';-import { getRemoteResource, invokeRemoteResourceAction, type RemoteResourceHostTarget } from '@/device-link/remoteResources';-import { BOT_GROUP_CLIENT_PRIMITIVES, botGroupChatDataFromResource, botGroupResourceRef, canManageBotGroup } from './botGroupRemote';-import { useTeammateRoster } from './useTeammateRoster';+import { randomUUID } from 'expo-crypto';+import type { BotGroupRemoteActionId, BotGroupRemoteChatData } from '@cindy/maker-shared/botGroupChat';+import { chatGroupView, type ChatActor, type ChatGroupSettingsAction } from '@/chat/chatServerClient';+import { useChatClient } from '@/chat/useChatServer';+import { canManageBotGroup } from './botGroupRemote';-type Manager = { host: RemoteResourceHostTarget; group: BotGroupRemoteChatData };+export type GroupSettingsActionId = BotGroupRemoteActionId | 'set-member-role';+type Settings = { group: BotGroupRemoteChatData; managerId?: string };-/** Associate a direct server chat with computers that actually expose this exact room. */-export function useBotGroupSettingsManagement(groupId: string, enabled: boolean) {- const { accountGeneration } = useAuth();- const { i18n } = useTranslation();- const { invoke, openLink, connectionEpoch, status, getPresenceAvailability, onRemoteResourceChanged } = useDeviceLink();- const revoked = useRevokedDevices();- const roster = useTeammateRoster(enabled);- const scope = JSON.stringify([accountGeneration, groupId, enabled, connectionEpoch]);- // Reopening the same group must not revive an earlier authorization or receipt.- const binding = useMemo(() => Symbol(scope), [scope]);- const bindingRef = useRef(binding); bindingRef.current = binding;- const activeBinding = useRef<typeof binding | null>(null);- useEffect(() => {- activeBinding.current = binding;- return () => { if (activeBinding.current === binding) activeBinding.current = null; };- }, [binding]);- const [selectedId, select] = useState('');- const [refreshVersion, setRefreshVersion] = useState(0);- const [snapshot, setSnapshot] = useState<{ binding: typeof binding; key: string; managers: Manager[]; reason: 'noHost' | 'permission' | 'upgrade' | 'unavailable' | null }>();- const writing = useRef(false);- const candidates = roster.groupTargets.filter(host => status === 'online'- && !revoked.has(host.deviceId) && getPresenceAvailability(host.deviceId) !== false);- const candidateKey = JSON.stringify(candidates.map(host => host.deviceId));- const onlineHost = roster.groupTargets.some(host => !revoked.has(host.deviceId) && getPresenceAvailability(host.deviceId) !== false);- const emptyReason = status === 'online' && roster.error && (!roster.groupTargets.length || onlineHost)- ? 'unavailable' : 'noHost';- const key = JSON.stringify([candidateKey, refreshVersion, status, emptyReason, i18n.language]);- const ready = !roster.loading;- const currentRef = useRef({ key, enabled, ready, managers: [] as Manager[] });- const own = snapshot?.binding === binding && snapshot.key === key;- // Content refreshes preserve verified authority until a new detail read replaces it.- const managers = snapshot?.binding === binding ? snapshot.managers.filter(manager =>- candidates.some(host => host.deviceId === manager.host.deviceId) && canManageBotGroup(manager.group)) : [];- currentRef.current = { key, enabled, ready, managers };- const selected = managers.find(manager => manager.host.deviceId === selectedId) ?? managers[0];- // Remember only the display name, never authorization or an editable snapshot.- const displayIdentity = JSON.stringify([accountGeneration, groupId]);- const rememberedHost = useRef<{ identity: string; host: RemoteResourceHostTarget } | undefined>(undefined);- const previousHost = rememberedHost.current?.identity === displayIdentity- && !revoked.has(rememberedHost.current.host.deviceId) ? rememberedHost.current.host : undefined;- const displayHost = selected?.host ?? previousHost ?? candidates[0];- useEffect(() => {- if (displayHost) rememberedHost.current = { identity: displayIdentity, host: displayHost };- else if (rememberedHost.current?.identity !== displayIdentity) rememberedHost.current = undefined;- }, [displayIdentity, displayHost]);-- const read = useRemoteSyncCoordinator(async run => {- if (!enabled || !ready) return;- const current = () => !run.isStale() && bindingRef.current === binding && currentRef.current.key === key && currentRef.current.ready;- const found: Manager[] = [];- let reason: NonNullable<typeof snapshot>['reason'] = candidates.length ? 'unavailable' : emptyReason;- for (let offset = 0; offset < candidates.length; offset += 2) {- const replies = await Promise.allSettled(candidates.slice(offset, offset + 2).map(async host => {- await openLink(host.deviceId);- if (!current()) return null;- const resource = await getRemoteResource(invoke, host, botGroupResourceRef(groupId), i18n.language, BOT_GROUP_CLIENT_PRIMITIVES);- const group = botGroupChatDataFromResource(resource);- return group?.id === groupId && group.serverBacked ? { host, group } : null;- }));- if (!current()) return;- for (const reply of replies) {- if (reply.status !== 'fulfilled' || !reply.value) continue;- const manager = reply.value;- if (canManageBotGroup(manager.group)) found.push(manager);- else if (!manager.group.supportsSettingsManagement) reason = 'upgrade';- else reason = 'permission';- }+/** Cloud settings use the account's chat service, never device discovery or a host link. */+export function useBotGroupSettingsManagement(source: BotGroupRemoteChatData, enabled: boolean) {+ const api = useChatClient();+ const groupId = source.id;+ const binding = useMemo(() => Symbol(), [api.owner, groupId, enabled]);+ const active = useRef<typeof binding | null>(binding); active.current = binding;+ useEffect(() => { active.current = binding; return () => { active.current = null; }; }, [binding]);+ const sequence = useRef(0);+ const verified = useRef<{ binding: typeof binding; settings: Settings } | null>(null);+ const writing = useRef<symbol | null>(null);+ const [state, setState] = useState<{ binding: typeof binding; settings?: Settings; loading: boolean; failed: boolean }>();+ const pending = useRef<{ binding: typeof binding; key: string; operationId: string; managerId: string; action: ChatGroupSettingsAction } | null>(null);+ const valid = useCallback(() => enabled && api.enabled && api.current() && active.current === binding, [api, enabled, binding]);+ const refresh = useCallback(async () => {+ if (!valid()) return;+ const run = ++sequence.current;+ verified.current = null;+ setState(previous => ({ binding, settings: previous?.binding === binding ? previous.settings : undefined, loading: true, failed: false }));+ try {+ const { snapshot, self, manager } = await api.client.groupSettings(groupId);+ if (!valid() || sequence.current !== run) return;+ const settings = { group: { ...chatGroupView({ snapshot, messages: [], before: null }, self), ...api.client.lifecycleCapabilities() }, managerId: manager?.id };+ verified.current = { binding, settings };+ setState({ binding, settings, loading: false, failed: false });+ } catch {+ if (valid() && sequence.current === run) setState({ binding, loading: false, failed: true });}- if (current()) setSnapshot({ binding, key, managers: found, reason: found.length ? null : reason });- }, scope);- useEffect(() => {- if (enabled && ready) void read({ reason: 'settings' });- }, [binding, key, enabled, ready, read]);+ }, [api, binding, groupId, valid]);+ // The parent already subscribes to server changes. Recheck only settings/membership changes.+ const sourceVersion = JSON.stringify([source.revision, source.archived, source.dissolvedAt,+ source.members.map(member => [member.actorId, member.role, member.status])]);+ useEffect(() => { void refresh(); }, [refresh, sourceVersion]);- const refresh = useCallback(() => { setRefreshVersion(value => value + 1); }, []);- useEffect(() => {- if (!enabled) return;- let timer: ReturnType<typeof setTimeout> | undefined;- const off = onRemoteResourceChanged((deviceId, payload) => {- if (!candidates.some(host => host.deviceId === deviceId) || payload.collectionId !== BOT_GROUP_REMOTE_COLLECTION_ID) return;- if (payload.resourceRefs?.length && !payload.resourceRefs.some(ref => ref.id === groupId)) return;- if (!timer) timer = setTimeout(() => { timer = undefined; refresh(); }, 150);- });- return () => { off(); if (timer) clearTimeout(timer); };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [enabled, groupId, candidateKey, onRemoteResourceChanged, refresh]);-- const act = useCallback(async (actionId: BotGroupRemoteActionId, input?: Record<string, unknown>) => {- const manager = selected;- if (!currentRef.current.enabled || !manager || writing.current) throw new Error('PERMISSION_DENIED');- writing.current = true;- const valid = () => activeBinding.current === binding && bindingRef.current === binding && currentRef.current.enabled- && currentRef.current.managers.some(current => current.host.deviceId === manager.host.deviceId && canManageBotGroup(current.group))- && getPresenceAvailability(manager.host.deviceId) !== false;+ const act = useCallback(async (actionId: GroupSettingsActionId, input: Record<string, unknown> = {}) => {+ const current = verified.current?.binding === binding ? verified.current.settings : undefined;+ if (!valid() || !current?.managerId || !canManageBotGroup(current.group) || current.group.dissolvedAt || writing.current) throw new Error('PERMISSION_DENIED');+ let action: ChatGroupSettingsAction;+ if (actionId === 'update' || actionId === 'delete') {+ const expectedRevision = input.expectedRevision ?? current.group.revision;+ if (!Number.isSafeInteger(expectedRevision) || Number(expectedRevision) < 1) throw new Error('REVISION_CONFLICT');+ action = { type: 'update', expectedRevision: Number(expectedRevision) };+ if (actionId === 'delete') action.archived = true;+ else {+ if (typeof input.name === 'string') action.name = input.name;+ if (typeof input.description === 'string') action.description = input.description;+ if (input.replyMode === 'all' || input.replyMode === 'mentioned') action.responseMode = input.replyMode;+ if (input.speakingMode === 'auto' || input.speakingMode === 'sequential') action.speakingMode = input.speakingMode;+ if (typeof input.organizerBotId === 'string' || input.organizerBotId === null) action.organizerId = input.organizerBotId;+ }+ } else if (actionId === 'add-member' || actionId === 'remove-member' || actionId === 'set-member-role') {+ action = { type: 'member', actorId: String(input.actorId ?? input.botId ?? ''),+ action: actionId === 'add-member' ? 'invite' : actionId === 'remove-member' ? 'remove' : 'role' };+ if (actionId === 'set-member-role') {+ if (input.role !== 'admin' && input.role !== 'member') throw new Error('INVALID_PARAMS');+ action.role = input.role;+ }+ } else throw new Error('UNSUPPORTED_CHAT_ACTION');+ // A readback may advance the revision after a lost acknowledgement. Retry the original+ // receipt and body for the same intended edit, rather than creating another mutation.+ const key = JSON.stringify(action.type === 'update' ? { ...action, expectedRevision: undefined } : action);+ const prior = pending.current;+ const operation = prior?.binding === binding && prior.key === key ? prior+ : { binding, key, operationId: randomUUID(), managerId: current.managerId, action };+ pending.current = operation;+ const write = Symbol(); writing.current = write;+ // Fence reads started before this mutation, including the parent subscription refresh.+ ++sequence.current; verified.current = null;try {- await openLink(manager.host.deviceId);- if (!valid()) throw new Error('PERMISSION_DENIED');- const receipt = await invokeRemoteResourceAction(<T,>(deviceId: string, channel: string, args?: unknown[]) =>- invoke<T>(deviceId, channel, args, { preSend: () => { if (!valid()) throw new Error('PERMISSION_DENIED'); } }), manager.host, {- collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, resourceRef: botGroupResourceRef(groupId), actionId,- input: { expectedRevision: manager.group.revision, ...input },- }, i18n.language);- // A reply from a prior account/sheet must not close the current screen.- if (bindingRef.current !== binding || activeBinding.current !== binding) throw new Error('PERMISSION_DENIED');- // Fence pre-write reads and edits until the new revision is verified.- currentRef.current = { ...currentRef.current, key: '', managers: [] };- setSnapshot(undefined);- return receipt;+ await api.client.manageGroup(groupId, operation.managerId, operation.action, operation.operationId);+ if (!valid()) throw new Error('OWNER_CHANGED');+ pending.current = null;+ return { effects: [] };+ } catch (error) {+ // A definite rejection may be corrected; an uncertain network result keeps its receipt ID.+ const status = (error as { status?: number } | null)?.status;+ if (valid() && status && status >= 400 && status < 500) pending.current = null;+ throw error;} finally {- writing.current = false;- if (bindingRef.current === binding && activeBinding.current === binding) refresh();+ if (writing.current === write) writing.current = null;+ if (valid()) await refresh();}- }, [binding, groupId, selected, getPresenceAvailability, openLink, invoke, i18n.language, refresh]);+ }, [api, binding, groupId, refresh, valid]);+ const own = state?.binding === binding;+ const settings = own ? state.settings : undefined;+ const loading = enabled && (!own || state.loading);+ const editable = !loading && !!settings?.managerId && canManageBotGroup(settings.group) && !settings.group.dissolvedAt;+ return { group: settings?.group, act, refresh, loading, editable,+ reason: loading ? null : own && state.failed ? 'unavailable' as const : editable ? null : 'permission' as const };+}- const loading = enabled && !selected && (roster.loading || !own);- return { selected, displayHost, managers, select, act, loading, reason: loading ? null : snapshot ? snapshot.reason : 'noHost',- refresh: () => { void roster.refresh(); refresh(); } };+/** Own cloud actors remain addable while their execution computers are offline. */+export function useCloudGroupCandidates(enabled: boolean) {+ const api = useChatClient();+ const [state, setState] = useState<{ owner: string; rows: ChatActor[]; loading: boolean; failed: boolean }>();+ useEffect(() => {+ if (!enabled || !api.enabled) return;+ let cancelled = false;+ setState({ owner: api.owner, rows: [], loading: true, failed: false });+ void api.client.actors().then(rows => {+ if (!cancelled && api.current()) setState({ owner: api.owner, rows: rows.filter(row => row.kind === 'bot'), loading: false, failed: false });+ }).catch(() => { if (!cancelled && api.current()) setState({ owner: api.owner, rows: [], loading: false, failed: true }); });+ return () => { cancelled = true; };+ }, [api, enabled]);+ return state?.owner === api.owner && enabled ? state : { rows: [], loading: enabled, failed: false };}diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex b5b2af4e8f..bce968acd1 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -466,7 +466,7 @@ Chat Server 声明 `capabilities.groupSingleSpeaker: 1` 时,服务器群按下- 伙伴列表使用当前账号所属 realm 的端点清单 `chatApiBaseUrl` 与既有 Bearer/401 续期;从 `/v1/conversations` 分页列出 `joined` 群,不注册伙伴或执行器,不触发本地旧群迁移。成员、历史范围及附件访问由服务器当前成员权限决定,不要求成员有本地伙伴 Profile。- 手机使用自身登录账号的 human actor,不指定代演身份或借用电脑 token;HTTP 与 WS 共用当前 realm 的受信清单地址。+ 手机阅读与发言使用自身登录账号的 human actor,不借用电脑 token;群管理可使用同账号拥有的管理 actor(见下文)。HTTP 与 WS 共用当前 realm 的受信清单地址。正式包由启动端点闸门解析 CDN 清单,网络故障沿用本区已校验缓存/随包清单;非法清单阻断并可重试。旧清单缺少群聊地址时显示本地化配置错误,重试重新读取同区受信清单,恢复后重新订阅;不把缺配置视为空群列表。`check:endpoints` 对两份生产正本检查群聊地址非空 HTTPS,并阻止直连代码硬编码生产地址。@@ -489,16 +489,18 @@ Chat Server 声明 `capabilities.groupSingleSpeaker: 1` 时,服务器群按下`@所有人` 在发送前读取当前授权成员,只展开已加入且非本人的 actor,避免使用旧页面快照漏掉新成员。私有附件点击时重新授权,图片走已有看图器,其他文件打开短期签名 HTTPS URL,不转交账号 token。列表失败与空列表分开呈现,服务器故障使用服务器文案,不误报电脑离线。-- 直连页的群设置通过既有设备互联管理:仅在打开设置时按群 ID 查找在线电脑,读取该电脑的- 最新群快照,确认支持 `supportsSettingsManagement`、当前账号拥有群主或管理员角色后开放- 群名、回复方式、发言方式、负责人和成员修改。多台电脑可管理时可选择管理电脑;不按名字或- 任意在线设备猜测归属。群主可归档服务器群,历史消息保留;项目文件夹仍只能在电脑上选择。- 保存绑定当前账号、群、电脑和编辑版本;群名冲突保留输入并提示核对,添加伙伴只追加一位,- 不整批覆盖成员。管理电脑信息仅用一行「设备名 · 状态 · 操作」展示:- 已连接时使用弱文字和绿点;连接中只显示一处进度指示;断开时提供「重连」。保留同账号、- 同群已识别的设备名用于展示,不缓存授权;打开设置仍核验最新权限和版本。不可编辑的- 设置统一置灰,旧电脑、权限不足和读取失败保留各自的简短原因,不误报为离线。- 聊天与历史继续直连服务器,管理电脑离线不会阻断服务器聊天。+- 直连页的群设置直接使用当前账号的 Chat Server 连接,不发现电脑、不打开 device-link,也不探测伙伴执行端。+ 打开时读取群快照及账号身份,群主/管理员可修改群名、简介、回复方式、负责人和成员角色;+ 服务器未声明 `groupSingleSpeaker` 时保留发言方式。所有写入仍由服务器按实时群角色核权,+ 同账号拥有的群主/管理员 actor 可沿用 Desktop 的 `X-Chat-Actor` 管理路径;不能借用其他账号身份。+ 成员候选来自账号云端伙伴列表,不以电脑在线状态筛选;添加/移出/角色修改逐个提交,+ 不整批覆盖成员。群资料保存携带编辑时的 `expectedRevision`,冲突保留输入并重读最新设置;+ 网络结果不确定时仅由用户重试,复用同一操作回执 ID,避免重复执行。+ 账号、群或设置页生命周期变化后,旧请求不能恢复授权或影响新页面;写后重新读取,+ 读取失败保留已确认保存的结果但暂停继续编辑,提供服务器读取重试。+ 群主可归档服务器群,离群/解散/个人移除保持既有直连路径;电脑离线不影响人际聊天与群管理。+ 项目文件夹属于执行电脑,直连云端设置不展示虚假的空目录,也不为读取它连接电脑;原电脑入口保留目录展示。+ 仅实际请求伙伴回答或执行时,执行服务检查相关伙伴的可用性,失败只影响该次执行。- 直连页暂不提供新建群、上传附件、分工编排/审批、Thread 与表情操作;卡片保留服务器可读 fallback。原电脑兼容入口保留既有操作,不能把两条入口的能力混为一谈。同账号另一台 Desktop 已经通过自身 Chat Server 适配器访问群,不应依赖远程伙伴列表再聚合一遍。