Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c36f8e3736 | ||
|
|
70ef0e6ae2 | ||
|
|
2a7ea3c76b | ||
|
|
7ffce997ce | ||
|
|
d80899b756 | ||
|
|
3671d9b72e | ||
|
|
78d7f66528 | ||
|
|
09b8269ced | ||
|
|
8b30480ceb |
+2
-1
@@ -53,4 +53,5 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
/public/sitemap.xml
|
||||
/public/robots.txt
|
||||
/public/sitemap-chunks/
|
||||
/.tmp
|
||||
/.tmp
|
||||
/.playwright-mcp
|
||||
@@ -88,20 +88,21 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
### Bots, sessions, chat
|
||||
|
||||
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts`.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest; each opening message is cut to `AppData.BotSessionNameMessageChars`, so a pasted brief of tens of thousands of characters costs one naming call, not a second copy of itself), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
|
||||
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
|
||||
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
|
||||
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
|
||||
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
|
||||
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown), checked by the composer before it sends (the reason shows under the input) and again by the route.
|
||||
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown, up to `BotMessageMaxCharsMax`), checked by the composer before it sends (the reason shows under the input) and again by the route (`messageTooLongMessage` says how far over it is and to attach the text as a file). Once stored, a message is never cut: it goes into every turn whole.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
|
||||
- **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), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). 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. 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). The reply's `ask_user`/`suggest_next_steps` and `QuestionsNote` are gated on `attended` (`isHiddenSession`), and a task run's on `can_ask`: a question in a hidden session has no card the user would see (one reached the coordinator as a bare `[question:22]`, its answer never getting back).
|
||||
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`.
|
||||
- **Suggested next steps:** `suggest_next_steps` puts up to `AppData.BotSuggestionMaxSteps` follow-ups under the answer, once per run -> `bot_suggestions` -> `[suggestion:ID]` rendered inline as buttons (`BotSuggestionsRef`); clicking one inserts it into the composer (`ComposerHandle.insertText`, never sends) and nothing waits on it, so it's `shown` in `withTakeOverRefs`, never `refs`, and never sets `needs_you`. For when the work is done and the bot offers follow-ups; when the answer decides what it does next, it's `ask_user`. Same runs as `ask_user`. Both are closing tools (`ClosingToolNames`, `src/harness/tools/closing-tool-names.ts`): the turn that writes the answer and puts the card up ends the run, after the usual `review`, because a reply is only the run's **last** message. Without that, a bot answered with the PR links the user asked for, then called `list_tasks` (which `TaskReminderNote` told it to do after answering), and the user was sent the short "still open" line alone.
|
||||
- **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).
|
||||
- **A user's own long message is cut:** the bubble shows the first twenty lines (`max-h-[25rem]`, the bubble's `leading-5`) with **Read more** under it, and **Show less** puts it back (`use-bubble-clamp.ts` measures the cut text in the browser: `bubbleOverflows`); a pasted prompt should not fill the screen. Only what's shown is cut, so the bot, Copy chat and the export still get every character.
|
||||
- **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.
|
||||
- **Attachments:** uploaded on pick (`upload-attachment.ts`, private `media`, no text kept: a reply reads a document's text from the file), linked via `bot_message_media`. Replies read files of the last `BotReplyAttachmentMessages` messages that have any, and only while they're within `BotReplyAttachmentMaxAgeMessages` of the latest (`liveAttachmentMessages`: one old screenshot, being the last message with files, was re-attached and re-read on every reply for the rest of a long session); older files are only named. An upload's bytes go with its message: whatever deletes messages that carry them (`deleteChatroomRows`, `deleteHookSessionRows`, `prune-bot-hook-events`) unlinks them and deletes a media row nothing else points at (`deleteUnlinkedAttachmentMedia`), and `prune-orphan-media` takes what is left after `AppData.MediaOrphanKeepDays` (both share `UnreferencedMediaSql`). Tasks don't get files yet.
|
||||
- **Thinking row / stop:** `bot-busy-state.ts` decides the row's line and whether Stop shows. Stop (`api/admin/bots/stop.ts`, `stop-bot-jobs`) fails every open job of that bot for the user, aborts the running handler (`job-abort-registry`) and drops late face updates.
|
||||
@@ -219,8 +220,8 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
|
||||
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown and a run assumes `AppData.HarnessUnknownContextWindow`, since a model with no window at all gets 70% of that as its working context no matter what `harness_context_budget_tokens` says.
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and any non-read tool (a write, `computer_bash`) clears what was remembered, so a file read, edited and read again is read again.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **Calling:** `resolveHarnessCandidates` -> `withCandidates` with process-wide cooldowns; errors are `HarnessError`. Order: the pick, the text setting's fallback models (`fallback_model_ids` in its options, up to `AppData.HarnessTextFallbackModelsMax`, any provider), then the free automatic picks (when `fallback` is on). Every failure is logged (`logCandidateFailure`) and benches its model (or provider, for a key or credits) for the model rest (app setting `harness_model_rest_seconds`, Settings > General run limits, default `AppData.HarnessModelRestMs`, or until the setting changes and the app restarts when the rest is unlimited), never longer, even past a `Retry-After`: one failure once left every reply on a weak free model for an hour. A message answered by a model in place of the one ahead of it shows the fallback on its usage chip (`fell_back_from`/`resting` in `token_usages.settings`). Entry points under `text/`, `media/`, `audio/`, `image/`, `embeddings/`. `run-text-loop.ts` sticks to one model (an automatic pick only until the pick or a fallback model has rested), caps steps (`grabHarnessMaxToolSteps`, `grabReplyMaxToolSteps`; routines and hook calls `grabUnattendedMaxToolSteps`, all unlimited by default, so a run's job deadline and its prompt-token budget are what end it; every run limit reads as `RunLimit` in `src/utils/run-limit.ts`, `number` or `"unlimited"`, saved as `-1` on the settings form and `"unlimited"` in `app_settings`; a run is told once, `stepsLowWarningLeft` steps before the wrap up, to save its report, and the wrap up keeps `WrapUpToolNames` (`write_file`, `import_file`, and `start_task` for work the run can't finish: a 20-step reply used for research otherwise left the writing undone and the next reply had the same budget) for a saving-or-hand-off turn before the last turn with no tools, since runs measured to their last step with the report unwritten) and the prompt tokens one run may spend (`grabRunMaxPromptTokens`, 4M by default: at 40M one task run spent 195 turns and 30M tokens re-reading its own notes with the ceiling never in reach; a run is told once, a quarter in and only while it has produced nothing (`commitEarlyNote`, `isWritingTool`, `AppData.HarnessRunTokensCommitShare`), to land one piece of the work, then once at `AppData.HarnessRunTokensWarnShare` of it to land the rest, `tokensLowNote`, then the wrap up). Results are cut keeping their start and their end (`run-tool-call.ts`, `capToolOutput`), never the start alone: a `du`/`find` sweep's totals are its last lines. A read the run already made is answered from that answer (`RepeatableToolNames`, `repeatToolCallKey`, `alreadyRanToolNote`): calling `read_file`, `list_files`, `search_knowledgebase`, `list_tasks` and the like again with the same arguments returns a pointer to the output above instead of running again, and any non-read tool (a write, `computer_bash`) clears what was remembered, so a file read, edited and read again is read again. A call that failed is answered from that failure the same way, past one retry (`toolCallKey`, `AppData.HarnessSameFailureRetries`, `failedToolCallNote`): five identical failing commands once cost five turns, each resending the whole transcript. A turn that wrote a message and then called any other tool is told once that the message never went out (`answerNotSentNote`), since only the last one is sent: a run that doesn't know ends with the tail of an answer it already wrote.
|
||||
- **Token use:** every turn resends the system prompt, tool definitions and whole transcript, so a run's cost grows with its length squared (production lost 39M tokens on one routine run on a 1M-window model that never trimmed). Keep turns small: `fitTranscriptToContext` trims to the working context (`grabContextBudgetTokens`, never just the window), cutting in one block down to 60% so the cached prefix holds between cuts, and a trimmed tool result keeps its start and its end (`TrimmedKeepChars`) instead of being replaced whole: the old note said "call it again if you still need it", so runs did, paying twice for the same output; **the user's own text is never trimmed** (a request can't be lost mid-run), so a run whose prompt is still over the working context after everything trimmable was cut is told once (`oversizedRequestNote`: work in pieces, don't paste more in, say what it could not reach), and `fitTranscriptToContext` reports it as `over_budget`; only the newest `browser_snapshot` per browser stays (`supersedeToolOutputs`); browser results are capped lower (`HarnessBrowserResultMaxChars`); MCP and user-browser tools are `deferred` (listed by name in the prompt, loaded with `load_tools`) once their definitions pass `HarnessDeferToolsMinChars`, loaded ones appended last. Don't rewrite earlier transcript messages every turn (it breaks providers' prompt caches); `token_usages.cached_tokens` shows what was served from cache. Models that can't take an image/audio part get it read by vision/transcription first (`prepareMessagesForModel`, per candidate). Tool images (screenshots, `read_file` images) are never read by the tool: tools return `{ text, images }`, the loop shows them in a user turn after the results (`toolImagesTurn`, fenced as tool output), and `prepareMessagesForModel` decides. A text model looks at images itself (attachments too) only when its text setting has "Use the model's own media reading" on (`sees_images` in the text harness options, per default/bot/workspace row, `textSeesImages`) and it takes image input: the catalog's `input_modalities` decide, so a custom provider's bare model id gets `guessModelModalities`, which says text-only for anything it doesn't recognise and then `sees_images` reads nothing (the Models page says so under the checkbox, `HarnessSeesImagesNote`, since the setting is otherwise silently useless). Otherwise the vision harness reads them (with the tool's `focus` and `redact`; pixels a seeing model gets can't be redacted). Readings are kept across runs by `MediaReadings` (`HarnessMediaReadingsCached`), keyed by `imageReadingKey`, so the same image is read once rather than once per reply; a reading made to `redact` a secret is never kept there. Only the newest `AppData.HarnessToolImagesKept` stay (`dropOldToolImages`).
|
||||
- **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 at the tool's `timeout_ms` (its own, else `AppData.HarnessToolTimeoutMs`; `null` means no cap, as `computer_bash` has); 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, `read_settings`, `read_message_usage`, `start_task`, `hand_over_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.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.20.0",
|
||||
"version": "0.20.2",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import sessionNameTranscript from "./session-name-transcript";
|
||||
|
||||
describe("sessionNameTranscript", () => {
|
||||
@@ -24,4 +25,25 @@ describe("sessionNameTranscript", () => {
|
||||
expect(transcript).toStartWith("(Summary of the earlier session this one carries on from)\n- Crew set up");
|
||||
expect(transcript).not.toContain("You: - Crew set up");
|
||||
});
|
||||
|
||||
test("names a session once as the opening pasted whole", () => {
|
||||
const brief = "a".repeat(AppData.BotSessionNameMessageChars);
|
||||
|
||||
expect(sessionNameTranscript({ messages: [{ id: 1, author: "user", text: brief }] })).toBe(`User: ${brief}`);
|
||||
});
|
||||
|
||||
test("cuts a pasted brief to its opening, and says it goes on", () => {
|
||||
const brief = "x".repeat(30_000);
|
||||
|
||||
const transcript = sessionNameTranscript({ messages: [{ id: 1, author: "user", text: brief }] });
|
||||
|
||||
expect(transcript).toStartWith(`User: ${brief.slice(0, AppData.BotSessionNameMessageChars)}...`);
|
||||
expect(transcript).toContain("the opening continues");
|
||||
expect(transcript).toContain("30,000 characters in all");
|
||||
expect(transcript.length).toBeLessThan(AppData.BotSessionNameMessageChars + 200);
|
||||
});
|
||||
|
||||
test("says a message carried only files", () => {
|
||||
expect(sessionNameTranscript({ messages: [{ id: 1, author: "user", text: "" }] })).toBe("User: (files only)");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { SessionOpeningMessage } from "@/src/functions/backend/db/bot-sessions/grab-session-opening";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type Params = {
|
||||
messages: SessionOpeningMessage[];
|
||||
@@ -9,13 +10,31 @@ type Params = {
|
||||
* a session the bot moved the conversation into is marked as the earlier
|
||||
* session's, so the title says what this one carries on with rather than
|
||||
* echoing everything the summary recaps.
|
||||
*
|
||||
* Each message is cut to `AppData.BotSessionNameMessageChars`: a pasted
|
||||
* brief of tens of thousands of characters names a session no better than
|
||||
* its first couple of paragraphs, and this is a model call like any other.
|
||||
*/
|
||||
export default function sessionNameTranscript({ messages }: Params) {
|
||||
return messages
|
||||
.map((message) =>
|
||||
message.carried_from_session_id
|
||||
? `(Summary of the earlier session this one carries on from)\n${message.text || ""}`
|
||||
: `${message.author == "user" ? "User" : "You"}: ${message.text || "(files only)"}`,
|
||||
? `(Summary of the earlier session this one carries on from)\n${openingText({ text: message.text })}`
|
||||
: `${message.author == "user" ? "User" : "You"}: ${openingText({ text: message.text })}`,
|
||||
)
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* What the naming turn reads of one message, cut at the limit with a note
|
||||
* so the model knows the opening goes on.
|
||||
*/
|
||||
function openingText({ text }: { text: string | null | undefined }) {
|
||||
const whole = text || "";
|
||||
|
||||
if (whole.length <= AppData.BotSessionNameMessageChars) return whole || "(files only)";
|
||||
|
||||
const cut = whole.slice(0, AppData.BotSessionNameMessageChars);
|
||||
|
||||
return `${cut}... (the opening continues, ${whole.length.toLocaleString("en-US")} characters in all)`;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import SunkenCodeBlock from "./sunken-code-block";
|
||||
|
||||
type Props = {
|
||||
text: string;
|
||||
@@ -12,17 +12,7 @@ type Props = {
|
||||
export default function FilePreviewCode({ text }: Props) {
|
||||
return (
|
||||
<Stack className="grow min-h-0 w-full overflow-auto p-4 items-stretch">
|
||||
<CodeBlock
|
||||
singleBlock
|
||||
backgroundColor="var(--color-sunken)"
|
||||
wrapperProps={{
|
||||
className:
|
||||
"max-w-full! outline-hairline dark:outline-hairline [&_.twui-code-block-header_svg]:stroke-ink-secondary",
|
||||
}}
|
||||
className="font-mono text-[13px] leading-5 text-ink py-2 pl-2 pr-10 whitespace-pre-wrap wrap-anywhere"
|
||||
>
|
||||
{text}
|
||||
</CodeBlock>
|
||||
<SunkenCodeBlock wrapAnywhere>{text}</SunkenCodeBlock>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import SunkenCodeBlock from "./sunken-code-block";
|
||||
|
||||
/**
|
||||
* twui's CodeBlock is a fixed dark block with a white copy icon. Everywhere
|
||||
* the app shows code it wants the theme's sunken surface instead, so this
|
||||
* wrapper is the one place that decides that: a light-mode Details modal
|
||||
* once showed dark-on-dark text because the block stayed `#28272b`.
|
||||
*/
|
||||
describe("SunkenCodeBlock", () => {
|
||||
test("rides the theme's sunken surface", () => {
|
||||
const html = renderToString(<SunkenCodeBlock>ls -la</SunkenCodeBlock>);
|
||||
|
||||
expect(html).toContain("var(--color-sunken)");
|
||||
expect(html).not.toContain("#28272b");
|
||||
expect(html).toContain("outline-hairline");
|
||||
});
|
||||
|
||||
test("draws the copy icon and its label in ink", () => {
|
||||
const html = renderToString(<SunkenCodeBlock>ls</SunkenCodeBlock>);
|
||||
|
||||
expect(html).toContain("stroke-ink-secondary");
|
||||
expect(html).toContain("twui-code-block-copied-text]:text-ink");
|
||||
});
|
||||
|
||||
test("sets code at 13px, and only breaks anywhere when asked", () => {
|
||||
const closing = renderToString(<SunkenCodeBlock>{"a".repeat(40)}</SunkenCodeBlock>);
|
||||
const wrapping = renderToString(<SunkenCodeBlock wrapAnywhere>{"a".repeat(40)}</SunkenCodeBlock>);
|
||||
|
||||
expect(closing).toContain("text-[13px]");
|
||||
expect(closing).not.toContain("wrap-anywhere");
|
||||
expect(wrapping).toContain("wrap-anywhere");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { ReactNode } from "react";
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
children?: ReactNode;
|
||||
/**
|
||||
* Break long words as well as lines, so one unbroken token (a JSON
|
||||
* argument, a long path) never pushes the block wider than its panel.
|
||||
*/
|
||||
wrapAnywhere?: boolean;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A block of code on the theme's sunken surface rather than twui's own dark
|
||||
* block (it defaults to `#28272b`): the surface follows light and dark, so
|
||||
* the text stays legible in both. twui draws the copy icon and its "Copied!"
|
||||
* label white, so both are recoloured to the ink scale, and the block is set
|
||||
* at 13px, the size the dense views around it use.
|
||||
*/
|
||||
export default function SunkenCodeBlock({ children, wrapAnywhere, className }: Props) {
|
||||
return (
|
||||
<CodeBlock
|
||||
singleBlock
|
||||
backgroundColor="var(--color-sunken)"
|
||||
wrapperProps={{
|
||||
className:
|
||||
"max-w-full! outline-hairline dark:outline-hairline [&_.twui-code-block-header_svg]:stroke-ink-secondary [&_.twui-code-block-copied-text]:text-ink",
|
||||
}}
|
||||
className={twMerge(
|
||||
"font-mono text-[13px] leading-5 text-ink py-2 pl-2 pr-10",
|
||||
wrapAnywhere && "whitespace-pre-wrap wrap-anywhere",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</CodeBlock>
|
||||
);
|
||||
}
|
||||
+34
-2
@@ -527,8 +527,36 @@ export const AppData = {
|
||||
* always holds, since step limits are unlimited by default, for runs
|
||||
* whose turns are large. The install may save its own
|
||||
* (`run_max_prompt_tokens`), read through `grabRunMaxPromptTokens`.
|
||||
*
|
||||
* 4M, not 40M: at 40M a run could spend 195 turns re-reading its own
|
||||
* notes and still be under the ceiling, which is what one task run did
|
||||
* (30M tokens, zero rows written, Nov 2026). A run that needs more than
|
||||
* 4M is a run to split, and an install can raise it to
|
||||
* `RunMaxPromptTokensMax`.
|
||||
*/
|
||||
RunMaxPromptTokens: 40_000_000,
|
||||
RunMaxPromptTokens: 4_000_000,
|
||||
/**
|
||||
* Share of its token budget a run is told about, once: past half of
|
||||
* it, every further turn costs what the answer costs, so it lands the
|
||||
* work rather than going on gathering (`tokensLowNote`).
|
||||
*/
|
||||
HarnessRunTokensWarnShare: 0.5,
|
||||
/**
|
||||
* Share of its token budget a run may spend before it is told, once,
|
||||
* that nothing has been produced yet: a quarter in, it still has room
|
||||
* to land the work, and a run that spends the whole budget measuring
|
||||
* ends with a report of what it found and none of what it was asked for
|
||||
* (`commitEarlyNote`). 0 turns it off.
|
||||
*/
|
||||
HarnessRunTokensCommitShare: 0.25,
|
||||
/**
|
||||
* How many times an identical call may fail before the run is answered
|
||||
* from that failure instead of paying for it again: one retry (a
|
||||
* transient error is worth retrying), then the note that the call
|
||||
* itself is wrong. A failing command was once repeated five times in a
|
||||
* row, each repeat resending the whole transcript.
|
||||
*/
|
||||
HarnessSameFailureRetries: 1,
|
||||
/**
|
||||
* The working context: how many tokens (estimated) of system prompt,
|
||||
* tool definitions and transcript a run sends per turn before old tool
|
||||
@@ -870,9 +898,13 @@ export const AppData = {
|
||||
BotSessionSummaryMaxChars: 4000,
|
||||
/**
|
||||
* The first messages of a session the bot reads to name and summarize
|
||||
* it once the first reply is in, and how long its title may be.
|
||||
* it once the first reply is in, how much of each message it reads (a
|
||||
* pasted brief can run to tens of thousands of characters, and the
|
||||
* naming turn is a model call like any other), and how long its title
|
||||
* may be.
|
||||
*/
|
||||
BotSessionNameMessages: 4,
|
||||
BotSessionNameMessageChars: 2000,
|
||||
BotSessionTitleMaxChars: 80,
|
||||
/**
|
||||
* Sessions listed per page in a conversation's sessions modal.
|
||||
|
||||
@@ -72,7 +72,9 @@ You are chatting with the user. Answer their latest messages directly and briefl
|
||||
|
||||
## Keep the work moving
|
||||
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just started a task (its result will offer what's next), or when the user is clearly wrapping up.`;
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just started a task (its result will offer what's next), or when the user is clearly wrapping up.
|
||||
|
||||
Your answer and that card go out together: ask_user and suggest_next_steps end the reply. Anything else you call after writing an answer carries on the run instead, and only the last message of it is sent, so an answer written before that never reaches the user.`;
|
||||
|
||||
/**
|
||||
* Added to every run, chat replies and tasks alike: where its files live,
|
||||
@@ -373,6 +375,84 @@ ${plan.steps.map((step, index) => `${index + 1}. ${step}`).join("\n")}${plan.don
|
||||
export const alreadyRanToolNote = ({ name, step }: { name: string; step: number }) =>
|
||||
`You already called ${name} with these exact arguments on step ${step + 1} of this run, and nothing has changed since. Its output is above: use that instead of calling it again.`;
|
||||
|
||||
/**
|
||||
* What a run gets back instead of paying for the same failure again: an
|
||||
* identical call (same tool, same arguments) that failed, retried once
|
||||
* (`AppData.HarnessSameFailureRetries`), fails the same way, and the error
|
||||
* is almost never about luck: it is the call itself. Nothing that could
|
||||
* have changed the outcome has run since, or the memory would have been
|
||||
* dropped.
|
||||
*/
|
||||
export const failedToolCallNote = ({
|
||||
name,
|
||||
step,
|
||||
attempts,
|
||||
error,
|
||||
}: {
|
||||
name: string;
|
||||
step: number;
|
||||
attempts: number;
|
||||
error: string;
|
||||
}) =>
|
||||
`You called ${name} with these exact arguments ${attempts} times since step ${step + 1} of this run, and it failed the same way each time: ${error}
|
||||
|
||||
Nothing has run since that could change that answer, so calling it once more only buys the same error (and resends this whole conversation). Fix the call itself: change the arguments, do the step it is missing first, or report it as blocked.`;
|
||||
|
||||
/**
|
||||
* Told once to a run that wrote a message for the user and then called a
|
||||
* tool: only the run's last message goes out, so that one never arrived.
|
||||
* Said while the turn carrying the tool's answer is still in the transcript,
|
||||
* so writing it again costs nothing but the tokens. A bot answered "here are
|
||||
* the links", went on to list its tasks, and the user was sent the list
|
||||
* alone (Nov 2026).
|
||||
*/
|
||||
export const answerNotSentNote = `The message you wrote before these tool results was never sent: a run sends only its final message, and you went on to call a tool after writing that one. If the user still needs any of it, write it again in your last message. Don't send work in progress as an answer and then carry on.`;
|
||||
|
||||
/**
|
||||
* Told once, when the prompt no longer fits the working context even after
|
||||
* everything trimmable was trimmed: what is left is what the user wrote,
|
||||
* which the app never cuts. A run that keeps reading whole files into the
|
||||
* conversation only makes the next turn larger, and its answer is paid for
|
||||
* out of whatever room is left. Told rather than trimming the request: the
|
||||
* model has to know it may not be seeing all of a pasted brief, so it says
|
||||
* what it could not reach instead of inventing the rest.
|
||||
*/
|
||||
export const oversizedRequestNote = ({ budget }: { budget: number }) =>
|
||||
`This conversation is already larger than the working context this model may be sent (about ${budget.toLocaleString("en-US")} tokens), and none of what is over is yours to trim: the app cuts tool output, never what the user wrote. Every turn resends all of it, so reading more makes the next one worse.
|
||||
|
||||
From here: stop pulling whole files, whole pages or entire command outputs into the conversation. Work from what you already have, read only the piece you need (a line range, a filter, grep), write what must be kept to a file rather than into a message, and answer on this turn.
|
||||
|
||||
If what you need sits in a part of the request you cannot reach in one piece, say plainly what you could and could not read, and ask the user to attach it as a file, put it in a knowledgebase, or point you at a path. A guess presented as a reading of it is worse than saying it was too long.`;
|
||||
|
||||
/**
|
||||
* Told once, when a run has spent `AppData.HarnessRunTokensWarnShare` of
|
||||
* the prompt tokens it may send: every further turn resends everything, so
|
||||
* what it does from here is paid for out of the answer's budget.
|
||||
*/
|
||||
export const tokensLowNote = ({ left }: { left: number }) =>
|
||||
`You have about ${Math.max(0, Math.round(left)).toLocaleString("en-US")} prompt tokens left in this run, and every further turn resends this whole conversation, so each one costs more than the last. Land the work now: write what you have to a file and finish the rest of the answer from it, or hand the rest on with start_task. Another round of gathering is not worth what is left.`;
|
||||
|
||||
/**
|
||||
* Sent once, a quarter of the way into a run's token budget, when nothing
|
||||
* has been produced yet: no file written, no record changed, nothing handed
|
||||
* on. One task run spent 195 turns and 30M tokens reading its own notes and
|
||||
* writing a single row to the database, because nothing ever asked it when
|
||||
* the work would start; the budget was far too large to arrive as a
|
||||
* deadline (`commitEarlyNote` says it while there is still room).
|
||||
*
|
||||
* It says a run already delivered through a shell reports that instead: the
|
||||
* harness can't tell an `UPDATE` from a `SELECT` (`isWritingTool`).
|
||||
*/
|
||||
export const commitEarlyNote = ({ spent, of }: { spent: number; of: number }) => {
|
||||
const share = Math.round((spent / Math.max(1, of)) * 100);
|
||||
|
||||
return `About ${share}% of this run's prompt-token budget is gone and nothing has been produced yet: no file written, nothing changed, nothing handed on. Reading is not the work.
|
||||
|
||||
Land one piece of what was asked for now, all the way through, before you open anything else: the first row, the first file, the first item of the list. Then the next. A run that finishes with everything understood and nothing delivered has failed at the job, however good the notes are.
|
||||
|
||||
If part of it has already landed some other way (a command that wrote it, a message that sent it), say plainly what landed and carry on from there.`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Added to a chat reply while the bot has runs open in this conversation
|
||||
* that take in what the user writes here: a correction to one reaches it,
|
||||
@@ -417,11 +497,12 @@ Tasks are the crew's to-do list. A task belongs to one bot, on its own list or i
|
||||
*/
|
||||
export const TaskReminderNote = `# Mentioning pending tasks
|
||||
|
||||
You have tasks of your own to keep up with. When the message is an opening ("hello", "what's up"), or after you've answered and propose what's next, call list_tasks and look at what's open.
|
||||
You have tasks of your own to keep up with. When the message is an opening ("hello", "what's up"), or when the work you're answering is done and you're about to offer what comes next, call list_tasks before you write your answer and put the reminder in the answer itself.
|
||||
|
||||
- If something is blocked on the user, or something open plainly connects to what they're asking, mention it in one short line with its status, at most ${AppData.TaskReminderDigestCount} tasks: "Still open: [task:12] send the signed form (blocked: you need to sign it), [task:14] recheck the invoices."
|
||||
- Don't list everything, don't repeat the same reminder reply after reply, and skip it when the user is mid-task, winding down, or you've just asked them a question. A greeting is a good moment; every greeting is not.
|
||||
- Never invent a task: name only what list_tasks returned.`;
|
||||
- Never invent a task: name only what list_tasks returned.
|
||||
- Never send the answer and then call list_tasks: only your last message goes out, so the answer you wrote first would never reach the user. Look first, then answer once.`;
|
||||
|
||||
/**
|
||||
* Added to a chat reply that has `hand_over_task`: a worker hands a task it
|
||||
|
||||
@@ -28,12 +28,50 @@ describe("fitTranscriptToContext", () => {
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 26000 });
|
||||
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 30000 characters of earlier computer_bash output");
|
||||
expect(String(transcript[2]!.content)).toContain("characters of the middle of this computer_bash output");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
expect(transcript[6]!.content).toBe("recent");
|
||||
expect(result.estimated_tokens).toBeLessThanOrEqual(result.budget);
|
||||
});
|
||||
|
||||
test("keeps both ends of what it trimmed, so the run need not call it again", () => {
|
||||
const content = `HEAD${'x'.repeat(30000)}TAIL`;
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "go" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "1", content },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: "second" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "ok" },
|
||||
];
|
||||
|
||||
fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 8000 });
|
||||
|
||||
const trimmed = String(transcript[2]!.content);
|
||||
|
||||
expect(trimmed).toStartWith("HEAD");
|
||||
expect(trimmed).toEndWith("TAIL");
|
||||
expect(trimmed).toContain("than repeating it");
|
||||
expect(trimmed.length).toBeLessThan(content.length);
|
||||
});
|
||||
|
||||
test("says nothing about ends it did not keep, for a short result", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "go" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "1", content: "short answer" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: "second" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "ok" },
|
||||
];
|
||||
|
||||
fitTranscriptToContext({ system: "s", transcript, context_length: 1_000_000, budget_tokens: 50 });
|
||||
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed: 12 characters of this computer_bash output");
|
||||
});
|
||||
|
||||
test("never trims the newest messages, even over budget", () => {
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: "go" },
|
||||
@@ -56,7 +94,7 @@ describe("fitTranscriptToContext", () => {
|
||||
|
||||
expect(result.budget).toBe(15000);
|
||||
expect(result.trimmed).toBe(1);
|
||||
expect(String(transcript[2]!.content)).toStartWith("[Trimmed:");
|
||||
expect(String(transcript[2]!.content)).toContain("[Trimmed:");
|
||||
expect(transcript[4]!.content).toBe(big);
|
||||
});
|
||||
|
||||
@@ -109,4 +147,53 @@ describe("fitTranscriptToContext", () => {
|
||||
|
||||
expect(JSON.parse(call.arguments).trimmed).toContain(`${long.length} characters`);
|
||||
});
|
||||
|
||||
test("never trims the user's own request, however long it is", () => {
|
||||
const request = "Explain this.".repeat(2500);
|
||||
|
||||
const transcript: HarnessMessage[] = [
|
||||
{ role: "user", content: request },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "1", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "1", content: big },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "2", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "2", content: big },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "3", name: "computer_bash", arguments: "{}" }] },
|
||||
{ role: "tool", tool_call_id: "3", content: "recent" },
|
||||
];
|
||||
|
||||
const result = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript,
|
||||
context_length: 131_072,
|
||||
budget_tokens: 12_000,
|
||||
});
|
||||
|
||||
expect(result.trimmed).toBeGreaterThan(0);
|
||||
expect(transcript[0]!.content).toBe(request);
|
||||
expect(String(transcript[2]!.content)).toContain("[Trimmed:");
|
||||
expect(result.over_budget).toBe(true);
|
||||
});
|
||||
|
||||
test("says a transcript it trimmed down fits", () => {
|
||||
const result = fitTranscriptToContext({
|
||||
system: "s",
|
||||
transcript: run(),
|
||||
context_length: 200_000,
|
||||
budget_tokens: 12_000,
|
||||
});
|
||||
|
||||
expect(result.over_budget).toBe(false);
|
||||
expect(result.estimated_tokens).toBeLessThanOrEqual(result.budget);
|
||||
});
|
||||
|
||||
test("says a request nothing can be cut from does not fit", () => {
|
||||
const request = "x".repeat(30_000);
|
||||
const transcript: HarnessMessage[] = [{ role: "user", content: request }];
|
||||
|
||||
const result = fitTranscriptToContext({ system: "s", transcript, context_length: 131_072, budget_tokens: 4_000 });
|
||||
|
||||
expect(result.trimmed).toBe(0);
|
||||
expect(result.over_budget).toBe(true);
|
||||
expect(transcript[0]!.content).toBe(request);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -46,6 +46,14 @@ const CharsPerToken = 3;
|
||||
* What an image or audio part is counted as, in tokens.
|
||||
*/
|
||||
const MediaTokens = 1500;
|
||||
/**
|
||||
* Characters of a trimmed tool result that are kept at each end. A trimmed
|
||||
* result used to be replaced whole, with a note telling the model to call
|
||||
* the tool again if it still needed it, so it did: the same `SELECT`, the
|
||||
* same `cat`, re-run and resent. Keeping the start and the end (the command
|
||||
* and its totals, as `truncate` does) is usually all the run still needs.
|
||||
*/
|
||||
const TrimmedKeepChars = 500;
|
||||
/**
|
||||
* Tool call arguments longer than this (a file written whole) are cut on
|
||||
* the second pass, after the tool results.
|
||||
@@ -58,7 +66,9 @@ const ArgumentsKeepChars = 1500;
|
||||
* working context, or 70% of the window when that is smaller), the
|
||||
* oldest tool results, then long tool call arguments, then the oldest
|
||||
* assistant texts are replaced with a note of what was cut, down to 60%
|
||||
* of the budget. Returns how many messages were trimmed.
|
||||
* of the budget. Returns how many messages were trimmed, and whether the
|
||||
* prompt still doesn't fit (nothing trimmable was left: the conversation
|
||||
* is the user's own text, which is never cut).
|
||||
*/
|
||||
export default function fitTranscriptToContext({
|
||||
system,
|
||||
@@ -76,7 +86,7 @@ export default function fitTranscriptToContext({
|
||||
transcript.reduce((sum, m) => sum + messageTokens({ message: m }), 0);
|
||||
let trimmed = 0;
|
||||
|
||||
if (total <= budget) return { trimmed, estimated_tokens: total, budget };
|
||||
if (total <= budget) return { trimmed, estimated_tokens: total, budget, over_budget: false };
|
||||
|
||||
const target = Math.floor(budget * TrimToShare);
|
||||
const trimmable = transcript.length - keep_last;
|
||||
@@ -90,6 +100,24 @@ export default function fitTranscriptToContext({
|
||||
trimmed++;
|
||||
};
|
||||
|
||||
/**
|
||||
* A tool result cut down to its two ends and a note: the run works from
|
||||
* what it kept, rather than paying for the call again.
|
||||
*/
|
||||
const trimResult = ({ index, content, name }: { index: number; content: string; name: string | undefined }) => {
|
||||
const kept = content.length > TrimmedKeepChars * 4;
|
||||
const head = kept ? content.slice(0, TrimmedKeepChars) : "";
|
||||
const tail = kept ? content.slice(-TrimmedKeepChars) : "";
|
||||
const cut = content.length - head.length - tail.length;
|
||||
const label = name ? `${name} output` : "tool output";
|
||||
|
||||
if (!kept) return `[Trimmed: ${cut} characters of this ${label} to fit the working context.]`;
|
||||
|
||||
const note = `[Trimmed: ${cut} characters of the middle of this ${label} to fit the working context. Its start and end are kept here: work from them, and narrow the call (a smaller range, a filter, one row) rather than repeating it.]`;
|
||||
|
||||
return `${head}\n\n${note}\n\n${tail}`;
|
||||
};
|
||||
|
||||
for (let index = 0; index < trimmable && total > target; index++) {
|
||||
const message = transcript[index]!;
|
||||
|
||||
@@ -101,7 +129,7 @@ export default function fitTranscriptToContext({
|
||||
index,
|
||||
message: {
|
||||
...message,
|
||||
content: `[Trimmed: ${message.content.length} characters of earlier ${name ? `${name} output` : "tool output"} to fit the working context. Call it again if you still need it.]`,
|
||||
content: trimResult({ index, content: message.content, name }),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -147,7 +175,7 @@ export default function fitTranscriptToContext({
|
||||
});
|
||||
}
|
||||
|
||||
return { trimmed, estimated_tokens: total, budget };
|
||||
return { trimmed, estimated_tokens: total, budget, over_budget: total > budget };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import { alreadyRanToolNote, DroppedToolImageNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import { alreadyRanToolNote, answerNotSentNote, DroppedToolImageNote, oversizedRequestNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
|
||||
import HarnessError from "../harness-error";
|
||||
import type { HarnessCandidate, HarnessTool } from "../types";
|
||||
import type { HarnessTrace } from "../trace/types";
|
||||
@@ -38,6 +38,30 @@ const remember: HarnessTool<{ note: string }> = {
|
||||
},
|
||||
};
|
||||
|
||||
const asked: string[] = [];
|
||||
|
||||
const askUser: HarnessTool<{ question: string }> = {
|
||||
name: "ask_user",
|
||||
description: "Asks the user.",
|
||||
schema: z.object({ question: z.string() }),
|
||||
run: async ({ args }) => {
|
||||
asked.push(args.question);
|
||||
return "Asked. The card is under the user's message.";
|
||||
},
|
||||
};
|
||||
|
||||
const suggested: string[] = [];
|
||||
|
||||
const suggestNextSteps: HarnessTool<{ steps: string[] }> = {
|
||||
name: "suggest_next_steps",
|
||||
description: "Offers the next steps as buttons.",
|
||||
schema: z.object({ steps: z.array(z.string()) }),
|
||||
run: async ({ args }) => {
|
||||
suggested.push(...args.steps);
|
||||
return "Suggested. The buttons are under your message.";
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* A fake model that plays back scripted turns and records what it saw.
|
||||
*/
|
||||
@@ -160,7 +184,7 @@ describe("runTextLoop", () => {
|
||||
});
|
||||
expect(seen[0]!.tools?.[0]?.name).toBe("remember");
|
||||
expect(seen[1]!.prefer_key).toBe("1:m");
|
||||
expect(seen[1]!.messages.slice(-2)).toEqual([
|
||||
expect(seen[1]!.messages.slice(-3)).toEqual([
|
||||
{
|
||||
role: "assistant",
|
||||
content: "Noting that.",
|
||||
@@ -169,6 +193,7 @@ describe("runTextLoop", () => {
|
||||
],
|
||||
},
|
||||
{ role: "tool", tool_call_id: "c1", content: "Saved." },
|
||||
{ role: "user", content: answerNotSentNote },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1050,7 +1075,7 @@ describe("runTextLoop trace", () => {
|
||||
});
|
||||
|
||||
expect(result.text).toBe("I'll remember you like tea.");
|
||||
expect(traces.map((entry) => entry.kind)).toEqual(["turn", "tool", "turn"]);
|
||||
expect(traces.map((entry) => entry.kind)).toEqual(["turn", "tool", "event", "turn"]);
|
||||
expect(traces[0]).toMatchObject({
|
||||
kind: "turn",
|
||||
index: 0,
|
||||
@@ -1074,6 +1099,12 @@ describe("runTextLoop trace", () => {
|
||||
});
|
||||
expect((traces[1] as { duration_ms: number }).duration_ms).toBeGreaterThanOrEqual(0);
|
||||
expect(traces[2]).toMatchObject({
|
||||
kind: "event",
|
||||
index: 0,
|
||||
name: "answer_not_sent",
|
||||
text: answerNotSentNote,
|
||||
});
|
||||
expect(traces[3]).toMatchObject({
|
||||
kind: "turn",
|
||||
index: 1,
|
||||
text: "I'll remember you like tea.",
|
||||
@@ -1097,3 +1128,381 @@ describe("runTextLoop trace", () => {
|
||||
expect(result.text).toBe("Done.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop repeated failures", () => {
|
||||
const failing = (id: string) => ({
|
||||
id,
|
||||
name: "computer_bash",
|
||||
arguments: JSON.stringify({ command: "python3 rb.py 22" }),
|
||||
});
|
||||
|
||||
const makeTools = () => {
|
||||
const counts = { commands: 0, writes: 0 };
|
||||
|
||||
const bash: HarnessTool<{ command: string }> = {
|
||||
name: "computer_bash",
|
||||
description: "Runs a command.",
|
||||
schema: z.object({ command: z.string() }),
|
||||
run: async () => {
|
||||
counts.commands++;
|
||||
|
||||
return "Error: Exit code: 1\nFileNotFoundError: plan/0.json";
|
||||
},
|
||||
};
|
||||
const write: HarnessTool<{ path: string }> = {
|
||||
name: "computer_write_file",
|
||||
description: "Writes a file.",
|
||||
schema: z.object({ path: z.string() }),
|
||||
run: async () => {
|
||||
counts.writes++;
|
||||
|
||||
return "Written.";
|
||||
},
|
||||
};
|
||||
|
||||
return { tools: [bash, write], counts };
|
||||
};
|
||||
|
||||
test("answers an identical failing call from its failure, after one retry", async () => {
|
||||
const { tools, counts } = makeTools();
|
||||
const { generate, seen } = scripted([
|
||||
{ tool_calls: [failing("c1")] },
|
||||
{ tool_calls: [failing("c2")] },
|
||||
{ tool_calls: [failing("c3")] },
|
||||
{ text: "Blocked: the engine path is wrong." },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Run it." }],
|
||||
tools,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(counts.commands).toBe(1 + AppData.HarnessSameFailureRetries);
|
||||
expect(result.text).toBe("Blocked: the engine path is wrong.");
|
||||
|
||||
const results = seen[3]!.messages.filter((message) => message.role == "tool");
|
||||
|
||||
expect(String(results[2]!.content)).toContain("failed the same way each time");
|
||||
expect(result.tool_uses.filter((use) => !use.ok)).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("runs the same call again once something could have changed its answer", async () => {
|
||||
const { tools, counts } = makeTools();
|
||||
const { generate } = scripted([
|
||||
{ tool_calls: [failing("c1")] },
|
||||
{ tool_calls: [{ id: "c2", name: "computer_write_file", arguments: `{"path":"plan/22.json"}` }] },
|
||||
{ tool_calls: [failing("c3")] },
|
||||
{ text: "Done." },
|
||||
]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "You are a bot.",
|
||||
messages: [{ role: "user", content: "Set the plan up, then run it." }],
|
||||
tools,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(counts.writes).toBe(1);
|
||||
expect(counts.commands).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop token warning", () => {
|
||||
test("says half the token budget is gone, once", async () => {
|
||||
const turn = {
|
||||
tool_calls: [{ id: "c", name: "remember", arguments: `{"note":"x"}` }],
|
||||
usage: { prompt_tokens: 300, completion_tokens: 1 },
|
||||
};
|
||||
const { generate, seen } = scripted([turn, turn, turn, turn, { text: "Landing it here." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
max_prompt_tokens: 1000,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
const warned = ({ turn }: { turn: number }) =>
|
||||
seen[turn]!.messages.filter(
|
||||
(message) =>
|
||||
message.role == "user" &&
|
||||
typeof message.content == "string" &&
|
||||
message.content.includes("prompt tokens left in this run"),
|
||||
).length;
|
||||
|
||||
expect(warned({ turn: 1 })).toBe(0);
|
||||
expect(warned({ turn: 2 })).toBe(1);
|
||||
expect(warned({ turn: 4 })).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop commit early", () => {
|
||||
const reading = (id: string) => ({
|
||||
tool_calls: [{ id, name: "remember", arguments: `{"note":"x"}` }],
|
||||
usage: { prompt_tokens: 300, completion_tokens: 1 },
|
||||
});
|
||||
const wrote = (id: string) => ({
|
||||
tool_calls: [{ id, name: "write_file", arguments: "{}" }],
|
||||
usage: { prompt_tokens: 300, completion_tokens: 1 },
|
||||
});
|
||||
const write_file: HarnessTool = {
|
||||
name: "write_file",
|
||||
description: "Writes a file.",
|
||||
schema: z.object({}),
|
||||
run: async () => "Written.",
|
||||
};
|
||||
const committed = ({ turn, seen }: { turn: number; seen: GenerateTextParams[] }) =>
|
||||
seen[turn]!.messages.filter(
|
||||
(message) =>
|
||||
message.role == "user" &&
|
||||
typeof message.content == "string" &&
|
||||
message.content.includes("nothing has been produced yet"),
|
||||
).length;
|
||||
|
||||
test("tells a run that has only been reading to land a piece of the work, once", async () => {
|
||||
const { generate, seen } = scripted([reading("a"), reading("b"), reading("c"), { text: "Done." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
max_prompt_tokens: 1000,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(committed({ turn: 0, seen })).toBe(0);
|
||||
expect(committed({ turn: 1, seen })).toBe(1);
|
||||
expect(committed({ turn: 3, seen })).toBe(1);
|
||||
});
|
||||
|
||||
test("says nothing to a run that has already written something", async () => {
|
||||
const { generate, seen } = scripted([wrote("a"), wrote("b"), wrote("c"), { text: "Done." }]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [write_file],
|
||||
max_prompt_tokens: 1000,
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(committed({ turn: 1, seen })).toBe(0);
|
||||
expect(committed({ turn: 3, seen })).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop closing tools", () => {
|
||||
test("ends the run on the turn that answers and asks the user", async () => {
|
||||
asked.length = 0;
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "Eight articles are left: five in batch 2 and three in batch 3.",
|
||||
tool_calls: [
|
||||
{ id: "q1", name: "ask_user", arguments: `{"question":"Which date rule?"}` },
|
||||
],
|
||||
},
|
||||
{ text: "Still waiting on your answer." },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "How many articles are left?" }],
|
||||
tools: [askUser, remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Eight articles are left: five in batch 2 and three in batch 3.");
|
||||
expect(result.steps).toBe(1);
|
||||
expect(seen.length).toBe(1);
|
||||
expect(asked).toEqual(["Which date rule?"]);
|
||||
});
|
||||
|
||||
test("ends the run on the turn that answers and offers what's next", async () => {
|
||||
suggested.length = 0;
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "PR #4: https://git.tben.me/Summit-Lending/main-site/pulls/4",
|
||||
tool_calls: [
|
||||
{ id: "s1", name: "suggest_next_steps", arguments: `{"steps":["Commit task 50"]}` },
|
||||
],
|
||||
},
|
||||
{ text: "Still open on my list: task 44, task 50." },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Send me the PR links." }],
|
||||
tools: [suggestNextSteps, remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("PR #4: https://git.tben.me/Summit-Lending/main-site/pulls/4");
|
||||
expect(result.steps).toBe(1);
|
||||
expect(seen.length).toBe(1);
|
||||
expect(suggested).toEqual(["Commit task 50"]);
|
||||
});
|
||||
|
||||
test("checks the answer before it goes out, and writes it again when the review sends it back", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "Done: [file:99] has all of it.",
|
||||
tool_calls: [{ id: "q1", name: "ask_user", arguments: `{"question":"Next?"}` }],
|
||||
},
|
||||
{
|
||||
text: "Done: [file:12] has all of it.",
|
||||
tool_calls: [{ id: "q2", name: "ask_user", arguments: `{"question":"Next?"}` }],
|
||||
},
|
||||
]);
|
||||
const notes = ["You named [file:99], which isn't there for the user."];
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "File it." }],
|
||||
tools: [askUser],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
review: async () => notes.shift() || null,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Done: [file:12] has all of it.");
|
||||
expect(result.steps).toBe(2);
|
||||
expect(seen[1]!.messages.at(-1)).toEqual({
|
||||
role: "user",
|
||||
content: "You named [file:99], which isn't there for the user.",
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps going when the card comes with real work", async () => {
|
||||
asked.length = 0;
|
||||
const { generate } = scripted([
|
||||
{
|
||||
text: "Saved your preference and put the question up.",
|
||||
tool_calls: [
|
||||
{ id: "c1", name: "remember", arguments: `{"note":"links"}` },
|
||||
{ id: "q1", name: "ask_user", arguments: `{"question":"Which repo?"}` },
|
||||
],
|
||||
},
|
||||
{ text: "Noted. The question is under this message." },
|
||||
]);
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "Always send me the links." }],
|
||||
tools: [askUser, remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Noted. The question is under this message.");
|
||||
expect(result.steps).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop answer not sent", () => {
|
||||
test("says once that a message written before a tool call never went out", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{
|
||||
text: "Here are the links.",
|
||||
tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"tea"}` }],
|
||||
},
|
||||
{
|
||||
text: "And the rest.",
|
||||
tool_calls: [{ id: "c2", name: "remember", arguments: `{"note":"coffee"}` }],
|
||||
},
|
||||
{ text: "Here are the links. And the rest." },
|
||||
]);
|
||||
|
||||
const told = ({ turn }: { turn: number }) =>
|
||||
seen[turn]!.messages.filter((message) => message.content == answerNotSentNote).length;
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("Here are the links. And the rest.");
|
||||
expect(told({ turn: 1 })).toBe(1);
|
||||
expect(told({ turn: 2 })).toBe(1);
|
||||
});
|
||||
|
||||
test("says nothing when the turn made no tool call", async () => {
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "The answer.", tool_calls: [] },
|
||||
]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
});
|
||||
|
||||
expect(seen.length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runTextLoop over budget", () => {
|
||||
test("tells a run whose own request is over the working context, once", async () => {
|
||||
const brief = "x".repeat(30_000);
|
||||
const note = oversizedRequestNote({ budget: 4_000 });
|
||||
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "One piece.", tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"a"}` }] },
|
||||
{ text: "The answer." },
|
||||
]);
|
||||
|
||||
const told = ({ turn }: { turn: number }) =>
|
||||
seen[turn]!.messages.filter((message) => String(message.content).includes(note)).length;
|
||||
|
||||
const result = await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: brief }],
|
||||
tools: [remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
context_budget: 4_000,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("The answer.");
|
||||
expect(told({ turn: 0 })).toBe(1);
|
||||
expect(told({ turn: 1 })).toBe(1);
|
||||
expect(seen[1]!.messages.some((message) => String(message.content).includes(brief))).toBe(true);
|
||||
});
|
||||
|
||||
test("says nothing when the transcript fits, or when trimming was enough", async () => {
|
||||
const note = oversizedRequestNote({ budget: 20_000 });
|
||||
|
||||
const { generate, seen } = scripted([
|
||||
{ text: "One.", tool_calls: [{ id: "c1", name: "remember", arguments: `{"note":"a"}` }] },
|
||||
{ text: "Two.", tool_calls: [{ id: "c2", name: "remember", arguments: `{"note":"b"}` }] },
|
||||
{ text: "The answer." },
|
||||
]);
|
||||
|
||||
await runTextLoop({
|
||||
system: "s",
|
||||
messages: [{ role: "user", content: "go" }],
|
||||
tools: [remember],
|
||||
generate,
|
||||
resolveCandidates,
|
||||
context_budget: 20_000,
|
||||
});
|
||||
|
||||
expect(seen.flatMap((turn) => turn.messages).some((message) => String(message.content).includes(note))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { alreadyRanToolNote } from "@/src/data/harness-prompts";
|
||||
import {
|
||||
alreadyRanToolNote,
|
||||
answerNotSentNote,
|
||||
commitEarlyNote,
|
||||
failedToolCallNote,
|
||||
oversizedRequestNote,
|
||||
tokensLowNote,
|
||||
} from "@/src/data/harness-prompts";
|
||||
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
|
||||
import HarnessError from "../harness-error";
|
||||
import isClosingTool from "../tools/closing-tool-names";
|
||||
import resolveHarnessCandidates from "../resolve/resolve-harness-candidates";
|
||||
import loadToolsTool from "../tools/load-tools-tool";
|
||||
import repeatToolCallKey from "../tools/repeat-tool-call-key";
|
||||
import repeatToolCallKey, { toolCallKey } from "../tools/repeat-tool-call-key";
|
||||
import isRepeatableTool from "../tools/repeatable-tool-names";
|
||||
import runToolCall from "../tools/run-tool-call";
|
||||
import type { ToolCallResult } from "../tools/run-tool-call";
|
||||
import toolDefinition from "../tools/tool-definition";
|
||||
import isWritingTool from "../tools/writing-tool-names";
|
||||
import type { HarnessTrace, HarnessTracer } from "../trace/types";
|
||||
import type {
|
||||
HarnessCandidate,
|
||||
@@ -327,6 +337,16 @@ export default async function runTextLoop({
|
||||
* read again.
|
||||
*/
|
||||
const repeated_reads = new Map<string, number>();
|
||||
/**
|
||||
* The calls that failed, by the call they answer (`toolCallKey`), with
|
||||
* the step the first of them ran on and the error it gave. An identical
|
||||
* call past `AppData.HarnessSameFailureRetries` is answered from here
|
||||
* instead of being run: it fails the same way, and each repeat resends
|
||||
* the whole transcript (one run paid five times for the same
|
||||
* `FileNotFoundError`). Anything that could change the outcome clears
|
||||
* them, so a call retried after the missing piece was put in place runs.
|
||||
*/
|
||||
const failed_calls = new Map<string, { step: number; attempts: number; error: string }>();
|
||||
/**
|
||||
* The tools a wrap up may still call: what saves the work, and
|
||||
* `start_task` for the work it can't finish. A run that spent every
|
||||
@@ -358,7 +378,39 @@ export default async function runTextLoop({
|
||||
const warn_at = isUnlimitedLimit(max_steps) ? 0 : stepsLowWarningLeft({ max_steps });
|
||||
let prefer_key: string | undefined;
|
||||
let reviewed = false;
|
||||
/**
|
||||
* A run that wrote a message and then called a tool has been told, once,
|
||||
* that the message never went out (`answerNotSentNote`).
|
||||
*/
|
||||
let told_answer_lost = false;
|
||||
/**
|
||||
* A run whose prompt no longer fits the working context, with nothing
|
||||
* trimmable left, has been told, once (`oversizedRequestNote`).
|
||||
*/
|
||||
let told_over_budget = false;
|
||||
let warned_steps = isUnlimitedLimit(max_steps) || max_steps < AppData.HarnessStepsLowMinSteps;
|
||||
/**
|
||||
* The prompt tokens past which the run is told to land the work
|
||||
* (`AppData.HarnessRunTokensWarnShare` of its budget), and whether it has
|
||||
* been told. A run with no token budget has none to be near the end of.
|
||||
*/
|
||||
const tokens_warn_at =
|
||||
typeof max_prompt_tokens == "number" && max_prompt_tokens > 0
|
||||
? Math.floor(max_prompt_tokens * AppData.HarnessRunTokensWarnShare)
|
||||
: Infinity;
|
||||
let warned_tokens = tokens_warn_at == Infinity;
|
||||
/**
|
||||
* A quarter of the budget with nothing produced yet: research is not
|
||||
* progress, and a run that spends the whole budget reading lands its
|
||||
* report but none of the work (one task run did exactly that: 195
|
||||
* turns, 30M tokens, zero rows written, Nov 2026). Said once, while
|
||||
* there is still budget to land the rest.
|
||||
*/
|
||||
const commits_at =
|
||||
typeof max_prompt_tokens == "number" && max_prompt_tokens > 0
|
||||
? Math.floor(max_prompt_tokens * AppData.HarnessRunTokensCommitShare)
|
||||
: Infinity;
|
||||
let told_to_commit = commits_at == Infinity;
|
||||
/**
|
||||
* The wrap up is announced once, and may save until it has: a run told
|
||||
* to stop with its report unwritten gets a turn to write it (at most
|
||||
@@ -439,7 +491,7 @@ export default async function runTextLoop({
|
||||
*/
|
||||
const model = (candidates.find((c) => c.key == prefer_key) || candidates[0])?.model;
|
||||
|
||||
fitTranscriptToContext({
|
||||
const fit = fitTranscriptToContext({
|
||||
system: run_system,
|
||||
transcript,
|
||||
context_length: model?.context_length || AppData.HarnessUnknownContextWindow,
|
||||
@@ -447,6 +499,21 @@ export default async function runTextLoop({
|
||||
tools_chars: JSON.stringify(definitions).length,
|
||||
});
|
||||
|
||||
/**
|
||||
* Everything trimmable was trimmed and it still doesn't fit: what is
|
||||
* over is what the user wrote, which is never cut. Told once, so it
|
||||
* works in pieces and says what it could not reach instead of
|
||||
* inventing the rest (`oversizedRequestNote`).
|
||||
*/
|
||||
if (fit.over_budget && !told_over_budget) {
|
||||
told_over_budget = true;
|
||||
|
||||
const note = oversizedRequestNote({ budget: fit.budget });
|
||||
|
||||
pushUserTurn({ transcript, content: note });
|
||||
await traced({ kind: "event", index, name: "over_budget", text: note });
|
||||
}
|
||||
|
||||
const turn_started_at = Date.now();
|
||||
|
||||
const answer = await generate({
|
||||
@@ -563,6 +630,10 @@ export default async function runTextLoop({
|
||||
for (const call of tool_calls) {
|
||||
const repeat_key = repeatToolCallKey({ call });
|
||||
const already_read = repeat_key ? repeated_reads.get(repeat_key) : undefined;
|
||||
const call_key = toolCallKey({ call });
|
||||
const failed_before = call_key ? failed_calls.get(call_key) : undefined;
|
||||
const give_up =
|
||||
failed_before !== undefined && failed_before.attempts > AppData.HarnessSameFailureRetries;
|
||||
|
||||
const result: ToolCallResult =
|
||||
already_read !== undefined
|
||||
@@ -571,9 +642,21 @@ export default async function runTextLoop({
|
||||
images: [],
|
||||
duration_ms: 0,
|
||||
}
|
||||
: await runToolCall({ call, tools: run_tools, signal });
|
||||
: give_up
|
||||
? {
|
||||
text: failedToolCallNote({
|
||||
name: call.name,
|
||||
step: failed_before.step,
|
||||
attempts: failed_before.attempts,
|
||||
error: failed_before.error,
|
||||
}),
|
||||
images: [],
|
||||
duration_ms: 0,
|
||||
}
|
||||
: await runToolCall({ call, tools: run_tools, signal });
|
||||
|
||||
const { text: content, images } = result;
|
||||
const ok = !give_up && !content.startsWith("Error:");
|
||||
|
||||
/**
|
||||
* A deferred tool called without loading it ran all the same;
|
||||
@@ -583,7 +666,7 @@ export default async function runTextLoop({
|
||||
loaded.push(call.name);
|
||||
}
|
||||
|
||||
tool_uses.push({ name: call.name, ok: !content.startsWith("Error:") });
|
||||
tool_uses.push({ name: call.name, ok });
|
||||
|
||||
await traced({
|
||||
kind: "tool",
|
||||
@@ -591,10 +674,10 @@ export default async function runTextLoop({
|
||||
name: call.name,
|
||||
arguments: call.arguments,
|
||||
result: content,
|
||||
ok: !content.startsWith("Error:"),
|
||||
ok,
|
||||
images: images.length,
|
||||
duration_ms: result.duration_ms,
|
||||
repeat_of: already_read ?? null,
|
||||
repeat_of: (give_up ? failed_before.step : already_read) ?? null,
|
||||
});
|
||||
|
||||
if (!repeat_key) {
|
||||
@@ -604,11 +687,61 @@ export default async function runTextLoop({
|
||||
else repeated_reads.set(repeat_key, index);
|
||||
}
|
||||
|
||||
if (give_up) {
|
||||
failed_calls.set(call_key!, { ...failed_before, attempts: failed_before.attempts + 1 });
|
||||
} else if (content.startsWith("Error:")) {
|
||||
if (call_key) {
|
||||
const earlier = failed_calls.get(call_key);
|
||||
|
||||
failed_calls.set(call_key, {
|
||||
step: earlier?.step ?? index,
|
||||
attempts: (earlier?.attempts ?? 0) + 1,
|
||||
error: earlier?.error ?? clipFailure({ text: content }),
|
||||
});
|
||||
}
|
||||
} else if (!call_key || !isRepeatableTool({ name: call.name })) {
|
||||
failed_calls.clear();
|
||||
}
|
||||
|
||||
transcript.push({ role: "tool", tool_call_id: call.id, content });
|
||||
|
||||
if (images.length) shown.push({ tool_name: call.name, images });
|
||||
}
|
||||
|
||||
/**
|
||||
* An answer that ends on a card is the whole reply: the question
|
||||
* waits for the user, and what comes next was just offered. Going on
|
||||
* would send the next turn's short line in its place, since the reply
|
||||
* is only the run's last message (`ClosingToolNames`).
|
||||
*/
|
||||
if (answer.text && tool_calls.every((call) => isClosingTool({ name: call.name }))) {
|
||||
/**
|
||||
* Checked before it goes out, as any reply is: a note comes
|
||||
* back and the answer is written again (the card stays on the
|
||||
* reply, its ref is already recorded).
|
||||
*/
|
||||
if (review && !reviewed) {
|
||||
reviewed = true;
|
||||
|
||||
const note = await review({ text: answer.text, tool_uses }).catch(() => null);
|
||||
|
||||
if (note) {
|
||||
await traced({ kind: "event", index, name: "review", text: note });
|
||||
pushUserTurn({ transcript, content: note });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
text: answer.text,
|
||||
messages: transcript,
|
||||
steps: index + 1,
|
||||
candidate: answer.candidate,
|
||||
usage,
|
||||
tool_uses,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Screenshots and other tool images follow the results in a user
|
||||
* turn. A model that sees gets them as they are when the text
|
||||
@@ -628,6 +761,44 @@ export default async function runTextLoop({
|
||||
|
||||
await takeIncoming({ note: incoming_notes?.working || IncomingMessagesNote, index });
|
||||
|
||||
/**
|
||||
* The run wrote for the user and then carried on: that message never
|
||||
* goes out, and a run that doesn't know it ends with the tail of an
|
||||
* answer it already wrote. Told once, with the message still in the
|
||||
* transcript to write again.
|
||||
*/
|
||||
if (!told_answer_lost && answer.text) {
|
||||
told_answer_lost = true;
|
||||
|
||||
pushUserTurn({ transcript, content: answerNotSentNote });
|
||||
await traced({ kind: "event", index, name: "answer_not_sent", text: answerNotSentNote });
|
||||
}
|
||||
|
||||
/**
|
||||
* What this turn spent: past the budget, the wrap up says it better
|
||||
* (`wrapUpPrompt`) than either note below.
|
||||
*/
|
||||
const spent_out =
|
||||
typeof max_prompt_tokens == "number" && max_prompt_tokens > 0 && usage.prompt_tokens >= max_prompt_tokens;
|
||||
|
||||
/**
|
||||
* Something produced, or a quarter of the budget gone without it:
|
||||
* said before the steps are nearly out, so a run still has room to
|
||||
* land the work rather than reporting on it. A run that has written
|
||||
* anything at all is left alone; one that landed its work through a
|
||||
* shell says so (`commitEarlyNote`).
|
||||
*/
|
||||
if (tool_uses.some((used) => used.ok && isWritingTool({ name: used.name }))) told_to_commit = true;
|
||||
|
||||
if (!told_to_commit && !spent_out && usage.prompt_tokens >= commits_at) {
|
||||
told_to_commit = true;
|
||||
|
||||
const note = commitEarlyNote({ spent: usage.prompt_tokens, of: max_prompt_tokens as number });
|
||||
|
||||
pushUserTurn({ transcript, content: note });
|
||||
await traced({ kind: "event", index, name: "commit_early", text: note });
|
||||
}
|
||||
|
||||
/**
|
||||
* Steps left before the wrap up, once the next turn is taken.
|
||||
* An unlimited run is never told it's nearly out: it has no budget
|
||||
@@ -640,6 +811,21 @@ export default async function runTextLoop({
|
||||
pushUserTurn({ transcript, content: stepsLowNote({ left }) });
|
||||
await traced({ kind: "event", index, name: "steps_low", text: stepsLowNote({ left }) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Half the token budget gone, once: every further turn resends this
|
||||
* whole conversation, so what the run does next is paid for out of
|
||||
* the answer. Skipped when the turn just spent the budget out: the
|
||||
* wrap up says it better (`wrapUpPrompt`).
|
||||
*/
|
||||
if (!warned_tokens && !spent_out && usage.prompt_tokens >= tokens_warn_at) {
|
||||
warned_tokens = true;
|
||||
|
||||
const tokens_left = (max_prompt_tokens as number) - usage.prompt_tokens;
|
||||
|
||||
pushUserTurn({ transcript, content: tokensLowNote({ left: tokens_left }) });
|
||||
await traced({ kind: "event", index, name: "tokens_low", text: tokensLowNote({ left: tokens_left }) });
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Unreachable: the text loop ended without an answer.`);
|
||||
@@ -673,3 +859,16 @@ export default async function runTextLoop({
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Characters of a failure a repeated call's note keeps: a failing command
|
||||
* can print a whole traceback, and the note is resent with every turn
|
||||
* after it.
|
||||
*/
|
||||
const FailureNoteChars = 400;
|
||||
|
||||
/**
|
||||
* The error a repeated call's note reuses, cut to `FailureNoteChars`.
|
||||
*/
|
||||
const clipFailure = ({ text }: { text: string }) =>
|
||||
text.length <= FailureNoteChars ? text : `${text.slice(0, FailureNoteChars)}...`;
|
||||
|
||||
@@ -28,15 +28,16 @@ type Args = {
|
||||
/**
|
||||
* Offers the user concrete next steps as buttons under the bot's answer.
|
||||
* Clicking one puts it in their input; nothing waits on it, unlike
|
||||
* `ask_user`, so the reply goes on as usual. Once per run, so every
|
||||
* suggestion lands in one row.
|
||||
* `ask_user`. Once per run, so every suggestion lands in one row. It ends
|
||||
* the reply (`ClosingToolNames`): the buttons belong under the answer, and
|
||||
* a run that kept going would replace that answer with a later line.
|
||||
*/
|
||||
export default function suggestNextStepsTool({ user_id, bot_id, session_id, workspace_id, onSuggest }: Params): HarnessTool<Args> {
|
||||
let suggested = false;
|
||||
|
||||
return {
|
||||
name: "suggest_next_steps",
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Use it once the work is done or a reply is complete, to make follow-ups one click away (your best suggestion first). This never waits for a response: don't ask the user to pick one, don't put the answers on hold, and carry on as if they may ignore it. When their answer decides what you do next, use ask_user instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
description: `Offer the user next steps they can take from here, shown as buttons under your answer: clicking one puts it in their input for them to send. Use it once the work is done or a reply is complete, to make follow-ups one click away (your best suggestion first). This never waits for a response: don't ask the user to pick one, don't put the answers on hold, and put it up in the same turn as the answer it belongs under. When their answer decides what you do next, use ask_user instead. Don't suggest what they already asked for, and don't repeat the steps in your text.`,
|
||||
schema: z.object({
|
||||
title: z
|
||||
.string()
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Tools a run ends on: they put a card under the answer and expect nothing
|
||||
* after them. `ask_user` waits for the user's answer, and
|
||||
* `suggest_next_steps` is offered when the work is done, so a turn that
|
||||
* writes the reply and asks, or offers what comes next, has said everything
|
||||
* it has to say.
|
||||
*
|
||||
* `runTextLoop` reads this to end the run on that turn, because the reply is
|
||||
* only the run's last message. A run that went on after answering sent
|
||||
* whatever it wrote last instead: a bot wrote out the PR links the user
|
||||
* asked for, then called `list_tasks` (which `TaskReminderNote` told it to
|
||||
* do after answering), and the user got the short "still open" line with no
|
||||
* links in it (Nov 2026).
|
||||
*/
|
||||
export const ClosingToolNames: readonly string[] = ["ask_user", "suggest_next_steps"];
|
||||
|
||||
/**
|
||||
* Whether a call to this tool ends the run when it carries the answer.
|
||||
*/
|
||||
export default function isClosingTool({ name }: { name: string }) {
|
||||
return ClosingToolNames.includes(name);
|
||||
}
|
||||
@@ -4,13 +4,14 @@ import isRepeatableTool from "./repeatable-tool-names";
|
||||
/**
|
||||
* What makes two calls the same call: the tool and its arguments, whatever
|
||||
* order the model wrote their keys in (a model re-reads a file it read
|
||||
* before with the same fields in another order). Null for a tool whose
|
||||
* answer may change, and for arguments that aren't a JSON object, which
|
||||
* `runToolCall` turns down anyway.
|
||||
* before with the same fields in another order). Null for arguments that
|
||||
* aren't a JSON object, which `runToolCall` turns down anyway.
|
||||
*
|
||||
* Every tool has one, not only the reads: a failing call repeated word for
|
||||
* word is answered from its failure (`runTextLoop`), since it fails the
|
||||
* same way rather than by luck.
|
||||
*/
|
||||
export default function repeatToolCallKey({ call }: { call: HarnessToolCall }): string | null {
|
||||
if (!isRepeatableTool({ name: call.name })) return null;
|
||||
|
||||
export function toolCallKey({ call }: { call: HarnessToolCall }): string | null {
|
||||
let args: unknown;
|
||||
|
||||
try {
|
||||
@@ -24,6 +25,16 @@ export default function repeatToolCallKey({ call }: { call: HarnessToolCall }):
|
||||
return `${call.name}:${JSON.stringify(sortKeys({ value: args }))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What makes two reads the same read: null for a tool whose answer may
|
||||
* change (anything with a side effect), which is answered by running it.
|
||||
*/
|
||||
export default function repeatToolCallKey({ call }: { call: HarnessToolCall }): string | null {
|
||||
if (!isRepeatableTool({ name: call.name })) return null;
|
||||
|
||||
return toolCallKey({ call });
|
||||
}
|
||||
|
||||
/**
|
||||
* The value with every object's keys sorted, so two spellings of the same
|
||||
* arguments compare equal.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import isWritingTool, { WritingToolNames } from "./writing-tool-names";
|
||||
|
||||
test("counts the tools that leave something behind", () => {
|
||||
for (const name of ["write_file", "import_file", "computer_edit_file", "update_task", "start_task", "set_picture"]) {
|
||||
expect(isWritingTool({ name })).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("counts none of the tools that only read", () => {
|
||||
for (const name of ["read_file", "list_files", "computer_read_file", "list_tasks", "search_computers", "load_tools"]) {
|
||||
expect(isWritingTool({ name })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("leaves computer_bash out, so a shell-driven run can still be told to land the work", () => {
|
||||
expect(isWritingTool({ name: "computer_bash" })).toBe(false);
|
||||
expect(WritingToolNames.includes("computer_bash")).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Tools that leave something behind: a file written, a record changed, a
|
||||
* graphic or a picture made, work handed on. `runTextLoop` reads this to
|
||||
* tell a run that has produced something from one that has only been
|
||||
* reading, so a run measuring its way through a whole budget is told to
|
||||
* land a piece of the work while there is still room (`commitEarlyNote`).
|
||||
*
|
||||
* `computer_bash` is deliberately not here: it is the one tool that both
|
||||
* reads and writes (a `SELECT` and an `UPDATE` look the same to the
|
||||
* harness), so counting it would let a shell-driven run research its way to
|
||||
* the ceiling and never be told. A run that has already landed work that
|
||||
* way says so in its answer, and the note asks it to.
|
||||
*/
|
||||
export const WritingToolNames: readonly string[] = [
|
||||
"write_file",
|
||||
"import_file",
|
||||
"copy_file",
|
||||
"move_file",
|
||||
"delete_file",
|
||||
"computer_write_file",
|
||||
"computer_edit_file",
|
||||
"make_pdf",
|
||||
"create_graphic",
|
||||
"update_graphic",
|
||||
"set_picture",
|
||||
"transform_image",
|
||||
"generate_image",
|
||||
"generate_video",
|
||||
"create_task",
|
||||
"update_task",
|
||||
"delete_task",
|
||||
"create_schedule",
|
||||
"update_schedule",
|
||||
"delete_schedule",
|
||||
"hand_over_schedule",
|
||||
"hand_over_task",
|
||||
"update_memory",
|
||||
"update_instructions",
|
||||
"set_bot_workspace_instructions",
|
||||
"capture_secret",
|
||||
"request_install",
|
||||
"answer_install_request",
|
||||
"start_task",
|
||||
"delegate_task",
|
||||
"ask_crew",
|
||||
"create_bot",
|
||||
"update_bot",
|
||||
"delete_bot",
|
||||
"create_workspace",
|
||||
"update_workspace",
|
||||
"delete_workspace",
|
||||
"add_bot_to_workspace",
|
||||
"remove_bot_from_workspace",
|
||||
"assign_computer",
|
||||
"set_workspace_computer",
|
||||
"set_bot_type",
|
||||
"set_extension_access",
|
||||
"set_user_workspace_role",
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether a successful call to this tool produced something.
|
||||
*/
|
||||
export default function isWritingTool({ name }: { name: string }) {
|
||||
return WritingToolNames.includes(name);
|
||||
}
|
||||
@@ -33,8 +33,9 @@ export type HarnessToolTrace = {
|
||||
images: number;
|
||||
duration_ms: number;
|
||||
/**
|
||||
* The step whose identical read answered this call, when the loop
|
||||
* skipped it (`alreadyRanToolNote`).
|
||||
* The step this call was answered from instead of being run: the one
|
||||
* whose identical read answered it (`alreadyRanToolNote`), or the one
|
||||
* whose identical failure did (`failedToolCallNote`).
|
||||
*/
|
||||
repeat_of?: number | null;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState, type RefObject } from "react";
|
||||
import bubbleOverflows from "../(utils)/bubble-overflow";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The message's text: a different message is measured again and starts
|
||||
* closed.
|
||||
*/
|
||||
text: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a user's own message is taller than the room it shows, and
|
||||
* whether the user opened the rest of it. A pasted prompt can run for
|
||||
* pages; the bubble cuts it, so it no longer pushes the conversation it
|
||||
* belongs to off the screen, and "Read more" opens the whole of it.
|
||||
* Measured in the browser only: the server has no layout, so the first
|
||||
* render shows the text cut and no button.
|
||||
*/
|
||||
export default function useBubbleClamp({ text }: Params) {
|
||||
const content_ref = useRef<HTMLDivElement | null>(null);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [overflows, setOverflows] = useState(false);
|
||||
/** An opened message shows all of its text, so it has nothing to cut. */
|
||||
const open = useRef(false);
|
||||
|
||||
open.current = expanded;
|
||||
|
||||
const measure = useCallback(() => {
|
||||
const element = content_ref.current;
|
||||
|
||||
if (!element || open.current) return;
|
||||
|
||||
setOverflows(
|
||||
bubbleOverflows({
|
||||
scroll_height: element.scrollHeight,
|
||||
client_height: element.clientHeight,
|
||||
}),
|
||||
);
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setExpanded(false);
|
||||
setOverflows(false);
|
||||
}, [text]);
|
||||
|
||||
/**
|
||||
* Measured before the first paint, so the button never lands after the
|
||||
* thread is already on screen, and again when the window (and with it
|
||||
* the bubble's width) changes.
|
||||
*/
|
||||
useLayoutEffect(() => {
|
||||
const element = content_ref.current;
|
||||
|
||||
if (!element) return;
|
||||
|
||||
measure();
|
||||
|
||||
if (typeof ResizeObserver == "undefined") return;
|
||||
|
||||
const observer = new ResizeObserver(measure);
|
||||
|
||||
observer.observe(element);
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, [measure, text, expanded]);
|
||||
|
||||
return {
|
||||
content_ref: content_ref as RefObject<HTMLDivElement>,
|
||||
expanded,
|
||||
overflows,
|
||||
toggle: useCallback(() => setExpanded((value) => !value), []),
|
||||
};
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { lazy, Suspense } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import { Bug } from "lucide-react";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
@@ -10,7 +11,12 @@ import { BotGettingMessageStatusLine } from "@/src/dict/bot-queue-dict";
|
||||
import type { BotWithLastMessage } from "@/src/types";
|
||||
import botBusyState from "../(utils)/bot-busy-state";
|
||||
import StopBotButton from "./stop-bot-button";
|
||||
import TracePanel from "./trace-panel";
|
||||
|
||||
/**
|
||||
* The debug strip is its own chunk: most conversations never open it, and
|
||||
* the page's first load is what the bundle budget is about.
|
||||
*/
|
||||
const TracePanel = lazy(() => import("./trace-panel"));
|
||||
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
@@ -131,7 +137,9 @@ export default function BotThinkingRow({
|
||||
<StopBotButton bot_name={bot.name} disabled={!stoppable} />
|
||||
</Row>
|
||||
{debug_open && on_toggle_debug ? (
|
||||
<TracePanel session_id={session_id} open={Boolean(debug_open)} />
|
||||
<Suspense fallback={null}>
|
||||
<TracePanel session_id={session_id} open={Boolean(debug_open)} />
|
||||
</Suspense>
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isValidElement, type ReactNode } from "react";
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import SunkenCodeBlock from "@/src/components/general/sunken-code-block";
|
||||
|
||||
/**
|
||||
* A fenced code block in a bot message, on the sunken surface with
|
||||
@@ -10,17 +10,5 @@ export default function MarkdownCodeBlock({ children }: { children?: ReactNode }
|
||||
? (children.props as { children?: ReactNode }).children
|
||||
: children;
|
||||
|
||||
return (
|
||||
<CodeBlock
|
||||
singleBlock
|
||||
backgroundColor="var(--color-sunken)"
|
||||
wrapperProps={{
|
||||
className:
|
||||
"max-w-full! outline-hairline dark:outline-hairline [&_.twui-code-block-header_svg]:stroke-ink-secondary",
|
||||
}}
|
||||
className="font-mono text-[13px] leading-5 text-ink py-2 pl-2 pr-10"
|
||||
>
|
||||
{code}
|
||||
</CodeBlock>
|
||||
);
|
||||
}
|
||||
return <SunkenCodeBlock>{code}</SunkenCodeBlock>;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { lazy, Suspense, useState } from "react";
|
||||
import Divider from "@moduletrace/twui/layout/Divider";
|
||||
import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
@@ -10,10 +10,15 @@ 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 MessageDebugLogs from "./message-debug-logs";
|
||||
import MessageDetailsBody from "./message-details-body";
|
||||
import MessageDetailsTabButton from "./message-details-tab-button";
|
||||
|
||||
/**
|
||||
* Only the modal's second tab needs the logs, and only once it's opened, so
|
||||
* it loads as its own chunk rather than with the conversation.
|
||||
*/
|
||||
const MessageDebugLogs = lazy(() => import("./message-debug-logs"));
|
||||
|
||||
type Props = {
|
||||
message_id: number;
|
||||
/**
|
||||
@@ -94,7 +99,9 @@ export default function MessageDetailsModal({ message_id, tool_log, chatroom_id
|
||||
)}
|
||||
</Stack>
|
||||
) : (
|
||||
<MessageDebugLogs message_id={message_id} chatroom_id={chatroom_id} />
|
||||
<Suspense fallback={null}>
|
||||
<MessageDebugLogs message_id={message_id} chatroom_id={chatroom_id} />
|
||||
</Suspense>
|
||||
)}
|
||||
</Stack>
|
||||
</Modal>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { TracePreviewChars } from "../(utils)/trace-entry-view";
|
||||
import TraceBlock from "./trace-block";
|
||||
|
||||
/**
|
||||
* A trace block is read inside the Details modal and the debug strip, on
|
||||
* whichever theme the user has. Code used to come out of twui's own dark
|
||||
* block (a fixed `#28272b`), which left dark-on-dark text in light mode and
|
||||
* set the block larger than the log around it.
|
||||
*/
|
||||
describe("TraceBlock", () => {
|
||||
test("code sits on the theme's sunken surface, never twui's dark block", () => {
|
||||
const html = renderToString(<TraceBlock label="What it was sent" kind="code" text={'{"command":"ls"}'} />);
|
||||
|
||||
expect(html).toContain("var(--color-sunken)");
|
||||
expect(html).not.toContain("#28272b");
|
||||
expect(html).toContain("text-ink");
|
||||
});
|
||||
|
||||
test("code and prose share the log's size", () => {
|
||||
const code = renderToString(<TraceBlock kind="code" text={"ls -la"} />);
|
||||
const prose = renderToString(<TraceBlock text="Two tabs are open." />);
|
||||
|
||||
expect(code).toContain("text-[13px]");
|
||||
expect(code).toContain("leading-5");
|
||||
expect(prose).toContain("text-[13px]");
|
||||
expect(prose).toContain("leading-5");
|
||||
});
|
||||
|
||||
test("a long text is cut until it is opened", () => {
|
||||
const text = `start ${"x".repeat(TracePreviewChars)}end`;
|
||||
|
||||
const cut = renderToString(<TraceBlock kind="code" text={text} />);
|
||||
const whole = renderToString(<TraceBlock kind="code" text="short" />);
|
||||
|
||||
expect(cut).toContain("start");
|
||||
expect(cut).not.toContain("end");
|
||||
expect(cut).toContain(`Show all ${text.length.toLocaleString()} characters`);
|
||||
expect(whole).not.toContain("Show all");
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,10 @@
|
||||
import { useState } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import CodeBlock from "@moduletrace/twui/elements/CodeBlock";
|
||||
import P from "@moduletrace/twui/layout/P";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import SunkenCodeBlock from "@/src/components/general/sunken-code-block";
|
||||
import { TracePreviewChars } from "../(utils)/trace-entry-view";
|
||||
|
||||
type Props = {
|
||||
@@ -40,11 +39,9 @@ export default function TraceBlock({ label, text, kind = "text" }: Props) {
|
||||
</Span>
|
||||
) : null}
|
||||
{kind == "code" ? (
|
||||
<CodeBlock>{shown}</CodeBlock>
|
||||
<SunkenCodeBlock wrapAnywhere>{shown}</SunkenCodeBlock>
|
||||
) : (
|
||||
<P className={twMerge("py-0 whitespace-pre-wrap text-sm text-ink")}>
|
||||
{shown}
|
||||
</P>
|
||||
<P className="py-0 whitespace-pre-wrap text-[13px] leading-5 text-ink">{shown}</P>
|
||||
)}
|
||||
{long ? (
|
||||
<Row className="w-full items-center gap-2">
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import UserBubble from "./user-bubble";
|
||||
|
||||
function render({ text }: { text: string }) {
|
||||
return renderToString(<UserBubble text={text} />);
|
||||
}
|
||||
|
||||
describe("UserBubble", () => {
|
||||
test("renders the user's markdown in the ink bubble", () => {
|
||||
const html = render({ text: "**Ship it** tonight" });
|
||||
|
||||
expect(html).toContain("font-bold\">Ship it");
|
||||
expect(html).toContain("conversation-user-bubble");
|
||||
});
|
||||
|
||||
test("cuts the text to twenty lines, with no button before it's measured", () => {
|
||||
const html = render({ text: "a long prompt\n\n".repeat(60) });
|
||||
|
||||
expect(html).toContain("max-h-[25rem]");
|
||||
expect(html).toContain("overflow-hidden");
|
||||
// The server has no layout: "Read more" appears once measured.
|
||||
expect(html).not.toContain("Read more");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import Markdown from "react-markdown";
|
||||
import remarkBreaks from "remark-breaks";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import linkComputerRefs from "@/src/utils/link-computer-refs";
|
||||
import { UserMarkdownComponents } from "../(data)/user-markdown-components";
|
||||
import useBubbleClamp from "../(hooks)/use-bubble-clamp";
|
||||
import { QuotableAttribute } from "../(hooks)/use-message-selection";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
@@ -17,24 +19,52 @@ const RemarkPlugins = [remarkGfm, remarkBreaks];
|
||||
* Ink bubble with paper text; inverts in dark mode. The text is markdown
|
||||
* (GFM; raw HTML is never rendered) as the composer writes it, a single
|
||||
* line break kept as one, so older plain messages read as typed. Bots
|
||||
* and workspaces it mentions show as chips.
|
||||
* and workspaces it mentions show as chips. A long message is cut to the
|
||||
* twenty lines of `max-h-[25rem]` (the bubble's `leading-5`), with "Read
|
||||
* more" under it for the rest: a pasted prompt should not fill the screen.
|
||||
*/
|
||||
export default function UserBubble({ text }: { text: string }) {
|
||||
const { content_ref, expanded, overflows, toggle } = useBubbleClamp({
|
||||
text,
|
||||
});
|
||||
|
||||
return (
|
||||
<Stack
|
||||
{...{ [QuotableAttribute]: "" }}
|
||||
className={twMerge(
|
||||
"max-w-[80%] min-w-0 gap-2.5! items-stretch rounded-default-lg",
|
||||
"max-w-[80%] min-w-0 gap-1.5! items-stretch rounded-default-lg",
|
||||
"bg-ink text-on-ink px-4 py-3 text-sm leading-5 wrap-anywhere",
|
||||
"conversation-user-bubble",
|
||||
)}
|
||||
>
|
||||
<Markdown
|
||||
remarkPlugins={RemarkPlugins}
|
||||
components={UserMarkdownComponents}
|
||||
<Stack
|
||||
{...{ [QuotableAttribute]: "" }}
|
||||
componentRef={content_ref}
|
||||
className={twMerge(
|
||||
"min-w-0 items-stretch gap-2.5!",
|
||||
!expanded && "max-h-[25rem] overflow-hidden",
|
||||
)}
|
||||
>
|
||||
{linkComputerRefs({ text })}
|
||||
</Markdown>
|
||||
<Markdown
|
||||
remarkPlugins={RemarkPlugins}
|
||||
components={UserMarkdownComponents}
|
||||
>
|
||||
{linkComputerRefs({ text })}
|
||||
</Markdown>
|
||||
</Stack>
|
||||
{overflows ? (
|
||||
<Button
|
||||
title={expanded ? "Show less" : "Read more"}
|
||||
aria-expanded={expanded}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="white"
|
||||
size="small"
|
||||
onClick={toggle}
|
||||
className="-ml-3 -mb-1 self-start text-on-ink/80 hover:text-on-ink"
|
||||
>
|
||||
{expanded ? "Show less" : "Read more"}
|
||||
</Button>
|
||||
) : null}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import bubbleOverflows from "./bubble-overflow";
|
||||
|
||||
describe("bubbleOverflows", () => {
|
||||
test("a message that fits has nothing to open", () => {
|
||||
expect(
|
||||
bubbleOverflows({ scroll_height: 380, client_height: 380 }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("a line of rounding is no overflow", () => {
|
||||
expect(
|
||||
bubbleOverflows({ scroll_height: 380, client_height: 379 }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("a message taller than its room is cut", () => {
|
||||
expect(
|
||||
bubbleOverflows({ scroll_height: 1200, client_height: 400 }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("an empty bubble has nothing to open", () => {
|
||||
expect(bubbleOverflows({ scroll_height: 0, client_height: 0 })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* How much taller a bubble's text may be than the room it shows before
|
||||
* it counts as cut: line heights and scroll sizes are rounded, and a
|
||||
* message that fits exactly must not offer "Read more".
|
||||
*/
|
||||
const OverflowSlackPx = 2;
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The height the bubble's text would take uncut (`scrollHeight`).
|
||||
*/
|
||||
scroll_height: number;
|
||||
/**
|
||||
* The height the bubble shows (`clientHeight`), cut to its lines.
|
||||
*/
|
||||
client_height: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a user's own message needs cutting: its text is taller than the
|
||||
* room it shows, so "Read more" opens the rest.
|
||||
*/
|
||||
export default function bubbleOverflows({
|
||||
scroll_height,
|
||||
client_height,
|
||||
}: Params) {
|
||||
return scroll_height - client_height > OverflowSlackPx;
|
||||
}
|
||||
Reference in New Issue
Block a user