Skip to content

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

Fetch long tool outputs on open so heavy conversations switch fast

AdityaUmale50815431589e
diff --git a/companion/src/routes.ts b/companion/src/routes.ts
index ebed3a2b85..54886462cb 100644
--- a/companion/src/routes.ts
+++ b/companion/src/routes.ts
@@ -162,6 +162,7 @@ const ALLOWED: ReadonlyArray<{ method: string; path: RegExp }> = [
{ method: "GET", path: /^\/api\/threads\/[\w-]+\/messages$/ },
{ method: "GET", path: /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/image$/ },
+ { method: "GET", path: /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/tool$/ },
// An app row's document is transcript data, scoped to its thread. `rpc` reaches only the app's own MCP
// server, under the bot's tool selection and approval rules; `context` is bounded text.
{ method: "GET", path: /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/app$/ },
diff --git a/companion/test/routes.test.ts b/companion/test/routes.test.ts
index cd36d40a05..7dc47770bb 100644
--- a/companion/test/routes.test.ts
+++ b/companion/test/routes.test.ts
@@ -88,6 +88,7 @@ describe("what the app may do", () => {
["DELETE", "/api/groups/room-1/tasks/th_1"],
["GET", "/api/threads/th_1/messages"],
["GET", "/api/threads/th_1/messages/msg_2/image"],
+ ["GET", "/api/threads/th_1/messages/msg_2/tool"],
["GET", "/api/threads/th_1/messages/msg_2/app"],
["POST", "/api/bots/bot_123/apps/msg_2/rpc"],
["POST", "/api/bots/bot_123/apps/msg_2/context"],
diff --git a/server/bot-visibility.e2e.test.ts b/server/bot-visibility.e2e.test.ts
index 72846605ee..d03e35fa27 100644
--- a/server/bot-visibility.e2e.test.ts
+++ b/server/bot-visibility.e2e.test.ts
@@ -233,6 +233,7 @@ posixOnly("per-bot visibility on a shared workspace", () => {
["GET", `/api/threads/${ids.hrThread}/messages`],
["GET", `/api/threads/${ids.hrThread}/messages?around=${hrMessage}`],
["GET", `/api/threads/${ids.hrThread}/messages/${hrMessage}/image`],
+ ["GET", `/api/threads/${ids.hrThread}/messages/${hrMessage}/tool`],
["GET", `/api/threads/${ids.hrThread}/export`],
["GET", `/api/threads/${ids.hrThread}/export?format=json`],
["POST", `/api/threads/${ids.hrThread}/respond`, { requestId: "x", behavior: "deny" }],
diff --git a/server/host/message-pages.test.ts b/server/host/message-pages.test.ts
new file mode 100644
index 0000000000..f23cdc49bb
--- /dev/null
+++ b/server/host/message-pages.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vitest";
+
+import type { Message } from "../store.ts";
+import { pageMessage, TOOL_OUTPUT_PREVIEW } from "./message-pages.ts";
+
+const step = (output: string | undefined, extra: Partial<Message> = {}): Message => ({
+ id: "m1", role: "bot", kind: "activity", at: 1, text: "", turnId: "t1",
+ tool: { name: "Read", ok: true, summary: "read notes.md", input: JSON.stringify({ path: "notes.md", text: "x".repeat(5_000) }), output },
+ ...extra,
+} as Message);
+
+describe("pageMessage", () => {
+ it("leaves a step whose output fits the preview exactly as stored", () => {
+ for (const output of [undefined, "", "short", "y".repeat(TOOL_OUTPUT_PREVIEW)]) {
+ const message = step(output);
+ expect(pageMessage(message)).toBe(message);
+ }
+ });
+
+ it("cuts a long output to its start, marks it clipped and keeps everything else", () => {
+ const message = step("z".repeat(6_000));
+ const paged = pageMessage(message) as Message;
+ expect(paged.tool).toEqual({ ...message.tool, output: "z".repeat(TOOL_OUTPUT_PREVIEW), clipped: true });
+ expect(paged.tool!.input).toBe(message.tool!.input);
+ expect({ ...paged, tool: undefined }).toEqual({ ...message, tool: undefined });
+ expect(message.tool!.output).toHaveLength(6_000);
+ expect(message.tool).not.toHaveProperty("clipped");
+ });
+
+ it("never splits a surrogate pair at the cut", () => {
+ const output = `${"a".repeat(TOOL_OUTPUT_PREVIEW - 1)}😀${"b".repeat(50)}`;
+ const paged = pageMessage(step(output)) as Message;
+ expect(paged.tool!.output).toBe("a".repeat(TOOL_OUTPUT_PREVIEW - 1));
+ expect(paged.tool).toHaveProperty("clipped", true);
+ });
+
+ it("keeps whole the rows whose output is the reply itself", () => {
+ const long = "r".repeat(6_000);
+ const rows: Array<Partial<Message>> = [
+ { relay: { kind: "told", email: "[email protected]", name: "Bob" } },
+ { roomRequest: { id: "q1", phase: "result" } },
+ { comm: { groupId: "g1", withBotId: "b2", withName: "Ada", withColor: "blue" } },
+ { threadRef: { botId: "b1", threadId: "th2", title: "Side job" } },
+ { kind: "text" },
+ ];
+ for (const extra of rows) {
+ const message = step(long, extra);
+ expect(pageMessage(message)).toBe(message);
+ }
+ });
+
+ it("still drops a screen's picture", () => {
+ const screen = { id: "s1", role: "bot", kind: "screen", at: 1, text: "", png: "iVBOR" } as Message;
+ expect(pageMessage(screen)).toEqual({ id: "s1", role: "bot", kind: "screen", at: 1, text: "", hasImage: true });
+ });
+});
diff --git a/server/host/message-pages.ts b/server/host/message-pages.ts
index 809c8fc7ef..dbfecce86b 100644
--- a/server/host/message-pages.ts
+++ b/server/host/message-pages.ts
@@ -1,6 +1,10 @@
import type { Message } from "../store.ts";
+import { toolResultPrefix } from "../tool-results.ts";
const MESSAGE_PAGE_MAX = 200;
+/** How much of a tool step's output a conversation page carries: the rest is fetched when the step is opened, so
+ * switching to a conversation full of tool steps stays light. */
+export const TOOL_OUTPUT_PREVIEW = 1_000;
/** undefined = absent, null = present but unusable (the caller answers 400). */
export function pageSize(raw: string | null): number | null | undefined {
@@ -15,3 +19,15 @@ export function slimMessage(message: Message): Message | Record<string, unknown>
const { png: _png, ...rest } = message;
return { ...rest, hasImage: true };
}
+
+/** A message as a conversation page carries it: slimmed, and a plain tool step's long output cut to a preview marked
+ * `clipped`. Input stays whole (labels parse it), and so do rows whose tool output is the reply itself (a teammate's
+ * result, a relayed message, a handoff). */
+export function pageMessage(message: Message): Message | Record<string, unknown> {
+ const slim = slimMessage(message);
+ const tool = message.tool;
+ if (!tool || message.kind !== "activity" || message.relay || message.roomRequest || message.comm || message.threadRef) return slim;
+ const output = tool.output;
+ if (output === undefined || output.length <= TOOL_OUTPUT_PREVIEW) return slim;
+ return { ...slim, tool: { ...tool, output: toolResultPrefix(output, TOOL_OUTPUT_PREVIEW), clipped: true } };
+}
diff --git a/server/index.ts b/server/index.ts
index 6a9f2fae23..3a08d2a5d3 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -300,7 +300,7 @@ import { createDelegatedLevel } from "./host/delegated-level.ts";
import { createLiveApprovalMode } from "./host/live-approval.ts";
import { CONSENT_RULE, escapeNotes, OUTSIDE, peerLineText, peerProvenanceNote, reportNote, requestWorkOrigin, type WorkOrigin } from "./peer-provenance.ts";
import { decideRoomPost, emptyRoomPostBudget, type RoomPostAttempt, type RoomPostBudget } from "./room-post-budget.ts";
-import { pageSize, slimMessage } from "./host/message-pages.ts";
+import { pageMessage, pageSize, slimMessage } from "./host/message-pages.ts";
import { ReplayBuffer } from "./host/sse-replay.ts";
import {
mentionedBots,
@@ -4620,14 +4620,14 @@ function messagePage(threadId: string, limit: number | undefined, before?: strin
}
if (!before) {
const tail = store.messagesTail(threadId, limit);
- return { messages: tail.messages.map(slimMessage), hasMore: tail.hasMore, activeLeafId: tail.activeLeafId };
+ return { messages: tail.messages.map(pageMessage), hasMore: tail.hasMore, activeLeafId: tail.activeLeafId };
}
const all = store.messagesFor(threadId);
const end = all.findIndex((msg) => msg.id === before);
const stop = end === -1 ? all.length : end;
const start = Math.max(0, stop - limit);
return {
- messages: all.slice(start, stop).map(slimMessage),
+ messages: all.slice(start, stop).map(pageMessage),
hasMore: start > 0,
activeLeafId: store.activeLeaf(threadId),
};
@@ -4689,7 +4689,7 @@ function messageWindow(threadId: string, messageId: string, limit: number) {
const before = Math.floor((limit - 1) / 2);
const start = Math.max(0, Math.min(index - before, all.length - limit));
const stop = Math.min(all.length, start + limit);
- return { messages: all.slice(start, stop).map(slimMessage), hasMore: start > 0 };
+ return { messages: all.slice(start, stop).map(pageMessage), hasMore: start > 0 };
}
interface SseClient {
diff --git a/server/message-db.ts b/server/message-db.ts
index 3bbac7a2d7..4055b958c1 100644
--- a/server/message-db.ts
+++ b/server/message-db.ts
@@ -398,6 +398,11 @@ export function readThread(threadId: string, legacyFile: string): ThreadRows {
return importLegacy(threadId, legacyFile);
}
+export function readMessage(threadId: string, messageId: string): Message | null {
+ const row = db().prepare("SELECT json FROM messages WHERE thread_id = ? AND id = ?").get(threadId, messageId);
+ return row ? rowToMessage(row as { json: string }) : null;
+}
+
export interface ThreadTailRows extends ThreadRows {
hasMore?: boolean;
}
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 05626c7b05..73e5dbb244 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -309,6 +309,7 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg
{ methods: ["GET"], path: /^\/api\/search$/ },
{ methods: ["GET"], path: /^\/api\/threads\/[\w-]+\/messages$/ },
{ methods: ["GET"], path: /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/image$/ },
+ { methods: ["GET"], path: /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/tool$/ },
// an app row's document is transcript data, read under the transcript's rules
{ methods: ["GET"], path: /^\/api\/threads\/[\w-]+\/messages\/[\w-]+\/app$/ },
{ methods: ["GET"], path: /^\/api\/threads\/[\w-]+\/export$/ },
diff --git a/server/routes/threads-tool-output.test.ts b/server/routes/threads-tool-output.test.ts
new file mode 100644
index 0000000000..16a4fb9ced
--- /dev/null
+++ b/server/routes/threads-tool-output.test.ts
@@ -0,0 +1,54 @@
+import { rmSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { DATA_DIR } from "../config.ts";
+import type { ModelSelection } from "../contracts.ts";
+import { json, readBody } from "../harness/http.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { Store } from "../store.ts";
+import { dispatchRoutes } from "./table.ts";
+import { createThreadRoutes, type ThreadRouteDeps } from "./threads.ts";
+
+const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };
+const servers: Server[] = [];
+
+beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
+afterEach(async () => {
+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
+});
+
+async function serve(store: Store): Promise<string> {
+ const deps = { store, viewerFor: () => ({}), visibleTo: () => ({ bot: () => true, group: () => true }), workspaceAccess: () => null,
+ desktopMutationToken: () => undefined, companionMutationToken: () => undefined, cliOwnerToken: () => undefined } as unknown as ThreadRouteDeps;
+ const routes = [createThreadRoutes(deps)];
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ const auth = { kind: "loopback", scopes: ["admin"] } as RequestAuth;
+ const handled = await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody });
+ if (!handled) json(res, 404, { from: "inline routes" });
+ });
+ servers.push(server);
+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+}
+
+describe("GET /api/threads/:threadId/messages/:messageId/tool", () => {
+ it("returns a tool step's whole output, and 404s anything else", async () => {
+ const store = new Store(() => sonnet);
+ const bot = store.createBot({ name: "Scout" }, { seedMessages: false });
+ const output = "line of output\n".repeat(500);
+ const tool = store.appendMessage(bot.threadId, { role: "bot", kind: "activity", tool: { name: "Bash", ok: true, input: "{}", output } });
+ const silent = store.appendMessage(bot.threadId, { role: "bot", kind: "activity", tool: { name: "Bash", ok: true } });
+ const text = store.appendMessage(bot.threadId, { role: "user", kind: "text", text: "hi" });
+ const base = await serve(store);
+ const get = async (path: string) => { const res = await fetch(`${base}${path}`); return { status: res.status, body: await res.json() }; };
+
+ expect(await get(`/api/threads/${bot.threadId}/messages/${tool.id}/tool`)).toEqual({ status: 200, body: { output } });
+ expect((await get(`/api/threads/${bot.threadId}/messages/${silent.id}/tool`)).status).toBe(404);
+ expect((await get(`/api/threads/${bot.threadId}/messages/${text.id}/tool`)).status).toBe(404);
+ expect((await get(`/api/threads/${bot.threadId}/messages/no-such-message/tool`)).status).toBe(404);
+ expect((await get(`/api/threads/no-such-thread/messages/${tool.id}/tool`)).status).toBe(404);
+ });
+});
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index 7b45b2f245..78a108ff4f 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -12,7 +12,7 @@ import { speakerOf, type PersonName } from "../replies.ts";
import type { Coordinator } from "../coordinator.ts";
import type { WorkspaceAccess } from "../enterprise.ts";
import type { GroupUsageReader } from "../group-thread-usage.ts";
-import { searchMessagesAsync } from "../message-db.ts";
+import { readMessage, searchMessagesAsync } from "../message-db.ts";
import {
listMessageFolder, messageAttachmentName, messageFileDisposition, messageFileDownloadName, messageFolderEntryName,
messageImageTargetAt, messageReferencesFile, openMessageFile, openMessageFolderEntry, referencedFileName,
@@ -154,6 +154,14 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
return res.end(bytes);
}
+ m = path.match(/^\/api\/threads\/([\w-]+)\/messages\/([\w-]+)\/tool$/);
+ if (m && method === "GET") {
+ if (!store.botByThread(m[1]) && !store.groupByThread(m[1])) return json(res, 404, { error: "no such conversation" });
+ const message = readMessage(m[1], m[2]);
+ if (message?.tool?.output === undefined) return json(res, 404, { error: "no tool output on that message" });
+ return json(res, 200, { output: message.tool.output });
+ }
+
// Only a file this exact stored message grants; deliberately not a general path reader.
m = path.match(/^\/api\/threads\/([\w-]+)\/messages\/([\w-]+)\/file$/);
const streamsMessageImage = Boolean(
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 93d685792b..5f45b4eb1e 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -634,7 +634,7 @@ function PeerLabel({ peer }: { peer: PeerLine }) {
}
const ActivityChip = memo(function ActivityChip({ message, place = "auto" }: { message: Message; place?: EffectivePlace }) {
- const { bots, dispatch, liveTools } = useChatRows();
+ const { bots, dispatch, liveTools, threadId } = useChatRows();
const tool = message.tool;
if (!tool) return null;
if (message.threadRef) return <ThreadChip message={message} />; if (message.relay) return <TeammateChip message={message} />;
@@ -643,7 +643,7 @@ const ActivityChip = memo(function ActivityChip({ message, place = "auto" }: { m
return <HandoffChip message={message} bots={bots} title={t("chat.openConversationWith", { name: comm.withName })}
onClick={() => dispatch({ type: "select", id: comm.groupId })} />;
}
- return <ToolActivity tool={tool} live={liveTools.has(message.id)} place={toolPlace(tool.name, place)} />;
+ return <ToolActivity tool={tool} live={liveTools.has(message.id)} place={toolPlace(tool.name, place)} source={{ threadId, messageId: message.id }} />;
});
const MessagesList = memo(function MessagesList({
diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsx
index 6d962125da..fa55bd41a3 100644
--- a/src/components/GroupView.tsx
+++ b/src/components/GroupView.tsx
@@ -100,7 +100,7 @@ import { RoomHeader } from "./RoomHeader";
import { useChatFindRequests } from "@/lib/chat-find";
import { simpleRoomHeader } from "@/lib/room-panel";
-export function RoomToolChip({ message, roomId, live = false }: { message: Message; roomId?: string; live?: boolean }) {
+export function RoomToolChip({ message, roomId, threadId, live = false }: { message: Message; roomId?: string; threadId?: string; live?: boolean }) {
const { state, dispatch } = useStore();
const tool = message.tool;
if (!tool) return null;
@@ -118,7 +118,7 @@ export function RoomToolChip({ message, roomId, live = false }: { message: Messa
}
}} />;
}
- if (!comm) return <ToolActivity tool={tool} live={live} />;
+ if (!comm) return <ToolActivity tool={tool} live={live} source={threadId ? { threadId, messageId: message.id } : undefined} />;
return (
<div className="flex justify-start">
<div
@@ -401,7 +401,7 @@ export const Transcript = memo(function Transcript({
<ActivityRun messages={item.messages} forceOpen={item.messages.some((step) => step.id === focusedId)}>
{item.messages.map((step) => (
<div key={step.id} className="contents" data-mid={step.id}>
- <RoomToolChip message={step} live={liveTools.has(step.id)} />
+ <RoomToolChip message={step} threadId={group.threadId} live={liveTools.has(step.id)} />
</div>
))}
</ActivityRun>
@@ -459,7 +459,7 @@ export const Transcript = memo(function Transcript({
</div>
) : m.kind === "activity" && m.tool ? (
roomActivityVisible(m, showToolCalls) ? (
- m.dataResult ? <DataResultChip message={m} /> : isStatusActivity(m) ? <StatusActivityRow message={m} /> : <RoomToolChip message={m} roomId={group.id} live={liveTools.has(m.id)} />
+ m.dataResult ? <DataResultChip message={m} /> : isStatusActivity(m) ? <StatusActivityRow message={m} /> : <RoomToolChip message={m} roomId={group.id} threadId={group.threadId} live={liveTools.has(m.id)} />
) : null
) : m.kind === "screen" ? (
<ScreenFrame threadId={group.threadId} message={m} />
diff --git a/src/components/ToolActivity.full.test.ts b/src/components/ToolActivity.full.test.ts
new file mode 100644
index 0000000000..151420d1bf
--- /dev/null
+++ b/src/components/ToolActivity.full.test.ts
@@ -0,0 +1,71 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const api = vi.fn();
+vi.mock("@/state/api", () => ({ api: (...args: unknown[]) => api(...args) }));
+vi.mock("@/lib/interface-mode", () => ({ useAdvancedMode: () => true }));
+const { ToolActivity } = await import("./ToolActivity");
+
+const source = { threadId: "th1", messageId: "m1" };
+const preview = "a".repeat(1_000);
+const whole = `${preview}${"b".repeat(5_000)}`;
+let root: Root; let host: HTMLDivElement;
+
+beforeEach(() => { api.mockReset(); host = document.createElement("div"); document.body.append(host); root = createRoot(host); });
+afterEach(() => { act(() => root.unmount()); host.remove(); });
+
+const render = (tool: Record<string, unknown>) => act(() => root.render(createElement(ToolActivity, { tool: { name: "Bash", ok: true, ...tool }, source })));
+const toggle = async (open: boolean) => {
+ const details = host.querySelector("details")!;
+ await act(async () => { details.open = open; details.dispatchEvent(new Event("toggle")); });
+};
+const shown = () => [...host.querySelectorAll("pre")].at(-1)?.textContent;
+
+describe("ToolActivity: a clipped step", () => {
+ it("loads its whole output once, when first opened", async () => {
+ api.mockResolvedValue({ output: whole });
+ render({ output: preview, clipped: true });
+ expect(api).not.toHaveBeenCalled();
+ await toggle(true);
+ expect(api).toHaveBeenCalledTimes(1);
+ expect(api.mock.calls[0]![0]).toBe("/api/threads/th1/messages/m1/tool");
+ expect(shown()).toBe(whole);
+ expect(host.textContent).not.toContain("Loading the full result");
+ await toggle(false);
+ await toggle(true);
+ expect(api).toHaveBeenCalledTimes(1);
+ expect(shown()).toBe(whole);
+ });
+
+ it("shows the start with a note while loading, and if loading fails", async () => {
+ let fail!: (error: Error) => void;
+ api.mockReturnValue(new Promise((_, reject) => { fail = reject; }));
+ render({ output: preview, clipped: true });
+ await toggle(true);
+ expect(shown()).toBe(preview);
+ expect(host.textContent).toContain("Loading the full result");
+ await act(async () => fail(new Error("offline")));
+ expect(shown()).toBe(preview);
+ expect(host.textContent).toContain("Showing the start of the result only");
+ });
+
+ it("asks again after being closed mid-load", async () => {
+ api.mockReturnValueOnce(new Promise(() => {})).mockResolvedValueOnce({ output: whole });
+ render({ output: preview, clipped: true });
+ await toggle(true);
+ await toggle(false);
+ await toggle(true);
+ expect(api).toHaveBeenCalledTimes(2);
+ expect(shown()).toBe(whole);
+ });
+
+ it("never fetches a step that came whole", async () => {
+ render({ output: "all of it" });
+ await toggle(true);
+ expect(api).not.toHaveBeenCalled();
+ expect(shown()).toBe("all of it");
+ });
+});
diff --git a/src/components/ToolActivity.tsx b/src/components/ToolActivity.tsx
index af1f46a72d..5bdb34544c 100644
--- a/src/components/ToolActivity.tsx
+++ b/src/components/ToolActivity.tsx
@@ -1,5 +1,6 @@
import { Check, ChevronRight, Circle, X } from "lucide-react";
-import { useState } from "react";
+import { useEffect, useState } from "react";
+import { api } from "@/state/api";
import type { Message } from "@/state/store";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
@@ -7,11 +8,15 @@ import { placeLabelKey, type Place } from "@/lib/place";
import { nameIsCommand } from "@/lib/verify-steps";
import { useAdvancedMode } from "@/lib/interface-mode";
import { toolStepLabel } from "@/lib/tool-step-label";
+import type { MessageAttachmentContext } from "./AttachmentPreview";
import { PlaceIcon } from "./PlaceIcon";
import { WorkingDots } from "./WorkingIndicator";
-export function ToolActivity({ tool, place = null, live = false }: { tool: NonNullable<Message["tool"]>; place?: Place | null; live?: boolean }) {
+/** Which stored message a step is: a clipped step (its output cut short in conversation pages) loads the rest from it. */
+export function ToolActivity({ tool, place = null, live = false, source }: { tool: NonNullable<Message["tool"]>; place?: Place | null; live?: boolean; source?: MessageAttachmentContext }) {
const [expanded, setExpanded] = useState(false);
+ const full = useFullOutput(expanded && tool.clipped ? source : undefined, tool.output);
+ const output = full.output ?? tool.output;
const failed = tool.ok === false;
const advanced = useAdvancedMode();
const label = advanced ? tool.name : toolStepLabel(tool);
@@ -42,10 +47,31 @@ export function ToolActivity({ tool, place = null, live = false }: { tool: NonNu
</div>
<div>
<div className="mb-1 text-[11px] font-medium">{t("toolDetail.output")}</div>
- {tool.output ? <pre dir="ltr" className="max-h-64 overflow-auto rounded-lg bg-inset p-2.5 font-mono text-xs whitespace-pre-wrap break-words text-ink">{tool.output}</pre> : <p className="text-xs">{tool.ok === undefined ? (live ? t("toolDetail.waiting") : t("toolDetail.unverified")) : t("toolDetail.noOutput")}</p>}
+ {output ? <pre dir="ltr" className="max-h-64 overflow-auto rounded-lg bg-inset p-2.5 font-mono text-xs whitespace-pre-wrap break-words text-ink">{output}</pre> : <p className="text-xs">{tool.ok === undefined ? (live ? t("toolDetail.waiting") : t("toolDetail.unverified")) : t("toolDetail.noOutput")}</p>}
</div>
+ {(full.state === "loading" || full.state === "failed") && <p className="text-[11px] text-ink-secondary" role="status">{t(full.state === "loading" ? "toolDetail.loadingFull" : "toolDetail.partial")}</p>}
<p className="text-[11px] text-ink-secondary">{t("toolDetail.previewHint")}</p>
</div>
</details>
);
}
+
+type FullOutput = { state: "idle" | "loading" | "done" | "failed"; output?: string };
+
+/** The whole output of a clipped step, fetched when it is opened: kept once it arrives, asked again after a failure. */
+function useFullOutput(source: MessageAttachmentContext | undefined, preview: string | undefined): FullOutput {
+ const url = source && `/api/threads/${encodeURIComponent(source.threadId)}/messages/${encodeURIComponent(source.messageId)}/tool`;
+ const key = url && `${url}#${preview?.length ?? 0}`;
+ const [full, setFull] = useState<FullOutput & { key?: string }>({ state: "idle" });
+ const have = full.key === key && full.state === "done";
+ useEffect(() => {
+ if (!url || have) return;
+ let current = true;
+ setFull({ state: "loading", key });
+ api<{ output: string }>(url)
+ .then((body) => { if (current) setFull({ state: "done", key, output: body.output }); })
+ .catch(() => { if (current) setFull({ state: "failed", key }); });
+ return () => { current = false; };
+ }, [url, key, have]);
+ return full.key === key ? full : { state: "idle" };
+}
diff --git a/src/locales/en.json b/src/locales/en.json
index 4c4330aa86..923fc7cf8c 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -673,6 +673,8 @@
"toolDetail.unverified": "No result",
"toolDetail.waiting": "Waiting for the tool to finish…",
"toolDetail.noOutput": "No output was recorded for this call.",
+ "toolDetail.loadingFull": "Loading the full result…",
+ "toolDetail.partial": "Showing the start of the result only: the rest could not be loaded.",
"toolDetail.previewHint": "Shortened, automatically redacted preview. Review before sharing.",
"toolDetail.tool": "Tool",
"toolStep.runCommand": "Run a command",
diff --git a/src/state/store.tsx b/src/state/store.tsx
index f253b8c82a..a73ac97ecb 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -141,7 +141,7 @@ export interface Message extends Pick<import("../../shared/wire").WireMessage, "
goalRun?: GroupGoalRunCardData;
call?: import("../../shared/wire").LiveCallRecord;
channelMode?: "chat" | "goal";
- tool?: { name: string; ok?: boolean; spoken?: string; setup?: boolean; claudeUpdate?: boolean; place?: PlaceRow; limitResetsAt?: number; summary?: string; input?: string; output?: string ; itemId?: string; outputPath?: string; fullResult?: boolean; rescue?: import("../../shared/first-reply-rescue").FirstReplyRescue; step?: import("../../shared/turn-progress").LiveStep; whose?: { person: string; app: string } };
+ tool?: { name: string; ok?: boolean; spoken?: string; setup?: boolean; claudeUpdate?: boolean; place?: PlaceRow; limitResetsAt?: number; summary?: string; input?: string; output?: string ; itemId?: string; outputPath?: string; fullResult?: boolean; clipped?: boolean; rescue?: import("../../shared/first-reply-rescue").FirstReplyRescue; step?: import("../../shared/turn-progress").LiveStep; whose?: { person: string; app: string } };
steered?: boolean;
via?: "api" | "call";
callId?: string;