Skip to content

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

Bots check back later, and hand-offs show who's working on what (2/2: hand-off status) (#6626)

Milind Soni20aaf4f3095e
diff --git a/docs/verification/README.md b/docs/verification/README.md
index 3c69deab90..0effa0a5bf 100644
--- a/docs/verification/README.md
+++ b/docs/verification/README.md
@@ -69,6 +69,7 @@ Use only mapped, tested commands:
- [Proactive routines and the brief](proactive-routines.md)
- [Waits: tell me when, with no AI while waiting](waits.md)
- [Check-backs: a bot comes back later by itself](check-backs.md)
+- [Hand-off status: who's working on what](handoff-status.md)
- [A new Cloud's first hour](first-hour.md)
- [Chat widgets](widgets.md)
- [Pages and apps in a room](room-pages.md)
diff --git a/docs/verification/evidence/followups/handoff-done-dark.png b/docs/verification/evidence/followups/handoff-done-dark.png
new file mode 100644
index 0000000000..552f5d656c
Binary files /dev/null and b/docs/verification/evidence/followups/handoff-done-dark.png differ
diff --git a/docs/verification/evidence/followups/handoff-done-light.png b/docs/verification/evidence/followups/handoff-done-light.png
new file mode 100644
index 0000000000..1f1cbb7b54
Binary files /dev/null and b/docs/verification/evidence/followups/handoff-done-light.png differ
diff --git a/docs/verification/evidence/followups/handoff-inbox-light.png b/docs/verification/evidence/followups/handoff-inbox-light.png
new file mode 100644
index 0000000000..10f081c04b
Binary files /dev/null and b/docs/verification/evidence/followups/handoff-inbox-light.png differ
diff --git a/docs/verification/evidence/followups/handoff-working-dark.png b/docs/verification/evidence/followups/handoff-working-dark.png
new file mode 100644
index 0000000000..e225d2ee11
Binary files /dev/null and b/docs/verification/evidence/followups/handoff-working-dark.png differ
diff --git a/docs/verification/evidence/followups/handoff-working-light.png b/docs/verification/evidence/followups/handoff-working-light.png
new file mode 100644
index 0000000000..67847e61fd
Binary files /dev/null and b/docs/verification/evidence/followups/handoff-working-light.png differ
diff --git a/docs/verification/handoff-status.md b/docs/verification/handoff-status.md
new file mode 100644
index 0000000000..11b97821e0
--- /dev/null
+++ b/docs/verification/handoff-status.md
@@ -0,0 +1,31 @@
+# Hand-off status: who's working on what
+
+When a bot hands work to another bot, its "Sent to …" row in the asking conversation carries a small status
+chip that updates live: **Claimed**, **Working**, **Waiting on <bot>** or **Waiting on you**, then **Done**
+(the row itself opens the conversation with the result) or **Failed: <one line why>**. The conversation that
+does the work carries the same status, so its row in the Inbox's active list says the same words. There is
+no new page and nothing to press; it is display only and never holds the work up.
+
+The status is read from the assignment records each time they are written (`server/host/handoff-status.ts`);
+no field is added to them. The rows it follows are kept in `handoff-lines.json` until they end, so a restart
+picks them up again.
+
+On a Team Cloud the chip also names whose request it is ("Working · for Mira") and the person a question waits
+on. When the work runs in a member's private chat and the row is somewhere that member doesn't own, the chip says
+only "for Mira (private)": no failure words, and the row's link loses the private chat's title. Everywhere else
+the chips name no person.
+
+Hand-offs into a room (its `comm` rows) keep their own room status and get no chip.
+
+## Automated checks
+
+```sh
+pnpm exec vitest run server/host/handoff-status.test.ts src/components/HandoffStatusChip.test.ts src/components/ThreadChip.test.ts src/components/SidebarBotActivity.test.ts
+OMB_TEST_PORTS=20900-20999 pnpm exec vitest run server/handoff-status.e2e.test.ts
+```
+
+The e2e test uses the scripted engine: Lead hands Coder a page, Coder hands Writer the copy, and Lead's row moves
+through working, waiting on Writer and done while Coder's work conversation shows the same; nobody presses anything.
+
+**What it does not prove:** phones (they show the row's English words), and a Team Cloud end to end (the unit
+tests cover its names and the private case).
diff --git a/packages/phone-protocol/src/handoff-status.ts b/packages/phone-protocol/src/handoff-status.ts
new file mode 100644
index 0000000000..db2873b082
--- /dev/null
+++ b/packages/phone-protocol/src/handoff-status.ts
@@ -0,0 +1,23 @@
+/** Where work one bot handed another stands: accepted, being worked on, waiting on someone, or ended. */
+export type HandoffState = "claimed" | "working" | "waiting" | "done" | "failed";
+
+/** A hand-off's status, on its "Sent to" row in the asking conversation (`WireMessage.handoff`) and on the conversation
+ * that does the work (`WireTask.handoff`). Names appear only on a Team Cloud; elsewhere a person waited on is "you". */
+export interface HandoffStatusLine {
+ /** The assignment's id. */
+ id: string;
+ state: HandoffState;
+ /** While waiting: on a bot (its name), or on a person (their name on a Team Cloud, none anywhere else). */
+ waitingOn?: { kind: "bot" | "person"; name?: string };
+ /** Failed: one line saying why. */
+ why?: string;
+ /** On a Team Cloud: whose request this is. `private`: it runs in their private chat, so a shared place shows only this. */
+ forPerson?: { name: string; private?: true };
+ /** When the state last changed, epoch ms. */
+ at: number;
+}
+
+/** `WireMessage.handoff` and `WireTask.handoff`. */
+export interface HandoffStatusField {
+ handoff?: HandoffStatusLine;
+}
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index 6a5b69a3d1..66f4a3e1c4 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -14,7 +14,7 @@ import type { CredentialTargetId, CUSTOM_SECRET_TARGET, SecretDelivery } from ".
import type { TeamSetupRequest } from "./team-setup.ts"; import type { DefaultBotFields, HelperIntroField } from "./default-bot.ts";
import type { SetupCardFields } from "./setup-card.ts"; import type { BugReportField } from "./devs-report-status.ts"; import type { AccessRequestCardField, BotAccessFields } from "./bot-access.ts";
import type { RoutineRequestCardData } from "./routine-request.ts"; import type { SavedStepsMark } from "./saved-steps.ts";
-import type { WebhookRequestCardData } from "./webhook-request.ts"; import type { WaitCardField, WaitLineField } from "./wait-request.ts"; import type { CheckBackLineField } from "./check-back.ts"; import type { ComputerAskField } from "./computer-ask.ts";
+import type { WebhookRequestCardData } from "./webhook-request.ts"; import type { WaitCardField, WaitLineField } from "./wait-request.ts"; import type { CheckBackLineField } from "./check-back.ts"; import type { HandoffStatusField } from "./handoff-status.ts"; import type { ComputerAskField } from "./computer-ask.ts";
import type { AppEventAttempt, AppTrigger, AppTriggerRequestCardData, AppTriggerService } from "./app-triggers.ts";
import type { ProfileRequestCardData } from "./profile-request.ts";
import type { ServerTextLine, ServerTextParams } from "./server-text.ts";
@@ -114,7 +114,7 @@ export interface BotMovedTo {
}
/** One task = one conversation with its own context, thread and provider session. */
-export interface WireTask extends InboxTask {
+export interface WireTask extends InboxTask, HandoffStatusField {
/** Outstanding handoffs, not an active provider turn. */
waitingForTeammates?: boolean;
threadId: string;
@@ -436,7 +436,7 @@ export type CardAnswerer = (
export const EXCERPT_SUMMARY_HEADER = "Historical excerpts in chronological order; newer corrections override older requests. These excerpts may omit earlier details.";
/** One transcript line, serialized as stored. */
-export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCardFields, WaitLineField, CheckBackLineField, BugReportField {
+export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCardFields, WaitLineField, CheckBackLineField, HandoffStatusField, BugReportField {
roomRequest?: { id: string; phase: "request" | "result" };
id: string;
role: "bot" | "user";
diff --git a/server/handoff-status.e2e.test.ts b/server/handoff-status.e2e.test.ts
new file mode 100644
index 0000000000..481d8475ff
--- /dev/null
+++ b/server/handoff-status.e2e.test.ts
@@ -0,0 +1,65 @@
+// A hand-off's status where people already look: Lead hands Coder a page, Coder hands Writer the copy, and Lead's "Sent
+// to Coder" row moves through claimed, working, waiting on Writer and done, while Coder's work conversation (what the
+// inbox lists) carries the same status. The scripted engine makes the real coordinate_bots calls through the agents
+// server; nobody presses anything.
+import { writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { request } from "../scripts/mcp-server.ts";
+
+it("moves the Sent-to row through claimed, working, waiting on a teammate and done, and the work conversation shows the same", async () => {
+ const session = await launchVerificationServer({ ...process.env }, undefined, undefined, undefined, undefined, { scripted: true });
+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: session.info.url } }) as Promise<any>;
+ const api = (path: string, init?: { method: string; body: unknown }) =>
+ request(path, init ? { method: init.method, body: JSON.stringify(init.body) } : {}, session.info.url) as Promise<any>;
+ const plan = join(session.info.dataDir, "room-plan.json");
+ const coderGate = join(session.info.dataDir, "coder-gate"), writerGate = join(session.info.dataDir, "writer-gate");
+ try {
+ const lead = (await cli("new-bot", "--name", "Lead", "--section", "Team")).bot;
+ const coder = (await cli("new-bot", "--name", "Coder", "--section", "Team")).bot;
+ const writer = (await cli("new-bot", "--name", "Writer", "--section", "Team")).bot;
+ await api(`/api/bots/${lead.id}`, { method: "PATCH", body: { chiefOfStaff: true, managedSections: ["Team"], acknowledgePeerScope: true } });
+ writeFileSync(plan, JSON.stringify({
+ [lead.id]: { steps: [{ arguments: { bot_ids: [coder.id], message: "Build the page" } }], reply: "Asked Coder", resumeReply: "All done" },
+ [coder.id]: { steps: [{ arguments: { bot_ids: [writer.id], message: "Write the copy" } }], gateFile: coderGate, reply: "Asked Writer", resumeReply: "Page built" },
+ [writer.id]: { gateFile: writerGate, reply: "Copy written" },
+ }));
+
+ const seen: string[] = [];
+ const sentRow = async () => {
+ const rows = (await api(`/api/threads/${lead.activeTaskId}/messages?limit=100`)).messages as any[];
+ const row = rows.find((message) => message.threadRef?.botId === coder.id);
+ const state = row?.handoff ? (row.handoff.waitingOn ? `${row.handoff.state}:${row.handoff.waitingOn.name ?? row.handoff.waitingOn.kind}` : row.handoff.state) : undefined;
+ if (state && seen.at(-1) !== state) seen.push(state);
+ return { row, state };
+ };
+ const coderTask = async () => {
+ const bots = (await api("/api/bots")).bots as any[];
+ return (bots.find((bot) => bot.id === coder.id)?.tasks ?? []).find((task: any) => task.handoff);
+ };
+
+ await cli("send", "--bot", lead.id, "--task", lead.activeTaskId, "--text", "Get the landing page built.");
+ await expect.poll(async () => (await sentRow()).state, { timeout: 30_000, interval: 100 }).toBe("working");
+ expect((await coderTask())?.handoff).toMatchObject({ state: "working" });
+
+ writeFileSync(coderGate, "go");
+ await expect.poll(async () => (await sentRow()).state, { timeout: 30_000, interval: 100 }).toBe("waiting:Writer");
+ expect((await coderTask())?.handoff).toMatchObject({ state: "waiting", waitingOn: { kind: "bot", name: "Writer" } });
+
+ writeFileSync(writerGate, "go");
+ await expect.poll(async () => (await sentRow()).state, { timeout: 30_000, interval: 100 }).toBe("done");
+ const { row } = await sentRow();
+ expect(row.handoff).toEqual({ id: expect.any(String), state: "done", at: expect.any(Number) });
+ expect(row.handoff.forPerson).toBeUndefined();
+ const states = seen.filter((state) => state !== "claimed");
+ expect(states.slice(0, 2)).toEqual(["working", "waiting:Writer"]);
+ expect(states.at(-1)).toBe("done");
+ expect(states.slice(2, -1).every((state) => state === "working"), "after the wait only Coder's resume shows before done").toBe(true);
+ expect((await coderTask())?.handoff).toMatchObject({ state: "done" });
+ const rows = (await api(`/api/threads/${lead.activeTaskId}/messages?limit=100`)).messages as any[];
+ expect(rows.filter((message) => message.kind === "options" && !message.card?.answered)).toEqual([]);
+ } finally {
+ await session.close();
+ }
+}, 120_000);
diff --git a/server/host/handoff-status.test.ts b/server/host/handoff-status.test.ts
new file mode 100644
index 0000000000..1f5b9975c8
--- /dev/null
+++ b/server/host/handoff-status.test.ts
@@ -0,0 +1,143 @@
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import type { HandoffStatusLine } from "../../shared/handoff-status.ts";
+import { createHandoffStatus, handoffLine, HANDOFF_LINES_FILE, type HandoffNode, type HandoffStatusDeps } from "./handoff-status.ts";
+
+const MIRA = "p_mmmmmmmmmmmmmmmmmmmmmm";
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+const node = (over: Partial<HandoffNode> = {}): HandoffNode => ({ id: "a1", status: "queued", botId: "coder", threadId: "work", result: "", ...over });
+
+describe("handoffLine", () => {
+ it("maps the record's status to claimed, working, waiting, done and failed", () => {
+ const at = 5;
+ expect(handoffLine(node({ status: "queued" }), { waitingBots: [] }, at)).toEqual({ id: "a1", state: "claimed", at });
+ expect(handoffLine(node({ status: "running" }), { waitingBots: [] }, at).state).toBe("working");
+ expect(handoffLine(node({ status: "resume" }), { waitingBots: [] }, at).state).toBe("working");
+ expect(handoffLine(node({ status: "waiting" }), { waitingBots: ["Writer"] }, at)).toMatchObject({ state: "waiting", waitingOn: { kind: "bot", name: "Writer" } });
+ expect(handoffLine(node({ status: "waiting" }), { waitingBots: ["A", "B", "C"] }, at).waitingOn).toEqual({ kind: "bot", name: "A, B +1" });
+ expect(handoffLine(node({ status: "completed", result: "Built it." }), { waitingBots: [] }, at)).toEqual({ id: "a1", state: "done", at });
+ expect(handoffLine(node({ status: "failed", outcomeDetail: "The engine stalled\nsecond line" }), { waitingBots: [] }, at)).toMatchObject({ state: "failed", why: "The engine stalled second line" });
+ expect(handoffLine(node({ status: "cancelled", outcome: "stopped" }), { waitingBots: [] }, at)).toMatchObject({ state: "failed", why: "Stopped" });
+ });
+
+ it("reads a wait whose teammates all answered as working: it is about to resume", () => {
+ expect(handoffLine(node({ status: "waiting" }), { waitingBots: [] }, 1)).toEqual({ id: "a1", state: "working", at: 1 });
+ });
+
+ it("waits on the person when it parked on a question: by name on a team, as you elsewhere", () => {
+ expect(handoffLine(node({ status: "waiting", question: "Which account?" }), { waitingBots: [] }, 1).waitingOn).toEqual({ kind: "person" });
+ expect(handoffLine(node({ status: "waiting", question: "Which account?" }), { waitingBots: [], askedPerson: "Mira", forPerson: { name: "Mira" } }, 1))
+ .toMatchObject({ waitingOn: { kind: "person", name: "Mira" }, forPerson: { name: "Mira" } });
+ });
+
+ it("never carries the question, and keeps a private failure's words out of a shared place", () => {
+ const line = handoffLine(node({ status: "waiting", question: "the secret plan?" }), { waitingBots: [] }, 1);
+ expect(JSON.stringify(line)).not.toContain("secret");
+ expect(handoffLine(node({ status: "failed", outcomeDetail: "Mira's salary sheet was locked" }), { waitingBots: [], forPerson: { name: "Mira", private: true } }, 1))
+ .toEqual({ id: "a1", state: "failed", forPerson: { name: "Mira", private: true }, at: 1 });
+ });
+});
+
+function harness(over: Partial<HandoffStatusDeps> = {}, dir = mkdtempSync(join(tmpdir(), "omb-handoff-status-"))) {
+ if (!dirs.includes(dir)) dirs.push(dir);
+ const nodes = new Map<string, HandoffNode>();
+ const rows = new Map<string, { id: string; threadRef?: { botId: string; threadId: string; title: string }; handoff?: HandoffStatusLine }>();
+ const republished: string[] = [];
+ let clock = 100;
+ const status = createHandoffStatus({
+ dataDir: dir, now: () => clock,
+ node: (id) => nodes.get(id),
+ children: (parent) => [...nodes.values()].filter((child) => child.parentId === parent.id),
+ botName: (botId) => ({ coder: "Coder", writer: "Writer" })[botId],
+ store: {
+ messagesFor: (() => [...rows.values()]) as never,
+ patchMessage: ((_threadId: string, id: string, patch: Record<string, unknown>) => { rows.set(id, { ...rows.get(id)!, ...patch }); }) as never,
+ },
+ republish: (botId) => republished.push(botId),
+ log: () => {},
+ ...over,
+ });
+ return { dir, nodes, rows, republished, status, tick: (ms: number) => { clock += ms; } };
+}
+
+describe("createHandoffStatus", () => {
+ it("updates the Sent-to row through claimed, working, waiting on a bot and done, and the work conversation's task with it", () => {
+ const h = harness();
+ h.nodes.set("a1", node());
+ h.rows.set("m1", { id: "m1", threadRef: { botId: "coder", threadId: "work", title: "Build the page" } });
+ h.status.track("a1", "lead-chat", "m1");
+ const seen = [h.rows.get("m1")!.handoff!.state];
+ for (const next of [{ status: "running" as const }, { status: "waiting" as const }]) {
+ h.nodes.set("a1", node(next));
+ if (next.status === "waiting") h.nodes.set("c1", node({ id: "c1", parentId: "a1", status: "running", botId: "writer", threadId: "w2" }));
+ h.tick(10);
+ h.status.refresh();
+ seen.push(h.rows.get("m1")!.handoff!.state);
+ }
+ expect(h.rows.get("m1")!.handoff!.waitingOn).toEqual({ kind: "bot", name: "Writer" });
+ expect(h.status.forWork("work")).toEqual({ handoff: h.rows.get("m1")!.handoff });
+ h.nodes.set("a1", node({ status: "completed" }));
+ h.status.refresh();
+ seen.push(h.rows.get("m1")!.handoff!.state);
+ expect(seen).toEqual(["claimed", "working", "waiting", "done"]);
+ expect(h.status.tracking()).toEqual([]);
+ expect(h.republished.every((botId) => botId === "coder")).toBe(true);
+ expect(h.rows.get("m1")!.threadRef!.title).toBe("Build the page");
+ });
+
+ it("patches only on a change", () => {
+ const h = harness();
+ h.nodes.set("a1", node({ status: "running" }));
+ h.rows.set("m1", { id: "m1" });
+ h.status.track("a1", "lead-chat", "m1");
+ const before = h.republished.length;
+ h.status.refresh();
+ h.status.refresh();
+ expect(h.republished.length).toBe(before);
+ });
+
+ it("keeps tracking across a restart and drops what the records no longer hold", () => {
+ const first = harness();
+ first.nodes.set("a1", node({ status: "running" }));
+ first.nodes.set("a2", node({ id: "a2", status: "running" }));
+ first.rows.set("m1", { id: "m1" });
+ first.rows.set("m2", { id: "m2" });
+ first.status.track("a1", "lead-chat", "m1");
+ first.status.track("a2", "lead-chat", "m2");
+ expect(JSON.parse(readFileSync(join(first.dir, HANDOFF_LINES_FILE), "utf8")).lines).toHaveLength(2);
+ const again = harness({}, first.dir);
+ again.rows.set("m1", { id: "m1" });
+ again.nodes.set("a1", node({ status: "completed" }));
+ again.status.refresh();
+ expect(again.rows.get("m1")!.handoff!.state).toBe("done");
+ expect(again.status.tracking()).toEqual([]);
+ expect(JSON.parse(readFileSync(join(first.dir, HANDOFF_LINES_FILE), "utf8")).lines).toEqual([]);
+ });
+
+ it("on a team names the asker, and hides a private chat's title from a shared row", () => {
+ const h = harness({ team: { personName: (person) => (person === MIRA ? "Mira" : undefined), privateTo: (threadId) => (threadId === "work" ? MIRA : null) } });
+ h.nodes.set("a1", node({ status: "running", origin: { kind: "user", request: "x", person: MIRA } }));
+ h.rows.set("m1", { id: "m1", threadRef: { botId: "coder", threadId: "work", title: "Mira's raise" } });
+ h.status.track("a1", "shared-chat", "m1");
+ expect(h.rows.get("m1")).toMatchObject({ handoff: { state: "working", forPerson: { name: "Mira", private: true } }, threadRef: { title: "" } });
+ const own = harness({ team: { personName: () => "Mira", privateTo: () => MIRA } });
+ own.nodes.set("a1", node({ status: "running", origin: { kind: "user", request: "x", person: MIRA } }));
+ own.rows.set("m1", { id: "m1", threadRef: { botId: "coder", threadId: "work", title: "Mira's raise" } });
+ own.status.track("a1", "miras-chat", "m1");
+ expect(own.rows.get("m1")).toMatchObject({ handoff: { forPerson: { name: "Mira" } }, threadRef: { title: "Mira's raise" } });
+ expect(own.rows.get("m1")!.handoff!.forPerson!.private).toBeUndefined();
+ });
+
+ it("names nobody off a team", () => {
+ const h = harness();
+ h.nodes.set("a1", node({ status: "waiting", question: "Which?", origin: { kind: "user", request: "x", person: MIRA } }));
+ h.rows.set("m1", { id: "m1" });
+ h.status.track("a1", "chat", "m1");
+ expect(h.rows.get("m1")!.handoff).toEqual({ id: "a1", state: "waiting", waitingOn: { kind: "person" }, at: 100 });
+ });
+});
diff --git a/server/host/handoff-status.ts b/server/host/handoff-status.ts
new file mode 100644
index 0000000000..a5328c1289
--- /dev/null
+++ b/server/host/handoff-status.ts
@@ -0,0 +1,196 @@
+// Where work one bot handed another stands, shown where people already look: on the "Sent to" row in the asking
+// conversation, and on the conversation that does the work (the inbox lists it). Read from the assignment records each
+// time they are written; nothing is added to them.
+//
+// Security: the row is one stored message that everyone who reads the asking conversation sees. It carries a state, a
+// bot's name, and on a Team Cloud the asker's name; never the work's words, its question or, when the work runs in a
+// person's private chat that the row's readers can't open, that chat's title.
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { z } from "zod";
+
+import type { HandoffState, HandoffStatusLine } from "../../shared/handoff-status.ts";
+import { writeFileAtomic } from "../atomic.ts";
+import type { HandoffView } from "../coordinator.ts";
+import type { Store } from "../store.ts";
+import { oneLine } from "./text-clip.ts";
+
+export const HANDOFF_LINES_FILE = "handoff-lines.json";
+const WHY_MAX = 160;
+/** Ended lines the work conversations still show, newest kept. */
+const ENDED_KEPT = 200;
+
+const id = z.string().min(1).max(200);
+const trackedSchema = z.object({ id, threadId: id, messageId: id, workThreadId: id, workBotId: id });
+const fileSchema = z.object({ version: z.literal(1), lines: z.array(trackedSchema) });
+type Tracked = z.infer<typeof trackedSchema> & { line?: HandoffStatusLine };
+
+export type HandoffNode = Pick<HandoffView, "id" | "status" | "botId" | "threadId" | "parentId" | "question" | "cards" | "outcome" | "outcomeDetail" | "result" | "origin">;
+
+export interface HandoffLineFacts {
+ /** The bots it waits on, by name. */
+ waitingBots: string[];
+ /** On a Team Cloud: the asker's name, and whether the work runs in their private chat while the row is somewhere they don't own. */
+ forPerson?: { name: string; private?: true };
+ /** On a Team Cloud, the person a question waits on; off a team, none ("you"). */
+ askedPerson?: string;
+}
+
+const stateOf = (node: Pick<HandoffNode, "status">): HandoffState => {
+ switch (node.status) {
+ case "queued": return "claimed";
+ case "waiting": return "waiting";
+ case "completed": return "done";
+ case "failed":
+ case "cancelled": return "failed";
+ default: return "working";
+ }
+};
+
+function whyFailed(node: HandoffNode): string {
+ if (node.status === "cancelled" && node.outcome === "stopped") return "Stopped";
+ return oneLine(node.outcomeDetail || node.result || (node.status === "cancelled" ? "Cancelled" : "Failed"), WHY_MAX);
+}
+
+/** The status line for one hand-off, from its record and what the host knows around it. */
+export function handoffLine(node: HandoffNode, facts: HandoffLineFacts, at: number): HandoffStatusLine {
+ const onPerson = Boolean(node.question || node.cards?.length);
+ const state = stateOf(node) === "waiting" && !onPerson && facts.waitingBots.length === 0 ? "working" : stateOf(node);
+ const line: HandoffStatusLine = { id: node.id, state, at };
+ if (state === "waiting") {
+ line.waitingOn = onPerson
+ ? { kind: "person", ...(facts.askedPerson ? { name: facts.askedPerson } : {}) }
+ : { kind: "bot", name: facts.waitingBots.length > 2 ? `${facts.waitingBots.slice(0, 2).join(", ")} +${facts.waitingBots.length - 2}` : facts.waitingBots.join(", ") };
+ }
+ if (state === "failed" && !facts.forPerson?.private) line.why = whyFailed(node);
+ if (facts.forPerson) line.forPerson = facts.forPerson;
+ return line;
+}
+
+const sameLine = (a: HandoffStatusLine | undefined, b: HandoffStatusLine) =>
+ a !== undefined && a.state === b.state && a.why === b.why && JSON.stringify(a.waitingOn) === JSON.stringify(b.waitingOn)
+ && JSON.stringify(a.forPerson) === JSON.stringify(b.forPerson);
+
+const ended = (line: HandoffStatusLine) => line.state === "done" || line.state === "failed";
+
+export interface HandoffStatusDeps {
+ dataDir: string;
+ now?: () => number;
+ node(id: string): HandoffNode | undefined;
+ /** Its open hand-offs: the work it waits on. */
+ children(node: HandoffNode): HandoffNode[];
+ botName(botId: string): string | undefined;
+ /** On a Team Cloud: a person's name by key, and the person a conversation is private to. Absent off a team. */
+ team?: { personName(person: string): string | undefined; privateTo(threadId: string): string | null };
+ store: Pick<Store, "messagesFor" | "patchMessage">;
+ /** The work conversation's bot changed what it shows: publish it again. */
+ republish(botId: string): void;
+ log?(text: string): void;
+}
+
+export function createHandoffStatus(deps: HandoffStatusDeps) {
+ const file = join(deps.dataDir, HANDOFF_LINES_FILE);
+ const now = deps.now ?? Date.now;
+ const log = deps.log ?? ((text: string) => console.error(text));
+ const tracked = new Map<string, Tracked>();
+ const byWork = new Map<string, HandoffStatusLine>();
+ let scheduled = false;
+
+ try {
+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));
+ if (parsed.success) for (const row of parsed.data.lines) tracked.set(row.id, row);
+ } catch { /* none yet */ }
+
+ function save(): void {
+ try {
+ writeFileAtomic(file, JSON.stringify({ version: 1, lines: [...tracked.values()].map(({ line: _line, ...row }) => row) }), { mode: 0o600 });
+ } catch (error) {
+ log(`handoff status: could not save: ${String(error)}`);
+ }
+ }
+
+ function facts(node: HandoffNode, row: Pick<Tracked, "threadId">): HandoffLineFacts {
+ const waitingBots = node.status === "waiting" ? deps.children(node).filter((child) => child.status !== "completed" && child.status !== "failed" && child.status !== "cancelled")
+ .map((child) => deps.botName(child.botId) ?? "a teammate") : [];
+ const team = deps.team;
+ const person = node.origin?.kind === "user" ? node.origin.person : undefined;
+ if (!team || !person) return { waitingBots };
+ const name = team.personName(person);
+ if (!name) return { waitingBots };
+ const privateWork = team.privateTo(node.threadId) === person && team.privateTo(row.threadId) !== person;
+ return { waitingBots, forPerson: { name, ...(privateWork ? { private: true as const } : {}) }, askedPerson: name };
+ }
+
+ function show(row: Tracked, line: HandoffStatusLine): void {
+ try {
+ const message = deps.store.messagesFor(row.threadId).find((candidate) => candidate.id === row.messageId);
+ if (message) {
+ const hideTitle = line.forPerson?.private === true && message.threadRef?.title;
+ deps.store.patchMessage(row.threadId, row.messageId, { handoff: line, ...(hideTitle ? { threadRef: { ...message.threadRef!, title: "" } } : {}) });
+ }
+ } catch (error) {
+ log(`handoff status ${row.id}: could not update its row: ${String(error)}`);
+ }
+ byWork.set(row.workThreadId, line);
+ if (byWork.size > ENDED_KEPT + tracked.size) {
+ for (const [thread, kept] of byWork) {
+ if (byWork.size <= ENDED_KEPT + tracked.size) break;
+ if (ended(kept)) byWork.delete(thread);
+ }
+ }
+ try { deps.republish(row.workBotId); } catch (error) { log(`handoff status ${row.id}: could not publish: ${String(error)}`); }
+ }
+
+ function refresh(): void {
+ let changed = false;
+ for (const row of tracked.values()) {
+ const node = deps.node(row.id);
+ if (!node) {
+ tracked.delete(row.id);
+ changed = true;
+ continue;
+ }
+ const next = handoffLine(node, facts(node, row), now());
+ if (sameLine(row.line, next)) continue;
+ if (row.line && row.line.state === next.state) next.at = row.line.at;
+ row.line = next;
+ show(row, next);
+ if (ended(next)) {
+ tracked.delete(row.id);
+ changed = true;
+ }
+ }
+ if (changed) save();
+ }
+
+ return {
+ /** A "Sent to" row was written for this hand-off. */
+ track(assignmentId: string, threadId: string, messageId: string): void {
+ const node = deps.node(assignmentId);
+ if (!node) return;
+ tracked.set(assignmentId, { id: assignmentId, threadId, messageId, workThreadId: node.threadId, workBotId: node.botId });
+ save();
+ refresh();
+ },
+ /** The assignment records were written: look again, once, after the write settles. */
+ changed(): void {
+ if (scheduled || !tracked.size) return;
+ scheduled = true;
+ setImmediate(() => {
+ scheduled = false;
+ try { refresh(); } catch (error) { log(`handoff status: ${String(error)}`); }
+ });
+ },
+ refresh,
+ /** The status of the hand-off a work conversation is doing, for its task row. */
+ forWork(threadId: string): { handoff: HandoffStatusLine } | Record<string, never> {
+ const line = byWork.get(threadId);
+ return line ? { handoff: line } : {};
+ },
+ tracking(): string[] {
+ return [...tracked.keys()];
+ },
+ };
+}
+
+export type HandoffStatus = ReturnType<typeof createHandoffStatus>;
diff --git a/server/index.ts b/server/index.ts
index c3efeeab54..06497477bb 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -605,7 +605,7 @@ import { createTrustAnswers } from "./host/trust-answers.ts";
import { createInternalThreadRoutes } from "./routes/internal-threads.ts";
import { createBrowserEvidenceRoutes } from "./routes/browser-evidence.ts";
import { createSignInCardRoutes } from "./routes/sign-in-cards.ts";
-import { createInternalChiefTeamRoutes } from "./routes/internal-chief-team.ts"; import { createInternalModelRoutes } from "./routes/internal-models.ts"; import { createOwnThreads } from "./host/own-threads.ts"; import { burstDefaultModel, burstProposalRefusal, createBurstHost } from "./host/burst-host.ts"; import { expandBurstTurnText } from "./burst/command.ts"; import { createBurstProposalRoutes, createBurstRoutes } from "./routes/burst.ts"; import { createCheckBacks } from "./host/check-backs.ts"; import { writeCheckBackLine } from "./host/check-back-host.ts"; import { checkBackRefusal, createCheckBackRoutes, createCheckBackToolRoutes } from "./routes/check-backs.ts";
+import { createInternalChiefTeamRoutes } from "./routes/internal-chief-team.ts"; import { createInternalModelRoutes } from "./routes/internal-models.ts"; import { createOwnThreads } from "./host/own-threads.ts"; import { burstDefaultModel, burstProposalRefusal, createBurstHost } from "./host/burst-host.ts"; import { expandBurstTurnText } from "./burst/command.ts"; import { createBurstProposalRoutes, createBurstRoutes } from "./routes/burst.ts"; import { createCheckBacks } from "./host/check-backs.ts"; import { writeCheckBackLine } from "./host/check-back-host.ts"; import { checkBackRefusal, createCheckBackRoutes, createCheckBackToolRoutes } from "./routes/check-backs.ts"; import { createHandoffStatus } from "./host/handoff-status.ts";
import { createRoomHoldRoutes } from "./routes/room-holds.ts";
import { checkedGroupResponder, createGroupRoutes } from "./routes/groups.ts";
import { createChannelRoutes } from "./routes/channels.ts";
@@ -2859,13 +2859,13 @@ try {
// Replay only after the secondary write above is durable.
if (browserCleanupReferencesReconciled) browserCleanup.startPending();
-let threadsAwaitingTeammates = (): ReadonlySet<string> => new Set<string>();
+let threadsAwaitingTeammates = (): ReadonlySet<string> => new Set<string>(); const handoffStatus = createHandoffStatus({ dataDir: DATA_DIR, store, node: (id) => coordinator.node(id), children: (node) => coordinator.outstandingFor(node.threadId).filter((child) => child.parentId === node.id), botName: (botId) => store.bot(botId)?.name, ...(CLOUD_TEAM ? { team: { personName: (person) => teamHost.personName(person), privateTo: (threadId) => teamHost.privateTo(threadId) } } : {}), republish: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); } });
let cacheKeepWarmStatus = (_threadId: string): KeepWarmStatus | undefined => undefined;
const wireTask = (task: TaskRecord, botModel: ModelSelection, awaiting = threadsAwaitingTeammates()): WireTask => {
// Snoozes heal on read against the server clock; the 0 sentinel ("until new activity") survives reads.
const { snoozedUntil, ...base } = toWireTask(task, botModel);
const keepWarm = cacheKeepWarmStatus(task.threadId);
- const coordinated = { ...base, waitingForTeammates: awaiting.has(task.threadId) && !task.busy, ...(keepWarm ? { cacheKeepWarm: keepWarm } : {}), ...(teamHost.ownTurn(task.threadId) ? { private: true as const } : {}), ...teamMessages.inbox.wire(task.threadId), ...runOwners.askedBy(task) };
+ const coordinated = { ...base, waitingForTeammates: awaiting.has(task.threadId) && !task.busy, ...(keepWarm ? { cacheKeepWarm: keepWarm } : {}), ...(teamHost.ownTurn(task.threadId) ? { private: true as const } : {}), ...teamMessages.inbox.wire(task.threadId), ...runOwners.askedBy(task), ...handoffStatus.forWork(task.threadId) };
const asleep = snoozedUntil === 0 || (snoozedUntil !== undefined && snoozedUntil > Date.now());
return asleep ? { ...coordinated, snoozedUntil } : coordinated;
};
@@ -3860,7 +3860,7 @@ const handoffFiles = createHandoffFiles({ dataDir: DATA_DIR, attachmentsDir: ATT
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 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: beginGroupTurnOperation, 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), refusal: botMoveRefusal, 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 handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoordinator({
dataDir: DATA_DIR,
- now: Date.now, wrote: handoffTicks.kick, handoffLimit: { refusal: (botId, open, origin) => botHolds.handoff(botId) ?? starterCaps.handoffs.refusal(botId, open) ?? usageCapGate.handoff(botId, origin) },
+ 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),
legacyThreads: {
standingThreadOf: botId => botMainThread(botId) ?? store.bot(botId)?.threadId,
@@ -13697,8 +13697,8 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
}));
if (!duplicate) {
if (!EXTERNAL) delegatedThisTurn(node.id);
- if (!post) 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) }));
+ 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);
}
} catch (error) {
if (createdThread) store.deleteTask(target.botId, createdThread);
@@ -15264,7 +15264,7 @@ server.listen(PORT, listenHost(server), async () => {
}
// Only once every registry is initialized and the endpoint listens: earlier dispatch can hit uninitialized bindings.
moveFreeze.hold(() => { routines!.start(); botWaits.start(); checkBacks.start(); proactive.start(); }, () => { routines!.stop(); botWaits.stop(); checkBacks.stop(); proactive.stop(); });
- limitClock.start(); burst.recover();
+ limitClock.start(); burst.recover(); handoffStatus.changed();
moveFreeze.hold(() => memoryUpkeep.start(), () => memoryUpkeep.stop());
});
diff --git a/shared/handoff-status.ts b/shared/handoff-status.ts
new file mode 100644
index 0000000000..3238554895
--- /dev/null
+++ b/shared/handoff-status.ts
@@ -0,0 +1 @@
+export * from "../packages/phone-protocol/src/handoff-status.ts";
diff --git a/src/components/HandoffStatusChip.test.ts b/src/components/HandoffStatusChip.test.ts
new file mode 100644
index 0000000000..99a9d2c13b
--- /dev/null
+++ b/src/components/HandoffStatusChip.test.ts
@@ -0,0 +1,63 @@
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+import type { HandoffStatusLine } from "../../shared/handoff-status";
+import type { Bot, Message, Task } from "@/state/store";
+
+const coder = { id: "coder", threadId: "coder-main", name: "Coder", color: "green", messages: [], tasks: [] } as unknown as Bot;
+vi.mock("@/state/store", async (importOriginal) => {
+ const original = await importOriginal<typeof import("@/state/store")>();
+ return { ...original, useStore: () => ({ state: { ...original.initialState, bots: [coder] }, dispatch: vi.fn() }) };
+});
+vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => true }));
+const { HandoffStatusChip, handoffStatusText } = await import("./HandoffStatusChip");
+const { ThreadChip } = await import("./ThreadChip");
+const { attentionRowStatus } = await import("./SidebarBotActivity");
+
+beforeEach(() => setLocale("en"));
+const line = (over: Partial<HandoffStatusLine>): HandoffStatusLine => ({ id: "a1", state: "working", at: 1, ...over });
+
+describe("hand-off status chip", () => {
+ it("says each state in a few words", () => {
+ expect(handoffStatusText(line({ state: "claimed" }))).toBe("Claimed");
+ expect(handoffStatusText(line({ state: "working" }))).toBe("Working");
+ expect(handoffStatusText(line({ state: "waiting", waitingOn: { kind: "bot", name: "Writer" } }))).toBe("Waiting on Writer");
+ expect(handoffStatusText(line({ state: "waiting", waitingOn: { kind: "person" } }))).toBe("Waiting on you");
+ expect(handoffStatusText(line({ state: "done" }))).toBe("Done");
+ expect(handoffStatusText(line({ state: "failed", why: "The engine stalled" }))).toBe("Failed: The engine stalled");
+ expect(handoffStatusText(line({ state: "failed" }))).toBe("Failed");
+ });
+
+ it("names the asker on a team, and a private one only as private", () => {
+ expect(handoffStatusText(line({ state: "waiting", waitingOn: { kind: "person", name: "Mira" }, forPerson: { name: "Mira" } }))).toBe("Waiting on Mira · for Mira");
+ expect(handoffStatusText(line({ forPerson: { name: "Mira", private: true } }))).toBe("Working · for Mira (private)");
+ });
+
+ it("is a status, not a control", () => {
+ const html = renderToStaticMarkup(createElement(HandoffStatusChip, { line: line({ state: "done" }) }));
+ expect(html).toContain('data-handoff-status="done"');
+ expect(html).toContain('role="status"');
+ expect(html).not.toContain("<button");
+ });
+
+ it("sits beside the Sent-to pill that opens the work", () => {
+ const row = { id: "r", role: "bot", kind: "activity", at: 1, tool: { name: "Sent to Coder", ok: true },
+ threadRef: { botId: "coder", threadId: "work", title: "Build the page" }, handoff: line({ state: "waiting", waitingOn: { kind: "bot", name: "Writer" } }) } as Message;
+ const html = renderToStaticMarkup(createElement(ThreadChip, { message: row, threadId: "lead" }));
+ expect(html).toContain('data-thread-chip="work"');
+ expect(html).toContain('data-handoff-status="waiting"');
+ expect(html).toContain("Waiting on Writer");
+ const plain = renderToStaticMarkup(createElement(ThreadChip, { message: { ...row, handoff: undefined }, threadId: "lead" }));
+ expect(plain).not.toContain("data-handoff-status");
+ });
+
+ it("gives the inbox's row for the work conversation the same words", () => {
+ const task = { threadId: "work", title: "Build the page", createdAt: 0, busy: true, queued: false, handoff: line({ forPerson: { name: "Mira" } }) } as Task & { queued: boolean };
+ const { handoff: _none, ...plain } = task;
+ expect(attentionRowStatus(task).label).toBe("Working · for Mira");
+ expect(attentionRowStatus({ ...task, busy: false, waitingForTeammates: true, handoff: line({ state: "waiting", waitingOn: { kind: "bot", name: "Writer" } }) }).label).toBe("Waiting on Writer");
+ expect(attentionRowStatus({ ...task, busy: false, activity: "waiting-on-you", handoff: line({ state: "waiting", waitingOn: { kind: "person" } }) }).label).toBe("Waiting on you");
+ expect(attentionRowStatus({ ...plain, busy: false, activity: "waiting-on-you" }).label).toBe("Waiting");
+ });
+});
diff --git a/src/components/HandoffStatusChip.tsx b/src/components/HandoffStatusChip.tsx
new file mode 100644
index 0000000000..1c988122b5
--- /dev/null
+++ b/src/components/HandoffStatusChip.tsx
@@ -0,0 +1,45 @@
+// A hand-off's status as one small chip: on its "Sent to" row and on the conversation that does the work. Display only.
+import type { HandoffStatusLine } from "../../shared/handoff-status";
+import { t } from "@/lib/i18n";
+import { cn } from "@/lib/cn";
+
+export function handoffStateText(line: HandoffStatusLine): string {
+ switch (line.state) {
+ case "claimed": return t("chat.handoff.claimed");
+ case "working": return t("chat.handoff.working");
+ case "waiting": {
+ const on = line.waitingOn;
+ if (on?.name) return t("chat.handoff.waitingOn", { name: on.name });
+ return on?.kind === "bot" ? t("chat.handoff.waitingOnTeammate") : t("chat.handoff.waitingOnYou");
+ }
+ case "done": return t("chat.handoff.done");
+ case "failed": return line.why ? t("chat.handoff.failedWhy", { why: line.why }) : t("chat.handoff.failed");
+ }
+}
+
+/** The chip's whole text: the state, and on a Team Cloud whose request it is. */
+export function handoffStatusText(line: HandoffStatusLine): string {
+ const state = handoffStateText(line);
+ const person = line.forPerson;
+ if (!person) return state;
+ return t(person.private ? "chat.handoff.forPrivate" : "chat.handoff.for", { status: state, name: person.name });
+}
+
+const TONE: Record<HandoffStatusLine["state"], string> = {
+ claimed: "bg-ink-tertiary",
+ working: "bg-accent",
+ waiting: "bg-warning",
+ done: "bg-success",
+ failed: "bg-danger",
+};
+
+export function HandoffStatusChip({ line, className }: { line: HandoffStatusLine; className?: string }) {
+ const text = handoffStatusText(line);
+ return (
+ <span data-handoff-status={line.state} title={text} role="status"
+ className={cn("inline-flex min-w-0 max-w-[320px] items-center gap-1.5 text-[12px] text-ink-secondary", line.state === "failed" && "text-danger", className)}>
+ <span aria-hidden="true" className={cn("size-1.5 shrink-0 rounded-full", TONE[line.state], line.state === "working" && "animate-pulse")} />
+ <span className="min-w-0 truncate">{text}</span>
+ </span>
+ );
+}
diff --git a/src/components/SidebarBotActivity.tsx b/src/components/SidebarBotActivity.tsx
index 5e6bb8639b..ed1ab94f6d 100644
--- a/src/components/SidebarBotActivity.tsx
+++ b/src/components/SidebarBotActivity.tsx
@@ -9,6 +9,7 @@ import type { SidebarDensity } from "@/lib/sidebar-preferences";
import { localizedTaskTitle } from "@/lib/task-title";
import { endedOnFailure } from "@/lib/mascot";
import { rowSelectedSurface } from "./SidebarRowMarkers";
+import { handoffStatusText } from "./HandoffStatusChip";
export function sidebarBotActivityTasks(bot: Bot, queued: Record<string, unknown[]>, archivedApprovals = false): Array<Task & { queued: boolean }> {
const tasks = bot.tasks ?? [{
@@ -126,7 +127,8 @@ export function attentionRowStatus(task: AttentionThread["task"]): { active: boo
const teammateWait = !waiting && task.waitingForTeammates === true;
const working = !waiting && !teammateWait && (task.busy || task.activity === "working");
const active = waiting || teammateWait || working || task.queued || task.unread === true;
- const label = waiting ? t("task.waiting") : working ? t("chat.activity.working") : teammateWait ? t("task.waitingOnTeammate") : task.queued ? t("task.queued") : t("task.unread");
+ const handoff = task.handoff && (waiting ? task.handoff.state === "waiting" : true) ? handoffStatusText(task.handoff) : undefined;
+ const label = handoff ?? (waiting ? t("task.waiting") : working ? t("chat.activity.working") : teammateWait ? t("task.waitingOnTeammate") : task.queued ? t("task.queued") : t("task.unread"));
const Icon = waiting ? CircleAlert : working ? Loader2 : teammateWait || task.queued ? Clock3 : BellDot;
const colorClass = cn(working && "animate-spin text-success", (waiting || teammateWait) && "text-warning");
return { active, Icon, colorClass, label };
diff --git a/src/components/ThreadChip.tsx b/src/components/ThreadChip.tsx
index 6f0dbaa5d0..fb6dde43d3 100644
--- a/src/components/ThreadChip.tsx
+++ b/src/components/ThreadChip.tsx
@@ -6,6 +6,7 @@ import { activityText } from "@/lib/activity-text";
import { cn } from "@/lib/cn";
import { BotAvatar } from "./Avatar";
import { HandoffReply } from "./HandoffReply";
+import { HandoffStatusChip } from "./HandoffStatusChip";
export function ThreadChip({ message, threadId }: { message: Message; threadId?: string }) {
const { state, dispatch } = useStore();
@@ -19,6 +20,7 @@ export function ThreadChip({ message, threadId }: { message: Message; threadId?:
: direct.room ? t("chat.sentDirectlyNotInRoom", { name: direct.name, room: direct.room }) : t("chat.sentDirectly", { name: direct.name });
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">
<button
type="button"
data-thread-chip={ref.threadId}
@@ -30,6 +32,8 @@ export function ThreadChip({ message, threadId }: { message: Message; threadId?:
<span className="max-w-[480px] truncate">{label}</span>
<ChevronRight size={13} />
</button>
+ {message.handoff && <HandoffStatusChip line={message.handoff} />}
+ </span>
</HandoffReply>
);
}
diff --git a/src/locales/en.json b/src/locales/en.json
index ff349700bc..0d6d584246 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2688,6 +2688,16 @@
"chat.checkBack.failed": "Couldn't check back {when}",
"chat.checkBack.cancel": "Cancel",
"chat.checkBack.cancelFailed": "Couldn't cancel. Try again.",
+ "chat.handoff.claimed": "Claimed",
+ "chat.handoff.working": "Working",
+ "chat.handoff.waitingOn": "Waiting on {name}",
+ "chat.handoff.waitingOnTeammate": "Waiting on a teammate",
+ "chat.handoff.waitingOnYou": "Waiting on you",
+ "chat.handoff.done": "Done",
+ "chat.handoff.failed": "Failed",
+ "chat.handoff.failedWhy": "Failed: {why}",
+ "chat.handoff.for": "{status} · for {name}",
+ "chat.handoff.forPrivate": "{status} · for {name} (private)",
"chat.sentDirectlyNotInRoom": "Sent to {name} directly: it isn't in {room}.",
"chat.botScreen": "Bot's screen",
"chat.digestChip": "Did {tools} tool calls · {files} files changed",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 71dd3340aa..bc9e871815 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -2504,6 +2504,16 @@
"chat.checkBack.failed": "Não foi possível verificar de novo: {when}",
"chat.checkBack.cancel": "Cancelar",
"chat.checkBack.cancelFailed": "Não foi possível cancelar. Tente de novo.",
+ "chat.handoff.claimed": "Aceito",
+ "chat.handoff.working": "Trabalhando",
+ "chat.handoff.waitingOn": "Aguardando {name}",
+ "chat.handoff.waitingOnTeammate": "Aguardando um colega",
+ "chat.handoff.waitingOnYou": "Aguardando você",
+ "chat.handoff.done": "Concluído",
+ "chat.handoff.failed": "Falhou",
+ "chat.handoff.failedWhy": "Falhou: {why}",
+ "chat.handoff.for": "{status} · para {name}",
+ "chat.handoff.forPrivate": "{status} · para {name} (privado)",
"chat.sentDirectlyNotInRoom": "Mensagem enviada diretamente a {name}: esse bot não está em {room}.",
"chat.botScreen": "Tela do bot",
"chat.digestChip": "Fez {tools} chamadas de ferramenta · {files} arquivos alterados",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index b5c3288e8d..038d698fc2 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -113,7 +113,7 @@ export type SecretRequestCardData = Omit<import("../../shared/wire").SecretReque
export type ComputerControlState = { held: boolean; helpReason: string | null; help?: import("../../shared/wire").ComputerHelpRef | null };
-export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "template" | "sender" | "setupSuggestion" | "settingsCard" | "helperIntro" | "helperFollowup" | "setupOffer" | "savedSteps" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen" | "checkBack" | "bugReport" | "engineCompaction" | "stoppedBy"> {
+export interface Message extends Pick<import("../../shared/wire").WireMessage, "widget" | "app" | "fromApp" | "pointed" | "routedBy" | "quickModel" | "automation" | "publishedPage" | "template" | "sender" | "setupSuggestion" | "settingsCard" | "helperIntro" | "helperFollowup" | "setupOffer" | "savedSteps" | "setupChoices" | "setupChoicesPending" | "setupChoicesUpdating" | "setupRequest" | "relay" | "inbox" | "sentDirectly" | "doneWhen" | "checkBack" | "handoff" | "bugReport" | "engineCompaction" | "stoppedBy"> {
id: string;
role: "bot" | "user";
kind: "text" | "options" | "activity" | "screen" | "connector" | "secret" | "signin" | "routine.run" | "goal.run" | "burst" | "digest" | "compaction" | "call" | "widget" | "app";
@@ -214,7 +214,7 @@ export interface ModelSelection {
variant?: string;
}
-export interface Task extends Pick<WireTask, "private" | "shared" | "sharedWith" | "setupRequest" | "inbox" | "openAsks" | "askedBy"> {
+export interface Task extends Pick<WireTask, "private" | "shared" | "sharedWith" | "setupRequest" | "inbox" | "openAsks" | "askedBy" | "handoff"> {
waitingForTeammates?: boolean; sharedChat?: true;
threadId: string;
origin?: import("../../shared/wire").ForkOrigin;