Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(notify): one "done" when a job is really finished (#4140)
Azad Jagtap3fd3b547c2e8
diff --git a/server/done-notice.test.ts b/server/done-notice.test.tsnew file mode 100644index 0000000000..e84abfe77b--- /dev/null+++ b/server/done-notice.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from "vitest";++import { createDoneNotice } from "./done-notice.ts";++const notice = (state: { awaiting?: Set<string>; queued?: Set<string> } = {}) => createDoneNotice({+ awaitingTeammates: (threadId) => state.awaiting?.has(threadId) ?? false,+ queuedFollowUp: (_botId, threadId) => state.queued?.has(threadId) ?? false,+});+const turn = (patch: Partial<Parameters<ReturnType<typeof notice>["atTurnEnd"]>[0]> = {}) =>+ ({ botId: "pen", threadId: "t", review: false, ok: true, routine: false, ...patch });++describe("when a turn's end is news", () => {+ it("notifies a plain finished turn, as before", () => {+ expect(notice().atTurnEnd(turn())).toBe("notify");+ });++ it("holds the done of a turn that handed work off, and notifies once when the reviewed answer lands", () => {+ const awaiting = new Set(["t"]);+ const done = notice({ awaiting });+ expect(done.atTurnEnd(turn())).toBe("hold");+ expect(done.owes("t")).toBe(true);+ awaiting.clear();+ expect(done.atTurnEnd(turn({ review: true }))).toBe("notify");+ expect(done.owes("t")).toBe(false);+ expect(done.atTurnEnd(turn({ review: true }))).toBe("quiet");+ });++ it("keeps holding through a review that hands work off again, and notifies at the last round's answer", () => {+ const awaiting = new Set(["t"]);+ const done = notice({ awaiting });+ expect(done.atTurnEnd(turn())).toBe("hold");+ expect(done.atTurnEnd(turn({ review: true }))).toBe("hold");+ awaiting.clear();+ expect(done.atTurnEnd(turn({ review: true }))).toBe("notify");+ });++ it("keeps a review nobody held a done for quiet, like an incident review", () => {+ expect(notice().atTurnEnd(turn({ review: true }))).toBe("quiet");+ });++ it("lets a failed review clear the debt quietly: its failure notifies on its own", () => {+ const done = notice({ awaiting: new Set(["t"]) });+ done.atTurnEnd(turn());+ expect(done.atTurnEnd(turn({ review: true, ok: false }))).toBe("quiet");+ expect(done.owes("t")).toBe(false);+ });++ it("holds the done of a turn the person's queued message continues", () => {+ expect(notice({ queued: new Set(["t"]) }).atTurnEnd(turn())).toBe("hold");+ });++ it("forgets what a stopped hand-off owed once the person starts a new turn", () => {+ const done = notice({ awaiting: new Set(["t"]) });+ done.atTurnEnd(turn());+ done.personTurnStarted("t");+ expect(done.atTurnEnd(turn({ review: true }))).toBe("quiet");+ });++ it("leaves routine runs to their own rules", () => {+ expect(notice({ awaiting: new Set(["t"]), queued: new Set(["t"]) }).atTurnEnd(turn({ routine: true }))).toBe("notify");+ });+});diff --git a/server/done-notice.ts b/server/done-notice.tsnew file mode 100644index 0000000000..a8502f606a--- /dev/null+++ b/server/done-notice.ts@@ -0,0 +1,38 @@+// When a direct turn's end is news. A turn that hands work to teammates, or that a queued follow-up continues, is not+// the end of the job: its "done" is held, and the job's real end notifies instead. For a hand-off that is the review+// answer once the teammates' results are in. A review nobody held a "done" for (an incident review) stays quiet.++export type DoneVerdict = "notify" | "hold" | "quiet";++export interface DoneNoticeDeps {+ /** The conversation's turn waits on teammates it handed work to. */+ awaitingTeammates(threadId: string): boolean;+ /** The person queued a message that starts as soon as this turn ends; a queued report or teammate's ask does not+ * count, since its turn may be quiet and the person would then hear nothing. */+ queuedFollowUp(botId: string, threadId: string): boolean;+}++export function createDoneNotice(deps: DoneNoticeDeps) {+ const owed = new Set<string>();+ return {+ /** Called where a direct turn's "done" would be sent; `review` is the answer after teammates report. */+ atTurnEnd(turn: { botId: string; threadId: string; review: boolean; ok: boolean; routine: boolean }): DoneVerdict {+ if (turn.review && !owed.has(turn.threadId)) return "quiet";+ if (turn.routine) return "notify";+ // A review that hands work off again (another round) is not the end either: the debt carries to the next review.+ if (turn.ok && deps.awaitingTeammates(turn.threadId)) {+ owed.add(turn.threadId);+ return "hold";+ }+ if (turn.review) return owed.delete(turn.threadId) && turn.ok ? "notify" : "quiet";+ return deps.queuedFollowUp(turn.botId, turn.threadId) ? "hold" : "notify";+ },+ /** A new person turn replaces whatever the last job owed: a hand-off that was stopped never pings later. */+ personTurnStarted(threadId: string): void {+ owed.delete(threadId);+ },+ owes: (threadId: string): boolean => owed.has(threadId),+ };+}++export type DoneNotice = ReturnType<typeof createDoneNotice>;diff --git a/server/index.ts b/server/index.tsindex 87a79cf8e1..57ec080b0d 100644--- a/server/index.ts+++ b/server/index.ts@@ -249,7 +249,7 @@ import { promptWithDataContext } from "../shared/data-context.ts";import { admit, roomTurnHolds } from "./admission.ts";import {drainSteeredMessages,- hasQueuedSteeredMessages,+ hasQueuedPersonMessage, hasQueuedSteeredMessages,isSteeredMessageQueued,onSteeredQueueChange,queuedSteerSnapshot,@@ -257,7 +257,7 @@ import {queuedThreadPosition,queueSteeredMessage,restoreSteeredMessages,-} from "./steer-queue.ts";+} from "./steer-queue.ts"; import { createDoneNotice } from "./done-notice.ts";import {drainChannelMessages,restoreChannelMessages,@@ -5029,7 +5029,7 @@ const providerLabel = (provider: string): string => {};// Rewritten by every dispatch, so a quiet turn never silences the next one.-const quietTurnThreads = new Set<string>();+const quietTurnThreads = new Set<string>(); const doneNotice = createDoneNotice({ awaitingTeammates: (threadId) => coordinator.awaitingTeammateThreads().has(threadId), queuedFollowUp: hasQueuedPersonMessage });const QUIET_TURN_NEWS: ReadonlySet<Notification["kind"]> = new Set(["done", "turn-failed", "incident"]);function notify(notification: Notification | null, how?: { routine?: boolean }) {@@ -6937,7 +6937,7 @@ bus.subscribe((event: RuntimeEvent) => {const routineReportThread = routineRun ? routineSourceThread(routineRun) : null;if (!routineReportThread && (!internal || reviewAnswer)) store.patchTask(bot.id, event.threadId, { unread: true });if (routineRun && routineReportThread !== event.threadId) automationReports.runSettled(routineRun, completedTurnId);- else if ((!routineRun || routineRun.status === "completed") && !internal && !computerSelectionTurns.get(event.threadId)?.selected) {+ else if ((!routineRun || routineRun.status === "completed") && (!internal || reviewAnswer) && !computerSelectionTurns.get(event.threadId)?.selected && doneNotice.atTurnEnd({ botId: bot.id, threadId: event.threadId, review: reviewAnswer, ok: event.ok, routine: Boolean(routineRun) }) === "notify") {notify(buildNotification("done", bot, event.threadId, routineRun ? reply || routineRun.output || routineRun.routineName : reply, { avatarUrl: bot.avatarUrl }), routineRun ? { routine: true } : undefined);}if (screenPollers.has(event.threadId)) {@@ -7757,7 +7757,7 @@ async function startTurn(const turnImages = usesNativeImageInput ? resolvedImages.images : [];const commsDepth = opts?.commsDepth ?? 0;if (commsDepth > 0) markInternalTurn(threadId);- else clearInternalTurn(threadId);+ else { clearInternalTurn(threadId); doneNotice.personTurnStarted(threadId); }if (answer.quiet) quietTurnThreads.add(threadId);else quietTurnThreads.delete(threadId);if (resolvedImages.text.trim() && !opts?.cardContinuation && !opts?.replyTo?.reactedWith) {diff --git a/server/long-running-chief.e2e.test.ts b/server/long-running-chief.e2e.test.tsindex 6089028d57..02066155c2 100644--- a/server/long-running-chief.e2e.test.ts+++ b/server/long-running-chief.e2e.test.ts@@ -231,10 +231,12 @@ it("carries a consult-and-implement job over several teammate turns, through a sexpect(chiefRows.filter((name: string) => name.startsWith("Resumed with"))).toEqual(["Resumed with Mira, Eli results, reviewing", "Resumed with Mira, Eli results, reviewing"]);for (const node of f.tree(job).filter((candidate: any) => candidate.parentId)) expect(await f.cards(node.threadId)).toEqual([]);expect(f.notifications.filter((notification: any) => notification.kind === "approval")).toEqual([]);+ // No "done" while teammates still work (A0, and A1 handing off again): one at the job's end, with its final answer.+ await expect.poll(() => f.notifications.some((notification: any) => notification.kind === "done"), { timeout: 10_000 }).toBe(true);expect(f.notifications.map((notification: any) => [notification.kind, notification.body])).toEqual([- ["done", "A0: Mira is consulting and Eli is implementing."],["delegation-settled", "Results in from Mira, Eli"],["delegation-settled", "Results in from Mira, Eli"],+ ["done", expect.stringContaining("A-FINAL")],]);const consult = f.prompt(f.turn("M1"));@@ -300,11 +302,12 @@ it("tells the Chief what happened to each approval: allowed, denied, or never anexpect(f.prompt(f.turn("B3"))).toContain("[OpenMausBot report from @Mira on assignment ");expect((await f.cards(work)).map((message: any) => [message.card.subtitle, message.card.answered, message.card.dismissed, message.card.answeredBy?.kind])).toEqual([["git log --oneline -5 -- src/export", "allow", false, "loopback"], ["git push origin export", "deny", false, "loopback"], ["pnpm test", "deny", true, undefined]]);+ await expect.poll(() => f.notifications.some((notification: any) => notification.kind === "done"), { timeout: 10_000 }).toBe(true);expect(f.notifications.map((notification: any) => [notification.kind, notification.body])).toEqual([- ["done", "B0: Mira is checking."],["approval", "git log --oneline -5 -- src/export"], ["delegation-settled", "Results in from Mira"],["approval", "git push origin export"], ["delegation-settled", "Results in from Mira"],["approval", "pnpm test"], ["delegation-settled", "Results in from Mira"],+ ["done", expect.stringContaining("APPROVALS-FINAL")],]);}), hostTimeout(120_000));@@ -415,8 +418,9 @@ it("tells the Chief a teammate's turn stalled, in the watchdog's words", () => cexpect(f.child(job, f.mira.id, "LONG-SUITE").result).toBe(stalled.result);expect(f.turns(f.clive.id).map((record: any) => record.planKey)).toEqual(["D0", "D1"]);expect((await f.tasks(f.clive.id)).map((task: any) => task.title)).not.toContain("Team incidents");+ await expect.poll(() => f.notifications.some((notification: any) => notification.kind === "done"), { timeout: 10_000 }).toBe(true);expect(f.notifications.map((notification: any) => [notification.kind, notification.body])).toEqual([- ["done", "D0: Mira is running the suite."], ["delegation-settled", "Results in from Mira"]]);+ ["delegation-settled", "Results in from Mira"], ["done", expect.stringContaining("STALL-FINAL")]]);}), hostTimeout(90_000));it("lets a card hold only its own job: other jobs run beside it, or say once whose card they wait behind", () => chiefJob(async (f) => {diff --git a/server/notification-routing.e2e.test.ts b/server/notification-routing.e2e.test.tsindex 81230e0662..66c55fe533 100644--- a/server/notification-routing.e2e.test.ts+++ b/server/notification-routing.e2e.test.ts@@ -391,8 +391,10 @@ describe("bot-to-bot coordination is recorded, not announced", () => {const notified = stream.frames.filter((candidate) => candidate.kind === "notify").map((candidate) => candidate.notification);expect(notified.filter((notification) => notification?.botId === peer.id), JSON.stringify(notified)).toEqual([]);expect(notified.every((notification) => notification?.botId === asker.id && notification?.threadId === asker.threadId), JSON.stringify(notified)).toBe(true);- expect(notified.map((notification) => notification?.kind), JSON.stringify(notified)).toEqual(["done", "delegation-settled"]);- expect(notified[1]).toMatchObject({ title: "Pen resumed with results", body: "Results in from Ink" });+ // The hand-off turn is not the end of the job: no "done" then. Results in, then one "done" with the reviewed answer.+ expect(notified.map((notification) => notification?.kind), JSON.stringify(notified)).toEqual(["delegation-settled", "done"]);+ expect(notified[0]).toMatchObject({ title: "Pen resumed with results", body: "Results in from Ink" });+ expect(notified[1]).toMatchObject({ title: "Pen finished", body: expect.stringContaining("saw the result") });} finally {stream.close();await cleanup([], [asker.id, peer.id]);diff --git a/server/steer-e2e.test.ts b/server/steer-e2e.test.tsindex a79340b3bf..d20d9b9808 100644--- a/server/steer-e2e.test.ts+++ b/server/steer-e2e.test.ts@@ -217,6 +217,11 @@ posixOnly("mid-turn steering e2e", () => {expect(bot.messages.some((m: any) => m.role === "bot" && m.kind === "text" && m.text.includes("steered: a new task for later"))).toBe(false);expect(bot.messages.some((m: any) => m.role === "bot" && m.kind === "text" && withoutTurnClock(m.text).startsWith("reply to: first"))).toBe(true);expect(bot.messages.filter((m: any) => m.role === "user" && m.kind === "text").map((m: any) => m.text)).toEqual(["first", "a new task for later"]);+ // The first turn's end was not the end: the queued message ran next. One "done", for the turn that finished last.+ await waitFor(async () => ((await api("GET", "/api/notifications")).body.notifications ?? []).some((n: any) => n.botId === created.id && n.kind === "done"), "the done notification");+ const dones = ((await api("GET", "/api/notifications")).body.notifications as any[]).filter((n) => n.botId === created.id && n.kind === "done");+ expect(dones).toHaveLength(1);+ expect(dones[0].body).toContain("a new task for l");}, 40_000);it("a message sent with followUp: restart during a Claude turn stops that turn and runs as the next one, never steered", async () => {diff --git a/server/steer-queue.ts b/server/steer-queue.tsindex 15abc0ce72..6559d7f01d 100644--- a/server/steer-queue.ts+++ b/server/steer-queue.ts@@ -155,6 +155,12 @@ export function hasQueuedSteeredMessages(botId: string, threadId: string): boolereturn entry?.botId === botId && entry.items.length > 0;}+/** A message the person typed waits to run next, not a teammate's ask, an incident report, a relay or unattended work. */+export function hasQueuedPersonMessage(botId: string, threadId: string): boolean {+ const entry = queues.get(threadId);+ return entry?.botId === botId && entry.items.some((item) => !item.peerAsk && !item.unattended && !item.relay && !item.fromApp);+}+export function isSteeredMessageQueued(botId: string, threadId: string, queueId: string): boolean {const entry = queues.get(threadId);return entry?.botId === botId && entry.items.some((item) => item.messageId === queueId);