Compare commits

...
4 Commits
Author SHA1 Message Date
tben 6a808d8417 Bump version to 0.18.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-12 18:42:33 +01:00
tben 585b77eec1 Copy a message's whole details from its Details modal
The Details modal under a bot message now has a Copy report button: it
puts that message's whole details on the clipboard as one markdown
document, every call and failure it took included rather than only the
first the modal lists. The modal and the report share their at-a-glance
facts and the failure-source wording, and the route takes full=1 to list
up to AppData.MessageDetailsCopyMaxCalls calls.
2026-11-12 18:42:27 +01:00
tben 74693cccd3 Bump version to 0.18.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-11 04:39:23 +01:00
tben 115113247f Give the coordinator its skill, server and tool tools in a workspace too
- grabCoordinatorExtensionTools was pushed only in the coordinator's own
  chat: both workspace branches returned before it, so a runbook asked for
  inside a workspace had no propose_skill to write it with, and the bot
  saved a file and called the skill created
- Pushed before the workspace split, so it comes wherever the coordinator
  works; the tools still return nothing unless the run's user is the super
  admin, and each re-checks on call (assertSuperAdminRun)
- grab-bot-chat-tools.test.ts pins all three cases: a workspace, a
  workspace with no worker (the empty-crew return) and its own chat
