Skip to content

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

Hand-off line: a chat notice code only, no line for room turns from the other place, tests

milind-soniec2f6b117734
diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.ts
index cd54a26f9d..09bb6c6b7d 100644
--- a/server/bot-link/link.test.ts
+++ b/server/bot-link/link.test.ts
@@ -939,6 +939,8 @@ describe("the link between a computer and its Cloud", () => {
expect(turns[1]!.text).not.toContain("how many orders");
expect(turns[1]!.threadId).toBe(turns[0]!.threadId);
expect(computer.said(room.id).at(-1)).toBe("Analyst: 3 returns.");
+ // A room turn is not a hand-off to the bot: its main chat gets no line for it.
+ expect(cloud.handed).toEqual([]);
// A report made twice, as after a restart between the two, leaves one line.
const child = computer.coordinator.all().find((node) => node.botId === onCloud("cloud-analyst") && node.status === "completed")!;
expect(computer.rooms.reply(child, undefined, "Analyst")).toBe(true);
diff --git a/server/bot-link/link.ts b/server/bot-link/link.ts
index ffdc18dabf..707fd68362 100644
--- a/server/bot-link/link.ts
+++ b/server/bot-link/link.ts
@@ -537,7 +537,8 @@ export function createBotLink(deps: BotLinkDeps) {
if (files.length) deps.files?.crossed(node.id, "sent", { botId: address.botId, name: frame.from.name }, files);
work.child = node.id;
state.work[frame.id] = work;
- deps.handed?.({ botId: bot.id, threadId, from: frame.from.name, text: frame.text });
+ // A room's turn for a member of this place is not a hand-off to the bot (its work thread is named after the room).
+ if (!frame.thread.includes(":room:")) deps.handed?.({ botId: bot.id, threadId, from: frame.from.name, text: frame.text });
save();
coordinator.endTurn(root, { ok: true, text: "" });
if (frame.mode === "notify") recordResult(frame.id, { ok: true, text: "" });
diff --git a/server/chat-notices.ts b/server/chat-notices.ts
index ea7ed5a380..c75c7f4fb5 100644
--- a/server/chat-notices.ts
+++ b/server/chat-notices.ts
@@ -120,6 +120,7 @@ export const CHAT_NOTICE = {
"chat.notice.waitingApprovalElsewhere": "Waiting on your approval in @{name}",
"chat.notice.waitingAnswerElsewhere": "Waiting on your answer in @{name}",
"chat.notice.teammateNeedsInput": "{name} needs your input: {question}",
+ "chat.notice.askedMe": "{bot} asked me: {title}",
"chat.notice.waitingPasswordElsewhere": "Waiting on your {label} in @{name}",
"chat.notice.waitingSignInElsewhere": "Waiting on you to sign in to {label} in @{name}",
"chat.notice.waitingConnectElsewhere": "Waiting on you to connect {label} in @{name}",
diff --git a/server/direct-coordination.e2e.test.ts b/server/direct-coordination.e2e.test.ts
index 6025ce44ab..ce15851d6a 100644
--- a/server/direct-coordination.e2e.test.ts
+++ b/server/direct-coordination.e2e.test.ts
@@ -434,6 +434,8 @@ it("leaves one quiet line in the teammate's main chat for a hand-off, which open
expect(leadBot.tasks.find((task: any) => task.threadId === f.lead.activeTaskId).unread).toBe(true);
// The hand-off ran in its own thread; the main chat took no turn for the line.
expect(f.evidence().filter((turn: any) => turn.botId === f.lead.id).map((turn: any) => turn.threadId)).toEqual([child.threadId]);
+ // The hand-off's own turn, which started after the line was written, does not read it either.
+ expect(told(f.evidence().find((turn: any) => turn.botId === f.lead.id))).not.toContain("asked me");
await f.cli("send", "--bot", f.lead.id, "--task", f.lead.activeTaskId, "--text", "Hello there");
expect((await f.cli("wait", "--bot", f.lead.id, "--task", f.lead.activeTaskId, "--timeout", "30")).status).toBe("settled");
diff --git a/server/host/handed-line.test.ts b/server/host/handed-line.test.ts
index 412ad106f6..36d277a229 100644
--- a/server/host/handed-line.test.ts
+++ b/server/host/handed-line.test.ts
@@ -19,7 +19,7 @@ function fakeStore(threads: Record<string, { title: string; unread?: boolean }>)
describe("the hand-off line in a helper's main chat", () => {
it("says who asked and for what, opens the hand-off thread, and marks the main chat unread", () => {
const { store, appended, patched } = fakeStore({ main: { title: "Garden" }, work: { title: "Octopus facts" } });
- const id = postHandedLine({ store, mainThread: () => "main", language: () => undefined },
+ const id = postHandedLine({ store, mainThread: () => "main" },
{ botId: "sage", threadId: "work", from: "Mochi", text: "Find three octopus facts", title: "Octopus facts" });
expect(id).toBe("m1");
expect(appended).toEqual([{ threadId: "main", message: {
@@ -30,17 +30,9 @@ describe("the hand-off line in a helper's main chat", () => {
expect(patched).toEqual([{ botId: "sage", threadId: "main", patch: { unread: true } }]);
});
- it("writes the line in the main chat's language", () => {
- const { store } = fakeStore({ main: { title: "Garden" }, work: { title: "Octopus facts" } });
- const asked: string[] = [];
- postHandedLine({ store, mainThread: () => "main", language: (threadId) => { asked.push(threadId); return undefined; } },
- { botId: "sage", threadId: "work", from: "Mochi", text: "Octopus facts" });
- expect(asked).toEqual(["main"]);
- });
-
it("leaves nothing when the work runs in the main chat itself, or either thread is gone", () => {
const { store, appended, patched } = fakeStore({ main: { title: "Garden" }, work: { title: "Work" } });
- const deps = { store, mainThread: () => "main", language: () => undefined };
+ const deps = { store, mainThread: () => "main" };
expect(postHandedLine(deps, { botId: "sage", threadId: "main", from: "Mochi", text: "x" })).toBeUndefined();
expect(postHandedLine(deps, { botId: "sage", threadId: "gone", from: "Mochi", text: "x" })).toBeUndefined();
expect(postHandedLine({ ...deps, mainThread: () => undefined }, { botId: "sage", threadId: "work", from: "Mochi", text: "x" })).toBeUndefined();
diff --git a/server/host/handed-line.ts b/server/host/handed-line.ts
index 12c17c9497..1b5e0ab094 100644
--- a/server/host/handed-line.ts
+++ b/server/host/handed-line.ts
@@ -3,11 +3,9 @@
// which opens that thread, and the main chat is marked unread like any other news. The line is an activity row with no
// tool item: it is never context for the bot's model (delta-context.ts isContextMessage, context-rebuild.ts
// replayToolCalls) and it starts no turn. Nothing else is sent: no notification, no card, nothing to answer.
-import { serverLine } from "../server-lines.ts";
+import { noticeTool } from "../chat-notices.ts";
import type { Message, Store } from "../store.ts";
-/** The words the app shows in the viewer's language; `tool.name` keeps them in the main chat's language. */
-export const HANDED_LINE_CODE = "chat.notice.askedMe";
const SUMMARY_MAX = 60;
/** What was asked, as the line says it: the title the sender gave, else the start of its message on one line. */
@@ -19,11 +17,11 @@ export function handedSummary(text: string, title?: string): string {
return characters.length <= SUMMARY_MAX ? words : `${characters.slice(0, SUMMARY_MAX - 1).join("").trimEnd()}…`;
}
-export function handedLine(input: { from: string; summary: string; botId: string; threadId: string; threadTitle: string; language?: string }): Omit<Message, "id" | "at"> {
- const params = { bot: input.from, title: input.summary };
+/** The app shows it in the viewer's language from `nameCode`; `tool.name` keeps the English for phones and exports. */
+export function handedLine(input: { from: string; summary: string; botId: string; threadId: string; threadTitle: string }): Omit<Message, "id" | "at"> {
return {
role: "bot", kind: "activity",
- tool: { name: serverLine(input.language, "server.teammates.askedMe", params), ok: true, nameCode: HANDED_LINE_CODE, nameParams: params },
+ tool: noticeTool("chat.notice.askedMe", { bot: input.from, title: input.summary }, { ok: true }),
threadRef: { botId: input.botId, threadId: input.threadId, title: input.threadTitle },
};
}
@@ -32,7 +30,6 @@ export type HandedLineDeps = {
store: Pick<Store, "appendMessage" | "patchTask" | "taskByThread">;
/** The bot's main chat with the person. */
mainThread(botId: string): string | undefined;
- language(threadId: string): string | undefined;
};
/** Leaves the line for one hand-off to `botId`, worked in `threadId`, in the bot's main chat, and marks that chat unread.
@@ -43,7 +40,7 @@ export function postHandedLine(deps: HandedLineDeps, input: { botId: string; thr
const work = deps.store.taskByThread(input.botId, input.threadId);
if (!work || !deps.store.taskByThread(input.botId, main)) return undefined;
const line = handedLine({ from: input.from, summary: handedSummary(input.text, input.title), botId: input.botId, threadId: input.threadId,
- threadTitle: work.title, language: deps.language(main) });
+ threadTitle: work.title });
const { id } = deps.store.appendMessage(main, line);
deps.store.patchTask(input.botId, main, { unread: true });
return id;
diff --git a/server/index.ts b/server/index.ts
index 185b6b6314..cebf28f544 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -3841,7 +3841,7 @@ const questionRouting = createQuestionRouting({ store, handedInUnproven, active:
steer: async (threadId, text) => canSteerThread(threadId) && (await steerThread(threadId, text)) !== "refused", mayReach: outsideLineage.mayReach });
const remoteTeammates = new RemoteTeammates(); const remoteHandoff = createRemoteHandoff({ teammates: remoteTeammates, coordinator: () => coordinator, localBots: () => store.bots, botName: (id) => store.bot(id)?.name, outside: (threadId) => (outsideLineage.outsideDrivenThread(threadId) || outsideLineage.cloudGuestDriven(threadId) ? OUTSIDE_STAYS_HERE : undefined), file: join(DATA_DIR, "remote-teammate-work.json"), log: (line) => console.error(line) }); const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATTACHMENTS_DIR, botName: (id) => store.bot(id)?.name, node: (id) => coordinator.node(id), children: (id) => coordinator.children(id), discard: deleteAttachment, threadsReferencing, changes: (listener) => store.onChange(listener), log: (line) => console.error(line),
worksInOwnFolder: (botId, threadId) => turnsRunInOwnFolder(botId, threadId, store.taskByThread(botId, threadId)?.cwd, store.bot(botId)?.cwd, Boolean(store.groupByThread(threadId))), vmHome: (botId) => localVmMode(cfg) === "per-bot" ? perBotLocalVmTarget(botId).workspaceDir : null, withheld: (child, parent) => Boolean(roomHandoffProblem(child, parent)) || keptPrivate({ child: teamHost.privateTo(child.threadId), parent: teamHost.privateTo(parent.threadId) }) });
-const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => botMainThread(botId) ?? store.bot(botId)?.threadId, language: (threadId) => threadLanguage(threadId) }; const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({
+const handedLines: HandedLineDeps | undefined = CLOUD_TEAM ? undefined : { store, mainThread: (botId) => botMainThread(botId) ?? store.bot(botId)?.threadId }; const titleHandedThread = createHandedThreadTitle({ store, gate: threadTitleGate, generate: generateThreadTitle }); const botLink = createBotLinkHost({ roomLine: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), roomWindow: (threadId, reader) => roomTranscript.window(threadId, userNameFor(threadId), undefined, reader), roomOpener: (botId, threadId) => handoffOpener({ botId, threadId }, threadId), roomChanged: (groupId) => { const room = store.group(groupId); if (room) broadcast({ kind: "group", group: publicGroupState(room) }); }, roomFollow: followRoomMentions<GroupTurnOperation>({ members: (groupId) => (store.group(groupId)?.memberIds ?? []).map((id) => store.bot(id)).filter((bot): bot is BotRecord => Boolean(bot)), mentioned: (text, members) => roomResponders(text, members, { kind: "mentions" }), begin: (groupId, threadId, botIds) => Object.assign(beginGroupTurnOperation(groupId, threadId, botIds), { farSide: true }), finish: finishGroupTurnOperation, queue: groupQueues, wait: waitForChatRoomMember, run: (groupId, threadId, botId, hop, spoken, operation) => runGroupMemberTurn(groupId, threadId, botId, hop, spoken, undefined, undefined, () => operation.cancelled, undefined, undefined, undefined, undefined, operation) }), dataDir: DATA_DIR, environmentId: ENVIRONMENT_ID, store, coordinator: () => coordinator, kick: () => handoffTicks.kick(), level: (bot) => approvalModeForTurn(bot, true, bot.threadId), titleHanded: titleHandedThread, ...(handedLines ? { handedLine: (input) => { postHandedLine(handedLines, input); } } : {}), refusal: (bot) => botMoveRefusal(bot) ?? botHolds.handoff(bot.id) ?? starterCaps.pausedText(bot.id, undefined), paused: (botId) => starterAwake.isPaused(botId) || botHolds.held(botId), acceptRefusal: (bot) => linkLimits.acceptRefusal(bot), language: (threadId) => threadLanguage(threadId), personName: personNameIn, sessions, power: () => cloudPower, files: handoffFiles, storeFile: (path, name, root) => saveBotAttachment({ path, name, roots: [root], byContent: true }), log: (line) => console.error(line), local: (auth) => auth.kind === "loopback" && auth.trust !== "service" && !CLOUD_HOME && !HOSTED_WORKSPACE, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }); ROUTES.push(botLink.routes); const linkedRoster = createLinkedRoster({ link: botLink.link, bots: () => store.bots, active: () => coordinator.active() }); const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({
dataDir: DATA_DIR, restartCut: restartCutStop({ dataDir: DATA_DIR, lines: (threadId) => store.activePath(threadId) }),
now: Date.now, wrote: () => { handoffTicks.kick(); handoffStatus.changed(); }, handoffLimit: { refusal: (botId, open, origin) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) ?? usageCapGate.handoff(botId, origin) },
log: line => console.error("coordinator:", line),
diff --git a/server/thread-aware-bots.e2e.test.ts b/server/thread-aware-bots.e2e.test.ts
index 95e5a636f4..aff983951f 100644
--- a/server/thread-aware-bots.e2e.test.ts
+++ b/server/thread-aware-bots.e2e.test.ts
@@ -655,9 +655,12 @@ describe("coordinate_bots on a teammate", () => {
// The review turn quotes the requests, gate markers included, so the engine files its prompt under the first request's gate.
expect(promptsOf(gate(1)).at(-1)?.message.content).toContain("Your downstream room requests have settled");
expect(stream.frames.filter((frame) => frame.kind === "notify" && frame.notification?.botId === qa.id)).toEqual([]);
- expect((await botState(qa.id)).tasks.filter((task: any) => task.unread)).toEqual([]);
+ // The person's conversation with the teammate only gets one quiet line per hand-off, each opening the work thread,
+ // and the unread mark that comes with it; the work stays in its own thread.
+ expect((await botState(qa.id)).tasks.filter((task: any) => task.unread).map((task: any) => task.threadId)).toEqual([qa.threadId]);
expect((await botState(qa.id)).threadId).toBe(qa.threadId);
- expect(await messages(qa.threadId)).toEqual(originalConversation);
+ const handedLine = expect.objectContaining({ role: "bot", kind: "activity", threadRef: expect.objectContaining({ botId: qa.id, threadId: thread }), tool: expect.objectContaining({ nameCode: "chat.notice.askedMe" }) });
+ expect(await messages(qa.threadId)).toEqual([...originalConversation, handedLine, handedLine, handedLine]);
} finally {
stream.close();
await cleanup([pm.id, qa.id]);
@@ -734,7 +737,8 @@ describe("coordinate_bots on a teammate", () => {
expect((await messages(pm.threadId)).some(message => message.roomRequest?.id === opened.id && message.roomRequest.phase === "result" && message.tool?.ok === false)).toBe(true);
release(hold.threadId);
await expect.poll(async () => (await taskOf(qa.id, hold.threadId))?.busy, { timeout: 15_000 }).toBe(false);
- expect(await messages(qa.threadId)).toEqual(originalConversation);
+ // Nothing of the work fell back into Quinn's own conversation: only the hand-off's quiet line is there.
+ expect(await messages(qa.threadId)).toEqual([...originalConversation, expect.objectContaining({ kind: "activity", threadRef: expect.objectContaining({ threadId: opened.threadId }) })]);
} finally {
await cleanup([pm.id, qa.id]);
expect((await api("PUT", "/api/config", { threads: { maxConcurrentPerBot: 2 } })).status).toBe(200);
diff --git a/src/locales/en.json b/src/locales/en.json
index b3058fa2ed..49db4a9c51 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -439,7 +439,6 @@
"server.rooms.compactedRequested": "compacted {bot}'s context ({percent}% full): fresh session with the room's recent messages",
"server.rooms.compactedThreshold": "{bot}'s context was {percent}% full: compacted to a fresh session with the room's recent messages",
"server.teammates.sent": "Sent to {bot}",
- "server.teammates.askedMe": "{bot} asked me: {title}",
"server.checkBack.pending": "Will check back {when}",
"server.checkBack.started": "Checked back {when}",
"server.checkBack.cancelled": "Check-back cancelled",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index a95f6f59f1..f0b2ca86dd 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -420,7 +420,6 @@
"server.rooms.compactedRequested": "Compactamos o contexto de {bot} ({percent}% ocupado): nova sessão com as mensagens recentes do grupo",
"server.rooms.compactedThreshold": "Compactamos o contexto de {bot}, que estava {percent}% ocupado: nova sessão com as mensagens recentes do grupo",
"server.teammates.sent": "Enviado para {bot}",
- "server.teammates.askedMe": "{bot} me pediu: {title}",
"server.checkBack.pending": "Vai verificar de novo: {when}",
"server.checkBack.started": "Verificou de novo: {when}",
"server.checkBack.cancelled": "Verificação cancelada",