Skip to content

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

Fold answers Check before done sent back for fixing

AdityaUmale7ed5130fd0b5
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index 3f46f1eeef..d832993d86 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -562,7 +562,7 @@ export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCard
/** On a conversational bot's user line: the picker label of the quick model its reply ran on. */
quickModel?: string;
/** On a "Sent to" hand-off row: the done_when the sender set, redacted, so the chip can show what counts as finished. */
- doneWhen?: string;
+ doneWhen?: string; /** On a Check before done line that sent the answer back for fixing: that round, so a client can fold the answer it replaced. */ checkRound?: number;
/** Set on the user-role line another bot delivered into this bot's own
* conversation (coordinate_bots, start_thread). `incident`: the line is a
* Team incidents report about that bot's thread
diff --git a/server/host/check-work.test.ts b/server/host/check-work.test.ts
index 966d0d27c3..4cf1b8442a 100644
--- a/server/host/check-work.test.ts
+++ b/server/host/check-work.test.ts
@@ -31,7 +31,7 @@ function fixture(options: { checkWork?: CheckWorkBot["checkWork"]; checkerReplie
const timers: Array<{ at: number; run: () => void; off: boolean }> = [];
const runs: Array<{ botId: string; threadId: string; text: string; kind: "check" | "fix" }> = [];
const held: Array<(outcome: HostTurnResult) => void> = [];
- const posted: Array<{ name: string; ok: boolean; input: string; output: string }> = [];
+ const posted: Array<{ name: string; ok: boolean; input: string; output: string; round?: number }> = [];
const done: string[] = [], interrupted: string[] = [], closed: Array<[string, boolean]> = [], changed: string[] = [];
let saved = options.saved ?? [];
const checkerReplies = [...(options.checkerReplies ?? [])], fixes = [...(options.fixes ?? [])];
@@ -163,6 +163,7 @@ describe("check before done", () => {
expect(f.runs[2]!.text).toContain("<result>\nFixed chapter, dawn, no scar.\n</result>");
expect(f.runs[2]!.text).toContain(`<earlier-report>\n${report}\n</earlier-report>`);
expect(f.posted.map((line) => [line.name, line.ok])).toEqual([["Vera found 2 issues · fixing them, round 1 of 3", true], ["Checked by Vera · passed in round 2", true]]);
+ expect(f.posted.map((line) => line.round)).toEqual([1, undefined]);
expect(f.done).toEqual(["Fixed chapter, dawn, no scar."]);
});
@@ -170,6 +171,7 @@ describe("check before done", () => {
const f = fixture({ checkerReplies: [{ text: "issues: 2\n1. a\n2. b" }, { text: "issues: 1\n1. b" }, { text: "1 issue\n1. still b" }], fixes: [{ text: "Fix one." }, { text: "Fix two." }] });
await f.start();
expect(f.runs.map((run) => run.kind)).toEqual(["check", "fix", "check", "fix", "check"]);
+ expect(f.posted.map((line) => line.round)).toEqual([1, 2, undefined]);
expect(f.posted.at(-1)).toEqual({ name: "Checked by Vera · 1 issue still open after 3 rounds", ok: false, input: "Vera · round 3 of 3", output: "1 issue\n1. still b", ref: { botId: "v", threadId: "check-1" } });
expect(f.done).toEqual(["Fix two."]);
});
diff --git a/server/host/check-work.ts b/server/host/check-work.ts
index c3f4815a0c..d700cf87ab 100644
--- a/server/host/check-work.ts
+++ b/server/host/check-work.ts
@@ -44,7 +44,7 @@ export interface CheckWorkDeps {
messages(threadId: string): readonly Line[];
/** A line in the person's conversation: with `ref`, a link to the thread the check ran in, which holds the full
* report; without, a quiet notice. Both show in Simple mode as in Advanced. */
- post(threadId: string, line: { name: string; ok: boolean; input: string; output: string; ref?: Place }): void;
+ post(threadId: string, line: { name: string; ok: boolean; input: string; output: string; ref?: Place; round?: number }): void;
line(threadId: string, key: ServerLineKey, params?: Readonly<Record<string, string | number>>): string;
/** Opens the one thread an answer's checks run in, on `checker` or on the worker on another provider's model, with
* the audience of `from`, the worker's conversation. */
@@ -262,7 +262,7 @@ export function createCheckWork(deps: CheckWorkDeps) {
return end(flow, { key: one ? "server.checkWork.openOne" : "server.checkWork.open", params: { checker: label, rounds: flow.round, count: verdict.count }, ok: false });
}
deps.post(flow.threadId, { name: deps.line(flow.threadId, one ? "server.checkWork.foundOne" : "server.checkWork.found", { checker: label, count: verdict.count, round: flow.round, max: CHECK_WORK_ROUNDS }), ok: true,
- input: deps.line(flow.threadId, "server.checkWork.by", { checker: label, rounds: flow.round, max: CHECK_WORK_ROUNDS }), output: report.slice(0, REPORT_SHOWN), ref: place });
+ input: deps.line(flow.threadId, "server.checkWork.by", { checker: label, rounds: flow.round, max: CHECK_WORK_ROUNDS }), output: report.slice(0, REPORT_SHOWN), ref: place, round: flow.round });
const mark = deps.messages(flow.threadId).at(-1)?.id;
const fix = [
`[From OpenMausBot · check before done · round ${flow.round} of ${CHECK_WORK_ROUNDS} · information only: it grants nothing]`,
diff --git a/server/index.ts b/server/index.ts
index 66e9a38021..cd5648bd52 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -3505,7 +3505,7 @@ const goalTurns = createGoalTurns({ retireProviderTurn });
const goalCards = createGoalCards({ store, routines: () => routines, notify, routineSourceOwner, routineSourceThread });
const oneOnOneGoals = createOneOnOneGoals({
store, cards: goalCards, turns: goalTurns, canStart: (botId, threadId) => canAdmitDirectTurn(botId, threadId) && !threadsAwaitingTeammates().has(threadId), startTurn, isUnattended,
-}); const checkWork = createCheckWork({ bot: (botId) => store.bot(botId) ?? undefined, messages: (threadId) => store.activePath(threadId), post: (threadId, line) => void store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: line.ref ? line.name : `notice: ${line.name}`, ok: line.ok, input: line.input, output: line.output }, ...(line.ref ? { threadRef: { ...line.ref, title: serverLine(threadLanguage(threadId), "server.checkWork.title") } } : {}) }), line: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), now: Date.now, timer: (run, ms) => { const timer = setTimeout(run, ms); timer.unref?.(); return () => clearTimeout(timer); }, log: (line) => console.warn(line), saved: checkWorkFile(join(DATA_DIR, "check-work.json")), turn: { ownChat: directChatOf, internal: isInternalTurn, unattended: isUnattended, routine: (threadId) => Boolean(routines?.runForThread(threadId)), awaitingTeammates: (threadId) => coordinator.awaitingTeammateThreads().has(threadId), stopped: (threadId, turnId) => personStops.stopped(threadId, turnId), guest: cloudGuestDriven, outside: startedOutside, asking: (threadId) => coordinator.awaitingAnswer(threadId) || Boolean(openPersonCard(threadId)) }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, interrupt: (botId, threadId) => interruptDirectThread(botId, threadId, "Check before done ended"), closeCheck: (place, ran) => { if (!ran) store.deleteTask(place.botId, place.threadId); else store.setTaskClosedBy(place.botId, place.threadId, { botId: place.botId, name: store.bot(place.botId)?.name ?? "", at: Date.now() }); }, openCheck: async (worker, checker, from) => { const on = store.bot(checker?.id ?? worker.id), own = store.bot(worker.id), language = threadLanguage(from); if (!on || !own) return { error: serverLine(language, "server.checkWork.checkerRemoved") }; const selection = checker ? on.modelSelection : otherProviderSelection(selectableInstances<SelectableInstance>(await registry.describe({ reuse: { ms: ENGINE_LIST_REUSE_MS, maxAgeMs: SUGGESTION_MAX_AGE_MS, changed: () => broadcast({ kind: "config", ...configStatus() }) } })), own.modelSelection, selectionContext) ?? own.modelSelection; const opener = openerFrom(from); const task = store.createTask(on.id, serverLine(language, "server.checkWork.title"), false, undefined, { botId: own.id, name: own.name, at: Date.now() }, undefined, checker ? undefined : selection, undefined, (created) => threadStarters.set(created.threadId, opener)); if (!task) return { error: serverLine(language, "server.checkWork.couldNotStart", { checker: on.name, reason: "no thread" }) }; outsideLineage.carry(from, task.threadId); return { botId: on.id, threadId: task.threadId, model: registry.get(selection.instanceId)?.models.options.find((option) => option.id === selection.model)?.label ?? selection.model }; }, run: (botId, threadId, text, kind, settled) => startTurn(botId, text, { threadId, commsDepth: 1, onSettled: settled, ...(kind === "fix" ? { cardContinuation: true, requestMessageId: directRequestOwners.get(threadId)?.messageId } : {}) }), exists: (place) => Boolean(store.taskByThread(place.botId, place.threadId)), done: (botId, threadId, text, restarted) => { const bot = store.bot(botId); if (!bot || !store.taskByThread(botId, threadId)) return; store.patchTask(botId, threadId, { unread: true }, { turnEnd: true }); if (doneNotice.atTurnEnd({ botId, threadId, review: true, ok: true, routine: false }) === "notify" || restarted) notify(buildNotification("done", bot, threadId, text, { avatarUrl: bot.avatarUrl })); } }); store.onChange((change) => { if (change.type === "bot" || change.type === "bot.deleted") checkWork.botChanged(change.botId); });
+}); const checkWork = createCheckWork({ bot: (botId) => store.bot(botId) ?? undefined, messages: (threadId) => store.activePath(threadId), post: (threadId, line) => void store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: line.ref ? line.name : `notice: ${line.name}`, ok: line.ok, input: line.input, output: line.output }, ...(line.round ? { checkRound: line.round } : {}), ...(line.ref ? { threadRef: { ...line.ref, title: serverLine(threadLanguage(threadId), "server.checkWork.title") } } : {}) }), line: (threadId, key, params) => serverLine(threadLanguage(threadId), key, params), now: Date.now, timer: (run, ms) => { const timer = setTimeout(run, ms); timer.unref?.(); return () => clearTimeout(timer); }, log: (line) => console.warn(line), saved: checkWorkFile(join(DATA_DIR, "check-work.json")), turn: { ownChat: directChatOf, internal: isInternalTurn, unattended: isUnattended, routine: (threadId) => Boolean(routines?.runForThread(threadId)), awaitingTeammates: (threadId) => coordinator.awaitingTeammateThreads().has(threadId), stopped: (threadId, turnId) => personStops.stopped(threadId, turnId), guest: cloudGuestDriven, outside: startedOutside, asking: (threadId) => coordinator.awaitingAnswer(threadId) || Boolean(openPersonCard(threadId)) }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, interrupt: (botId, threadId) => interruptDirectThread(botId, threadId, "Check before done ended"), closeCheck: (place, ran) => { if (!ran) store.deleteTask(place.botId, place.threadId); else store.setTaskClosedBy(place.botId, place.threadId, { botId: place.botId, name: store.bot(place.botId)?.name ?? "", at: Date.now() }); }, openCheck: async (worker, checker, from) => { const on = store.bot(checker?.id ?? worker.id), own = store.bot(worker.id), language = threadLanguage(from); if (!on || !own) return { error: serverLine(language, "server.checkWork.checkerRemoved") }; const selection = checker ? on.modelSelection : otherProviderSelection(selectableInstances<SelectableInstance>(await registry.describe({ reuse: { ms: ENGINE_LIST_REUSE_MS, maxAgeMs: SUGGESTION_MAX_AGE_MS, changed: () => broadcast({ kind: "config", ...configStatus() }) } })), own.modelSelection, selectionContext) ?? own.modelSelection; const opener = openerFrom(from); const task = store.createTask(on.id, serverLine(language, "server.checkWork.title"), false, undefined, { botId: own.id, name: own.name, at: Date.now() }, undefined, checker ? undefined : selection, undefined, (created) => threadStarters.set(created.threadId, opener)); if (!task) return { error: serverLine(language, "server.checkWork.couldNotStart", { checker: on.name, reason: "no thread" }) }; outsideLineage.carry(from, task.threadId); return { botId: on.id, threadId: task.threadId, model: registry.get(selection.instanceId)?.models.options.find((option) => option.id === selection.model)?.label ?? selection.model }; }, run: (botId, threadId, text, kind, settled) => startTurn(botId, text, { threadId, commsDepth: 1, onSettled: settled, ...(kind === "fix" ? { cardContinuation: true, requestMessageId: directRequestOwners.get(threadId)?.messageId } : {}) }), exists: (place) => Boolean(store.taskByThread(place.botId, place.threadId)), done: (botId, threadId, text, restarted) => { const bot = store.bot(botId); if (!bot || !store.taskByThread(botId, threadId)) return; store.patchTask(botId, threadId, { unread: true }, { turnEnd: true }); if (doneNotice.atTurnEnd({ botId, threadId, review: true, ok: true, routine: false }) === "notify" || restarted) notify(buildNotification("done", bot, threadId, text, { avatarUrl: bot.avatarUrl })); } }); store.onChange((change) => { if (change.type === "bot" || change.type === "bot.deleted") checkWork.botChanged(change.botId); });
bus.subscribe((event: RuntimeEvent) => { if (event.type === "turn.completed" && event.ok && event.turnId && !shouldIgnoreProviderEvent(event)) checkWork.answered(store.botByThread(event.threadId)?.id, event.threadId, event.turnId); });
function groupIsWorking(group: GroupRecord): boolean {
diff --git a/src/components/ChatView.check-rounds.test.ts b/src/components/ChatView.check-rounds.test.ts
new file mode 100644
index 0000000000..881a4d41f6
--- /dev/null
+++ b/src/components/ChatView.check-rounds.test.ts
@@ -0,0 +1,75 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { describe, expect, it, vi } from "vitest";
+import type { AppState, Bot, InstanceInfo, Message } from "@/state/store";
+
+vi.mock("./DesktopCapabilities", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./DesktopCapabilities")>(),
+ useDesktopCapabilities: () => ({ capabilities: { dictation: { available: false }, host: { packaged: true, platform: "other" }, localComputer: { available: false } }, ready: true }),
+ useCaptionChrome: () => ({}),
+}));
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+vi.mock("@/lib/cloud-guest", () => ({ useCanWriteIn: () => true, useReactor: () => "user" }));
+vi.mock("./ModelPicker", () => ({ ModelPicker: () => null }));
+
+const { ChatView } = await import("./ChatView");
+const { BotEditorStore, initialState } = await import("@/state/store");
+const { t } = await import("@/lib/i18n");
+
+const at = new Date(2026, 10, 25, 9, 0).getTime();
+const check = (id: string, parentId: string, name: string, round?: number): Message => ({
+ id, parentId, at, role: "bot", kind: "activity", tool: { name, ok: true, input: "Vera · round 1 of 3", output: "Issues found: 1" },
+ threadRef: { botId: "pepper", threadId: "check-thread", title: "Check before done" }, ...(round ? { checkRound: round } : {}),
+});
+const messages: Message[] = [
+ { id: "ask", parentId: undefined, at, role: "user", kind: "text", text: "Write the summary" },
+ { id: "first", parentId: "ask", at, role: "bot", kind: "text", text: "First summary, it says dusk." },
+ check("found", "first", "Vera found 1 issue · fixing it, round 1 of 3", 1),
+ { id: "fixed", parentId: "found", at, role: "bot", kind: "text", text: "Fixed summary, it says dawn." },
+ check("passed", "fixed", "Checked by Vera · passed in round 2"),
+];
+const bot: Bot = {
+ id: "pepper", threadId: "pepper-thread", name: "Pepper", title: "", description: "", color: "green",
+ notifications: true, unread: false, busy: false, messages, activeLeafId: "passed", modelSelection: { instanceId: "test", model: "m" },
+ tasks: [{ threadId: "pepper-thread", title: "Thread", createdAt: 1, busy: false, activity: "idle", modelSelection: { instanceId: "test", model: "m" }, approvalMode: "ask" }],
+};
+const state: AppState = {
+ ...initialState,
+ connected: true,
+ selectedId: "pepper",
+ bots: [bot],
+ instances: [{ instanceId: "test", driverKind: "codex", displayName: "Test", snapshot: { state: "available" } } as InstanceInfo],
+ config: { features: { showToolCalls: false }, rooms: { turnTimeoutMinutes: 30 } } as unknown as AppState["config"],
+};
+
+describe("Check before done rounds in the chat", () => {
+ it("shows an answer a check sent back as one line that opens and folds again, and the fixed answer in full", () => {
+ vi.stubGlobal("fetch", () => new Promise(() => {}));
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ const value = { state, dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };
+ try {
+ flushSync(() => root.render(createElement(BotEditorStore, { value, children: createElement(ChatView, { bot }) })));
+ const folded = () => container.querySelector<HTMLButtonElement>("[data-testid=earlier-answer]");
+ expect(folded()?.textContent).toBe(`${t("chat.checkWork.earlierAnswer", { round: 1 })}First summary, it says dusk.`);
+ expect(container.querySelectorAll("[data-testid=earlier-answer]")).toHaveLength(1);
+ expect(container.querySelector("[data-look=message-bot]")?.textContent).toContain("Fixed summary, it says dawn.");
+ expect([...container.querySelectorAll("[data-look=message-bot]")].some((row) => row.textContent?.includes("First summary"))).toBe(false);
+
+ flushSync(() => folded()!.click());
+ expect(folded()).toBeNull();
+ const opened = [...container.querySelectorAll("[data-look=message-bot]")].find((row) => row.textContent?.includes("First summary, it says dusk."));
+ expect(opened).toBeDefined();
+ const less = [...opened!.querySelectorAll("button")].find((button) => button.textContent === t("chat.showLess"));
+ flushSync(() => less!.click());
+ expect(folded()).not.toBeNull();
+ } finally {
+ root.unmount();
+ container.remove();
+ vi.unstubAllGlobals();
+ }
+ });
+});
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index fa668b8e97..94ba15385b 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -51,7 +51,7 @@ import { BotAvatar } from "./Avatar";
import { TurnPresence } from "./TurnPresence";
import { showToolCallsEnabled } from "@/lib/feature-flags";
import { stateForBot } from "@/lib/mascot";
-import { peerLine, peerPreview, peerRequest } from "@/lib/peer-message"; import { PeerCompactRow, PeerLabel, PeerMessagesContext, PeerOpenedActions } from "./PeerExchange";
+import { flatPreview, peerLine, peerPreview, peerRequest } from "@/lib/peer-message"; import { PeerCompactRow, PeerLabel, PeerMessagesContext, PeerOpenedActions } from "./PeerExchange"; import { earlierAnswers } from "@/lib/check-rounds";
import { lastRequests } from "@/lib/automation-note"; import { automationNoteRow } from "./AutomationNoteRow";
import { showWorkingDots } from "@/lib/turn-tail";
import { lastNonReceipt } from "@/lib/receipts";
@@ -275,11 +275,11 @@ const Bubble = memo(function Bubble({
onRegenerate,
replyTarget,
onReply,
- forked = false,
+ forked = false, earlierRound,
}: {
message: Message;
/** A conversation was forked from this message. */
- forked?: boolean;
+ forked?: boolean; /** Check before done sent this answer back for fixing in this round: it shows as one line until opened. */ earlierRound?: number;
emerging?: boolean;
eagerAttachments?: boolean;
/** Simple mode: this bubble meets the one above (or below) in its sender's group. */
@@ -374,7 +374,7 @@ const Bubble = memo(function Bubble({
// A long request from another bot is one line until opened.
const peerLong = peer ? peerPreview(text) : null;
- if (peer && peerLong && !expanded && (!focusedSearch || folded)) return <div {...{ [MESSAGE_ROW]: "" }} className="group flex w-full flex-col items-start"><PeerLabel peer={peer} bots={bots} /><PeerCompactRow preview={peerLong} onOpen={() => setExpanded(true)} /></div>;
+ if (peer && peerLong && !expanded && (!focusedSearch || folded)) return <div {...{ [MESSAGE_ROW]: "" }} className="group flex w-full flex-col items-start"><PeerLabel peer={peer} bots={bots} /><PeerCompactRow preview={peerLong} onOpen={() => setExpanded(true)} /></div>; if (earlierRound && !expanded && !focusedSearch) return <div {...{ [MESSAGE_ROW]: "" }} className="group flex w-full flex-col items-start"><PeerCompactRow label={t("chat.checkWork.earlierAnswer", { round: earlierRound })} preview={flatPreview(text)} testId="earlier-answer" onOpen={() => setExpanded(true)} /></div>;
const forks = user && versions ? versions : [message];
const versionIndex = forks.findIndex((v) => v.id === message.id);
const switchTo = (v: Message | undefined) => {
@@ -537,7 +537,7 @@ const Bubble = memo(function Bubble({
</span>
</div>
{Boolean(message.reactions?.length) && <ReactionChips threadId={threadId} message={message} bots={bots} align={user ? "end" : "start"} canReact={canReact} />}
- {peer && expanded && peerLong && <PeerOpenedActions peer={peer} bots={bots} botId={botId} botName={botName} onFold={() => { setExpanded(false); setFolded(true); }} />}
+ {peer && expanded && peerLong && <PeerOpenedActions peer={peer} bots={bots} botId={botId} botName={botName} onFold={() => { setExpanded(false); setFolded(true); }} />}{earlierRound !== undefined && expanded && <button type="button" onClick={() => setExpanded(false)} className="mt-1 pl-0.5 text-[13px] text-ink-secondary hover:text-ink">{t("chat.showLess")}</button>}
{forked && <ForkLinks kind="bot" ownerId={botId} threadId={threadId} messageId={message.id} phone={phone} />}
{forks.length > 1 && (
<div className="mt-1 flex items-center gap-0.5 pr-1 text-[12px] text-ink-secondary">
@@ -612,7 +612,7 @@ const MessagesList = memo(function MessagesList({
const { botId, threadId, botName, botColor, bots, hasMore, focus, showToolCalls, locale, dispatch, canReact, simple = false } = useChatRows(), busy = use(ChatBusyContext);
const messages = useLiveTranscriptLayout(threadId, saved, transcript), forked = useForkedMessages("bot", botId, threadId);
// A finished turn keeps the bot's progress lines and folds only its tool steps under "Worked for", in both modes.
- const items = useMemo(() => groupTranscript(messages), [messages, locale]);
+ const items = useMemo(() => groupTranscript(messages), [messages, locale]), earlier = useMemo(() => earlierAnswers(messages), [messages]);
const drawnFrom = useMemo(() => drawFrom ? Math.max(0, items.findIndex((item) => item.kind === "message" ? item.message.id === drawFrom : item.messages.some((row) => row.id === drawFrom))) : 0, [items, drawFrom]);
const newestMessageId = messages.at(-1)?.id;
let newestUserMessageId: string | undefined;
@@ -723,7 +723,7 @@ const MessagesList = memo(function MessagesList({
onSubmitEdit={onSubmitEdit}
onRegenerate={m.id === lastBotTextId && !m.automation && canRetryLast ? onRegenerate : undefined}
replyTarget={lookups.replyTarget(m)}
- onReply={onReply} forked={forked.has(m.id)}
+ onReply={onReply} forked={forked.has(m.id)} earlierRound={earlier.get(m.id)}
/>
);
}
diff --git a/src/components/PeerExchange.tsx b/src/components/PeerExchange.tsx
index c7ac08f0e2..dfef8f6745 100644
--- a/src/components/PeerExchange.tsx
+++ b/src/components/PeerExchange.tsx
@@ -38,18 +38,19 @@ export const PEER_HOW = {
ask_bot: "chat.peer.asked",
} as const satisfies Record<PeerLine["delivery"], string>;
-/** The folded request: one line, opened by a click. */
-export function PeerCompactRow({ preview, onOpen }: { preview: string; onOpen: () => void }) {
+/** A folded message: one line, opened by a click, with `label` before the preview. */
+export function PeerCompactRow({ preview, onOpen, label, testId = "peer-compact" }: { preview: string; onOpen: () => void; label?: string; testId?: string }) {
return (
<button
type="button"
onClick={onOpen}
title={t("chat.showFull")}
- data-testid="peer-compact"
+ data-testid={testId}
className="flex w-fit max-w-[min(var(--chat-bubble-max),var(--chat-bubble-pct))] items-center gap-1.5 rounded-xl bg-card px-3 py-1.5 text-left text-[14px] text-ink-secondary hover:text-ink"
>
<ChevronRight size={14} className="shrink-0" />
- <span className="truncate">{preview}</span>
+ {label && <span className="shrink-0 font-medium">{label}</span>}
+ <span className={label ? "min-w-0 truncate" : "truncate"}>{preview}</span>
</button>
);
}
diff --git a/src/lib/check-rounds.test.ts b/src/lib/check-rounds.test.ts
new file mode 100644
index 0000000000..488824e318
--- /dev/null
+++ b/src/lib/check-rounds.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+import type { WireMessage as Message } from "../../shared/wire.ts";
+import { earlierAnswers } from "./check-rounds";
+
+const row = (id: string, fields: Partial<Message>): Message => ({ id, at: 1, role: "bot", kind: "text", ...fields }) as Message;
+const ask = (id: string) => row(id, { role: "user", text: "Write the chapter" });
+const answer = (id: string, text = `answer ${id}`) => row(id, { text });
+const found = (id: string, round: number) => row(id, { kind: "activity", tool: { name: "Vera found 2 issues", ok: true }, checkRound: round });
+const passed = (id: string) => row(id, { kind: "activity", tool: { name: "Checked by Vera · passed", ok: true }, threadRef: { botId: "vera", threadId: "check", title: "Check" } });
+
+describe("earlierAnswers", () => {
+ it("folds each answer a check sent back, with its round, and keeps the last answer whole", () => {
+ const messages = [ask("q"), answer("a1"), found("f1", 1), answer("a2"), found("f2", 2), answer("a3"), passed("p")];
+ expect([...earlierAnswers(messages)]).toEqual([["a1", 1], ["a2", 2]]);
+ });
+
+ it("folds every line of an answer given in several messages, and none of the fixed one", () => {
+ const messages = [ask("q"), answer("a1"), row("tool", { kind: "activity", tool: { name: "search", ok: true } }), answer("a1b"), found("f1", 1), answer("a2"), answer("a2b")];
+ expect([...earlierAnswers(messages)]).toEqual([["a1", 1], ["a1b", 1]]);
+ });
+
+ it("folds nothing in a chat with no check line, and never an answer to an earlier request", () => {
+ expect(earlierAnswers([ask("q"), answer("a1"), passed("p"), ask("q2"), answer("a2")]).size).toBe(0);
+ expect([...earlierAnswers([ask("q"), answer("old"), ask("q2"), answer("a1"), found("f1", 1), answer("a2")])]).toEqual([["a1", 1]]);
+ });
+
+ it("keeps the answer whole when the fix wrote nothing, as that answer is the one delivered", () => {
+ expect(earlierAnswers([ask("q"), answer("a1"), found("f1", 1), row("n", { kind: "activity", tool: { name: "notice: Not checked: the fix did not finish", ok: false } })]).size).toBe(0);
+ expect([...earlierAnswers([ask("q"), answer("a1"), found("f1", 1), answer("a2"), found("f2", 2)])]).toEqual([["a1", 1]]);
+ expect(earlierAnswers([ask("q"), answer("a1"), found("f1", 1), ask("q2"), answer("b1")]).size).toBe(0);
+ });
+
+ it("skips empty lines and lines from another bot", () => {
+ const messages = [ask("q"), answer("blank", " "), row("peer", { text: "from a teammate", from: { botId: "x", name: "X", color: "blue" } }), answer("a1"), found("f1", 1), answer("a2")];
+ expect([...earlierAnswers(messages)]).toEqual([["a1", 1]]);
+ });
+});
diff --git a/src/lib/check-rounds.ts b/src/lib/check-rounds.ts
new file mode 100644
index 0000000000..a3411052bc
--- /dev/null
+++ b/src/lib/check-rounds.ts
@@ -0,0 +1,24 @@
+// Check before done sends an answer back for fixing with a line that carries `checkRound`; the fixed answer follows it.
+import type { WireMessage as Message } from "../../shared/wire.ts";
+
+/** The bot's own answer lines a later check sent back for fixing, by message id, with that check's round: each answer
+ * line since the person last wrote, up to a line with `checkRound`, once a fixed answer follows that line. An answer
+ * whose fix wrote nothing (it failed or was stopped) is the one the person gets, so it stays whole. */
+export function earlierAnswers(messages: readonly Message[]): ReadonlyMap<string, number> {
+ const earlier = new Map<string, number>();
+ let answer: string[] = [], sentBack: { ids: string[]; round: number } | null = null;
+ for (const message of messages) {
+ if (message.role === "user") {
+ answer = [];
+ sentBack = null;
+ } else if (message.checkRound) {
+ sentBack = { ids: answer, round: message.checkRound };
+ answer = [];
+ } else if (message.role === "bot" && message.kind === "text" && !message.from && message.text?.trim()) {
+ for (const id of sentBack?.ids ?? []) earlier.set(id, sentBack!.round);
+ sentBack = null;
+ answer.push(message.id);
+ }
+ }
+ return earlier;
+}
diff --git a/src/lib/peer-message.ts b/src/lib/peer-message.ts
index 0fa9e7b839..78331fbe15 100644
--- a/src/lib/peer-message.ts
+++ b/src/lib/peer-message.ts
@@ -56,7 +56,12 @@ const PREVIEW_CHARS = 240;
export function peerPreview(body: string): string | null {
const text = body.trim();
if (text.length <= COMPACT_CHARS && text.split("\n").length <= COMPACT_LINES) return null;
- const flat = text.replace(/\s+/g, " ");
+ return flatPreview(text);
+}
+
+/** `body` on one line, cut to a preview. */
+export function flatPreview(body: string): string {
+ const flat = body.trim().replace(/\s+/g, " ");
return flat.length > PREVIEW_CHARS ? `${flat.slice(0, PREVIEW_CHARS).trimEnd()}…` : flat;
}
diff --git a/src/locales/de.json b/src/locales/de.json
index 349e816096..14679322f2 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -1026,6 +1026,7 @@
"chat.sentMidTurnHint": "Gesendet, während der Bot arbeitete — er hat es vor seinem nächsten Schritt gesehen, im selben Zug.",
"chat.showFull": "Ganze Nachricht zeigen",
"chat.showLess": "Weniger zeigen",
+ "chat.checkWork.earlierAnswer": "Vor Prüfung {round}",
"chat.generatedImage": "Erzeugtes Bild",
"chat.regenerate": "Antwort neu erzeugen",
"chat.previousVersion": "Vorherige Version",
diff --git a/src/locales/en.json b/src/locales/en.json
index 83749429f1..28077fb855 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -2726,6 +2726,7 @@
"chat.callSheet.keptSpoken": "Your requests, and what {name} said, did and answered. Nothing else you said on the call is kept.",
"chat.showFull": "Show full message",
"chat.showLess": "Show less",
+ "chat.checkWork.earlierAnswer": "Before check {round}",
"chat.automationNote.followUp": "Following up on the wait: {label}",
"chat.automationNote.followUpUnnamed": "Following up on a wait",
"chat.automationNote.show": "Show instructions",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 9211f00498..09605c29bc 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -2514,6 +2514,7 @@
"chat.callSheet.keptSpoken": "Seus pedidos e o que {name} disse, fez e respondeu. Nada mais do que você disse na chamada fica salvo.",
"chat.showFull": "Ver a mensagem inteira",
"chat.showLess": "Mostrar menos",
+ "chat.checkWork.earlierAnswer": "Antes da verificação {round}",
"chat.automationNote.followUp": "Continuação da espera: {label}",
"chat.automationNote.followUpUnnamed": "Continuação de uma espera",
"chat.automationNote.show": "Mostrar instruções",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index f12a426fe8..837cdcd55b 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -116,7 +116,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" | "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" | "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"> {
id: string;
role: "bot" | "user";
kind: "text" | "options" | "activity" | "screen" | "connector" | "secret" | "signin" | "routine.run" | "goal.run" | "burst" | "digest" | "compaction" | "call" | "widget" | "app";