Skip to content

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

Rooms: a bot picked from the @ list is the one reached, even when two share its name

milind-sonid455f768f801
diff --git a/server/channel-queue.ts b/server/channel-queue.ts
index 9a4a646f4c..9226ef8c48 100644
--- a/server/channel-queue.ts
+++ b/server/channel-queue.ts
@@ -17,6 +17,8 @@ export interface ChannelQueueItem {
sender?: ResolvedSender;
trigger?: UsageTrigger;
reaction?: string;
+ /** Bot ids picked from the @ list; the turn that drains this line reads its @names with them. */
+ mentions?: string[];
queuedAt: number;
}
@@ -62,6 +64,7 @@ export function queueChannelMessage(
sender?: ResolvedSender;
trigger?: UsageTrigger;
reaction?: string;
+ mentions?: string[];
} = {},
): QueuedChannelMessage {
const entry = queues.get(threadId) ?? { groupId, items: [] };
@@ -76,6 +79,7 @@ export function queueChannelMessage(
sender: options.sender,
trigger: options.trigger,
...(options.reaction ? { reaction: options.reaction } : {}),
+ ...(options.mentions?.length ? { mentions: options.mentions } : {}),
queuedAt: Date.now(),
};
saveChatFollowup({ id: item.id, kind: "channel", ownerId: groupId, threadId, payload: item });
diff --git a/server/direct-send.ts b/server/direct-send.ts
index c1fe4b33d9..b298626c6c 100644
--- a/server/direct-send.ts
+++ b/server/direct-send.ts
@@ -20,6 +20,8 @@ export interface DirectSendInput {
app?: { context?: string; fromApp?: Message["fromApp"]; pointed?: Message["pointed"] };
/** Sent while the bot works: steer into the running turn, queue after it, or restart it (shared/follow-up.ts). */
followUp?: FollowUp;
+ /** Bot ids the person picked from the @ list. */
+ mentions?: string[];
}
export type DirectSendReceipt =
diff --git a/server/index.ts b/server/index.ts
index 8d66da0e6f..9a1f3ee9af 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -4358,13 +4358,13 @@ async function interruptHeldMember(groupId: string, botId: string): Promise<void
}
/** Applied at accept, before the message queues behind a busy room, so a stop reaches a member working now. */
-function applyRoomHoldsFromMessage(groupId: string, text: string): void {
+function applyRoomHoldsFromMessage(groupId: string, text: string, mentions?: readonly string[]): void {
const group = store.group(groupId);
if (!group || group.dm) return;
const members = group.memberIds
.map((id) => store.bot(id))
.filter((bot): bot is BotRecord => Boolean(bot) && !bot!.hidden);
- const mentioned = mentionedBots(text, members).map((bot) => bot.id);
+ const mentioned = mentionedBots(text, members, mentions).map((bot) => bot.id);
const change = applyHoldDirective(group.holds, classifyHoldDirective(text, mentioned), members.map((bot) => bot.id), Date.now());
if (!change.held.length && !change.released.length) return;
store.patchGroup(groupId, { holds: change.holds });
@@ -7256,7 +7256,7 @@ function drainQueuedSendsNow() {
new Promise<void>((resolve, reject) => {
void startTurn(botId, prompt, {
threadId, userMessage, excludeMessageIds: excludeIds, unattended, onTurnSettled: resolve, allowRoomTurnElsewhere: !head.peerAsk,
- trigger: queuedTurnTrigger(head), ...(head.origin ? { origin: head.origin } : {}),
+ trigger: queuedTurnTrigger(head), ...(head.origin ? { origin: head.origin } : {}), ...(head.mentions ? { mentions: head.mentions } : {}),
}).catch((err) => {
const why = err instanceof Error ? err.message : String(err);
const chief = head.peerAsk?.incident ? store.bot(botId) : null;
@@ -7276,7 +7276,7 @@ function drainQueuedSendsNow() {
);
}
-async function startOrQueueDirectMessage(botId: string, threadId: string, text: string, replyTo?: ReplyTarget, sendId?: string, sender?: ResolvedSender, trigger?: UsageTrigger, via?: "call", callId?: string, dataContext?: DataContext, app?: { context?: string; fromApp?: Message["fromApp"]; pointed?: Message["pointed"] }) {
+async function startOrQueueDirectMessage(botId: string, threadId: string, text: string, replyTo?: ReplyTarget, sendId?: string, sender?: ResolvedSender, trigger?: UsageTrigger, via?: "call", callId?: string, dataContext?: DataContext, app?: { context?: string; fromApp?: Message["fromApp"]; pointed?: Message["pointed"] }, mentions?: string[]) {
const decision = admit("direct", {}, {
atCapacity: botAtThreadCapacity(botId, threadId),
threadBusy: threadBusy(botId, threadId),
@@ -7287,7 +7287,7 @@ async function startOrQueueDirectMessage(botId: string, threadId: string, text:
const queued = queueSteeredMessage(botId, threadId, text, {
replyToId: replyTo?.id,
sendId,
- dataContext, fromApp: app?.fromApp,
+ dataContext, fromApp: app?.fromApp, mentions,
reason: decision.reason,
prompt: (app?.context ?? "") + personPrompt(threadId, sender, promptWithReply(promptWithDataContext(text, dataContext), replyTo, userNameFor(threadId))),
sender,
@@ -7298,7 +7298,7 @@ async function startOrQueueDirectMessage(botId: string, threadId: string, text:
});
return { ok: true as const, queued: true as const, queueId: queued.id, threadId, reason: decision.reason };
}
- const message = await startTurn(botId, text, { threadId, replyTo, sendId, sender, trigger, via, callId, dataContext, app, allowRoomTurnElsewhere: true });
+ const message = await startTurn(botId, text, { threadId, replyTo, sendId, sender, trigger, via, callId, dataContext, app, mentions, allowRoomTurnElsewhere: true });
return { ok: true as const, threadId, message };
}
@@ -7328,7 +7328,7 @@ async function acceptDirectSend(
input: DirectSendInput,
guardedStart?: (currentAtStart: BotRecord) => Promise<DirectSendReceipt>,
): Promise<DirectSendReceipt> {
- const { botId, threadId, text, sendId, replyTo, sender, trigger, via, callId, dataContext, personPresent, app, followUp } = input;
+ const { botId, threadId, text, sendId, replyTo, sender, trigger, via, callId, dataContext, personPresent, app, followUp, mentions } = input;
const refused = directSendRefusal(botId, threadId);
if (refused) throw refused;
return sendSequencer.run(
@@ -7434,16 +7434,16 @@ async function acceptDirectSend(
store.setTaskAskedAt(botId, threadId, message.at);
handoffs.steered(threadId, steerTarget, instance?.instanceId, message.id);
signInSettle.answerInChat(botId, threadId);
- if (personsOwn) personFirst.wait(threadId, { requeue: (note) => void queueSteeredMessage(current.id, threadId, text, { prompt: note ? `${queuedPrompt}\n\n${note}` : queuedPrompt, rowId: message.id, first: true, queuedAt: message.at, replyToId: replyTo?.id, dataContext, sender, trigger, via, callId }) });
+ if (personsOwn) personFirst.wait(threadId, { requeue: (note) => void queueSteeredMessage(current.id, threadId, text, { prompt: note ? `${queuedPrompt}\n\n${note}` : queuedPrompt, rowId: message.id, first: true, queuedAt: message.at, replyToId: replyTo?.id, dataContext, sender, trigger, via, callId, mentions }) });
return { ok: true as const, steered: true as const, threadId, message };
}
if (!current.busy) {
- return startOrQueueDirectMessage(botId, threadId, text, replyTo, sendId, sender, trigger, via, callId, dataContext, app);
+ return startOrQueueDirectMessage(botId, threadId, text, replyTo, sendId, sender, trigger, via, callId, dataContext, app, mentions);
}
const queued = queueSteeredMessage(current.id, threadId, text, {
replyToId: replyTo?.id,
sendId,
- dataContext, fromApp: app?.fromApp,
+ dataContext, fromApp: app?.fromApp, mentions,
prompt: queuedPrompt,
sender,
trigger,
@@ -7455,7 +7455,7 @@ async function acceptDirectSend(
if (chose === "restart") await restartForPerson(botId, threadId, trigger);
return { ok: true as const, queued: true as const, queueId: queued.id, threadId };
}
- return startOrQueueDirectMessage(botId, threadId, text, replyTo, sendId, sender, trigger, via, callId, dataContext, app);
+ return startOrQueueDirectMessage(botId, threadId, text, replyTo, sendId, sender, trigger, via, callId, dataContext, app, mentions);
},
);
}
@@ -7652,7 +7652,7 @@ async function beginTurn(
sendId?: string;
via?: "call"; callId?: string;
relayed?: boolean;
- dataContext?: DataContext;
+ dataContext?: DataContext; mentions?: string[];
app?: { context?: string; fromApp?: Message["fromApp"]; pointed?: Message["pointed"] };
onDispatchError?: (message: string) => void;
compactOnly?: boolean;
@@ -8383,7 +8383,7 @@ async function beginTurn(
// "@Bob" is the teammate Bob (or the writer themselves), never a bot that shares the name.
const tagged = integrations.agents
? mentionedBots(withoutPersonTags(providerText, [...personTagNames(cfg.profile?.name), ...teamMessages.people().flatMap((one) => one.tags)],
- store.bots.filter((one) => !one.hidden).map((one) => one.name)), sectionPeers)
+ store.bots.filter((one) => !one.hidden).map((one) => one.name)), sectionPeers, opts?.mentions)
: [];
const coordinationPrompt = chiefLevel(bot)
? chiefOfStaffSystemPrompt(bot.id, store.bots, Boolean(integrations.agents), chiefEscalationsEnabled(cfg))
@@ -10645,7 +10645,7 @@ async function runClaimedGroupMemberTurn(
replyText,
reachablePeers(store.bots, bot).filter((peer) => !group.memberIds.includes(peer.id)),
); for (const line of placesElsewhere.missed(replyText, store.bots)) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: line, ok: false } });
- for (const peer of missed) {
+ for (const peer of missed.filter((one, at) => missed.findIndex((other) => other.name === one.name) === at)) {
store.appendMessage(threadId, {
role: "bot",
kind: "activity",
@@ -10848,7 +10848,7 @@ async function runGroupGoalOperation(args: {
type StartGroupTurnOptions = {
threadId?: string;
goalCoordinatorBotId?: string;
- goalRunId?: string;
+ goalRunId?: string; mentions?: string[];
via?: "api";
sender?: ResolvedSender;
trigger?: UsageTrigger;
@@ -10957,13 +10957,13 @@ function startGroupTurn(
},
});
}
- let responders = roomResponders(text, members, group.defaultResponder);
+ let responders = roomResponders(text, members, group.defaultResponder, options.mentions);
if (!group.dm) {
const addressed = stopWordPlacement(text) === "adjacent" ? undefined : message.id;
for (const held of responders.filter(isHeld)) noteHeldSkip(group.id, threadId, held, addressed);
responders = responders.filter((responder) => !isHeld(responder));
}
- const explicitlyMentionedLead = roomResponders(text, routableMembers, { kind: "mentions" })[0];
+ const explicitlyMentionedLead = roomResponders(text, routableMembers, { kind: "mentions" }, options.mentions)[0];
const goalCoordinator = channelMode === "goal"
? requestedGoalCoordinator ?? explicitlyMentionedLead ?? selectGroupGoalCoordinator(routableMembers, group.defaultResponder)
: null;
@@ -10976,7 +10976,7 @@ function startGroupTurn(
}
// Auto's responders are a fallback until the decision model answers; the append and the return stay synchronous.
const autoRoute = autoCandidate && !goalCoordinator && routableMembers.length > 1 &&
- roomResponders(text, availableMembers, { kind: "mentions" }).length === 0;
+ roomResponders(text, availableMembers, { kind: "mentions" }, options.mentions).length === 0;
if (!responders.length && !goalCoordinator && !autoRoute) {
const defaultArchivedId = group.defaultResponder.kind === "member" ? group.defaultResponder.botId : undefined;
@@ -11135,7 +11135,7 @@ function drainQueuedChannelSendsNow(): void {
threadId,
sender: head.sender,
trigger: queuedTurnTrigger({ trigger: head.trigger, sender: head.sender }),
- queuedGroup: items,
+ queuedGroup: items, mentions: items.flatMap((item) => item.mentions ?? []),
});
} catch (error) {
for (const item of items) {
diff --git a/server/message-db.ts b/server/message-db.ts
index cc4f71d3ce..95fa45652e 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -220,6 +220,7 @@ export interface FollowupPayload {
origin?: WorkOrigin;
queuedAt?: number;
rowId?: string;
+ mentions?: string[];
}
export type FollowupStatus = "pending" | "dispatching" | "interrupted" | "cancelled";
export interface ChatFollowup {
diff --git a/server/person-replies.ts b/server/person-replies.ts
index 32f0cdbe4b..2d5f548d45 100644
--- a/server/person-replies.ts
+++ b/server/person-replies.ts
@@ -17,7 +17,7 @@ export interface PersonReplyDeps {
usageTriggerFor(auth: RequestAuth): UsageTrigger;
groupThreadIsWorking(groupId: string, threadId: string): boolean;
startGroupTurn(groupId: string, text: string, replyTo: ReplyTarget, sendId: string, mode: "chat", queueId: undefined,
- options: { threadId: string; sender?: ResolvedSender; trigger: UsageTrigger }): unknown;
+ options: { threadId: string; sender?: ResolvedSender; trigger: UsageTrigger; mentions: string[] }): unknown;
startOrQueueDirectMessage(botId: string, threadId: string, text: string, replyTo: ReplyTarget, sendId: string,
sender?: ResolvedSender, trigger?: UsageTrigger, via?: "call", callId?: string): Promise<{ queued?: true }>;
}
@@ -91,10 +91,10 @@ export function createPersonReplies(deps: PersonReplyDeps) {
const current = store.group(group.id);
if (!current || !owned) throw conflict(`the room switched tasks before it could receive the answer`);
if (deps.groupThreadIsWorking(current.id, threadId)) {
- queueChannelMessage(current.id, threadId, text, { replyToId: target.id, sendId, mode: "chat", sender, trigger, reaction: target.reactedWith });
+ queueChannelMessage(current.id, threadId, text, { replyToId: target.id, sendId, mode: "chat", sender, trigger, reaction: target.reactedWith, mentions: [owner.id] });
return { queued: true };
}
- deps.startGroupTurn(current.id, text, target, sendId, "chat", undefined, { threadId, sender, trigger });
+ deps.startGroupTurn(current.id, text, target, sendId, "chat", undefined, { threadId, sender, trigger, mentions: [owner.id] });
return { queued: false };
}
const direct = await deps.startOrQueueDirectMessage(owner.id, threadId, text, target, sendId, sender, trigger, via, callId);
diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.ts
index 535e9ab8b3..fabfc2adad 100644
--- a/server/routes/bot-messages.ts
+++ b/server/routes/bot-messages.ts
@@ -33,6 +33,7 @@ import { extractSteerImages } from "../turn-images.ts";
import { followupFacts, helperFollowup, helperFollowupBody, mayFollowUp } from "../helper-followup.ts";
import type { UsageTrigger } from "../usage-ledger.ts";
import { noteTypedSend } from "../typed-sends.ts";
+import { parseMentionPicks } from "../../shared/room-mentions.ts";
import { pinnedClientThreadGuard } from "./pinned-client-thread.ts";
import { PASS, type RouteHandler } from "./table.ts";
@@ -197,6 +198,8 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
if (pointing && (guarded || pressed || fromAnApp)) return json(res, 400, { error: "only a typed message can carry what the person pointed at" });
const followUp = parseFollowUp(body.followUp);
if (followUp === null) return json(res, 400, { error: "followUp must be steer, queue or restart" });
+ const mentions = parseMentionPicks(body.mentions);
+ if (mentions === null) return json(res, 400, { error: "mentions must be a list of up to 20 bot ids" });
if (followUp && (guarded || pressed || fromAnApp)) return json(res, 400, { error: "only a typed message can choose how it meets the running turn" });
// A distinct route, so an older server answers 404 instead of ignoring the safety preconditions.
const guardedBody = guarded ? guardedSendSchema.safeParse(body) : null;
@@ -326,6 +329,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler
const receipt = await acceptDirectSend({
botId: bot.id, threadId, text, sendId, replyTo, sender, trigger, dataContext, ...(app ? { app } : {}),
personPresent, ...(followUp ? { followUp } : {}),
+ ...(mentions?.length && !press && !appSent ? { mentions } : {}),
}, guardedStart);
press?.settle("queueId" in receipt ? receipt.queueId : undefined);
appContext?.deliver();
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index b1af1d5af4..60ae84c07e 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -28,6 +28,9 @@ import type { BotRecord, GroupRecord, GroupTaskPatch, Message, Store } from "../
import type { ThreadStarters } from "../thread-starters.ts";
import { extractSteerImages } from "../turn-images.ts";
import type { UsageTrigger } from "../usage-ledger.ts";
+import { parseMentionPicks } from "../../shared/room-mentions.ts";
+import { sameNameRefusal } from "../same-name-mentions.ts";
+import { conversationLanguage } from "../server-lines.ts";
import { bulkDeleteThreadIds, type BulkDeleteRefusal } from "./bulk-delete.ts";
import { PASS, type RouteHandler } from "./table.ts";
import { sawThread } from "../thread-presence.ts";
@@ -83,9 +86,9 @@ export interface ChannelRouteDeps {
sendId: string | undefined,
channelMode: "chat" | "goal",
queueId: undefined,
- options: { via?: "api"; sender?: ResolvedSender; trigger?: UsageTrigger; threadId?: string },
+ options: { via?: "api"; sender?: ResolvedSender; trigger?: UsageTrigger; threadId?: string; mentions?: string[] },
): Message;
- applyRoomHoldsFromMessage(groupId: string, text: string): void;
+ applyRoomHoldsFromMessage(groupId: string, text: string, mentions?: readonly string[]): void;
cancelGroupTurnOperations(groupId: string, threadId: string): void;
drainQueuedChannelSends(): void;
clearTurnDigestState(threadId: string): void;
@@ -330,6 +333,8 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
if (body.threadId !== undefined && (typeof body.threadId !== "string" || !/^[\w-]+$/.test(body.threadId))) {
return json(res, 400, { error: "threadId must be a task id" });
}
+ const mentions = parseMentionPicks(body.mentions);
+ if (mentions === null) return json(res, 400, { error: "mentions must be a list of up to 20 bot ids" });
const threadId = body.threadId ?? group.threadId;
const trigger = usageTriggerFor(auth);
try {
@@ -388,7 +393,10 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
status: 404,
});
}
- if (channelMode === "chat") applyRoomHoldsFromMessage(current.id, text);
+ const members = current.memberIds.map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot));
+ const sameName = sameNameRefusal(text, members, mentions, conversationLanguage(threadId));
+ if (sameName) throw Object.assign(new Error(sameName), { status: 409 });
+ if (channelMode === "chat") applyRoomHoldsFromMessage(current.id, text, mentions);
const threadWorking = groupThreadIsWorking(current.id, threadId);
const decision = admit("room", {}, { roomWorking: threadWorking, threadWorking });
if (decision.action === "queue") {
@@ -399,10 +407,11 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
via,
sender: messageSender(auth),
trigger,
+ mentions,
});
return { ok: true as const, queued: true as const, queueId: queued.id, threadId };
}
- const message = startGroupTurn(current.id, text, replyTo, sendId, channelMode, undefined, { via, sender: messageSender(auth), trigger, threadId });
+ const message = startGroupTurn(current.id, text, replyTo, sendId, channelMode, undefined, { via, sender: messageSender(auth), trigger, threadId, mentions });
return { ok: true as const, threadId, message };
},
);
diff --git a/server/same-name-mentions.e2e.test.ts b/server/same-name-mentions.e2e.test.ts
new file mode 100644
index 0000000000..6f8414022b
--- /dev/null
+++ b/server/same-name-mentions.e2e.test.ts
@@ -0,0 +1,139 @@
+// Two bots on a Team Cloud share a name, end to end. In a room with both, the one a person picks from the @ list is the
+// one that answers, also when the line waits behind a running turn; the same name typed with no pick is refused in plain
+// words before anything is queued; a name only one bot has still works. In a one-to-one chat the picked teammate is the
+// one the bot is told about. The engine is the synthetic Claude CLI playing a scripted plan, so it proves the routing,
+// not a model's judgement.
+import { randomBytes, randomUUID } 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 ENGINE = `process.env.FAKE_CLAUDE_ROOM_PLAN = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/plan.json";`;
+const REFUSED = 'Two bots here are named "Marlowe": Marlowe, Analyst and Marlowe, Chief of Staff. Pick the one you mean from the @ list.';
+const HOLD = "hold the room for a moment";
+
+type Bot = { id: string; name: string; threadId: string };
+type Message = { role: string; kind?: string; text?: string; from?: { botId: string } };
+type Turn = { botId: string; system: string; prompt: unknown };
+
+let fx: CloudSendFixture, team: CloudTeamFixture;
+let olive = "";
+let lead: Bot, analyst: Bot, chief: Bot;
+let room: { id: string; threadId: string };
+
+const planPath = () => join(team.home, "plan.json");
+const leadGo = () => join(team.home, "lead-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 ran = (bot: Bot) => turns().filter((turn) => turn.botId === bot.id).length;
+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 transcript = async () =>
+ ((await team.as(olive, "GET", `/api/threads/${room.threadId}/messages?limit=200`)).body.messages ?? []) as Message[];
+const repliesFrom = async (bot: Bot) => (await transcript()).filter((message) => message.kind === "text" && message.from?.botId === bot.id).length;
+const roomNow = async () => ((await team.as(olive, "GET", "/api/bots?messages=0")).body.groups as Array<{ id: string; busyBotId?: string | null; working?: boolean }>)
+ .find((group) => group.id === room.id);
+const settled = async () => {
+ const listed = (await team.as(olive, "GET", "/api/bots?messages=0")).body as { bots: Array<{ busy?: boolean; tasks?: Array<{ busy?: boolean }> }>; groups: Array<{ id: string; working?: boolean; busyBotId?: string | null }> };
+ const group = listed.groups.find((one) => one.id === room.id);
+ return listed.bots.every((one) => !one.busy && !(one.tasks ?? []).some((task) => task.busy)) && !group?.working && !group?.busyBotId;
+};
+const say = (text: string, extra: Record<string, unknown> = {}) =>
+ team.as(olive, "POST", `/api/groups/${room.id}/messages`, { text, sendId: randomUUID(), ...extra });
+
+beforeAll(async () => {
+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-1", name: "Acme", engine: ENGINE } });
+ team = fx.team!;
+ olive = (await team.pair(OLIVE)).token!;
+ lead = await create({ name: "Tessaly", title: "Support lead", reportsTo: OLIVE.email });
+ analyst = await create({ name: "Marlowe", title: "Analyst", reportsTo: OLIVE.email });
+ chief = await create({ name: "Marlowe", reportsTo: OLIVE.email });
+ expect((await team.as(olive, "PATCH", `/api/bots/${chief.id}`, { chiefOfStaff: true })).status).toBe(200);
+ const made = await team.as(olive, "POST", "/api/groups", { name: "Launch", memberIds: [lead.id, analyst.id, chief.id],
+ setup: { bulletin: "", defaultResponder: { kind: "member", botId: lead.id } } });
+ expect(made.status, JSON.stringify(made.body)).toBe(201);
+ room = made.body.group;
+ writeFileSync(planPath(), JSON.stringify({
+ [lead.id]: { byPrompt: [{ promptIncludes: HOLD, plan: { reply: "Holding.", gateFile: leadGo() } }], reply: "Tessaly here." },
+ [analyst.id]: { reply: "The analyst here." },
+ [chief.id]: { reply: "The chief here." },
+ }));
+}, hostTimeout(120_000));
+
+afterAll(async () => {
+ await fx?.close();
+});
+
+it("sends a line with a picked bot to that bot alone, never the older one of the same name", async () => {
+ const sent = await say("@Marlowe please check the launch numbers", { mentions: [chief.id] });
+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);
+ await expect.poll(() => repliesFrom(chief), { timeout: 60_000 }).toBe(1);
+ await expect.poll(settled, { timeout: 30_000 }).toBe(true);
+ expect(ran(chief)).toBe(1);
+ expect(ran(analyst)).toBe(0);
+ expect(ran(lead)).toBe(0);
+}, hostTimeout(120_000));
+
+it("refuses the shared name typed with no pick, in plain words, before anything is queued", async () => {
+ const opened = await say(`@Tessaly ${HOLD}`);
+ expect(opened.status, JSON.stringify(opened.body)).toBe(202);
+ await expect.poll(async () => (await roomNow())?.busyBotId, { timeout: 30_000 }).toBe(lead.id);
+
+ const refused = await say("@Marlowe are you there?");
+ expect(refused.status).toBe(409);
+ expect(refused.body.error).toBe(REFUSED);
+ const waiting = await say("@Marlowe are the numbers in?", { mentions: [analyst.id] });
+ expect(waiting.status, JSON.stringify(waiting.body)).toBe(202);
+ expect(waiting.body.queued).toBe(true);
+
+ writeFileSync(leadGo(), "go");
+ await expect.poll(() => repliesFrom(analyst), { timeout: 60_000 }).toBe(1);
+ await expect.poll(settled, { timeout: 30_000 }).toBe(true);
+ const lines = await transcript();
+ expect(lines.some((message) => message.text?.includes("are you there?"))).toBe(false);
+ expect(lines.filter((message) => message.role === "user").map((message) => message.text)).toEqual([
+ "@Marlowe please check the launch numbers", `@Tessaly ${HOLD}`, "@Marlowe are the numbers in?",
+ ]);
+ expect(ran(analyst)).toBe(1);
+ expect(ran(chief)).toBe(1);
+}, hostTimeout(120_000));
+
+it("still sends a name only one bot has, and refuses picks that are not a list of ids", async () => {
+ const before = ran(lead);
+ const sent = await say("@Tessaly how are we doing?");
+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);
+ await expect.poll(() => ran(lead), { timeout: 60_000 }).toBe(before + 1);
+ await expect.poll(settled, { timeout: 30_000 }).toBe(true);
+ for (const mentions of ["not-a-list", [42], Array.from({ length: 21 }, (_, i) => `bot-${i}`)]) {
+ const bad = await say("@Marlowe hello", { mentions });
+ expect(bad.status).toBe(400);
+ expect(bad.body.error).toBe("mentions must be a list of up to 20 bot ids");
+ }
+}, hostTimeout(120_000));
+
+it("tells a bot in a one-to-one chat about the teammate picked, and about both when the name was typed", async () => {
+ const opened = await team.as(olive, "POST", `/api/bots/${lead.id}/tasks`, { title: "Numbers" });
+ expect(opened.status, JSON.stringify(opened.body)).toBe(201);
+ const chat = opened.body.task.threadId as string;
+ const asked = async (text: string, mentions?: string[]) => {
+ const before = ran(lead);
+ const sent = await team.as(olive, "POST", `/api/bots/${lead.id}/messages`, { text, threadId: chat, ...(mentions ? { mentions } : {}) });
+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);
+ await expect.poll(() => ran(lead), { timeout: 60_000 }).toBe(before + 1);
+ await expect.poll(settled, { timeout: 30_000 }).toBe(true);
+ const turn = turns().filter((one) => one.botId === lead.id).at(-1)!;
+ return `${turn.system}\n${JSON.stringify(turn.prompt)}`;
+ };
+ const picked = await asked("can you ask @Marlowe for the launch numbers?", [analyst.id]);
+ expect(picked).toContain(`The user named these existing teammates: Marlowe (${analyst.id})`);
+ expect(picked).not.toContain(`Marlowe (${chief.id})`);
+ const typed = (await asked("can you ask @Marlowe for the launch numbers again?")).match(/The user named these existing teammates: [^.]*\./)?.[0];
+ expect(typed).toContain(`Marlowe (${analyst.id})`);
+ expect(typed).toContain(`Marlowe (${chief.id})`);
+}, hostTimeout(120_000));
diff --git a/server/same-name-mentions.test.ts b/server/same-name-mentions.test.ts
new file mode 100644
index 0000000000..214308561f
--- /dev/null
+++ b/server/same-name-mentions.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+
+import { sameNameRefusal } from "./same-name-mentions.ts";
+import { mentionedBots, roomResponders } from "./store.ts";
+
+const analyst = { id: "quill-analyst", name: "Quill", title: "Analyst" };
+const chief = { id: "quill-chief", name: "Quill", title: "", chiefOfStaff: true };
+const scout = { id: "scout", name: "Scout", title: "Support agent" };
+const room = [analyst, chief, scout];
+
+describe("a person's room line that tags a name two bots share", () => {
+ it("is refused in plain words that name each bot by its role", () => {
+ expect(sameNameRefusal("@Quill can you check this?", room, undefined, undefined)).toBe(
+ 'Two bots here are named "Quill": Quill, Analyst and Quill, Chief of Staff. Pick the one you mean from the @ list.',
+ );
+ });
+
+ it("names three or more, and a bot with no role by its name alone", () => {
+ const plain = { id: "quill-plain", name: "QUILL", title: " " };
+ expect(sameNameRefusal("hey @quill", [...room, plain], [], "en")).toBe(
+ '3 bots here are named "Quill": Quill, Analyst; Quill, Chief of Staff; QUILL. Pick the one you mean from the @ list.',
+ );
+ });
+
+ it("goes when the bot was picked from the @ list, or the name is only one bot's", () => {
+ expect(sameNameRefusal("@Quill can you check this?", room, [chief.id], undefined)).toBeNull();
+ expect(sameNameRefusal("@Scout can you check this?", room, undefined, undefined)).toBeNull();
+ expect(sameNameRefusal("@everyone standup", room, undefined, undefined)).toBeNull();
+ expect(sameNameRefusal("no tags at all", room, undefined, undefined)).toBeNull();
+ });
+});
+
+describe("room routing with picks", () => {
+ it("sends a picked line to the picked bot alone, not the older one", () => {
+ expect(roomResponders("@Quill take this", room, { kind: "member", botId: scout.id }, [chief.id])).toEqual([chief]);
+ expect(mentionedBots("@Quill take this", room, [analyst.id])).toEqual([analyst]);
+ });
+
+ it("sends a bot's own unpicked tag of a shared name to every bot of that name", () => {
+ expect(roomResponders("@Quill take this", room, { kind: "mentions" })).toEqual([analyst, chief]);
+ });
+
+ it("keeps @everyone and a unique name as they were", () => {
+ expect(roomResponders("@everyone standup", room, { kind: "mentions" }, [chief.id])).toEqual(room);
+ expect(roomResponders("@Scout look", room, { kind: "member", botId: analyst.id })).toEqual([scout]);
+ expect(roomResponders("hello", room, { kind: "member", botId: analyst.id }, [chief.id])).toEqual([analyst]);
+ });
+});
diff --git a/server/same-name-mentions.ts b/server/same-name-mentions.ts
new file mode 100644
index 0000000000..a6044bfd1d
--- /dev/null
+++ b/server/same-name-mentions.ts
@@ -0,0 +1,26 @@
+import { resolveMentions } from "../shared/room-mentions.ts";
+import { clip } from "./peer-roster.ts";
+import { serverLine } from "./server-lines.ts";
+
+type Member = { id: string; name: string; title?: string; chiefOfStaff?: boolean; hidden?: boolean };
+
+/** Why a person's line cannot go into this room: it @-tags a name several active members share and none of them was
+ * picked from the @ list. Null when it can go. */
+export function sameNameRefusal(
+ text: string,
+ members: readonly Member[],
+ picked: readonly string[] | undefined,
+ language: string | undefined,
+): string | null {
+ const [sharing] = resolveMentions(text, members, picked).ambiguous;
+ if (!sharing) return null;
+ const choices = sharing.map((bot) => {
+ const name = clip(bot.name, 80);
+ const role = clip(bot.title ?? "", 120) || (bot.chiefOfStaff ? serverLine(language, "server.rooms.sameName.chief") : "");
+ return role ? serverLine(language, "server.rooms.sameName.choice", { name, role }) : name;
+ });
+ const name = clip(sharing[0]!.name, 80);
+ return choices.length === 2
+ ? serverLine(language, "server.rooms.sameName.two", { name, first: choices[0]!, second: choices[1]! })
+ : serverLine(language, "server.rooms.sameName.many", { name, count: choices.length, choices: choices.join("; ") });
+}
diff --git a/server/steer-queue.ts b/server/steer-queue.ts
index 6559d7f01d..aad0140b49 100644
--- a/server/steer-queue.ts
+++ b/server/steer-queue.ts
@@ -42,10 +42,12 @@ interface QueueEntry {
/** The person's row already in the transcript, steered into a turn that was stopped before it read it: it runs as
* it is, never as a second copy. */
rowId?: string;
+ /** Bot ids picked from the @ list. */
+ mentions?: string[];
}>;
}
-export type SteerQueueHead = Pick<QueueEntry["items"][number], "trigger" | "sender" | "peerAsk" | "origin">;
+export type SteerQueueHead = Pick<QueueEntry["items"][number], "trigger" | "sender" | "peerAsk" | "origin" | "mentions">;
const queues = new Map<string, QueueEntry>();
@@ -105,7 +107,7 @@ export function queueSteeredMessage(
botId: string,
threadId: string,
text: string,
- options: { prompt?: string; replyToId?: string; sendId?: string; dataContext?: Message["dataContext"]; reason?: SteerQueueReason; unattended?: boolean; peerAsk?: Message["peerAsk"]; origin?: WorkOrigin; sender?: ResolvedSender; trigger?: UsageTrigger; callId?: string; via?: "call"; reaction?: string; fromApp?: Message["fromApp"]; relay?: Message["relay"]; rowId?: string; first?: boolean; queuedAt?: number } = {},
+ options: { prompt?: string; replyToId?: string; sendId?: string; dataContext?: Message["dataContext"]; reason?: SteerQueueReason; unattended?: boolean; peerAsk?: Message["peerAsk"]; origin?: WorkOrigin; sender?: ResolvedSender; trigger?: UsageTrigger; callId?: string; via?: "call"; reaction?: string; fromApp?: Message["fromApp"]; relay?: Message["relay"]; rowId?: string; first?: boolean; queuedAt?: number; mentions?: string[] } = {},
): QueuedSteer {
const id = newId();
const entry = queues.get(threadId) ?? { botId, items: [] };
@@ -129,6 +131,7 @@ export function queueSteeredMessage(
...(options.reaction ? { reaction: options.reaction } : {}),
...(options.relay ? { relay: options.relay } : {}),
...(options.rowId ? { rowId: options.rowId } : {}),
+ ...(options.mentions?.length ? { mentions: options.mentions } : {}),
};
saveChatFollowup({ id, kind: "bot", ownerId: botId, threadId, payload: item });
// `first`: ahead of everything queued but the person's own messages sent before it.
@@ -226,6 +229,7 @@ export function drainSteeredMessages(
if (!last) continue;
// A blank line keeps each message its own Markdown block; otherwise a trailing attachment tag merges into the next and stops being an image.
const prompt = group.map((item) => item.prompt).join("\n\n");
+ const mentions = group.flatMap((item) => item.mentions ?? []);
const running = run(
entry.botId,
threadId,
@@ -234,7 +238,7 @@ export function drainSteeredMessages(
appended.map((message) => message.id),
// One unattended line makes the turn unattended: a person's words in the group cannot re-attend a bot's own.
group.some((item) => item.unattended === true),
- { trigger: group[0].trigger, sender: group[0].sender, peerAsk: group[0].peerAsk, origin: group[0].origin },
+ { trigger: group[0].trigger, sender: group[0].sender, peerAsk: group[0].peerAsk, origin: group[0].origin, ...(mentions.length ? { mentions } : {}) },
);
void Promise.resolve(running).then(
() => settleChatFollowups(ids, null),
diff --git a/server/store.ts b/server/store.ts
index 9cde89b0b6..7c85a49dda 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -27,7 +27,7 @@ import { lastChangeRequestUrl } from "../shared/thread-link.ts";
import { REMOVED_COMPUTER_DRIVER, type ComputerEngineMove } from "./computer-engine-removal.ts";
import type { TeamSetupRequest, TeamSetupResult } from "../shared/team-setup.ts";
import type { GroupGoalRunCardData } from "../shared/group-goal-run.ts";
-import { isMentionBoundary, isMentionNameContinuation } from "../shared/mention-boundary.ts";
+import { isMentionBoundary, isMentionNameContinuation } from "../shared/mention-boundary.ts"; import { resolveMentions } from "../shared/room-mentions.ts";
import type { HandedState } from "./delta-context.ts";
import type { AgentPart, PartPair, RoomPart } from "./package-parts.ts";
import type {
@@ -207,25 +207,8 @@ const messagesFile = (threadId: string) => join(DATA_DIR, `messages-${threadId}.
export const sectionKey = (section?: string | null): string => section?.trim() || "";
-export function mentionedBots<T extends { name: string; hidden?: boolean }>(text: string, peers: T[]): T[] {
- const candidates = peers
- .filter((p) => !p.hidden && p.name.trim())
- .sort((a, b) => b.name.length - a.name.length);
- const lower = text.toLowerCase();
- const found: T[] = [];
- let at = -1;
- while ((at = lower.indexOf("@", at + 1)) !== -1) {
- if (!isMentionBoundary(text, at)) continue;
- const rest = lower.slice(at + 1);
- const hit = candidates.find((p) => {
- const name = p.name.toLowerCase();
- if (!rest.startsWith(name)) return false;
- const after = rest.slice(name.length);
- return !isMentionNameContinuation(after);
- });
- if (hit && !found.includes(hit)) found.push(hit);
- }
- return found;
+export function mentionedBots<T extends { id?: string; name: string; hidden?: boolean }>(text: string, peers: T[], picked: readonly string[] = []): T[] {
+ return resolveMentions(text, peers, picked).bots;
}
export function normalizeGroupDefaultResponder(
@@ -259,6 +242,7 @@ export function roomResponders<T extends { id: string; name: string; hidden?: bo
text: string,
members: T[],
defaultResponder: GroupDefaultResponder,
+ picked: readonly string[] = [],
): T[] {
const available = members.filter((member) => !member.hidden);
const everyone = "everyone";
@@ -272,7 +256,7 @@ export function roomResponders<T extends { id: string; name: string; hidden?: bo
return available;
}
}
- const mentioned = mentionedBots(text, available);
+ const mentioned = mentionedBots(text, available, picked);
if (mentioned.length) return mentioned;
if (defaultResponder.kind === "everyone") return available;
if (defaultResponder.kind === "member") {
diff --git a/shared/room-mentions.test.ts b/shared/room-mentions.test.ts
new file mode 100644
index 0000000000..f16d83d5b5
--- /dev/null
+++ b/shared/room-mentions.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vitest";
+
+import { MENTION_PICKS_MAX, parseMentionPicks, resolveMentions } from "./room-mentions.ts";
+
+const analyst = { id: "quill-analyst", name: "Quill", title: "Analyst" };
+const chief = { id: "quill-chief", name: "quill", chiefOfStaff: true };
+const scout = { id: "scout", name: "Scout" };
+const room = [analyst, chief, scout];
+const ids = (bots: Array<{ id: string }>) => bots.map((bot) => bot.id);
+
+describe("resolveMentions", () => {
+ it("reaches the picked bot among two that share a name, and only it", () => {
+ expect(resolveMentions("@Quill can you check this?", room, [chief.id])).toEqual({ bots: [chief], ambiguous: [] });
+ expect(resolveMentions("@Quill can you check this?", room, [analyst.id])).toEqual({ bots: [analyst], ambiguous: [] });
+ });
+
+ it("reaches both when both were picked, in the order the line names them", () => {
+ expect(ids(resolveMentions("@Scout and @Quill", room, [chief.id, analyst.id]).bots)).toEqual([scout.id, analyst.id, chief.id]);
+ });
+
+ it("reports a typed name two bots share with both bots, instead of the first one", () => {
+ const typed = resolveMentions("@quill can you check this?", room);
+ expect(typed.ambiguous).toEqual([[analyst, chief]]);
+ expect(typed.bots).toEqual([analyst, chief]);
+ });
+
+ it("reports a shared name once however often the line tags it", () => {
+ expect(resolveMentions("@Quill, @QUILL and (@quill)", room).ambiguous).toEqual([[analyst, chief]]);
+ });
+
+ it("still resolves a name only one bot has, with or without a pick", () => {
+ expect(resolveMentions("@Scout look", room)).toEqual({ bots: [scout], ambiguous: [] });
+ expect(resolveMentions("@Scout look", room, [scout.id])).toEqual({ bots: [scout], ambiguous: [] });
+ });
+
+ it("never adds a picked bot the line does not tag, nor one archived", () => {
+ expect(resolveMentions("@Scout look", room, [analyst.id])).toEqual({ bots: [scout], ambiguous: [] });
+ expect(resolveMentions("no tags here", room, [analyst.id])).toEqual({ bots: [], ambiguous: [] });
+ expect(resolveMentions("@Quill look", [analyst, { ...chief, hidden: true }])).toEqual({ bots: [analyst], ambiguous: [] });
+ });
+
+ it("lets a longer name win over a shared shorter one", () => {
+ const junior = { id: "quill-jr", name: "Quill Jr" };
+ expect(resolveMentions("@Quill Jr please", [...room, junior])).toEqual({ bots: [junior], ambiguous: [] });
+ });
+
+ it("keeps the shared mention boundaries", () => {
+ expect(resolveMentions("mail [email protected] or /@Quill", room)).toEqual({ bots: [], ambiguous: [] });
+ expect(resolveMentions("@Quillo is someone else", room)).toEqual({ bots: [], ambiguous: [] });
+ expect(resolveMentions("İ **@Scout**", room).bots).toEqual([scout]);
+ });
+
+ it("reads @everyone as no bot's name", () => {
+ expect(resolveMentions("@everyone hello", room)).toEqual({ bots: [], ambiguous: [] });
+ });
+});
+
+describe("parseMentionPicks", () => {
+ it("takes a short list of ids and drops repeats", () => {
+ expect(parseMentionPicks(undefined)).toBeUndefined();
+ expect(parseMentionPicks(null)).toBeUndefined();
+ expect(parseMentionPicks([])).toEqual([]);
+ expect(parseMentionPicks(["a-1", "b_2", "a-1"])).toEqual(["a-1", "b_2"]);
+ });
+
+ it("refuses anything else", () => {
+ expect(parseMentionPicks("a-1")).toBeNull();
+ expect(parseMentionPicks([1])).toBeNull();
+ expect(parseMentionPicks(["has space"])).toBeNull();
+ expect(parseMentionPicks(["x".repeat(129)])).toBeNull();
+ expect(parseMentionPicks(Array.from({ length: MENTION_PICKS_MAX + 1 }, (_, i) => `bot-${i}`))).toBeNull();
+ expect(parseMentionPicks(Array.from({ length: MENTION_PICKS_MAX }, (_, i) => `bot-${i}`))).toHaveLength(MENTION_PICKS_MAX);
+ });
+});
diff --git a/shared/room-mentions.ts b/shared/room-mentions.ts
new file mode 100644
index 0000000000..3c24eb8f79
--- /dev/null
+++ b/shared/room-mentions.ts
@@ -0,0 +1,47 @@
+import { isMentionBoundary, isMentionNameContinuation } from "./mention-boundary.ts";
+
+/** The most bot ids one send may carry as picks from the @ list. */
+export const MENTION_PICKS_MAX = 20;
+
+/** Who a line's @names reach, read the same way in the app and on the host. */
+export interface ResolvedMentions<T> {
+ /** In the order the line names them: the one bot of a name; among bots that share a name, the ones picked from the @
+ * list; and, for a shared name with no pick, every bot of that name. */
+ bots: T[];
+ /** Each name that several bots share and none of them was picked, as the bots of that name. A person's line with one
+ * is refused rather than guessed. */
+ ambiguous: T[][];
+}
+
+/** `picked`: ids a person chose from the @ list. A pick never adds a bot whose name the line does not @-tag; it only
+ * says which of the bots sharing that name was meant. */
+export function resolveMentions<T extends { id?: string; name: string; hidden?: boolean }>(
+ text: string,
+ peers: readonly T[],
+ picked: readonly string[] = [],
+): ResolvedMentions<T> {
+ const candidates = peers
+ .filter((peer) => !peer.hidden && peer.name.trim())
+ .sort((a, b) => b.name.length - a.name.length);
+ const bots: T[] = [];
+ const ambiguous: T[][] = [];
+ for (let at = text.indexOf("@"); at !== -1; at = text.indexOf("@", at + 1)) {
+ if (!isMentionBoundary(text, at)) continue;
+ const named = (peer: T) => text.slice(at + 1, at + 1 + peer.name.length).toLowerCase() === peer.name.toLowerCase();
+ const hit = candidates.find((peer) => named(peer) && !isMentionNameContinuation(text.slice(at + 1 + peer.name.length)));
+ if (!hit) continue;
+ const sharing = candidates.filter((peer) => peer.name.toLowerCase() === hit.name.toLowerCase());
+ const chosen = sharing.filter((peer) => peer.id !== undefined && picked.includes(peer.id));
+ if (sharing.length > 1 && !chosen.length && !ambiguous.some((group) => group[0] === sharing[0])) ambiguous.push(sharing);
+ for (const peer of sharing.length > 1 && chosen.length ? chosen : sharing) if (!bots.includes(peer)) bots.push(peer);
+ }
+ return { bots, ambiguous };
+}
+
+/** The `mentions` a send carries: undefined when absent, null when it is not a short list of ids. */
+export function parseMentionPicks(value: unknown): string[] | undefined | null {
+ if (value === undefined || value === null) return undefined;
+ if (!Array.isArray(value) || value.length > MENTION_PICKS_MAX) return null;
+ if (!value.every((id) => typeof id === "string" && /^[\w-]{1,128}$/.test(id))) return null;
+ return [...new Set(value as string[])];
+}
diff --git a/src/components/Composer.mentions.test.ts b/src/components/Composer.mentions.test.ts
new file mode 100644
index 0000000000..8eb3a26fb5
--- /dev/null
+++ b/src/components/Composer.mentions.test.ts
@@ -0,0 +1,120 @@
+// @vitest-environment happy-dom
+// Picking a bot from the @ list sends its id with the words, so the bot picked is the one reached even when another
+// bot has the same name. Typed names carry no ids. The desktop app and the web app share this composer.
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Bot, Group } from "@/state/store";
+import { restoreComposerDraft } from "@/lib/drafts";
+
+const fixture = vi.hoisted(() => ({ dispatch: vi.fn() }));
+const ENGINE = "claude-3f0c2b1e-9d1a-4c55-8a51-0a3a6f1e2b7c";
+vi.mock("@/state/store", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/state/store")>();
+ return { ...original, useStore: () => ({
+ state: { ...original.initialState, bots: [scout, analyst, chief], instances: [{
+ instanceId: ENGINE, driverKind: "claudeAgent", displayName: "Claude", capabilities: { agentsMcp: true },
+ }] },
+ dispatch: fixture.dispatch,
+ }) };
+});
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => true }));
+vi.mock("./CallView", () => ({ CallButton: () => null }));
+vi.mock("./GroupCallView", () => ({ GroupCallButton: () => null }));
+
+import { Composer } from "./Composer";
+
+const scout: Bot = {
+ id: "scout", threadId: "scout-thread", name: "Scout", title: "Support agent", description: "",
+ color: "blue", notifications: false, unread: false, busy: false, messages: [],
+ modelSelection: { instanceId: ENGINE, model: "fake" },
+};
+const analyst: Bot = { ...scout, id: "quill-analyst", threadId: "analyst-thread", name: "Quill", title: "Analyst", color: "teal" };
+const chief: Bot = { ...scout, id: "quill-chief", threadId: "chief-thread", name: "Quill", title: "", color: "purple", chiefOfStaff: true };
+const room: Group = {
+ id: "room", threadId: "room-thread", name: "Launch", memberIds: [scout.id, analyst.id, chief.id],
+ defaultResponder: { kind: "member", botId: scout.id }, bulletin: "", unread: false, createdAt: 1, setupCompletedAt: 1, messages: [],
+};
+const drafts = [`group:${room.id}:${room.threadId}`, `bot:${scout.id}:${scout.threadId}`];
+
+let root: Root;
+let container: HTMLDivElement;
+
+beforeEach(() => {
+ vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} });
+ vi.spyOn(HTMLElement.prototype, "scrollIntoView").mockImplementation(() => {});
+ for (const id of drafts) restoreComposerDraft(id, { text: "", attachments: [] });
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ flushSync(() => root.unmount());
+ container.remove();
+ for (const id of drafts) restoreComposerDraft(id, { text: "", attachments: [] });
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+const input = () => container.querySelector("textarea")!;
+function type(draftId: string, text: string) {
+ flushSync(() => restoreComposerDraft(draftId, { text, attachments: [] }));
+ input().setSelectionRange(text.length, text.length);
+ flushSync(() => input().dispatchEvent(new KeyboardEvent("keyup", { key: "a", bubbles: true })));
+}
+const options = () => [...container.querySelectorAll<HTMLElement>('[role="option"]')];
+function pick(name: string, role: string) {
+ const option = options().find((one) => one.textContent?.includes(name) && one.textContent.includes(role));
+ if (!option) throw new Error(`no ${name}, ${role} in the @ list: ${options().map((one) => one.textContent).join(" | ")}`);
+ flushSync(() => option.click());
+}
+function send() {
+ flushSync(() => input().dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true })));
+}
+const sent = () => fixture.dispatch.mock.calls.map(([action]) => action).filter((action) => action.type === "sendGroup" || action.type === "send");
+
+describe("a room's @ list", () => {
+ beforeEach(() => flushSync(() => root.render(createElement(Composer, { group: room, members: [scout, analyst, chief] }))));
+
+ it("shows each Quill by its role, and sends the picked one's id", () => {
+ type(drafts[0]!, "@Qu");
+ expect(options().map((one) => one.textContent)).toEqual([expect.stringContaining("Analyst"), expect.stringContaining("Chief of Staff")]);
+ pick("Quill", "Chief of Staff");
+ expect(input().value).toBe("@Quill ");
+ send();
+ expect(sent()).toEqual([expect.objectContaining({ type: "sendGroup", groupId: room.id, text: "@Quill", mentions: [chief.id] })]);
+ });
+
+ it("sends a typed name with no ids, and forgets a pick once its line is sent", () => {
+ type(drafts[0]!, "@Qu");
+ pick("Quill", "Analyst");
+ send();
+ type(drafts[0]!, "@Quill check the numbers");
+ send();
+ expect(sent().map((action) => action.mentions)).toEqual([[analyst.id], []]);
+ });
+
+ it("keeps the pick with words a failed send hands back", () => {
+ type(drafts[0]!, "@Qu");
+ pick("Quill", "Chief of Staff");
+ send();
+ flushSync(() => sent()[0]!.onError());
+ expect(input().value).toBe("@Quill ");
+ send();
+ expect(sent().map((action) => action.mentions)).toEqual([[chief.id], [chief.id]]);
+ });
+});
+
+describe("a one-to-one chat's @ list", () => {
+ it("sends the picked teammate's id too", () => {
+ flushSync(() => root.render(createElement(Composer, { bot: scout })));
+ type(drafts[1]!, "ask @Qu");
+ pick("Quill", "Analyst");
+ send();
+ expect(sent()).toEqual([expect.objectContaining({ type: "send", botId: scout.id, text: "ask @Quill", mentions: [analyst.id] })]);
+ });
+});
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index b30071f3be..03b87f85df 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -62,7 +62,7 @@ import {
type Attachment,
type PasteAttachment,
} from "@/lib/composer-attachments";
-import { goalCoordinatorForComposer, jevRoomRoutingOn, openTaskWorking, roomRespondersForComposer } from "@/lib/group-routing";
+import { goalCoordinatorForComposer, jevRoomRoutingOn, openTaskWorking, roomRouteForComposer } from "@/lib/group-routing";
import { composerPlaceholder, sendLabels, SIMPLE_COMPOSER, SIMPLE_CONTROL, slotColors } from "./composer-simple"; import { ComposerSendButton } from "./ComposerSendButton";
import { PendingApprovalActions, PendingApprovalPanel, pendingApprovals } from "./PendingApproval";
import { CallButton } from "./CallView";
@@ -82,7 +82,7 @@ import {
doubleEnterSteersQueue,
} from "./ComposerQueuedMessages";
import { skillAuthoringEnabled } from "@/lib/feature-flags";
-import { mentionChoicesForQuery, mentionQueryAt } from "@/lib/mentions";
+import { mentionChoicesForQuery, mentionQueryAt } from "@/lib/mentions"; import { mentionPicksFor, restoreMentionPicks } from "@/lib/mention-picks";
import { serializeThreadRefs, threadTokenFromPaste, threadTokenSpacing } from "@/lib/thread-refs";
import {
composerSlashTrigger,
@@ -168,7 +168,7 @@ export function Composer({
!group && bot ? `bot:${bot.id}` : undefined,
);
const attachmentPending = useDraftAttachmentPending(draftId);
- const failedSends = useFailedComposerSends(draftId);
+ const failedSends = useFailedComposerSends(draftId); const picks = mentionPicksFor(draftId);
const [channelMode, setChannelMode] = useComposerChannelMode(draftId);
const editText = useCallback(
(next: string) => {
@@ -187,7 +187,7 @@ export function Composer({
const restoreDraft = useCallback(
(sent: ComposerDraftSnapshot) => {
if (recoverFailedComposerSend(sent) === "restored") {
- if (sent.reply) onRestoreReply?.(sent.reply, sent.threadId);
+ restoreMentionPicks(sent.draftId, sent.mentions); if (sent.reply) onRestoreReply?.(sent.reply, sent.threadId);
}
},
[onRestoreReply],
@@ -283,10 +283,10 @@ export function Composer({
const imageTargetsSupport = (message: string, mode: "chat" | "goal") => {
if (!group) return botSupportsImages(bot);
if (mode === "goal") {
- return botSupportsImages(goalCoordinatorForComposer(message, members ?? [], group) ?? undefined);
+ return botSupportsImages(goalCoordinatorForComposer(message, members ?? [], group, picks.ids(message)) ?? undefined);
}
- const responders = roomRespondersForComposer(message, members ?? [], group);
- return responders.length > 0 && responders.every(botSupportsImages);
+ const route = roomRouteForComposer(message, members ?? [], group, picks.ids(message));
+ return route.ambiguous || (route.responders.length > 0 && route.responders.every(botSupportsImages));
};
const typedGoalText = !group?.dm ? goalTextFromComposer(text) : null;
const effectiveText = typedGoalText ?? text;
@@ -373,7 +373,7 @@ export function Composer({
if (!mention) return;
const after = text.slice(caret);
const next = `${text.slice(0, mention.start)}@${peer.name} ${after}`;
- editText(next);
+ picks.pick(peer); editText(next);
const newCaret = mention.start + peer.name.length + 2;
setCaret(newCaret);
setDismissedAt(mention.start);
@@ -546,14 +546,14 @@ export function Composer({
sendId: failed.sendId,
text: failed.requestText,
replyToId: failed.replyToId,
- threadId: failed.threadId,
+ threadId: failed.threadId, mentions: failed.mentions,
onError: () => {
rememberFailedComposerSend(draftId, {
sendId: failed.sendId,
text: failed.text,
requestText: failed.requestText,
replyToId: failed.replyToId,
- threadId: failed.threadId,
+ threadId: failed.threadId, mentions: failed.mentions,
channelMode: failed.channelMode,
});
},
@@ -588,7 +588,7 @@ export function Composer({
reply: replyTo ?? null,
replyToId: replyTo?.id,
threadId,
- channelMode: effectiveChannelMode,
+ channelMode: effectiveChannelMode, mentions: picks.ids(body),
};
if (group) {
dispatch({
@@ -598,21 +598,21 @@ export function Composer({
sendId: sentDraft.sendId,
replyToId: replyTo?.id,
threadId,
- mode: effectiveChannelMode,
+ mode: effectiveChannelMode, mentions: sentDraft.mentions,
onError: () => restoreDraft(sentDraft),
});
roomMessageSent(effectiveChannelMode, busy);
} else if (bot) {
const points = effectiveChannelMode === "goal" ? null : takePointedChips(threadId);
dispatch({
- type: "send", botId: bot.id, text: body, sendId: sentDraft.sendId, replyToId: replyTo?.id, threadId, dataContext, mode: effectiveChannelMode,
+ type: "send", botId: bot.id, text: body, sendId: sentDraft.sendId, replyToId: replyTo?.id, threadId, dataContext, mode: effectiveChannelMode, mentions: sentDraft.mentions,
...(points ? { pointed: points.pointed } : {}), ...(followUp ? { followUp } : {}),
onError: () => { points?.restore(); restoreDraft(sentDraft); },
});
directMessageSent(state.instances, bot.modelSelection?.instanceId, busy && followUp !== "steer");
}
setText("");
- setAttachments([]);
+ setAttachments([]); picks.clear();
onConsumeReply?.();
setChannelMode("chat");
};
diff --git a/src/components/MentionMenu.tsx b/src/components/MentionMenu.tsx
index a68ed512a5..fb342779d2 100644
--- a/src/components/MentionMenu.tsx
+++ b/src/components/MentionMenu.tsx
@@ -43,7 +43,7 @@ export function MentionMenu({ listRef, motion, choices, highlight, everyoneCount
className={cn("absolute bottom-full start-2 z-20 mb-2 max-h-72 w-72 overflow-x-hidden overflow-y-auto overscroll-contain rounded-xl border border-hairline/40 bg-raised shadow-lg", motion.className, className)} {...motion.exitProps}
>
{choices.map((choice, i) => {
- const description = choice.person ? "" : choice.devs ? t("composer.mention.devsDesc") : mentionRowDescription(choice.bot ? { kind: "bot", title: choice.bot.title }
+ const description = choice.person ? "" : choice.devs ? t("composer.mention.devsDesc") : mentionRowDescription(choice.bot ? { kind: "bot", title: choice.bot.title.trim() || (choice.bot.chiefOfStaff ? t("chat.chiefOfStaff") : "") }
: choice.team ? { kind: "team", count: choice.team.count }
: choice.all ? { kind: "all", count: choice.all.count } : { kind: "everyone", count: everyoneCount });
return (
diff --git a/src/lib/drafts.ts b/src/lib/drafts.ts
index 8c0a37376d..adec0c534d 100644
--- a/src/lib/drafts.ts
+++ b/src/lib/drafts.ts
@@ -23,6 +23,8 @@ export interface FailedComposerSend {
replyToId?: string;
threadId: string;
channelMode?: "chat" | "goal";
+ /** Bot ids picked from the @ list. */
+ mentions?: string[];
}
type FailedComposerSendInput = Omit<FailedComposerSend, "id">;
export interface ComposerSendSnapshot extends FailedComposerSendInput {
@@ -425,6 +427,7 @@ export function recoverFailedComposerSend(sent: ComposerSendSnapshot): "restored
replyToId: sent.replyToId,
threadId: sent.threadId,
channelMode: sent.channelMode,
+ mentions: sent.mentions,
});
return "outbox";
}
diff --git a/src/lib/group-routing.test.ts b/src/lib/group-routing.test.ts
index 7f2060316e..d772908255 100644
--- a/src/lib/group-routing.test.ts
+++ b/src/lib/group-routing.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it } from "vitest";
import { setLocale } from "./i18n";
-import { goalCoordinatorForComposer, groupComposerHint, openTaskWorking, roomRespondersForComposer } from "./group-routing";
+import { goalCoordinatorForComposer, groupComposerHint, openTaskWorking, roomRespondersForComposer, roomRouteForComposer } from "./group-routing";
import type { Group, GroupDefaultResponder } from "@/state/store";
describe("openTaskWorking", () => {
@@ -69,6 +69,30 @@ describe("roomRespondersForComposer", () => {
});
});
+describe("who answers when two room members share a name", () => {
+ const analyst = { id: "quill-analyst", name: "Quill" };
+ const chief = { id: "quill-chief", name: "Quill", chiefOfStaff: true };
+ const scout = { id: "scout", name: "Scout" };
+ const members = [analyst, chief, scout];
+ const led = { defaultResponder: { kind: "member", botId: "scout" } } as const;
+
+ it("names the bot picked from the @ list, as the room will", () => {
+ expect(roomRouteForComposer("@Quill check this", members, led, [chief.id])).toEqual({ responders: [chief], ambiguous: false });
+ expect(roomRespondersForComposer("@Quill check this", members, led, [analyst.id])).toEqual([analyst]);
+ expect(goalCoordinatorForComposer("@Quill finish this", members, led, [chief.id])?.id).toBe(chief.id);
+ });
+
+ it("names nobody for a typed name with no pick, since the room refuses that line", () => {
+ expect(roomRouteForComposer("@Quill check this", members, led)).toEqual({ responders: [], ambiguous: true });
+ });
+
+ it("keeps a unique name, the lead and @everyone as they were", () => {
+ expect(roomRouteForComposer("@Scout check this", members, led)).toEqual({ responders: [scout], ambiguous: false });
+ expect(roomRouteForComposer("check this", members, led, [chief.id])).toEqual({ responders: [scout], ambiguous: false });
+ expect(roomRouteForComposer("@everyone @Quill check this", members, led)).toEqual({ responders: members, ambiguous: false });
+ });
+});
+
describe("goalCoordinatorForComposer", () => {
const members = [
{ id: "first", name: "First" },
diff --git a/src/lib/group-routing.ts b/src/lib/group-routing.ts
index a9890775d6..c8d0da34a5 100644
--- a/src/lib/group-routing.ts
+++ b/src/lib/group-routing.ts
@@ -1,5 +1,6 @@
import type { Bot, ConfigStatus, Group, GroupDefaultResponder } from "@/state/store";
import { isMentionBoundary, isMentionNameContinuation } from "../../shared/mention-boundary";
+import { resolveMentions } from "../../shared/room-mentions";
import { t } from "./i18n";
export function jevRoomRoutingOn(config: ConfigStatus | null | undefined): boolean {
@@ -52,11 +53,14 @@ export function openTaskWorking(group: Pick<Group, "threadId" | "working" | "tas
return task ? Boolean(task.working) : Boolean(group.working);
}
-export function roomRespondersForComposer<T extends { id: string; name: string; hidden?: boolean }>(
+/** Who answers this line, as the room reads it. `ambiguous`: it @-tags a name several members share and none of them
+ * was picked from the @ list, so the room refuses it and nobody answers. */
+export function roomRouteForComposer<T extends { id: string; name: string; hidden?: boolean }>(
text: string,
members: T[],
group: Pick<Group, "defaultResponder">,
-): T[] {
+ picked: readonly string[] = [],
+): { responders: T[]; ambiguous: boolean } {
const available = members.filter((member) => !member.hidden);
const everyone = "everyone";
let everyoneAt = -1;
@@ -66,19 +70,25 @@ export function roomRespondersForComposer<T extends { id: string; name: string;
&& text.slice(everyoneAt + 1, everyoneAt + 1 + everyone.length).toLowerCase() === everyone
&& !isMentionNameContinuation(text.slice(everyoneAt + 1 + everyone.length))
) {
- return available;
+ return { responders: available, ambiguous: false };
}
}
- const mentioned = mentionedMembers(text, available);
- if (mentioned.length) return mentioned;
+ const mentioned = resolveMentions(text, available, picked);
+ if (mentioned.ambiguous.length) return { responders: [], ambiguous: true };
+ if (mentioned.bots.length) return { responders: mentioned.bots, ambiguous: false };
const fallback = effectiveDefaultResponder(group, available);
- if (fallback.kind === "everyone") return available;
- if (fallback.kind === "auto") return available;
- if (fallback.kind === "member") {
- const lead = available.find((member) => member.id === fallback.botId);
- return lead ? [lead] : [];
- }
- return [];
+ if (fallback.kind === "everyone" || fallback.kind === "auto") return { responders: available, ambiguous: false };
+ const lead = fallback.kind === "member" ? available.find((member) => member.id === fallback.botId) : undefined;
+ return { responders: lead ? [lead] : [], ambiguous: false };
+}
+
+export function roomRespondersForComposer<T extends { id: string; name: string; hidden?: boolean }>(
+ text: string,
+ members: T[],
+ group: Pick<Group, "defaultResponder">,
+ picked: readonly string[] = [],
+): T[] {
+ return roomRouteForComposer(text, members, group, picked).responders;
}
export function goalCoordinatorForComposer<
@@ -87,12 +97,14 @@ export function goalCoordinatorForComposer<
text: string,
members: T[],
group: Pick<Group, "defaultResponder">,
+ picked: readonly string[] = [],
): T | null {
const available = members.filter((member) => !member.hidden);
const explicitlyMentioned = roomRespondersForComposer(
text,
available,
{ defaultResponder: { kind: "mentions" } },
+ picked,
)[0];
if (explicitlyMentioned) return explicitlyMentioned;
const configuredResponder = group.defaultResponder;
@@ -104,21 +116,3 @@ export function goalCoordinatorForComposer<
}
return available.find((member) => member.chiefOfStaff) ?? available[0] ?? null;
}
-
-function mentionedMembers<T extends { name: string; hidden?: boolean }>(text: string, peers: T[]): T[] {
- const candidates = peers
- .filter((p) => !p.hidden && p.name.trim())
- .sort((a, b) => b.name.length - a.name.length);
- const found: T[] = [];
- let at = -1;
- while ((at = text.indexOf("@", at + 1)) !== -1) {
- if (!isMentionBoundary(text, at)) continue;
- const hit = candidates.find((p) => {
- const name = p.name.toLowerCase();
- if (text.slice(at + 1, at + 1 + p.name.length).toLowerCase() !== name) return false;
- return !isMentionNameContinuation(text.slice(at + 1 + p.name.length));
- });
- if (hit && !found.includes(hit)) found.push(hit);
- }
- return found;
-}
diff --git a/src/lib/mention-picks.ts b/src/lib/mention-picks.ts
new file mode 100644
index 0000000000..137d3da375
--- /dev/null
+++ b/src/lib/mention-picks.ts
@@ -0,0 +1,36 @@
+import { MENTION_PICKS_MAX, resolveMentions } from "../../shared/room-mentions";
+
+type Picked = { id: string; name: string };
+
+const picksByDraft = new Map<string, Picked[]>();
+const pickedNames = new Map<string, string>();
+
+/** The bots a person chose from the @ list while writing one draft. A send carries the ids of those its text still
+ * @-tags, so the chosen bot is the one reached even when another bot has the same name. */
+export function mentionPicksFor(draftId: string) {
+ return {
+ pick(choice: { id: string; name: string; bot?: unknown }): void {
+ if (!choice.bot) return;
+ pickedNames.set(choice.id, choice.name);
+ const kept = (picksByDraft.get(draftId) ?? []).filter((one) => one.id !== choice.id);
+ picksByDraft.set(draftId, [...kept, { id: choice.id, name: choice.name }]);
+ },
+ ids(text: string): string[] {
+ const picks = picksByDraft.get(draftId) ?? [];
+ if (!picks.length) return [];
+ return resolveMentions(text, picks, picks.map((one) => one.id)).bots.map((one) => one.id).slice(0, MENTION_PICKS_MAX);
+ },
+ clear(): void {
+ picksByDraft.delete(draftId);
+ },
+ };
+}
+
+/** A send that failed hands its words back to the draft, and its picks with them. */
+export function restoreMentionPicks(draftId: string, ids: readonly string[] | undefined): void {
+ const picks = mentionPicksFor(draftId);
+ for (const id of ids ?? []) {
+ const name = pickedNames.get(id);
+ if (name !== undefined) picks.pick({ id, name, bot: true });
+ }
+}
diff --git a/src/locales/de.json b/src/locales/de.json
index a0129703e1..26de144dfe 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -182,6 +182,10 @@
"server.rooms.becameBusy": "{bot} ist in einer anderen Unterhaltung beschäftigt geworden, daher diese Runde übersprungen",
"server.rooms.mentionMissed": "{bot} ist nicht in diesem Raum, die Erwähnung hat ihn also nicht erreicht. Füge ihn dem Raum hinzu, um ihn einzubeziehen.",
"server.rooms.archived": "{bot} ist archiviert und kann nicht antworten. Stelle ihn wieder her oder erwähne ein aktives Raummitglied.",
+ "server.rooms.sameName.two": "Zwei Bots hier heißen „{name}“: {first} und {second}. Wähle in der @-Liste den aus, den du meinst.",
+ "server.rooms.sameName.many": "{count} Bots hier heißen „{name}“: {choices}. Wähle in der @-Liste den aus, den du meinst.",
+ "server.rooms.sameName.choice": "{name}, {role}",
+ "server.rooms.sameName.chief": "Stabschef",
"server.rooms.noneActive": "Kein aktives Raummitglied kann antworten. Stelle einen archivierten Bot wieder her oder füge ein aktives Mitglied hinzu.",
"server.rooms.stillStopping": "{bot} wird noch gestoppt, diese Nachricht wurde nicht zugestellt",
"server.rooms.someoneStillStopping": "Ein Raummitglied wird noch gestoppt, diese Nachricht wurde nicht zugestellt",
diff --git a/src/locales/en.json b/src/locales/en.json
index 6454005cd9..d1806d545e 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -274,6 +274,10 @@
"server.rooms.becameBusy": "{bot} became busy in another conversation — skipped this round",
"server.rooms.mentionMissed": "{bot} isn't in this room, so that mention didn't reach them — add them to the room to bring them in.",
"server.rooms.archived": "{bot} is archived and can't respond — restore it or mention an active room member.",
+ "server.rooms.sameName.two": "Two bots here are named \"{name}\": {first} and {second}. Pick the one you mean from the @ list.",
+ "server.rooms.sameName.many": "{count} bots here are named \"{name}\": {choices}. Pick the one you mean from the @ list.",
+ "server.rooms.sameName.choice": "{name}, {role}",
+ "server.rooms.sameName.chief": "Chief of Staff",
"server.rooms.noneActive": "No active room members can respond — restore an archived bot or add an active member.",
"server.rooms.stillStopping": "{bot} is still stopping — this message was not dispatched",
"server.rooms.someoneStillStopping": "A room member is still stopping — this message was not dispatched",
diff --git a/src/state/send-mentions.test.ts b/src/state/send-mentions.test.ts
new file mode 100644
index 0000000000..e7da820527
--- /dev/null
+++ b/src/state/send-mentions.test.ts
@@ -0,0 +1,84 @@
+// @vitest-environment happy-dom
+// A send asks with the ids of the bots picked from the @ list, in a room and in a one-to-one chat, and with none when
+// nothing was picked. The desktop app and the web app share this store.
+import { createElement, type Dispatch } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Action, Group } from "./store";
+
+class FixtureEventSource {
+ static opened: FixtureEventSource[] = [];
+ onopen: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;
+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }
+ close() {}
+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }
+}
+
+const room = {
+ id: "room", threadId: "room-thread", name: "Room", memberIds: [], defaultResponder: { kind: "mentions" }, bulletin: "",
+ unread: false, createdAt: 1, messages: [],
+} as unknown as Group;
+const posted: Array<{ path: string; body: Record<string, unknown> }> = [];
+const json = (body: unknown) => Promise.resolve(new Response(JSON.stringify(body)));
+
+const { StoreProvider, useStore } = await import("./store");
+
+let dispatch!: Dispatch<Action>;
+function Probe() {
+ ({ dispatch } = useStore());
+ return null;
+}
+let root: Root;
+const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((resolve) => setTimeout(resolve, 0)); };
+const sent = async (action: Action) => {
+ posted.length = 0;
+ flushSync(() => dispatch(action));
+ await settle();
+ return posted.map(({ path, body }) => ({ path, mentions: body.mentions }));
+};
+
+beforeAll(async () => {
+ vi.stubGlobal("EventSource", FixtureEventSource);
+ vi.stubGlobal("fetch", (path: string, init?: RequestInit) => {
+ if (path.startsWith("/api/bots?")) return json({ bots: [], groups: [room] });
+ if (init?.method === "POST" && path.endsWith("/messages")) {
+ posted.push({ path, body: JSON.parse(String(init.body)) as Record<string, unknown> });
+ return json({ ok: true, threadId: "elsewhere", queued: true, queueId: "q" });
+ }
+ return json({});
+ });
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));
+ await settle();
+ FixtureEventSource.opened[0].send({ kind: "hello", resumed: false, cursor: "run:0" });
+ await settle();
+});
+beforeEach(() => { posted.length = 0; });
+afterAll(() => {
+ root.unmount();
+ vi.unstubAllGlobals();
+});
+
+describe("a send with bots picked from the @ list", () => {
+ it("carries their ids into a room", async () => {
+ expect(await sent({ type: "sendGroup", groupId: "room", text: "@Quill hi", sendId: "s1", mentions: ["quill-chief"] }))
+ .toEqual([{ path: "/api/groups/room/messages", mentions: ["quill-chief"] }]);
+ });
+
+ it("carries them into a one-to-one chat", async () => {
+ expect(await sent({ type: "send", botId: "scout", threadId: "scout-thread", text: "ask @Quill", sendId: "s2", mentions: ["quill-analyst"] }))
+ .toEqual([{ path: "/api/bots/scout/messages", mentions: ["quill-analyst"] }]);
+ });
+
+ it("asks with no ids when none was picked", async () => {
+ expect(await sent({ type: "sendGroup", groupId: "room", text: "@Quill hi", sendId: "s3", mentions: [] }))
+ .toEqual([{ path: "/api/groups/room/messages", mentions: undefined }]);
+ expect(await sent({ type: "send", botId: "scout", threadId: "scout-thread", text: "ask @Quill", sendId: "s4" }))
+ .toEqual([{ path: "/api/bots/scout/messages", mentions: undefined }]);
+ });
+});
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 771c9a8e3f..08a1ba439b 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -686,7 +686,7 @@ export type Action =
sendId?: string;
replyToId?: string;
threadId?: string;
- mode?: "chat" | "goal";
+ mode?: "chat" | "goal"; mentions?: string[];
onError?: () => void;
}
| {
@@ -719,7 +719,7 @@ export type Action =
replyToId?: string;
threadId?: string;
dataContext?: import("../../shared/data-context").DataContext; pointed?: import("../../shared/app-frame/point").PointedElement[]; mode?: "chat" | "goal";
- followUp?: import("../../shared/follow-up").FollowUp; onError?: () => void;
+ followUp?: import("../../shared/follow-up").FollowUp; mentions?: string[]; onError?: () => void;
}
| { type: "pendingQueued"; threadId: string; queueId: string; text: string; reason?: SteerQueueReason }
| { type: "consumePendingQueued"; threadId: string; queueId: string }
@@ -2451,7 +2451,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
void waitForExecutionSettings(botBeforeSend ? [botBeforeSend] : [], threadId)
.then(() => sendReconciled(() => api(`/api/bots/${action.botId}/messages`, {
method: "POST",
- body: JSON.stringify({ text: action.text, replyToId: action.replyToId, threadId, sendId, ...(action.dataContext ? { dataContext: action.dataContext } : {}), ...(action.pointed?.length ? { pointed: action.pointed } : {}), ...(action.mode === "goal" ? { mode: "goal" } : {}), ...(action.followUp ? { followUp: action.followUp } : {}) }),
+ body: JSON.stringify({ text: action.text, replyToId: action.replyToId, threadId, sendId, ...(action.dataContext ? { dataContext: action.dataContext } : {}), ...(action.pointed?.length ? { pointed: action.pointed } : {}), ...(action.mode === "goal" ? { mode: "goal" } : {}), ...(action.followUp ? { followUp: action.followUp } : {}), ...(action.mentions?.length ? { mentions: action.mentions } : {}) }),
}), arrived))
.then((sent) => {
if (!("body" in sent)) return;
@@ -2701,7 +2701,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
replyToId: action.replyToId,
threadId,
sendId,
- mode: action.mode ?? "chat",
+ mode: action.mode ?? "chat", ...(action.mentions?.length ? { mentions: action.mentions } : {}),
}),
}))
.then((body) => {