Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(bot-group): let a companion answer in several Threads at once
zqchrisb8b728732931
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.tsindex 68a6cfb994..de40d322a9 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts@@ -973,6 +973,18 @@ describe('Chat Server result delivery and refresh', () => {expect(deps.dispatch).toHaveBeenCalledOnce();});+ // bot-group-chat.md §3: a companion may answer in several Threads at once.+ it('shows a companion running in two Threads as one speaker', async () => {+ fixture.handle.mockImplementation(route => {+ if (route.endsWith('/executions')) return { body: [{ ...execution, status: 'running' },+ { ...execution, id: '50000000-0000-4000-8000-000000000099', status: 'running' }] };+ return response(route);+ });+ const result = await service.getGroup(roomId);+ expect(result).toMatchObject({ ok: true, group: { round: { status: 'running', speakers: [{ activity: 'reply' }] } } });+ expect(result.ok && result.group.round.speakers).toHaveLength(1);+ });+it.each(['IMAGE_INPUT_UNSUPPORTED', 'private token and path'])('projects a failed execution from its visible source with a safe code %s', async code => {const source = { id: execution.source_message_id, seq: '7', authorId: selfId, author: { kind: 'human', name: 'Owner' },content: [{ type: 'text', text: 'Question' }], origin: 'user', deleted: false, threadRootId: null, createdAt: '2026-10-03T00:00:00Z' };diff --git a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.tsindex f7cfafc6e5..0d3d00406e 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/chatServerThreadContext.test.ts@@ -69,6 +69,8 @@ let queue = new Map<string, FakeExecution[]>();let executions = new Map<string, FakeExecution>();let completed: Array<{ executionId: string; body: Record<string, unknown> }> = [];let directPosts = 0;+/** The room's execution list; off by default so other cases keep reading no executions. */+let listExecutions = false;function post(text: string, options: { by?: 'owner' | number; threadRootId?: string; mentions?: string[]; media?: string[] } = {}) {const bot = typeof options.by === 'number' ? bots[options.by] : undefined;@@ -103,9 +105,13 @@ function handle(route: string, method: string, body: Record<string, unknown> | uif (path === '/me') return { body: { actor: { id: ownerId } } };if (path === '/actors') return { body: bots.map(bot => ({ id: bot.id, kind: 'bot', externalId: bot.local, name: bot.name })) };if (path === '/executions/claim') {- // Like the server, only a queued execution can be claimed, and claiming is atomic.- let next = queue.get(actor ?? '')?.shift();- while (next && next.status !== 'queued') next = queue.get(actor ?? '')?.shift();+ // Like the server, only a queued execution can be claimed, and claiming is atomic. A named+ // execution is taken exactly; otherwise the oldest queued one.+ const named = typeof body?.executionId === 'string' ? body.executionId : undefined;+ let next = named ? queue.get(actor ?? '')?.find(e => e.id === named) : queue.get(actor ?? '')?.shift();+ if (named && next) queue.set(actor ?? '', queue.get(actor ?? '')!.filter(e => e !== next));+ while (!named && next && next.status !== 'queued') next = queue.get(actor ?? '')?.shift();+ if (next && next.status !== 'queued') next = undefined;if (next) next.status = 'running';return { body: { execution: next ? { ...next } : null } };}@@ -130,6 +136,7 @@ function handle(route: string, method: string, body: Record<string, unknown> | u}return { body: {} };}+ if (path.endsWith('/executions') && listExecutions) return { body: [...executions.values()].map(e => ({ ...e })) };if (path.endsWith('/members') || path.endsWith('/executions') || path.includes('/plans')) return { body: [] };return { body: {} };}@@ -141,7 +148,7 @@ describe('Chat Server Thread context reaches the Agent input', () => {vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'Date'] });vi.setSystemTime(new Date('2026-10-13T00:00:00Z'));vi.stubEnv('XDT_ISOLATED', '1');- ids = 100; seq = 0; messages = []; hidden = new Set(); queue = new Map(); executions = new Map(); completed = []; directPosts = 0;+ ids = 100; seq = 0; messages = []; hidden = new Set(); queue = new Map(); executions = new Map(); completed = []; directPosts = 0; listExecutions = false;fixture.profiles = bots.map(bot => ({ id: bot.local, displayName: bot.name, avatar: null, status: 'active' }));fixture.handle.mockImplementation(handle);fixture.download.mockImplementation(async (_room: string, mediaId: string) => ({ id: mediaId, name: mediaId, category: 'image', path: '/test/image', url: null }));@@ -312,6 +319,35 @@ describe('Chat Server Thread context reaches the Agent input', () => {expect(later.thread.replies.map((m: { id: string }) => m.id)).not.toContain(permissionsQuestion.id);});+ // bot-group-chat.md §3: a companion answers in several Threads at once, one turn at a time in each.+ it('runs one companion in two Threads at once and keeps a second request in a busy Thread waiting', async () => {+ listExecutions = true;+ const laneOf = (local: string, threadRootId?: string) => `lane-${local}${threadRootId ? `:${threadRootId}` : ''}`;+ deps.ensureLane = vi.fn(async ({ botId, threadRootId }: { botId: string; threadRootId?: string }) =>+ ({ ok: true, sessionId: laneOf(botId, threadRootId) })) as unknown as BotGroupChatServiceDeps['ensureLane'];+ const sessions = () => vi.mocked(deps.dispatch).mock.calls.map(call => call[0].targetSessionId);+ const pricing = post('定价要不要调?');+ const release = post('发布前要不要先冻结主干?');+ const [first] = trigger(post('@Nova 你怎么看定价?', { threadRootId: pricing.id, mentions: [bots[0].id] }));+ await vi.advanceTimersByTimeAsync(2000);+ expect(sessions()).toEqual([laneOf('nova', pricing.id)]);++ // While Nova answers about pricing, it is asked in the release Thread and again about pricing.+ const [other] = trigger(post('@Nova 发布这边呢?', { threadRootId: release.id, mentions: [bots[0].id] }));+ const [again] = trigger(post('@Nova 再补充一下定价?', { threadRootId: pricing.id, mentions: [bots[0].id] }));+ await vi.advanceTimersByTimeAsync(2000);+ expect(sessions()).toEqual([laneOf('nova', pricing.id), laneOf('nova', release.id)]);+ expect(executions.get(other.id)!.status).toBe('running');+ expect(executions.get(again.id)!.status).toBe('queued');++ // The pricing turn ends; the waiting request in that Thread runs next, in the same lane.+ await service.settleLaneTurn({ sessionId: laneOf('nova', pricing.id), activeInputClientId: null, outcome: 'done', resultText: '先不调。' });+ expect(completed.map(c => c.executionId)).toEqual([first.id]);+ await vi.advanceTimersByTimeAsync(10_000);+ expect(sessions()).toEqual([laneOf('nova', pricing.id), laneOf('nova', release.id), laneOf('nova', pricing.id)]);+ expect(executions.get(again.id)!.status).toBe('running');+ });+it.each([['everyone', undefined, ['nova', 'pico']], ['one companion', 0, ['nova']]] as const)('runs only the server-targeted companions for a Thread mention of %s', async (_label, target, expected) => {const root = post('只要伙伴能管理任务,是不是就拿到了所有权限?');diff --git a/apps/desktop/src/main/maker-ipc/chatServer.ts b/apps/desktop/src/main/maker-ipc/chatServer.tsindex dc1b3614c2..87208def11 100644--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@ -73,6 +73,7 @@ interface Execution {failure_code?: unknown; updated_at?: string;plan_id?: string | null; plan_step?: number | null;trigger?: unknown; trigger_type?: string | null;+ created_at?: string;context_seq: string; attachment_after_seq?: string; epoch: number; status: string; access_mode: 'owner' | 'chat' | 'tools'; access_revision: number;}interface ServerPlan {@@ -83,6 +84,8 @@ interface ServerPlan {}interface Running {execution: Execution; sessionId: string; clientId: string; accepted: boolean; started: number;+ /** The conversation this turn answers in (see executionLane); unknown until its source is read. */+ lane?: string;context?: ExecutionContext;settlement?: { terminal: BotGroupLaneTerminal; payload?: Record<string, unknown>; retryAt: number; keepLease?: boolean };delivery?: Promise<void>;@@ -107,6 +110,8 @@ const THREAD_LIST_LIMIT = 50;const CHANGE_COALESCE_MS = 150;/** A realtime notice of newly queued work claims it this soon instead of on the next 2s tick. */const CLAIM_TRIGGER_MS = 250;+/** How often a busy companion's rooms are re-read for work queued in its other conversations. */+const LANE_SWEEP_MS = 10_000;/** A room snapshot reused for a send while its realtime subscription reports no change since. */const SNAPSHOT_REUSE_MS = 30_000;/** A sidebar summary reused while the room's change head is unchanged; names can change elsewhere. */@@ -400,7 +405,12 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// Per-companion name / avatar publish failures of the last pass: one broken avatar never blocks the rest.let profileFailures = new Map<string, unknown>();let profileRefreshedAt = 0;+ /** Turns in progress by execution ID: one companion may answer in several conversations at once. */const running = new Map<string, Running>();+ /** Work announced as queued for a companion (execution ID → room), read when it is busy elsewhere. */+ const queuedHints = new Map<string, Map<string, string>>();+ /** When each busy companion's own rooms are next re-read for work its realtime notices missed. */+ const laneSweeps = new Map<string, number>();const metadata = new Map<string, Promise<void>>();/*** Followed room scopes, each with the newest cursor this process has read or acked. It only@@ -850,7 +860,16 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD// not renew one either. Any other or unknown change re-checks the room's running work.if (!types.length || types.some(type => typeof type !== 'string' || !CHATTER_CHANGES.has(type)))for (const run of running.values()) if (run.execution.conversation_id === roomId) void checkLease(run);- if (changes.some(queuedForThisDevice)) triggerClaim();+ if (changes.some(queuedForThisDevice)) {+ for (const change of changes) {+ const value = change as { entityId?: unknown; data?: { botId?: unknown } };+ if (!queuedForThisDevice(change) || typeof value.entityId !== 'string' || typeof value.data?.botId !== 'string') continue;+ const hints = queuedHints.get(value.data.botId) ?? new Map<string, string>();+ hints.set(value.entityId, roomId);+ queuedHints.set(value.data.botId, hints);+ }+ triggerClaim();+ }}else {for (const change of event.changes ?? []) {@@ -1205,9 +1224,15 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst workspace = workspaces().read(roomId);const plans = serverPlans.map(plan => planView(plan, s.members, workspace));const open = plans.find(p => ['proposed', 'running', 'waiting'].includes(p.status));- const speakers: BotGroupSpeaker[] = executions.filter(e => e.status === 'running').map(e => ({- botId: localBot(e.bot_id)?.id ?? e.bot_id, sessionId: running.get(e.bot_id)?.sessionId ?? null, activity: e.plan_id ? 'step' as const : 'reply' as const,- }));+ // A companion answering in several Threads at once is still one speaker per activity; the one+ // whose turn runs on this computer is shown, so its Session can be opened.+ const speakers: BotGroupSpeaker[] = [];+ for (const e of executions.filter(e => e.status === 'running')) {+ const speaker = { botId: localBot(e.bot_id)?.id ?? e.bot_id, sessionId: running.get(e.id)?.sessionId ?? null, activity: e.plan_id ? 'step' as const : 'reply' as const };+ const known = speakers.findIndex(other => other.botId === speaker.botId && other.activity === speaker.activity);+ if (known < 0) speakers.push(speaker);+ else if (!speakers[known]!.sessionId && speaker.sessionId) speakers[known] = speaker;+ }// The organizer is visibly 「正在看」 while this device decides whether to arrange (§7.2),// as the local service showed it. It works on the auxiliary model, not in a lane session.const deciding = planning.get(roomId);@@ -1351,7 +1376,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}/** One execution gets one immutable terminal result, regardless of which boundary ends it. */async function settleExecution(run: Running, terminal: BotGroupLaneTerminal, abort = false): Promise<void> {- if (!current() || running.get(run.execution.bot_id) !== run) return;+ if (!current() || running.get(run.execution.id) !== run) return;if (!run.settlement) {run.settlement = { terminal: { ...terminal }, retryAt: 0 };run.releaseToolAuthority?.();@@ -1363,7 +1388,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDfunction deliverSettlement(run: Running): Promise<void> {if (run.delivery) return run.delivery;const pending = run.settlement;- if (!pending || !current() || running.get(run.execution.bot_id) !== run || Date.now() < pending.retryAt) return Promise.resolve();+ if (!pending || !current() || running.get(run.execution.id) !== run || Date.now() < pending.retryAt) return Promise.resolve();run.delivery = (async () => {try {if (!pending.payload) {@@ -1388,7 +1413,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDpending.payload = terminal.outcome === 'error' ? { detail: botGroupRuntimeFailureDetail(terminal.failureCode ?? 'RUNTIME_ERROR') }: { ...(isBotGroupNoReplyText(text) && !files.length ? {} : { content: [{ type: 'text', text: text.slice(0, 16000) || '已完成' }, ...files] }), continueDiscussion: run.context?.kind !== 'member.joined' && !run.plan && !isBotGroupNoReplyText(text) };}- if (!current() || running.get(run.execution.bot_id) !== run) return;+ if (!current() || running.get(run.execution.id) !== run) return;await updateExecution(run, pending.terminal.outcome === 'error' ? 'fail' : 'complete', pending.payload);if (run.plan && deps.onStepSettled) {const s = await snapshot(run.execution.conversation_id);@@ -1412,9 +1437,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDreturn;}} finally { run.delivery = undefined; }- if (running.get(run.execution.bot_id) === run) {+ if (running.get(run.execution.id) === run) {run.releaseToolAuthority?.();- running.delete(run.execution.bot_id);+ running.delete(run.execution.id);// Refresh both delivered results and local failures without waiting for an echo.changed(run.execution.conversation_id);}@@ -1431,11 +1456,13 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDthrow error;}}- async function runExecution(execution: Execution) {+ async function runExecution(execution: Execution, lane?: string) {const bot = localBot(execution.bot_id);- if (!bot || running.has(execution.bot_id)) return;- const run: Running = { execution, sessionId: '', clientId: BOT_GROUP_CLIENT_ID.memberTurn(execution.conversation_id, execution.id, bot.id), accepted: false, started: Date.now() };- running.set(execution.bot_id, run);+ if (!bot || running.has(execution.id)) return;+ const run: Running = { execution, sessionId: '', clientId: BOT_GROUP_CLIENT_ID.memberTurn(execution.conversation_id, execution.id, bot.id), accepted: false, started: Date.now(), lane };+ running.set(execution.id, run);+ // Until its conversation is known, this turn holds back the companion's other work.+ if (!lane) void executionLane(execution).then(value => { run.lane = value; }, () => undefined);try {z.object({ access_mode: z.enum(['owner', 'chat', 'tools']), access_revision: z.number().int().positive() }).parse(execution);run.context = ordinaryExecution(execution) ? { kind: 'message' }@@ -1484,7 +1511,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD|| eventSource.authorId !== trigger.actorId || eventSource.seq !== execution.context_seq || !card)throw new Error('INVALID_EXECUTION_TRIGGER');}- if (!current() || running.get(execution.bot_id) !== run) throw new Error('STALE_EXECUTOR');+ if (!current() || running.get(execution.id) !== run) throw new Error('STALE_EXECUTOR');if (ownDirectRoom) { await runDirectExecution(run, bot.id, s.room.id); return; }// Lane setup and context metadata reads run together; attachment bytes wait for setup// to succeed so a failed setup cannot leave downloads running after settlement.@@ -1532,7 +1559,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDrun.releaseToolAuthority = registerGroupToolAuthority(lane.sessionId, {botId: bot.id, mode: execution.access_mode,sourceGroup: { groupId: s.room.id, name: s.room.name },- isCurrent: () => current() && running.get(execution.bot_id) === run && !run.settlement,+ isCurrent: () => current() && running.get(execution.id) === run && !run.settlement,validate: async () => {// Recheck metadata and the execution lease at the actual tool boundary.// Group administrators cannot grant access to someone else's companion.@@ -1702,11 +1729,11 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD'Keep your reply concise. Your final response will be posted to the group. Do not call another participant just to reply.',].join('\n');await updateExecution(run, 'heartbeat');- if (!current() || running.get(execution.bot_id) !== run) throw new Error('STALE_EXECUTOR');+ if (!current() || running.get(execution.id) !== run) throw new Error('STALE_EXECUTOR');const dispatched = await deps.dispatch({ targetSessionId: lane.sessionId, clientId: run.clientId, message: prompt,persistedContent: `${UI_ACTION_TRIGGER_PREFIX}${prompt}`, attachments, toolsDisabled: execution.access_mode === 'chat',onQueued: async clientId => { run.clientId = clientId; }, onAccepted: async () => {- if (!current() || running.get(execution.bot_id) !== run) { await deps.abortLane(lane.sessionId); throw new Error('STALE_EXECUTOR'); }+ if (!current() || running.get(execution.id) !== run) { await deps.abortLane(lane.sessionId); throw new Error('STALE_EXECUTOR'); }run.accepted = true;} });if (!dispatched.ok) throw new Error(botGroupRuntimeFailureCode({ code: dispatched.errorCode, message: dispatched.message }));@@ -1730,7 +1757,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDhumanActorId: selfId, botId, deliver: deps.companionCloud.deliverToCanonical,beforeDeliver: async () => {await updateExecution(run, 'heartbeat');- if (!current() || running.get(execution.bot_id) !== run) throw new Error('STALE_EXECUTOR');+ if (!current() || running.get(execution.id) !== run) throw new Error('STALE_EXECUTOR');// Handed to another computer since the claim (the hand-over demotes this copy): never run it here.if (companion?.isShadowed(botId) || !companion?.installConfirmed(botId)) throw new Error('MEMBER_UNAVAILABLE');} });@@ -1760,28 +1787,80 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDreturn value?.type === 'execution.changed' && value.data?.status === 'queued'&& (typeof value.data.botId !== 'string' || ownedActiveBot(value.data.botId));}- /** One claim per idle owned companion, all at once; the first failure in companion order is reported. */+ /**+ * The conversation an execution answers in: the group's main timeline, one Thread, or one plan+ * (bot-group-chat.md §3). A companion takes one turn at a time per conversation, while its turns in+ * different conversations run side by side, each in its own lane.+ */+ async function executionLane(execution: Execution): Promise<string> {+ const room = execution.conversation_id;+ if (execution.plan_id) return `${room}:plan:${execution.plan_id}`;+ if (!ordinaryExecution(execution)) return `${room}:main`;+ const source = await readMessage(room, execution.source_message_id);+ return source?.threadRootId ? `${room}:thread:${source.threadRootId}` : `${room}:main`;+ }+ const runsOf = (botId: string) => [...running.values()].filter(run => run.execution.bot_id === botId);+ /** Leases one execution: the oldest the server offers, or exactly `executionId`. */+ async function claim(actorId: string, executionId?: string): Promise<Execution | null> {+ const payload = { operationId: randomUUID(), executorId, accessPolicyVersion: 1, planVersion: 1, ...(directRoomClaims ? { directRoomVersion: 1 } : {}),+ ...(executionId ? { executionId } : {}) };+ // Parallel claims may see another companion's downgrade; each judges the request it sent.+ const withEvents = memberJoinedClaims;+ try {+ return (await api<{ execution: Execution | null }>('/executions/claim', 'POST', { ...payload, ...(withEvents ? { memberJoinedVersion: 1 } : {}) }, actorId)).execution;+ } catch (error) {+ if (!withEvents || !(error instanceof ChatResponseError) || error.status !== 400 || error.message !== 'INVALID_INPUT') throw error;+ memberJoinedClaims = false;+ return (await api<{ execution: Execution | null }>('/executions/claim', 'POST', payload, actorId)).execution;+ }+ }+ /**+ * A busy companion takes only work in its other conversations: a turn in a Thread never waits for+ * one in the main timeline or another Thread, while turns in one conversation stay in order. The+ * server offers the oldest work first, so this names each execution it may take.+ */+ async function claimBesideRuns(actorId: string, runs: Running[]) {+ const lanes = new Set(runs.map(run => run.lane));+ const hints = queuedHints.get(actorId) ?? new Map<string, string>();+ const rooms = new Set(hints.values());+ if (Date.now() >= (laneSweeps.get(actorId) ?? 0)) {+ laneSweeps.set(actorId, Date.now() + LANE_SWEEP_MS);+ for (const run of runs) rooms.add(run.execution.conversation_id);+ }+ for (const room of [...rooms].sort()) {+ const rows = await api<Execution[]>(`/conversations/${room}/executions`);+ for (const [executionId, hinted] of hints) if (hinted === room) hints.delete(executionId);+ const queued = rows.filter(row => row.bot_id === actorId && row.status === 'queued')+ .sort((a, b) => (a.created_at ?? '').localeCompare(b.created_at ?? '') || a.id.localeCompare(b.id));+ for (const row of queued) {+ const lane = await executionLane(row);+ if (lanes.has(lane)) continue;+ const execution = await claim(actorId, row.id);+ if (!execution) continue;+ lanes.add(lane);+ void runExecution(execution, lane);+ }+ }+ if (!hints.size) queuedHints.delete(actorId);+ }+ /** One claim pass per owned companion, all at once; the first failure in companion order is reported. */async function claimOnce() {- const idle = actors.filter(a => a.kind === 'bot' && localBot(a.id)?.status === 'active' && !running.has(a.id)+ const owned = actors.filter(a => a.kind === 'bot' && localBot(a.id)?.status === 'active'// Only the registered home runs a companion: skip while the home is elsewhere or not yet// registered (an unset home would let any copy of the owner claim it).&& !(companionHome && a.homeDeviceId !== selfDeviceId)// Shadowed here (demoted, or run by another installation on this device), or this// installation is not yet confirmed to run it (the server only tells devices apart): never claim.&& !(companionHome && (companion?.isShadowed(a.externalId) || !companion?.installConfirmed(a.externalId))));- settledValues(await settleBounded(idle, idle.length, async actor => {- let claim: { execution: Execution | null };- const payload = { operationId: randomUUID(), executorId, accessPolicyVersion: 1, planVersion: 1, ...(directRoomClaims ? { directRoomVersion: 1 } : {}) };- // Parallel claims may see another companion's downgrade; each judges the request it sent.- const withEvents = memberJoinedClaims;- try {- claim = await api('/executions/claim', 'POST', { ...payload, ...(withEvents ? { memberJoinedVersion: 1 } : {}) }, actor.id);- } catch (error) {- if (!withEvents || !(error instanceof ChatResponseError) || error.status !== 400 || error.message !== 'INVALID_INPUT') throw error;- memberJoinedClaims = false;- claim = await api('/executions/claim', 'POST', payload, actor.id);- }- const { execution } = claim;+ // A turn whose conversation is not yet known holds back the rest of its companion's work.+ const ready = owned.filter(a => runsOf(a.id).every(run => run.lane));+ settledValues(await settleBounded(ready, ready.length, async actor => {+ const runs = runsOf(actor.id);+ if (runs.length) { await claimBesideRuns(actor.id, runs); return; }+ // An idle companion takes the oldest work wherever it is.+ queuedHints.delete(actor.id);+ laneSweeps.delete(actor.id);+ const execution = await claim(actor.id);if (execution) void runExecution(execution);}));}@@ -1832,9 +1911,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDtry { await updateExecution(run, 'heartbeat'); }catch (error) {if (error instanceof ChatResponseError && !retryableResponse(error)) {- if (running.get(run.execution.bot_id) === run) {+ if (running.get(run.execution.id) === run) {run.releaseToolAuthority?.();- running.delete(run.execution.bot_id);+ running.delete(run.execution.id);changed(run.execution.conversation_id);}return;@@ -1843,7 +1922,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD}await deliverSettlement(run); return;}- if (running.get(run.execution.bot_id) !== run) return;+ if (running.get(run.execution.id) !== run) return;if (checking.has(run)) { recheck.add(run); return; }checking.add(run);try {@@ -1859,9 +1938,9 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceD} catch {// An in-flight heartbeat must not discard a result that became ready while// it was awaiting its response; retry the terminal operation for its receipt.- if (!run.settlement && running.get(run.execution.bot_id) === run) {+ if (!run.settlement && running.get(run.execution.id) === run) {run.releaseToolAuthority?.();- running.delete(run.execution.bot_id);+ running.delete(run.execution.id);if (run.sessionId) await deps.abortLane(run.sessionId).catch(() => undefined);changed(run.execution.conversation_id);}@@ -1869,7 +1948,7 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDchecking.delete(run);// A dissolve or change can arrive while an older heartbeat is in flight.// Check the new authority once that response settles, without waiting 15s.- if (recheck.delete(run) && running.get(run.execution.bot_id) === run) void checkLease(run);+ if (recheck.delete(run) && running.get(run.execution.id) === run) void checkLease(run);}}const heartbeat = setInterval(() => { for (const run of running.values()) void checkLease(run); }, 15000);@@ -2268,8 +2347,8 @@ function createChatServer(local: BotGroupChatService, deps: BotGroupChatServiceDconst executions = await api<Execution[]>(`/conversations/${room}/executions`);for (const e of executions.filter(e => ['queued', 'running', 'needs_input'].includes(e.status) && !e.plan_id)) {await api(`/conversations/${room}/executions/${e.id}/control`, 'POST', { operationId: randomUUID(), action: 'stop' });- const run = running.get(e.bot_id);- if (run?.execution.id === e.id) { running.delete(e.bot_id); if (run.sessionId) await deps.abortLane(run.sessionId); }+ const run = running.get(e.id);+ if (run) { running.delete(e.id); if (run.sessionId) await deps.abortLane(run.sessionId); }}changed(room); return { ok: true as const };}),diff --git a/docs/product-rules/bot-group-chat.md b/docs/product-rules/bot-group-chat.mdindex 157cba80c0..0249a07ca6 100644--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@ -503,7 +503,11 @@ Chat Server 既有的回应者接口直到最后一页(离群成员保留回回复由服务端写回源消息所在的同一 Thread;单独 @ 一位伙伴、@所有人和不 @ 的规则仍由服务端决定。话题 Session 只装这个话题,每轮说明「这段对话只属于这个话题」;群专线说明较早的轮次可能来自启用话题 Session 之前的话题。以上内容仍以低信任数据块放在本轮用户段,不进入 system prompt。-同一位伙伴同一时间仍只执行一件群里的活(宿主按伙伴排队),不同话题的回复会排队,上下文互不影响。+同一位伙伴可以同时在不同对话里干活(2026-10-21):主群、每个话题、每张安排各算一个对话,各自一个 Session,+互不等待;同一个对话里仍一次一轮,后到的请求排在前一轮之后,按服务端顺序执行。伙伴空闲时照旧认领最早排队的活;+正在某个对话里干活时,宿主只按执行 ID 认领它在其他对话里排队的活:候选来自实时的「排队」通知,另外每 10 秒+重读一次它正在干活的群,补上漏收的通知。别的群里早于它开始干活前就已排队、又没有收到通知的活,等它空闲后再按顺序认领。+同一伙伴的多个对话同时写同一个工作目录时,与同一项目里同时开两个任务相同,不另加锁。引用回复(`replyToId`)是另一层关系,不等同于 Thread 根消息。回归见 `chatServerThreadContext.test.ts`。### 引用回复与创建话题(2026-10-13)