Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(coordination): two teammates asking a bot the same thing get one answer (#3957)

Milind Soni9368f25b81b9
diff --git a/docs/runtime-contract.md b/docs/runtime-contract.md
index 1e966dec06..c5999641f8 100644
--- a/docs/runtime-contract.md
+++ b/docs/runtime-contract.md
@@ -35,6 +35,7 @@ queued ──admit──> running ──turn ends──> completed | failed | ca
- **Enqueue** checks the parent is running (or there is no parent), refuses work back to an ancestor, dedupes (same brief, same assignee, same parent, unless `rework`), checks depth and the root's budgets, computes the level, writes the row with event `enqueued`. Refusals return a typed reason; they never throw into a turn.
- **Admission** is one rule for every path: the runtime asks the host `canStart`; the host answers from its slots (a sibling waiting on the person does not hold its sibling). Same-conversation turns never overlap. `validate` runs before every dispatch and again on every tick for every live row: access that closes while a teammate works ends that work `failed(refused)` with the reason, its words are dropped, and a report whose route no longer admits it is withheld from the requester's resume.
+- **One answer to the same request.** When a requester's work starts, the coordinator looks for the same request to the same bot from another requester, asked earlier and still being answered when this one was asked, in another conversation and outside a room (rooms keep their own turn order). "The same" means the same mode, approval level and `doneWhen`, and the same words in the same order once case, punctuation and spacing are set aside, 40 characters or more (`server/same-request.ts`): requests that differ by any word are two requests, however alike they read, and an answer from before the request was asked is never reused. The host decides whether this requester may have that answer (`shareAnswer`, `server/host/share-answer.ts`): the same people see both requesters' conversations, as on any home of one person, and the bot works on both in the same folder (two conversations' own private folders count as one). Such a request runs no turn of its own: it waits for that answer, kept out of the stall window, completes with it ("Another teammate asked this a moment ago, so it was answered once, for both of you:"), and is reported to its own requester as usual; the host notes in its thread why it ran nothing (`joined`). If the first ends without an answer, the second runs its own turn. A request in other words is not caught by this.
- **A turn** is one `run` of the assignee. Its result is `completed`, `failed(outcome)`, `needs_input(question)` or `continue`. If it handed out work, the node goes to `waiting` instead; when every child has settled and been reported, it goes to `resume` and runs once more with the children's results.
- **A child's question interrupts the wait.** When a child it waits on parks on a typed question (`needs_input` without cards), a `waiting` node goes to `resume` on the next tick and runs once with that question (`asked` in its run input) next to whatever has settled, told that the question is already in front of the person where it was asked and not to repeat it; its other children stay awaited, and once that turn ends it waits again. A child that settles while that turn runs is a result the turn has not seen, so the node still resumes once more when every child has settled. The question's inbox item is marked delivered with the dispatch, and only that turn carries the question: a later question, or every child settling, resumes the node again, and its later turns (an answer to its own question, a continuation, the final resume) do not repeat it. A restart that cuts that turn reruns it like any cut turn (§5), and the rerun carries the same question once more. If the question is answered or the child ends before the node can start, the node goes back to `waiting` instead of running with nothing new. That turn leaves the node's restart note for its final resume. A card park does not interrupt the wait, a `poll` root is never resumed for a question, and the question still expires on its own clock.
- **A typed question is a card too.** A direct child's typed question becomes a question card in its own conversation, in place of its `NEEDS INPUT:` line, with a reply field; it goes out as a question, so on a Team Cloud its copy reaches the asked person's inbox. An answer from the card, from the copy or from a line of the person's own in that conversation answers the parked node; Stop and an expired wait close the card (`stopped`, `expired`). The park is still a typed one: the requester is resumed with the question as above.
diff --git a/docs/team-cloud.md b/docs/team-cloud.md
index a796b4db98..44c4259a83 100644
--- a/docs/team-cloud.md
+++ b/docs/team-cloud.md
@@ -243,6 +243,10 @@ work, `session_search` (memory of the layer and the team's; conversations the tu
turn's layer folder back read-write for that conversation's boxes only (`botBox.lend`). Member layers are sibling
folders of the bot's own, never inside it, so no other turn of that bot can read them.
+The same request to one bot from two requesters is answered once only where the same people see both conversations
+(`shareAnswer`, see `docs/runtime-contract.md`): two bots working for Mira get one answer, while Mira's private work
+never gets the answer Ben's got, so each of them is answered on its own.
+
### Engine homes
The engines keep each conversation's transcript and session files in their HOME (`~/.claude/projects`,
diff --git a/server/cloud-team-one-answer.e2e.test.ts b/server/cloud-team-one-answer.e2e.test.ts
new file mode 100644
index 0000000000..bb9e2b07d6
--- /dev/null
+++ b/server/cloud-team-one-answer.e2e.test.ts
@@ -0,0 +1,118 @@
+// The same question from two teammates gets one answer, end to end on a Team Cloud. In Bob's private chat Scout asks
+// Bolt for a migration estimate and has Quill look into it too; Quill asks Bolt the same while Bolt still works on it.
+// Bolt answers once, Quill gets that answer, and Bolt's thread for Quill says why it ran no turn of its own. Olive asks
+// Bolt the same from her own private chat while it still works on it: Bob's answer is never hers, so Bolt answers her
+// separately. The engine is the synthetic Claude CLI playing a scripted plan through the real agents tools, so it proves
+// the routing, not a model's judgement.
+import { randomBytes } from "node:crypto";
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { afterAll, beforeAll, expect, it } from "vitest";
+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
+const OLIVE = { email: "[email protected]", role: "owner" as const };
+const BOB = { email: "[email protected]", role: "member" as const };
+const ENGINE = `process.env.FAKE_CLAUDE_ROOM_PLAN = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/plan.json";`;
+const ASK = "How many days would the database migration to the new hosting provider take, roughly?";
+const ASKED_AGAIN = "How many days would the database migration to the new hosting provider take roughly";
+const ANSWER = "About 15 working days, most of it testing.";
+const JOINED = "Another teammate asked this a moment ago, so it was answered once, for both of you:";
+const DONE = "Bolt estimates about 15 working days.";
+
+type Bot = { id: string; name: string; threadId: string; tasks?: Array<{ threadId: string; title: string; busy?: boolean }> };
+type Turn = { botId: string; turnIndex: number; system: string; prompt: unknown };
+
+let fx: CloudSendFixture, team: CloudTeamFixture;
+let olive = "", bob = "";
+let scout: Bot, quill: Bot, bolt: Bot, pip: Bot;
+
+const planPath = () => join(team.home, "plan.json");
+/** Bolt works on its answer until this file exists. */
+const boltGo = () => join(team.home, "bolt-go");
+const turns = (): Turn[] => existsSync(`${planPath()}.evidence.jsonl`)
+ ? readFileSync(`${planPath()}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line) as Turn) : [];
+const create = async (body: Record<string, unknown>) => {
+ const created = await team.as(olive, "POST", "/api/bots", body);
+ expect(created.status, JSON.stringify(created.body)).toBe(201);
+ return created.body.bot as Bot;
+};
+const messages = async (token: string, threadId: string) =>
+ ((await team.as(token, "GET", `/api/threads/${threadId}/messages?limit=200`)).body.messages ?? []) as Array<{ text?: string; tool?: { name: string } }>;
+const settled = async () => {
+ const bots = (await team.as(olive, "GET", "/api/bots?messages=0")).body.bots as Array<{ busy?: boolean; waitingForTeammates?: boolean; tasks?: Array<{ busy?: boolean; waitingForTeammates?: boolean }> }>;
+ return bots.every((one) => !one.busy && !(one.tasks ?? []).some((task) => task.busy || task.waitingForTeammates));
+};
+const boltRuns = () => turns().filter((turn) => turn.botId === bolt.id).length;
+const boltTasks = async (token: string) =>
+ ((await team.as(token, "GET", "/api/bots")).body.bots as Bot[]).find((bot) => bot.id === bolt.id)?.tasks ?? [];
+/** The notes in Bolt's threads this person reads that a request waited for another's answer. */
+const joinedNotes = async (token: string) => (await Promise.all((await boltTasks(token)).map((task) => messages(token, task.threadId).catch(() => []))))
+ .flat().filter((message) => message.tool?.name.startsWith("notice: Another teammate asked the same a moment ago")).length;
+const privateChat = async (token: string, bot: Bot, title: string) => {
+ const opened = await team.as(token, "POST", `/api/bots/${bot.id}/tasks`, { title });
+ expect(opened.status, JSON.stringify(opened.body)).toBe(201);
+ return opened.body.task.threadId as string;
+};
+
+beforeAll(async () => {
+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-3", name: "Acme", engine: ENGINE } });
+ team = fx.team!;
+ olive = (await team.pair(OLIVE)).token!;
+ bob = (await team.pair(BOB)).token!;
+ scout = await create({ name: "Scout", title: "Assistant", section: "Support", reportsTo: BOB.email });
+ quill = await create({ name: "Quill", title: "Analyst", section: "Support", reportsTo: BOB.email });
+ bolt = await create({ name: "Bolt", title: "Developer", section: "Dev", reportsTo: OLIVE.email });
+ pip = await create({ name: "Pip", title: "Assistant", section: "Dev", reportsTo: OLIVE.email });
+ writeFileSync(planPath(), JSON.stringify({
+ [scout.id]: { turns: [
+ { steps: [
+ { arguments: { bot_ids: ["Bolt"], message: ASK, consult: true, reason: "Bob asked for the estimate" } },
+ { arguments: { bot_ids: ["Quill"], message: "Get Bolt's estimate for the database migration too.", reason: "Bob asked Quill to look into it" } },
+ ], reply: "Asked Bolt and Quill." },
+ { reply: DONE },
+ ] },
+ [quill.id]: { turns: [
+ { steps: [{ arguments: { bot_ids: ["Bolt"], message: ASKED_AGAIN, consult: true, reason: "Scout asked for Bolt's estimate" } }], reply: "Asked Bolt." },
+ { reply: "Bolt's estimate is in." },
+ ] },
+ [pip.id]: { turns: [
+ { steps: [{ arguments: { bot_ids: ["Bolt"], message: ASK, consult: true, reason: "Olive asked for the estimate" } }], reply: "Asked Bolt." },
+ { reply: "Bolt answered." },
+ ] },
+ [bolt.id]: { reply: ANSWER, gateFile: boltGo() },
+ }));
+}, hostTimeout(120_000));
+
+afterAll(async () => {
+ await fx?.close();
+});
+
+it("answers the same question from two of Bob's teammates once, and Olive's, which Bob's answer may not reach, on its own", async () => {
+ const bobChat = await privateChat(bob, scout, "Migration estimate");
+ const sent = await team.as(bob, "POST", `/api/bots/${scout.id}/messages`, { text: "How long will the migration take? Ask Bolt, and have Quill look too.", threadId: bobChat });
+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);
+ // Quill asked while Bolt still works on Scout's question: its request waits for that answer.
+ await expect.poll(() => joinedNotes(bob), { timeout: 90_000 }).toBe(1);
+
+ const oliveChat = await privateChat(olive, pip, "Estimate");
+ const asked = await team.as(olive, "POST", `/api/bots/${pip.id}/messages`, { text: "Ask Bolt how long the migration takes.", threadId: oliveChat });
+ expect(asked.status, JSON.stringify(asked.body)).toBe(202);
+ // Olive asks the same while Bolt still works on it, but Bob's answer is never hers: Bolt works on hers too.
+ await expect.poll(async () => (await boltTasks(olive)).some((task) => task.busy), { timeout: 90_000 }).toBe(true);
+
+ writeFileSync(boltGo(), "go");
+ await expect.poll(async () => (await messages(bob, bobChat)).some((message) => message.text === DONE), { timeout: 90_000 }).toBe(true);
+ await expect.poll(async () => (await messages(olive, oliveChat)).some((message) => message.text === "Bolt answered."), { timeout: 90_000 }).toBe(true);
+ await expect.poll(settled, { timeout: 20_000 }).toBe(true);
+
+ expect(boltRuns(), "Bolt worked out the estimate once for Bob and once for Olive").toBe(2);
+ const quillResumed = JSON.stringify(turns().find((turn) => turn.botId === quill.id && turn.turnIndex === 1)!.prompt);
+ expect(quillResumed).toContain(JOINED);
+ expect(quillResumed).toContain(ANSWER);
+ const pipResumed = JSON.stringify(turns().find((turn) => turn.botId === pip.id && turn.turnIndex === 1)!.prompt);
+ expect(pipResumed).toContain(ANSWER);
+ expect(pipResumed).not.toContain(JOINED);
+ expect(await joinedNotes(bob)).toBe(1);
+ expect(await joinedNotes(olive)).toBe(0);
+}, hostTimeout(240_000));
diff --git a/server/coordinator.ts b/server/coordinator.ts
index 73a176ea27..2ce6c5bec6 100644
--- a/server/coordinator.ts
+++ b/server/coordinator.ts
@@ -131,6 +131,11 @@ export interface CoordinatorHost {
chiefOf(address: RoomAddress): boolean;
/** What the cut turn already did outward (sent, posted, paid): a turn that acted outward is not run again. */
outward?(node: HandoffView): string[];
+ /** Whether `joiner`'s requester may read the answer `first` gives its own (the same people see both conversations),
+ * so the same request from two teammates is answered once. Absent: never. */
+ shareAnswer?(first: HandoffView, joiner: HandoffView): boolean;
+ /** `node` waits for `first`'s answer instead of running its own turn (only ever a request outside a room). */
+ joined?(node: HandoffView, first: HandoffView): void;
}
export interface Coordinator {
diff --git a/server/host/share-answer.test.ts b/server/host/share-answer.test.ts
new file mode 100644
index 0000000000..4cf4aedd4b
--- /dev/null
+++ b/server/host/share-answer.test.ts
@@ -0,0 +1,52 @@
+import { join } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import type { HandoffView } from "../coordinator.ts";
+import { createShareAnswer } from "./share-answer.ts";
+
+const PRIVATE = join("/data", "task-workspaces");
+const node = (id: string, parentId: string | undefined, threadId: string): HandoffView => ({
+ id, rootId: "root", ...(parentId ? { parentId } : {}), threadId, botId: "bolt", key: "bolt", text: "", createdAt: 0, status: "running",
+ result: "", reported: false, executions: 1, approvalGranted: false, kind: "work", restarts: 0, mode: "consult", reply: "resume",
+});
+
+function rule(over: { audiences?: Record<string, string>; pinned?: Record<string, string | null>; botFolder?: string } = {}) {
+ const asked: Record<string, string> = { "scout-turn": "scout-chat", "quill-turn": "quill-chat" };
+ return createShareAnswer({
+ askedFrom: (one) => (one.parentId ? asked[one.parentId] : undefined),
+ audienceOf: (threadId) => over.audiences?.[threadId] ?? "member:[email protected]",
+ pinned: (_botId, threadId) => over.pinned?.[threadId],
+ botFolder: () => over.botFolder,
+ privateFolders: PRIVATE,
+ });
+}
+const first = node("a", "scout-turn", "bolt-for-scout");
+const joiner = node("b", "quill-turn", "bolt-for-quill");
+
+describe("whether a bot's answer to one requester may answer another's same request", () => {
+ it("shares it where the same people see both conversations and the bot works in the same folder", () => {
+ expect(rule()(first, joiner)).toBe(true);
+ expect(rule({ botFolder: "/work/site" })(first, joiner)).toBe(true);
+ expect(rule({ pinned: { "bolt-for-scout": "/work/site" }, botFolder: "/work/site" })(first, joiner)).toBe(true);
+ });
+
+ it("counts two conversations' own private folders as one: neither holds anything of a requester's", () => {
+ expect(rule({ pinned: { "bolt-for-scout": join(PRIVATE, "bolt", "bolt-for-scout"), "bolt-for-quill": null } })(first, joiner)).toBe(true);
+ });
+
+ it("never shares it with someone who may not read the conversation it was asked from", () => {
+ expect(rule({ audiences: { "scout-chat": "member:[email protected]", "quill-chat": "member:[email protected]" } })(first, joiner)).toBe(false);
+ expect(rule({ audiences: { "scout-chat": "member:[email protected]", "quill-chat": "team" } })(first, joiner)).toBe(false);
+ });
+
+ it("never shares an answer the bot worked out in another folder: a question about files is answered from the files there", () => {
+ expect(rule({ pinned: { "bolt-for-scout": "/work/site", "bolt-for-quill": "/work/app" } })(first, joiner)).toBe(false);
+ expect(rule({ pinned: { "bolt-for-scout": "/work/site" } })(first, joiner)).toBe(false);
+ });
+
+ it("never shares one whose requester is unknown", () => {
+ expect(rule()(node("a", undefined, "bolt-for-scout"), joiner)).toBe(false);
+ expect(rule()(first, node("b", "gone-turn", "bolt-for-quill"))).toBe(false);
+ });
+});
diff --git a/server/host/share-answer.ts b/server/host/share-answer.ts
new file mode 100644
index 0000000000..51b425e734
--- /dev/null
+++ b/server/host/share-answer.ts
@@ -0,0 +1,31 @@
+// Whether a bot's answer to one requester may also answer another requester's same request (the coordinator's
+// shareAnswer): only where the same people see both requesters' conversations, and only when the bot works on both in
+// the same folder, since a question about files is answered from the files there. A conversation's own private folder
+// starts with nothing of either requester's, so two of those count as one.
+import { sep } from "node:path";
+
+import type { HandoffView } from "../coordinator.ts";
+
+export interface ShareAnswerDeps {
+ /** The conversation a request came from (its requester's), if it is known. */
+ askedFrom(node: HandoffView): string | undefined;
+ audienceOf(threadId: string): string;
+ /** The folder pinned to a bot's conversation: a path, null for its own private folder, undefined while unpinned. */
+ pinned(botId: string, threadId: string): string | null | undefined;
+ /** The bot's project folder, which an unpinned conversation takes. */
+ botFolder(botId: string): string | undefined;
+ /** Where conversations' own private folders live. */
+ privateFolders: string;
+}
+
+export function createShareAnswer(deps: ShareAnswerDeps): (first: HandoffView, joiner: HandoffView) => boolean {
+ const folder = (node: HandoffView): string | null => {
+ const pinned = deps.pinned(node.botId, node.threadId);
+ const cwd = pinned === undefined ? deps.botFolder(node.botId) ?? null : pinned;
+ return cwd && !cwd.startsWith(deps.privateFolders + sep) ? cwd : null;
+ };
+ return (first, joiner) => {
+ const a = deps.askedFrom(first), b = deps.askedFrom(joiner);
+ return a !== undefined && b !== undefined && deps.audienceOf(a) === deps.audienceOf(b) && folder(first) === folder(joiner);
+ };
+}
diff --git a/server/index.ts b/server/index.ts
index 7631f99f61..96bbdd6636 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -628,7 +628,7 @@ import { createReactions, withReactionNotes, type Reactor } from "./reactions.ts
import { createPersonReplies } from "./person-replies.ts";
import { personKey, relayedPersonKey } from "./person-key.ts";
import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";
-import { createDevsReports } from "./host/devs-reports.ts"; import { bugReportEndpoint, devsReportSender } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts";
+import { createDevsReports } from "./host/devs-reports.ts"; import { bugReportEndpoint, devsReportSender } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";
import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, privateHandBack, withPerson } from "./host/acting-person.ts";
import { createThreadRoutes } from "./routes/threads.ts";
import { createWebhookRoutes } from "./routes/webhooks.ts";
@@ -4156,6 +4156,8 @@ const coordinator: Coordinator = createCoordinator({
}
return outwardActions(turnRows(node));
},
+ shareAnswer: createShareAnswer({ askedFrom: (node) => (node.parentId ? coordinator.node(node.parentId)?.threadId : undefined), audienceOf: teamHost.audienceOf, pinned: (botId, threadId) => store.taskByThread(botId, threadId)?.cwd, botFolder: (botId) => store.bot(botId)?.cwd, privateFolders: TASK_WORKSPACES_DIR }),
+ joined: (node) => { store.appendMessage(node.threadId, { role: "bot", kind: "activity", tool: { name: "notice: Another teammate asked the same a moment ago, so this gets that answer instead of a second one.", ok: true } }); },
},
});
threadsAwaitingTeammates = () => coordinator.awaitingTeammateThreads();
diff --git a/server/runtime-coordinator.test.ts b/server/runtime-coordinator.test.ts
index 6200893548..eda80e0310 100644
--- a/server/runtime-coordinator.test.ts
+++ b/server/runtime-coordinator.test.ts
@@ -2,7 +2,7 @@ import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import type { BeginTurnRequest, ComposedTurn, CoordinatorHost, HandoffOpener, HandoffOptions, HandoffView, HostTurnResult } from "./coordinator.ts";
import type { RoomAddress } from "./coordinator.ts";
@@ -412,6 +412,175 @@ describe("RuntimeCoordinator: refusals in the legacy words", () => {
});
});
+describe("RuntimeCoordinator: one answer to the same request from two teammates", () => {
+ const lead: RoomAddress = { botId: "lead", threadId: "lead-chat" };
+ const builderForLead: RoomAddress = { botId: "builder", threadId: "builder-work-2" };
+ const ASK = "How many days would the database migration to the new hosting provider take, roughly?";
+ const ASKED_AGAIN = "How many days would the database migration to the new hosting provider take roughly";
+ const sharing = (w: World, joined: Array<{ node: string; first: string }> = []) => {
+ w.host.shareAnswer = () => true;
+ w.host.joined = (node, first) => { joined.push({ node: node.id, first: first.id }); };
+ return joined;
+ };
+ const settledChild = async (w: World, id: string) => {
+ await vi.waitFor(() => expect(w.coordinator.node(id)?.status).toBe("completed"), { timeout: 5_000, interval: 50 });
+ return w.coordinator.node(id)!;
+ };
+
+ it("gives the second teammate the first one's answer while the bot works on it: one turn, one answer, both resumed", async () => {
+ const w = world(hold);
+ const joined = sharing(w);
+ const first = send(w, chief, "gen-1", undefined, builder, ASK);
+ const second = send(w, lead, "gen-2", undefined, builderForLead, ASKED_AGAIN);
+ expect(second.duplicate).toBe(false);
+ w.coordinator.tick(); await flush();
+ expect(w.host.runs.filter((run) => run.node.botId === "builder").map((run) => run.node.id)).toEqual([first.node.id]);
+ expect(joined).toEqual([{ node: second.node.id, first: first.node.id }]);
+ await w.host.release(first.node.id, { ok: true, text: "About 15 days." });
+ w.coordinator.tick(); await flush();
+ const answered = await settledChild(w, second.node.id);
+ expect(answered.result).toBe("Another teammate asked this a moment ago, so it was answered once, for both of you:\nAbout 15 days.");
+ expect(w.coordinator.node(first.node.id)?.result).toBe("About 15 days.");
+ expect(w.host.runs.filter((run) => run.node.botId === "builder")).toHaveLength(1);
+ expect(w.host.reports.map((report) => report.child.id).sort()).toEqual([first.node.id, second.node.id].sort());
+ });
+
+ it("gives the answer at once when it came while the second request waited for its turn", async () => {
+ const w = world(hold);
+ sharing(w);
+ const first = send(w, chief, "gen-1", undefined, builder, ASK);
+ w.coordinator.tick(); await flush();
+ w.host.busyAnswer = (node) => node.id !== first.node.id;
+ await sleep(2);
+ const second = send(w, lead, "gen-2", undefined, builderForLead, ASK);
+ w.coordinator.tick(); await flush();
+ expect(w.coordinator.node(second.node.id)?.status).toBe("queued");
+ await sleep(2);
+ await w.host.release(first.node.id, { ok: true, text: "About 15 days." });
+ w.host.busyAnswer = () => false;
+ w.coordinator.tick(); await flush();
+ expect((await settledChild(w, second.node.id)).result).toContain("About 15 days.");
+ expect(w.host.runs.filter((run) => run.node.botId === "builder")).toHaveLength(1);
+ });
+
+ it("keeps the request that waits for the answer out of the stall window", async () => {
+ const w = world(hold, { turnStallMs: 1_500 });
+ sharing(w);
+ const first = send(w, chief, "gen-1", undefined, builder, ASK);
+ const second = send(w, lead, "gen-2", undefined, builderForLead, ASK);
+ w.coordinator.tick(); await flush();
+ for (let waited = 0; waited < 2_500; waited += 100) {
+ w.coordinator.progress(builder.threadId);
+ w.coordinator.tick();
+ await sleep(100);
+ }
+ expect(w.coordinator.node(second.node.id)?.status).toBe("running");
+ await w.host.release(first.node.id, { ok: true, text: "About 15 days." });
+ expect((await settledChild(w, second.node.id)).result).toContain("About 15 days.");
+ });
+
+ it("stops waiting when its work is stopped, while the first goes on", async () => {
+ const w = world(hold);
+ sharing(w);
+ const first = send(w, chief, "gen-1", undefined, builder, ASK);
+ const second = send(w, lead, "gen-2", undefined, builderForLead, ASK);
+ w.coordinator.tick(); await flush();
+ w.coordinator.cancelDirect(builderForLead.threadId);
+ await flush();
+ expect(w.coordinator.node(second.node.id)?.status).toBe("cancelled");
+ expect(w.coordinator.node(first.node.id)?.status).toBe("running");
+ await w.host.release(first.node.id, { ok: true, text: "About 15 days." });
+ expect(w.coordinator.node(first.node.id)).toMatchObject({ status: "completed", result: "About 15 days." });
+ expect(w.coordinator.node(second.node.id)?.status).toBe("cancelled");
+ });
+
+ it("never reuses an answer given before the request was asked: things may have changed since", async () => {
+ const w = world();
+ sharing(w);
+ const first = send(w, chief, "gen-1", undefined, builder, ASK);
+ w.coordinator.tick(); await flush();
+ expect(w.coordinator.node(first.node.id)?.status).toBe("completed");
+ await sleep(2);
+ const second = send(w, lead, "gen-2", undefined, builderForLead, ASK);
+ w.coordinator.tick(); await flush();
+ expect((await settledChild(w, second.node.id)).result).toBe("builder done");
+ expect(w.host.runs.filter((run) => run.node.botId === "builder")).toHaveLength(2);
+ });
+
+ it.each<[string, (w: World) => void]>([
+ ["a different request", (w) => {
+ send(w, chief, "gen-1", undefined, builder, ASK);
+ send(w, lead, "gen-2", undefined, builderForLead, "How many days would the database migration to the new hosting provider cost, roughly?");
+ }],
+ ["a requester who may not read the first answer", (w) => {
+ w.host.shareAnswer = () => false;
+ send(w, chief, "gen-1", undefined, builder, ASK);
+ send(w, lead, "gen-2", undefined, builderForLead, ASK);
+ }],
+ ["a short request, which two conversations can mean two ways", (w) => {
+ send(w, chief, "gen-1", undefined, builder, "Any update on this one?");
+ send(w, lead, "gen-2", undefined, builderForLead, "Any update on this one?");
+ }],
+ ["a request asked at another approval level", (w) => {
+ w.host.levelOf = (_target, source) => ({ level: source?.botId === "lead" ? "full" : "ask" });
+ send(w, chief, "gen-1", undefined, builder, ASK);
+ send(w, lead, "gen-2", undefined, builderForLead, ASK);
+ }],
+ ["a request with another finish line", (w) => {
+ send(w, chief, "gen-1", undefined, builder, ASK);
+ begun(w, lead, "gen-2");
+ w.coordinator.enqueue(lead, "gen-2", undefined, builderForLead, ASK, { doneWhen: "A number of days, with the reason." });
+ }],
+ ["the requester's own second ask, which may mean to ask again", (w) => {
+ send(w, chief, "gen-1", undefined, builder, ASK);
+ send(w, chief, "gen-1", undefined, builderForLead, ASKED_AGAIN);
+ }],
+ ["a request in a room to one outside it", (w) => {
+ send(w, chief, "gen-1", undefined, builder, ASK);
+ send(w, lead, "gen-2", undefined, inRoom("builder"), ASK);
+ }],
+ ["a request outside a room to one in it", (w) => {
+ send(w, chief, "gen-1", undefined, inRoom("builder"), ASK);
+ send(w, lead, "gen-2", undefined, builderForLead, ASK);
+ }],
+ ])("never joins %s: the bot works on each", async (_name, ask) => {
+ const w = world(hold);
+ sharing(w);
+ ask(w);
+ w.coordinator.tick(); await flush();
+ expect(w.host.runs.filter((run) => run.node.botId === "builder")).toHaveLength(2);
+ });
+
+ it("works on the request itself when the first one ends without an answer", async () => {
+ const w = world(hold);
+ sharing(w);
+ const first = send(w, chief, "gen-1", undefined, builder, ASK);
+ const second = send(w, lead, "gen-2", undefined, builderForLead, ASK);
+ w.coordinator.tick(); await flush();
+ await w.host.release(first.node.id, { ok: false, text: "The provider failed." });
+ w.coordinator.tick(); await flush();
+ await vi.waitFor(() => expect(w.host.runs.map((run) => run.node.id)).toContain(second.node.id), { timeout: 5_000, interval: 50 });
+ });
+
+ it("never waits on a request still to be answered in its own conversation, which could only go on after it", async () => {
+ const w = world((node) => node.botId === "tester" ? "hold" : undefined);
+ sharing(w);
+ const first = send(w, chief, "gen-1", undefined, builder, ASK);
+ w.coordinator.tick();
+ const check = send(w, builder, "gen-1", first.node.id, tester, "Check the database size for the estimate.").node;
+ await flush();
+ expect(w.coordinator.node(first.node.id)?.status).toBe("waiting");
+ const second = send(w, lead, "gen-2", undefined, builder, ASK);
+ w.coordinator.tick(); await flush();
+ expect(w.host.runs.map((run) => run.node.id)).toContain(second.node.id);
+ await w.host.release(check.id, { ok: true, text: "About 40 GB." });
+ await vi.waitFor(() => {
+ w.coordinator.tick();
+ expect(w.coordinator.node(first.node.id)?.status).toBe("completed");
+ }, { timeout: 5_000, interval: 50 });
+ });
+});
+
describe("RuntimeCoordinator: the run adapter", () => {
it("parks a turn that ends on NEEDS INPUT, takes the person's answer, and carries it into the next turn", async () => {
let turns = 0;
diff --git a/server/runtime-coordinator.ts b/server/runtime-coordinator.ts
index a061d5f077..4091eead02 100644
--- a/server/runtime-coordinator.ts
+++ b/server/runtime-coordinator.ts
@@ -8,6 +8,7 @@ import { importLegacyDelegations, importLegacyHandoffs, type LegacyThreadResolve
import { openRuntimeStore, type RuntimeStore } from "./runtime/store.ts";
import { childrenSince, clip, isTerminal, path } from "./runtime/tree.ts";
import type { Assignment, EndResult, Origin, Owner, Reply, Requester, RunInput, RunResult, StatusView, TurnRunner } from "./runtime/types.ts";
+import { sameRequest } from "./same-request.ts";
const NOT_RUNNING = "The originating room task is no longer running";
const WRONG_SPEAKER = "The handoff belongs to a different room speaker";
@@ -94,6 +95,10 @@ export function view(a: Assignment, parent?: Assignment): HandoffView {
return node;
}
+/** How often a request that joined another looks at it. */
+const JOIN_POLL_MS = 1_000;
+const JOINED_NOTE = "Another teammate asked this a moment ago, so it was answered once, for both of you:";
+
export class RuntimeCoordinator implements Coordinator {
private readonly host: CoordinatorHost;
private readonly store: RuntimeStore;
@@ -470,6 +475,10 @@ export class RuntimeCoordinator implements Coordinator {
}
private async run(a: Assignment, input: RunInput, signal: AbortSignal): Promise<RunResult> {
+ const first = input.turn === "first" || input.turn === "rerun" ? this.answeredElsewhere(a) : undefined;
+ if (first && input.turn === "first") this.host.joined?.(this.project(a), this.project(first));
+ const answer = first ? await this.joinAnswer(a, first.id, signal) : undefined;
+ if (answer) return answer;
const parent = a.parentId ? this.store.get(a.parentId) : undefined;
const node = view(a, parent);
const resumed = input.turn === "resume";
@@ -501,6 +510,43 @@ export class RuntimeCoordinator implements Coordinator {
return this.store.all({ nonTerminal: true });
}
+ /** The same request to the same bot from another requester (same words, mode, approval level and finish line), asked
+ * earlier and still being answered when this one was asked, whose answer this one's requester may read
+ * (host.shareAnswer): two teammates asking the same thing at the same time get one answer. An answer from before this
+ * request was asked is never reused, as things may have changed since. Rooms keep their own turn order, and a request
+ * still to be answered in this one's conversation could only go on after it: neither is joined. */
+ private answeredElsewhere(a: Assignment): Assignment | undefined {
+ const share = this.host.shareAnswer;
+ if (!share || !a.parentId || a.mode === "notify" || a.rework || a.assignee.destination.groupId !== undefined) return undefined;
+ const mine = this.project(a);
+ // In the order they were asked, each still open when this one was asked.
+ const rows = this.store.all({ openSince: a.createdAt });
+ const at = rows.findIndex(o => o.id === a.id);
+ return rows.slice(0, Math.max(at, 0))
+ .filter(o => o.parentId !== undefined && o.parentId !== a.parentId && !o.rework && o.mode === a.mode
+ && o.level === a.level && o.doneWhen === a.doneWhen
+ && o.assignee.botId === a.assignee.botId && o.assignee.destination.groupId === undefined
+ && (o.status === "completed" || (!isTerminal(o) && o.assignee.destination.threadId !== a.assignee.destination.threadId))
+ && sameRequest(o.brief, a.brief))
+ .find(o => share(this.project(o), mine));
+ }
+
+ /** Waits for the request `firstId` to be answered, keeping this one's turn out of the stall window, and ends with that
+ * answer. Undefined when it ends without one: this request is then worked on as usual. */
+ private async joinAnswer(a: Assignment, firstId: string, signal: AbortSignal): Promise<RunResult | undefined> {
+ this.log(`${a.id} joins ${firstId}: the same request to ${a.assignee.botId}`);
+ // One listener for the whole wait, however long the first takes.
+ const stopped = new Promise<void>(resolve => signal.addEventListener("abort", () => resolve(), { once: true }));
+ for (;;) {
+ if (signal.aborted) return { kind: "failed", outcome: "stopped", text: "" };
+ const first = this.store.get(firstId);
+ if (first?.status === "completed") return { kind: "completed", text: `${JOINED_NOTE}\n${first.result.replace(`${JOINED_NOTE}\n`, "")}` };
+ if (!first || isTerminal(first)) return undefined;
+ this.runtime.progress(a.id);
+ await Promise.race([stopped, new Promise<void>(resolve => setTimeout(resolve, JOIN_POLL_MS))]);
+ }
+ }
+
private parkedIn(threadId: string): Assignment | undefined {
return this.live().find(n => n.status === "needs_input" && n.assignee.destination.threadId === threadId);
}
diff --git a/server/same-request.test.ts b/server/same-request.test.ts
new file mode 100644
index 0000000000..c1050e657e
--- /dev/null
+++ b/server/same-request.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+
+import { sameRequest } from "./same-request.ts";
+
+describe("whether two requests to one bot ask the same thing", () => {
+ it("reads a question passed on twice, in other case, punctuation or spacing, as one", () => {
+ expect(sameRequest(
+ "How many days would the database migration to the new hosting provider take, roughly?",
+ "how many DAYS would the database migration to the new hosting provider take roughly",
+ )).toBe(true);
+ expect(sameRequest(
+ "Standing rule from the person, decided today: put reminders in the task app, never in the calendar.",
+ "Standing rule from the person (decided today): put reminders in the task app - never in the calendar!",
+ )).toBe(true);
+ });
+
+ const ASK = "How many days would the database migration to the new hosting provider take, roughly?";
+ it.each([
+ ["one word for another", ASK, "How many days would the database migration to the new hosting provider cost, roughly?"],
+ ["another subject", "Please draft the reply to the customer about the late invoice and send it to me first.",
+ "Please draft the reply to the customer about the refund and send it to me first."],
+ ["a word more", ASK, "How many days would the database migration to the new hosting provider not take, roughly?"],
+ ["a number", ASK, "How many days would the database migration to the 2 new hosting providers take, roughly?"],
+ ["digits run together", `${ASK} 5-6`, `${ASK} 56`],
+ ])("keeps two requests apart that differ by %s, however alike they read", (_name, asked, other) => {
+ expect(sameRequest(asked, other)).toBe(false);
+ });
+
+ it("never joins short requests, which mean different things in different conversations", () => {
+ expect(sameRequest("Any update on this one?", "Any update on this one?")).toBe(false);
+ expect(sameRequest("", "")).toBe(false);
+ });
+});
diff --git a/server/same-request.ts b/server/same-request.ts
new file mode 100644
index 0000000000..52439aa7d4
--- /dev/null
+++ b/server/same-request.ts
@@ -0,0 +1,16 @@
+// Whether two requests to the same bot ask the same thing: the same words in the same order, whatever their case,
+// punctuation or spacing, as when two teammates pass on one question in the person's words. Requests that differ by
+// any word (an amount, a date, "not", "cost" for "take") are two requests, however alike they read: answering one
+// with the other's answer would be wrong, while answering both only costs a second turn. Only a long enough request
+// counts: a short "any update?" from two conversations means two things.
+
+/** At least this many characters of words, once case, punctuation and spacing are set aside. */
+export const SAME_REQUEST_MIN_CHARS = 40;
+
+/** Punctuation becomes a space, so "5-6 days" never reads as "56 days". */
+const words = (text: string) => text.toLowerCase().replace(/[^\p{L}\p{N}\s]+/gu, " ").replace(/\s+/g, " ").trim();
+
+export function sameRequest(a: string, b: string): boolean {
+ const left = words(a);
+ return left.length >= SAME_REQUEST_MIN_CHARS && left === words(b);
+}