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(bots): 群附件的引用、账号与交付边界

Chris4374a33a0743
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 3b91af607b..490df437ae 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupAttachments.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupAttachments.test.ts
@@ -9,6 +9,8 @@ const h = vi.hoisted(() => ({
blobDir: '',
removed: [] as string[],
uploads: new Map<string, string>(),
+ db: { name: 'account-a' } as object,
+ dbSeen: [] as unknown[],
}));
vi.mock('../../cindy-media/blobStore.js', () => ({
@@ -23,16 +25,19 @@ vi.mock('../../cindy-media/ledger.js', () => ({
pinBlob: vi.fn(async () => undefined),
hasRef: vi.fn(async (ref: { hash: string; refKind: string; refId: string }) =>
h.refs.some((row) => row.hash === ref.hash && row.refKind === ref.refKind && row.refId === ref.refId)),
- addRef: vi.fn(async (ref: { hash: string; refKind: string; refId: string }) => {
- const id = `ref-${h.refs.length + 1}`;
+ addRef: vi.fn(async (ref: { hash: string; refKind: string; refId: string }, db?: unknown) => {
+ h.dbSeen.push(db);
+ const id = `ref-${h.refs.length + 1}-${Math.random().toString(36).slice(2, 6)}`;
h.refs.push({ id, ...ref });
return id;
}),
- removeRefById: vi.fn(async (id: string) => {
+ removeRefById: vi.fn(async (id: string, db?: unknown) => {
+ h.dbSeen.push(db);
h.refs = h.refs.filter((row) => row.id !== id);
return 1;
}),
}));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: h.db }) }));
vi.mock('../../cindy-media/ingest.js', () => ({
ingestMedia: vi.fn(async (params: { buffer: Uint8Array; refs: Array<{ refKind: string; refId: string }> }) => {
const hash = 'b'.repeat(64);
@@ -72,6 +77,8 @@ beforeEach(async () => {
await fs.mkdir(h.blobDir);
await fs.writeFile(path.join(h.blobDir, `${hash}.png`), 'png');
h.refs = [];
+ h.dbSeen = [];
+ h.db = { name: 'account-a' };
h.removed = [];
h.uploads = new Map();
});
@@ -83,7 +90,7 @@ afterEach(async () => {
const store = () => createBotGroupAttachmentStore({ ownerRoot: () => path.join(root, 'owner') });
describe('bot group attachment store', () => {
- it('references this computer’s images once per group and keeps picked files in place', async () => {
+ it('references this computer’s images for the group and keeps picked files in place', async () => {
const doc = path.join(root, '需求.pdf');
await fs.writeFile(doc, 'pdf!');
const odd = path.join(root, 'scan.heic');
@@ -106,7 +113,31 @@ describe('bot group attachment store', () => {
// The media store cannot take it, so members get it as a file.
{ id: 'f2', name: 'scan.heic', category: 'file', mimeType: 'image/heic', size: 4, url: null, path: odd },
]);
- expect(h.refs).toEqual([{ id: 'ref-1', hash, refKind: 'bot-group-attachment', refId: 'g1', originKind: 'user' }]);
+ expect(h.refs).toHaveLength(2);
+ for (const ref of h.refs) expect(ref).toMatchObject({ hash, refKind: 'bot-group-attachment', refId: 'g1', originKind: 'user' });
+ });
+
+ it('never lets undoing one send unpin an image another send posted', async () => {
+ const image = { id: 'i1', name: 'shot.png', path: 'x', category: 'image', mimeType: 'image/png', url: `cindy-media://blobs/${hash}.png` };
+ // The second send starts while the first is still waiting for its group's queue.
+ const first = await store().prepare({ groupId: 'g1', attachments: [image] });
+ const second = await store().prepare({ groupId: 'g1', attachments: [image] });
+ if (!first.ok || !second.ok) throw new Error('prepare failed');
+ second.commit();
+ await first.discard();
+ expect(h.refs).toHaveLength(1);
+ expect(h.refs[0]).toMatchObject({ hash, refId: 'g1' });
+ });
+
+ it('keeps a batch on the account it started in', async () => {
+ const image = { id: 'i1', name: 'shot.png', path: 'x', category: 'image', mimeType: 'image/png', url: `cindy-media://blobs/${hash}.png` };
+ const accountA = h.db;
+ const prepared = await store().prepare({ groupId: 'g1', attachments: [image] });
+ if (!prepared.ok) throw new Error(prepared.message);
+ h.db = { name: 'account-b' };
+ await prepared.discard();
+ expect(h.dbSeen).toEqual([accountA, accountA]);
+ expect(h.refs).toEqual([]);
});
it('refuses anything it cannot vouch for, undoing the batch', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts
index 2eda25bbdb..728a8ee350 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botGroupChatService.test.ts
@@ -1278,6 +1278,83 @@ describe('botGroupChatService attachments', () => {
expect(h.sqlite!.prepare('SELECT id FROM media_refs ORDER BY id').all()).toEqual([{ id: 'r2' }, { id: 'r3' }]);
});
+ it('undoes a batch whose account changed or whose send broke before it was posted', async () => {
+ const store = fakeAttachments();
+ let switched = false;
+ const harness = createHarness(() => 'x', {
+ prepareAttachments: async (input) => {
+ const result = await store.prepare(input);
+ switched = true;
+ return result;
+ },
+ captureOwnerScope: () => ({ owner: 'a' }) as never,
+ isOwnerScopeCurrent: () => !switched,
+ });
+ const groupId = await createGroup(harness);
+ expect(await harness.service.sendMessage({ groupId, text: 'x', mentions: NONE, clientId: 'c1', attachments: attach('a.pdf') }))
+ .toMatchObject({ ok: false });
+ expect(store.discard).toHaveBeenCalledTimes(1);
+ expect(store.commit).not.toHaveBeenCalled();
+
+ switched = false;
+ const broken = fakeAttachments();
+ h.sqlite?.close();
+ h.sqlite = createDatabase();
+ const other = createHarness(() => 'x', { prepareAttachments: broken.prepare });
+ const otherGroup = await createGroup(other);
+ h.sqlite!.exec('DROP TABLE bot_group_members');
+ await expect(other.service.sendMessage({ groupId: otherGroup, text: 'x', mentions: NONE, clientId: 'c2', attachments: attach('b.pdf') }))
+ .rejects.toThrow();
+ expect(broken.discard).toHaveBeenCalledTimes(1);
+ });
+
+ it('hands over the attachments of unseen messages left out of the prompt, newest first when too many', async () => {
+ const store = fakeAttachments();
+ const harness = createHarness(() => '收到', { prepareAttachments: store.prepare });
+ const groupId = await createGroup(harness);
+ await harness.service.updateGroup({ groupId, replyMode: 'mentioned' });
+ for (let index = 0; index < 45; index += 1) {
+ await harness.service.sendMessage({ groupId, text: `第${index}条`, mentions: NONE, clientId: `m${index}`, attachments: attach(`f${index}.pdf`) });
+ }
+ expect(harness.dispatches).toHaveLength(0);
+ await harness.service.sendMessage({ groupId, text: '@咪咪 都看看', mentions: { all: false, botIds: ['mimi'] }, clientId: 'ask' });
+ await waitForIdle(harness, groupId);
+ const turn = harness.dispatches[0]!;
+ expect(turn.attachments).toEqual(Array.from({ length: 40 }, (_, index) => `f${index + 5}.pdf`));
+ expect(turn.prompt).toContain('The omitted earlier messages carried these attachments');
+ expect(turn.prompt).toContain('f15.pdf');
+ expect(turn.prompt).not.toContain('f4.pdf');
+ expect(turn.prompt).toContain('(5 older attachments are not included');
+ });
+
+ it('keeps what the user added to a step that then failed for its retry', async () => {
+ const store = fakeAttachments();
+ let first = true;
+ const harness = createHarness((botId) => {
+ if (botId === 'mimi' && first) {
+ first = false;
+ return null;
+ }
+ return '好了';
+ }, { decidePlan: async () => THREE_STEPS, workDir: fakeWorkDir(), prepareAttachments: store.prepare });
+ const groupId = await createGroup(harness);
+ const plan = await proposePlan(harness, groupId);
+ await harness.service.startPlan({ groupId, planId: plan.id });
+ await vi.waitFor(() => expect(harness.dispatches.at(-1)?.botId).toBe('mimi'));
+ const running = harness.dispatches.at(-1)!;
+ await harness.service.sendMessage({ groupId, text: '参考这份', mentions: NONE, clientId: 'note', attachments: attach('参考.pdf') });
+ await harness.service.settleLaneTurn({ sessionId: running.sessionId, activeInputClientId: running.clientId, outcome: 'error', resultText: '' });
+ let group = await waitForIdle(harness, groupId);
+ expect(openPlan(group).steps[0]!.status).toBe('failed');
+
+ await harness.service.retryPlan({ groupId, planId: plan.id });
+ group = await waitForIdle(harness, groupId);
+ const retry = harness.dispatches.at(-1)!;
+ expect(retry).toMatchObject({ botId: 'mimi', attachments: ['参考.pdf'] });
+ expect(retry.prompt).toContain('参考这份');
+ expect(openPlan(group).steps[0]!.status).toBe('done');
+ });
+
it('gives every 分工 step the request attachments, and a redo only the new ones', async () => {
const store = fakeAttachments();
const decidePlan = vi.fn(async (_input: PlanDecisionInput) => THREE_STEPS);
diff --git a/apps/desktop/src/main/maker-ipc/botGroupAttachments.ts b/apps/desktop/src/main/maker-ipc/botGroupAttachments.ts
index 5c34c57018..d0c0d03c34 100644
--- a/apps/desktop/src/main/maker-ipc/botGroupAttachments.ts
+++ b/apps/desktop/src/main/maker-ipc/botGroupAttachments.ts
@@ -19,6 +19,7 @@ import type { AttachmentIntegrity } from '@cindy/device-link';
import * as blobStore from '../cindy-media/blobStore.js';
import { ingestMedia } from '../cindy-media/ingest.js';
import * as ledger from '../cindy-media/ledger.js';
+import { getDbClient } from '../localDb/client/current.js';
import { removeRemote } from '../device-link/mediaTransfer.js';
import {
materializeRemoteAttachment,
@@ -105,19 +106,25 @@ export interface BotGroupAttachmentStore {
export function createBotGroupAttachmentStore(deps: { ownerRoot: () => string }): BotGroupAttachmentStore {
const prepare: BotGroupAttachmentStore['prepare'] = async (input) => {
if (input.attachments.length > BOT_GROUP_ATTACHMENTS_MAX) return invalid();
+ // One account for the whole batch: an account switch while a phone upload is fetched must
+ // neither write into nor clean up the next account's data.
+ const db = getDbClient().drizzle;
+ const ownerRoot = deps.ownerRoot();
const refIds: string[] = [];
const folders: string[] = [];
const uploads: string[] = [];
const discard = async () => {
- for (const refId of refIds.splice(0)) await ledger.removeRefById(refId).catch(() => undefined);
+ for (const refId of refIds.splice(0)) await ledger.removeRefById(refId, db).catch(() => undefined);
for (const folder of folders.splice(0)) await fs.rm(folder, { recursive: true, force: true }).catch(() => undefined);
};
- /** The group's reference to an image already in the media store (once per group). */
+ /**
+ * The group's reference to an image already in the media store. Every batch keeps its
+ * own, never another send's: undoing a batch must not unpin an image a posted message shows.
+ */
const referenceImage = async (hash: string) => {
- await ledger.pinBlob(hash);
- if (await ledger.hasRef({ hash, refKind: 'bot-group-attachment', refId: input.groupId })) return;
- refIds.push(await ledger.addRef({ hash, refKind: 'bot-group-attachment', refId: input.groupId, originKind: 'user' }));
+ await ledger.pinBlob(hash, db);
+ refIds.push(await ledger.addRef({ hash, refKind: 'bot-group-attachment', refId: input.groupId, originKind: 'user' }, db));
};
/** Picked on this computer: images are already in the media store, files stay in place. */
@@ -144,7 +151,7 @@ export function createBotGroupAttachmentStore(deps: { ownerRoot: () => string })
const ref = parseRemoteAttachmentRef(refText);
if (!ref) return null;
const mimeType = ref.mimeType ?? entry.mimeType;
- const dir = botGroupAttachmentsPath(deps.ownerRoot(), input.groupId);
+ const dir = botGroupAttachmentsPath(ownerRoot, input.groupId);
await fs.mkdir(dir, { recursive: true });
const incoming = path.join(dir, `.incoming-${randomUUID()}`);
try {
@@ -155,7 +162,7 @@ export function createBotGroupAttachmentStore(deps: { ownerRoot: () => string })
buffer: await fs.readFile(incoming),
mimeType,
refs: [{ refKind: 'bot-group-attachment', refId: input.groupId, originKind: 'user' }],
- });
+ }, db);
refIds.push(...written.refIds);
const size = await isRegularFile(blobStore.resolveSafe(written.url).absPath) ?? 0;
return { id: entry.id, name: entry.name, category: 'image', mimeType, size, url: written.url, path: null, ...(entry.annotated ? { annotated: true } : {}) };
diff --git a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
index a9e7e93799..8d54ee46e9 100644
--- a/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
+++ b/apps/desktop/src/main/maker-ipc/botGroupChatService.ts
@@ -69,6 +69,8 @@ const MAX_CIRCLES_PER_ROUND = 3;
const MAX_BOT_MESSAGES_PER_ROUND = 10;
const MEMBER_TURN_TIMEOUT_MS = 5 * 60_000;
const MAX_DELTA_MESSAGES = 30;
+/** Attachments sent with one member turn; the newest win when unseen messages carry more. */
+const MAX_TURN_ATTACHMENTS = 40;
const MAX_DELTA_MESSAGE_CHARS = 4_000;
const MAX_BOT_REPLY_CHARS = 16_000;
const PREVIEW_CHARS = 80;
@@ -256,6 +258,11 @@ interface GroupRuntime {
round: ActiveRound | null;
planning: PlanningState | null;
step: ActiveStep | null;
+ /**
+ * What the user said to a step whose attempt failed before using it, kept for the retry of
+ * that step so neither the words nor their attachments are lost (§3.1). Memory only.
+ */
+ carriedNotes: { planId: string; position: number; notes: StepNote[] } | null;
/** Serializes user actions (send / continue / stop / membership / delete). */
tail: Promise<unknown>;
}
@@ -447,6 +454,10 @@ export function buildMemberTurnPrompt(input: {
*/
messages: Array<{ from: string; text: string; files?: string[]; attachments?: string[] }>;
omitted: number;
+ /** Attachments of messages left out above; they come with this turn too. */
+ earlierAttachments?: string[];
+ /** Older attachments that do not come with this turn (too many at once). */
+ attachmentsLeftOut?: number;
/** The Bot's previous turn in this group was stopped or timed out before it was posted. */
previousTurnInterrupted?: boolean;
}): string {
@@ -470,6 +481,15 @@ export function buildMemberTurnPrompt(input: {
if (input.messages.some((message) => message.attachments && message.attachments.length > 0)) {
lines.push('Attachments listed with a message come with this turn.');
}
+ if (input.earlierAttachments && input.earlierAttachments.length > 0) {
+ lines.push(
+ 'The omitted earlier messages carried these attachments; they come with this turn too:',
+ untrustedJsonBlock(input.earlierAttachments),
+ );
+ }
+ if (input.attachmentsLeftOut && input.attachmentsLeftOut > 0) {
+ lines.push(`(${input.attachmentsLeftOut} older attachments are not included; ask the user if you need them.)`);
+ }
if (input.previousTurnInterrupted) {
lines.push('Your previous turn in this group was stopped before it was posted; the group never saw it.');
}
@@ -516,7 +536,7 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
const runtimeFor = (groupId: string): GroupRuntime => {
let runtime = runtimes.get(groupId);
if (!runtime) {
- runtime = { round: null, planning: null, step: null, tail: Promise.resolve() };
+ runtime = { round: null, planning: null, step: null, carriedNotes: null, tail: Promise.resolve() };
runtimes.set(groupId, runtime);
}
return runtime;
@@ -901,6 +921,11 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
.map((row) => [row.id, row.workDir] as const)
: [],
);
+ // What the user attached to every message this turn delivers goes with it (§3.1), even
+ // when older messages' text is left out of the prompt; only the newest are sent if many.
+ const delivered = uniqueAttachments(others.flatMap((row) => parseAttachments(row.attachmentsJson)));
+ const attachments = delivered.slice(-MAX_TURN_ATTACHMENTS);
+ const shownIds = new Set(recent.flatMap((row) => parseAttachments(row.attachmentsJson).map((attachment) => attachment.id)));
const prompt = buildMemberTurnPrompt({
groupName: group.name,
botName: member.name,
@@ -918,11 +943,11 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
};
}),
omitted: others.length - recent.length,
+ earlierAttachments: attachments.filter((attachment) => !shownIds.has(attachment.id)).map((attachment) => attachment.name),
+ attachmentsLeftOut: delivered.length - attachments.length,
previousTurnInterrupted: interruptedLanes.delete(lane.sessionId),
});
const deliveredThrough = delta.at(-1)?.sequence ?? seen.lastSeenSequence;
- // What the user attached to the messages this turn delivers goes with it (§3.1).
- const attachments = uniqueAttachments(recent.flatMap((row) => parseAttachments(row.attachmentsJson)));
// The awaits above leave a window in which the user may have superseded this round.
// From here to dispatch nothing awaits, so a live round owns the lane it registers.
@@ -1287,10 +1312,18 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
const beginStep = async (
plan: PlanRow,
step: StepRow,
- notes: StepNotes | null,
+ given: StepNotes | null,
scope?: DataOwnerBroadcastScope,
): Promise<void> => {
const runtime = runtimeFor(plan.groupId);
+ // A failed attempt's unused notes go first into the next attempt at the same step.
+ const carried = runtime.carriedNotes?.planId === plan.id && runtime.carriedNotes.position === step.position
+ ? runtime.carriedNotes.notes
+ : [];
+ runtime.carriedNotes = null;
+ const notes: StepNotes | null = carried.length > 0
+ ? { kind: given?.kind ?? 'retry', notes: [...carried, ...(given?.notes ?? [])] }
+ : given;
const active: ActiveStep = {
groupId: plan.groupId,
planId: plan.id,
@@ -1320,10 +1353,16 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
const { groupId, planId, position } = active;
const runtime = runtimeFor(groupId);
let leftoverNotes: StepNote[] = [];
+ /** Notes the current attempt was given; they did not land if the attempt fails. */
+ let inFlight: StepNote[] = initialNotes?.notes ?? [];
const live = () => !active.cancelled && !disposed && scopeIsCurrent(scope) && runtime.step === active;
const settle = async (outcome: { kind: 'done'; text: string; files: string[] } | { kind: 'failed'; notice: BotGroupNoticeCode }) => {
if (!live()) return;
+ if (outcome.kind === 'failed') {
+ const unused = [...inFlight, ...active.notes.splice(0)];
+ runtime.carriedNotes = unused.length > 0 ? { planId, position, notes: unused } : null;
+ }
const steps = await readSteps(planId);
const step = steps.find((row) => row.position === position);
if (!step) return;
@@ -1436,6 +1475,7 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
let withRequestAttachments = initialNotes?.kind !== 'redo';
for (;;) {
if (!live()) return;
+ inFlight = notes?.notes ?? [];
const brief = await buildBrief(plan, group, member, position, workDir, branch, notes, withRequestAttachments);
const attachments = uniqueAttachments([
...(withRequestAttachments ? parseAttachments(plan.attachmentsJson) : []),
@@ -1914,7 +1954,9 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
.where(and(eq(botGroupMessages.groupId, groupId), eq(botGroupMessages.clientId, clientId)))
.limit(1);
if (posted) return { ok: true, messageId: posted.id } as const;
- // Stored outside the group's queue: a phone upload may take a while to fetch.
+ // Stored outside the group's queue: a phone upload may take a while to fetch. The batch
+ // belongs to the account it was stored in; a switch meanwhile undoes it (§3.1).
+ const owner = captureScope();
let prepared: Omit<BotGroupPreparedAttachments, 'ok'> = { attachments: [], commit: () => undefined, discard: async () => undefined };
if (attachmentInputs.length > 0) {
if (!deps.prepareAttachments) return failure('INVALID_PARAMS', '附件无效');
@@ -1929,87 +1971,101 @@ export function createBotGroupChatService(deps: BotGroupChatServiceDeps) {
const attachments = prepared.attachments;
const discard = () => prepared.discard().catch((error) =>
deps.log?.warn('Bot group attachments were not cleaned up', { groupId, error: String(error) }));
- const sent = await serialize(groupId, async () => {
- const group = await readGroup(groupId);
- if (!group) return failure('NOT_FOUND', '群聊不存在');
- const members = await readMembers(groupId);
- const mentions = resolveGroupMentions(text, inputMentions, members);
- const openPlan = await readOpenPlan(groupId);
- if (division && openPlan && openPlan.status !== 'proposed') {
- return failure('PLAN_OPEN', '群里还有没做完的分工,请先做完或结束');
- }
- const scope = captureScope();
- let appended: { id: string; sequence: number; created: boolean };
- try {
- appended = await appendMessage({ groupId, kind: 'message', authorKind: 'user', content: text, mentions, clientId, attachments });
- } catch (error) {
- return txFailure(error);
- }
- if (!appended.created) {
- await discard();
- return { ok: true, messageId: appended.id } as const;
- }
- prepared.commit();
- // A new user message supersedes whatever the group was saying or deciding.
- await cancelRound(groupId, scope);
- if (cancelPlanning(groupId)) emit(groupId, 'round', scope);
- emit(groupId, 'messages', scope);
- for (const member of members) {
- if (member.status !== 'active' && mentions.botIds.includes(member.botId)) {
- await postNotice(groupId, member, 'member-unavailable', scope);
+ if (!scopeIsCurrent(owner)) {
+ await discard();
+ return failure('NOT_FOUND', '群聊不存在');
+ }
+ let sent: BotGroupSendResult;
+ let posting = false;
+ try {
+ sent = await serialize(groupId, async () => {
+ if (!scopeIsCurrent(owner)) return failure('NOT_FOUND', '群聊不存在');
+ const group = await readGroup(groupId);
+ if (!group) return failure('NOT_FOUND', '群聊不存在');
+ const members = await readMembers(groupId);
+ const mentions = resolveGroupMentions(text, inputMentions, members);
+ const openPlan = await readOpenPlan(groupId);
+ if (division && openPlan && openPlan.status !== 'proposed') {
+ return failure('PLAN_OPEN', '群里还有没做完的分工,请先做完或结束');
}
- }
- const responders = respondersFor(group, members, mentions);
- const chatRound = () => startRound({
- groupId,
- responders,
- mentions,
- parallelFirstCircle: isParallelBroadcast(group, mentions, responders),
- scope,
- });
- // Naming specific Bots is ordinary chat; everything else goes through 分工 routing (§7.2–7.4),
- // including 「@所有人」 and groups where only mentioned Bots reply.
- const direct = mentions.botIds.length > 0;
- if (direct && !division) {
- chatRound();
- return { ok: true, messageId: appended.id } as const;
- }
- const organizer = effectiveOrganizer(group.organizerBotId, members);
- const planning = (mode: PlanDecisionMode, revisePlan: PlanRow | null, fallback: (() => void) | null) => {
- if (!organizer) {
- fallback?.();
- return;
+ const scope = captureScope();
+ let appended: { id: string; sequence: number; created: boolean };
+ try {
+ appended = await appendMessage({ groupId, kind: 'message', authorKind: 'user', content: text, mentions, clientId, attachments });
+ } catch (error) {
+ return txFailure(error);
}
- startPlanning({
- group,
- organizer,
- members,
- mode,
- requestText: text,
- requestAttachments: attachments,
- requestSequence: appended.sequence,
- revisePlan,
- fallback,
+ if (!appended.created) {
+ await discard();
+ return { ok: true, messageId: appended.id } as const;
+ }
+ posting = true;
+ prepared.commit();
+ // A new user message supersedes whatever the group was saying or deciding.
+ await cancelRound(groupId, scope);
+ if (cancelPlanning(groupId)) emit(groupId, 'round', scope);
+ emit(groupId, 'messages', scope);
+ for (const member of members) {
+ if (member.status !== 'active' && mentions.botIds.includes(member.botId)) {
+ await postNotice(groupId, member, 'member-unavailable', scope);
+ }
+ }
+ const responders = respondersFor(group, members, mentions);
+ const chatRound = () => startRound({
+ groupId,
+ responders,
+ mentions,
+ parallelFirstCircle: isParallelBroadcast(group, mentions, responders),
scope,
});
- };
- if (division) {
- planning('forced', null, null);
- } else if (openPlan?.status === 'proposed') {
- planning('revise', openPlan, null);
- } else if (openPlan?.status === 'running') {
- const step = runtimes.get(groupId)?.step;
- if (step && step.planId === openPlan.id) step.notes.push({ text, attachments });
- } else if (openPlan?.status === 'waiting') {
- const current = (await readSteps(openPlan.id)).find((step) => step.position === openPlan.currentStep);
- if (current) await beginStep(openPlan, current, { kind: current.status === 'failed' ? 'retry' : 'redo', notes: [{ text, attachments }] }, scope);
- } else if (deps.decidePlan && members.filter((member) => member.status === 'active').length >= 2) {
- planning('auto', null, chatRound);
- } else {
- chatRound();
- }
- return { ok: true, messageId: appended.id } as const;
- });
+ // Naming specific Bots is ordinary chat; everything else goes through 分工 routing (§7.2–7.4),
+ // including 「@所有人」 and groups where only mentioned Bots reply.
+ const direct = mentions.botIds.length > 0;
+ if (direct && !division) {
+ chatRound();
+ return { ok: true, messageId: appended.id } as const;
+ }
+ const organizer = effectiveOrganizer(group.organizerBotId, members);
+ const planning = (mode: PlanDecisionMode, revisePlan: PlanRow | null, fallback: (() => void) | null) => {
+ if (!organizer) {
+ fallback?.();
+ return;
+ }
+ startPlanning({
+ group,
+ organizer,
+ members,
+ mode,
+ requestText: text,
+ requestAttachments: attachments,
+ requestSequence: appended.sequence,
+ revisePlan,
+ fallback,
+ scope,
+ });
+ };
+ if (division) {
+ planning('forced', null, null);
+ } else if (openPlan?.status === 'proposed') {
+ planning('revise', openPlan, null);
+ } else if (openPlan?.status === 'running') {
+ const step = runtimes.get(groupId)?.step;
+ if (step && step.planId === openPlan.id) step.notes.push({ text, attachments });
+ } else if (openPlan?.status === 'waiting') {
+ const current = (await readSteps(openPlan.id)).find((step) => step.position === openPlan.currentStep);
+ if (current) await beginStep(openPlan, current, { kind: current.status === 'failed' ? 'retry' : 'redo', notes: [{ text, attachments }] }, scope);
+ } else if (deps.decidePlan && members.filter((member) => member.status === 'active').length >= 2) {
+ planning('auto', null, chatRound);
+ } else {
+ chatRound();
+ }
+ return { ok: true, messageId: appended.id } as const;
+ });
+ } catch (error) {
+ // Until the message is stored the batch belongs to no message; after that it stays.
+ if (!posting) await discard();
+ throw error;
+ }
// Nothing was posted: this batch belongs to no message.
if (!sent.ok) await discard();
return sent;
diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.md
index d75a6498d0..b29a4a03d7 100644
--- a/docs/product-rules/bot-group-chat.md
+++ b/docs/product-rules/bot-group-chat.md
@@ -46,12 +46,15 @@
- 入口与普通聊天一致:电脑上「+」→「添加文件、图片或视频…」、粘贴、拖入;手机上「+」里的照片、拍照、
文件(iOS 有最近照片),以及粘贴图片。一条消息最多 20 个附件;有附件时可以不写字。
- 附件属于用户那条消息(`bot_group_messages.attachments_json`),时间线里显示图片缩略图和文件名。
-- 交给谁:每位伙伴轮到发言时,拿到它还没看过的消息里的附件,和普通任务消息的附件一样随这一轮送达;
- 同一轮后面的发言不会重复送。分工时,发起这张安排的消息里的附件交给每一步;步骤进行中补充的话、
- 要求重做的话带的附件也一起送到(重做不重复送原来的附件)。负责人决定要不要分工时知道请求带了哪些附件。
+- 交给谁:每位伙伴轮到发言时,拿到它还没看过的所有消息里的附件(包括因太早没放进这一轮文字的消息),
+ 和普通任务消息的附件一样随这一轮送达;一轮最多带最新的 40 个,更早的告诉伙伴没带上;同一轮后面的发言
+ 不会重复送。分工时,发起这张安排的消息里的附件交给每一步;步骤进行中补充的话、要求重做的话带的附件也一起
+ 送到(重做不重复送原来的附件);这一步没做完时,还没用上的补充和附件留给重试。负责人决定要不要分工时知道
+ 请求带了哪些附件。
- 存放:
- - 图片进媒体总仓,挂群的引用(`bot-group-attachment`,refId = 群 id),删群时在同一事务里释放;各伙伴自己的
- Session 另有自己的引用,互不牵连。
+ - 图片进媒体总仓,每次发送各挂一条群的引用(`bot-group-attachment`,refId = 群 id),撤销一次没发出去的
+ 发送不会动别的消息的引用;删群时在同一事务里释放;各伙伴自己的 Session 另有自己的引用,互不牵连。
+ - 一次发送的附件只记在开始时的账号下;准备期间切换账号则整批撤销、不发送。
- 电脑上选的文件就地使用,和普通聊天一样不复制。
- 手机传来的非图片文件放在群自己的目录 `bot-groups/<groupId>/attachments/`,删群时随群目录移到废纸篓。
- 手机传来的附件只接受这台手机自己的上传(直传或云端中转),不接受电脑上的路径;取回后删除云端中转副本。