Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(chat): bound an exchange reopened from an earlier request by its own end
luishron123a44d67772a5b
diff --git a/src/components/HandoffExchange.dom.test.ts b/src/components/HandoffExchange.dom.test.tsindex 33146ce4d0..a43846d161 100644--- a/src/components/HandoffExchange.dom.test.ts+++ b/src/components/HandoffExchange.dom.test.ts@@ -12,6 +12,7 @@ const fixture = vi.hoisted(() => ({dispatch: vi.fn(),listeners: new Set<LiveFrameListener>(),load: vi.fn(),+ api: vi.fn(),}));const bot = (id: string, name: string, color: string, threadId: string, tasks: Bot["tasks"] = []): Bot => ({id, threadId, name, title: "", description: "", notifications: true, color, unread: false, messages: [],@@ -31,7 +32,7 @@ vi.mock("@/state/store-select", async (importOriginal) => ({useStoreSelector: (select: (state: unknown) => unknown) => select({ bots: [maestro, helper] }),}));vi.mock("@/state/api", async (importOriginal) => ({- ...await importOriginal<typeof import("@/state/api")>(), api: async () => ({ since: 0, version: "v1", nodes: [], needsInput: [] }),+ ...await importOriginal<typeof import("@/state/api")>(), api: fixture.api,}));vi.mock("@/state/message-history", async (importOriginal) => ({...await importOriginal<typeof import("@/state/message-history")>(), loadFullThread: fixture.load,@@ -66,6 +67,8 @@ beforeEach(() => {fixture.dispatch.mockClear();fixture.listeners.clear();fixture.load.mockReset();+ fixture.api.mockReset();+ fixture.api.mockResolvedValue({ since: 0, version: "v1", nodes: [], needsInput: [] });if (typeof globalThis.ResizeObserver === "undefined") {vi.stubGlobal("ResizeObserver", class { observe() {} disconnect() {} unobserve() {} });}@@ -216,6 +219,40 @@ describe("a teammate's hand-off line", () => {expect(rows()).toEqual(["asker: MaestroNow run the tests", "helper: FerramenteiroTests pass"]);});+ describe("reopened from an earlier request", () => {+ // h1 ended at 2 500; a later line in the helper's thread is not part of it. The "Sent to" row saw the end late.+ const request: Message = { id: "q1", role: "bot", kind: "text", text: "Please check the build", at: 1_000, parentId: null,+ from: { botId: "maestro", name: "Maestro", color: "blue" }, roomRequest: { id: "h1", phase: "request" } } as Message;+ const reply: Message = { id: "r1", role: "bot", kind: "text", text: "Build is green", at: 2_000, parentId: "q1" };+ const later: Message = { id: "r2", role: "bot", kind: "text", text: "Cleaned up the cache too", at: 6_000, parentId: "r1" };+ const row = sent({ id: "sent-h1", at: 900, handoff: { id: "h1", state: "done", at: 2_600 } });+ const node = (extra: object) => ({ botName: "", threadId: "", status: "completed", reply: "required", createdAt: 950, ...extra });+ async function reopen() {+ fixture.load.mockResolvedValue({ messages: [request, reply, later], activeLeafId: "r2" });+ render(row);+ flushSync(() => chip().click());+ for (let i = 0; i < 3; i++) await settle();+ flushSync(() => {});+ }++ it("reads that hand-off from its \"Sent to\" row and shows only its own lines and how it ended", async () => {+ fixture.api.mockImplementation(async (path: string) => path.includes("since=900") ? {+ since: 900, version: "v1", needsInput: [],+ nodes: [node({ id: "root", botId: "maestro", botName: "Maestro", threadId: "maestro-main" }),+ node({ id: "h1", parentId: "root", botId: "tool", botName: "Ferramenteiro", threadId: "help-1", finishedAt: 2_500 })],+ } : { since: 0, version: "v1", nodes: [], needsInput: [] });+ await reopen();+ expect(fixture.api.mock.calls.map(([path]) => path)).toContain("/api/threads/maestro-main/job?since=900");+ expect(rows()).toEqual(["asker: MaestroPlease check the build", "helper: FerramenteiroBuild is green"]);+ expect(exchange()!.querySelector("[data-bot-exchange-status]")!.textContent).toBe("Ferramenteiro answered in 2s");+ });++ it("bounds its lines by when its row saw it end when the server no longer has it", async () => {+ await reopen();+ expect(rows()).toEqual(["asker: MaestroPlease check the build", "helper: FerramenteiroBuild is green"]);+ });+ });+it("opens the thread as before where no chat column hosts the exchange", () => {flushSync(() => root.render(createElement(ThreadChip, { message: sent(), threadId: "maestro-main" })));expect(chip().hasAttribute("data-exchange-chip")).toBe(false);diff --git a/src/components/HandoffExchange.tsx b/src/components/HandoffExchange.tsxindex dd9f92de6e..21d2aad29b 100644--- a/src/components/HandoffExchange.tsx+++ b/src/components/HandoffExchange.tsx@@ -16,7 +16,7 @@ import { conversationRows, handoffTranscript, LOADING_TRANSCRIPT, type Conversatimport { intlLocale, t } from "@/lib/i18n";import { listenLiveFrames } from "@/lib/live-events";import { localDay } from "@/lib/transcript-derivations";-import { BotExchangesContext, latestPersonTurn, useBotExchanges } from "@/lib/use-bot-exchanges";+import { BotExchangesContext, latestPersonTurn, useBotExchanges, useEarlierExchange } from "@/lib/use-bot-exchanges";import { loadFullThread } from "@/state/message-history";import { visibleMessages } from "@/state/snapshot-navigation";import type { Bot, Message } from "@/state/store";@@ -31,6 +31,10 @@ export interface HandoffExchange {threadId: string;/** The hand-off, when the view is for one exchange: only its own lines show, and it can be stopped. */id?: string;+ /** When its "Sent to" row was written, for a hand-off from an earlier request. */+ sentAt?: number;+ /** When its "Sent to" row last saw it end: the bound on its lines if the server no longer has the hand-off. */+ endedAt?: number;}/** Opens a hand-off's exchange in place of the chat it is in. Null where no chat column hosts one (a room, the side@@ -46,7 +50,11 @@ export function HandoffExchangeHost({ bot, children }: { bot: Bot; children: Reaconst openExchange = useCallback((exchange: HandoffExchange) => setOpen({ chat, exchange }), [chat]);const exchange = open?.chat === chat ? open.exchange : null;const since = useMemo(() => latestPersonTurn(bot.messages), [bot.messages]);- const exchanges = useBotExchanges(bot.threadId, since, Boolean(bot.busy || bot.waitingForTeammates));+ const current = useBotExchanges(bot.threadId, since, Boolean(bot.busy || bot.waitingForTeammates));+ const covered = current.exchanges.some((entry) => entry.id === exchange?.id);+ const earlier = useEarlierExchange(bot.threadId, exchange?.id, exchange?.sentAt, covered);+ const exchanges = useMemo(() => earlier && !covered ? { ...current, exchanges: [...current.exchanges, earlier] } : current,+ [current, earlier, covered]);return (<BotExchangesContext value={exchanges}>{exchange ? <HandoffExchangeView key={exchange.id ?? exchange.threadId} exchange={exchange} onBack={() => setOpen(null)} />@@ -55,7 +63,7 @@ export function HandoffExchangeHost({ bot, children }: { bot: Bot; children: Rea);}-export function HandoffExchangeView({ exchange: { asker, helper, threadId, id }, onBack }: { exchange: HandoffExchange; onBack: () => void }) {+export function HandoffExchangeView({ exchange: { asker, helper, threadId, id, endedAt }, onBack }: { exchange: HandoffExchange; onBack: () => void }) {const [transcript, dispatch] = useReducer(handoffTranscript, LOADING_TRANSCRIPT);const [load, setLoad] = useState(0);const reload = () => {@@ -87,8 +95,8 @@ export function HandoffExchangeView({ exchange: { asker, helper, threadId, id },const entry = use(BotExchangesContext).exchanges.find((candidate) => candidate.id === id);const lines = useMemo(() => id === undefined ? null- : exchangeLines(visibleMessages(transcript), { id, state: entry?.state ?? "working", finishedAt: entry?.finishedAt }),- [transcript, id, entry?.state, entry?.finishedAt]);+ : exchangeLines(visibleMessages(transcript), { id, state: entry?.state ?? "working", finishedAt: entry?.finishedAt ?? endedAt }),+ [transcript, id, entry?.state, entry?.finishedAt, endedAt]);const you = t("chat.you");const rows = useMemo(() => {const all = conversationRows(transcript, asker, helper, you);diff --git a/src/components/ThreadChip.tsx b/src/components/ThreadChip.tsxindex cae3815449..47cc21d3b2 100644--- a/src/components/ThreadChip.tsx+++ b/src/components/ThreadChip.tsx@@ -24,9 +24,10 @@ export function ThreadChip({ message, threadId }: { message: Message; threadId?:// A teammate's work for the bot that sent it is read in place of this chat; any other thread still opens in its own chat.const asker = message.from;// The helper's main chat is its talk with the person, not with the asker: that still opens there.+ const handoff = message.handoff, ended = handoff?.state === "done" || handoff?.state === "failed";const workThread = bot && ref.threadId !== bot.threadId && (bot.tasks ?? []).some((task) => task.threadId === ref.threadId);const exchange = openExchange && !direct && asker && bot && asker.botId !== bot.id && workThread- ? { asker, helper: { botId: bot.id, name: bot.name, color: bot.color }, threadId: ref.threadId, ...(message.handoff ? { id: message.handoff.id } : {}) }+ ? { 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 }) : "";return (diff --git a/src/lib/use-bot-exchanges.ts b/src/lib/use-bot-exchanges.tsindex 70628b9cb9..5b0e9a518b 100644--- a/src/lib/use-bot-exchanges.ts+++ b/src/lib/use-bot-exchanges.ts@@ -72,6 +72,23 @@ export function useBotExchanges(threadId: string | undefined, since: number | unreturn useMemo(() => ({ exchanges, stop }), [exchanges, stop]);}+/** An exchange opened from an earlier request, which the read from the person's latest message no longer covers. The+ * server's job read takes every hand-off still open at `since`, so reading from its "Sent to" row finds it. */+export function useEarlierExchange(threadId: string | undefined, id: string | undefined, since: number | undefined, covered: boolean): BotExchangeEntry | undefined {+ const [found, setFound] = useState<{ id: string; entry: BotExchangeEntry } | null>(null);+ const teammate = t("chat.botExchange.teammate");+ useEffect(() => {+ if (!threadId || !id || since === undefined || covered) return;+ const abort = new AbortController();+ api<JobRead>(`/api/threads/${encodeURIComponent(threadId)}/job?since=${since}`, { signal: abort.signal, background: true }).then((job) => {+ const entry = Array.isArray(job?.nodes) ? exchangesOf(job, teammate).find((candidate) => candidate.id === id) : undefined;+ if (entry && !abort.signal.aborted) setFound({ id, entry });+ }, () => {});+ return () => abort.abort();+ }, [threadId, id, since, covered, teammate]);+ return found && found.id === id ? found.entry : undefined;+}+const pause = (ms: number, signal: AbortSignal) => new Promise<void>((resolve) => {const stop = () => { clearTimeout(timer); resolve(); };const timer = setTimeout(() => { signal.removeEventListener("abort", stop); resolve(); }, ms);