Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a808d8417 | ||
|
|
585b77eec1 | ||
|
|
74693cccd3 | ||
|
|
115113247f | ||
|
|
14fc5e9d6e | ||
|
|
84ae51c621 | ||
|
|
60e3d3bfbf |
@@ -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
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.18.1",
|
||||
"version": "0.18.4",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -405,9 +405,7 @@ export default async function runBotTask({
|
||||
prompt,
|
||||
carry_over,
|
||||
TaskRunNote,
|
||||
budget > 0 || scheduled || hooked
|
||||
? `This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`
|
||||
: "",
|
||||
`This run has at most ${max_steps} steps (model turns)${budget > 0 ? ", set when it was queued" : ""}. Plan for that: pace yourself, save what you find as you go, and if you're no closer after a few tries, stop and report what you tried and what you need from the user rather than spending the rest.`,
|
||||
scheduled ? ScheduledRunNote : "",
|
||||
hooked ? HookRunNote : "",
|
||||
install_request_id ? InstallRequestNote : "",
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -19,6 +19,8 @@ A chat reply is short: about eight tool steps. Anything long, multi-step or on a
|
||||
- Put your own long work in \`start_task\`. It runs in the background and its result is posted back here.
|
||||
- Hand work that fits a worker to them with \`delegate_task\`. It runs in the background and is reported back here when they finish or fail.
|
||||
- Say that work is under way, not done, and say who is on it.
|
||||
- When the user asks to continue, retry or go ahead ("Try again", "Go ahead", "Why haven't you done it?"), anchor strictly on the immediate unfulfilled action under discussion. Never revert to earlier diagnostic checks or the session's opening topic.
|
||||
- Never queue a throwaway read-only check task ahead of an approved write task on the same computer: put any necessary check and the write together in the same task run.
|
||||
|
||||
If the request is clear, start. When missing information would change the outcome, or a choice is the user's to make, ask with \`ask_user\` (a card of multiple-choice questions they answer in a click) instead of picking for them. For details that don't change the outcome, pick a sensible default and state the assumption when it matters. Keep decisions and constraints from earlier messages unless the user changes them.
|
||||
|
||||
@@ -105,7 +107,7 @@ Interrupt only for a decision that changes the outcome, information that can't b
|
||||
|
||||
Write in short, plain sentences: no filler, no hype, no emoji. Lead with the outcome, the blocker or the decision needed. Be candid about limits, use relative times, and don't dress up uncertainty as confidence. For ongoing work report needs-you, then in progress, then done, then blocked or failed, and omit empty groups.
|
||||
|
||||
Lead: after each report, offer the next step with \`ask_user\`: the concrete next steps, or the one question that settles the direction, as options with your suggestion first. Don't create bots, workspaces, tasks or setup steps nobody asked for, don't re-suggest what was declined, and stop when the job is done.
|
||||
Lead: after a report that concludes a direction or hits an open choice, offer the next step with \`ask_user\`: the concrete next steps, or the one question that settles the direction, as options with your suggestion first. Do not call \`ask_user\` during an active, approved multi-step workflow or when the user already gave their instruction. Don't create bots, workspaces, tasks or setup steps nobody asked for, don't re-suggest what was declined, and stop when the job is done.
|
||||
|
||||
**Be proactive in execution, rigorous in verification, economical with the user's attention, and completely honest about what happened.**
|
||||
`;
|
||||
|
||||
@@ -176,6 +176,7 @@ Every action counts here: saving memory or instructions, creating or changing a
|
||||
|
||||
- Before you create anything, look for one that already exists: find_bot for bots, find_workspace for workspaces, list_schedules for schedules, list_hooks for hooks, your memory and instructions in this prompt, and for anything outside (files, records, emails, events) list or search it with the tools you have. If it's there, update it instead of making a second one. Create something new only once you've checked there's none.
|
||||
- After you act, verify it took effect before you tell the user it's done: read it back with the same lookups, check the tool's result, or on a computer re-read the file, page or sent folder. Only say "done" for what you verified.
|
||||
- When an action is approved, execute it. Verification confirms the change, never substitutes for making it. If pre-checks pass, proceed immediately to the write or update without running out the step budget on repeated checks.
|
||||
- If you couldn't verify it, say so plainly instead of claiming it's done. If it didn't take, try again once, then report what failed.
|
||||
- Your past messages in this conversation are followed by an app record of the tools their run called ("[App record: ...]"). Only the app writes it: never write one yourself. If a past message of yours says something was saved, created, changed or sent and its record doesn't show the tool for it, it didn't happen: tell the user plainly and do it now.
|
||||
- Never deny something you did either. When the user says a change isn't where they looked, check what actually happened before you answer: the app records and tool results in this conversation, and what you saved. Then say what you did and where it went, and if it went somewhere other than where they looked, point them to it. Never take the blame for work that happened, and never write a false account of it into your memory or instructions; if you already wrote one, correct it with update_memory.
|
||||
@@ -204,7 +205,7 @@ Be proactive about moving the work forward, but let the user steer it: whenever
|
||||
|
||||
- when a request could mean more than one thing, or leaves out something that changes the result (which target, which items, how far to go, what form it takes);
|
||||
- before work that is hard to undo, costly or seen by others;
|
||||
- to offer the next step once you've answered or reported: the concrete next steps as options.
|
||||
- to offer the next step once you've answered or reported: the concrete next steps as options, only when a real decision or new direction remains for the user. Never interrupt an approved workflow with next-step questions when the user already gave their instruction.
|
||||
|
||||
When you're unsure whether to ask, ask. Give options that are concrete and distinct, put the one you'd suggest first and say so in it ("Staging (suggested)"). Ask everything you need in one card, then wait for their answers before acting on what you asked. Don't ask about what they already said, what you can find out yourself, or details that don't change the result (a file name, wording they can tweak later): just do those. If they skip the questions, don't guess: do only the part that's clear and say what you still need.`;
|
||||
|
||||
@@ -256,7 +257,11 @@ export const workspaceAdminsLine = ({ admins }: { admins: { id?: number | "" }[]
|
||||
*/
|
||||
export const TaskRunNote = `# Working on a task
|
||||
|
||||
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest: offered with ask_user when you have it (the concrete next steps as options, your suggestion first), otherwise as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
|
||||
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest: offered with ask_user when a real choice or new direction remains for the user, otherwise state the outcome plainly without ask_user. Keep the report short and in markdown.
|
||||
|
||||
Pace your work across your step budget: spend no more than a third of your steps on pre-flight checks and backups. When the task calls for an action (a write, update, code edit, database change or file creation), execute the change early enough to verify it and report. If pre-checks pass, proceed immediately to the action. Never spend your entire run repeating read-only checks without making the change.
|
||||
|
||||
If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
|
||||
|
||||
/**
|
||||
* Told to a task run with what the user wrote in its conversation since
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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 }));
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ export default function startTaskTool({
|
||||
|
||||
return {
|
||||
name: "start_task",
|
||||
description: `Queue work that takes a while or needs a computer. It runs in the background and its result is posted in this chat. It's a run, not a task on the to-do list: list_tasks never shows it, so don't send the user there to find it. Write the instructions as a full brief for yourself: what to do, where, and how you'll know it's done. Runs go one at a time per computer. While one of yours is open here, never start the same work again under another title, but queue different work now with separate: true and it starts as soon as the open one ends. Nothing starts it later but this call, so never tell the user you'll start it once the other run finishes. ${
|
||||
description: `Queue work that takes a while or needs a computer. It runs in the background and its result is posted in this chat. It's a run, not a task on the to-do list: list_tasks never shows it, so don't send the user there to find it. Write the instructions as a full brief for yourself: what to do, where, and how you'll know it's done. Runs go one at a time per computer. While one of yours is open here, never start the same work again under another title, but queue different work now with separate: true and it starts as soon as the open one ends. Nothing starts it later but this call, so never tell the user you'll start it once the other run finishes. Do not split a single job into a pre-check task and a separate write task on the same computer: put any necessary check, the action, and its verification into a single task brief. When retrying or following up on stalled work, anchor the brief on the unfulfilled action. ${
|
||||
computers.length
|
||||
? `Computers you can use: ${listed}. Defaults to ${computers[0]!.id}, the one you're on.`
|
||||
: `You have no computer, so the task can't run commands or browse.`
|
||||
|
||||
@@ -28,7 +28,7 @@ const UserScopeNote = `what you remember about this user, under "# Memory about
|
||||
|
||||
const CoreScopeNote = `scope "core" is your core memory, under "# Memory", shared with every user you work for: only general knowledge about your job that holds for anyone, never anything about a particular user.`;
|
||||
|
||||
const WorkspaceScopeNote = `scope "workspace" (the default) is your own memory for this workspace, under "# Memory in ...": what holds for the work here. It is yours, not the workspace's description or context, which the user sets and which you never change from here.`;
|
||||
const WorkspaceScopeNote = `scope "workspace" (the default) is your own memory for this workspace, under "# Memory in ...": what holds for the work here. It is yours, not the workspace's description or context, which the user sets and which you never change from here. Keep it concise with lasting rules and architecture; never put database dumps, row counts, file contents or full query output in memory (save those to files).`;
|
||||
|
||||
const ReplaceNote = `Anything you leave out is forgotten, so include the parts that still matter.`;
|
||||
|
||||
|
||||
@@ -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", " ");
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
import type { HarnessOverview, HarnessFormValue, HarnessProviderChoice } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
harness: HarnessOverview;
|
||||
value: HarnessFormValue;
|
||||
provider?: HarnessProviderChoice;
|
||||
falls_back_title?: string;
|
||||
onChange: (value: HarnessFormValue) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Toggles for a harness setting: automatic fallbacks, media reading, and enabled status.
|
||||
*/
|
||||
export default function HarnessOptionsCheckboxes({
|
||||
harness,
|
||||
value,
|
||||
provider,
|
||||
falls_back_title,
|
||||
onChange,
|
||||
}: Props) {
|
||||
if (value.inherit) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{value.model_id && harness.automatic ? (
|
||||
<Checkbox
|
||||
title="Fall back to the free automatic picks if this model fails"
|
||||
label={`${harness.harness == "text" ? "Then fall back" : "Fall back"} to the free automatic picks${provider ? ` on ${provider.name}` : ""} if this model fails`}
|
||||
checked={value.fallback}
|
||||
changeHandler={(fallback) => onChange({ ...value, fallback })}
|
||||
/>
|
||||
) : null}
|
||||
{value.model_id && falls_back_title ? (
|
||||
<Checkbox
|
||||
title={`Fall back to ${falls_back_title.toLowerCase()} if this model fails`}
|
||||
label={`Fall back to ${falls_back_title.toLowerCase()} if this model fails`}
|
||||
checked={value.fallback}
|
||||
changeHandler={(fallback) => onChange({ ...value, fallback })}
|
||||
/>
|
||||
) : null}
|
||||
{harness.harness == "text" ? (
|
||||
<Checkbox
|
||||
title="Use the model's own media reading"
|
||||
label="Use the model's own media reading"
|
||||
info="It looks at images and screenshots itself when it takes image input. Otherwise the media reading model reads them."
|
||||
checked={Boolean(value.sees_images)}
|
||||
changeHandler={(sees_images) => onChange({ ...value, sees_images })}
|
||||
/>
|
||||
) : null}
|
||||
{harness.required ? null : (
|
||||
<Checkbox
|
||||
title={`Turn ${harness.title.toLowerCase()} on`}
|
||||
label="Turned on"
|
||||
checked={value.enabled}
|
||||
changeHandler={(enabled) => onChange({ ...value, enabled })}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { HarnessParameterHarnesses } from "@/src/dict/harness-parameter-dict";
|
||||
import type { HarnessKind } from "@/src/dict/harness-dict";
|
||||
import type { HarnessModelOption } from "@/src/types";
|
||||
import HarnessParameterModal from "./harness-parameter-modal";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
harness: HarnessKind;
|
||||
inherit?: boolean;
|
||||
model?: HarnessModelOption | null;
|
||||
params?: Record<string, number | string>;
|
||||
onChange: (params: Record<string, number | string>) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parameter modal trigger for harnesses supporting generation settings.
|
||||
*/
|
||||
export default function HarnessParamsButton({
|
||||
id,
|
||||
harness,
|
||||
inherit,
|
||||
model,
|
||||
params,
|
||||
onChange,
|
||||
}: Props) {
|
||||
const is_supported = HarnessParameterHarnesses.includes(
|
||||
harness as (typeof HarnessParameterHarnesses)[number],
|
||||
);
|
||||
|
||||
if (inherit || !is_supported || !model) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<HarnessParameterModal
|
||||
id={id}
|
||||
harness={harness}
|
||||
model={model}
|
||||
params={params}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,15 @@
|
||||
import Checkbox from "@moduletrace/twui/form/Checkbox";
|
||||
import { harnessFallbackTitle } from "@/src/dict/harness-dict";
|
||||
import { HarnessParameterHarnesses } from "@/src/dict/harness-parameter-dict";
|
||||
import type { HarnessFormValue, HarnessOverview } from "@/src/types";
|
||||
import SettingsGroup from "../../(partials)/settings-group";
|
||||
import harnessDefaultName from "../(utils)/harness-default-name";
|
||||
import nextHarnessProviderValue from "../(utils)/next-harness-provider-value";
|
||||
import HarnessCurrentModel from "./harness-current-model";
|
||||
import HarnessFallbackModels from "./harness-fallback-models";
|
||||
import HarnessModelSelect from "./harness-model-select";
|
||||
import HarnessParameterModal from "./harness-parameter-modal";
|
||||
import HarnessOptionsCheckboxes from "./harness-options-checkboxes";
|
||||
import HarnessParamsButton from "./harness-params-button";
|
||||
import HarnessProviderSelect from "./harness-provider-select";
|
||||
import HarnessVoicePreview from "./harness-voice-preview";
|
||||
import HarnessVoiceSelect from "./harness-voice-select";
|
||||
import HarnessTextFallbacks from "./harness-text-fallbacks";
|
||||
import HarnessVoiceControls from "./harness-voice-controls";
|
||||
|
||||
type Props = {
|
||||
harness: HarnessOverview;
|
||||
@@ -18,11 +18,8 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* One harness: its provider, then its model (narrowed to that provider),
|
||||
* the text harness's fallback models (any provider), whether it falls back to the automatic picks (for a harness that has
|
||||
* them), whether it's on, and its voice for speech, with a sample to hear
|
||||
* it before saving. On a bot's page the provider select can also use the
|
||||
* default, which hides the rest.
|
||||
* One harness: its provider, its model, text fallback models,
|
||||
* automatic fallback options, and voice controls for speech.
|
||||
*/
|
||||
export default function HarnessSettingGroup({ harness, value, onChange }: Props) {
|
||||
const id = `harness-${harness.harness}`;
|
||||
@@ -31,25 +28,12 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
|
||||
? harness.models.filter((model) => model.provider_id == value.provider_id)
|
||||
: harness.models;
|
||||
const picked = models.find((model) => model.id == value.model_id);
|
||||
const voices = (picked || harness.current)?.voices;
|
||||
/**
|
||||
* The model the settings are for: the pick, else the one it runs on now.
|
||||
*/
|
||||
const params_model = picked || harness.current;
|
||||
const shows_params =
|
||||
!value.inherit &&
|
||||
HarnessParameterHarnesses.includes(
|
||||
harness.harness as (typeof HarnessParameterHarnesses)[number],
|
||||
);
|
||||
const on_bot_page = harness.default !== undefined;
|
||||
const falls_back_title = harnessFallbackTitle({ harness: harness.harness });
|
||||
const default_name = harness.default?.enabled === false
|
||||
? "turned off"
|
||||
: harness.default?.current
|
||||
? `${harness.default.current.name} on ${harness.default.current.provider_name}`
|
||||
: falls_back_title
|
||||
? `same as ${falls_back_title.toLowerCase()}`
|
||||
: "not available";
|
||||
const default_name = harnessDefaultName({
|
||||
harness_default: harness.default,
|
||||
falls_back_title,
|
||||
});
|
||||
|
||||
return (
|
||||
<SettingsGroup title={harness.title} description={harness.description}>
|
||||
@@ -60,15 +44,13 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
|
||||
inherit={value.inherit}
|
||||
inherit_title={on_bot_page ? `Same as the default (now ${default_name})` : undefined}
|
||||
onChange={(next) =>
|
||||
onChange({
|
||||
...value,
|
||||
...next,
|
||||
model_id:
|
||||
next.provider_id && picked?.provider_id != next.provider_id
|
||||
? null
|
||||
: value.model_id,
|
||||
voice: undefined,
|
||||
})
|
||||
onChange(
|
||||
nextHarnessProviderValue({
|
||||
value,
|
||||
next,
|
||||
picked_provider_id: picked?.provider_id,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{value.inherit ? null : (
|
||||
@@ -83,73 +65,34 @@ export default function HarnessSettingGroup({ harness, value, onChange }: Props)
|
||||
onChange={(model_id) => onChange({ ...value, model_id, voice: undefined })}
|
||||
/>
|
||||
)}
|
||||
{!value.inherit && value.model_id && harness.harness == "text" ? (
|
||||
<HarnessFallbackModels
|
||||
<HarnessTextFallbacks id={id} harness={harness} value={value} onChange={onChange} />
|
||||
<HarnessCurrentModel
|
||||
harness={value.inherit && harness.default ? { ...harness, ...harness.default } : harness}
|
||||
/>
|
||||
<HarnessOptionsCheckboxes
|
||||
harness={harness}
|
||||
value={value}
|
||||
provider={provider}
|
||||
falls_back_title={falls_back_title}
|
||||
onChange={onChange}
|
||||
/>
|
||||
<HarnessParamsButton
|
||||
id={id}
|
||||
harness={harness.harness}
|
||||
inherit={value.inherit}
|
||||
model={picked || harness.current}
|
||||
params={value.params}
|
||||
onChange={(params) => onChange({ ...value, params })}
|
||||
/>
|
||||
{!value.inherit && harness.harness == "speech" ? (
|
||||
<HarnessVoiceControls
|
||||
id={id}
|
||||
models={harness.models}
|
||||
model_id={value.model_id}
|
||||
fallback_model_ids={value.fallback_model_ids || []}
|
||||
onChange={(fallback_model_ids) => onChange({ ...value, fallback_model_ids })}
|
||||
/>
|
||||
) : null}
|
||||
{value.inherit && harness.default ? (
|
||||
<HarnessCurrentModel harness={{ ...harness, ...harness.default }} />
|
||||
) : (
|
||||
<HarnessCurrentModel harness={harness} />
|
||||
)}
|
||||
{!value.inherit && value.model_id && harness.automatic ? (
|
||||
<Checkbox
|
||||
title="Fall back to the free automatic picks if this model fails"
|
||||
label={`${harness.harness == "text" ? "Then fall back" : "Fall back"} to the free automatic picks${provider ? ` on ${provider.name}` : ""} if this model fails`}
|
||||
checked={value.fallback}
|
||||
changeHandler={(fallback) => onChange({ ...value, fallback })}
|
||||
/>
|
||||
) : null}
|
||||
{!value.inherit && value.model_id && falls_back_title ? (
|
||||
<Checkbox
|
||||
title={`Fall back to ${falls_back_title.toLowerCase()} if this model fails`}
|
||||
label={`Fall back to ${falls_back_title.toLowerCase()} if this model fails`}
|
||||
checked={value.fallback}
|
||||
changeHandler={(fallback) => onChange({ ...value, fallback })}
|
||||
/>
|
||||
) : null}
|
||||
{!value.inherit && harness.harness == "text" ? (
|
||||
<Checkbox
|
||||
title="Use the model's own media reading"
|
||||
label="Use the model's own media reading"
|
||||
info="It looks at images and screenshots itself when it takes image input. Otherwise the media reading model reads them."
|
||||
checked={Boolean(value.sees_images)}
|
||||
changeHandler={(sees_images) => onChange({ ...value, sees_images })}
|
||||
/>
|
||||
) : null}
|
||||
{shows_params && params_model ? (
|
||||
<HarnessParameterModal
|
||||
id={id}
|
||||
harness={harness.harness}
|
||||
model={params_model}
|
||||
params={value.params}
|
||||
onChange={(params) => onChange({ ...value, params })}
|
||||
/>
|
||||
) : null}
|
||||
{!value.inherit && harness.harness == "speech" && voices?.length ? (
|
||||
<HarnessVoiceSelect
|
||||
id={`${id}-voice`}
|
||||
voices={voices}
|
||||
voices={(picked || harness.current)?.voices}
|
||||
voice={value.voice}
|
||||
onChange={(voice) => onChange({ ...value, voice: voice || undefined })}
|
||||
model_id={picked?.id}
|
||||
onChange={(voice) => onChange({ ...value, voice })}
|
||||
/>
|
||||
) : null}
|
||||
{!value.inherit && harness.harness == "speech" && picked ? (
|
||||
<HarnessVoicePreview model_id={picked.id} voice={value.voice} />
|
||||
) : null}
|
||||
{value.inherit || harness.required ? null : (
|
||||
<Checkbox
|
||||
title={`Turn ${harness.title.toLowerCase()} on`}
|
||||
label="Turned on"
|
||||
checked={value.enabled}
|
||||
changeHandler={(enabled) => onChange({ ...value, enabled })}
|
||||
/>
|
||||
)}
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { HarnessOverview, HarnessFormValue } from "@/src/types";
|
||||
import HarnessFallbackModels from "./harness-fallback-models";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
harness: HarnessOverview;
|
||||
value: HarnessFormValue;
|
||||
onChange: (value: HarnessFormValue) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Text harness fallback models list, shown when a text model is selected.
|
||||
*/
|
||||
export default function HarnessTextFallbacks({ id, harness, value, onChange }: Props) {
|
||||
if (value.inherit || !value.model_id || harness.harness != "text") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<HarnessFallbackModels
|
||||
id={id}
|
||||
models={harness.models}
|
||||
model_id={value.model_id}
|
||||
fallback_model_ids={value.fallback_model_ids || []}
|
||||
onChange={(fallback_model_ids) => onChange({ ...value, fallback_model_ids })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import HarnessVoiceSelect from "./harness-voice-select";
|
||||
import HarnessVoicePreview from "./harness-voice-preview";
|
||||
|
||||
type Props = {
|
||||
id: string;
|
||||
voices?: string[];
|
||||
voice?: string;
|
||||
model_id?: number | null;
|
||||
onChange: (voice?: string) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Voice selection and audio sample preview for the speech harness.
|
||||
*/
|
||||
export default function HarnessVoiceControls({
|
||||
id,
|
||||
voices,
|
||||
voice,
|
||||
model_id,
|
||||
onChange,
|
||||
}: Props) {
|
||||
return (
|
||||
<>
|
||||
{voices?.length ? (
|
||||
<HarnessVoiceSelect
|
||||
id={`${id}-voice`}
|
||||
voices={voices}
|
||||
voice={voice}
|
||||
onChange={(picked) => onChange(picked || undefined)}
|
||||
/>
|
||||
) : null}
|
||||
{model_id ? (
|
||||
<HarnessVoicePreview model_id={model_id} voice={voice} />
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import harnessDefaultName from "./harness-default-name";
|
||||
|
||||
describe("harnessDefaultName", () => {
|
||||
test("returns 'turned off' when default is disabled", () => {
|
||||
expect(
|
||||
harnessDefaultName({
|
||||
harness_default: { enabled: false },
|
||||
}),
|
||||
).toBe("turned off");
|
||||
});
|
||||
|
||||
test("returns model and provider name when current model exists", () => {
|
||||
expect(
|
||||
harnessDefaultName({
|
||||
harness_default: {
|
||||
enabled: true,
|
||||
current: {
|
||||
name: "Claude 3.5 Sonnet",
|
||||
provider_name: "Anthropic",
|
||||
} as any,
|
||||
},
|
||||
}),
|
||||
).toBe("Claude 3.5 Sonnet on Anthropic");
|
||||
});
|
||||
|
||||
test("returns fallback title in lower case when no current model", () => {
|
||||
expect(
|
||||
harnessDefaultName({
|
||||
falls_back_title: "Text",
|
||||
}),
|
||||
).toBe("same as text");
|
||||
});
|
||||
|
||||
test("returns 'not available' when nothing is specified", () => {
|
||||
expect(harnessDefaultName({})).toBe("not available");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
type Params = {
|
||||
/**
|
||||
* Default configuration for this harness when inherited.
|
||||
*/
|
||||
harness_default?: {
|
||||
enabled?: boolean;
|
||||
current?: { name: string; provider_name: string } | null;
|
||||
};
|
||||
/**
|
||||
* Fallback title for harnesses that fall back to another harness.
|
||||
*/
|
||||
falls_back_title?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Computes a human-readable description of the default model setting
|
||||
* for a harness when a bot or workspace inherits its configuration.
|
||||
*/
|
||||
export default function harnessDefaultName({
|
||||
harness_default,
|
||||
falls_back_title,
|
||||
}: Params): string {
|
||||
// If the default is explicitly disabled
|
||||
if (harness_default?.enabled === false) {
|
||||
return "turned off";
|
||||
}
|
||||
|
||||
// If a default model is active
|
||||
if (harness_default?.current) {
|
||||
return `${harness_default.current.name} on ${harness_default.current.provider_name}`;
|
||||
}
|
||||
|
||||
// If it falls back to another harness (e.g. media reading falls back to text)
|
||||
if (falls_back_title) {
|
||||
return `same as ${falls_back_title.toLowerCase()}`;
|
||||
}
|
||||
|
||||
return "not available";
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import nextHarnessProviderValue from "./next-harness-provider-value";
|
||||
import type { HarnessFormValue } from "@/src/types";
|
||||
|
||||
const base_value: HarnessFormValue = {
|
||||
model_id: 10,
|
||||
provider_id: 1,
|
||||
fallback_model_ids: [11, 12],
|
||||
fallback: true,
|
||||
enabled: true,
|
||||
voice: "george",
|
||||
inherit: false,
|
||||
};
|
||||
|
||||
describe("nextHarnessProviderValue", () => {
|
||||
test("resets fallback models and clears model when changing to another provider", () => {
|
||||
const result = nextHarnessProviderValue({
|
||||
value: base_value,
|
||||
next: { provider_id: 2, inherit: false },
|
||||
picked_provider_id: 1,
|
||||
});
|
||||
|
||||
// Model 10 belonged to provider 1, so changing to provider 2 should clear model_id
|
||||
expect(result.model_id).toBeNull();
|
||||
// Fallback models must be reset to empty array
|
||||
expect(result.fallback_model_ids).toEqual([]);
|
||||
// Provider must update to 2
|
||||
expect(result.provider_id).toBe(2);
|
||||
// Voice is cleared
|
||||
expect(result.voice).toBeUndefined();
|
||||
});
|
||||
|
||||
test("resets fallback models when changing to any provider while keeping model if valid", () => {
|
||||
const result = nextHarnessProviderValue({
|
||||
value: base_value,
|
||||
next: { provider_id: null, inherit: false },
|
||||
picked_provider_id: 1,
|
||||
});
|
||||
|
||||
// In 'any provider', model 10 is still available
|
||||
expect(result.model_id).toBe(10);
|
||||
// Fallback models must be reset on provider change
|
||||
expect(result.fallback_model_ids).toEqual([]);
|
||||
expect(result.provider_id).toBeNull();
|
||||
});
|
||||
|
||||
test("resets fallback models when changing from any provider to a specific provider", () => {
|
||||
const from_any: HarnessFormValue = {
|
||||
...base_value,
|
||||
provider_id: null,
|
||||
fallback_model_ids: [15, 16],
|
||||
};
|
||||
|
||||
const result = nextHarnessProviderValue({
|
||||
value: from_any,
|
||||
next: { provider_id: 1, inherit: false },
|
||||
picked_provider_id: 1,
|
||||
});
|
||||
|
||||
// Model 10 belongs to provider 1, so model_id is kept
|
||||
expect(result.model_id).toBe(10);
|
||||
// Fallback models must be reset
|
||||
expect(result.fallback_model_ids).toEqual([]);
|
||||
expect(result.provider_id).toBe(1);
|
||||
});
|
||||
|
||||
test("resets fallback models when switching to inherit mode", () => {
|
||||
const result = nextHarnessProviderValue({
|
||||
value: base_value,
|
||||
next: { provider_id: null, inherit: true },
|
||||
picked_provider_id: 1,
|
||||
});
|
||||
|
||||
expect(result.inherit).toBe(true);
|
||||
expect(result.fallback_model_ids).toEqual([]);
|
||||
});
|
||||
|
||||
test("keeps fallback models when provider selection has not changed", () => {
|
||||
const result = nextHarnessProviderValue({
|
||||
value: base_value,
|
||||
next: { provider_id: 1, inherit: false },
|
||||
picked_provider_id: 1,
|
||||
});
|
||||
|
||||
expect(result.model_id).toBe(10);
|
||||
expect(result.fallback_model_ids).toEqual([11, 12]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { HarnessFormValue } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The current harness form state before the provider selection change.
|
||||
*/
|
||||
value: HarnessFormValue;
|
||||
/**
|
||||
* The new provider id and inherit state selected by the user.
|
||||
*/
|
||||
next: { provider_id: number | null; inherit: boolean };
|
||||
/**
|
||||
* The provider id of the currently picked model, if any.
|
||||
*/
|
||||
picked_provider_id?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Calculates the next harness form value when the model provider changes.
|
||||
*
|
||||
* When the provider changes (including switching between specific providers,
|
||||
* 'any provider', or inherit mode), fallback models are reset to empty to avoid
|
||||
* retaining fallback models from the previous provider configuration.
|
||||
*
|
||||
* The selected model is also cleared if a specific provider is chosen and the
|
||||
* currently picked model does not belong to that provider.
|
||||
*/
|
||||
export default function nextHarnessProviderValue({
|
||||
value,
|
||||
next,
|
||||
picked_provider_id,
|
||||
}: Params): HarnessFormValue {
|
||||
// Detect whether the provider selection or inherit mode actually changed
|
||||
const provider_changed =
|
||||
next.provider_id != value.provider_id ||
|
||||
Boolean(next.inherit) != Boolean(value.inherit);
|
||||
|
||||
// If a specific provider was selected and the picked model does not belong to it, clear the model
|
||||
const should_clear_model = Boolean(
|
||||
next.provider_id && picked_provider_id != next.provider_id,
|
||||
);
|
||||
|
||||
return {
|
||||
...value,
|
||||
...next,
|
||||
// Reset the model if it is invalid under the newly selected provider
|
||||
model_id: should_clear_model ? null : value.model_id,
|
||||
// Reset fallback models when the provider changes
|
||||
fallback_model_ids: provider_changed ? [] : (value.fallback_model_ids || []),
|
||||
// Voice is cleared on provider change as voices are provider/model-specific
|
||||
voice: undefined,
|
||||
};
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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>;
|
||||
|
||||
Reference in New Issue
Block a user