- AGENTS.md records it
2026-11-11 04:39:20 +01:00
19 changed files with 759 additions and 46 deletions
+2 -2
View File
@@ -98,7 +98,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
- **Task chips:** which tracker tasks a bot message is about is the app's record, not the bot's word: a run's task tools report each task they touch (`onTask`: `list_tasks` with `task_id`, `create_task`, `update_task`, `delegate_task`'s hand-over), plus a handed-over job's `tracker_task_id`, into `bot_messages.task_ids` (also on its failure notice and its report relayed to the requester). The thread shows them under the message (`MessageTaskChips`) with title and status, read per viewer and only for tasks they reach (`grabMessagesTasks`; pushes carry them through `withMessageTasks`).
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (its header shows the size and the file's full path on the data volume, `full_path`, e.g. `bots/3/reports/q3.md`, absolute when outside it; every opener passes it; markdown rendered with the message elements, CSV/TSV as a table via `parseCsv`, images in `ImageViewer` (zoom buttons and keys, Ctrl/Cmd+wheel or pinch at the pointer, Fit, Fit width (a full-page screenshot opens that way and scrolls down), Actual size, double click, drag to pan; sized by the `width` attribute and centred with auto margins, never flex centring, which cuts off a tall picture's top), PDF/audio/video in place, HTML in a frame with `sandbox=""` (plus the media server's `sandbox` CSP), other text as code, the kind from `filePreviewKind`; Download and Open in a new tab), a modified click still opens a tab. Text is read up to `AppData.FilePreviewMaxTextBytes`. Never render a file's HTML on the app's origin or with scripts. Opened from a list (a folder, the files modal, a message's images), an image gets that list's images as its `gallery` (`imagePreviewGallery`): Previous/Next and the arrow keys step through them in the same modal, neighbours preloaded. Escape closes only the top modal of a stack (`useTopModalEscape`; twui closes every open one). The message elements and the preview import each other (through the file chips), so the preview merges `MessageMarkdownComponents` when it renders, never at module load.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch.
- **Copy chat** (header menu): the active session (the one on screen) as one markdown document (`api/admin/bots/conversation-export` -> `conversationMarkdown`, refs as names, message headings demoted). The clipboard write starts on the click with a pending `ClipboardItem` (`copyPendingText`), since Safari drops the gesture after a fetch. A message's Details modal has its own **Copy report** (`messageDetailsMarkdown`, the same pending write): that message's whole details, listing up to `AppData.MessageDetailsCopyMaxCalls` calls and failures (the route's `full=1`) instead of the modal's first `MessageDetailsMaxCalls`.
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
@@ -218,7 +218,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
- **Per-bot models:** workspace row > bot row > default; the coordinator always uses the defaults. Every entry point takes `bot_id` and passes it on. **Embeddings are install-wide** (`install_wide` in `Harnesses`, `isInstallWideHarness`): `grabHarnessSetting` ignores bot/workspace rows for them, the per-bot/workspace forms don't list them and saving one is refused, so every stored vector comes from one model. Shared form `settings/models/(partials)/harness-settings-form.tsx`.
- **Tools:** `HarnessTool` built per run; own tools validate with zod. `run-tool-call.ts` reports errors back to the model and caps each call (`AppData.HarnessToolTimeoutMs`); a `computer_*`/`browser_*` call from a run without them (a reply) is told to use `start_task` (`unknownToolMessage`). Bot tools in `src/harness/tools/bot/` (memory, instructions, tasks, schedules, `start_task`, coordinator's crew management, `delegate_task` and `hand_over_schedule`, with results relayed back by `relayJobToRequester`).
- **Extensions:** MCP servers (`mcp_servers`, remote or stdio), custom tools (`custom_tools`: http, script, prompt) and skills (`skills`, runbooks loaded with `load_skill`). Given per bot / per workspace (`botExtensionsSql`); `all_bots` only decides what new bots get. Templates `{{args.x}}`/`{{env.KEY}}` via `fillTemplate`; secrets redacted from results. stdio servers run in a per-process pool. Skill body limits are app settings (`grabSkillBodyMaxChars`, `grabSkillBodyShownChars`). A skill proposal says what it changes (`skillProposalChanges`) to the bot and in the confirm outcome, takes no unknown keys (a misnamed `body` would re-propose the saved runbook) and is refused when it changes nothing.
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access). New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
- **Bots never add or repoint extensions or set envs.** The coordinator may only change what can't alter where data is sent (name, description, on/off, access); its extension tools (`grabCoordinatorExtensionTools`) come wherever it works, a workspace as much as its own chat. New skills, servers, tools, or changes to a URL, headers, kind, config or a skill's runbook go through `propose_*` -> `extension_proposals` -> `[proposal:ID]` card, which the app describes from the config itself (never from what the bot says) and the super admin confirms (`checkProposalData` re-checks). Stdio servers are never proposed by bots (they run in the app container, which holds the docker socket).
- **Check before and after acting** (`ActionCheckNote`): look for an existing record before creating one, verify every action took effect. Tools enforce it (read-back on memory saves, duplicate checks on bots, schedules, tasks, workspaces).
### Token usage
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.18.2",
"version": "0.18.4",
"module": "index.ts",
"type": "module",
"private": true,
+7
View File
@@ -675,6 +675,13 @@ export const AppData = {
* long task can take hundreds; the totals still count every one.
*/
MessageDetailsMaxCalls: 200,
/**
* The most model calls and failed calls a message's details report
* lists one by one when it's copied (the Details modal's icon): a
* whole report for a bug report, not only the first calls the modal
* shows. The totals count every call either way.
*/
MessageDetailsCopyMaxCalls: 2000,
/**
* The most characters of a provider's error kept on a failed model
* call (`harness_call_failures.error`), shown in the message's details.
@@ -11,6 +11,12 @@ type Params = {
*/
message_id: number;
created_at?: number | null;
/**
* The most calls and failures listed one by one; the totals count
* every one either way. The modal shows `AppData.MessageDetailsMaxCalls`
* of them, its copied report far more.
*/
max_calls?: number;
};
type CallRow = {
@@ -64,7 +70,11 @@ type JobRow = {
* model's display name come from their live rows, so a deleted provider
* or an unlisted model still reads by the name it was called with.
*/
export default async function grabMessageDetails({ message_id, created_at }: Params): Promise<MessageDetails> {
export default async function grabMessageDetails({
message_id,
created_at,
max_calls = AppData.MessageDetailsMaxCalls,
}: Params): Promise<MessageDetails> {
const rows =
(
await BunSQLite.sql<CallRow>({
@@ -145,8 +155,8 @@ export default async function grabMessageDetails({ message_id, created_at }: Par
created_at: created_at || null,
totals,
models: groupMessageCalls({ calls }),
calls: calls.slice(0, AppData.MessageDetailsMaxCalls),
failures: failures.slice(0, AppData.MessageDetailsMaxCalls),
calls: calls.slice(0, max_calls),
failures: failures.slice(0, max_calls),
failed_calls: failures.length,
job: job_id ? await grabJob({ job_id: Number(job_id) }) : null,
};
@@ -0,0 +1,96 @@
import { afterAll, describe, expect, mock, test } from "bun:test";
import type { HarnessTool } from "../../types";
import type { BUN_SQLITE_COBBLE_BOTS } from "@/db/types/db";
/**
* The coordinator keeps the install's skills, MCP servers and tools
* wherever it works. Its workspace conversation is where a runbook for
* that workspace's crew gets written, so the branch that returns early for
* a workspace must still carry `grabCoordinatorExtensionTools`: a
* coordinator asked to make a skill there once had no tool to make one
* with, and wrote a file into its folder instead.
*
* Everything the tool list would read from the database is mocked, so this
* suite checks the list's structure alone: which branch pushed what.
*/
const marker = ({ name }: { name: string }): HarnessTool => ({
name,
description: `${name} marker`,
run: async () => "ok",
});
/**
* What `grabCrewWorkers` answers, per test: a workspace with no worker is
* the branch that returned before the extension tools were pushed.
*/
let workers: BUN_SQLITE_COBBLE_BOTS[] = [{ id: 5, name: "A worker", kind: "worker" }];
mock.module("./extensions/grab-coordinator-extension-tools", () => ({
default: async () => [marker({ name: "list_extensions" }), marker({ name: "propose_skill" })],
}));
mock.module("./grab-bot-tools", () => ({
default: async () => [marker({ name: "update_memory" })],
}));
mock.module("@/src/functions/backend/db/workspaces/grab-user-workspaces", () => ({
default: async () => [{ id: 11, name: "A workspace", archived: 0 }],
}));
mock.module("@/src/functions/backend/db/bots/grab-crew-workers", () => ({
default: async () => workers,
}));
const grabBotChatTools = (await import("./grab-bot-chat-tools")).default;
afterAll(() => {
mock.restore();
});
async function names({ workspace_id }: { workspace_id: number | null }) {
const coordinator = {
bot_types: [],
is_coordinator: true,
admin_workspace_ids: [],
is_workspace_admin: false,
can: () => true,
};
const tools = await grabBotChatTools({
bot: { id: 1, kind: "coordinator", name: "Coordinator" },
powers: coordinator,
user_id: 1,
computers: [],
session_id: 9,
workspace_id,
onPropose: () => {},
});
return tools.map((tool) => tool.name);
}
describe("grabBotChatTools", () => {
test("the coordinator in a workspace reaches the install's skills, servers and tools", async () => {
workers = [{ id: 5, name: "A worker", kind: "worker" }];
const list = await names({ workspace_id: 11 });
expect(list).toContain("list_extensions");
expect(list).toContain("propose_skill");
});
test("a workspace with no worker still gets them, before the empty-crew return", async () => {
workers = [];
const list = await names({ workspace_id: 11 });
expect(list).toContain("list_extensions");
expect(list).toContain("propose_skill");
});
test("its own chat carries them too", async () => {
workers = [{ id: 5, name: "A worker", kind: "worker" }];
const list = await names({ workspace_id: null });
expect(list).toContain("list_extensions");
expect(list).toContain("propose_skill");
});
});
+15 -10
View File
@@ -105,10 +105,12 @@ type Params = {
* update_bot, delete_bot and delete_workspace (which workspace, which
* computers, and which name, role and core instructions each crew member
* gets, and what goes) and the install's skills, MCP servers and custom
* tools (`grabCoordinatorExtensionTools`) or, in a workspace,
* set_bot_workspace_instructions and update_bot for the workspace's crew
* (a bot's core prompt is asked for from wherever the user is), plus
* set_bot_type to make a worker a workspace's admin. A workspace admin, in the workspace it leads, gets
* tools (`grabCoordinatorExtensionTools`, in a workspace as much as in its
* own chat: a runbook for the crew there is written from either) or, in a
* workspace, set_bot_workspace_instructions and update_bot for the
* workspace's crew (a bot's core prompt is asked for from wherever the
* user is), plus set_bot_type to make a worker a workspace's admin. A
* workspace admin, in the workspace it leads, gets
* `grabWorkspaceAdminTools`. Every gate reads the bot's types (`powers`),
* never `bots.kind`. Anything else on a computer goes through a task,
* never mid-reply.
@@ -177,6 +179,14 @@ export default async function grabBotChatTools({
return tools;
}
/**
* The install's skills, MCP servers and tools are the coordinator's
* wherever it works, a workspace as much as its own chat: a skill the
* crew there needs is written from either, and every tool checks the
* super admin again when it runs.
*/
tools.push(...(await grabCoordinatorExtensionTools({ user_id, bot_id, session_id, workspace_id, onPropose })));
const workspaces = (await grabUserWorkspaces({ user_id })).filter((w) => !w.archived);
/**
@@ -227,12 +237,7 @@ export default async function grabBotChatTools({
return tools;
}
tools.push(
findBotTool(),
findWorkspaceTool({ user_id }),
listWorkspaceBotsTool({ user_id }),
...(await grabCoordinatorExtensionTools({ user_id, bot_id, session_id, workspace_id, onPropose })),
);
tools.push(findBotTool(), findWorkspaceTool({ user_id }), listWorkspaceBotsTool({ user_id }));
tools.push(deleteWorkspaceTool({ user_id, workspaces }));
@@ -0,0 +1,28 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import type { MessageDetailsRequest } from "@/src/schemas/bot-schema";
import type { MessageDetails } from "@/src/types";
type Params = {
message_id: MessageDetailsRequest["message_id"];
/**
* Every call and failure, for the report's copy, not the first the
* modal lists.
*/
full?: boolean;
};
/**
* How one of the bot's messages was generated. `full` reads every call
* and failure it took, which the modal's copy of the report needs.
*/
export default async function fetchMessageDetails({ message_id, full }: Params) {
const query = new URLSearchParams({ message_id: String(message_id) });
if (full) query.set("full", "1");
return await fetchApi<{}, APIResponseObject<MessageDetails>>(
`/api/admin/bots/message-details?${query.toString()}`,
{ method: "GET" },
);
}
@@ -1,7 +1,6 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useCallback, useEffect, useState } from "react";
import type { MessageDetails } from "@/src/types";
import fetchMessageDetails from "../(functions)/fetch-message-details";
type Params = {
message_id: number;
@@ -24,10 +23,7 @@ export default function useMessageDetails({ message_id, enabled = true }: Params
setLoading(true);
setError(undefined);
const res = await fetchApi<{}, APIResponseObject<MessageDetails>>(
`/api/admin/bots/message-details?message_id=${message_id}`,
{ method: "GET" },
).catch(() => null);
const res = await fetchMessageDetails({ message_id }).catch(() => null);
setLoading(false);
@@ -0,0 +1,77 @@
import { useEffect, useRef, useState } from "react";
import Button from "@moduletrace/twui/layout/Button";
import { Check, ClipboardCopy } from "lucide-react";
import { AppData } from "@/src/data/app-data";
import copyPendingText from "@/src/utils/copy-pending-text";
import messageDetailsMarkdown from "../(utils)/message-details-markdown";
import fetchMessageDetails from "../(functions)/fetch-message-details";
type Props = {
message_id: number;
};
/**
* The details modal's "Copy report": puts the message's whole details on
* the clipboard as one markdown document (`messageDetailsMarkdown`),
* every call and failure it took included, not only the ones the modal
* lists. The row shows a check for a moment, then goes back.
*/
export default function CopyMessageDetailsButton({ message_id }: Props) {
const [loading, setLoading] = useState(false);
const [copied, setCopied] = useState(false);
const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
return () => {
if (timeout.current) clearTimeout(timeout.current);
};
}, []);
const copy = async () => {
setLoading(true);
const markdown = fetchMessageDetails({ message_id, full: true }).then((res) => {
if (!res?.success || !res.singleRes) {
throw new Error(res?.msg || "Couldn't load this message's details.");
}
return messageDetailsMarkdown({ details: res.singleRes, now: Date.now() });
});
try {
const worked = await copyPendingText({ text: markdown });
setLoading(false);
if (!worked) {
window.alert("Couldn't copy the report to the clipboard.");
return;
}
setCopied(true);
timeout.current = setTimeout(() => setCopied(false), AppData.CopyConfirmationMs);
} catch (error: unknown) {
setLoading(false);
window.alert(error instanceof Error ? error.message : "Couldn't copy the report.");
}
};
return (
<Button
title={copied ? "Copied" : "Copy this message's whole details as markdown"}
type="button"
variant="ghost"
color="gray"
size="small"
beforeIcon={copied ? <Check size={14} aria-hidden /> : <ClipboardCopy size={14} aria-hidden />}
loading={loading}
disabled={loading}
onClick={() => {
if (!copied) void copy();
}}
className="shrink-0 px-2! text-[12px]"
>
{copied ? "Copied" : "Copy report"}
</Button>
);
}
@@ -1,12 +1,10 @@
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { BotJobKinds } from "@/src/dict/bot-queue-dict";
import type { MessageDetails } from "@/src/types";
import formatDuration from "@/src/utils/format-duration";
import formatTokens from "@/src/utils/format-tokens";
import relativeTime from "@/src/utils/relative-time";
import costLabel from "../(utils)/cost-label";
import providerLabel from "../(utils)/provider-label";
import messageDetailsFacts from "../(utils)/message-details-facts";
import MessageDetailRow from "./message-detail-row";
import MessageDetailsCallRow from "./message-details-call-row";
import MessageDetailsFailureRow from "./message-details-failure-row";
@@ -24,17 +22,7 @@ type Props = {
*/
export default function MessageDetailsBody({ details }: Props) {
const { totals, models, calls, failures, failed_calls, job } = details;
const providers = [
...new Set(models.map((m) => providerLabel({ name: m.provider_name, kind: m.provider_kind }))),
];
const model_names = [...new Set(models.map((m) => m.model_name || m.model_slug || "Unknown model"))];
const first_at = Math.min(
...[calls[0]?.created_at, failures[0]?.created_at].filter((at): at is number => Boolean(at)),
Number.MAX_SAFE_INTEGER,
);
const job_kind = BotJobKinds.find((k) => k.value == job?.kind)?.title || job?.kind;
const job_took =
job?.started_at && job.finished_at ? formatDuration({ ms: job.finished_at - job.started_at }) : "";
const { providers, model_names, first_at, job_kind, job_took } = messageDetailsFacts({ details });
return (
<Stack className="w-full gap-0! items-stretch">
@@ -3,6 +3,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import type { MessageDetailsFailure } from "@/src/types";
import formatDuration from "@/src/utils/format-duration";
import failureSourceLabel from "../(utils)/failure-source-label";
import harnessLabel from "../(utils)/harness-label";
import providerLabel from "../(utils)/provider-label";
@@ -16,12 +17,6 @@ type Props = {
first_at: number;
};
const SourceLabels: Record<NonNullable<MessageDetailsFailure["source"]>, string> = {
pinned: "the pick",
fallback: "a fallback model",
auto: "an automatic pick",
};
/**
* One model call that failed: its number, when it came after the first
* call, which model and its HTTP status, then what the provider said and
@@ -46,7 +41,7 @@ export default function MessageDetailsFailureRow({ failure, index, first_at }: P
className="grow min-w-0 text-[12px] leading-4 text-ink truncate"
title={[
`${model}${failure.model_slug ? ` (${failure.model_slug})` : ""} on ${provider}`,
`${harnessLabel({ harness: failure.harness })}${failure.source ? `, ${SourceLabels[failure.source]}` : ""}`,
`${harnessLabel({ harness: failure.harness })}${failure.source ? `, ${failureSourceLabel({ source: failure.source })}` : ""}`,
].join("\n")}
>
{model}
@@ -1,10 +1,12 @@
import { useState } from "react";
import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { Info } from "lucide-react";
import useMessageDetails from "../(hooks)/use-message-details";
import CopyMessageDetailsButton from "./copy-message-details-button";
import MessageActionButton from "./message-action-button";
import MessageDetailsBody from "./message-details-body";
@@ -34,7 +36,10 @@ export default function MessageDetailsModal({ message_id }: Props) {
className="max-w-xl bg-paper p-6"
>
<Stack className="w-full gap-1! items-stretch">
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">Message details</H2>
<Row className="w-full gap-2! flex-nowrap items-center">
<H2 className="grow text-lg! leading-6! tracking-normal! font-bold text-ink">Message details</H2>
<CopyMessageDetailsButton message_id={message_id} />
</Row>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
How this answer was generated: the provider and model behind it, the settings they were called with, and what it spent.
</Span>
@@ -0,0 +1,19 @@
import type { MessageDetailsFailure } from "@/src/types";
const SourceLabels: Record<NonNullable<MessageDetailsFailure["source"]>, string> = {
pinned: "the pick",
fallback: "a fallback model",
auto: "an automatic pick",
};
type Params = {
source: MessageDetailsFailure["source"];
};
/**
* How a failed call's model was picked, in words: "the pick", "a fallback
* model", "an automatic pick". Empty when the call recorded no source.
*/
export default function failureSourceLabel({ source }: Params) {
return source ? SourceLabels[source] : "";
}
@@ -0,0 +1,49 @@
import { BotJobKinds } from "@/src/dict/bot-queue-dict";
import type { MessageDetails } from "@/src/types";
import formatDuration from "@/src/utils/format-duration";
import providerLabel from "./provider-label";
type Params = {
details: MessageDetails;
};
export type MessageDetailsFacts = {
/**
* Every provider name that answered, in the order they first did.
*/
providers: string[];
/**
* Every model name that answered, in the order they first did.
*/
model_names: string[];
/**
* When the earliest call or failure was made, so each reads as an
* offset from it.
*/
first_at: number;
job_kind: string;
job_took: string;
};
/**
* What a message's details say at a glance, worked out once so the modal
* and the copy of it never disagree: the providers and models behind the
* message, when its first call was made, and how the run reads.
*/
export default function messageDetailsFacts({ details }: Params): MessageDetailsFacts {
const { models, calls, failures, job } = details;
return {
providers: [
...new Set(models.map((model) => providerLabel({ name: model.provider_name, kind: model.provider_kind }))),
],
model_names: [...new Set(models.map((model) => model.model_name || model.model_slug || "Unknown model"))],
first_at: Math.min(
...[calls[0]?.created_at, failures[0]?.created_at].filter((at): at is number => Boolean(at)),
Number.MAX_SAFE_INTEGER,
),
job_kind: BotJobKinds.find((kind) => kind.value == job?.kind)?.title || job?.kind || "",
job_took:
job?.started_at && job.finished_at ? formatDuration({ ms: job.finished_at - job.started_at }) : "",
};
}
@@ -0,0 +1,201 @@
import { describe, expect, test } from "bun:test";
import type { HarnessCallSettings } from "@/src/harness/usage/types";
import type { MessageDetails, MessageDetailsCall, MessageDetailsFailure } from "@/src/types";
import messageDetailsMarkdown from "./message-details-markdown";
const format_time = (time: number) => `t${time}`;
const settings: HarnessCallSettings = {
model_source: "pinned",
settings_source: "bot",
params: { temperature: 0.3 },
};
function call(overrides: Partial<MessageDetailsCall>): MessageDetailsCall {
return {
id: 1,
created_at: 1_000,
harness: "text",
provider_id: 1,
provider_name: "OpenRouter",
provider_kind: "openrouter",
model_slug: "deepseek/deepseek-v4",
model_name: "DeepSeek V4",
prompt_tokens: 1_200,
cached_tokens: 200,
completion_tokens: 80,
cost: 0.0123,
settings,
...overrides,
};
}
function failure(overrides: Partial<MessageDetailsFailure>): MessageDetailsFailure {
return {
id: 1,
created_at: 1_000,
harness: "text",
provider_name: "OpenRouter",
provider_kind: "openrouter",
model_slug: "deepseek/deepseek-v4",
model_name: "DeepSeek V4",
source: "pinned",
status: 429,
error: "Rate limited\nTry again later",
rests_until: 61_000,
...overrides,
};
}
function details(overrides: Partial<MessageDetails>): MessageDetails {
return {
message_id: 42,
created_at: 5_000,
totals: { prompt_tokens: 1_200, completion_tokens: 80, total_tokens: 1_280, calls: 1 },
models: [],
calls: [],
failures: [],
failed_calls: 0,
job: null,
...overrides,
};
}
describe("messageDetailsMarkdown", () => {
test("heads the report with the message, its totals and when it was copied", () => {
const markdown = messageDetailsMarkdown({
details: details({
totals: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0, calls: 0 },
}),
now: 9_000,
format_time,
});
expect(markdown).toContain("# Message details");
expect(markdown).toContain("- **Message:** #42");
expect(markdown).toContain("- **Written:** t5000");
expect(markdown).toContain("- **Tokens:** 0 (0 in, 0 out)");
expect(markdown).toContain("- **Copied:** t9000");
expect(markdown).toContain("No model calls were recorded for this message.");
});
test("lists every call in a table, with its offset and fallback mark", () => {
const markdown = messageDetailsMarkdown({
details: details({
totals: { prompt_tokens: 1_300, completion_tokens: 90, total_tokens: 1_390, calls: 2 },
calls: [
call({ id: 1, created_at: 1_000 }),
call({
id: 2,
created_at: 5_200,
prompt_tokens: 100,
completion_tokens: 10,
settings: { ...settings, fell_back_from: ["openrouter:big"] },
}),
],
}),
now: 9_000,
format_time,
});
expect(markdown).toContain("| # | At | Model | Harness | Prompt | Cached | Completion | Cost |");
expect(markdown).toContain("| 1 | start | DeepSeek V4 (deepseek/deepseek-v4) | Text | 1,200 | 200 | 80 | $0.0123 |");
expect(markdown).toContain("| 2 | +4.2s | DeepSeek V4 (deepseek/deepseek-v4) (fallback) | Text | 100 | 200 | 10 | $0.0123 |");
});
test("quotes a failed call's error line by line and names what rested", () => {
const markdown = messageDetailsMarkdown({
details: details({ failures: [failure({})], failed_calls: 1 }),
now: 9_000,
format_time,
});
expect(markdown).toContain("## Failed call");
expect(markdown).toContain("### Failure #1 · start");
expect(markdown).toContain("- **Status:** HTTP 429");
expect(markdown).toContain("- **Rested for:** 1m");
expect(markdown).toContain("> Rate limited\n> Try again later");
});
test("sums each model with its settings in a table", () => {
const markdown = messageDetailsMarkdown({
details: details({
models: [
{
harness: "text",
provider_name: "OpenRouter",
provider_kind: "openrouter",
model_slug: "deepseek/deepseek-v4",
model_name: "DeepSeek V4",
settings,
prompt_tokens: 1_200,
completion_tokens: 80,
total_tokens: 1_280,
calls: 1,
cost: 0.0123,
},
],
}),
now: 9_000,
format_time,
});
expect(markdown).toContain("## Model used");
expect(markdown).toContain("### DeepSeek V4");
expect(markdown).toContain("- **Provider:** OpenRouter");
expect(markdown).toContain("| Setting | Value |");
expect(markdown).toContain("| Temperature | 0.3 |");
});
test("spells out the run behind the message", () => {
const markdown = messageDetailsMarkdown({
details: details({
job: {
id: 7,
kind: "task",
title: "Weekly report",
status: "completed",
attempts: 1,
started_at: 1_000,
finished_at: 181_000,
steps: 12,
},
}),
now: 200_000,
format_time,
});
expect(markdown).toContain("## Run");
expect(markdown).toContain("- **Id:** #7");
expect(markdown).toContain("- **Kind:** Task");
expect(markdown).toContain("- **Title:** Weekly report");
expect(markdown).toContain("- **Took:** 3m");
expect(markdown).toContain("- **Steps:** 12");
});
test("says when the report lists fewer calls than were made", () => {
const markdown = messageDetailsMarkdown({
details: details({
totals: { prompt_tokens: 1_200, completion_tokens: 80, total_tokens: 1_280, calls: 5 },
calls: [call({})],
}),
now: 9_000,
format_time,
});
expect(markdown).toContain("Showing the first 1 of 5 calls. The totals count every one.");
});
test("keeps a pipe in a model name from breaking a table cell", () => {
const markdown = messageDetailsMarkdown({
details: details({
calls: [call({ model_name: "A|B" })],
totals: { prompt_tokens: 1_200, completion_tokens: 80, total_tokens: 1_280, calls: 1 },
}),
now: 9_000,
format_time,
});
expect(markdown).toContain("A\\|B");
});
});
@@ -0,0 +1,203 @@
import type { MessageDetails, MessageDetailsCall, MessageDetailsFailure, MessageDetailsModel } from "@/src/types";
import describeCallSettings from "@/src/utils/describe-call-settings";
import formatDuration from "@/src/utils/format-duration";
import costLabel from "./cost-label";
import failureSourceLabel from "./failure-source-label";
import harnessLabel from "./harness-label";
import messageDetailsFacts from "./message-details-facts";
import providerLabel from "./provider-label";
type Params = {
details: MessageDetails;
/**
* When the copy was made.
*/
now: number;
/**
* A timestamp as the reader sees it; local time by default.
*/
format_time?: (time: number) => string;
};
type DetailLine = {
label: string;
value: string;
};
/**
* Everything a message's details hold as one markdown report, for a bug
* report or a note: the provider and model that answered and what it
* spent, the run behind it, every model it used, every call in order and
* every call that failed, with why. The whole message, not only the calls
* the modal lists.
*/
export default function messageDetailsMarkdown({
details,
now,
format_time = (time) =>
new Date(time).toLocaleString(undefined, {
dateStyle: "medium",
timeStyle: "short",
}),
}: Params) {
const { totals, models, calls, failures, failed_calls, job } = details;
const { providers, model_names, first_at, job_kind, job_took } = messageDetailsFacts({ details });
const out: string[] = [
"# Message details",
"",
...lines([
{ label: "Message", value: `#${details.message_id}` },
{ label: "Written", value: details.created_at ? format_time(details.created_at) : "" },
{ label: providers.length > 1 ? "Providers" : "Provider", value: providers.join(", ") },
{ label: model_names.length > 1 ? "Models" : "Model", value: model_names.join(", ") },
{ label: "Tokens", value: `${totals.total_tokens.toLocaleString()} (${totals.prompt_tokens.toLocaleString()} in, ${totals.completion_tokens.toLocaleString()} out)` },
{ label: "Cost", value: costLabel({ cost: totals.cost }) },
{ label: "Model calls", value: String(totals.calls) },
{ label: "Failed calls", value: failed_calls ? String(failed_calls) : "" },
{ label: "Copied", value: format_time(now) },
]),
];
if (!totals.calls && !failed_calls) {
out.push(
"",
"No model calls were recorded for this message. It was written by the app itself (a stop, a failure notice), or before usage was recorded.",
);
}
if (job) {
out.push(
"",
"## Run",
"",
...lines([
{ label: "Id", value: `#${job.id}` },
{ label: "Kind", value: job_kind },
{ label: "Title", value: job.title || "" },
{ label: "Status", value: job.status || "" },
{ label: "Took", value: job_took },
{ label: "Attempts", value: String(job.attempts || 1) },
{ label: "Steps", value: String(job.steps) },
]),
);
}
if (models.length) {
out.push("", `## ${models.length > 1 ? "Models used" : "Model used"}`, ...models.flatMap(modelBlock));
}
if (calls.length) {
out.push("", "## Calls in order", "", callTable({ calls, first_at }));
if (totals.calls > calls.length) {
out.push("", `Showing the first ${calls.length} of ${totals.calls} calls. The totals count every one.`);
}
}
if (failures.length) {
out.push("", `## ${failures.length > 1 ? "Failed calls" : "Failed call"}`, ...failures.flatMap((failure, index) => failureBlock({ failure, index, first_at })));
if (failed_calls > failures.length) {
out.push("", `Showing the first ${failures.length} of ${failed_calls} failed calls.`);
}
}
return `${out.join("\n").trimEnd()}\n`;
}
/**
* A label and its value per line, skipping the ones with nothing to say.
*/
function lines(rows: DetailLine[]) {
return rows.filter((row) => row.value).map((row) => `- **${row.label}:** ${row.value}`);
}
function modelBlock(model: MessageDetailsModel) {
const name = model.model_name || model.model_slug || "Unknown model";
const settings = model.settings ? describeCallSettings({ settings: model.settings, harness: model.harness }) : [];
const out = [
"",
`### ${name}`,
"",
...lines([
{ label: "Id", value: model.model_slug && model.model_slug != name ? model.model_slug : "" },
{ label: "Provider", value: providerLabel({ name: model.provider_name, kind: model.provider_kind }) },
{ label: "Harness", value: harnessLabel({ harness: model.harness }) },
{ label: "Calls", value: String(model.calls) },
{ label: "Tokens", value: `${model.total_tokens.toLocaleString()} (${model.prompt_tokens.toLocaleString()} in, ${model.completion_tokens.toLocaleString()} out)` },
{ label: "Cost", value: costLabel({ cost: model.cost }) },
]),
];
if (settings.length) {
out.push("", "| Setting | Value |", "| --- | --- |");
out.push(...settings.map(({ label, value }) => `| ${label} | ${escapeCell({ text: value })} |`));
}
return out;
}
function callTable({ calls, first_at }: { calls: MessageDetailsCall[]; first_at: number }) {
const out = [
"| # | At | Model | Harness | Prompt | Cached | Completion | Cost |",
"| --- | --- | --- | --- | --- | --- | --- | --- |",
];
out.push(
...calls.map((call, index) => {
const model = `${call.model_name || call.model_slug || "Unknown model"}${call.model_slug && call.model_name ? ` (${call.model_slug})` : ""}`;
const fell_back = call.settings?.fell_back_from?.length ? " (fallback)" : "";
return [
`| ${index + 1}`,
offsetLabel({ at: call.created_at, first_at }),
escapeCell({ text: `${model}${fell_back}` }),
harnessLabel({ harness: call.harness }),
call.prompt_tokens.toLocaleString(),
call.cached_tokens.toLocaleString(),
call.completion_tokens.toLocaleString(),
escapeCell({ text: costLabel({ cost: call.cost }) }),
].join(" | ") + " |";
}),
);
return out.join("\n");
}
function failureBlock({ failure, index, first_at }: { failure: MessageDetailsFailure; index: number; first_at: number }) {
const model = `${failure.model_name || failure.model_slug || "Unknown model"}${failure.model_slug && failure.model_name ? ` (${failure.model_slug})` : ""}`;
const rested =
failure.rests_until && failure.rests_until > failure.created_at
? formatDuration({ ms: failure.rests_until - failure.created_at })
: "";
return [
"",
`### Failure #${index + 1} · ${offsetLabel({ at: failure.created_at, first_at })}`,
"",
...lines([
{ label: "Model", value: model },
{ label: "Provider", value: providerLabel({ name: failure.provider_name, kind: failure.provider_kind }) },
{ label: "Harness", value: harnessLabel({ harness: failure.harness }) },
{ label: "Picked", value: failureSourceLabel({ source: failure.source }) },
{ label: "Status", value: failure.status ? `HTTP ${failure.status}` : "No response" },
{ label: "Rested for", value: rested },
]),
"",
"> " + failure.error.split("\n").join("\n> "),
];
}
/**
* When a call came after the first: "+4.2s", or "start" for the first.
*/
function offsetLabel({ at, first_at }: { at: number; first_at: number }) {
return at > first_at ? `+${formatDuration({ ms: at - first_at })}` : "start";
}
/**
* A value inside a table cell, kept on one line.
*/
function escapeCell({ text }: { text: string }) {
return text.replaceAll("|", "\\|").replaceAll("\n", " ");
}
+5 -2
View File
@@ -1,3 +1,4 @@
import { AppData } from "@/src/data/app-data";
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabSpeakableMessage from "@/src/functions/backend/db/bots/grab-speakable-message";
import grabMessageDetails from "@/src/functions/backend/db/usage/grab-message-details";
@@ -11,7 +12,8 @@ import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bune
* `GET ?message_id=`: how one of the bot's messages in the user's own
* conversation was generated (the job, every model call with its provider
* and model, and the tokens and cost). Loaded when its details modal
* opens, so the thread's messages stay small.
* opens, so the thread's messages stay small. `&full=1` lists every call
* and failure, for the copy of the report.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<MessageDetails>> = async ({ req, query }) => {
try {
@@ -25,7 +27,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<MessageDetails>> =
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
const { message_id } = parseWithSchema({ schema: MessageDetailsRequestSchema, data: query });
const { message_id, full } = parseWithSchema({ schema: MessageDetailsRequestSchema, data: query });
const { message } = await grabSpeakableMessage({ user_id: Number(user.id), message_id });
return {
@@ -33,6 +35,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<MessageDetails>> =
singleRes: await grabMessageDetails({
message_id: Number(message.id),
created_at: Number(message.created_at) || null,
...(full ? { max_calls: AppData.MessageDetailsCopyMaxCalls } : {}),
}),
};
} catch (error: unknown) {
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, test } from "bun:test";
import { MessageDetailsRequestSchema } from "./bot-schema";
describe("MessageDetailsRequestSchema", () => {
test("asks for the modal's calls by default", () => {
const parsed = MessageDetailsRequestSchema.parse({ message_id: "7" });
expect(parsed).toEqual({ message_id: 7, full: false });
});
test("reads the report's flag from a query string", () => {
expect(MessageDetailsRequestSchema.parse({ message_id: "7", full: "1" }).full).toBe(true);
expect(MessageDetailsRequestSchema.parse({ message_id: "7", full: "true" }).full).toBe(true);
expect(MessageDetailsRequestSchema.parse({ message_id: "7", full: "0" }).full).toBe(false);
expect(MessageDetailsRequestSchema.parse({ message_id: "7", full: false }).full).toBe(false);
});
test("refuses a message it can't read", () => {
expect(MessageDetailsRequestSchema.safeParse({ message_id: "0" }).success).toBe(false);
expect(MessageDetailsRequestSchema.safeParse({ message_id: "abc" }).success).toBe(false);
expect(MessageDetailsRequestSchema.safeParse({}).success).toBe(false);
});
});
+8
View File
@@ -220,6 +220,14 @@ export type SpeakBotMessageRequest = z.infer<typeof SpeakBotMessageRequestSchema
export const MessageDetailsRequestSchema = z.object({
message_id: z.coerce.number().int().positive("Pick a message"),
/**
* `1` lists every call and failure the message took, for its copied
* report, instead of the modal's first `MessageDetailsMaxCalls`.
*/
full: z
.union([z.literal("1"), z.literal("true"), z.literal("0"), z.literal("false"), z.boolean()])
.optional()
.transform((value) => value === "1" || value === "true" || value === true),
});
export type MessageDetailsRequest = z.infer<typeof MessageDetailsRequestSchema>;