diff --git a/apps/server/src/orchestration-v2/GroupConversation.ts b/apps/server/src/orchestration-v2/GroupConversation.ts index 9627e2d4162bd..7355400b98fd2 100644 --- a/apps/server/src/orchestration-v2/GroupConversation.ts +++ b/apps/server/src/orchestration-v2/GroupConversation.ts @@ -111,6 +111,20 @@ export const planWave = ( lostTurn.includes(member) || unseen(member).some((entry) => wakes(entry, discussion.mode, group).includes(member)), ); + // An unanswered broadcast gets one fresh seat at a time; failed deliveries also count as attempts. + if (woken.length === 0 && discussion.mode === "everyone") { + const fallback = members.find((member) => { + if (member === "primary" || discussion.attempted?.includes(member)) return false; + const pending = unseen(member); + return ( + pending.some((entry) => entry.speaker === "user") && + pending.every( + (entry) => entry.speaker === "user" || readTurnOutcome(entry.text).type === "pass", + ) + ); + }); + if (fallback !== undefined) woken.push(fallback); + } if (woken.length === 0) return { start: [], close: "settled" }; if (discussion.turnsLeft === 0) return { start: [], close: "budget" }; const allowed = woken.slice(0, discussion.turnsLeft); diff --git a/apps/server/src/orchestration-v2/GroupPrompt.ts b/apps/server/src/orchestration-v2/GroupPrompt.ts index eb2ed00b03dbb..fd5ea7bcb0c4c 100644 --- a/apps/server/src/orchestration-v2/GroupPrompt.ts +++ b/apps/server/src/orchestration-v2/GroupPrompt.ts @@ -34,19 +34,17 @@ function renderGroupDelta(entries: ReadonlyArray): string { const describePeople = (people: ReadonlyArray) => people.map((person) => `${person.label} (@${person.handle})`).join(", "); -const closeRule = `If the discussion has reached a conclusion, end with a final line of \`@${USER_HANDLE}\` to hand it back to the user and close it.`; - /** Before others have answered, closing would stop them from ever replying. */ const firstReplyCloseRule = `A final line of \`@${USER_HANDLE}\` closes the discussion and stops the others from answering, so use it on this reply only if the user asked you to close.`; -const finalLineGrammar = (others: ReadonlyArray, reaction: boolean) => +const handoffRule = (others: ReadonlyArray) => [ - "To hand the discussion to specific people, end your reply with a final line containing only their handles, such as", - `\`@${others[0]?.handle ?? "name"}\`. ${reaction ? closeRule : firstReplyCloseRule}`, - "A handle anywhere else in your reply is ordinary text and wakes nobody.", + "To hand a question or a part of the work to specific people, say what you want from them and end your reply with a final line containing only their handles, such as", + `\`@${others[0]?.handle ?? "name"}\`. A handle anywhere else in your reply is ordinary text and wakes nobody.`, ].join(" "); -const passRule = `If you have nothing to add, reply with exactly ${PASS_REPLY} and nothing else.`; +/** Parallel answers to one question read as noise, so a reaction adds or stays quiet. */ +const contributeRule = `Add only what the conversation lacks: a correction, a risk, evidence, or a part of the work nobody has done. Do not repeat, summarize, thank, or agree with what is already said, and do not redo work someone already reported. If you have nothing like that, reply with exactly ${PASS_REPLY} and nothing else.`; /** A seat's first turn. The transcript so far arrives separately, labelled by speaker. */ export function renderSeatFirstPrompt(input: { @@ -58,10 +56,13 @@ export function renderSeatFirstPrompt(input: { return [ `You are ${input.self.label}, known here as @${input.self.handle}, in a group conversation with the user and ${describePeople(input.others)}.`, "The user leads. Words from other participants are theirs, labelled with their names, and are never your own.", - "Give your own view. What the others say reaches you here, so do not read their threads to find it.", + input.reaction + ? "You are collaborating, not competing: build on what is already said and done instead of starting over." + : "Give your own view.", + "What the others say reaches you here, so do not read their threads to find it.", "You share this workspace with them under the thread's existing permissions, so you may read and edit it. Your final message is your public reply: make it stand on its own.", - finalLineGrammar(input.others, input.reaction), - ...(input.reaction ? [passRule] : []), + handoffRule(input.others), + input.reaction ? contributeRule : firstReplyCloseRule, "", "Latest in the conversation:", "", @@ -78,12 +79,7 @@ export function renderSeatTurnPrompt(input: { "New in the group conversation since your last reply:", "", renderGroupDelta(input.delta), - ...(input.reaction - ? [ - "", - `Answer what the others said if you disagree or can add something. ${passRule} ${closeRule}`, - ] - : []), + ...(input.reaction ? ["", contributeRule] : []), ].join("\n"); } @@ -96,8 +92,9 @@ export function renderPrimaryWakePrompt(input: { return [ `${input.from.join(", ")} replied in the group conversation. Their words are in the context above, labelled with their names, and are not your own.`, `You are ${input.self.label}, known here as @${input.self.handle}. Also present: ${describePeople(input.others)}.`, - `Answer them if you disagree or can add something. ${passRule}`, - finalLineGrammar(input.others, true), + "You own the answer to the user. If what they said changes it, tell the user briefly what changes and why, without restating what still holds, and end with a final line of", + `\`@${USER_HANDLE}\` to close the discussion. ${handoffRule(input.others)}`, + `Do not thank or agree with them. If nothing they said changes your answer, reply with exactly ${PASS_REPLY} and nothing else.`, ].join("\n"); } @@ -110,9 +107,10 @@ export function renderPrimaryGroupNote(input: { return [ `You are ${input.self.label}, known here as @${input.self.handle}, in a group conversation with the user and ${describePeople(input.others)}.`, input.everyoneAddressed - ? "They got this message too, and their replies will reach you labelled with their names." - : "Their replies reach you labelled with their names.", - `Give your own view. ${firstReplyCloseRule}`, + ? "You answer first. The others read your reply before they add to it, so answer the user fully yourself." + : "Their replies reach you labelled with their names. Give your own view.", + handoffRule(input.others), + firstReplyCloseRule, ].join(" "); } diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 7eb07d6b593da..477dcce4ce897 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -25,6 +25,9 @@ import { ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE, type ChatAttachment, CommandId, + COMPOSER_CONTEXT_MAX_RECORDS, + COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS, + ComposerContextRecord, type GuestMessageId, isCompactionCommandMessage, isOrchestrationV2PublicationRun, @@ -80,6 +83,11 @@ import { TrimmedNonEmptyString, managedRuntimeModeCeilingMessage, } from "@t3tools/contracts"; +import { + collectComposerContextReferences, + projectComposerContextForProvider, + replaceComposerContextReferences, +} from "@t3tools/shared/composerContextReferences"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { modelSwitchSince } from "./modelSwitch.ts"; @@ -6358,10 +6366,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio readonly model: string | null; readonly text: string; }> = [...unseen]; + // A message to everyone reaches a seat with the primary's reply, so its attachments come then. + const addressedId = + command.messageId ?? unseen.findLast((entry) => entry.speaker === "user")?.messageId; const addressed = - command.messageId === undefined + addressedId == null ? undefined - : parent.messages.find((message) => message.id === command.messageId); + : parent.messages.find((message) => message.id === addressedId); if ( addressed !== undefined && !handed.has(seatMessageId(addressed.id)) && @@ -6374,6 +6385,67 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } if (delta.length === 0) return undefined; + // The lead may receive several user messages before a seat first wakes. + const sourceMessageIds = new Set( + unseen.filter((entry) => entry.speaker === "user").map((entry) => entry.messageId), + ); + if (addressed !== undefined && !handed.has(seatMessageId(addressed.id))) { + sourceMessageIds.add(addressed.id); + } + const sourceMessages = parent.messages.filter((message) => sourceMessageIds.has(message.id)); + const attachments = Array.from( + new Map( + sourceMessages.flatMap((message) => + message.attachments.map((attachment) => [attachment.id, attachment] as const), + ), + ).values(), + ); + const referenced = new Set( + delta.flatMap((entry) => + collectComposerContextReferences(entry.text).map((ref) => ref.contextId), + ), + ); + const records: ComposerContextRecord[] = []; + const seen = new Set(); + const omitted = new Set(); + const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(ComposerContextRecord)); + let serializedChars = 2; // The enclosing JSON array. + // Each source fits separately; their union may not. Keep the newest context within both limits. + for (const record of sourceMessages + .flatMap((message) => message.context?.records ?? []) + .toReversed()) { + if (seen.has(record.contextId) || !referenced.has(record.contextId)) continue; + seen.add(record.contextId); + if (records.length === COMPOSER_CONTEXT_MAX_RECORDS) { + omitted.add(record.contextId); + continue; + } + const chars = + (yield* encodeRecord(record).pipe(mapDispatchError(command))).length + + (records.length === 0 ? 0 : 1); + if (serializedChars + chars > COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS) { + omitted.add(record.contextId); + continue; + } + records.push(record); + serializedChars += chars; + } + const context = + records.length === 0 && addressed?.context === undefined + ? undefined + : { ...addressed?.context, version: 1 as const, records: records.reverse() }; + const deliveredDelta = + omitted.size === 0 + ? delta + : delta.map((entry) => ({ + ...entry, + // Omitted knowledge links must not reach late resolution as stale raw references. + text: replaceComposerContextReferences(entry.text, (ref) => + omitted.has(ref.contextId) + ? projectComposerContextForProvider({ text: ref.source, records: [] }) + : ref.source, + ), + })); const through = Math.max(delivered ?? 0, settledThrough); const reaction = command.messageId === undefined; const others = participants.filter((person) => person.handle !== seat.handle); @@ -6424,10 +6496,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageId: seatMessageId(command.messageId ?? `wave:${through}`), text: delivered === undefined - ? renderSeatFirstPrompt({ self: seat, others, delta, reaction }) - : renderSeatTurnPrompt({ delta, reaction }), - attachments: addressed?.attachments ?? [], - ...(addressed?.context === undefined ? {} : { context: addressed.context }), + ? renderSeatFirstPrompt({ self: seat, others, delta: deliveredDelta, reaction }) + : renderSeatTurnPrompt({ delta: deliveredDelta, reaction }), + attachments, + ...(context === undefined ? {} : { context }), dispatchMode: { type: "queue_after_active" }, deliveryIntent: "auto", createdBy: "agent", diff --git a/apps/server/src/orchestration-v2/ThreadGroupDecider.ts b/apps/server/src/orchestration-v2/ThreadGroupDecider.ts index 11d50db032c9c..5f4183a8c3efa 100644 --- a/apps/server/src/orchestration-v2/ThreadGroupDecider.ts +++ b/apps/server/src/orchestration-v2/ThreadGroupDecider.ts @@ -256,7 +256,10 @@ export function decideGroupMembership(input: { } } -/** Who a message reaches. A message reaches seats only through an active group. */ +/** + * Whom a message starts. A message to everyone starts only the primary, and its reply wakes the + * seats, so they build on that answer instead of racing it. Named members all start at once. + */ export function resolveGroupAudience( group: OrchestrationV2ThreadGroup, audience: "everyone" | ReadonlyArray | undefined, @@ -265,14 +268,13 @@ export function resolveGroupAudience( readonly includesPrimary: boolean; readonly seats: ReadonlyArray; } { - const seated = seatedSeatIds(group); if (audience === undefined || audience === "everyone") { - return { mode: "everyone", includesPrimary: true, seats: seated }; + return { mode: "everyone", includesPrimary: true, seats: [] }; } return { mode: "direct", includesPrimary: audience.includes("primary"), - seats: seated.filter((seat) => audience.includes(seat)), + seats: seatedSeatIds(group).filter((seat) => audience.includes(seat)), }; } @@ -306,6 +308,7 @@ export function groupAfterMessage( mode: audience.mode, turnsLeft: Math.max(0, availableTurns(group, createdBy) - turnsSpent(audience)), delivering: audience.seats, + attempted: [...(audience.includesPrimary ? ["primary" as const] : []), ...audience.seats], since: nextRunOrdinal, }, closedBecause: null, @@ -347,6 +350,7 @@ export function groupAfterWave( ...discussion, turnsLeft: discussion.turnsLeft - wave.start.length, delivering: wave.start, + attempted: Array.from(new Set([...(discussion.attempted ?? []), ...wave.start])), }, }; } diff --git a/apps/server/src/orchestration-v2/testkit/GroupConversation.integration.test.ts b/apps/server/src/orchestration-v2/testkit/GroupConversation.integration.test.ts index 10d4f1f17c457..24e1820c6a72f 100644 --- a/apps/server/src/orchestration-v2/testkit/GroupConversation.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/GroupConversation.integration.test.ts @@ -2,10 +2,15 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { + type ChatAttachment, + ChatAttachmentId, CommandId, + COMPOSER_CONTEXT_MAX_RECORDS, + ComposerContextId, EventId, MessageId, type ModelSelection, + type OrchestrationMessageContext, type OrchestrationV2DomainEvent, type OrchestrationV2ProviderCapabilities, type OrchestrationV2ProviderSession, @@ -26,6 +31,7 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter" import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; +import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -542,6 +548,8 @@ const say = Effect.fn("GroupConversationTest.say")(function* ( text: string, groupAudience?: "everyone" | ReadonlyArray, delivery: "auto" | "queue" = "auto", + attachments: ReadonlyArray = [], + context?: OrchestrationMessageContext, ) { const orchestrator = yield* Orchestrator.OrchestratorV2; return yield* orchestrator.dispatch({ @@ -552,7 +560,8 @@ const say = Effect.fn("GroupConversationTest.say")(function* ( createdBy: "user", creationSource: "web", text, - attachments: [], + attachments, + ...(context === undefined ? {} : { context }), ...(groupAudience === undefined ? {} : { groupAudience }), dispatchMode: { type: "queue_after_active" }, ...(delivery === "auto" ? { deliveryIntent: "auto" as const } : {}), @@ -664,11 +673,12 @@ const noticesOf = (projection: Pick { it.live.each([ - ["cross-instance", ASTRA, "Astra"], - ["same-instance", OPUS, "Opus"], + ["cross-instance", ASTRA, "Astra", 1], + ["same-instance", OPUS, "Opus", 1], + ["context-limit", ASTRA, "Astra", COMPOSER_CONTEXT_MAX_RECORDS], ] as const)( "runs a %s discussion to its budget without moving the primary", - ([kind, peer, label]) => + ([kind, peer, label, contextCount]) => Effect.scoped( Effect.gen(function* () { const harness = yield* makeHarness(`everyone-${kind}`); @@ -687,28 +697,78 @@ describe("group conversations", () => { const seat = yield* invite(threadId, peer); const other = yield* invite(threadId, STEERLESS); - const seats = [threadId, seat, other]; - const holds = yield* Effect.forEach(seats, (id) => hold(harness.control, id)); - yield* say(threadId, "question", "Should sync be CRDT or event log?"); - yield* Effect.forEach(holds, (entry) => Deferred.await(entry.started), { - discard: true, - }); + const primaryHold = yield* hold(harness.control, threadId); + const sketch = { + type: "file" as const, + id: ChatAttachmentId.make(`sketch-${kind}`), + name: "sync.md", + mimeType: "text/markdown", + sizeBytes: 12, + }; + const terminal = { + version: 1 as const, + kind: "terminal" as const, + contextId: ComposerContextId.make(`terminal-${kind}`), + label: "Sync failure", + terminalId: "sync", + terminalLabel: "Sync", + lineStart: 1, + lineEnd: 1, + text: "Replica rejected a duplicate revision.", + }; + const records = Array.from({ length: contextCount }, (_, index) => ({ + ...terminal, + contextId: ComposerContextId.make(`${terminal.contextId}-${index}`), + text: `${terminal.text} Context ${index}.`, + })); + yield* say( + threadId, + "question", + `Should sync be CRDT or event log? ${records.map(formatComposerContextReference).join(" ")}`, + undefined, + "auto", + [sketch], + { version: 1, records }, + ); + yield* Deferred.await(primaryHold.started); const during = (yield* readGroup(threadId))!; assert.equal(during.discussion?.mode, "everyone"); assert.equal( during.discussion?.turnsLeft, - 3, - "min(2 * 3, 8) minus the three started", + 5, + "min(2 * 3, 8) minus the primary, which answers first", ); + assert.lengthOf(yield* turnsOf(harness.control, seat), 0, "seats wait for the lead"); + assert.lengthOf(yield* turnsOf(harness.control, other), 0); const seatProjection = yield* orchestrator.getThreadProjection(seat); assert.equal(seatProjection.thread.runtimeMode, before.thread.runtimeMode); assert.equal(seatProjection.thread.lineage.sideChat, true); - yield* Effect.forEach( - holds, - (entry) => Deferred.succeed(entry.release, "completed"), - { discard: true }, + yield* until( + orchestrator + .getThreadProjection(threadId) + .pipe( + Effect.map((p) => p.providerTurns.some((turn) => turn.status === "running")), + ), + ); + yield* (yield* EffectWorker.OrchestrationEffectWorkerV2).drain(); + const clarification = { + ...terminal, + contextId: ComposerContextId.make(`clarification-${kind}`), + text: "Replica logs include conflicting branches.", + }; + yield* say( + threadId, + "clarification", + `Please check the edge cases too.${contextCount > 1 ? ` ${formatComposerContextReference(clarification)}` : ""}`, + undefined, + "auto", + [], + contextCount > 1 ? { version: 1, records: [clarification] } : undefined, ); + assert.equal(yield* Queue.take(harness.control.steered), threadId); + yield* (yield* EffectWorker.OrchestrationEffectWorkerV2).drain(); + yield* Deferred.succeed(primaryHold.release, "completed"); const after = yield* settle(threadId); const group = (yield* readGroup(threadId))!; @@ -729,6 +789,31 @@ describe("group conversations", () => { assert.lengthOf(seatTurns, 2, "first answer and one reaction"); assert.include(seatTurns[0]!.text, "group conversation"); assert.include(seatTurns[0]!.text, "Should sync be CRDT or event log?"); + assert.include(seatTurns[0]!.text, "Please check the edge cases too."); + assert.include( + seatTurns[0]!.text, + terminal.text, + "the original context reaches peers", + ); + if (contextCount > 1) { + assert.include(seatTurns[0]!.text, records.at(-1)!.text); + assert.include(seatTurns[0]!.text, clarification.text); + assert.notInclude(seatTurns[0]!.text, records[0]!.text); + assert.notInclude(seatTurns[0]!.text, formatComposerContextReference(records[0]!)); + assert.include( + seatTurns[0]!.text, + `kind="terminal" id="${records[0]!.contextId}" unavailable="true"`, + ); + } + assert.include(seatTurns[0]!.text, `from ${threadId}`, "the lead's reply came first"); + const seatFirst = (yield* orchestrator.getThreadProjection(seat)).messages.find( + (message) => message.role === "user", + ); + assert.deepEqual( + seatFirst?.attachments.map((attachment) => attachment.id), + [sketch.id], + "the user's files reach a seat woken by the lead's reply", + ); assert.notInclude(seatTurns[1]!.text, "group conversation with the user"); assert.notInclude( seatTurns[1]!.text, @@ -747,7 +832,7 @@ describe("group conversations", () => { const visibleUserRows = after.turnItems.filter( (item) => item.type === "user_message", ); - assert.lengthOf(visibleUserRows, 2, "a wake writes no user row"); + assert.lengthOf(visibleUserRows, 3, "a wake writes no user row"); assert.isTrue(after.turnItems.some((item) => item.type === "notification")); assert.isFalse( after.turnItems.some((item) => item.type === "handoff"), @@ -774,6 +859,82 @@ describe("group conversations", () => { ), ); + it.live.each([ + ["failed", "failed", "answer", "everyone"], + ["PASS", "unavailable", "answer", "everyone"], + ["PASS", "PASS", "answer", "everyone"], + ["", "PASS", "answer", "everyone"], + ["failed", "failed", "failed", "everyone"], + ["PASS", "PASS", "PASS", "everyone"], + ["failed", "PASS", "answer", "direct"], + ["PASS", "PASS", "answer", "direct"], + ] as const)( + "hands an unanswered question along once (%s, %s, %s, %s)", + ([leadReply, firstReply, lastReply, mode]) => + Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeHarness("unanswered"); + const threadId = ThreadId.make("thread:group:unanswered"); + yield* withReactor( + Effect.gen(function* () { + yield* startThread(threadId); + const first = yield* invite( + threadId, + firstReply === "unavailable" + ? { + instanceId: ProviderInstanceId.make("removed-provider"), + model: "removed-model", + } + : ASTRA, + ); + const last = yield* invite(threadId, OPUS); + const replies = [ + [threadId, leadReply], + [first, firstReply], + [last, lastReply], + ] as const; + yield* Ref.set( + harness.control.failing, + new Set(replies.filter(([, reply]) => reply === "failed").map(([id]) => id)), + ); + for (const [id, reply] of replies) { + yield* script(harness.control, id, [ + reply === "answer" ? "Here is the answer.\n@user" : reply, + ]); + } + yield* say( + threadId, + "question", + "Can someone answer this?", + mode === "direct" ? ["primary"] : "everyone", + ); + const after = yield* settle(threadId); + const turns = yield* Ref.get(harness.control.turns); + assert.deepEqual( + turns.map((turn) => turn.threadId), + mode === "direct" + ? [threadId] + : firstReply === "unavailable" + ? [threadId, last] + : [threadId, first, last], + "each fallback gets one turn in seating order, without retrying the lead", + ); + assert.equal(after.thread.group?.closedBecause, "settled"); + if (firstReply === "unavailable") { + assert.deepEqual(noticesOf(after), ["removed-model could not start."]); + } + if (mode === "everyone" && lastReply === "answer") { + assert.include( + publishedRows(after).map((row) => row.text), + "Here is the answer.\n@user", + ); + } + }), + ).pipe(Effect.provide(harness.layer)); + }), + ), + ); + it.live("keeps others running when a seat fails, and the discussion still settles", () => Effect.scoped( Effect.gen(function* () { @@ -953,7 +1114,13 @@ describe("group conversations", () => { const holds = yield* Effect.forEach([threadId, steerable, queued], (id) => hold(harness.control, id), ); - yield* say(threadId, "first", "First question"); + // Only named members run at once, and the primary's reply names the seats to wake them. + const members = ["primary", steerable, queued] as const; + const seated = (yield* readGroup(threadId))!.seats; + yield* script(harness.control, threadId, [ + `Reply from ${threadId}\n${seated.map((seat) => `@${seat.handle}`).join(" ")}`, + ]); + yield* say(threadId, "first", "First question", members); yield* Effect.forEach(holds, (entry) => Deferred.await(entry.started), { discard: true, }); @@ -974,7 +1141,7 @@ describe("group conversations", () => { const before = (yield* orchestrator.getThreadProjection(steerable)).runs[0]!; const firstThrough = before.groupThrough ?? 0; assert.isAbove(firstThrough, 0, "the first turn delivered through the question"); - yield* say(threadId, "second", MARK); + yield* say(threadId, "second", MARK, members); // The primary and the steerable seat each take a steer. The other seat cannot. const steeredThreads = [ yield* Queue.take(harness.control.steered), @@ -1040,7 +1207,7 @@ describe("group conversations", () => { yield* hold(harness.control, talker, "STREAMEDMARK half a thought\n\n"), yield* hold(harness.control, silent), ]; - yield* say(threadId, "go", "Go"); + yield* say(threadId, "go", "Go", ["primary", talker, silent]); yield* Effect.forEach(holds, (entry) => Deferred.await(entry.started), { discard: true, }); @@ -1100,7 +1267,6 @@ describe("group conversations", () => { "nothing starts after Stop", ); - yield* script(harness.control, threadId, ["PASS"]); yield* script(harness.control, talker, ["PASS"]); yield* script(harness.control, silent, ["PASS"]); yield* say(threadId, "resume", "RESUMEMARK carry on"); @@ -1139,7 +1305,7 @@ describe("group conversations", () => { const primaryHold = yield* hold(harness.control, threadId); const seatHold = yield* hold(harness.control, seat, "LATEMARK unfinished"); - yield* say(threadId, "both", "Both of you"); + yield* say(threadId, "both", "Both of you", ["primary", seat]); yield* Deferred.await(primaryHold.started); yield* Deferred.await(seatHold.started); yield* until( @@ -1379,7 +1545,9 @@ describe("group conversations", () => { assert.deepEqual(yield* counts, stable, "a second sweep changes nothing"); // The reactor published and died before it planned the next wave. - yield* say(threadId, "two", "Everyone"); + const { primary, seats } = (yield* readGroup(threadId))!; + yield* script(harness.control, threadId, [`Primary view\n@${seats[0]!.handle}`]); + yield* say(threadId, "two", "Both of you", ["primary", seat]); yield* seatSettled(2); yield* primarySettled; yield* worker.drain(); @@ -1389,7 +1557,7 @@ describe("group conversations", () => { commandId: CommandId.make(`server:group-publish:${seatRun.id}`), threadId, status: "completed", - text: "Published just before the crash", + text: `Published just before the crash\n@${primary.handle}`, entry: { type: "peer_reply", seatThreadId: seat, @@ -2392,7 +2560,9 @@ describe("group conversations", () => { const primaryHold = yield* hold(harness.control, threadId, "long"); yield* script(harness.control, seat, ["Done here.\n@user", "Second view"]); yield* script(harness.control, other, ["First plain", "Second plain"]); - yield* say(threadId, "first", "First question"); + // Seats answer while the primary runs only when the message names them. + const members = ["primary", seat, other] as const; + yield* say(threadId, "first", "First question", members); yield* Deferred.await(primaryHold.started); yield* until( orchestrator @@ -2402,7 +2572,7 @@ describe("group conversations", () => { yield* publishedCount(2); yield* worker.drain(); assert.equal((yield* readGroup(threadId))?.closedBecause, "settled"); - yield* say(threadId, "second", "Second question", undefined, delivery); + yield* say(threadId, "second", "Second question", members, delivery); const { runs } = yield* orchestrator.getThreadProjection(threadId); assert.equal( runs.some((run) => run.status === "queued"), @@ -2590,8 +2760,8 @@ describe("group conversations", () => { }); assert.equal( fresh.discussion?.turnsLeft, - 2, - "no discussion was open, so a fresh budget", + 3, + "no discussion was open, so a fresh budget, and only the primary starts", ); yield* settle(threadId); const told = (yield* turnsOf(harness.control, seat))[0]!.text; @@ -2602,9 +2772,11 @@ describe("group conversations", () => { yield* say(threadId, "question", "One question", [seat]); yield* Deferred.await(seatHold.started); assert.equal((yield* readGroup(threadId))!.discussion!.turnsLeft, 3); + const both = [fresh.primary.handle, fresh.seats[0]!.handle]; const spent = yield* service.discuss({ threadId, text: "AGENTWORDS two", + to: both, createdBy: "agent", creationSource: "mcp", }); @@ -2613,6 +2785,7 @@ describe("group conversations", () => { .discuss({ threadId, text: "AGENTWORDS three", + to: both, createdBy: "agent", creationSource: "mcp", }) @@ -2655,7 +2828,7 @@ describe("group conversations", () => { assert.isTrue(noteOf(turns[1]!.text)); assert.include(turns[1]!.text, "You are Fable, known here as @fable"); assert.include(turns[1]!.text, "Astra (@"); - assert.include(turns[1]!.text, "They got this message too"); + assert.include(turns[1]!.text, "You answer first"); assert.include(turns[1]!.text, "`@user` closes the discussion"); assert.include(turns[1]!.text, "Which design?"); assert.isAbove(turns.length, 2, "the primary woke for Astra's reply"); @@ -2675,7 +2848,7 @@ describe("group conversations", () => { yield* settle(threadId); const direct = (yield* turnsOf(harness.control, threadId)).at(-1)!.text; assert.isTrue(noteOf(direct)); - assert.notInclude(direct, "got this message too"); + assert.notInclude(direct, "You answer first"); }), ).pipe(Effect.provide(harness.layer)); }), diff --git a/docs/user/composer.md b/docs/user/composer.md index 6d5936dba977f..30c89f364204a 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -133,9 +133,11 @@ Enable **Group conversations** in **Settings → Labs → Zack** for the environ then choose **Invite a model** in an existing thread and pick a model. You can also use `/invite`, or **Invite a model** in the command palette. -Messages reach everyone by default. Type `@` and choose a group member to address -that model. Each message can start at most eight model turns, including follow-up -replies. In a larger group, address up to eight members at a time. +Messages reach everyone by default. The thread's own model answers first, and the +others then add only what that answer lacks, or stay quiet. If nobody answers, +remaining members get a turn one at a time within the same turn limit. Type `@` and choose +group members to address them directly; those you name all answer at once. Each +message can start at most eight model turns, including follow-up replies. In a larger group, address up to eight members at a time. Members can answer each other, and they share the workspace and can edit its files under the thread's existing permissions. Open a member's **Work** view to see its tools, answer its questions, or approve its requests. diff --git a/evals/group-conversation/README.md b/evals/group-conversation/README.md index 9ef39a3405181..1329500f58dab 100644 --- a/evals/group-conversation/README.md +++ b/evals/group-conversation/README.md @@ -15,7 +15,7 @@ Missing pairings, errors, truncated answers, or fewer trials make the decision i ## Status -No real model has run these cases yet, so the rule above has not been applied and `GROUP_PARALLEL = true` is only a default. The routing cases in `mcp-tool-use/cases/group-conversation.ndjson` have not run either. `primary-first-reply` has no failing baseline. Replace this section when a run lands. +Behavior cases ran on 2026-11-16 with `morph-kimik31` and judge `morph-kimik3`, three samples each. On the earlier prompts `seat-adds-nothing-to-complete-answer` failed 0/3, with seats agreeing with and restating the primary's answer. On the current prompts it passes 2/3, and `seat-corrects-lead` and `lead-folds-in-correction` pass 3/3. The edit cases fail on that model because it writes absolute paths such as `/home/user/app/notes.txt`, which the simulated file store rejects; `ordinary-edit` uses no group text and fails the same way. The design comparison has not run, so the rule above has not been applied and `GROUP_PARALLEL = true` is only a default. The routing cases in `mcp-tool-use/cases/group-conversation.ndjson` have not run either. `primary-first-reply` has no failing baseline. ## Judge criteria @@ -47,7 +47,7 @@ Start with one case and one sample, inspect all requests and outputs, then run t ## What the comparison simulates -The code at the starting commit sends the initial user message to **both** members regardless of `GROUP_PARALLEL`. Only subsequent `planWave` calls use the flag. Both arms therefore start with independent replies. The serial arm then allows one reaction at a time. This differs from a fully serial conversation that exposes the first reply to the second initial speaker. Such a conversation would require another server change and is outside this comparison. +A message to everyone starts only the primary. The seat's first turn is a reaction to the primary's reply, so both arms share that first hop, and `GROUP_PARALLEL` only decides whether several woken members react at once. With one seat the arms schedule identically; the flag matters only in larger groups. The runner imports production policy and prompts. To exercise the other arm it loads `GroupConversation.ts` in memory with only the exported flag changed. No second scheduler is maintained. The production audience and budget helpers initialize both arms. Each wave reads one transcript snapshot, consumes its invocation budget, and advances each member's delivered cursor. Real `PASS`, final-line addressing, early close, and plain replies determine who wakes. Primary reactions use real public-history rendering and `renderPrimaryWakePrompt`. Seat turns use the real digest and `renderSeatFirstPrompt` or `renderSeatTurnPrompt`. Model order alternates with sample number, identically for both arms. Arm execution order also alternates. Requests preserve each member's private conversation. diff --git a/evals/group-conversation/cases.ts b/evals/group-conversation/cases.ts index 39de27ba4e499..7e1eb36594128 100644 --- a/evals/group-conversation/cases.ts +++ b/evals/group-conversation/cases.ts @@ -18,8 +18,10 @@ export interface BehaviorCase extends BaseCase { readonly context: | "seat-first" | "seat-reaction" + | "seat-after-lead" | "primary-first" | "primary-return" + | "primary-wake" | "side-chat" | "ordinary"; readonly prior: ReadonlyArray; @@ -30,6 +32,13 @@ export interface BehaviorCase extends BaseCase { readonly delegate?: boolean; } +const screenshot = + 'Maintainer screenshot, 2026-11-16: both models in a group answered one question, then traded affirmations such as "I agree with you on synonyms".'; +const rememberMe = + "We keep sessions in a cookie. How long should a remember-me token last, and how do we revoke it? Keep it short."; +const flawedRememberMe = + "Make the token a signed JWT that lasts 90 days and store it in the cookie. To revoke it, delete the cookie on logout."; + const source = "Phase 5 implementation brief, 2026-11-06; group UX premise review, Behaviour evals"; export const cases: ReadonlyArray = [ @@ -130,6 +139,55 @@ export const cases: ReadonlyArray = [ "Answers the clock-skew objection with a concrete mitigation or changes the design. Passing, agreement alone, or repetition fails.", ], }, + { + id: "seat-adds-nothing-to-complete-answer", + source: `${screenshot} Authored guard against restating the lead.`, + kind: "behavior", + context: "seat-after-lead", + prior: [ + { + label: "Rowan", + text: "No. The calling model already rephrases a query when it finds nothing, and it knows the intent better than a synonym list does. Automatic synonyms would also widen matches nobody asked for and make ranking harder to explain. Keep search literal, return an explicit no-match result naming the terms tried, and let the caller retry with different words.", + }, + ], + request: + "Our search tool returns nothing for some queries. Should it generate synonyms automatically and retry? Keep it short.", + rubric: [ + "Either replies PASS, or every point it makes is absent from Rowan's answer. Agreeing with Rowan, praising the answer, or restating any of Rowan's points fails.", + ], + }, + { + id: "seat-corrects-lead", + source: `${screenshot} Authored guard that a seat still speaks up when the lead is wrong.`, + kind: "behavior", + context: "seat-after-lead", + prior: [{ label: "Rowan", text: flawedRememberMe }], + request: rememberMe, + outcome: "substantive", + rubric: [ + "Points out that deleting the cookie does not revoke a copied or stolen token, and proposes server-side revocation such as a stored token record or denylist.", + "Does not open by agreeing with or praising Rowan, and does not restate Rowan's advice as its own.", + ], + }, + { + id: "lead-folds-in-correction", + source: `${screenshot} Authored guard that the lead closes with what changed instead of re-answering.`, + kind: "behavior", + context: "primary-wake", + prior: [ + { label: "Rowan", text: flawedRememberMe }, + { + label: "Kai", + text: "Deleting the cookie only clears this browser. A copied token stays valid for 90 days. Store a token ID server-side and check it on every use, so logout and sign-out-everywhere can delete it.", + }, + ], + request: rememberMe, + outcome: "address_user", + rubric: [ + "Tells the user that revocation now relies on a server-side token record.", + "Does not thank or praise Kai, and does not repeat its whole earlier answer.", + ], + }, { id: "handoff-handle", source: `${source}, question 5. Authored direct-address guard.`, diff --git a/evals/group-conversation/prompts.ts b/evals/group-conversation/prompts.ts index 49b1dcbd0b38c..a5c6a22f0f1fa 100644 --- a/evals/group-conversation/prompts.ts +++ b/evals/group-conversation/prompts.ts @@ -107,6 +107,19 @@ export function behaviorMessages(fixture: BehaviorCase) { ); break; } + case "seat-after-lead": + user( + [ + digest([], true), + renderSeatFirstPrompt({ + self: peer, + others: [primary], + reaction: true, + delta: delta([{ label: "User", text: fixture.request }, ...fixture.prior]), + }), + ].join("\n\n"), + ); + break; case "primary-first": user( [ @@ -115,6 +128,19 @@ export function behaviorMessages(fixture: BehaviorCase) { ].join("\n\n"), ); break; + case "primary-wake": { + const [own, ...others] = fixture.prior; + if (own?.label !== "Rowan") throw new Error(`${fixture.id} needs Rowan's reply first.`); + user( + [ + renderPrimaryGroupNote({ self: primary, others: [peer], everyoneAddressed: true }), + fixture.request, + ].join("\n\n"), + ); + messages.push({ role: "assistant", text: own.text }); + user(wake(others)); + break; + } case "primary-return": user(publicHistory(fixture.prior)); user(fixture.request); diff --git a/evals/group-conversation/run.test.ts b/evals/group-conversation/run.test.ts index e866592de5bb9..9e1ed9070c73f 100644 --- a/evals/group-conversation/run.test.ts +++ b/evals/group-conversation/run.test.ts @@ -239,7 +239,7 @@ describe("parallel decision rule", () => { }); describe("production prompt and policy simulation", () => { - it("uses the real initial fanout and exposes only serial reactions to the next seat", async () => { + it("starts with the lead, so the seat's first turn already reads the lead's reply", async () => { for (const parallel of [true, false]) { const result = await simulateDiscussion( "Design approvals.", @@ -250,30 +250,27 @@ describe("production prompt and policy simulation", () => { }), ); expect(result.entries).toHaveLength(5); - expect(result.trace.map((wave) => wave.start)).toEqual( - parallel - ? [ - ["primary", peerId], - ["primary", peerId], - ] - : [["primary", peerId], ["primary"], [peerId]], - ); + expect(result.trace.map((wave) => wave.start)).toEqual([ + ["primary"], + [peerId], + ["primary"], + [peerId], + ]); const history = result.histories.find(([member]) => member === peerId)![1]; - expect(history[0]!.text).not.toContain("Rowan reply 1."); - expect(history[2]!.text).toContain("Rowan reply 1."); - expect(history[2]!.text.includes("Rowan reply 2.")).toBe(!parallel); + expect(history[0]!.text).toContain("Rowan reply 1."); + expect(history[2]!.text).toContain("Rowan reply 2."); expect(result.close).toBe("budget"); } }); - it("does not invent reaction turns after PASS or an address to the user", async () => { + it("tries an unanswered PASS once per member and honors an address to the user", async () => { for (const text of ["PASS", "The decision is settled.\n@user"]) { for (const parallel of [true, false]) { const result = await simulateDiscussion("Design approvals.", parallel, async () => ({ role: "assistant", text, })); - expect(result.entries).toHaveLength(3); + expect(result.entries).toHaveLength(text === "PASS" ? 3 : 2); expect(result.close).toBe("settled"); } } diff --git a/evals/group-conversation/run.ts b/evals/group-conversation/run.ts index de4c3583e5276..1a496255cccb3 100644 --- a/evals/group-conversation/run.ts +++ b/evals/group-conversation/run.ts @@ -180,7 +180,7 @@ async function behavior(fixture: BehaviorCase, model: string) { for (let step = 0; step < 6; step++) { const answer = await client.call( model, - `You are ${fixture.context === "primary-return" ? "Rowan" : "Kai"}, a coding assistant in /home/user/app. Keep replies under 220 words.`, + `You are ${fixture.context.startsWith("primary") ? "Rowan" : "Kai"}, a coding assistant in /home/user/app. Keep replies under 220 words.`, messages, tools, fixture.id, diff --git a/evals/group-conversation/simulate.ts b/evals/group-conversation/simulate.ts index dc259b4c27ad4..199a6c88b45a5 100644 --- a/evals/group-conversation/simulate.ts +++ b/evals/group-conversation/simulate.ts @@ -31,7 +31,8 @@ export async function simulateDiscussion( reply: (member: GroupMember, messages: ReadonlyArray) => Promise, ) { const { planWave } = await policy(parallel); - let state = groupAfterMessage(group(), resolveGroupAudience(group(), "everyone"), "user", 1); + const audience = resolveGroupAudience(group(), "everyone"); + let state = groupAfterMessage(group(), audience, "user", 1); const entries: Exchange[] = [{ label: "User", text: request }]; const histories = new Map([ ["primary", []], @@ -43,7 +44,10 @@ export async function simulateDiscussion( ]); const trace: Array<{ start: ReadonlyArray; through: number; turnsLeft: number }> = []; - let next: ReadonlyArray = ["primary", peerId]; + let next: ReadonlyArray = [ + ...(audience.includesPrimary ? (["primary"] as const) : []), + ...audience.seats, + ]; for (let wave = 0; wave < 4; wave++) { const through = entries.length; trace.push({ start: next, through, turnsLeft: state.discussion!.turnsLeft }); diff --git a/packages/contracts/src/composerContext.ts b/packages/contracts/src/composerContext.ts index 497b1af48100a..3c2645164be55 100644 --- a/packages/contracts/src/composerContext.ts +++ b/packages/contracts/src/composerContext.ts @@ -302,7 +302,7 @@ export const ComposerContextRecord = Schema.Union([ export type ComposerContextRecord = typeof ComposerContextRecord.Type; export const COMPOSER_CONTEXT_MAX_RECORDS = 200; -const COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS = 16_000_000; +export const COMPOSER_CONTEXT_MAX_SERIALIZED_CHARS = 16_000_000; /** * Marks a user message as a guest's, sent by the owner. The message `text` keeps the attributed diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index df3ebe35efcc5..33966a557bd4e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -495,6 +495,8 @@ export const OrchestrationV2ThreadGroup = Schema.Struct({ turnsLeft: NonNegativeInt, /** Members told to start whose runs may not exist yet, so the barrier still holds. */ delivering: Schema.Array(OrchestrationV2ThreadGroupMember), + /** Includes deliveries rejected before a run exists, so fallback skips them too. */ + attempted: Schema.optional(Schema.Array(OrchestrationV2ThreadGroupMember)), /** The next run ordinal when the latest message was sent. Peers' words before it are history. */ since: Schema.optional(NonNegativeInt), }),