Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Hand-off line: a record, not an announcement; one line per thread, folded with a count
milind-soni9894cccea748
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex d832993d86..0108c07793 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -585,7 +585,7 @@ export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCard/** On a Team Cloud, a line in its person's inbox: who it is from and where it came from. */inbox?: InboxItem;/** thread chips: "Opened thread #Title on @X". */- threadRef?: { botId: string; threadId: string; title: string };+ threadRef?: { botId: string; threadId: string; title: string }; /** The quiet line recording hand-offs to this bot ("Mochi asked me: …"): who asked, how many it folds, their threads. */ askedBy?: { botId: string; name: string; count?: number; threadIds?: string[] };/** A "Sent to" row for work addressed into a room the bot `name` isn't in, so it went to the bot directly. `room`* names that room when this row is not in it. Clients say it in their own words; `tool.name` is the English. */sentDirectly?: { name: string; room?: string };diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.tsindex 09bb6c6b7d..97650df81e 100644--- a/server/bot-link/link.test.ts+++ b/server/bot-link/link.test.ts@@ -47,7 +47,9 @@ function place(label: string, bots: Bot[], version?: number) {/** Each work thread this place opened for a far bot: the job it was opened with names it. */const opened: Array<{ threadId: string; title: string; from: string; brief: string }> = [];/** Each hand-off from the far place this place's bot took, as its main chat is told of it. */- const handed: Array<{ botId: string; threadId: string; from: string; text: string }> = [];+ const handed: Array<{ botId: string; threadId: string; from: { botId: string; name: string }; text: string }> = [];+ /** Set to make writing the hand-off line throw, as a full disk would. */+ const handedFails = { on: false };const runs: Array<{ botId: string; threadId: string; text: string; resumed: boolean; requester: string; origin: unknown }> = [];const sent: Array<{ recipient: string; threadId: string; roomId?: string }> = [];const results: Array<{ thread: string; name: string; status: string; result: string }> = [];@@ -109,7 +111,7 @@ function place(label: string, bots: Bot[], version?: number) {dataDir: dir, coordinator: () => coordinator, bots: () => bots, bot: (id) => bots.find((bot) => bot.id === id), level: () => "full", paused: (bot) => Boolean((bot as Bot).paused), acceptRefusal: (bot) => (bot as Bot).farWorkRefused ?? null,...(options.tell ? { tellAfterMs: options.tell.afterMs, tellWithinMs: options.tell.withinMs } : {}),openThread: (bot, title, opener, brief) => { const id = `${bot.id}-work-${++openedCount}`; threads.add(id); opened.push({ threadId: id, title, from: opener.name, brief }); return id; },- hasThread: (_botId, threadId) => threads.has(threadId), personName: () => "Sam", handed: (input) => { handed.push(input); },+ hasThread: (_botId, threadId) => threads.has(threadId), personName: () => "Sam", handed: (input) => { if (handedFails.on) throw new Error("the line could not be written"); handed.push(input); },sentRow: (input) => { sent.push({ recipient: input.recipient.name, threadId: input.threadId, ...(input.roomId ? { roomId: input.roomId } : {}) }); },resultRow: (parent, child, name) => { results.push({ thread: parent.threadId, name, status: child.status, result: child.result }); for (const listener of resultListeners) listener(); },kick: () => { queueMicrotask(() => { try { coordinator.tick(); } catch { /* closed */ } }); },@@ -196,7 +198,7 @@ function place(label: string, bots: Bot[], version?: number) {}const api = {- dir, bots, runs, sent, results, requests, opened, handed, boot, listen, unplug, shutdown, handOff, keep, ledger,+ dir, bots, runs, sent, results, requests, opened, handed, handedFails, boot, listen, unplug, shutdown, handOff, keep, ledger,nextResult(): Promise<void> {return new Promise((resolve) => {const listener = () => { resultListeners.delete(listener); resolve(); };@@ -408,12 +410,21 @@ describe("the link between a computer and its Cloud", () => {expect(cloud.opened).toEqual([{ threadId: "cloud-analyst-work-1", title: "@Writer · work", from: "Writer", brief: "Count the orders" }]);// One line per hand-off in the Cloud bot's main chat, each pointing at the thread its work ran in.expect(cloud.handed).toEqual([- { botId: "cloud-analyst", threadId: "cloud-analyst-work-1", from: "Writer", text: "Count the orders" },- { botId: "cloud-analyst", threadId: "cloud-analyst-work-1", from: "Writer", text: "Now the refunds" },+ { botId: "cloud-analyst", threadId: "cloud-analyst-work-1", from: { botId: expect.stringContaining("local-writer"), name: "Writer" }, text: "Count the orders" },+ { botId: "cloud-analyst", threadId: "cloud-analyst-work-1", from: { botId: expect.stringContaining("local-writer"), name: "Writer" }, text: "Now the refunds" },]);expect(computer.handed).toEqual([]);});+ it("a hand-off line that cannot be written never stops the work it records", async () => {+ const { computer, cloud } = await two();+ cloud.handedFails.on = true;+ await computer.handOff("local-writer", call(["Analyst"], "Count the orders"));+ await until(() => computer.results.length === 1, "the result is back");+ expect(computer.results[0]).toMatchObject({ status: "completed", result: "cloud-analyst did: Count the orders" });+ expect(cloud.handed).toEqual([]);+ });+it("a call that got one instruction-only local refusal and one real refusal from the other place fails, and says why", async () => {const { computer } = await two();const nothingLeft = "nothing of Writer's waits on an answer as a1: it was answered or its work ended. Send it without answers if it still needs doing";diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex 707fd68362..1e1dd9b2f9 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -134,7 +134,7 @@ export interface BotLinkDeps {openThread(bot: LocalBot, title: string, opener: { botId: string; name: string; threadId: string }, brief: string): string | undefined;hasThread(botId: string, threadId: string): boolean;/** Work from the other place reached `botId`'s thread `threadId`: its main chat may say so (server/host/handed-line.ts). */- handed?(input: { botId: string; threadId: string; from: string; text: string }): void;+ handed?(input: { botId: string; threadId: string; from: { botId: string; name: string }; text: string }): void;personName(threadId: string): string | undefined;/** "Sent to …" in the requester's conversation. */sentRow(input: { sender: LocalBot; threadId: string; recipient: { id: string; name: string }; workThreadId: string; nodeId: string; reason?: string; doneWhen?: string;@@ -538,7 +538,11 @@ export function createBotLink(deps: BotLinkDeps) {work.child = node.id;state.work[frame.id] = work;// 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 });+ // A failure there never stops the work: it is logged, and the hand-off goes on.+ if (!frame.thread.includes(":room:")) {+ try { deps.handed?.({ botId: bot.id, threadId, from: { botId: address.botId, name: frame.from.name }, text: frame.text }); }+ catch (error) { log(`bot link: the hand-off line for ${frame.id} was not written (${said(error)})`); }+ }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.tsindex c75c7f4fb5..9303c7b82e 100644--- a/server/chat-notices.ts+++ b/server/chat-notices.ts@@ -121,6 +121,7 @@ export const CHAT_NOTICE = {"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.askedMeTimes": "{bot} asked me {count} times: {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.tsindex ce15851d6a..4878742a7a 100644--- a/server/direct-coordination.e2e.test.ts+++ b/server/direct-coordination.e2e.test.ts@@ -428,10 +428,12 @@ it("leaves one quiet line in the teammate's main chat for a hand-off, which openconst lines = (await f.messages(f.lead.activeTaskId)).filter((message: any) => message.threadRef?.threadId === child.threadId);expect(lines).toHaveLength(1);expect(lines[0]).toMatchObject({ role: "bot", kind: "activity", threadRef: { botId: f.lead.id, threadId: child.threadId, title: "Octopus facts" },- tool: { name: "Clive asked me: Octopus facts", ok: true, nameCode: "chat.notice.askedMe", nameParams: { bot: "Clive", title: "Octopus facts" } } });+ tool: { name: "Clive asked me: Octopus facts", ok: true, nameCode: "chat.notice.askedMe", nameParams: { bot: "Clive", title: "Octopus facts" } },+ askedBy: { botId: f.chief.id, name: "Clive", threadIds: [child.threadId] } });expect(lines[0].tool).not.toHaveProperty("itemId");+ // A record, not an announcement: the lead's main chat is not marked unread for it.const leadBot = (await f.api("/api/bots")).bots.find((bot: any) => bot.id === f.lead.id);- expect(leadBot.tasks.find((task: any) => task.threadId === f.lead.activeTaskId).unread).toBe(true);+ expect(leadBot.tasks.find((task: any) => task.threadId === f.lead.activeTaskId).unread).toBeFalsy();// 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.diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.tsindex 2689619773..46d6616076 100644--- a/server/host/bot-link-host.ts+++ b/server/host/bot-link-host.ts@@ -36,7 +36,7 @@ export interface BotLinkHostDeps {/** A work thread a far bot opened here is named from the job it handed, behind "@Sender · ". */titleHanded?(botId: string, threadId: string, brief: string, prefix: string): void;/** One line in the receiving bot's main chat for each hand-off the other place sends it (server/host/handed-line.ts). */- handedLine?(input: { botId: string; threadId: string; from: string; text: string }): void;+ handedLine?(input: { botId: string; threadId: string; from: { botId: string; name: string }; text: string }): void;refusal(bot: BotRecord): string | null;/** Why this bot cannot take work from the other place now (server/bot-link/far-side.ts), or null. */acceptRefusal?(bot: BotRecord): string | null;diff --git a/server/host/handed-line.test.ts b/server/host/handed-line.test.tsindex 36d277a229..ae6a0aa61d 100644--- a/server/host/handed-line.test.ts+++ b/server/host/handed-line.test.ts@@ -2,58 +2,134 @@ import { describe, expect, it } from "vitest";import { replayToolCalls } from "../context-rebuild.ts";import { isContextMessage } from "../delta-context.ts";+import { reviewTranscript } from "../skill-review.ts";import type { Message } from "../store.ts";-import { handedLine, handedSummary, postHandedLine, type HandedLineDeps } from "./handed-line.ts";+import { handedLine, handedMainThread, handedSummary, postHandedLine, writeHandedLine, type HandedLineDeps } from "./handed-line.ts";-function fakeStore(threads: Record<string, { title: string; unread?: boolean }>) {- const appended: Array<{ threadId: string; message: Omit<Message, "id" | "at"> }> = [];- const patched: Array<{ botId: string; threadId: string; patch: Record<string, unknown> }> = [];+const MOCHI = { botId: "mochi", name: "Mochi" };+const KAI = { botId: "kai", name: "Kai" };++function fakeStore(threads: Record<string, { title: string; archivedAt?: number }>, path: Message[] = []) {+ const main = [...path];+ const calls: string[] = [];const store = {- taskByThread: (_botId: string, threadId: string) => threads[threadId] ? { threadId, ...threads[threadId] } : null,- appendMessage: (threadId: string, message: Omit<Message, "id" | "at">) => { appended.push({ threadId, message }); return { ...message, id: `m${appended.length}`, at: 1 }; },- patchTask: (botId: string, threadId: string, patch: Record<string, unknown>) => { patched.push({ botId, threadId, patch }); return null; },+ taskByThread: (_botId: string, threadId: string) => threads[threadId] ? { threadId, ...threads[threadId] } : undefined,+ activePath: () => main,+ appendMessage: (threadId: string, message: Omit<Message, "id" | "at">) => {+ calls.push(`append ${threadId}`);+ const full = { ...message, id: `m${main.length + 1}`, at: main.length + 1 } as Message;+ main.push(full);+ return full;+ },+ patchMessage: (threadId: string, id: string, patch: Partial<Message>) => {+ calls.push(`patch ${threadId} ${id}`);+ const index = main.findIndex((message) => message.id === id);+ main[index] = { ...main[index]!, ...patch };+ return main[index]!;+ },+ patchTask: () => { calls.push("patchTask"); return null; },} as unknown as HandedLineDeps["store"];- return { store, appended, patched };+ return { store, main, calls, deps: { store, mainThread: () => "main" } as HandedLineDeps };}+const person = (id: string): Message => ({ id, at: 0, role: "user", kind: "text", text: "hello" });+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" },- { botId: "sage", threadId: "work", from: "Mochi", text: "Find three octopus facts", title: "Octopus facts" });- expect(id).toBe("m1");- expect(appended).toEqual([{ threadId: "main", message: {+ it("records who asked and for what, opens the hand-off thread, and marks nothing unread", () => {+ const { main, calls, deps } = fakeStore({ main: { title: "Garden" }, work: { title: "Octopus facts" } });+ expect(postHandedLine(deps, { botId: "sage", threadId: "work", from: MOCHI, text: "Find three octopus facts", title: "Octopus facts" })).toBe("m1");+ expect(main).toEqual([expect.objectContaining({role: "bot", kind: "activity",tool: { name: "Mochi asked me: Octopus facts", ok: true, nameCode: "chat.notice.askedMe", nameParams: { bot: "Mochi", title: "Octopus facts" } },threadRef: { botId: "sage", threadId: "work", title: "Octopus facts" },- } }]);- expect(patched).toEqual([{ botId: "sage", threadId: "main", patch: { unread: true } }]);+ askedBy: { botId: "mochi", name: "Mochi", threadIds: ["work"] },+ })]);+ expect(calls).toEqual(["append main"]);+ });++ it("keeps one line per hand-off thread: a follow-up, a consult round or rework into it adds nothing", () => {+ const { main, calls, deps } = fakeStore({ main: { title: "Garden" }, work: { title: "Octopus facts" } });+ postHandedLine(deps, { botId: "sage", threadId: "work", from: MOCHI, text: "Find octopus facts" });+ main.push(person("p1"));+ expect(postHandedLine(deps, { botId: "sage", threadId: "work", from: MOCHI, text: "Check them again" })).toBeUndefined();+ expect(postHandedLine(deps, { botId: "sage", threadId: "work", from: KAI, text: "And from me" })).toBeUndefined();+ expect(calls).toEqual(["append main"]);+ });++ it("folds fresh hand-offs from the same bot with nothing from the person in between into one line with a count", () => {+ const threads = { main: { title: "Garden" }, w1: { title: "One" }, w2: { title: "Two" }, w3: { title: "Three" }, w4: { title: "Four" } };+ const { main, calls, deps } = fakeStore(threads);+ for (const id of ["w1", "w2", "w3", "w4"]) postHandedLine(deps, { botId: "sage", threadId: id, from: MOCHI, text: threads[id as keyof typeof threads].title });+ expect(main).toHaveLength(1);+ expect(main[0]).toMatchObject({+ tool: { name: "Mochi asked me 4 times: Four", nameCode: "chat.notice.askedMeTimes", nameParams: { bot: "Mochi", count: 4, title: "Four" } },+ threadRef: { threadId: "w4", title: "Four" }, askedBy: { botId: "mochi", count: 4, threadIds: ["w1", "w2", "w3", "w4"] },+ });+ expect(calls).toEqual(["append main", "patch main m1", "patch main m1", "patch main m1"]);+ // A follow-up into any thread the folded line covers still adds nothing.+ expect(postHandedLine(deps, { botId: "sage", threadId: "w2", from: MOCHI, text: "again" })).toBeUndefined();+ });++ it("starts a new line once the person wrote, or another bot asks", () => {+ const threads = { main: { title: "Garden" }, w1: { title: "One" }, w2: { title: "Two" }, w3: { title: "Three" } };+ const { main, deps } = fakeStore(threads);+ postHandedLine(deps, { botId: "sage", threadId: "w1", from: MOCHI, text: "One" });+ main.push(person("p1"));+ postHandedLine(deps, { botId: "sage", threadId: "w2", from: MOCHI, text: "Two" });+ postHandedLine(deps, { botId: "sage", threadId: "w3", from: KAI, text: "Three" });+ expect(main.filter((message) => message.askedBy).map((message) => [message.askedBy!.botId, message.threadRef!.threadId])).toEqual([["mochi", "w1"], ["mochi", "w2"], ["kai", "w3"]]);+ });++ it("does not count a bot's or a routine's line as the person's", () => {+ const threads = { main: { title: "Garden" }, w1: { title: "One" }, w2: { title: "Two" } };+ const { main, deps } = fakeStore(threads);+ postHandedLine(deps, { botId: "sage", threadId: "w1", from: MOCHI, text: "One" });+ main.push({ ...person("auto"), automated: true }, { id: "reply", at: 0, role: "bot", kind: "text", text: "Done." });+ postHandedLine(deps, { botId: "sage", threadId: "w2", from: MOCHI, text: "Two" });+ expect(main.filter((message) => message.askedBy)).toHaveLength(1);});- 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" };- 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();- expect(postHandedLine({ ...deps, mainThread: () => "missing" }, { botId: "sage", threadId: "work", from: "Mochi", text: "x" })).toBeUndefined();- expect(appended).toEqual([]);- expect(patched).toEqual([]);+ it("writes nothing when the work runs in the main chat, the main chat is archived, or a thread is gone", () => {+ const { calls, deps } = fakeStore({ main: { title: "Garden" }, work: { title: "Work" } });+ 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();+ const archived = fakeStore({ main: { title: "Garden", archivedAt: 5 }, work: { title: "Work" } });+ expect(postHandedLine(archived.deps, { botId: "sage", threadId: "work", from: MOCHI, text: "x" })).toBeUndefined();+ expect([...calls, ...archived.calls]).toEqual([]);});- it("says the request on one line, cut short, when the sender gave no title", () => {+ it("finds no main chat while the one the person chose is archived, instead of falling back to another", () => {+ const archived = new Set(["chosen"]);+ expect(handedMainThread({ mainThreadChoice: "chosen" }, (id) => archived.has(id), () => "oldest")).toBeUndefined();+ expect(handedMainThread({ mainThreadChoice: "other" }, (id) => archived.has(id), () => "other")).toBe("other");+ expect(handedMainThread({ mainThreadChoice: "x", mainThreadKept: { id: "chosen", under: "x" } }, (id) => archived.has(id), () => "oldest")).toBeUndefined();+ expect(handedMainThread({}, () => false, () => "first")).toBe("first");+ });++ it("caps what the line says at 60 characters, a sender's title too", () => {expect(handedSummary(" Find three\n\noctopus facts ")).toBe("Find three octopus facts");const long = handedSummary("word ".repeat(40));expect([...long].length).toBeLessThanOrEqual(60);expect(long.endsWith("…")).toBe(true);expect(handedSummary("ignored", " Octopus facts ")).toBe("Octopus facts");+ const title = handedSummary("ignored", "T".repeat(200));+ expect([...title].length).toBe(60);+ expect(title.endsWith("…")).toBe(true);+ });++ it("never lets a failure in the line stop the hand-off: it is logged", () => {+ const logged: string[] = [];+ expect(() => writeHandedLine(() => { throw new Error("disk full"); }, (line) => logged.push(line))).not.toThrow();+ expect(logged).toEqual(["hand-off line not written: disk full"]);});- it("is never context for the bot's model: not a message, not a replayed tool call", () => {- const line = { ...handedLine({ from: "Mochi", summary: "Octopus facts", botId: "sage", threadId: "work", threadTitle: "Octopus facts" }), id: "line", at: 2 } as Message;+ it("is never context for the bot's model: not a message, not a replayed tool call, not in a skill review", () => {+ const line = { ...handedLine({ from: MOCHI, summary: "Octopus facts", botId: "sage", threadId: "work", threadTitle: "Octopus facts" }), id: "line", at: 2 } as Message;expect(isContextMessage(line)).toBe(false);const before = { id: "a", at: 1, role: "user", kind: "text", text: "Hello" } as Message;const after = { id: "b", at: 3, role: "bot", kind: "text", text: "Hi" } as Message;expect(replayToolCalls([before, line, after], { replayToolHistory: true }, {})).toEqual([]);+ expect(reviewTranscript([before, line, after], { id: "sage", name: "Sage" }, false)).not.toContain("asked me");});});diff --git a/server/host/handed-line.ts b/server/host/handed-line.tsindex 1b5e0ab094..7189203ffc 100644--- a/server/host/handed-line.ts+++ b/server/host/handed-line.ts@@ -1,47 +1,83 @@// A bot a teammate hands work to does it in a thread of its own, which closes once the result is back. So that opening-// the bot shows the work happened, its main chat gets one quiet line per hand-off ("Mochi asked me: Octopus facts"),-// 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.+// the bot shows the work happened, its main chat keeps one quiet line for it ("Mochi asked me: Octopus facts"), which+// opens that thread. The line is a record, not an announcement: it marks nothing unread, buzzes nothing and puts nothing+// in the Inbox. It is an activity row with no tool item, so it is never context for the bot's model+// (delta-context.ts isContextMessage, context-rebuild.ts replayToolCalls, skill-review.ts), and it starts no turn.+// It stays bounded: one line per hand-off thread, and fresh hand-offs from the same bot with nothing from the person in+// between fold into the line already there, with a count.import { noticeTool } from "../chat-notices.ts";import type { Message, Store } from "../store.ts";const SUMMARY_MAX = 60;+/** How many hand-off threads one folded line remembers, so a follow-up into any of them adds nothing. */+const THREADS_KEPT = 50;-/** What was asked, as the line says it: the title the sender gave, else the start of its message on one line. */+type AskedBy = NonNullable<Message["askedBy"]>;++function clipped(text: string): string {+ const characters = [...text];+ return characters.length <= SUMMARY_MAX ? text : `${characters.slice(0, SUMMARY_MAX - 1).join("").trimEnd()}…`;+}++/** What was asked, as the line says it: the title the sender gave, else the start of its message, on one line and short. */export function handedSummary(text: string, title?: string): string {const named = title?.replace(/\s+/g, " ").trim();- if (named) return named;- const words = text.replace(/\s+/g, " ").trim();- const characters = [...words];- return characters.length <= SUMMARY_MAX ? words : `${characters.slice(0, SUMMARY_MAX - 1).join("").trimEnd()}…`;+ return clipped(named || text.replace(/\s+/g, " ").trim());}/** 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"> {+export function handedLine(input: { from: { botId: string; name: string }; summary: string; botId: string; threadId: string; threadTitle: string; count?: number; threadIds?: string[] }): Omit<Message, "id" | "at"> {+ const count = input.count ?? 1;return {role: "bot", kind: "activity",- tool: noticeTool("chat.notice.askedMe", { bot: input.from, title: input.summary }, { ok: true }),+ tool: count > 1+ ? noticeTool("chat.notice.askedMeTimes", { bot: input.from.name, count, title: input.summary }, { ok: true })+ : noticeTool("chat.notice.askedMe", { bot: input.from.name, title: input.summary }, { ok: true }),threadRef: { botId: input.botId, threadId: input.threadId, title: input.threadTitle },+ askedBy: { botId: input.from.botId, name: input.from.name, ...(count > 1 ? { count } : {}), threadIds: input.threadIds ?? [input.threadId] },};}+/** A line the person wrote, not one a bot, routine or app sent in. */+const fromThePerson = (message: Message) => message.role === "user" && !message.automated && !message.peerAsk && !message.aside;+export type HandedLineDeps = {- store: Pick<Store, "appendMessage" | "patchTask" | "taskByThread">;- /** The bot's main chat with the person. */+ store: Pick<Store, "appendMessage" | "patchMessage" | "taskByThread" | "activePath">;+ /** The bot's main chat with the person, or undefined when it has none open to write in. */mainThread(botId: 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.- * Nothing when the work runs in the main chat itself. Returns the line's id. */-export function postHandedLine(deps: HandedLineDeps, input: { botId: string; threadId: string; from: string; text: string; title?: string }): string | undefined {+/** Records one hand-off to `botId`, worked in `threadId`, in the bot's main chat. Nothing when the work runs in the main+ * chat itself, the main chat is archived, or a line there already opens this thread. Returns the line's id. */+export function postHandedLine(deps: HandedLineDeps, input: { botId: string; threadId: string; from: { botId: string; name: string }; text: string; title?: string }): string | undefined {const main = deps.mainThread(input.botId);if (!main || main === input.threadId) return undefined;- 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 });- const { id } = deps.store.appendMessage(main, line);- deps.store.patchTask(input.botId, main, { unread: true });- return id;+ const work = deps.store.taskByThread(input.botId, input.threadId), home = deps.store.taskByThread(input.botId, main);+ if (!work || !home || home.archivedAt !== undefined) return undefined;+ const path = deps.store.activePath(main);+ const lines = path.filter((message) => message.askedBy !== undefined);+ if (lines.some((message) => message.askedBy!.threadIds?.includes(input.threadId) || message.threadRef?.threadId === input.threadId)) return undefined;+ const summary = handedSummary(input.text, input.title);+ const last = lines.at(-1);+ const lastAt = last ? path.lastIndexOf(last) : -1;+ if (last && last.askedBy!.botId === input.from.botId && !path.slice(lastAt + 1).some(fromThePerson)) {+ const was: AskedBy = last.askedBy!;+ const threadIds = [...(was.threadIds ?? []), input.threadId].slice(-THREADS_KEPT);+ const line = handedLine({ from: input.from, summary, botId: input.botId, threadId: input.threadId, threadTitle: work.title, count: (was.count ?? 1) + 1, threadIds });+ return deps.store.patchMessage(main, last.id, line)?.id;+ }+ return deps.store.appendMessage(main, handedLine({ from: input.from, summary, botId: input.botId, threadId: input.threadId, threadTitle: work.title })).id;+}++/** The main chat a hand-off line goes to: none while the main chat the person chose is archived, rather than another one. */+export function handedMainThread(bot: { mainThreadChoice?: string; mainThreadKept?: { id: string; under?: string } } | null | undefined,+ archived: (threadId: string) => boolean, main: () => string | undefined): string | undefined {+ const chosen = bot?.mainThreadKept && bot.mainThreadKept.under === bot.mainThreadChoice ? bot.mainThreadKept.id : bot?.mainThreadChoice;+ if (chosen && archived(chosen)) return undefined;+ return main();+}++/** Runs `post` so that a failure in the line never stops the hand-off it records: the work goes on, the error is logged. */+export function writeHandedLine(post: () => unknown, log: (line: string) => void): void {+ try { post(); } catch (error) { log(`hand-off line not written: ${error instanceof Error ? error.message : String(error)}`); }}diff --git a/server/index.ts b/server/index.tsindex cebf28f544..77e17b612e 100644--- a/server/index.ts+++ b/server/index.ts@@ -332,7 +332,7 @@ import { buildRecoveryText, buildTurnContext, replaysNatively } from "./turn-conimport { Handoffs, isContextMessage, recordHanded, renderUnseen, sessionStart, withUnseenMessages, type ContextMessage } from "./delta-context.ts"; import { isFreshStart, sinceFreshStart } from "./fresh-start.ts";import { extractReplayImages, extractTurnImages, nativeClips, turnMedia, videoFramesWithin } from "./turn-images.ts";import { callTitleExcerpt } from "./thread-title.ts";-import { generateThreadTitle } from "./thread-title-generate.ts"; import { createHandedThreadTitle } from "./host/handed-thread-title.ts"; import { postHandedLine, type HandedLineDeps } from "./host/handed-line.ts";+import { generateThreadTitle } from "./thread-title-generate.ts"; import { createHandedThreadTitle } from "./host/handed-thread-title.ts"; import { handedMainThread, postHandedLine, writeHandedLine, type HandedLineDeps } from "./host/handed-line.ts";import { engineCommandCpuMs, engineProcessExited, engineProcessGone, ENGINE_EXIT_STALL_MS, stallLimitMs, stallNotice, TurnWatchdog } from "./turn-watchdog.ts"; import { createIdleThreads } from "./host/idle-threads.ts"; import { createDispatchClaims } from "./host/dispatch-claims.ts";import { TurnResources, type TurnOwner } from "./turn-resources.ts";import { createPhoneHold } from "./phone-screen/hold.ts"; import { createPhoneGate } from "./routes/phone-gate.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 }; 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) => handedMainThread(store.bot(botId), (threadId) => store.taskByThread(botId, threadId)?.archivedAt !== undefined, () => 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),@@ -13599,7 +13599,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {...(via === "room" ? {} : { threadId: node.threadId }),}));if (!duplicate) {- if (!EXTERNAL) delegatedThisTurn(node.id); if (handedLines && via === "direct" && !post && !call.answers && recipient.id !== internalSender.id) postHandedLine(handedLines, { botId: recipient.id, threadId: node.threadId, from: internalSender.name, text: call.message, ...(call.title ? { title: call.title } : {}) });+ if (!EXTERNAL) delegatedThisTurn(node.id); if (handedLines && via === "direct" && !post && !call.answers && recipient.id !== internalSender.id) writeHandedLine(() => postHandedLine(handedLines, { botId: recipient.id, threadId: node.threadId, from: { botId: internalSender.id, name: internalSender.name }, text: call.message, ...(call.title ? { title: call.title } : {}) }), (line) => console.error(line));const sentRowId = post ? undefined : store.appendMessage(address.threadId, sentRow({ sender: internalSender, recipient, threadId: node.threadId, room: addressedRoom, via, language: threadLanguage(address.threadId),reason: call.reason, doneWhen: call.doneWhen ? redactSecretsInText(call.doneWhen) : undefined, title: store.taskByThread(recipient.id, node.threadId)?.title, ...handoffFiles.sentWith(node.id) })).id; if (sentRowId && via !== "room") handoffStatus.track(node.id, address.threadId, sentRowId);}diff --git a/server/notification-routing.e2e.test.ts b/server/notification-routing.e2e.test.tsindex 8477820a62..f652fe1471 100644--- a/server/notification-routing.e2e.test.ts+++ b/server/notification-routing.e2e.test.ts@@ -530,10 +530,8 @@ describe("bot-to-bot coordination is recorded, not announced", () => {const consult = await consultation(asked.body.receipts[0].requestId);expect(consult.threadId).not.toBe(peer.threadId);await expect.poll(() => handoffs().find((node) => node.id === consult.id)?.status, { timeout: 20_000 }).toBe("completed");- // The hand-off's quiet line marks Vellum's chat unread; read it, so the mark below is the person's own message.- expect((await botState(peer.id))?.unread).toBe(true);- expect((await api("POST", `/api/bots/${peer.id}/read`, { reason: "select" })).status).toBeLessThan(300);- await expect.poll(async () => (await botState(peer.id))?.unread, { timeout: 10_000 }).toBeFalsy();+ // The hand-off is recorded in Vellum's chat, not announced: nothing there is unread.+ expect((await botState(peer.id))?.unread).toBeFalsy();expect((await api("POST", `/api/bots/${peer.id}/messages`, { text: "and for me?" })).status).toBe(202);const frame = await stream.until(@@ -570,10 +568,8 @@ describe("bot-to-bot coordination is recorded, not announced", () => {expect(asked.body.receipts[0]).toMatchObject({ botId: peer.id, outcome: "queued" });const consult = await consultation(asked.body.receipts[0].requestId);expect(consult.threadId).not.toBe(peer.threadId);- // The hand-off's quiet line marks Folio's chat unread; read it, so the mark below is the person's own message.- expect((await botState(peer.id))?.unread).toBe(true);- expect((await api("POST", `/api/bots/${peer.id}/read`, { reason: "select" })).status).toBeLessThan(300);- await expect.poll(async () => (await botState(peer.id))?.unread, { timeout: 10_000 }).toBeFalsy();+ // The hand-off is recorded in Folio's chat, not announced: nothing there is unread.+ expect((await botState(peer.id))?.unread).toBeFalsy();expect((await api("PATCH", `/api/bots/${peer.id}`, {modelSelection: { instanceId: "quick", model: "claude-sonnet-5" },diff --git a/server/skill-review.ts b/server/skill-review.tsindex 1f0ef6f0d4..8534f6c3d3 100644--- a/server/skill-review.ts+++ b/server/skill-review.ts@@ -86,7 +86,7 @@ function entriesFor(messages: readonly ReviewMessage[], bot: { id: string; name:if (message.kind === "text" && message.text?.trim()) {if (message.role === "user") entries.push({ role: "person", speaker: "Person", text: message.text });else entries.push({ role: mine ? "self" : "other", speaker: mine ? bot.name : message.from?.name ?? "Another bot", text: message.text });- } else if (message.kind === "activity" && message.tool?.name && !message.tool.setup && mine) {+ } else if (message.kind === "activity" && message.tool?.name && !message.tool.setup && !message.tool.nameCode?.startsWith("chat.notice.") && mine) {const detail = [message.tool.input, message.tool.summary].filter((part): part is string => Boolean(part?.trim())).map((part) => oneLine(part, 160)).join(" — ");entries.push({ role: "tool", speaker: bot.name, text: `${message.tool.name}${message.tool.ok === false ? " (failed)" : ""}${detail ? `: ${detail}` : ""}` });} else if (message.kind === "options" && message.card?.skillRequest && (message.card.skillRequest.botId === bot.id)) {diff --git a/server/thread-aware-bots.e2e.test.ts b/server/thread-aware-bots.e2e.test.tsindex aff983951f..8cf9d72bfb 100644--- a/server/thread-aware-bots.e2e.test.ts+++ b/server/thread-aware-bots.e2e.test.ts@@ -655,12 +655,13 @@ 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([]);- // 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]);+ // The person's conversation with the teammate records the three hand-offs into one thread as one quiet line that+ // opens it; nothing is marked unread, and the work stays in its own thread.+ expect((await botState(qa.id)).tasks.filter((task: any) => task.unread)).toEqual([]);expect((await botState(qa.id)).threadId).toBe(qa.threadId);- 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]);+ const handedLine = expect.objectContaining({ role: "bot", kind: "activity", threadRef: expect.objectContaining({ botId: qa.id, threadId: thread }),+ tool: expect.objectContaining({ nameCode: "chat.notice.askedMe" }), askedBy: expect.objectContaining({ botId: pm.id, threadIds: [thread] }) });+ expect(await messages(qa.threadId)).toEqual([...originalConversation, handedLine]);} finally {stream.close();await cleanup([pm.id, qa.id]);diff --git a/src/components/ThreadChip.test.ts b/src/components/ThreadChip.test.tsindex e8c2e1d844..fa82cddf39 100644--- a/src/components/ThreadChip.test.ts+++ b/src/components/ThreadChip.test.ts@@ -10,14 +10,17 @@ const scout: Bot = {tasks: [{ threadId: "scout-main", title: "Main", createdAt: 1 },{ threadId: "qa-245", title: "QA PR 245", createdAt: 2, openedBy: { botId: "ada", name: "Ada", at: 2 } },+ { threadId: "octopus", title: "Octopus facts", createdAt: 3, openedBy: { botId: "ada", name: "Ada", at: 3 }, closedBy: { botId: "ada", name: "Ada", at: 4 }, archivedAt: 4 },],};+const ada: Bot = { ...scout, id: "ada", threadId: "ada-main", name: "Ada", color: "orange", tasks: [{ threadId: "ada-main", title: "Main", createdAt: 1 }] };vi.mock("@/state/store", async (importOriginal) => {const original = await importOriginal<typeof import("@/state/store")>();- return { ...original, useStore: () => ({ state: { ...original.initialState, bots: [scout] }, dispatch: fixture.dispatch }) };+ return { ...original, useStore: () => ({ state: { ...original.initialState, bots: [scout, ada] }, dispatch: fixture.dispatch }) };});vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => fixture.showThreads }));import { ThreadChip } from "./ThreadChip";+import { BotAvatar } from "./Avatar";const receipt = (threadId = "qa-245"): Message => ({id: "receipt", role: "bot", kind: "activity", at: 3,@@ -37,7 +40,39 @@ function findElement(tree: ReactNode, attribute: string): ReactElement<ElementPrbeforeEach(() => { fixture.dispatch.mockClear(); fixture.showThreads = true; });+function findType(tree: ReactNode, type: unknown): ReactElement<ElementProps> | undefined {+ for (const child of Children.toArray(tree)) {+ if (!isValidElement<ElementProps>(child)) continue;+ if (child.type === type) return child;+ const found = findType(child.props.children, type);+ if (found) return found;+ }+}+describe("ThreadChip", () => {+ it("shows the bot that asked on the line that records a hand-off, and opens the archived hand-off thread", () => {+ const line: Message = { id: "asked", role: "bot", kind: "activity", at: 5,+ tool: { name: "Ada asked me: Octopus facts", ok: true, nameCode: "chat.notice.askedMe", nameParams: { bot: "Ada", title: "Octopus facts" } },+ threadRef: { botId: "scout", threadId: "octopus", title: "Octopus facts" }, askedBy: { botId: "ada", name: "Ada", threadIds: ["octopus"] } };+ let tree: ReactNode;+ function Capture() { tree = ThreadChip({ message: line }); return tree; }+ expect(renderToStaticMarkup(createElement(Capture))).toContain("Ada asked me: Octopus facts");+ expect((findType(tree, BotAvatar)!.props.bot as Bot).id).toBe("ada");+ findElement(tree, "data-thread-chip")!.props.onClick!();+ expect(fixture.dispatch.mock.calls.map(([action]) => action)).toEqual([+ { type: "select", id: "scout" },+ { type: "switchTask", botId: "scout", threadId: "octopus" },+ { type: "revealThread", threadId: "octopus" },+ ]);+ });++ it("keeps the thread's own bot on every other chip", () => {+ let tree: ReactNode;+ function Capture() { tree = ThreadChip({ message: receipt() }); return tree; }+ renderToStaticMarkup(createElement(Capture));+ expect((findType(tree, BotAvatar)!.props.bot as Bot).id).toBe("scout");+ });+it("renders the receipt as a pill named for the thread it opens", () => {const markup = renderToStaticMarkup(createElement(ThreadChip, { message: receipt() }));expect(markup).toContain("<button");diff --git a/src/components/ThreadChip.tsx b/src/components/ThreadChip.tsxindex 47cc21d3b2..f350cc1d4c 100644--- a/src/components/ThreadChip.tsx+++ b/src/components/ThreadChip.tsx@@ -30,6 +30,8 @@ export function ThreadChip({ message, threadId }: { message: Message; threadId?:? { asker, helper: { botId: bot.id, name: bot.name, color: bot.color }, threadId: ref.threadId, ...(handoff ? { id: handoff.id, sentAt: message.at, ...(ended ? { endedAt: handoff.at } : {}) } : {}) }: null;const exchangeLabel = bot ? t("chat.handoffExchange.open", { name: bot.name }) : "";+ // The line that records a hand-off in the helper's own chat shows the bot that asked.+ const pictured = message.askedBy ? state.bots.find((candidate) => candidate.id === message.askedBy!.botId) : bot;return (<HandoffReply message={message} threadId={threadId}><span className="flex min-w-0 max-w-full flex-wrap items-center gap-x-2 gap-y-1">@@ -54,7 +56,7 @@ export function ThreadChip({ message, threadId }: { message: Message; threadId?:title={t("chat.openThread", { title: ref.title })}className={cn("ui-pill", tool.ok === false && "text-danger")}>- {bot ? <BotAvatar bot={bot} state="happy" size={16} animated={false} /> : <MessagesSquare size={13} aria-hidden="true" />}+ {pictured ? <BotAvatar bot={pictured} state="happy" size={16} animated={false} /> : <MessagesSquare size={13} aria-hidden="true" />}<span className="max-w-[480px] truncate">{label}</span><ChevronRight size={13} /></button>diff --git a/src/locales/en.json b/src/locales/en.jsonindex 49db4a9c51..b02e243b28 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -10300,6 +10300,7 @@"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.askedMeTimes": "{bot} asked me {count} times: {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/src/locales/pt-br.json b/src/locales/pt-br.jsonindex f0b2ca86dd..908c8e1baa 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10220,6 +10220,7 @@"chat.notice.waitingAnswerElsewhere": "Esperando sua resposta em @{name}","chat.notice.teammateNeedsInput": "{name} precisa da sua resposta: {question}","chat.notice.askedMe": "{bot} me pediu: {title}",+ "chat.notice.askedMeTimes": "{bot} me pediu {count} vezes: {title}","chat.notice.waitingPasswordElsewhere": "Esperando você em @{name}: {label}","chat.notice.waitingSignInElsewhere": "Esperando você entrar em {label} em @{name}","chat.notice.waitingConnectElsewhere": "Esperando você conectar {label} em @{name}",diff --git a/src/state/store.tsx b/src/state/store.tsxindex 837cdcd55b..4cb75236c5 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -116,7 +116,7 @@ export type SecretRequestCardData = Omit<import("../../shared/wire").SecretRequeexport type ComputerControlState = { held: boolean; helpReason: string | null; help?: import("../../shared/wire").ComputerHelpRef | null };-export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "automated" | "waitId" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "template" | "sender" | "setupSuggestion" | "settingsCard" | "helperIntro" | "helperFollowup" | "setupOffer" | "savedSteps" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen" | "checkBack" | "checkRound" | "handoff" | "bugReport" | "engineCompaction" | "stoppedBy"> {+export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "automated" | "waitId" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "template" | "sender" | "setupSuggestion" | "settingsCard" | "helperIntro" | "helperFollowup" | "setupOffer" | "savedSteps" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen" | "checkBack" | "checkRound" | "handoff" | "bugReport" | "engineCompaction" | "stoppedBy" | "askedBy"> {id: string;role: "bot" | "user";kind: "text" | "options" | "activity" | "screen" | "connector" | "secret" | "signin" | "routine.run" | "goal.run" | "burst" | "digest" | "compaction" | "call" | "widget" | "app";