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): coordinate server planning and attachment delivery

Chris689ba044a819
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 504c8316fd..2d4676bd01 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerMedia.test.ts
@@ -58,4 +58,14 @@ describe('chat private media', () => {
await expect(media.download('room', 'media')).rejects.toThrow('CONVERSATION_NOT_FOUND');
expect(api).toHaveBeenCalledTimes(2);
});
+ it('permits exact loopback media only for the explicitly isolated adapter', async () => {
+ f.read.mockResolvedValue({ buffer: Buffer.from('png') });f.fetch.mockResolvedValue(new Response('', { status: 200 }));
+ let uploadUrl = 'http://127.0.0.1:3018/dev-media/fixture';
+ const api = vi.fn(async () => ({ id: 'media', uploadUrl })) as unknown as ChatApi;
+ await expect(createChatMedia(api, () => true).upload('room','op',[attachment],'actor')).rejects.toThrow('INVALID_MEDIA_URL');
+ await expect(createChatMedia(api, () => true, undefined, { allowLoopback: true }).upload('room','op',[attachment],'actor')).resolves.toHaveLength(1);
+ uploadUrl = 'http://127.0.0.1:3019/private';
+ await expect(createChatMedia(api, () => true, undefined, { allowLoopback: true }).upload('room','op',[attachment],'actor')).rejects.toThrow('INVALID_MEDIA_URL');
+ });
+
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts
index 4a4a111af8..55197cfbd8 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerParity.test.ts
@@ -181,4 +181,56 @@ describe('server group feature parity', () => {
expect(input.message).toContain('file-0');
expect(input.attachments![0].id).toBe(messages[0].content[0].mediaId);
});
+ it('negotiates broadcast and cancels the server deferred source on stop', async () => {
+ arrange();
+ const base = fixture.handle.getMockImplementation()!;
+ fixture.handle.mockImplementation((route, ...args) => route === '/me' ? { body: { actor: { id: selfId }, capabilities: { groupDiscussionParity: 1 } } } : base(route, ...args));
+ let finish!: (value: unknown) => void;
+ deps.decidePlan = vi.fn(() => new Promise(resolve => { finish = resolve; })) as typeof deps.decidePlan;
+ await send({ mentions: { all: true, botIds: [] } }); await flush();
+ expect(fixture.handle.mock.calls.find(([route, method]) => route.endsWith('/messages') && method === 'POST')?.[2].mentionsAll).toBe(true);
+ await service.stopRound(roomId);
+ expect(fixture.handle.mock.calls.some(([route]) => route.endsWith('/cancel-planning'))).toBe(true);
+ finish({ needsPlan: true, steps }); await flush();expect(planPosts()).toHaveLength(0);
+ });
+ it('reports forced planning failure without silently starting ordinary discussion', async () => {
+ arrange();
+ const base = fixture.handle.getMockImplementation()!;
+ fixture.handle.mockImplementation((route, ...args) => route === '/me' ? { body: { actor: { id: selfId }, capabilities: { groupDiscussionParity: 1 } } } : base(route, ...args));
+ deps.decidePlan = vi.fn(async () => null);
+ await send({ division: true });await flush();
+ expect(fixture.handle.mock.calls.find(([route]) => route.endsWith('/cancel-planning'))?.[2].failed).toBe(true);
+ expect(fixture.handle.mock.calls.some(([route]) => route.endsWith('/continue'))).toBe(false);
+ });
+ it('keeps legacy servers without a watermark on the bounded text page', async () => {
+ arrange();fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];
+ const base = fixture.handle.getMockImplementation()!;
+ fixture.handle.mockImplementation((route, ...args) => route.includes('/messages?') ? { body: Array.from({ length: 100 }, (_, n) => ({
+ id: `message-${n}`, seq: String(100-n), authorId: selfId, author: { kind: 'human', name: 'Me' }, deleted: false, content: [{ type: 'text', text: 'history' }],
+ })) } : base(route, ...args));
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(deps.dispatch).toHaveBeenCalledOnce();
+ expect(fixture.handle.mock.calls.filter(([route]) => route.includes('/messages?'))).toHaveLength(1);
+ });
+ it('paginates unseen attachments before the text window and skips delivered files', async () => {
+ arrange();fixture.profiles = [{ id: 'local-bot', displayName: 'Bot', avatar: null, status: 'active' }];
+ const base = fixture.handle.getMockImplementation()!;
+ const message = (seq: number, media = false) => ({ id: `message-${seq}`, seq: String(seq), authorId: selfId, author: { kind: 'human', name: 'Me' }, deleted: false,
+ content: media ? [{ type: 'media', mediaId: `60000000-0000-4000-8000-${String(seq).padStart(12,'0')}` }] : [{ type: 'text', text: 'text' }] });
+ fixture.handle.mockImplementation((route, ...args) => {
+ if (route === '/executions/claim' && !claimed) { claimed = true; return { body: { execution: { ...execution, context_seq: '350', attachment_after_seq: '100' } } }; }
+ if (route.includes('/messages?')) {
+ if (route.endsWith('before=351')) return { body: Array.from({ length: 100 }, (_, n) => message(350-n)) };
+ if (route.endsWith('before=251')) return { body: Array.from({ length: 100 }, (_, n) => message(250-n,n===99)) };
+ return { body: [message(150,true),message(100,true)] };
+ }
+ return base(route, ...args);
+ });
+ fixture.download.mockImplementation(async (_room, id) => ({ id, name: id, category: 'file', path: '/test/file', url: null }));
+ await vi.advanceTimersByTimeAsync(2000);
+ const input = vi.mocked(deps.dispatch).mock.calls[0][0];
+ expect(input.attachments?.map(a => a.id)).toEqual([151,150].map(n => `60000000-0000-4000-8000-${String(n).padStart(12,'0')}`));
+ expect(fixture.urls.some(url => url.endsWith('before=151'))).toBe(true);
+ });
+
});
diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.ts
index 9bf0f1b8a9..5bb776cf96 100644
--- a/apps/desktop/src/main/maker-ipc/chatServer.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts
@@ -47,7 +47,7 @@ interface Snapshot { room: Room; members: Member[]; messages: Message[]; cursor:
interface Execution {
id: string; conversation_id: string; source_message_id: string; bot_id: string;
plan_id?: string | null; plan_step?: number | null;
- context_seq: string; epoch: number; status: string; access_mode: 'owner' | 'chat' | 'tools'; access_revision: number;
+ context_seq: string; attachment_after_seq?: string; epoch: number; status: string; access_mode: 'owner' | 'chat' | 'tools'; access_revision: number;
}
interface ServerPlan {
id: string; revision: number; source_message_id: string; request_text: string; organizer_id: string; creator_id: string;
@@ -129,14 +129,29 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const planning = new Map<string, { botId: string; controller: AbortController }>();
// Invalidate even a send still preparing/uploading its attachments. Its delayed
// receipt must not start an arrangement after a newer message or control action.
- const planIntents = new Map<string, object>();
- function replacePlanIntent(roomId: string) {
+ type PlanIntent = { sourceId?: string };
+ const planIntents = new Map<string, PlanIntent>();
+ let groupDiscussionParity = false;
+ const pendingPlanCancels = new Map<string, Map<string, boolean>>();
+ async function cancelPlanning(roomId: string, sourceId: string, failed = false) {
+ if (!groupDiscussionParity) return;
+ let pending = pendingPlanCancels.get(roomId);
+ if (!pending) { pending = new Map(); pendingPlanCancels.set(roomId, pending); }
+ pending.set(sourceId, failed);
+ await api(`/conversations/${roomId}/messages/${sourceId}/cancel-planning`, 'POST', { operationId: `cancel-plan:${sourceId}:${failed}`, failed });
+ pending.delete(sourceId);
+ if (!pending.size) pendingPlanCancels.delete(roomId);
+ }
+ async function replacePlanIntent(roomId: string) {
const pending = planning.get(roomId);
pending?.controller.abort();
planning.delete(roomId);
if (pending) changed(roomId);
- const intent = {};
+ const previous = planIntents.get(roomId);
+ const intent: PlanIntent = {};
planIntents.set(roomId, intent);
+ if (previous?.sourceId) await cancelPlanning(roomId, previous.sourceId);
+ for (const [sourceId, failed] of pendingPlanCancels.get(roomId) ?? []) await cancelPlanning(roomId, sourceId, failed);
return intent;
}
let registeredAt = 0;
@@ -206,7 +221,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
throw error;
});
}
- const media = createChatMedia(api, current, deps.log);
+ const media = createChatMedia(api, current, deps.log, { allowLoopback: !app.isPackaged && process.env.XDT_ISOLATED === '1' && config.baseUrl === 'http://127.0.0.1:3018' });
let upgrade: Promise<Map<string, string>> | undefined;
let upgradeRetryAt = 0;
const upgradeErrors = new Map<string, string>();
@@ -308,7 +323,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if (Date.now() - registeredAt < 5000) return;
refreshActors = (async () => {
profiles = await getDbClient().drizzle.select().from(botProfiles).where(undefined);
- const me = await api<{ actor: Actor }>('/me'); selfId = me.actor.id;
+ const me = await api<{ actor: Actor; capabilities?: { groupDiscussionParity?: number } }>('/me'); selfId = me.actor.id;
+ groupDiscussionParity = me.capabilities?.groupDiscussionParity === 1;
// Refresh from the issuing auth server, never overwrite with a stale device cache.
if (Date.now() - profileRefreshedAt > 60000) {
await api('/profile/refresh', 'POST').then(() => { profileRefreshedAt = Date.now(); }).catch(() => undefined);
@@ -423,6 +439,14 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
threadRootId: m.threadRootId, replyCount: 0, reactions: [], mentions: { all: false, botIds: [] },
noticeCode: joined ? 'member-joined' : null, planId: null, files: [], attachments: [], createdAt: Date.parse(m.createdAt) };
}
+ const notice = m.origin === 'integration' && !m.deleted ? m.content.find(b => b.namespace === 'cindy.group-notice' && b.schemaRevision === 1) : undefined;
+ const noticeCode = notice?.data?.noticeCode;
+ if (noticeCode === 'member-failed' || noticeCode === 'member-timeout' || noticeCode === 'plan-failed') return {
+ id: m.id, sequence: Number(m.seq), kind: 'notice', authorKind: 'system', isSelf: false,
+ authorBotId: localBot(m.authorId)?.id ?? null, authorName: members.find(member => member.id === m.authorId)?.name ?? '',
+ content: bodyText(m), threadRootId: m.threadRootId, replyCount: 0, reactions: [], mentions: { all: false, botIds: [] },
+ noticeCode, planId: null, files: [], attachments: [], createdAt: Date.parse(m.createdAt),
+ };
const member = members.find(member => member.id === m.authorId);
const planCard = m.content.find(b => b.namespace === 'cindy.plan');
const legacy = m.origin === 'import' ? m.content.find(b => b.namespace === 'cindy.local-history')?.data : undefined;
@@ -490,7 +514,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
? Math.max(latest, Date.parse(m.createdAt)) : latest, 0),
createdAt: Date.parse(s.room.created_at), updatedAt: Date.parse(s.room.updated_at ?? s.room.created_at),
messages, hasMoreBefore: page.length === (o.limit ?? 100), plans,
- round: { status: executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers, canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id) || s.messages.some(m => !m.deleted && m.origin !== 'system' && m.author.kind === 'human' && !m.content.some(b => b.namespace === 'cindy.plan'))) && !executions.some(e => ['queued','running','stopping','needs_input'].includes(e.status)) } };
+ round: { status: executions.some(e => ['queued', 'running'].includes(e.status)) ? 'running' : 'idle', speakers, canContinue: !open && !planning.has(roomId) && (executions.some(e => !e.plan_id) || s.messages.some(m => !m.deleted && m.origin !== 'system' && m.author.kind === 'human' && !m.content.some(b => b.namespace === 'cindy.plan'))) && !executions.some(e => ['queued','running','stopping'].includes(e.status)) } };
}
function planView(plan: ServerPlan, members: Member[], workspace: ReturnType<ReturnType<typeof chatServerWorkspaces>['read']>): BotGroupPlanView {
return { id: plan.id, status: plan.status, organizerBotId: localBot(plan.organizer_id)?.id ?? plan.organizer_id,
@@ -503,7 +527,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const i = z.object({ groupId: id, planId: id, position: z.number().int().min(0).max(11).optional(),
action: z.enum(['remove','reassign']).optional(), botId: z.string().optional() }).parse(input);
const room = await resolveGroup(i.groupId);
- replacePlanIntent(room);
+ await replacePlanIntent(room);
const plans = await api<ServerPlan[]>(`/conversations/${room}/plans?ids=${i.planId}`);
const plan = plans.find(p => p.id === i.planId); if (!plan) throw new Error('PLAN_CLOSED');
const botId = i.botId ? actors.find(a => a.externalId === i.botId)?.id ?? id.parse(i.botId) : undefined;
@@ -511,7 +535,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
action: i.action ?? action, position: i.position, botId });
changed(room); return { ok: true as const };
}
- async function decideArrangement(s: Snapshot, sourceId: string, text: string, forced: boolean, attachments: BotGroupAttachment[], intent: object) {
+ async function decideArrangement(s: Snapshot, sourceId: string, text: string, forced: boolean, attachments: BotGroupAttachment[], intent: PlanIntent) {
if (!current() || planIntents.get(s.room.id) !== intent) return;
const members = s.members.filter(m => m.kind === 'bot' && m.state === 'joined' && (!localBot(m.id) || localBot(m.id)?.status === 'active') && (m.ownerActorId === selfId || m.guestAccess !== 'none'));
const organizer = members.find(m => m.id === s.room.organizer_id) ?? members[0];
@@ -520,10 +544,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
const controller = new AbortController();
const pending = { botId: localBot(organizer.id)?.id ?? organizer.id, controller };
planning.set(s.room.id, pending); changed(s.room.id);
+ let explicit = forced;
try {
const plans = await api<ServerPlan[]>(`/conversations/${s.room.id}/plans`);
if (!current() || controller.signal.aborted) return;
const proposed = plans.find(p => p.status === 'proposed' && p.creator_id === selfId);
+ explicit ||= !!proposed;
const decision = await deps.decidePlan({ mode: proposed ? 'revise' : forced ? 'forced' : 'auto', groupName: s.room.name,
organizerName: organizer.name, members: members.map(m => ({ botId: m.id, name: m.name, description: localBot(m.id)?.description ?? '' })),
recent: s.messages.slice(0, 12).reverse().map(m => ({ from: m.author.name, text: bodyText(m) })), request: text,
@@ -531,14 +557,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
if (!current() || controller.signal.aborted || planIntents.get(s.room.id) !== intent) return;
if (decision?.needsPlan) await api(`/conversations/${s.room.id}/plans`, 'POST', {
operationId: `plan:${sourceId}`, sourceMessageId: sourceId, organizerId: organizer.id, request: text, steps: decision.steps });
- else await api(`/conversations/${s.room.id}/messages/${sourceId}/continue`, 'POST', { operationId: `discuss:${sourceId}` });
+ else if (explicit) await cancelPlanning(s.room.id, sourceId, true);
+ else await api(`/conversations/${s.room.id}/messages/${sourceId}/continue`, 'POST', { operationId: `discuss:${sourceId}`, ...(groupDiscussionParity ? { automatic: true } : {}) });
} catch (error) {
if (current() && !controller.signal.aborted) {
// An organizer failure must not swallow the user's posted request.
- await api(`/conversations/${s.room.id}/messages/${sourceId}/continue`, 'POST', { operationId: `discuss:${sourceId}` });
+ if (explicit) await cancelPlanning(s.room.id, sourceId, true);
+ else await api(`/conversations/${s.room.id}/messages/${sourceId}/continue`, 'POST', { operationId: `discuss:${sourceId}`, ...(groupDiscussionParity ? { automatic: true } : {}) });
deps.log?.warn('Group arrangement could not be prepared', { groupId: s.room.id });
}
- } finally { if (planning.get(s.room.id) === pending) { planning.delete(s.room.id); changed(s.room.id); } }
+ } finally { delete intent.sourceId; if (planning.get(s.room.id) === pending) { planning.delete(s.room.id); changed(s.room.id); } }
}
async function updateExecution(run: Running, action: string, extra: Record<string, unknown> = {}) {
return api(`/conversations/${run.execution.conversation_id}/executions/${run.execution.id}`, 'POST', {
@@ -653,14 +681,26 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
await updateExecution(run, 'heartbeat');
if (!current()) throw new Error('OWNER_CHANGED');
const history = await api<Message[]>(`/conversations/${s.room.id}/messages?all=true&limit=100&before=${BigInt(execution.context_seq) + 1n}`);
+ let page = [...history];
if (run.plan) for (const messageId of new Set([run.plan.source_message_id, ...run.plan.steps.flatMap(step => step.resultMessageId ? [step.resultMessageId] : []), ...(run.plan.note_message_ids ?? [])])) {
if (!history.some(message => message.id === messageId)) history.push(await api<Message>(`/conversations/${s.room.id}/messages/${id.parse(messageId)}`));
}
+ // Text stays bounded, but unseen attachments may precede the latest text page.
+ // The server watermark is scoped to this bot/grant/plan step and advances only on success.
+ const attachmentHistory = [...history];
+ const after = BigInt(execution.attachment_after_seq ?? '0');
+ while (execution.attachment_after_seq !== undefined && page.length === 100) {
+ const before = page.reduce((min, m) => BigInt(m.seq) < min ? BigInt(m.seq) : min, BigInt(execution.context_seq) + 1n);
+ if (before <= after + 1n) break;
+ page = await api<Message[]>(`/conversations/${s.room.id}/messages?all=true&limit=100&before=${before}`);
+ attachmentHistory.push(...page);
+ }
const attachments: BotGroupAttachment[] = [];
const missingAttachments: string[] = [];
// Attach a bounded newest set, and retain the names of older files in context.
const seenMedia = new Set<string>();
- for (const message of [...history].sort((a, b) => Number(b.seq) - Number(a.seq))) for (const block of message.content) {
+ for (const message of attachmentHistory.sort((a, b) => BigInt(a.seq) < BigInt(b.seq) ? 1 : -1)) for (const block of message.content) {
+ if (BigInt(message.seq) <= after) continue;
if (message.deleted || block.type !== 'media' || !block.mediaId || seenMedia.has(block.mediaId)) continue;
seenMedia.add(block.mediaId);
if (attachments.length >= 40) { missingAttachments.push(block.caption ?? block.mediaId); continue; }
@@ -830,7 +870,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
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 intent = replacePlanIntent(i.groupId);
+ const intent = await replacePlanIntent(i.groupId);
const s = await snapshot(i.groupId);
const plans = await api<ServerPlan[]>(`/conversations/${i.groupId}/plans`);
const openPlan = plans.find(p => ['proposed','running','waiting'].includes(p.status));
@@ -850,14 +890,20 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
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,
+ ...await media.upload(i.groupId, i.clientId, prepared?.ok ? prepared.attachments : [], selfId) ], mentions, deferExecution: shouldPlan, ...(groupDiscussionParity ? { mentionsAll: i.mentions.all, planningMode: i.division || proposed ? 'explicit' : 'auto' } : {}),
});
} 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 : [], intent).catch(() => undefined);
+ if (shouldPlan) {
+ if (planIntents.get(i.groupId) !== intent) await cancelPlanning(i.groupId, result.id);
+ else {
+ intent.sourceId = result.id;
+ void decideArrangement(s, result.id, i.text, i.division === true, prepared?.ok ? prepared.attachments : [], intent).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 };
@@ -922,7 +968,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD
}),
stopRound: roomId => safe(async () => {
const room = await resolveGroup(id.parse(roomId));
- replacePlanIntent(room);
+ await replacePlanIntent(room);
const plans = await api<ServerPlan[]>(`/conversations/${room}/plans`);
for (const plan of plans.filter(p => ['proposed','running','waiting'].includes(p.status))) await actPlan({ groupId: room, planId: plan.id }, 'stop');
const executions = await api<Execution[]>(`/conversations/${room}/executions`);
diff --git a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
index 28e0132575..d287523651 100644
--- a/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
+++ b/apps/desktop/src/main/maker-ipc/chatServerMedia.ts
@@ -13,12 +13,12 @@ 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, log?: { warn(message: string, meta?: Record<string, unknown>): void }) {
+export function createChatMedia(api: ChatApi, current: () => boolean, log?: { warn(message: string, meta?: Record<string, unknown>): void }, options: { allowLoopback?: boolean } = {}) {
const cache = new Map<string, Promise<BotGroupAttachment>>();
const check = () => { if (!current()) throw new Error('OWNER_CHANGED'); };
const signedUrl = (value: string) => {
const url = new URL(value);
- if (url.protocol !== 'https:' || url.username || url.password) throw new Error('INVALID_MEDIA_URL');
+ if ((url.protocol !== 'https:' && !(options.allowLoopback && url.origin === 'http://127.0.0.1:3018')) || url.username || url.password) throw new Error('INVALID_MEDIA_URL');
return url.href;
};
return {
diff --git a/docs/dev-rules/chat-server-feature-parity.md b/docs/dev-rules/chat-server-feature-parity.md
index 31e5f94626..738ddec112 100644
--- a/docs/dev-rules/chat-server-feature-parity.md
+++ b/docs/dev-rules/chat-server-feature-parity.md
@@ -1,7 +1,7 @@
# 伙伴本地群迁到 Chat Server:功能对照
-核对日期:2026-10-08。客户端基线 `90b66756b`;服务端代码基线
-`xindong/cindy-server@8a61a72c`。这是代码与离线回归结论,不代表线上部署或安装包验收。
+核对日期:2026-10-08。客户端基线 `52ed7876` + #5613;服务端代码基线
+`xindong/cindy-server@8a61a72c`。本文区分实现、离线回归和隔离 DEV 实测;不代表线上部署或发布安装包已验收。
原有行为以 [伙伴群聊](../product-rules/bot-group-chat.md) 为准;普通伙伴私聊仍走
[伙伴运行时](../product-rules/cindy-bots-runtime.md),不是服务器群时间线。
@@ -11,42 +11,41 @@
| --- | --- |
| 伙伴身份、长期私聊、记忆、Skill、模型候选与权限 | 原主任务保留;群内使用独立授权专线。非主人默认仅交流是多人群的权限设计,不应恢复成读取主人私有资料。群内工具授权及主人私聊由 #5587 处理 |
| 建群、名称、成员、负责人、回复方式、发言方式 | `chatServer.createGroup/updateGroup/setMembers` 已接服务器接口;混合真人/伙伴管理与手机入口由 #5613 处理;#5607 也涉及手机新增成员校验,合并时避免重复覆盖 |
-| 用户发言、@伙伴、@所有人、复制、分享、回复、表情 | 发送与 Thread 已有接线;@所有人在线上协议被展开成所有 Bot ID,和用户逐个点名无法区分,见下方服务端遗漏 |
+| 用户发言、@伙伴、@所有人、复制、分享、回复、表情 | 发送与 Thread 已有接线;本次配套用可选 mentionsAll 保留全体语义,兼容旧 mentions 列表 |
| 自动判断分工、手动分工、修改待开始安排 | 本次恢复 @所有人的自动判断;按原规则由辅助模型判定单一可用成员是否需要分工;待开始安排优先走 revise,避免手动分工覆盖修改语义。别人的提议不触发新安排 |
| 修改安排时仍可单独 @伙伴讨论 | 本次保留。已有提议时 @所有人也是讨论,不当作修改意见 |
-| 判断过程中插话、停止、点击开始/不用了/编辑 | 本次用同群意图代次取消旧判断,包含消息上传/提交回执迟到的情况;取消即撤掉本机判断状态,旧模型结果不能另建卡。服务端的延迟讨论兜底另见下方 |
+| 判断过程中插话、停止、点击开始/不用了/编辑 | 本次用同群意图代次取消旧判断,包含消息上传/提交回执迟到的情况;取消即撤掉本机判断状态,旧模型结果不能另建卡。同时取消服务端延迟兜底,并拒绝迟到安排 |
| 安排卡、开始/不用了、继续/重试/结束 | 操作接口已有;真人署名的服务端卡被当作普通本人消息而丢失操作入口,由 #5613 修复双端渲染 |
| 分工期间补充、等待时返工 | 客户端发往 plans/:id/messages;服务端 comment 与完成逻辑已接入,保留本轮内容并对同一步继续执行 |
-| 分工未做/失败步骤换人 | 客户端已有入口,服务端仍拒绝 waiting 状态,见下方 |
+| 分工未做/失败步骤换人 | 本次服务端恢复 waiting 时更换 pending/failed 步骤;已完成步骤仍不能换人 |
| 项目目录、Git worktree、逐步交接文件 | 现有 workDir.prepare、grant 隔离目录、changedFiles 和媒体上传接线保留;远端执行者各有本机工作目录,通过附件交接,不把一台电脑路径当另一台电脑路径 |
-| 图片、文件、视频输入 | 上传、下载、历史迁移已有;#5613 处理类型/错误诊断、手机等待预算与发送回执复用。真实对象存储配置与现场发图仍需验收,不能把诊断增强称为线上发送已修复 |
-| 每轮最多 40 个附件交给伙伴 | 本次将普通讨论误降为 10 的限制恢复成 40;按消息新旧选取、同一媒体去重,下载失败或超额的名字明确告诉模型。分工继续保留 40 上限 |
+| 图片、文件、视频输入 | 上传、下载、历史迁移已有;#5613 处理类型/错误诊断、手机等待预算与发送回执复用。隔离 DEV 的真实图片/文本上传与伙伴读取已通过;生产对象存储故障仍需现场证据 |
+| 每轮最多 40 个附件交给伙伴 | 本次将普通讨论误降为 10 的限制恢复成 40;按消息新旧选取、同一媒体去重,下载失败或超额的名字明确告诉模型。分工继续保留 40 上限;服务器提供同伙伴/授权/步骤的成功投递水位,客户端跨页查找未见附件 |
| 无补充时 NO_REPLY,不显示空发言 | 终态过滤已有;本次恢复普通讨论的 NO_REPLY 提示,分工交付不受此提示影响 |
| 历史、安排与工作目录迁移 | `chatServerMigration` 与 afterMessages 已有分批水位、稳定来源 ID、安排恢复和本机目录登记;保留旧数据作为迁移源,不另建可发言本地群 |
| 手机查看/发言、分工控制、待回复推送 | 继续通过被控 Desktop 的 `bot-groups` Remote Resource 与 onStepSettled;本次主机修复同时作用于这些入口,不增加 Mobile 原生能力或协议字段 |
| 删除群 | 多人版群主归档、成员退出是已定的新语义;不能照搬本地删除整群数据,影响其他成员 |
-## 已确认仍需服务端配套的遗漏
-
-这些条目不是“已修复”,也不是新的产品方向。本次客户端补丁不能独立宣称完全恢复旧群功能。
-
-1. **等待时换人**:`chat-server/src/plans.ts` 将 reassign 和 remove 一起限制为 proposed;旧行为允许 waiting 时更换 pending/failed 步骤,只有删除步骤限制在开始前。
-2. **轮流上下文**:`work.ts::queueRound` 为整圈固定同一个 context_seq,claim 没有在轮到后继发言者时更新;后继伙伴的 `before=context_seq+1` 看不到本圈前面的回复。自动首圈的共同快照应保留,轮流时应推进。
-3. **发言顺序与继续讨论**:queueRound 按 actor ID 而非群成员顺序,不轮换第二/三圈起点;continue 开启的新 cycle 仍可能自动并行。需保留原回答者顺序,并让手动继续始终轮流。
-4. **@所有人的并行语义**:客户端把所有伙伴写入 mentions,服务器将其视为 named,因而强制轮流。需兼容地表达“全体”与逐个点名,不能通过丢掉 mentions 破坏 mentioned 回复模式。
-5. **额度、失败与租约过期**:queueRound 按执行请求数计算 10 条额度而非实际发布回复数;后续圈的推进只在 succeeded 路径,最后结束的是 fail 时可能提前断圈;needs_input 的过期租约也会卡住轮流后继。应保留单成员失败不影响其他伙伴、每圈无发言才提前结束的行为,并提供失败提示。
-6. **停止辅助判断后的服务器兜底**:客户端可取消旧模型结果,但 deferExecution 的 planning_deadline 仍可能由 recoverDeferred 自动恢复旧讨论。停止必须同时终止该来源的延迟调度,不能删掉用户消息或关闭全局兜底来规避。
-
-还需按真实执行链核验附件增量投递与跨页历史:现有执行适配器每轮读取最近 100 条,
-没有旧实现按专线投递水位读取全部未见附件的机制。一次性恢复 40 上限不等于解决跨页/重复投递。
-手动/修改分工失败时的专属轻提示同样需配套,不能把用户明确的分工意图静默改为普通讨论。
-
-## 本次验证与避让
-
-- `chatServerParity.test.ts` 从实际 withChatServer 入口检查请求、辅助判断、取消信号和执行输入,
- 使用离线 HTTP/WebSocket fixture;另保留原 chatServer 与辅助模型判断测试。
-- Desktop 与 Mobile 均消费同一主机服务;本次不重做 #5613 的卡片、成员 UI、多语言、上传诊断,
- 不改 #5587 的工具权限和私聊服务。
-- 未跑整仓测试、全包类型检查或多端打包;未启动模拟器、真实 Agent 或向线上群发测试消息。
-- 上述服务端清单需独立配套实现与定向回归;需分别记录客户端已合并、服务端已合并、已部署、
- 安装包已验收,不能用其中一项代替其余项。
+## 本次服务端配套
+
+1. **等待时换人**:允许 waiting 时更换 pending/failed 步骤;删除步骤仍仅限开始前。
+2. **轮流上下文**:顺序执行在 claim 时推进 context_seq,后继伙伴可读本圈前面的回复;自动首圈保持共同快照。
+3. **顺序与继续**:新群按输入成员顺序入群,第二/三圈轮换起点;手动继续始终轮流。旧群相同 joined_at 无法恢复丢失的选择顺序,保留稳定 ID 兜底。
+4. **@所有人**:可选 mentionsAll 与命名列表并存,保留 mentioned 回复方式与自动首圈并行。
+5. **额度与失败**:10 条按实际发布回复计数,领取时计入在途预约;NO_REPLY 不占回复额度。失败或租约过期不阻塞其它伙伴,不自动重跑失败者,并给出轻提示。
+6. **停止辅助判断**:取消接口清除延迟调度、撤回尚未执行的安排并栅栏化迟到结果,保留用户原消息。
+7. **附件增量**:领取回传成功投递水位,按伙伴、授权版本和分工步骤隔离;客户端倒序翻页,不局限最近 100 条。仅成功执行推进水位。
+8. **明确分工失败**:planningMode 保留手动/修改意图;辅助判断失败或超时提示重试,不静默降为普通讨论。
+
+新增字段与取消接口由 `/me.capabilities.groupDiscussionParity=1` 协商;旧服务器仍用旧请求形状。
+先完成整个 Chat Server 集群升级,再发布使用能力位的新客户端,避免滚动期间请求落到旧副本。
+迁移 008/009 均为带默认值的增量列,不改写原消息;避开并行 #836 的 007 迁移。
+
+## 验证与避让
+
+- 客户端相关四个测试文件 47/47;服务端 group-parity 11/11,覆盖旧版非空 schema 升级、再次启动及旧写入形状。
+- 隔离 Desktop + 持久 Chat Server DEV:两位真实伙伴回复;安排开始、逐步结果回流;等待时换人后继续;不用了后直接恢复讨论;修改提议生成更新后的安排;图片与文本文件上传后两位伙伴均正确读取。
+- 已重启隔离 Desktop 和服务端并读回原消息/安排;服务中断超过租约后显示没做完,用户明确重试后完成,没有静默重复执行。另用旧本地 schema 的非空夹具通过正式迁移入口保留两条历史、成员顺序、负责人、回复方式;迁移后两位真实伙伴读出旧历史识别码,双端服务重启后不重复导入。数据库旧版非空夹具经实际 migrate-cli 升级 008/009,读写、重跑及持久 PostgreSQL 重启后核对通过。手机已构建安装并打开到登录页,缺正常登录,尚未完成手机到 Desktop 的群操作验收。
+- DEV 媒体使用显式 `--local-media` 的本机磁盘对象存储与真实 HTTP 字节传输;客户端只在未打包且显式隔离、服务器为固定 loopback 地址时允许 HTTP。生产 HTTPS 校验不变。
+- Desktop 与 Mobile 消费同一主机服务;继承 #5613 的卡片、成员 UI、上传诊断,不重复实现;不改 #5587 的工具权限和私聊服务。服务端 #835 的 Thread 可见性、#836 的可信成员事件由各自 PR 处理,合并时保留其约束。
+- 未运行无关整仓测试;受影响端实际运行验收继续完成后才能解除 PR 阻断。分别记录客户端合并、服务端合并/部署、发布包验收,任何一项不能替代其它项。
diff --git a/docs/dev-rules/chat-server-local-test.md b/docs/dev-rules/chat-server-local-test.md
index 9e4d5f4359..085c69a23d 100644
--- a/docs/dev-rules/chat-server-local-test.md
+++ b/docs/dev-rules/chat-server-local-test.md
@@ -130,3 +130,14 @@ Desktop 将服务端持久消息 `origin: "system"` 中的
回执缓存只在当前账号的主机进程内保留最近 128 次成功发送,进程重启/换账号后仍依赖服务器的
operationId 幂等合同,不宣称具备跨重启持久发件箱。检查 Windows + Android 原现场和 iOS
同源界面,分别记录 Light/Dark 是否目检;没有实际执行的项保持待验收。
+
+## 伙伴补全与附件 DEV 验收(2026-10-08)
+
+服务端启动加 `--local-media --data-dir=<独立目录>` 可启用磁盘对象存储:真实 PUT/GET
+传输字节、校验大小/类型、封存后重启可读。短期地址限本机和短时有效;不是生产 OSS 替代品。
+客户端只在未打包、显式隔离且 baseUrl 为 `http://127.0.0.1:3018` 时接受对应 HTTP 媒体地址,
+正式包仍仅允许 HTTPS,不转发账号令牌到媒体地址。
+
+隔离 DEV 已通过图片和文本文件发送、两位真实伙伴正确读取、分工开始/结果回流、等待换人继续、
+不用了后恢复普通讨论、修改提议与重启读回。完整验收范围与剩余缺项见
+[功能对照](chat-server-feature-parity.md)。不据此声称生产对象存储故障已经修复。
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index b6f1760284..c1b06d8768 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1011,3 +1011,15 @@ Mobile 据此区分已关闭与已删除的旧选择:保留任务或草稿原
共享连接、自动重试或授权。超时不能证明操作未执行,重试沿用 clientId;当前账号主机进程
合并相同在途请求并缓存最近成功回执,服务器 operationId 仍是最终幂等依据。
不新增 IPC channel、数据库迁移或 Mobile 原生指纹输入。
+
+### 服务器伙伴群讨论与分工补全
+
+Chat Server `/me` 追加 `capabilities.groupDiscussionParity: 1`。Desktop 只在该能力存在时发送
+可选 `mentionsAll`、`planningMode`,辅助判断后用 `continue({automatic:true})`,停止判断用
+`messages/:id/cancel-planning`。旧服务器继续收到旧形状;能力协商并不恢复旧服务端缺失的行为。
+整个服务端集群升级后再发布客户端,不能在新旧副本混用时提前承诺该能力。
+
+领取执行追加可选 `attachment_after_seq`,按伙伴/群/授权版本/分工步骤隔离成功投递水位。
+缺字段时沿用旧读取范围;新客户端以此翻页收集未见附件,保留每轮 40 个上限及缺失名称提示。
+`cindy.group-notice` v1 的 integration 卡映射到已有 plan-failed/member-failed/member-timeout
+展示提示,仅承担文案,不授予执行权限。Mobile 继续消费主机既有群资源投影,无新增原生能力。