Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bot-groups): restore plans and member management, diagnose attachment sends

Chris39dc6b00b144
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupAttachments.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupAttachments.test.ts
index 490df437ae..fdada6abd7 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupAttachments.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupAttachments.test.ts
@@ -216,7 +216,7 @@ describe('bot group attachment store', () => {
controllerDeviceId: 'phone-1',
attachments: [{ id: 'p', name: 'x.pdf', path: 'upload://peer-x.pdf', category: 'pdf', mimeType: 'application/pdf' }],
});
- expect(result).toEqual({ ok: false, errorCode: 'INVALID_PARAMS', message: 'FILE_PEER_DENIED' });
+ expect(result).toEqual({ ok: false, errorCode: 'ATTACHMENT_UNAVAILABLE', message: 'FILE_PEER_DENIED' });
});
it('turns any name into one safe path segment', () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts
index 0010b799d5..4cb3fa222f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupRemoteResourceProvider.test.ts
@@ -94,6 +94,7 @@ const service = {
continuePlan: vi.fn(),
retryPlan: vi.fn(),
editPlanStep: vi.fn(),
+ chatServer: { manage: vi.fn() },
};
describe('bot group remote resources', () => {
@@ -108,7 +109,8 @@ describe('bot group remote resources', () => {
INSERT INTO bot_profiles VALUES ('mimi', NULL, 'active'), ('abu', NULL, 'active'), ('ghost', 5, 'active');
`);
h.ownerCurrent = () => true;
- for (const fn of Object.values(service)) fn.mockReset();
+ for (const fn of Object.values(service)) if (typeof fn === 'function') fn.mockReset();
+ service.chatServer.manage.mockReset().mockResolvedValue({ ok: true });
service.getGroup.mockResolvedValue({ ok: true, group: detail() });
for (const name of ['updateGroup', 'setMembers', 'deleteGroup', 'continueRound', 'stopRound', 'startPlan', 'dismissPlan', 'continuePlan', 'retryPlan', 'editPlanStep'] as const) {
service[name].mockResolvedValue({ ok: true });
@@ -251,6 +253,38 @@ describe('bot group remote resources', () => {
expect(service.stopRound).not.toHaveBeenCalled();
});
+ it('preserves mixed membership, validates additions and removes a human by actor id', async () => {
+ const members: BotGroupSummary['members'] = [
+ { botId: 'mimi', actorId: 'cloud-mimi', actorKind: 'bot', isOwned: true, name: 'Mimi', avatar: '', avatarColor: '', status: 'active' },
+ { botId: 'person', actorId: 'actor-person', actorKind: 'human', isOwned: false, name: 'Guest', avatar: '', avatarColor: '', status: 'active' },
+ { botId: 'foreign', actorId: 'actor-foreign', actorKind: 'bot', isOwned: false, name: 'Foreign', avatar: '', avatarColor: '', status: 'active' },
+ ];
+ service.getGroup.mockResolvedValue({ ok: true, group: detail({ serverBacked: true, members }) });
+ const invoke = (actionId: string, input: Record<string, unknown>) => remoteResourceRegistry.invoke(context, {
+ client: client(), collectionId: BOT_GROUP_REMOTE_COLLECTION_ID, actionId, resourceRef: ref('g1'), input,
+ });
+ await invoke('set-members', { botIds: ['mimi', 'person', 'foreign', 'abu'] });
+ expect(service.setMembers).toHaveBeenLastCalledWith({ groupId: 'g1', botIds: ['mimi', 'person', 'foreign', 'abu'] });
+ for (const added of ['ghost', 'missing'])
+ await expect(invoke('set-members', { botIds: ['mimi', 'person', added] })).rejects.toMatchObject({ message: 'MEMBER_UNAVAILABLE' });
+ await expect(invoke('update', { organizerBotId: 'person' })).rejects.toMatchObject({ message: 'MEMBER_UNAVAILABLE' });
+ await invoke('update', { organizerBotId: 'foreign' });
+ expect(service.updateGroup).toHaveBeenLastCalledWith({ groupId: 'g1', organizerBotId: 'foreign' });
+ await invoke('plan-edit', { planId: 'p1', position: 0, action: 'reassign', botId: 'foreign' });
+ expect(service.editPlanStep).toHaveBeenLastCalledWith({ groupId: 'g1', planId: 'p1', position: 0, action: 'reassign', botId: 'foreign' });
+ await expect(invoke('plan-edit', { planId: 'p1', position: 0, action: 'reassign', botId: 'person' })).rejects.toThrow('MEMBER_UNAVAILABLE');
+ await invoke('remove-member', { actorId: 'actor-person' });
+ expect(service.chatServer.manage).toHaveBeenLastCalledWith({ groupId: 'g1', action: { type: 'member', action: 'remove', actorId: 'actor-person' } });
+ service.chatServer.manage.mockResolvedValueOnce({ ok: false, errorCode: 'ROLE_REQUIRED' });
+ await expect(invoke('remove-member', { actorId: 'actor-person' })).rejects.toThrow('PERMISSION_DENIED');
+ service.chatServer.manage.mockClear();
+ await expect(invoke('remove-member', { actorId: 'not-a-member' })).rejects.toThrow('NOT_FOUND');
+ expect(service.chatServer.manage).not.toHaveBeenCalled();
+ h.ownerCurrent = () => false;
+ await expect(invoke('remove-member', { actorId: 'actor-person' })).rejects.toThrow('Account changed');
+ expect(service.chatServer.manage).not.toHaveBeenCalled();
+ });
+
it('passes a phone’s attachments on with the phone that sent them', async () => {
const attachments = [{ id: 'a1', name: 'photo.jpg', path: 'cindy-peer-attach://x', category: 'image', mimeType: 'image/jpeg' }];
await remoteResourceRegistry.invoke(context, {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
index c5aa0874d3..e3701b4f2e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts
@@ -114,6 +114,53 @@ describe('Chat Server result delivery and refresh', () => {
service = withChatServer({ listGroups: vi.fn(async () => ({ ok: true, groups: [] })), settleLaneTurn: vi.fn(async () => false), dispose: vi.fn() } as unknown as BotGroupChatService, deps);
});
afterEach(() => { service.dispose(); vi.useRealTimers(); vi.unstubAllEnvs(); fixture.config = ''; vi.clearAllMocks(); });
+ it.each(['ATTACHMENT_UNAVAILABLE', 'INVALID_PARAMS'] as const)('keeps a useful reason for prepare %s', async (errorCode) => {
+ deps.prepareAttachments = vi.fn(async () => ({ ok: false, errorCode, message: 'private details' }));
+ deps.log = { warn: vi.fn() };
+ const result = await service.sendMessage({ groupId: roomId, text: '', clientId: 'phone-send-1', mentions: { all: false, botIds: [] }, attachments: [{}] }, { controllerDeviceId: 'phone' });
+ expect(result).toMatchObject({ ok: false, errorCode: errorCode === 'INVALID_PARAMS' ? 'INVALID_ATTACHMENT' : errorCode });
+ expect(JSON.stringify(vi.mocked(deps.log.warn).mock.calls)).not.toContain('private details');
+ });
+
+ it('returns a slow send receipt to duplicate attempts without consuming the phone upload again', async () => {
+ const commit = vi.fn();
+ let release!: () => void;
+ deps.prepareAttachments = vi.fn(async () => {
+ await new Promise<void>(resolve => { release = resolve; });
+ return { ok: true as const, attachments: [], commit, discard: vi.fn() };
+ });
+ fixture.handle.mockImplementation((route, method) => {
+ if (route.endsWith('/members')) return { body: [] };
+ if (route.endsWith('/messages') && method === 'POST') return { body: { id: 'saved-message' } };
+ return response(route);
+ });
+ const input = { groupId: roomId, text: 'photo', clientId: 'phone-send-1', mentions: { all: false, botIds: [] }, attachments: [{}] };
+ const first = service.sendMessage(input, { controllerDeviceId: 'phone' });
+ await vi.advanceTimersByTimeAsync(16_000);
+ expect(release).toBeTypeOf('function');
+ const retry = service.sendMessage(input, { controllerDeviceId: 'phone' });
+ release();
+ expect(await first).toEqual({ ok: true, messageId: 'saved-message' });
+ expect(await retry).toEqual(await first);
+ expect(await service.sendMessage(input, { controllerDeviceId: 'phone' })).toEqual(await first);
+ expect(deps.prepareAttachments).toHaveBeenCalledTimes(1);
+ expect(commit).toHaveBeenCalledTimes(1);
+ expect(fixture.handle.mock.calls.filter(([route, method]) => route.endsWith('/messages') && method === 'POST')).toHaveLength(1);
+ });
+
+ it('reports an HTTP send failure with safe route, code and status', async () => {
+ deps.log = { warn: vi.fn() };
+ fixture.handle.mockImplementation((route, method) => {
+ if (route.endsWith('/members')) return { body: [] };
+ if (route.endsWith('/messages') && method === 'POST') return { status: 500, body: { error: { code: 'UPSTREAM_FAILED', message: 'secret text' } } };
+ return response(route);
+ });
+ expect(await service.sendMessage({ groupId: roomId, text: 'private body', clientId: 'send-500-test', mentions: { all: false, botIds: [] } }))
+ .toMatchObject({ ok: false, errorCode: 'SERVICE_ERROR' });
+ expect(deps.log.warn).toHaveBeenCalledWith('Chat request failed', expect.objectContaining({ route: '/conversations/:id/messages', status: 500, code: 'UPSTREAM_FAILED' }));
+ expect(JSON.stringify(vi.mocked(deps.log.warn).mock.calls)).not.toMatch(/private body|secret text/);
+ });
+
async function start() {
fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];
await vi.advanceTimersByTimeAsync(2000);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerErrors.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerErrors.test.ts
new file mode 100644
index 0000000000..c04a434fec
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerErrors.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+import { chatErrorDiagnostic, chatGroupFailure } from '../chatServerErrors.js';
+
+describe('chat group errors', () => {
+ it.each([
+ ['MEMBER_UNAVAILABLE', 'MEMBER_UNAVAILABLE'], ['INVALID_ATTACHMENT', 'INVALID_ATTACHMENT'],
+ ['FILE_PEER_TIMEOUT', 'ATTACHMENT_UNAVAILABLE'], ['ATTACHMENT_TOO_LARGE', 'ATTACHMENT_TOO_LARGE'],
+ ['MEDIA_UPLOAD_FAILED', 'MEDIA_UPLOAD_FAILED'], ['INVALID_MEDIA_URL', 'MEDIA_UPLOAD_FAILED'],
+ ['AUTH_REQUIRED', 'AUTH_REQUIRED'], ['CHAT_ENDPOINT_UNAVAILABLE', 'CHAT_UNAVAILABLE'],
+ ['IMPORT_PENDING', 'IMPORT_PENDING'], ['REQUEST_TIMEOUT', 'REQUEST_TIMEOUT'],
+ ['ROLE_REQUIRED', 'PERMISSION_DENIED'], ['CONVERSATION_ARCHIVED', 'GROUP_ARCHIVED'],
+ ['CONVERSATION_NOT_FOUND', 'NOT_FOUND'], ['untrusted /private/path?token=secret', 'SERVICE_ERROR'],
+ ])('classifies %s without exposing exception text', (code, expected) => {
+ expect(chatGroupFailure(new Error(code))).toEqual({ ok: false, errorCode: expected, message: expected });
+ });
+ it('keeps only diagnostic code and HTTP status', () => {
+ expect(chatErrorDiagnostic(Object.assign(new Error('private URL https://x/?token=secret'), { status: 500 })))
+ .toEqual({ code: 'UNKNOWN', status: 500 });
+ expect(chatErrorDiagnostic(Object.assign(new Error('arbitrary message'), { code: 'ECONNRESET' })))
+ .toEqual({ code: 'ECONNRESET' });
+ expect(chatGroupFailure(new DOMException('signed URL', 'TimeoutError')).errorCode).toBe('REQUEST_TIMEOUT');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
index 753884967d..504c8316fd 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
@@ -21,6 +21,20 @@ describe('chat private media', () => {
expect(f.fetch).toHaveBeenLastCalledWith('https://upload.example.test/signed', expect.objectContaining({ redirect: 'error', headers: { 'Content-Type': 'image/png' } }));
expect(vi.mocked(api).mock.calls.at(-1)?.[0]).toBe('/conversations/room/media/media/complete');
});
+ it.each(['prepare', 'upload', 'complete'])('reports the failing %s stage without signed URLs or filenames', async (stage) => {
+ f.read.mockResolvedValue({ buffer: Buffer.from('png') });
+ const log = { warn: vi.fn() };
+ f.fetch.mockResolvedValue(new Response('', { status: stage === 'upload' ? 403 : 200 }));
+ const api = vi.fn(async (route: string) => {
+ if (stage === 'prepare' && route.endsWith('/media') || stage === 'complete' && route.endsWith('/complete'))
+ throw Object.assign(new Error('REQUEST_FAILED'), { status: 500 });
+ return { id: 'media', uploadUrl: 'https://upload.example.test/private?token=secret' };
+ }) as unknown as ChatApi;
+ await expect(createChatMedia(api, () => true, log).upload('room', 'operation', [attachment], 'actor')).rejects.toThrow();
+ expect(log.warn).toHaveBeenCalledWith('Chat media upload failed', expect.objectContaining({ stage, status: stage === 'upload' ? 403 : 500 }));
+ expect(JSON.stringify(log.warn.mock.calls)).not.toMatch(/secret|picture.png|https:/);
+ });
+
it('does not upload bytes when the owner changes during local file reading', async () => {
let current = true;
f.fetch.mockClear();
diff --git a/apps/desktop/src/main/maker-ipc/botGroupAttachments.ts b/apps/desktop/src/main/maker-ipc/botGroupAttachments.ts
index d0c0d03c34..6bffccb98a 100644
--- a/apps/desktop/src/main/maker-ipc/botGroupAttachments.ts
+++ b/apps/desktop/src/main/maker-ipc/botGroupAttachments.ts
@@ -10,6 +10,7 @@
* folder (`bot-groups/<groupId>/attachments/`), which goes to the trash with the group.
*/
+import { chatErrorDiagnostic } from './chatServerErrors.js';
import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
@@ -194,8 +195,8 @@ export function createBotGroupAttachmentStore(deps: { ownerRoot: () => string })
} catch (error) {
await discard();
// Transfer errors carry no host paths; anything else is reported generically.
- const message = error instanceof Error && /^FILE_PEER_|DEVICE_LINK_/.test(error.message) ? error.message : '附件无效';
- return { ok: false, errorCode: 'INVALID_PARAMS', message };
+ const { code } = chatErrorDiagnostic(error);
+ return { ok: false, errorCode: code.startsWith('FILE_PEER_') || code.startsWith('DEVICE_LINK_') ? 'ATTACHMENT_UNAVAILABLE' : 'INVALID_ATTACHMENT', message: code };
}
return {
ok: true,
diff --git a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
index 68424b7100..70896c636a 100644
--- a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
+++ b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
@@ -159,7 +159,7 @@ export interface BotGroupChatServiceDeps {
createId?: () => string;
memberTurnTimeoutMs?: number;
stepTurnTimeoutMs?: number;
- log?: { warn: (message: string, meta?: Record<string, unknown>) => void };
+ log?: { warn: (message: string, meta?: Record<string, unknown>) => void; info?: (message: string, meta?: Record<string, unknown>) => void };
}
export interface BotGroupPreparedAttachments {
diff --git a/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts b/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts
index 7626d57217..6cbf9d43d7 100644
--- a/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts
+++ b/apps/desktop/src/main/maker-ipc/botGroupRemoteResourceProvider.ts
@@ -8,6 +8,7 @@
*/
import path from 'node:path';
+import { chatGroupFailure } from './chatServerErrors.js';
import { inArray } from 'drizzle-orm';
import type {
@@ -187,6 +188,7 @@ export function botGroupRemoteChatData(detail: BotGroupDetail): BotGroupRemoteCh
? { ...message, attachments: message.attachments.map((attachment) => ({ ...attachment, path: null })) }
: message)),
supportsAttachments: true,
+ supportsMemberRemoval: detail.serverBacked === true,
};
}
@@ -348,10 +350,20 @@ export function registerBotGroupRemoteResourceProvider(service: () => BotGroupCh
: null;
if (!groupId) throw new RemoteResourceRegistryError('INVALID_PARAMS', 'INVALID_PARAMS');
// Every action re-checks that the phone may still see this group, and any teammate it names.
- await readVisibleGroup(groupId);
- if (actionId === 'update' && typeof input.organizerBotId === 'string') await assertBotsVisible([input.organizerBotId]);
- if (actionId === 'set-members') await assertBotsVisible(botIdsInput());
- if (actionId === 'plan-edit' && typeof input.botId === 'string') await assertBotsVisible([input.botId]);
+ const visibleGroup = await readVisibleGroup(groupId);
+ const candidateId = actionId === 'update' ? input.organizerBotId : actionId === 'plan-edit' ? input.botId : undefined;
+ if (typeof candidateId === 'string') {
+ const member = visibleGroup.members.find(member => member.botId === candidateId);
+ if (visibleGroup.serverBacked) {
+ if (!member || member.actorKind !== 'bot' || member.status !== 'active')
+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'MEMBER_UNAVAILABLE');
+ } else await assertBotsVisible([candidateId]);
+ }
+ if (actionId === 'set-members') {
+ // Preserve server humans and foreign companions; only newly added IDs need local visibility.
+ const currentMemberIds = new Set(visibleGroup.members.map(member => member.botId));
+ await assertBotsVisible(botIdsInput().filter(botId => !currentMemberIds.has(botId)));
+ }
const current = ownerService();
const planInput = { groupId, planId: input.planId };
let result: { ok: true } | BotGroupFailure;
@@ -381,6 +393,15 @@ export function registerBotGroupRemoteResourceProvider(service: () => BotGroupCh
result = await current.updateGroup(patch);
break;
}
+ case 'remove-member': {
+ const member = visibleGroup.members.find(member => member.actorId === input.actorId);
+ if (!visibleGroup.serverBacked || !current.chatServer || !member?.actorId)
+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'NOT_FOUND');
+ const removed = await current.chatServer.manage({ groupId, action: { type: 'member', action: 'remove', actorId: member.actorId } });
+ if (!removed.ok) refuse(chatGroupFailure(new Error(removed.errorCode)));
+ result = { ok: true };
+ break;
+ }
case 'set-members':
result = await current.setMembers({ groupId, botIds: botIdsInput() });
break;
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 05b197893e..000605793d 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -9,6 +9,7 @@ import { existsSync, readFileSync } from 'node:fs';
import { request as httpRequest } from 'node:http';
import { request as httpsRequest } from 'node:https';
import { migrateLocalGroups } from './chatServerMigration.js';
+import { chatErrorDiagnostic, chatGroupFailure } from './chatServerErrors.js';
import { createChatMedia } from './chatServerMedia.js';
import { chatServerWorkspaces } from './chatServerWorkspaces.js';
import { buildPlanStepBrief } from './botGroupDivision.js';
@@ -68,7 +69,6 @@ class ChatResponseError extends Error {
}
const id = z.string().uuid();
const groupInput = z.object({ name: z.string().trim().min(1).max(40), botIds: z.array(z.string().min(1)).max(6) });
-const failure = (message: string): BotGroupFailure => ({ ok: false, errorCode: 'HOST_NOT_READY', message });
const bodyText = (m: Message) => m.deleted ? '(消息已删除)' : m.content.filter(b => b.namespace !== 'cindy.local-history' || b.data?.activity === true).map(b => b.text ?? b.fallback ?? (b.type === 'media' ? `[附件: ${b.caption ?? '文件'}]` : '')).join('\n');
// Presentation only: keep actor IDs and stored names independent of ownership labels.
const memberName = (m: Member) => m.kind === 'bot' && m.ownerName.trim() ? `${m.name} (${m.ownerName.trim()})` : m.name;
@@ -153,7 +153,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if (url.protocol !== 'https:' && (app.isPackaged || url.origin !== 'http://127.0.0.1:3018')) return Promise.reject(new Error('INVALID_CHAT_ENDPOINT'));
const token = getAccessToken();
if (!token) return Promise.reject(new Error('AUTH_REQUIRED'));
- return new Promise((resolve, reject) => {
+ const started = Date.now();
+ return new Promise<T>((resolve, reject) => {
const req = (url.protocol === 'https:' ? httpsRequest : httpRequest)(url, {
method, headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json',
...(actorId ? { 'X-Chat-Actor': actorId } : {}) }, timeout: 15000,
@@ -173,7 +174,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
throw new Error('AUTH_REQUIRED');
}
if ((res.statusCode ?? 500) >= 300 && (res.statusCode ?? 500) < 400) throw new Error('CHAT_REDIRECT_REFUSED');
- const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
+ let value;
+ try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
+ catch { throw new ChatResponseError('INVALID_RESPONSE', res.statusCode ?? 500); }
if ((res.statusCode ?? 500) >= 400) throw new ChatResponseError(value.error?.code ?? 'REQUEST_FAILED', res.statusCode ?? 500);
resolve(value);
} catch (error) { reject(error); }
@@ -182,9 +185,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
req.on('timeout', () => req.destroy(new Error('REQUEST_TIMEOUT')));
req.on('error', reject);
req.end(data === undefined ? undefined : JSON.stringify(data));
+ }).catch(error => {
+ const routeTemplate = route.split('?')[0].split('/').map(part =>
+ ['conversations','media','complete','messages','plans','members','snapshot','import','actors','me','executions'].includes(part) || !part ? part : ':id').join('/');
+ const operation = data && typeof data === 'object' && 'operationId' in data ? data.operationId : null;
+ deps.log?.warn('Chat request failed', { route: routeTemplate, method, durationMs: Date.now() - started,
+ ...(typeof operation === 'string' ? { trace: createHash('sha256').update(operation).digest('hex').slice(0, 16) } : {}), ...chatErrorDiagnostic(error) });
+ throw error;
});
}
- const media = createChatMedia(api, current);
+ const media = createChatMedia(api, current, deps.log);
let upgrade: Promise<Map<string, string>> | undefined;
let upgradeRetryAt = 0;
const upgradeErrors = new Map<string, string>();
@@ -223,7 +233,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
onError: (source, error) => {
incomplete = true;
upgradeErrors.set(source, error instanceof Error ? error.message : 'IMPORT_FAILED');
- deps.log?.warn('Group history upgrade will retry', { groupId: source });
+ deps.log?.warn('Group history upgrade will retry', { groupId: source, ...chatErrorDiagnostic(error) });
changed(upgradedGroups.get(source) ?? source);
},
receipts: chatMigrationReceipts(config.baseUrl, selfId, current),
@@ -718,13 +728,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const heartbeat = setInterval(() => { for (const run of running.values()) void checkLease(run); }, 15000);
timer.unref(); heartbeat.unref();
const safe = <T>(fn: () => Promise<T>): Promise<T | BotGroupFailure> => fn().catch(error => {
- const code = error instanceof Error ? error.message : '';
- if (['PLAN_OPEN','PLAN_CLOSED'].includes(code)) return { ok: false, errorCode: code as 'PLAN_OPEN' | 'PLAN_CLOSED', message: '分工状态已变化,请刷新后重试。' };
- if (code === 'IMPORT_PENDING') return failure('这个群的历史记录尚未上传完成,稍后会自动重试,其他群可正常使用。');
- if (code === 'CONVERSATION_NOT_FOUND') return { ok: false, errorCode: 'NOT_FOUND', message: '你已退出此群,或没有访问权限。' };
- if (code === 'CONVERSATION_ARCHIVED') return { ok: false, errorCode: 'INVALID_PARAMS', message: '本群已归档,不能发送新消息。' };
- if (['ROLE_REQUIRED', 'ACTOR_NOT_OWNED', 'OWNER_REQUIRED'].includes(code)) return { ok: false, errorCode: 'INVALID_PARAMS', message: '你没有执行此操作的权限。' };
- return failure('聊天服务暂时无法连接,请稍后重试。');
+ deps.log?.warn('Chat group action failed', chatErrorDiagnostic(error));
+ return chatGroupFailure(error instanceof z.ZodError ? new Error('INVALID_PARAMS') : error);
});
async function mentionIds(roomId: string, mentions: { all: boolean; botIds: string[] }) {
const members = await api<Member[]>(`/conversations/${roomId}/members`);
@@ -800,6 +805,43 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
rooms.delete(room.groupId); subscribe(room.groupId); changed(room.groupId); return room;
}),
};
+ const sendMessage: BotGroupChatService['sendMessage'] = (input, origin) => safe(async () => {
+ const started = Date.now();
+ const i = z.object({ groupId: id, text: z.string().max(8000), clientId: z.string().min(8).max(160),
+ mentions: z.object({ all: z.boolean(), botIds: z.array(z.string()) }), division: z.boolean().optional(), attachments: z.array(z.unknown()).optional() }).parse(input);
+ i.groupId = await resolveGroup(i.groupId);
+ if (!i.text.trim() && !i.attachments?.length) throw new Error('INVALID_INPUT');
+ const s = await snapshot(i.groupId);
+ const openPlan = (await api<ServerPlan[]>(`/conversations/${i.groupId}/plans`)).find(p => ['running','waiting'].includes(p.status));
+ if (i.division && openPlan) throw new Error('PLAN_OPEN');
+ const commentPlan = openPlan && !i.mentions.botIds.length && !i.mentions.all && (openPlan.creator_id === selfId || s.members.some(m => m.id === selfId && ['owner','admin'].includes(m.role))) ? openPlan : undefined;
+ const shouldPlan = !openPlan && !!deps.decidePlan && (i.division || !i.mentions.botIds.length && !i.mentions.all && s.members.filter(m => m.kind === 'bot' && m.state === 'joined').length >= 2);
+ const prepared = i.attachments?.length ? await deps.prepareAttachments?.({ groupId: i.groupId, attachments: i.attachments, controllerDeviceId: origin?.controllerDeviceId }) : undefined;
+ if (i.attachments?.length && (!prepared || !prepared.ok)) {
+ const error = new Error(prepared && !prepared.ok ? prepared.errorCode === 'INVALID_PARAMS' ? 'INVALID_ATTACHMENT' : prepared.errorCode : 'INVALID_ATTACHMENT');
+ deps.log?.warn('Chat attachment preparation failed', { groupId: i.groupId, trace: createHash('sha256').update(i.clientId).digest('hex').slice(0, 16), ...chatErrorDiagnostic(prepared && !prepared.ok ? new Error(prepared.message) : error) });
+ throw error;
+ }
+ let result: { id: string };
+ try {
+ const mentions = await mentionIds(i.groupId, i.mentions);
+ result = await api<{ id: string }>(`/conversations/${i.groupId}/${commentPlan ? `plans/${commentPlan.id}/messages` : 'messages'}`, 'POST', {
+ operationId: i.clientId, content: [ ...(i.text ? [{ type: 'text', text: i.text }] : []),
+ ...await media.upload(i.groupId, i.clientId, prepared?.ok ? prepared.attachments : [], selfId) ], mentions, deferExecution: shouldPlan,
+ });
+ } catch (error) {
+ if (prepared?.ok) await prepared.discard();
+ throw error;
+ }
+ if (prepared?.ok) prepared.commit();
+ if (shouldPlan) void decideArrangement(s, result.id, i.text, i.division === true, prepared?.ok ? prepared.attachments : []).catch(() => undefined);
+ deps.log?.info?.('Chat group send confirmed', { groupId: i.groupId, messageId: result.id,
+ trace: createHash('sha256').update(i.clientId).digest('hex').slice(0, 16), durationMs: Date.now() - started });
+ changed(i.groupId); return { ok: true as const, messageId: result.id };
+ });
+ // A lost controller ACK must not consume the phone upload or submit the same message twice.
+ const pendingSends = new Map<string, ReturnType<BotGroupChatService['sendMessage']>>();
+ const sendReceipts = new Map<string, Awaited<ReturnType<BotGroupChatService['sendMessage']>>>();
return {
chatServer,
listGroups: () => safe(async () => {
@@ -825,33 +867,23 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const room = await api<{ id: string }>('/conversations', 'POST', { operationId: randomUUID(), kind: 'group', name: i.name, participants });
subscribe(room.id); changed(room.id); return { ok: true as const, groupId: room.id };
}),
- sendMessage: (input, origin) => safe(async () => {
- const i = z.object({ groupId: id, text: z.string().max(8000), clientId: z.string().min(8).max(160),
- mentions: z.object({ all: z.boolean(), botIds: z.array(z.string()) }), division: z.boolean().optional(), attachments: z.array(z.unknown()).optional() }).parse(input);
- i.groupId = await resolveGroup(i.groupId);
- if (!i.text.trim() && !i.attachments?.length) throw new Error('INVALID_INPUT');
- const s = await snapshot(i.groupId);
- const openPlan = (await api<ServerPlan[]>(`/conversations/${i.groupId}/plans`)).find(p => ['running','waiting'].includes(p.status));
- if (i.division && openPlan) throw new Error('PLAN_OPEN');
- const commentPlan = openPlan && !i.mentions.botIds.length && !i.mentions.all && (openPlan.creator_id === selfId || s.members.some(m => m.id === selfId && ['owner','admin'].includes(m.role))) ? openPlan : undefined;
- const shouldPlan = !openPlan && !!deps.decidePlan && (i.division || !i.mentions.botIds.length && !i.mentions.all && s.members.filter(m => m.kind === 'bot' && m.state === 'joined').length >= 2);
- const prepared = i.attachments?.length ? await deps.prepareAttachments?.({ groupId: i.groupId, attachments: i.attachments, controllerDeviceId: origin?.controllerDeviceId }) : undefined;
- if (i.attachments?.length && (!prepared || !prepared.ok)) throw new Error('INVALID_ATTACHMENT');
- let result: { id: string };
- try {
- const mentions = await mentionIds(i.groupId, i.mentions);
- result = await api<{ id: string }>(`/conversations/${i.groupId}/${commentPlan ? `plans/${commentPlan.id}/messages` : 'messages'}`, 'POST', {
- operationId: i.clientId, content: [ ...(i.text ? [{ type: 'text', text: i.text }] : []),
- ...await media.upload(i.groupId, i.clientId, prepared?.ok ? prepared.attachments : [], selfId) ], mentions, deferExecution: shouldPlan,
- });
- } catch (error) {
- if (prepared?.ok) await prepared.discard();
- throw error;
- }
- if (prepared?.ok) prepared.commit();
- if (shouldPlan) void decideArrangement(s, result.id, i.text, i.division === true, prepared?.ok ? prepared.attachments : []).catch(() => undefined);
- changed(i.groupId); return { ok: true as const, messageId: result.id };
- }),
+ sendMessage: (input, origin) => {
+ if (!current()) return Promise.resolve(chatGroupFailure(new Error('OWNER_CHANGED')));
+ const key = createHash('sha256').update(JSON.stringify([input, origin?.controllerDeviceId ?? null])).digest('hex');
+ const receipt = sendReceipts.get(key);
+ if (receipt) return Promise.resolve(receipt);
+ const pending = pendingSends.get(key);
+ if (pending) return pending;
+ const attempt = sendMessage(input, origin).then(result => {
+ if (result.ok && current()) {
+ sendReceipts.set(key, result);
+ if (sendReceipts.size > 128) sendReceipts.delete(sendReceipts.keys().next().value!);
+ }
+ return result;
+ }).finally(() => pendingSends.delete(key));
+ pendingSends.set(key, attempt);
+ return attempt;
+ },
updateGroup: input => safe(async () => {
const i = z.object({ groupId: id, name: z.string().min(1).max(40).optional(), replyMode: z.enum(['all', 'mentioned']).optional(),
speakingMode: z.enum(['auto', 'sequential']).optional(), organizerBotId: z.string().nullable().optional(), projectDir: z.string().max(4096).nullable().optional() }).parse(input);
diff --git a/apps/desktop/src/main/maker-ipc/chatServerErrors.ts b/apps/desktop/src/main/maker-ipc/chatServerErrors.ts
new file mode 100644
index 0000000000..e1e445f0c4
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/chatServerErrors.ts
@@ -0,0 +1,31 @@
+import type { BotGroupErrorCode, BotGroupFailure } from '../../shared/botGroupChat.js';
+
+/** Keep diagnostic codes and HTTP status, never exception text, URLs, paths or response bodies. */
+export function chatErrorDiagnostic(error: unknown): { code: string; status?: number } {
+ const value = error as { code?: unknown; message?: unknown; status?: unknown; name?: unknown } | null;
+ const candidate = typeof value?.code === 'string' ? value.code : value?.message;
+ const code = typeof candidate === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(candidate)
+ ? candidate : value?.name === 'TimeoutError' || value?.name === 'AbortError' ? 'REQUEST_TIMEOUT' : 'UNKNOWN';
+ return { code, ...(typeof value?.status === 'number' && Number.isInteger(value.status) ? { status: value.status } : {}) };
+}
+
+/** Stable localized categories for desktop and remote controllers; raw errors stay private. */
+export function chatGroupFailure(error: unknown): BotGroupFailure {
+ const { code, status } = chatErrorDiagnostic(error);
+ let errorCode: BotGroupErrorCode;
+ if (['PLAN_OPEN', 'PLAN_CLOSED', 'MEMBER_LIMIT', 'MEMBER_UNAVAILABLE', 'HOST_NOT_READY',
+ 'INVALID_ATTACHMENT', 'ATTACHMENT_UNAVAILABLE', 'ATTACHMENT_TOO_LARGE', 'MEDIA_UPLOAD_FAILED',
+ 'AUTH_REQUIRED', 'IMPORT_PENDING', 'REQUEST_TIMEOUT'].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';
+ else if (code === 'CHAT_ENDPOINT_UNAVAILABLE' || code === 'INVALID_CHAT_ENDPOINT' || ['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN'].includes(code)) errorCode = 'CHAT_UNAVAILABLE';
+ else if (code === 'ETIMEDOUT' || code === 'ECONNRESET') errorCode = 'REQUEST_TIMEOUT';
+ 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_ARCHIVED') errorCode = 'GROUP_ARCHIVED';
+ else if (code === 'INVALID_INPUT' || code === 'INVALID_PARAMS') errorCode = 'INVALID_PARAMS';
+ else errorCode = 'SERVICE_ERROR';
+ return { ok: false, errorCode, message: errorCode };
+}
diff --git a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
index 43493c7b19..28e0132575 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
@@ -1,3 +1,4 @@
+import { chatErrorDiagnostic } from './chatServerErrors.js';
import { net } from 'electron';
import fs from 'node:fs/promises';
import path from 'node:path';
@@ -12,7 +13,7 @@ import type { BotGroupAttachment } from '../../shared/botGroupChat.js';
import type { ChatApi, ChatContentBlock } from './chatServerMigration.js';
const MAX_SIZE = 100 * 1024 * 1024;
-export function createChatMedia(api: ChatApi, current: () => boolean) {
+export function createChatMedia(api: ChatApi, current: () => boolean, log?: { warn(message: string, meta?: Record<string, unknown>): void }) {
const cache = new Map<string, Promise<BotGroupAttachment>>();
const check = () => { if (!current()) throw new Error('OWNER_CHANGED'); };
const signedUrl = (value: string) => {
@@ -24,37 +25,48 @@ export function createChatMedia(api: ChatApi, current: () => boolean) {
async upload(roomId: string, source: string, attachments: BotGroupAttachment[], actorId: string): Promise<ChatContentBlock[]> {
const blocks: ChatContentBlock[] = [];
for (const attachment of attachments) {
- check();
- if (attachment.size > MAX_SIZE) throw new Error('ATTACHMENT_TOO_LARGE');
- if (attachment.path) {
- const stat = await fs.stat(attachment.path); check();
- if (!stat.isFile() || stat.size > MAX_SIZE) throw new Error('ATTACHMENT_TOO_LARGE');
- }
- const bytes = attachment.url?.startsWith('cindy-media://') ? (await readMedia(attachment.url)).buffer
- : attachment.path ? await fs.readFile(attachment.path) : null;
- check();
- if (!bytes || !bytes.length || bytes.length > MAX_SIZE) throw new Error('ATTACHMENT_UNAVAILABLE');
- const key = createHash('sha256').update(source).update(attachment.id).update(bytes).digest('hex');
- // Expired abandoned uploads must get a new prepare receipt, but a successful
- // message keeps the same content even when the request's ACK was lost.
- let upload: { id: string; uploadUrl: string };
+ let stage = 'read';
+ const started = Date.now();
try {
- upload = await api(`/conversations/${roomId}/media`, 'POST', {
- operationId: `media:${key}`, name: attachment.name, type: attachment.mimeType, size: bytes.length,
- }, actorId);
+ check();
+ if (attachment.size > MAX_SIZE) throw new Error('ATTACHMENT_TOO_LARGE');
+ if (attachment.path) {
+ const stat = await fs.stat(attachment.path); check();
+ if (!stat.isFile() || stat.size > MAX_SIZE) throw new Error('ATTACHMENT_TOO_LARGE');
+ }
+ const bytes = attachment.url?.startsWith('cindy-media://') ? (await readMedia(attachment.url)).buffer
+ : attachment.path ? await fs.readFile(attachment.path) : null;
+ check();
+ if (!bytes || !bytes.length || bytes.length > MAX_SIZE) throw new Error('ATTACHMENT_UNAVAILABLE');
+ const key = createHash('sha256').update(source).update(attachment.id).update(bytes).digest('hex');
+ // Expired abandoned uploads must get a new prepare receipt, but a successful
+ // message keeps the same content even when the request's ACK was lost.
+ let upload: { id: string; uploadUrl: string };
+ stage = 'prepare';
+ try {
+ upload = await api(`/conversations/${roomId}/media`, 'POST', {
+ operationId: `media:${key}`, name: attachment.name, type: attachment.mimeType, size: bytes.length,
+ }, actorId);
+ } catch (error) {
+ if (!(error instanceof Error) || error.message !== 'UPLOAD_EXPIRED') throw error;
+ upload = await api(`/conversations/${roomId}/media`, 'POST', {
+ operationId: `media:${key}:${randomUUID()}`, name: attachment.name, type: attachment.mimeType, size: bytes.length,
+ }, actorId);
+ }
+ check();
+ stage = 'upload';
+ const response = await net.fetch(signedUrl(upload.uploadUrl), { method: 'PUT', redirect: 'error',
+ headers: { 'Content-Type': attachment.mimeType }, body: new Uint8Array(bytes), signal: AbortSignal.timeout(60000) });
+ if (!response.ok) throw Object.assign(new Error('MEDIA_UPLOAD_FAILED'), { status: response.status });
+ check();
+ stage = 'complete';
+ await api(`/conversations/${roomId}/media/${upload.id}/complete`, 'POST', { operationId: `seal:${upload.id}` }, actorId);
+ blocks.push({ type: 'media', mediaId: upload.id, caption: attachment.name });
} catch (error) {
- if (!(error instanceof Error) || error.message !== 'UPLOAD_EXPIRED') throw error;
- upload = await api(`/conversations/${roomId}/media`, 'POST', {
- operationId: `media:${key}:${randomUUID()}`, name: attachment.name, type: attachment.mimeType, size: bytes.length,
- }, actorId);
+ log?.warn('Chat media upload failed', { stage, groupId: roomId,
+ trace: createHash('sha256').update(source).digest('hex').slice(0, 16), durationMs: Date.now() - started, ...chatErrorDiagnostic(error) });
+ throw error;
}
- check();
- const response = await net.fetch(signedUrl(upload.uploadUrl), { method: 'PUT', redirect: 'error',
- headers: { 'Content-Type': attachment.mimeType }, body: new Uint8Array(bytes), signal: AbortSignal.timeout(60000) });
- if (!response.ok) throw new Error('MEDIA_UPLOAD_FAILED');
- check();
- await api(`/conversations/${roomId}/media/${upload.id}/complete`, 'POST', { operationId: `seal:${upload.id}` }, actorId);
- blocks.push({ type: 'media', mediaId: upload.id, caption: attachment.name });
}
return blocks;
},
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
index 3411b2d066..da9de8d4c1 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx
@@ -753,7 +753,7 @@ function BotGroupTimelineItem({
const text = key ? t(key, { name }) : message.content;
return <p className="text-center text-12 text-[var(--text-tertiary)]">{text}</p>;
}
- if (message.authorKind === 'user' && message.isSelf !== false) {
+ if (message.kind === 'message' && message.authorKind === 'user' && message.isSelf !== false) {
// An attachment-only message shows just its attachments, without an empty bubble.
const hasText = message.content.trim().length > 0;
return (
@@ -785,14 +785,15 @@ function BotGroupTimelineItem({
</article>
);
}
- // Name snapshot from when it was said; the avatar follows the live profile.
+ // A server plan is signed by its human creator; present the organizer without changing authorship.
+ const isPlanCard = message.kind === 'plan';
+ const identity = isPlanCard ? members.find(candidate => candidate.botId === plan?.organizerBotId) : member;
const author = {
- name: message.authorName || member?.name || '',
- avatar: member?.avatar ?? null,
- avatarUrl: member?.avatarUrl,
- avatarColor: member?.avatarColor ?? null,
+ name: isPlanCard ? identity?.name || plan?.organizerName || '' : message.authorName || identity?.name || '',
+ avatar: identity?.avatar ?? null,
+ avatarUrl: identity?.avatarUrl,
+ avatarColor: identity?.avatarColor ?? null,
};
- const isPlanCard = message.kind === 'plan';
const hasText = message.content.trim().length > 0;
return (
<article {...(message.kind === 'message' ? { [SHARE_SESSION_ATTR]: shareScope, [SHARE_MESSAGE_ATTR]: message.id } : {})}
diff --git a/apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx b/apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx
index f27b3a42b4..1243637ed1 100644
--- a/apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx
@@ -162,7 +162,7 @@ function EditableStepRow({
onEdit: (step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) => void;
}) {
const { t } = useTranslation();
- const candidates = members.filter(isActiveBotGroupMember);
+ const candidates = members.filter(member => isActiveBotGroupMember(member) && (!member.actorKind || member.actorKind === 'bot'));
const lastStep = plan.steps.length <= 1;
return (
<DropdownMenu>
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
index 8d72194ccd..7e238eb003 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx
@@ -597,6 +597,32 @@ describe('BotGroupChatView', () => {
await waitFor(() => expect(mocks.dismissBotGroupPlan).toHaveBeenCalledWith({ groupId: 'g1', planId: 'p1' }));
});
+ it.each([true, false])('renders a human-signed plan with organizer and controls (self=%s)', async (isSelf) => {
+ const group = withPlan(plan());
+ group.messages = group.messages.map(message => message.kind === 'plan'
+ ? { ...message, authorKind: 'user', authorBotId: null, authorName: 'Human creator', isSelf } : message);
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group });
+ renderView();
+ const card = await screen.findByTestId('bot-group-plan');
+ expect(card.closest('article')?.textContent).toContain('咪咪');
+ expect(card.closest('article')?.textContent).not.toContain('Human creator');
+ fireEvent.click(screen.getByRole('button', { name: 'bots.groupChat.plan.start' }));
+ await waitFor(() => expect(mocks.startBotGroupPlan).toHaveBeenCalledWith({ groupId: 'g1', planId: 'p1' }));
+ await waitFor(() => expect((screen.getByRole('button', { name: 'bots.groupChat.plan.dismiss' }) as HTMLButtonElement).disabled).toBe(false));
+ fireEvent.click(screen.getByRole('button', { name: 'bots.groupChat.plan.dismiss' }));
+ await waitFor(() => expect(mocks.dismissBotGroupPlan).toHaveBeenCalledWith({ groupId: 'g1', planId: 'p1' }));
+ });
+
+ it('keeps human-signed superseded plans visible and read-only', async () => {
+ const group = withPlan(plan({ status: 'superseded' }));
+ group.messages = group.messages.map(message => message.kind === 'plan' ? { ...message, authorKind: 'user', authorBotId: null } : message);
+ mocks.getBotGroup.mockResolvedValue({ ok: true, group });
+ renderView();
+ expect(await screen.findByText('bots.groupChat.plan.superseded')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'bots.groupChat.plan.start' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'bots.groupChat.plan.dismiss' })).toBeNull();
+ });
+
it('explains a failed plan action and re-reads the group', async () => {
mocks.getBotGroup.mockResolvedValue({ ok: true, group: withPlan(plan()) });
mocks.startBotGroupPlan.mockResolvedValue({ ok: false, errorCode: 'PLAN_CLOSED', message: '' });
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 7e2af7b72a..74b2c612a5 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8540,7 +8540,18 @@
"notFound": "This group chat no longer exists",
"hostNotReady": "Cindy is still getting ready. Try again in a moment.",
"planOpen": "A work split is underway. Finish or stop it before starting another.",
- "planClosed": "This plan has already ended or been updated."
+ "planClosed": "This plan has already ended or been updated.",
+ "invalidAttachment": "This attachment cannot be read. Select it again and send.",
+ "attachmentUnavailable": "Could not retrieve the attachment from your phone. Check the device connection and retry.",
+ "attachmentTooLarge": "The attachment exceeds 100 MB. Choose a smaller file.",
+ "mediaUploadFailed": "Could not upload the attachment to the chat service. Try again later.",
+ "authRequired": "Your sign-in has expired. Sign in again on your computer.",
+ "chatUnavailable": "The chat service is unavailable. Check your connection and retry.",
+ "importPending": "Group history is still syncing. Try again later.",
+ "requestTimeout": "The result is not confirmed yet. Refresh to check before retrying.",
+ "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."
},
"organizer": "Organizer",
"plan": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 9c126d836e..862507376f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8525,7 +8525,18 @@
"notFound": "このグループチャットはもう存在しません",
"hostNotReady": "Cindy の準備がまだ終わっていません。しばらくしてから再試行してください",
"planOpen": "役割分担の途中です。終わるか停止してから新しく始めてください",
- "planClosed": "この計画はすでに終了したか、更新されています"
+ "planClosed": "この計画はすでに終了したか、更新されています",
+ "invalidAttachment": "添付ファイルを読み込めません。選び直して送信してください。",
+ "attachmentUnavailable": "スマートフォンから添付ファイルを取得できません。接続を確認して再試行してください。",
+ "attachmentTooLarge": "添付ファイルが 100 MB を超えています。小さいファイルを選んでください。",
+ "mediaUploadFailed": "チャットサービスに添付ファイルをアップロードできません。しばらくしてから再試行してください。",
+ "authRequired": "ログインの有効期限が切れました。パソコンで再度ログインしてください。",
+ "chatUnavailable": "チャットサービスに接続できません。ネットワークを確認して再試行してください。",
+ "importPending": "グループの履歴を同期中です。しばらくしてから再試行してください。",
+ "requestTimeout": "操作の結果をまだ確認できません。更新して結果を確認してから再試行してください。",
+ "permissionDenied": "このグループを管理する権限がありません。",
+ "serviceError": "チャットサービスで処理を完了できません。しばらくしてから再試行してください。",
+ "groupArchived": "このグループはアーカイブ済みのため操作できません。"
},
"organizer": "まとめ役",
"plan": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 06e1b845c0..2168e25fc1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8525,7 +8525,18 @@
"notFound": "이 그룹 채팅은 더 이상 존재하지 않습니다",
"hostNotReady": "Cindy가 아직 준비 중입니다. 잠시 후 다시 시도하세요",
"planOpen": "역할 분담이 진행 중입니다. 끝내거나 중지한 뒤 새로 시작하세요",
- "planClosed": "이 계획은 이미 끝났거나 업데이트되었습니다"
+ "planClosed": "이 계획은 이미 끝났거나 업데이트되었습니다",
+ "invalidAttachment": "첨부 파일을 읽을 수 없어요. 다시 선택한 후 보내 주세요.",
+ "attachmentUnavailable": "휴대폰에서 첨부 파일을 가져오지 못했어요. 기기 연결을 확인하고 다시 시도해 주세요.",
+ "attachmentTooLarge": "첨부 파일이 100 MB를 초과해요. 더 작은 파일을 선택해 주세요.",
+ "mediaUploadFailed": "채팅 서비스에 첨부 파일을 업로드하지 못했어요. 잠시 후 다시 시도해 주세요.",
+ "authRequired": "로그인이 만료되었어요. 컴퓨터에서 다시 로그인해 주세요.",
+ "chatUnavailable": "채팅 서비스에 연결할 수 없어요. 네트워크를 확인하고 다시 시도해 주세요.",
+ "importPending": "그룹 기록을 동기화하고 있어요. 잠시 후 다시 시도해 주세요.",
+ "requestTimeout": "아직 작업 결과를 확인하지 못했어요. 새로고침하여 확인한 후 다시 시도해 주세요.",
+ "permissionDenied": "이 그룹을 관리할 권한이 없어요.",
+ "serviceError": "채팅 서비스에서 요청을 처리하지 못했어요. 잠시 후 다시 시도해 주세요.",
+ "groupArchived": "보관된 그룹에서는 이 작업을 수행할 수 없어요."
},
"organizer": "담당자",
"plan": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 97ca25c95d..b60fc503a9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8525,7 +8525,18 @@
"notFound": "这个群聊已不存在",
"hostNotReady": "Cindy 还在准备中,请稍后重试",
"planOpen": "正在分工,做完或停止后才能安排新的",
- "planClosed": "这个安排已经结束或更新了"
+ "planClosed": "这个安排已经结束或更新了",
+ "invalidAttachment": "附件无法读取,请重新选择后发送。",
+ "attachmentUnavailable": "未能从手机取回附件,请检查设备连接后重试。",
+ "attachmentTooLarge": "附件超过 100 MB,请选择较小的文件。",
+ "mediaUploadFailed": "附件未能上传到群聊服务,请稍后重试。",
+ "authRequired": "登录已失效,请在电脑上重新登录。",
+ "chatUnavailable": "群聊服务暂时无法连接,请检查网络后重试。",
+ "importPending": "群历史记录仍在同步,请稍后重试。",
+ "requestTimeout": "还未确认操作结果,请刷新查看后再重试。",
+ "permissionDenied": "你没有执行此操作的群管理权限。",
+ "serviceError": "群聊服务处理失败,请稍后重试。",
+ "groupArchived": "本群已归档,不能执行此操作。"
},
"organizer": "负责人",
"plan": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 9162c4279e..9f26dfec62 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8525,7 +8525,18 @@
"notFound": "這個群聊已不存在",
"hostNotReady": "Cindy 還在準備中,請稍後重試",
"planOpen": "正在分工,做完或停止後才能安排新的",
- "planClosed": "這個安排已經結束或更新了"
+ "planClosed": "這個安排已經結束或更新了",
+ "invalidAttachment": "附件無法讀取,請重新選擇後傳送。",
+ "attachmentUnavailable": "未能從手機取回附件,請檢查裝置連線後重試。",
+ "attachmentTooLarge": "附件超過 100 MB,請選擇較小的檔案。",
+ "mediaUploadFailed": "附件未能上傳到群聊服務,請稍後重試。",
+ "authRequired": "登入已失效,請在電腦上重新登入。",
+ "chatUnavailable": "群聊服務暫時無法連線,請檢查網路後重試。",
+ "importPending": "群歷史記錄仍在同步,請稍後重試。",
+ "requestTimeout": "還未確認操作結果,請重新整理查看後再重試。",
+ "permissionDenied": "你沒有執行此操作的群管理權限。",
+ "serviceError": "群聊服務處理失敗,請稍後重試。",
+ "groupArchived": "本群已封存,無法執行此操作。"
},
"organizer": "負責人",
"plan": {
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
index 53045fe936..33b9585959 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -375,6 +375,39 @@ describe('group timeline', () => {
expect(h.chat.act).toHaveBeenLastCalledWith('plan-edit', { planId: 'p1', position: 0, action: 'remove' });
});
+ it('renders human-signed plans as organizer cards with working actions and read-only old plans', async () => {
+ const data = group();
+ data.messages = data.messages.map(message => message.kind === 'plan'
+ ? { ...message, authorKind: 'user', authorBotId: null, authorName: 'Human creator' } : message);
+ await render(data);
+ expect(byId('botGroup.message.plan')?.textContent).toContain('咪咪');
+ expect(byId('botGroup.message.plan')?.textContent).not.toContain('Human creator');
+ await click('botGroup.plan.start');
+ expect(h.chat.act).toHaveBeenLastCalledWith('plan-start', { planId: 'p1' });
+ await click('botGroup.plan.dismiss');
+ expect(h.chat.act).toHaveBeenLastCalledWith('plan-dismiss', { planId: 'p1' });
+ data.plans[0]!.status = 'superseded';
+ data.openPlan = null;
+ await render(data);
+ expect(byId('botGroup.plan.finalNote')?.textContent).toBe('groupChat.plan.superseded');
+ expect(byId('botGroup.plan.start')).toBeNull();
+ });
+
+ it('removes a server human by actor identity without offering them as organizer', async () => {
+ const data = group({ serverBacked: true, supportsMemberRemoval: true });
+ data.members.push({ botId: 'person', actorId: 'actor-person', actorKind: 'human', name: 'Person', avatar: '', avatarColor: '', status: 'active' });
+ await render(data);
+ expect(byId('botGroup.plan.stepMenu.0.action.member:person')).toBeNull();
+ await click('botGroup.settingsButton');
+ expect(byId('botGroup.settings.memberMenu.person.action.organizer:person')).toBeNull();
+ await click('botGroup.settings.memberMenu.person.action.remove:person');
+ expect(h.chat.act).toHaveBeenLastCalledWith('remove-member', { actorId: 'actor-person' });
+ h.chat.act.mockRejectedValueOnce(new Error('PERMISSION_DENIED'));
+ await click('botGroup.settings.memberMenu.person.action.remove:person');
+ expect(node.textContent).toContain('groupChat.errors.permissionDenied');
+ expect(byId('botGroup.settings.member.person')).not.toBeNull();
+ });
+
it('keeps at least one step and names the host’s reason when an action is refused', async () => {
const data = group();
data.plans[0]!.steps = [data.plans[0]!.steps[0]!];
diff --git a/apps/mobile/src/__tests__/botGroupCopy.test.ts b/apps/mobile/src/__tests__/botGroupCopy.test.ts
new file mode 100644
index 0000000000..5b6b1ff0d7
--- /dev/null
+++ b/apps/mobile/src/__tests__/botGroupCopy.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from 'vitest';
+import { botGroupActionErrorText } from '../session/botGroupCopy';
+
+describe('group send results', () => {
+ it('does not call a transport timeout a failed send or expose raw errors', () => {
+ const t = (key: string) => key;
+ expect(botGroupActionErrorText(t, Object.assign(new Error('INVOKE_TIMEOUT'), { code: 'INVOKE_TIMEOUT' }), 'groupChat.composer.sendFailed'))
+ .toBe('groupChat.errors.requestTimeout');
+ expect(botGroupActionErrorText(t, new Error('INVALID_PARAMS: MEDIA_UPLOAD_FAILED'), 'fallback'))
+ .toBe('groupChat.errors.mediaUploadFailed');
+ expect(botGroupActionErrorText(t, new Error('private /path secret'), 'fallback')).toBe('fallback');
+ });
+});
diff --git a/apps/mobile/src/__tests__/botGroupRemote.test.ts b/apps/mobile/src/__tests__/botGroupRemote.test.ts
index 4f9de39dc2..7016c038cb 100644
--- a/apps/mobile/src/__tests__/botGroupRemote.test.ts
+++ b/apps/mobile/src/__tests__/botGroupRemote.test.ts
@@ -45,6 +45,13 @@ function chatData(overrides: Record<string, unknown> = {}) {
}
describe('parseBotGroupChatData', () => {
+ it('preserves server member identities and removal capability', () => {
+ const parsed = parseBotGroupChatData(chatData({ serverBacked: true, supportsMemberRemoval: true,
+ members: [{ botId: 'human', actorId: 'actor', actorKind: 'human', isOwned: false, name: 'Person', status: 'active' }] }));
+ expect(parsed).toMatchObject({ serverBacked: true, supportsMemberRemoval: true,
+ members: [expect.objectContaining({ actorId: 'actor', actorKind: 'human', isOwned: false })] });
+ });
+
it('preserves a server join notice through the phone projection', () => {
const joined = { id: 'joined', sequence: 20, kind: 'notice', authorKind: 'system', authorBotId: null,
authorName: 'Taylor', content: 'Taylor joined the group', noticeCode: 'member-joined',
diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.json
index 5bcf89255e..3c720377b4 100644
--- a/apps/mobile/src/i18n/locales/en/groupChat.json
+++ b/apps/mobile/src/i18n/locales/en/groupChat.json
@@ -169,7 +169,18 @@
"notFound": "This group chat no longer exists",
"hostNotReady": "Cindy is still getting ready. Try again in a moment.",
"planOpen": "A work split is underway. Finish or stop it before starting another.",
- "planClosed": "This plan has already ended or been updated."
+ "planClosed": "This plan has already ended or been updated.",
+ "invalidAttachment": "This attachment cannot be read. Select it again and send.",
+ "attachmentUnavailable": "Could not retrieve the attachment from your phone. Check the device connection and retry.",
+ "attachmentTooLarge": "The attachment exceeds 100 MB. Choose a smaller file.",
+ "mediaUploadFailed": "Could not upload the attachment to the chat service. Try again later.",
+ "authRequired": "Your sign-in has expired. Sign in again on your computer.",
+ "chatUnavailable": "The chat service is unavailable. Check your connection and retry.",
+ "importPending": "Group history is still syncing. Try again later.",
+ "requestTimeout": "The result is not confirmed yet. Refresh to check before retrying.",
+ "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."
},
"followUp": {
"next": "Plan · Next step",
diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.json
index a4f3012b40..a224030717 100644
--- a/apps/mobile/src/i18n/locales/ja/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json
@@ -169,7 +169,18 @@
"notFound": "このグループチャットはもう存在しません",
"hostNotReady": "Cindy の準備がまだ終わっていません。しばらくしてから再試行してください",
"planOpen": "役割分担の途中です。終わるか停止してから新しく始めてください",
- "planClosed": "この計画はすでに終了したか、更新されています"
+ "planClosed": "この計画はすでに終了したか、更新されています",
+ "invalidAttachment": "添付ファイルを読み込めません。選び直して送信してください。",
+ "attachmentUnavailable": "スマートフォンから添付ファイルを取得できません。接続を確認して再試行してください。",
+ "attachmentTooLarge": "添付ファイルが 100 MB を超えています。小さいファイルを選んでください。",
+ "mediaUploadFailed": "チャットサービスに添付ファイルをアップロードできません。しばらくしてから再試行してください。",
+ "authRequired": "ログインの有効期限が切れました。パソコンで再度ログインしてください。",
+ "chatUnavailable": "チャットサービスに接続できません。ネットワークを確認して再試行してください。",
+ "importPending": "グループの履歴を同期中です。しばらくしてから再試行してください。",
+ "requestTimeout": "操作の結果をまだ確認できません。更新して結果を確認してから再試行してください。",
+ "permissionDenied": "このグループを管理する権限がありません。",
+ "serviceError": "チャットサービスで処理を完了できません。しばらくしてから再試行してください。",
+ "groupArchived": "このグループはアーカイブ済みのため操作できません。"
},
"followUp": {
"next": "分担 · 次のステップ",
diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.json
index 050549a8fe..b9c4066c7d 100644
--- a/apps/mobile/src/i18n/locales/ko/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json
@@ -169,7 +169,18 @@
"notFound": "이 그룹 채팅은 더 이상 존재하지 않습니다",
"hostNotReady": "Cindy가 아직 준비 중입니다. 잠시 후 다시 시도하세요",
"planOpen": "역할 분담이 진행 중입니다. 끝내거나 중지한 뒤 새로 시작하세요",
- "planClosed": "이 계획은 이미 끝났거나 업데이트되었습니다"
+ "planClosed": "이 계획은 이미 끝났거나 업데이트되었습니다",
+ "invalidAttachment": "첨부 파일을 읽을 수 없어요. 다시 선택한 후 보내 주세요.",
+ "attachmentUnavailable": "휴대폰에서 첨부 파일을 가져오지 못했어요. 기기 연결을 확인하고 다시 시도해 주세요.",
+ "attachmentTooLarge": "첨부 파일이 100 MB를 초과해요. 더 작은 파일을 선택해 주세요.",
+ "mediaUploadFailed": "채팅 서비스에 첨부 파일을 업로드하지 못했어요. 잠시 후 다시 시도해 주세요.",
+ "authRequired": "로그인이 만료되었어요. 컴퓨터에서 다시 로그인해 주세요.",
+ "chatUnavailable": "채팅 서비스에 연결할 수 없어요. 네트워크를 확인하고 다시 시도해 주세요.",
+ "importPending": "그룹 기록을 동기화하고 있어요. 잠시 후 다시 시도해 주세요.",
+ "requestTimeout": "아직 작업 결과를 확인하지 못했어요. 새로고침하여 확인한 후 다시 시도해 주세요.",
+ "permissionDenied": "이 그룹을 관리할 권한이 없어요.",
+ "serviceError": "채팅 서비스에서 요청을 처리하지 못했어요. 잠시 후 다시 시도해 주세요.",
+ "groupArchived": "보관된 그룹에서는 이 작업을 수행할 수 없어요."
},
"followUp": {
"next": "분담 · 다음 단계",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
index 43f0642693..494501d0f8 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
@@ -169,7 +169,18 @@
"notFound": "这个群聊已不存在",
"hostNotReady": "Cindy 还在准备中,请稍后重试",
"planOpen": "正在分工,做完或停止后才能安排新的",
- "planClosed": "这个安排已经结束或更新了"
+ "planClosed": "这个安排已经结束或更新了",
+ "invalidAttachment": "附件无法读取,请重新选择后发送。",
+ "attachmentUnavailable": "未能从手机取回附件,请检查设备连接后重试。",
+ "attachmentTooLarge": "附件超过 100 MB,请选择较小的文件。",
+ "mediaUploadFailed": "附件未能上传到群聊服务,请稍后重试。",
+ "authRequired": "登录已失效,请在电脑上重新登录。",
+ "chatUnavailable": "群聊服务暂时无法连接,请检查网络后重试。",
+ "importPending": "群历史记录仍在同步,请稍后重试。",
+ "requestTimeout": "还未确认操作结果,请刷新查看后再重试。",
+ "permissionDenied": "你没有执行此操作的群管理权限。",
+ "serviceError": "群聊服务处理失败,请稍后重试。",
+ "groupArchived": "本群已归档,不能执行此操作。"
},
"followUp": {
"next": "分工 · 下一步",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
index d40d38a3ea..984b00f942 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
@@ -169,7 +169,18 @@
"notFound": "這個群聊已不存在",
"hostNotReady": "Cindy 還在準備中,請稍後重試",
"planOpen": "正在分工,做完或停止後才能安排新的",
- "planClosed": "這個安排已經結束或更新了"
+ "planClosed": "這個安排已經結束或更新了",
+ "invalidAttachment": "附件無法讀取,請重新選擇後傳送。",
+ "attachmentUnavailable": "未能從手機取回附件,請檢查裝置連線後重試。",
+ "attachmentTooLarge": "附件超過 100 MB,請選擇較小的檔案。",
+ "mediaUploadFailed": "附件未能上傳到群聊服務,請稍後重試。",
+ "authRequired": "登入已失效,請在電腦上重新登入。",
+ "chatUnavailable": "群聊服務暫時無法連線,請檢查網路後重試。",
+ "importPending": "群歷史記錄仍在同步,請稍後重試。",
+ "requestTimeout": "還未確認操作結果,請重新整理查看後再重試。",
+ "permissionDenied": "你沒有執行此操作的群管理權限。",
+ "serviceError": "群聊服務處理失敗,請稍後重試。",
+ "groupArchived": "本群已封存,無法執行此操作。"
},
"followUp": {
"next": "分工 · 下一步",
diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsx
index 8341e94dcb..c3f8aaf6dc 100644
--- a/apps/mobile/src/session/BotGroupChatScreen.tsx
+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx
@@ -445,7 +445,7 @@ function BotGroupTimelineItem({
const variant = botGroupNoticeVariant(message.noticeCode, message.planId !== null);
return <Text style={styles.notice} testID="botGroup.notice">{variant ? t(`groupChat.notice.${variant}`, { name }) : message.content}</Text>;
}
- if (message.authorKind === 'user') {
+ if (message.kind === 'message' && message.authorKind === 'user') {
// Older computers send no attachments; a message with only attachments has no bubble.
const attachments = message.attachments ?? [];
const bubble = message.content.trim().length > 0 || attachments.length === 0;
@@ -462,9 +462,13 @@ function BotGroupTimelineItem({
</View>
</View>;
}
- // Name snapshot from when it was said; the avatar follows the live profile.
- const author = identityFor(message.authorBotId ?? '', message.authorName || member?.name || '');
+ // Server plans retain the human creator as author, but the card belongs to its organizer.
const isPlanCard = message.kind === 'plan';
+ const organizer = isPlanCard ? members.find(candidate => candidate.botId === plan?.organizerBotId) : undefined;
+ const author = isPlanCard
+ ? identityFor(plan?.organizerBotId ?? '', organizer?.name || plan?.organizerName || '')
+ : identityFor(message.authorBotId ?? '', message.authorName || member?.name || '');
+ if (isPlanCard) continued = false;
return <View style={[styles.botRow, continued && styles.botRowContinued]} testID={isPlanCard ? 'botGroup.message.plan' : 'botGroup.message.bot'}>
{continued ? <View style={styles.avatarSpacer} /> : <View style={styles.avatarSlot}>
<BotGroupAvatar deviceId={deviceId} identity={author} size={BOT_GROUP_MESSAGE_AVATAR_SIZE} online={online} />
diff --git a/apps/mobile/src/session/BotGroupPlan.tsx b/apps/mobile/src/session/BotGroupPlan.tsx
index 793ec9e7ed..1e2cce002d 100644
--- a/apps/mobile/src/session/BotGroupPlan.tsx
+++ b/apps/mobile/src/session/BotGroupPlan.tsx
@@ -146,7 +146,7 @@ export function BotGroupPlanCard({
: plan.status === 'dismissed' ? 'groupChat.plan.dismissed'
: plan.status === 'stopped' ? 'groupChat.plan.stopped' : null;
const busy = pending !== null;
- const candidates = members.filter(isActiveBotGroupMember);
+ const candidates = members.filter(member => isActiveBotGroupMember(member) && (!member.actorKind || member.actorKind === 'bot'));
const steps = plan.steps.length;
const done = plan.steps.filter((step) => step.status === 'done').length;
const progress = plan.status === 'proposed' ? t('groupChat.plan.awaitingStart')
diff --git a/apps/mobile/src/session/BotGroupSettingsSheet.tsx b/apps/mobile/src/session/BotGroupSettingsSheet.tsx
index 4522b8efe5..1704806b96 100644
--- a/apps/mobile/src/session/BotGroupSettingsSheet.tsx
+++ b/apps/mobile/src/session/BotGroupSettingsSheet.tsx
@@ -148,12 +148,14 @@ export function BotGroupSettingsSheet({ visible, group, host, identityFor, onlin
{group.members.map((member) => {
const identity = identityFor(member.botId, member.name);
const active = isActiveBotGroupMember(member);
+ const canOrganize = active && (!member.actorKind || member.actorKind === 'bot');
+ const removable = canRemove && (!member.actorKind || member.actorKind === 'bot' || group.supportsMemberRemoval === true);
const organizer = member.botId === group.organizerBotId;
// G12: one row per member; a tap opens its menu (设为负责人 / 移出群聊) instead of two inline buttons.
const options = [
- ...(!organizer && active ? [{ id: `organizer:${member.botId}`, title: t('groupChat.settings.setOrganizer') }] : []),
+ ...(!organizer && canOrganize ? [{ id: `organizer:${member.botId}`, title: t('groupChat.settings.setOrganizer') }] : []),
{
- id: `remove:${member.botId}`, title: t('groupChat.settings.remove'), destructive: true, disabled: !canRemove,
+ id: `remove:${member.botId}`, title: t('groupChat.settings.remove'), destructive: true, disabled: !removable,
...(canRemove ? {} : { subtitle: t('groupChat.settings.minMembers', { min: BOT_GROUP_MIN_MEMBERS }) }),
},
];
@@ -164,7 +166,11 @@ export function BotGroupSettingsSheet({ visible, group, host, identityFor, onlin
sections={[{ id: 'member', options }]}
onSelect={(id) => {
if (id.startsWith('organizer:')) void run('organizer', 'update', { organizerBotId: member.botId }, 'groupChat.settings.organizerSaveFailed');
- else if (id.startsWith('remove:')) void setMembers(memberIds.filter((botId) => botId !== member.botId));
+ else if (id.startsWith('remove:')) {
+ if (group.supportsMemberRemoval && member.actorId)
+ void run('members', 'remove-member', { actorId: member.actorId }, 'groupChat.settings.membersSaveFailed');
+ else void setMembers(memberIds.filter((botId) => botId !== member.botId));
+ }
}}>
{(open) => <Pressable accessibilityRole="button" accessibilityLabel={t('groupChat.settings.memberActions', { name: identity.name })}
disabled={locked} onPress={open}
diff --git a/apps/mobile/src/session/botGroupCopy.ts b/apps/mobile/src/session/botGroupCopy.ts
index ad8c87f161..a4dff8c2a5 100644
--- a/apps/mobile/src/session/botGroupCopy.ts
+++ b/apps/mobile/src/session/botGroupCopy.ts
@@ -1,3 +1,4 @@
+import { formatRemoteError } from '@cindy/maker-shared/device-link-contract';
import { botGroupErrorVariant } from '@cindy/maker-shared/botGroupPresentation';
import { botGroupErrorCode } from './botGroupRemote';
@@ -8,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 {
- const variant = botGroupErrorVariant(botGroupErrorCode(error));
+ const timeout = /\bINVOKE_TIMEOUT\b/.test(formatRemoteError(error));
+ const variant = botGroupErrorVariant(timeout ? 'REQUEST_TIMEOUT' : botGroupErrorCode(error));
return t(variant ? `groupChat.errors.${variant}` : fallbackKey);
}
diff --git a/apps/mobile/src/session/botGroupRemote.ts b/apps/mobile/src/session/botGroupRemote.ts
index 31d5b5268b..28e912cbe5 100644
--- a/apps/mobile/src/session/botGroupRemote.ts
+++ b/apps/mobile/src/session/botGroupRemote.ts
@@ -145,6 +145,10 @@ function parseMember(value: unknown): BotGroupMemberView | null {
return {
botId,
name,
+ ...(id(record.actorId) ? { actorId: id(record.actorId)! } : {}),
+ ...(record.actorKind === 'human' || record.actorKind === 'bot' || record.actorKind === 'integration' ? { actorKind: record.actorKind } : {}),
+ ...(typeof record.isOwned === 'boolean' ? { isOwned: record.isOwned } : {}),
+ ...(typeof record.isSelf === 'boolean' ? { isSelf: record.isSelf } : {}),
avatar: text(record.avatar, 4_096) ?? '',
avatarColor: text(record.avatarColor, 64) ?? '',
status: enumOf(record.status, MEMBER_STATUSES) ?? 'missing',
@@ -327,6 +331,8 @@ export function parseBotGroupChatData(value: unknown): BotGroupRemoteChatData |
return {
id: groupId,
name,
+ serverBacked: record.serverBacked === true,
+ supportsMemberRemoval: record.supportsMemberRemoval === true,
replyMode: record.replyMode === 'mentioned' ? 'mentioned' : 'all',
speakingMode: record.speakingMode === 'sequential' ? 'sequential' : 'auto',
members,
@@ -358,6 +364,17 @@ export function botGroupChatDataFromResource(resource: Pick<RemoteResource, 'blo
/** Specific codes first: the transport code (INVALID_PARAMS / NOT_FOUND) wraps them. */
const ERROR_CODES: readonly BotGroupErrorCode[] = [
+ 'INVALID_ATTACHMENT',
+ 'ATTACHMENT_UNAVAILABLE',
+ 'ATTACHMENT_TOO_LARGE',
+ 'MEDIA_UPLOAD_FAILED',
+ 'AUTH_REQUIRED',
+ 'CHAT_UNAVAILABLE',
+ 'IMPORT_PENDING',
+ 'REQUEST_TIMEOUT',
+ 'PERMISSION_DENIED',
+ 'SERVICE_ERROR',
+ 'GROUP_ARCHIVED',
'MEMBER_LIMIT',
'MEMBER_UNAVAILABLE',
'PLAN_OPEN',
diff --git a/docs/dev-rules/chat-server-local-test.md b/docs/dev-rules/chat-server-local-test.md
index 3fcc36c723..9e4d5f4359 100644
--- a/docs/dev-rules/chat-server-local-test.md
+++ b/docs/dev-rules/chat-server-local-test.md
@@ -108,3 +108,25 @@ Desktop 将服务端持久消息 `origin: "system"` 中的
本次客户端回归使用离线 HTTP/WebSocket fixture、桌面与手机组件测试;不代表安装版、
线上服务或真实双账号已经验收。普通项目任务与伙伴私聊不经过本次群提示投影。
+
+## 伙伴群聊故障回归(#5604 / #5605 / #5606)
+
+以下离线回归不代替含修复构建的现场验收:
+
+| 场景 | 自动回归 | 现场预期 |
+| --- | --- | --- |
+| 服务端安排卡署名为真人 | 双端 `BotGroupChatView.test.tsx` / `BotGroupChatScreen.test.tsx` | 卡片显示负责人、步骤和开始/不用了;旧安排只读。开始后完成第一步可继续,另一张安排可取消;运行中补充及等待时返工语义不变 |
+| 群里同时有真人、本机与外来伙伴 | `botGroupRemoteResourceProvider.test.ts`、Mobile `botGroupRemote.test.ts` / `BotGroupChatScreen.test.tsx` | 添加/移出伙伴不被既有真人挡住;真人按 actor ID 单独移出;真人不进入负责人/步骤候选,外来活跃伙伴仍可分工;无管理权限失败且名单不变 |
+| 附件准备、media POST、OSS PUT、complete 或消息提交失败 | `botGroupAttachments.test.ts`、`chatServerMedia.test.ts`、`chatServer.test.ts`、`chatServerErrors.test.ts` | 双端按原因显示提示;日志包含阶段、稳定错误码、可取得的 HTTP 状态,以及同次发送关联 trace。不得记录正文、文件名/路径、token、签名 URL |
+| 发送超过 15 秒,回执丢失后重试 | `chatServer.test.ts`、device-link `invokePolicy.test.ts`、Mobile `botGroupCopy.test.ts`,保留现有 composer 重试用例 | 群发送单独等待最多 180 秒;超时提示结果未确认,刷新确认后再重试;同一内容沿用 clientId,当前主机进程内在途/已成功请求复用回执,不重复消耗手机上传或提交消息 |
+
+现场使用无敏感内容的小 JPEG,分别验证电脑选图、手机 peer/OSS 引用、纯文字消息;
+记录 Desktop/Mobile 的版本与 sourceCommit、发生时间、群 ID、发送 trace 及服务器消息 ID。
+`Chat group send confirmed` 是主机收到提交回执,不能据它推断手机已经收到了回包。
+失败时按阶段关联服务器的认证、media prepare、OSS 签名/上传、complete 和消息提交记录;
+接口 `/ready` 正常或未认证 `/me` 返回 401 都不能证明对象存储已配置或附件链路正常。
+老群升级另看下一次重试的错误码及对应请求/上传阶段,保留源历史与导入水位,不以新发图成功代替历史完整性验收。
+
+回执缓存只在当前账号的主机进程内保留最近 128 次成功发送,进程重启/换账号后仍依赖服务器的
+operationId 幂等合同,不宣称具备跨重启持久发件箱。检查 Windows + Android 原现场和 iOS
+同源界面,分别记录 Light/Dark 是否目检;没有实际执行的项保持待验收。
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index fe241be04e..b6f1760284 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -995,3 +995,19 @@ Mobile 据此区分已关闭与已删除的旧选择:保留任务或草稿原
这是执行主机的投影修复,旧 Mobile 和远控 Desktop 无需新增能力协商即可接收。
不增加分页、客户端重组或重试,不提高传输大小上限;本机 Desktop 设置仍读取完整目录。
“关闭后必须重选”的提示与发送前检查随 Mobile 更新;旧版控制端仍沿用各自既有选择处理。
+
+### 伙伴群聊成员操作与发送错误(#5604–#5606)
+
+`bot-group-chat` 数据追加可选 `supportsMemberRemoval`;仅为 true 时手机调用
+`remove-member({ actorId })`,主机复用现有 Chat Server 单成员 remove 与管理权限校验。
+成员投影中的 actorId/actorKind 在手机保留,真人不作为分工负责人/步骤候选;缺字段的
+旧本地伙伴保持原行为。旧手机继续用 `set-members`,新主机只校验其中新增的本机伙伴,
+不丢弃既有真人/外来伙伴 ID。新版手机连旧主机时不调用新动作,伙伴管理沿用旧入口;
+真人移出需升级主机,不能用整份伙伴名单差分假报成功。
+
+群错误仍以稳定码作为 Remote Resource 错误 message,新增附件、鉴权、群服务不可达、
+历史迁移、权限、归档及结果未确认等分类;新版双端本地化,旧端遇到未知码保留原通用失败提示。
+不透传服务器正文或异常文本。仅群 send 的 invoke 预算增加到 180 秒,不改变其他动作、
+共享连接、自动重试或授权。超时不能证明操作未执行,重试沿用 clientId;当前账号主机进程
+合并相同在途请求并缓存最近成功回执,服务器 operationId 仍是最终幂等依据。
+不新增 IPC channel、数据库迁移或 Mobile 原生指纹输入。
diff --git a/packages/device-link/src/__tests__/invokePolicy.test.ts b/packages/device-link/src/__tests__/invokePolicy.test.ts
index 7905dcbe44..828dc869db 100644
--- a/packages/device-link/src/__tests__/invokePolicy.test.ts
+++ b/packages/device-link/src/__tests__/invokePolicy.test.ts
@@ -8,6 +8,15 @@ import {
} from '../index.js';
describe('remote invoke policy boundaries', () => {
+ it.each(['desktop', 'mobile'] as const)('waits for group sends only on %s without replaying writes', (platform) => {
+ const channel = 'maker:remote-resources:invoke';
+ expect(resolveRemoteInvokeTimeoutMs(channel, [{ collectionId: 'bot-groups', actionId: 'send' }], platform)).toBe(180_000);
+ expect(resolveRemoteInvokeTimeoutMs(channel, [{ collectionId: 'bot-groups', actionId: 'update' }], platform)).not.toBe(180_000);
+ expect(resolveRemoteInvokeTimeoutMs(channel, [{ collectionId: 'teammates', actionId: 'send' }], platform)).not.toBe(180_000);
+ expect(isPeerResetRetryableReadChannel(channel)).toBe(false);
+ expect(isCompletedInvokeRetryableReadChannel(channel)).toBe(false);
+ });
+
it('gives predictions the host budget on both controllers without automatic link retries', () => {
expect(resolveRemoteInvokeTimeoutMs('maker:predict-prompt', [], 'mobile')).toBe(45_000);
expect(resolveRemoteInvokeTimeoutMs('maker:predict-prompt', [], 'desktop')).toBe(45_000);
diff --git a/packages/device-link/src/invokePolicy.ts b/packages/device-link/src/invokePolicy.ts
index 70a1fbc0f9..843f471cf6 100644
--- a/packages/device-link/src/invokePolicy.ts
+++ b/packages/device-link/src/invokePolicy.ts
@@ -111,12 +111,15 @@ export const MOBILE_INVOKE_TIMEOUT_OVERRIDES_MS: Record<string, number> = {
export const MOBILE_SCHEDULE_CHANNEL_TIMEOUT_MS = 40_000;
+export const BOT_GROUP_SEND_TIMEOUT_MS = 180_000;
+
/**
* Every action-specific desktop budget `resolveRemoteInvokeTimeoutMs` can return beyond
* INVOKE_TIMEOUT_OVERRIDES_MS. Hosts size their global orphan/outbox ceilings from both,
* so a host never gives up before the controller stops waiting.
*/
export const ACTION_INVOKE_TIMEOUTS_MS: readonly number[] = [
+ BOT_GROUP_SEND_TIMEOUT_MS,
TASK_MIGRATION_ESTIMATE_TIMEOUT_MS,
TASK_MIGRATION_RECEIVE_TIMEOUT_MS,
];
@@ -126,6 +129,11 @@ export function resolveRemoteInvokeTimeoutMs(
args?: unknown[],
platform: 'desktop' | 'mobile' = 'desktop',
): number | undefined {
+ // Group sends can materialize phone attachments, upload media and then submit the message.
+ // Only this action gets the larger window; a timeout still means an unconfirmed result.
+ const groupRequest = args?.[0] as { collectionId?: unknown; actionId?: unknown } | undefined;
+ if (channel === 'maker:remote-resources:invoke' && groupRequest?.collectionId === 'bot-groups' && groupRequest.actionId === 'send')
+ return BOT_GROUP_SEND_TIMEOUT_MS;
if (channel === TASK_MIGRATION_CHANNEL) {
const request = args?.[0];
const action = request && typeof request === 'object' && 'action' in request ? request.action : undefined;
diff --git a/packages/maker-shared/src/botGroupChat.ts b/packages/maker-shared/src/botGroupChat.ts
index 82720ebfbb..043e71d607 100644
--- a/packages/maker-shared/src/botGroupChat.ts
+++ b/packages/maker-shared/src/botGroupChat.ts
@@ -245,6 +245,17 @@ export interface BotGroupDetail extends BotGroupSummary {
}
export type BotGroupErrorCode =
+ | 'INVALID_ATTACHMENT'
+ | 'ATTACHMENT_UNAVAILABLE'
+ | 'ATTACHMENT_TOO_LARGE'
+ | 'MEDIA_UPLOAD_FAILED'
+ | 'AUTH_REQUIRED'
+ | 'CHAT_UNAVAILABLE'
+ | 'IMPORT_PENDING'
+ | 'REQUEST_TIMEOUT'
+ | 'PERMISSION_DENIED'
+ | 'SERVICE_ERROR'
+ | 'GROUP_ARCHIVED'
| 'INVALID_PARAMS'
| 'NOT_FOUND'
| 'MEMBER_LIMIT'
@@ -357,7 +368,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 }), `delete`, `plan-start` / `plan-dismiss` / `plan-continue` /
+ * `set-members` ({ botIds }), `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.
*/
@@ -368,6 +379,7 @@ export type BotGroupRemoteActionId =
| 'stop'
| 'update'
| 'set-members'
+ | 'remove-member'
| 'delete'
| 'plan-start'
| 'plan-dismiss'
@@ -386,6 +398,8 @@ export interface BotGroupRemoteChatData extends BotGroupDetail {
* drop them). Attachment `path`s are always null here.
*/
supportsAttachments?: boolean;
+ /** Host supports removing one server actor, including a human. */
+ supportsMemberRemoval?: boolean;
}
export const BOT_GROUP_CLIENT_ID_PREFIX = 'bot-group:';
diff --git a/packages/maker-shared/src/botGroupPresentation.ts b/packages/maker-shared/src/botGroupPresentation.ts
index 9e57724fbe..350158b3ec 100644
--- a/packages/maker-shared/src/botGroupPresentation.ts
+++ b/packages/maker-shared/src/botGroupPresentation.ts
@@ -73,6 +73,17 @@ export function mergeBotGroupMessages(
/** Copy variant for a refused group action; null keeps the caller's own fallback. */
export type BotGroupErrorVariant =
+ | 'invalidAttachment'
+ | 'attachmentUnavailable'
+ | 'attachmentTooLarge'
+ | 'mediaUploadFailed'
+ | 'authRequired'
+ | 'chatUnavailable'
+ | 'importPending'
+ | 'requestTimeout'
+ | 'permissionDenied'
+ | 'serviceError'
+ | 'groupArchived'
| 'memberLimit'
| 'memberUnavailable'
| 'notFound'
@@ -81,6 +92,17 @@ export type BotGroupErrorVariant =
| 'planClosed';
const ERROR_VARIANTS: ReadonlyMap<string, BotGroupErrorVariant> = new Map<BotGroupErrorCode, BotGroupErrorVariant>([
+ ['INVALID_ATTACHMENT', 'invalidAttachment'],
+ ['ATTACHMENT_UNAVAILABLE', 'attachmentUnavailable'],
+ ['ATTACHMENT_TOO_LARGE', 'attachmentTooLarge'],
+ ['MEDIA_UPLOAD_FAILED', 'mediaUploadFailed'],
+ ['AUTH_REQUIRED', 'authRequired'],
+ ['CHAT_UNAVAILABLE', 'chatUnavailable'],
+ ['IMPORT_PENDING', 'importPending'],
+ ['REQUEST_TIMEOUT', 'requestTimeout'],
+ ['PERMISSION_DENIED', 'permissionDenied'],
+ ['SERVICE_ERROR', 'serviceError'],
+ ['GROUP_ARCHIVED', 'groupArchived'],
['MEMBER_LIMIT', 'memberLimit'],
['MEMBER_UNAVAILABLE', 'memberUnavailable'],
['NOT_FOUND', 'notFound'],