Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c36f8e3736 | ||
|
|
70ef0e6ae2 | ||
|
|
2a7ea3c76b | ||
|
|
7ffce997ce | ||
|
|
d80899b756 |
+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`, 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.
|
||||
- **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; 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.1",
|
||||
"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)`;
|
||||
}
|
||||
@@ -898,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,
|
||||
@@ -396,6 +398,32 @@ export const failedToolCallNote = ({
|
||||
|
||||
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
|
||||
@@ -469,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
|
||||
|
||||
@@ -147,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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -66,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,
|
||||
@@ -84,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;
|
||||
@@ -173,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.",
|
||||
@@ -1267,3 +1298,211 @@ describe("runTextLoop commit early", () => {
|
||||
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,7 +1,15 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { alreadyRanToolNote, commitEarlyNote, failedToolCallNote, tokensLowNote } 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, { toolCallKey } from "../tools/repeat-tool-call-key";
|
||||
@@ -370,6 +378,16 @@ 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
|
||||
@@ -473,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,
|
||||
@@ -481,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({
|
||||
@@ -675,6 +708,40 @@ export default async function runTextLoop({
|
||||
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
|
||||
@@ -694,6 +761,19 @@ 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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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), []),
|
||||
};
|
||||
}
|
||||
@@ -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