Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0885e12a8b | ||
|
|
7da9003e7b | ||
|
|
b609d72888 |
@@ -94,12 +94,13 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **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 and task (`session-messages`, `use-reply-catch-up`), 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.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@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), `[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.
|
||||
- **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).
|
||||
- **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`.
|
||||
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
|
||||
- **Replies/reactions:** `reply_to_message_id` (not an FK); reactions from the fixed `BotMessageReactions`, toggled by `react-message.ts` and the `react_to_message` tool, pushed as `server:bot-reaction`. A reply's history shows the user's own reactions on each bot message in its app record (`botMessagesToHarness`, so `run-bot-reply` loads history with `user_id`), and the chat reply note tells the bot to save lasting preferences they show in its memory of that user; 👎 is in the set for that.
|
||||
- **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.
|
||||
|
||||
@@ -60,6 +60,7 @@
|
||||
"@types/sanitize-html": "^2.16.2",
|
||||
"@types/turndown": "^5.0.6",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"marked": "17.0.6",
|
||||
"tailwindcss": "^4.3.3",
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -1797,6 +1797,48 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_suggestions",
|
||||
tableDescription: `Next steps a bot suggests under its answer (\`suggest_next_steps\`): buttons that put the step in the user's input. Unlike \`bot_questions\`, nothing waits on them`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "title",
|
||||
fieldDescription: `A short heading for the row of buttons; empty for "Next steps"`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "steps",
|
||||
fieldDescription: `JSON array of the suggested steps, each put in the user's input when clicked`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "user_id",
|
||||
fieldDescription: `The user they were suggested to, who alone reads them. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "bot_id",
|
||||
fieldDescription: `The bot that suggested them. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "session_id",
|
||||
fieldDescription: `The conversation they were suggested in. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
fieldName: "workspace_id",
|
||||
fieldDescription: `The session's workspace; null for the bot's own chat. Not a foreign key`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
],
|
||||
indexes: [
|
||||
{
|
||||
indexName: "idx_bot_suggestions_session_id",
|
||||
indexTableFields: ["session_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tableName: "bot_graphics",
|
||||
tableDescription: `A visual a bot made for a user (a chart, diagram, timeline or report) as one self-contained HTML document. Served by the app at \`/graphics/<id>\` in a sandbox with no network and an origin of its own, so it never runs with the viewer's session. Per user like the conversation it was made in; an edit replaces the HTML and bumps \`version\``,
|
||||
|
||||
+41
-1
@@ -24,6 +24,7 @@ export const BunSQLiteTables = [
|
||||
"secret_requests",
|
||||
"install_requests",
|
||||
"bot_questions",
|
||||
"bot_suggestions",
|
||||
"bot_graphics",
|
||||
"workspaces",
|
||||
"workspace_bots",
|
||||
@@ -1164,6 +1165,45 @@ export type BUN_SQLITE_COBBLE_BOT_QUESTIONS = {
|
||||
workspace_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_SUGGESTIONS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
*/
|
||||
id?: number | "";
|
||||
/**
|
||||
* The time when the record was created. (Unix Timestamp)
|
||||
*/
|
||||
created_at?: number | "";
|
||||
/**
|
||||
* The time when the record was updated. (Unix Timestamp)
|
||||
*/
|
||||
updated_at?: number | "";
|
||||
/**
|
||||
* A short heading for the row of buttons; empty for "Next steps"
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* JSON array of the suggested steps, each put in the user's input when clicked
|
||||
*/
|
||||
steps?: string;
|
||||
/**
|
||||
* The user they were suggested to, who alone reads them. Not a foreign key
|
||||
*/
|
||||
user_id?: number | "";
|
||||
/**
|
||||
* The bot that suggested them. Not a foreign key
|
||||
*/
|
||||
bot_id?: number | "";
|
||||
/**
|
||||
* The conversation they were suggested in. Not a foreign key
|
||||
*/
|
||||
session_id?: number | "";
|
||||
/**
|
||||
* The session's workspace; null for the bot's own chat. Not a foreign key
|
||||
*/
|
||||
workspace_id?: number | "";
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_BOT_GRAPHICS = {
|
||||
/**
|
||||
* The unique identifier of the record.
|
||||
@@ -2826,4 +2866,4 @@ export type BUN_SQLITE_COBBLE_APP_SETTINGS = {
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
|
||||
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_INSTALL_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_SUGGESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_ROLES & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_BROWSERS & BUN_SQLITE_COBBLE_BROWSER_ACCESS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_HARNESS_CALL_FAILURES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.18.9",
|
||||
"version": "0.18.10",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
@@ -35,6 +35,7 @@
|
||||
"@types/sanitize-html": "^2.16.2",
|
||||
"@types/turndown": "^5.0.6",
|
||||
"@types/web-push": "^3.6.4",
|
||||
"marked": "17.0.6",
|
||||
"tailwindcss": "^4.3.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
|
||||
@@ -61,6 +61,7 @@ import markReplyAnswered from "@/src/functions/backend/db/bots-queue/mark-reply-
|
||||
import sendMessageTool from "@/src/harness/tools/bot/send-message-tool";
|
||||
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
|
||||
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
|
||||
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import type { HarnessMessage } from "@/src/harness/types";
|
||||
import type { BotJobContext, BotJobOutcome } from "./types";
|
||||
@@ -211,8 +212,9 @@ export default async function runBotReply({
|
||||
*/
|
||||
const proposals: string[] = [];
|
||||
/**
|
||||
* The secrets the bot showed (`show_secret`) and the graphics it made
|
||||
* or changed, whose chips the reply always carries.
|
||||
* The secrets the bot showed (`show_secret`), the graphics it made
|
||||
* or changed, and the next steps it suggested: their chips the reply
|
||||
* always carries, without needing the user.
|
||||
*/
|
||||
const shown: string[] = [];
|
||||
/**
|
||||
@@ -415,6 +417,13 @@ export default async function runBotReply({
|
||||
workspace_id,
|
||||
onAsk: ({ ref }) => proposals.push(ref),
|
||||
}),
|
||||
suggestNextStepsTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
onSuggest: ({ ref }) => shown.push(ref),
|
||||
}),
|
||||
...(has_past_sessions
|
||||
? [searchPastSessionsTool(past_scope), readPastSessionTool(past_scope)]
|
||||
: []),
|
||||
|
||||
@@ -45,6 +45,7 @@ import openBotKnowledgebases from "@/src/harness/tools/knowledgebases/open-bot-k
|
||||
import grabBotTools from "@/src/harness/tools/bot/grab-bot-tools";
|
||||
import grabBotSecretTools from "@/src/harness/tools/bot/secrets/grab-bot-secret-tools";
|
||||
import askUserTool from "@/src/harness/tools/bot/questions/ask-user-tool";
|
||||
import suggestNextStepsTool from "@/src/harness/tools/bot/suggestions/suggest-next-steps-tool";
|
||||
import createWorkspaceTool from "@/src/harness/tools/bot/create-workspace-tool";
|
||||
import updateWorkspaceTool from "@/src/harness/tools/bot/update-workspace-tool";
|
||||
import listWorkspacePeopleTool from "@/src/harness/tools/bot/list-workspace-people-tool";
|
||||
@@ -163,6 +164,11 @@ export default async function runBotTask({
|
||||
signal,
|
||||
}).catch(() => "");
|
||||
const take_overs: string[] = [];
|
||||
/**
|
||||
* The next steps the bot suggested: added to the message without
|
||||
* needing the user.
|
||||
*/
|
||||
const suggestions: string[] = [];
|
||||
/**
|
||||
* Files the bot wrote and asked to send with its report.
|
||||
*/
|
||||
@@ -285,6 +291,13 @@ export default async function runBotTask({
|
||||
in_task: true,
|
||||
onAsk: ({ ref }) => take_overs.push(ref),
|
||||
}),
|
||||
suggestNextStepsTool({
|
||||
user_id,
|
||||
bot_id: bot.id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
onSuggest: ({ ref }) => suggestions.push(ref),
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
...(scheduled || hooked ? [reportRunFailedTool({ onFail: ({ reason }) => (failure = reason) })] : []),
|
||||
@@ -534,7 +547,7 @@ export default async function runBotTask({
|
||||
...withTakeOverRefs({
|
||||
text: computer ? computer.redact(text) : text,
|
||||
refs: take_overs,
|
||||
shown,
|
||||
shown: [...shown, ...suggestions],
|
||||
}),
|
||||
attachments: attachments.length ? attachments : undefined,
|
||||
tool_log: result.tool_uses,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import takeOverRef from "@/src/utils/take-over-ref";
|
||||
import botSuggestionRef from "@/src/utils/bot-suggestion-ref";
|
||||
import withTakeOverRefs from "./with-take-over-refs";
|
||||
|
||||
const ref = takeOverRef({ id: 1, mode: "browser" });
|
||||
@@ -21,4 +22,13 @@ describe("withTakeOverRefs", () => {
|
||||
test("leaves a message without a take-over alone", () => {
|
||||
expect(withTakeOverRefs({ text: "Done.", refs: [] })).toEqual({ result: "Done.", needs_you: false });
|
||||
});
|
||||
|
||||
test("adds suggested next steps without needing the user", () => {
|
||||
const suggestions = botSuggestionRef({ id: 4 });
|
||||
|
||||
expect(withTakeOverRefs({ text: "Done.", refs: [], shown: [suggestions] })).toEqual({
|
||||
result: `Done.\n\n${suggestions}`,
|
||||
needs_you: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,8 +6,9 @@ type Params = {
|
||||
*/
|
||||
refs: string[];
|
||||
/**
|
||||
* The secrets it showed (`secretRef`): added the same way, but they
|
||||
* don't need the user.
|
||||
* The secrets it showed (`secretRef`) and the next steps it suggested
|
||||
* (`botSuggestionRef`): added the same way, but they don't need the
|
||||
* user, so neither makes the message.
|
||||
*/
|
||||
shown?: string[];
|
||||
};
|
||||
@@ -16,7 +17,8 @@ type Params = {
|
||||
* A job's message with every take-over the bot asked for in it and every
|
||||
* proposal it made: refs the bot didn't write itself are added at the
|
||||
* end, so the user always gets the button. A message asking for either
|
||||
* needs the user.
|
||||
* needs the user; secrets it showed and next steps it suggested are added
|
||||
* without asking anything of them.
|
||||
*/
|
||||
export default function withTakeOverRefs({ text, refs, shown = [] }: Params) {
|
||||
const missing = [...new Set([...refs, ...shown])].filter((ref) => !text.includes(ref));
|
||||
|
||||
@@ -977,6 +977,19 @@ export const AppData = {
|
||||
* Longest answer a user may type into a question's "Other".
|
||||
*/
|
||||
BotQuestionOtherMaxChars: 1000,
|
||||
/**
|
||||
* Most next steps one `suggest_next_steps` row offers.
|
||||
*/
|
||||
BotSuggestionMaxSteps: 4,
|
||||
/**
|
||||
* Longest one suggested next step may be (the text that fills the
|
||||
* user's input).
|
||||
*/
|
||||
BotSuggestionStepMaxChars: 120,
|
||||
/**
|
||||
* Longest heading a bot may give its suggested next steps.
|
||||
*/
|
||||
BotSuggestionTitleMaxChars: 120,
|
||||
/**
|
||||
* Longest dictation the composer records before it stops on its own.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_SUGGESTIONS, BunSQLiteTables } from "@/db/types/db";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
session_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
title: string;
|
||||
steps: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Stores next steps a bot suggests under its answer, read back as buttons
|
||||
* that put a step in the user's input. Returns its id.
|
||||
*/
|
||||
export default async function createBotSuggestion({ user_id, bot_id, session_id, workspace_id, title, steps }: Params) {
|
||||
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_SUGGESTIONS, (typeof BunSQLiteTables)[number]>({
|
||||
table: "bot_suggestions",
|
||||
data: [
|
||||
{
|
||||
title,
|
||||
steps: JSON.stringify(steps),
|
||||
user_id: Number(user_id),
|
||||
bot_id: Number(bot_id),
|
||||
session_id: Number(session_id),
|
||||
workspace_id: workspace_id ? Number(workspace_id) : undefined,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const id = Number(res.singleRes?.id || res.postInsertReturn?.insertId);
|
||||
|
||||
if (!res.success || !id) throw new Error(`Couldn't store the suggested next steps: ${res.msg}`);
|
||||
|
||||
return id;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BotSuggestionView } from "@/src/types";
|
||||
import grabBotSuggestion from "./grab-bot-suggestion";
|
||||
import parseBotSuggestionRow from "@/src/utils/parse-bot-suggestion-row";
|
||||
|
||||
type Params = {
|
||||
suggestion_id: number | string;
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Next steps a bot suggested as the thread shows them: its heading and the
|
||||
* steps, each a button that puts it in the user's input.
|
||||
*/
|
||||
export default async function grabBotSuggestionView({ suggestion_id, user_id }: Params): Promise<BotSuggestionView> {
|
||||
const row = await grabBotSuggestion({ suggestion_id, user_id });
|
||||
const { steps } = parseBotSuggestionRow({ row });
|
||||
|
||||
const bot = (
|
||||
await BunSQLite.sql<{ name: string }>({
|
||||
sql: `SELECT name FROM bots WHERE id = ? LIMIT 1`,
|
||||
values: [row.bot_id || 0],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
return {
|
||||
id: Number(row.id),
|
||||
title: row.title || "",
|
||||
steps,
|
||||
bot_id: Number(row.bot_id),
|
||||
bot_name: bot?.name || "The bot",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_SUGGESTIONS } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
|
||||
type Params = {
|
||||
suggestion_id: number | string;
|
||||
/**
|
||||
* Only the user they were suggested to reads them.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Next steps a bot suggested, only for the user they were suggested to.
|
||||
* Throws otherwise.
|
||||
*/
|
||||
export default async function grabBotSuggestion({ suggestion_id, user_id }: Params) {
|
||||
const row = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SUGGESTIONS>({
|
||||
sql: `SELECT * FROM bot_suggestions WHERE id = ? AND user_id = ? LIMIT 1`,
|
||||
values: [Number(suggestion_id), Number(user_id)],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!row?.id) throw new AppError(`Those next steps aren't yours or no longer exist.`);
|
||||
|
||||
return row;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import suggestNextStepsTool from "./suggest-next-steps-tool";
|
||||
|
||||
const refs: string[] = [];
|
||||
const tool = suggestNextStepsTool({ user_id: 1, bot_id: 2, session_id: 3, onSuggest: ({ ref }) => refs.push(ref) });
|
||||
|
||||
describe("suggestNextStepsTool", () => {
|
||||
test("takes a set of steps with an optional heading", () => {
|
||||
expect(tool.schema?.safeParse({ title: "What I can do next", steps: ["Write the report", "Email the team"] }).success).toBe(true);
|
||||
expect(tool.schema?.safeParse({ steps: ["Write the report"] }).success).toBe(true);
|
||||
});
|
||||
|
||||
test("needs at least one step and no duplicates", () => {
|
||||
expect(tool.schema?.safeParse({ steps: [] }).success).toBe(false);
|
||||
expect(tool.schema?.safeParse({ steps: ["Write the report", "write the report"] }).success).toBe(false);
|
||||
expect(tool.schema?.safeParse({ steps: [" "] }).success).toBe(false);
|
||||
});
|
||||
|
||||
test("caps how many steps one row holds and how long each is", () => {
|
||||
expect(tool.schema?.safeParse({ steps: Array.from({ length: 5 }, (_, i) => `Step ${i}`) }).success).toBe(false);
|
||||
expect(tool.schema?.safeParse({ steps: ["x".repeat(121)] }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { z } from "zod";
|
||||
import createBotSuggestion from "@/src/functions/backend/db/bot-suggestions/create-bot-suggestion";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { BotSuggestionStepsSchema } from "@/src/schemas/bot-suggestion-schema";
|
||||
import botSuggestionRef from "@/src/utils/bot-suggestion-ref";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
type Params = {
|
||||
user_id: number | string;
|
||||
bot_id: number | string;
|
||||
/**
|
||||
* The conversation they show in.
|
||||
*/
|
||||
session_id: number | string;
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* Called with the suggestions' ref, so the message always carries
|
||||
* their buttons.
|
||||
*/
|
||||
onSuggest: (params: { ref: string }) => void;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
title?: string;
|
||||
steps: z.infer<typeof BotSuggestionStepsSchema>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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.`,
|
||||
schema: z.object({
|
||||
title: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(AppData.BotSuggestionTitleMaxChars)
|
||||
.optional()
|
||||
.describe(`A short heading for the row, e.g. "What I can do next" (defaults to "Next steps")`),
|
||||
steps: BotSuggestionStepsSchema.describe("The suggested steps, best first, each written as the message the user would send"),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (suggested) {
|
||||
throw new Error(`You already suggested next steps in this run. Put every suggestion in one suggest_next_steps call.`);
|
||||
}
|
||||
|
||||
const id = await createBotSuggestion({
|
||||
user_id,
|
||||
bot_id,
|
||||
session_id,
|
||||
workspace_id,
|
||||
title: args.title?.trim() || "",
|
||||
steps: args.steps,
|
||||
});
|
||||
|
||||
suggested = true;
|
||||
onSuggest({ ref: botSuggestionRef({ id }) });
|
||||
|
||||
const count = args.steps.length;
|
||||
|
||||
return `Suggested ${count} next step${count == 1 ? "" : "s"}: the buttons are under your message, and clicking one puts it in the user's input. They need do nothing; don't wait for them and don't repeat the steps in your text.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { MarkdownManager } from "@tiptap/markdown";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import { Marked, marked } from "marked";
|
||||
import ComposerOrderedList from "./composer-ordered-list";
|
||||
|
||||
/**
|
||||
* The composer reads a draft or a recalled message back through the same
|
||||
* markdown manager its editor builds, extensions and all. Its own marked
|
||||
* instance, since Tiptap hands every manager the module-level one and a
|
||||
* manager built elsewhere (another test) would leave its tokenizers there.
|
||||
*/
|
||||
const manager = new MarkdownManager({
|
||||
marked: new Marked() as unknown as typeof marked,
|
||||
extensions: [StarterKit.configure({ orderedList: false }), ComposerOrderedList] as never,
|
||||
});
|
||||
|
||||
const parse = ({ markdown }: { markdown: string }) => manager.parse(markdown) as {
|
||||
type: string;
|
||||
attrs?: { start?: number };
|
||||
content?: {
|
||||
type: string;
|
||||
attrs?: { start?: number };
|
||||
text?: string;
|
||||
content?: { type: string; text?: string }[];
|
||||
}[];
|
||||
};
|
||||
|
||||
const text = ({ markdown }: { markdown: string }) => parse({ markdown }).content?.[0]?.content?.[0]?.text;
|
||||
|
||||
describe("composer ordered lists read digits only", () => {
|
||||
test("a sentence opening with a short word stays a paragraph", () => {
|
||||
const doc = parse({ markdown: "Ok. Do another pass on the browser." });
|
||||
|
||||
expect(doc.content?.map((node) => node.type)).toEqual(["paragraph"]);
|
||||
expect(text({ markdown: "Ok. Do another pass on the browser." })).toBe(
|
||||
"Ok. Do another pass on the browser.",
|
||||
);
|
||||
});
|
||||
|
||||
test("a two-letter word with a full stop stays a paragraph", () => {
|
||||
expect(parse({ markdown: "ab. xyz" }).content?.[0]?.type).toBe("paragraph");
|
||||
});
|
||||
|
||||
test("a roman numeral marker stays a paragraph", () => {
|
||||
expect(parse({ markdown: "ii. second point" }).content?.[0]?.type).toBe("paragraph");
|
||||
});
|
||||
|
||||
test("a digit marker is still an ordered list", () => {
|
||||
expect(parse({ markdown: "1. first\n2. second" }).content?.[0]?.type).toBe("orderedList");
|
||||
});
|
||||
|
||||
test("a list keeps its start number", () => {
|
||||
expect(parse({ markdown: "10. tenth" }).content?.[0]?.attrs?.start).toBe(10);
|
||||
});
|
||||
|
||||
test("a bullet list is untouched", () => {
|
||||
expect(parse({ markdown: "- one\n- two" }).content?.[0]?.type).toBe("bulletList");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { MarkdownTokenizer } from "@tiptap/core";
|
||||
import OrderedList from "@tiptap/extension-ordered-list";
|
||||
|
||||
/**
|
||||
* The one way markdown starts an ordered list here: digits, as every
|
||||
* renderer in the app reads it (react-markdown/remark). Tiptap's own
|
||||
* tokenizer also takes `a.` and `i.`, so a recalled message such as
|
||||
* "Ok. Do another pass on the browser." came back as a list item
|
||||
* numbered 401 with "Ok." swallowed as the marker.
|
||||
*/
|
||||
const DigitMarker = /^ {0,3}\d{1,9}[.)][\t ]/;
|
||||
|
||||
const TiptapTokenizer = OrderedList.config.markdownTokenizer as MarkdownTokenizer;
|
||||
|
||||
const ComposerOrderedList = OrderedList.extend({
|
||||
markdownTokenizer: {
|
||||
...TiptapTokenizer,
|
||||
tokenize: (src, tokens, lexer) => {
|
||||
if (!DigitMarker.test(src)) return undefined;
|
||||
|
||||
return TiptapTokenizer.tokenize(src, tokens, lexer);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export default ComposerOrderedList;
|
||||
@@ -9,9 +9,15 @@ import type { BotMessageWithAttachments } from "@/src/types";
|
||||
export type BotMessageActions = {
|
||||
onReply: (params: { message: BotMessageWithAttachments }) => void;
|
||||
onReact: (params: { message_id: number; emoji: BotMessageReactionEmoji }) => void;
|
||||
/**
|
||||
* A suggested next step the user clicked (`[suggestion:ID]`): put it
|
||||
* in their input, never send it.
|
||||
*/
|
||||
onUseSuggestion: (params: { text: string }) => void;
|
||||
};
|
||||
|
||||
export const BotMessageActionsContext = React.createContext<BotMessageActions>({
|
||||
onReply: () => {},
|
||||
onReact: () => {},
|
||||
onUseSuggestion: () => {},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import { useEffect, useState } from "react";
|
||||
import type { BotSuggestionView } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
suggestion_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Next steps already read, by id, so a thread naming them twice asks once.
|
||||
*/
|
||||
const loaded = new Map<number, Promise<BotSuggestionView | null>>();
|
||||
|
||||
function loadSuggestion({ suggestion_id }: Params) {
|
||||
const cached = loaded.get(suggestion_id);
|
||||
|
||||
if (cached) return cached;
|
||||
|
||||
const pending = fetchApi<{}, APIResponseObject<BotSuggestionView>>(
|
||||
`/api/admin/bot-suggestions/get-suggestion?suggestion_id=${suggestion_id}`,
|
||||
{ method: "GET" },
|
||||
)
|
||||
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
|
||||
.catch(() => null);
|
||||
|
||||
loaded.set(suggestion_id, pending);
|
||||
|
||||
return pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* Next steps a bot suggested (`[suggestion:ID]`): read when their buttons
|
||||
* render. Only the user they were suggested to can read them; anyone else
|
||||
* gets null.
|
||||
*/
|
||||
export default function useBotSuggestion({ suggestion_id }: Params) {
|
||||
const [view, setView] = useState<BotSuggestionView | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
|
||||
loadSuggestion({ suggestion_id }).then((result) => {
|
||||
if (!live) return;
|
||||
setView(result);
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [suggestion_id]);
|
||||
|
||||
return { view, loading };
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import Placeholder from "@tiptap/extension-placeholder";
|
||||
import { Markdown } from "@tiptap/markdown";
|
||||
import type { SuggestionOptions, SuggestionProps } from "@tiptap/suggestion";
|
||||
import type { BotWithLastMessage, WorkspaceWithActivity } from "@/src/types";
|
||||
import ComposerOrderedList from "../(data)/composer-ordered-list";
|
||||
import {
|
||||
ComposerMentionKinds,
|
||||
type ComposerMentionChar,
|
||||
@@ -39,6 +40,11 @@ type Params = {
|
||||
* Files pasted or dropped in.
|
||||
*/
|
||||
onFiles: (params: { files: File[] }) => void;
|
||||
/**
|
||||
* An arrow key that may walk the user's previous messages; true when it
|
||||
* did, so the cursor stays where the recalled message left it.
|
||||
*/
|
||||
onHistory: (params: { direction: "up" | "down"; empty: boolean }) => boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -49,7 +55,9 @@ type Params = {
|
||||
* in a code block or list, where Enter is the editor's and Mod+Enter
|
||||
* sends. Enter picks from an open mention menu. Pasted text comes in
|
||||
* plain, without another site's styling; pasted or dropped files go to
|
||||
* `onFiles`.
|
||||
* `onFiles`. The Up and Down arrows walk the user's previous messages
|
||||
* through `onHistory` (an empty input recalls the newest; an open mention
|
||||
* menu keeps them for itself).
|
||||
*/
|
||||
export default function useComposerEditor({
|
||||
placeholder,
|
||||
@@ -58,9 +66,10 @@ export default function useComposerEditor({
|
||||
onChange,
|
||||
onSubmit,
|
||||
onFiles,
|
||||
onHistory,
|
||||
}: Params) {
|
||||
const latest = useRef({ bots, workspaces, onChange, onSubmit, onFiles });
|
||||
latest.current = { bots, workspaces, onChange, onSubmit, onFiles };
|
||||
const latest = useRef({ bots, workspaces, onChange, onSubmit, onFiles, onHistory });
|
||||
latest.current = { bots, workspaces, onChange, onSubmit, onFiles, onHistory };
|
||||
|
||||
const [menu, setMenu] = useState<ComposerMentionMenu | null>(null);
|
||||
const menu_ref = useRef<ComposerMentionMenu | null>(null);
|
||||
@@ -134,7 +143,10 @@ export default function useComposerEditor({
|
||||
horizontalRule: false,
|
||||
underline: false,
|
||||
link: { openOnClick: false, autolink: true },
|
||||
orderedList: false,
|
||||
}),
|
||||
/** Digits only, so text like "Ok. Do that." stays a paragraph. */
|
||||
ComposerOrderedList,
|
||||
Placeholder.configure({ placeholder }),
|
||||
Markdown,
|
||||
Mention.extend({
|
||||
@@ -155,7 +167,17 @@ export default function useComposerEditor({
|
||||
const editorOwnsEnter = () =>
|
||||
this.editor.isActive("codeBlock") || this.editor.isActive("listItem");
|
||||
|
||||
/** A selection, a composing IME or an open menu keep the arrows. */
|
||||
const walkHistory = (direction: "up" | "down") => {
|
||||
if (menu_ref.current?.items.length || this.editor.view.composing) return false;
|
||||
if (!this.editor.state.selection.empty) return false;
|
||||
|
||||
return latest.current.onHistory({ direction, empty: this.editor.isEmpty });
|
||||
};
|
||||
|
||||
return {
|
||||
ArrowUp: () => walkHistory("up"),
|
||||
ArrowDown: () => walkHistory("down"),
|
||||
Enter: () => {
|
||||
if (menu_ref.current?.items.length || this.editor.view.composing) return false;
|
||||
if (editorOwnsEnter()) return false;
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useRef } from "react";
|
||||
import stepComposerHistory, {
|
||||
EmptyComposerHistory,
|
||||
type ComposerHistoryState,
|
||||
} from "../(utils)/composer-history-step";
|
||||
|
||||
/**
|
||||
* The user's previous messages, walked with the Up and Down arrows: what
|
||||
* they were typing is kept and comes back when Down passes the newest
|
||||
* message again.
|
||||
*/
|
||||
export type ComposerHistory = {
|
||||
/** A recalled message is in the input (so the arrows keep walking). */
|
||||
isActive: () => boolean;
|
||||
/**
|
||||
* One arrow press: the text the input takes, or null when the key
|
||||
* belongs to the editor (a cursor to move, nothing to recall).
|
||||
*/
|
||||
step: (params: {
|
||||
direction: "up" | "down";
|
||||
/** What's in the input now, put back on the way down. */
|
||||
draft: string;
|
||||
/** Whether the input has nothing in it. */
|
||||
empty: boolean;
|
||||
}) => { text: string } | null;
|
||||
/** Typing (or sending) takes the input back from the recalled messages. */
|
||||
reset: () => void;
|
||||
};
|
||||
|
||||
export default function useComposerHistory({
|
||||
texts,
|
||||
}: {
|
||||
/** What the user typed before, oldest first. */
|
||||
texts: string[];
|
||||
}): ComposerHistory {
|
||||
const state = useRef<ComposerHistoryState>(EmptyComposerHistory);
|
||||
const texts_ref = useRef(texts);
|
||||
|
||||
texts_ref.current = texts;
|
||||
|
||||
const reset = () => {
|
||||
state.current = EmptyComposerHistory;
|
||||
};
|
||||
|
||||
const step = ({
|
||||
direction,
|
||||
draft,
|
||||
empty,
|
||||
}: {
|
||||
direction: "up" | "down";
|
||||
draft: string;
|
||||
empty: boolean;
|
||||
}) => {
|
||||
const next = stepComposerHistory({
|
||||
state: state.current,
|
||||
texts: texts_ref.current,
|
||||
direction,
|
||||
draft,
|
||||
empty,
|
||||
});
|
||||
|
||||
if (!next) return null;
|
||||
|
||||
state.current = next.state;
|
||||
|
||||
return { text: next.text };
|
||||
};
|
||||
|
||||
return { isActive: () => state.current.index > 0, step, reset };
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useContext } from "react";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { ArrowUpRight } from "lucide-react";
|
||||
import { BotMessageActionsContext } from "../(data)/message-actions-context";
|
||||
|
||||
type Props = {
|
||||
step: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* One suggested next step, a button that puts it in the user's input (it
|
||||
* never sends on its own).
|
||||
*/
|
||||
export default function BotSuggestionChip({ step }: Props) {
|
||||
const { onUseSuggestion } = useContext(BotMessageActionsContext);
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outlined"
|
||||
color="gray"
|
||||
size="smaller"
|
||||
title={`Put this in your input: ${step}`}
|
||||
className="inline-flex h-auto max-w-full gap-1! flex-nowrap align-middle px-2! py-1! text-left text-[13px] font-normal whitespace-normal [&_.twui-button-content-wrapper]:min-w-0"
|
||||
onClick={() => onUseSuggestion({ text: step })}
|
||||
>
|
||||
<Span className="min-w-0">{step}</Span>
|
||||
<ArrowUpRight size={14} aria-hidden className="shrink-0" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import useBotSuggestion from "../(hooks)/use-bot-suggestion";
|
||||
import BotSuggestionChip from "./bot-suggestion-chip";
|
||||
|
||||
type Props = {
|
||||
suggestion_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Next steps a bot suggested (`botSuggestionRef`): its heading and a
|
||||
* button per step, inline under the answer. Clicking one puts it in the
|
||||
* user's input; nothing has to be answered. Anyone they weren't suggested
|
||||
* to sees their number only.
|
||||
*/
|
||||
export default function BotSuggestionsRef({ suggestion_id }: Props) {
|
||||
const { view, loading } = useBotSuggestion({ suggestion_id });
|
||||
|
||||
if (!view) {
|
||||
return (
|
||||
<Span className="font-bold">
|
||||
{loading ? `next steps ${suggestion_id}` : `next steps ${suggestion_id} (not available)`}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
|
||||
if (!view.steps.length) return null;
|
||||
|
||||
return (
|
||||
<Span className="inline-flex max-w-full flex-wrap items-center gap-1.5 align-middle">
|
||||
<Span className="text-[13px] font-bold text-ink-secondary">{view.title || "Next steps"}</Span>
|
||||
{view.steps.map((step) => (
|
||||
<BotSuggestionChip key={step} step={step} />
|
||||
))}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
type Props = {
|
||||
disabled?: boolean;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Empties the input's text (the quote, the picked files and the draft it
|
||||
* saves stay where they are).
|
||||
*/
|
||||
export default function ComposerClearButton({ disabled, onClick }: Props) {
|
||||
return (
|
||||
<Button
|
||||
title={disabled ? "Nothing to clear" : "Clear the text"}
|
||||
aria-label="Clear the text"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
disabled={disabled}
|
||||
onClick={onClick}
|
||||
className="shrink-0 p-1! -mx-1 my-1 text-ink dark:text-ink rounded-default-xs focus-visible:ring-2 focus-visible:ring-ink"
|
||||
>
|
||||
<X size={16} aria-hidden />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -23,12 +23,15 @@ import transcribeVoice from "../(functions)/transcribe-voice";
|
||||
import useComposerAttachments from "../(hooks)/use-composer-attachments";
|
||||
import useComposerDraft from "../(hooks)/use-composer-draft";
|
||||
import useComposerEditor from "../(hooks)/use-composer-editor";
|
||||
import useComposerHistory from "../(hooks)/use-composer-history";
|
||||
import useVoiceRecorder from "../(hooks)/use-voice-recorder";
|
||||
import useOnlineStatus from "@/src/hooks/use-online-status";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import messageTooLongMessage from "@/src/utils/message-too-long-message";
|
||||
import composerHistoryTexts from "../(utils)/composer-history-texts";
|
||||
import ComposerAttachButton from "./composer-attach-button";
|
||||
import ComposerAttachments from "./composer-attachments";
|
||||
import ComposerClearButton from "./composer-clear-button";
|
||||
import ComposerEditor from "./composer-editor";
|
||||
import ComposerMentionList from "./composer-mention-list";
|
||||
import ComposerReplyPreview from "./composer-reply-preview";
|
||||
@@ -44,6 +47,11 @@ export type ComposerHandle = {
|
||||
* Quotes text from the thread at the cursor.
|
||||
*/
|
||||
insertQuote: (params: { text: string }) => void;
|
||||
/**
|
||||
* Puts text at the cursor (a suggested next step), leaving the draft
|
||||
* to the user to edit and send.
|
||||
*/
|
||||
insertText: (params: { text: string }) => void;
|
||||
};
|
||||
|
||||
type Props = {
|
||||
@@ -69,6 +77,11 @@ type Props = {
|
||||
* before anything is sent, and again by the server.
|
||||
*/
|
||||
max_chars?: number | null;
|
||||
/**
|
||||
* The user's own earlier messages in the thread, oldest first: the Up
|
||||
* and Down arrows walk them.
|
||||
*/
|
||||
previous_messages?: BotMessageWithAttachments[];
|
||||
/**
|
||||
* The message the next one quotes, if the user picked one.
|
||||
*/
|
||||
@@ -100,7 +113,9 @@ type Props = {
|
||||
* are listed under the input. The mic dictates: what's said is written
|
||||
* into the input at the cursor, to edit before sending. Sending shows the
|
||||
* message in the thread straight away and empties the input, so a slow
|
||||
* connection never holds either; a failed send puts both back.
|
||||
* connection never holds either; a failed send puts both back. Up recalls
|
||||
* the message the user sent before (Down comes forward again, back to what
|
||||
* they were typing), and the X button empties the text without sending it.
|
||||
*/
|
||||
export default function Composer({
|
||||
bot,
|
||||
@@ -109,6 +124,7 @@ export default function Composer({
|
||||
voice,
|
||||
has_browsers,
|
||||
max_chars,
|
||||
previous_messages,
|
||||
reply_to,
|
||||
onCancelReply,
|
||||
onSendStart,
|
||||
@@ -135,20 +151,54 @@ export default function Composer({
|
||||
|
||||
latest_text.current = text;
|
||||
|
||||
const history = useComposerHistory({
|
||||
texts: composerHistoryTexts({ messages: previous_messages || [] }),
|
||||
});
|
||||
/**
|
||||
* Assigned once the editor exists, since recalling a message writes
|
||||
* into it; the editor's keys read it through a ref.
|
||||
*/
|
||||
const walk_history = useRef<
|
||||
(params: { direction: "up" | "down"; empty: boolean }) => boolean
|
||||
>(() => false);
|
||||
|
||||
const input = useComposerEditor({
|
||||
placeholder: `Message ${bot.name}`,
|
||||
bots,
|
||||
workspaces,
|
||||
onChange: ({ markdown }) => setText(markdown),
|
||||
onChange: ({ markdown }) => {
|
||||
history.reset();
|
||||
setText(markdown);
|
||||
},
|
||||
onSubmit: () => send_ref.current(),
|
||||
onFiles: files.add,
|
||||
onHistory: (params) => walk_history.current(params),
|
||||
});
|
||||
const editor = input.editor;
|
||||
|
||||
walk_history.current = ({ direction, empty }) => {
|
||||
const next = history.step({
|
||||
direction,
|
||||
draft: latest_text.current,
|
||||
empty,
|
||||
});
|
||||
|
||||
if (!next) return false;
|
||||
|
||||
setText(next.text);
|
||||
input.setMarkdown({ markdown: next.text });
|
||||
editor?.commands.focus("end");
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
useImperativeHandle(
|
||||
handle_ref,
|
||||
() => ({ insertQuote: input.insertQuote }),
|
||||
[input.insertQuote],
|
||||
() => ({
|
||||
insertQuote: input.insertQuote,
|
||||
insertText: input.insertText,
|
||||
}),
|
||||
[input.insertQuote, input.insertText],
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -221,6 +271,17 @@ export default function Composer({
|
||||
files.restore({ attachments });
|
||||
};
|
||||
|
||||
/**
|
||||
* Empties the input's text, without sending it: what was typed is
|
||||
* dropped, the quote and the picked files stay.
|
||||
*/
|
||||
function clearText() {
|
||||
setText("");
|
||||
history.reset();
|
||||
input.clear();
|
||||
editor?.commands.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* The bubble and the bot's "getting your message" row show at once, and
|
||||
* the input empties, so a slow connection never holds any of it. The
|
||||
@@ -285,6 +346,7 @@ export default function Composer({
|
||||
onCancelReply?.();
|
||||
|
||||
setText("");
|
||||
history.reset();
|
||||
input.clear();
|
||||
files.clear();
|
||||
|
||||
@@ -363,6 +425,11 @@ export default function Composer({
|
||||
title={error}
|
||||
/>
|
||||
|
||||
<ComposerClearButton
|
||||
disabled={!text.trim()}
|
||||
onClick={clearText}
|
||||
/>
|
||||
|
||||
{recorder.supported ? (
|
||||
<ComposerVoiceButton
|
||||
state={recorder.state}
|
||||
|
||||
@@ -63,7 +63,8 @@ import requestLiveCrewRefresh from "@/src/functions/frontend/request-live-crew-r
|
||||
* when the back button restores the page. Older messages load as the
|
||||
* thread scrolls up. `?session_id=` opens another session of the
|
||||
* conversation; a closed one shows, in the composer's place, a link to
|
||||
* where the conversation went on.
|
||||
* where the conversation went on. Up recalls the last message the user
|
||||
* sent, in the composer.
|
||||
*/
|
||||
export default function Conversation() {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
@@ -381,6 +382,8 @@ export default function Conversation() {
|
||||
onReply: ({ message }: { message: BotMessageWithAttachments }) =>
|
||||
setReplyTo(message),
|
||||
onReact: reactToMessage,
|
||||
onUseSuggestion: ({ text }: { text: string }) =>
|
||||
composer.current?.insertText({ text }),
|
||||
}),
|
||||
[],
|
||||
);
|
||||
@@ -467,6 +470,7 @@ export default function Conversation() {
|
||||
voice={pageProps?.bot_voice}
|
||||
has_browsers={Boolean(pageProps?.has_browsers)}
|
||||
max_chars={pageProps?.message_max_chars}
|
||||
previous_messages={thread_messages}
|
||||
reply_to={reply_to}
|
||||
onCancelReply={() => setReplyTo(null)}
|
||||
onSendStart={({ message }) =>
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import stepComposerHistory, {
|
||||
EmptyComposerHistory,
|
||||
type ComposerHistoryState,
|
||||
} from "./composer-history-step";
|
||||
|
||||
/** Presses arrows in turn, collecting what the input took each time. */
|
||||
function walk({
|
||||
texts,
|
||||
presses,
|
||||
draft = "",
|
||||
empty = true,
|
||||
state = EmptyComposerHistory,
|
||||
}: {
|
||||
texts: string[];
|
||||
presses: ("up" | "down")[];
|
||||
draft?: string;
|
||||
empty?: boolean;
|
||||
state?: ComposerHistoryState;
|
||||
}) {
|
||||
const shown: (string | null)[] = [];
|
||||
let current = state;
|
||||
let in_input = draft;
|
||||
|
||||
for (const direction of presses) {
|
||||
const next = stepComposerHistory({
|
||||
state: current,
|
||||
texts,
|
||||
direction,
|
||||
draft: in_input,
|
||||
empty,
|
||||
});
|
||||
|
||||
shown.push(next ? next.text : null);
|
||||
|
||||
if (next) {
|
||||
current = next.state;
|
||||
in_input = next.text;
|
||||
}
|
||||
|
||||
/** Once a message is in, the input isn't empty any more. */
|
||||
empty = false;
|
||||
}
|
||||
|
||||
return { shown, state: current, in_input };
|
||||
}
|
||||
|
||||
const texts = ["first", "second", "third"];
|
||||
|
||||
describe("stepComposerHistory", () => {
|
||||
test("Up on an empty input recalls the newest message", () => {
|
||||
const { shown } = walk({ texts, presses: ["up"] });
|
||||
|
||||
expect(shown).toEqual(["third"]);
|
||||
});
|
||||
|
||||
test("Up again walks back through older messages", () => {
|
||||
const { shown } = walk({ texts, presses: ["up", "up", "up"] });
|
||||
|
||||
expect(shown).toEqual(["third", "second", "first"]);
|
||||
});
|
||||
|
||||
test("Up on the oldest message is the editor's; the input stays as it is", () => {
|
||||
const { shown, in_input } = walk({ texts, presses: ["up", "up", "up", "up"] });
|
||||
|
||||
expect(shown).toEqual(["third", "second", "first", null]);
|
||||
expect(in_input).toEqual("first");
|
||||
});
|
||||
|
||||
test("Down comes forward again and then back to what was being typed", () => {
|
||||
const { shown, in_input } = walk({
|
||||
texts,
|
||||
presses: ["up", "up", "down", "down"],
|
||||
draft: "half a thought",
|
||||
});
|
||||
|
||||
expect(shown).toEqual(["third", "second", "third", "half a thought"]);
|
||||
expect(in_input).toEqual("half a thought");
|
||||
});
|
||||
|
||||
test("the draft survives walking all the way back and forth", () => {
|
||||
const { in_input, state } = walk({
|
||||
texts,
|
||||
presses: ["up", "up", "up", "down", "down", "down"],
|
||||
draft: "an edit",
|
||||
});
|
||||
|
||||
expect(in_input).toEqual("an edit");
|
||||
expect(state).toEqual(EmptyComposerHistory);
|
||||
});
|
||||
|
||||
test("Down on the draft is the editor's", () => {
|
||||
const { shown } = walk({ texts, presses: ["down"] });
|
||||
|
||||
expect(shown).toEqual([null]);
|
||||
});
|
||||
|
||||
test("Up with text being edited moves the cursor, never replaces the text", () => {
|
||||
const { shown } = walk({
|
||||
texts,
|
||||
presses: ["up"],
|
||||
draft: "still typing",
|
||||
empty: false,
|
||||
});
|
||||
|
||||
expect(shown).toEqual([null]);
|
||||
});
|
||||
|
||||
test("Up recalls nothing in a conversation with no earlier message", () => {
|
||||
const { shown } = walk({ texts: [], presses: ["up"] });
|
||||
|
||||
expect(shown).toEqual([null]);
|
||||
});
|
||||
|
||||
test("recalling the only message and pressing Up again stops there", () => {
|
||||
const { shown } = walk({ texts: ["only"], presses: ["up", "up"] });
|
||||
|
||||
expect(shown).toEqual(["only", null]);
|
||||
});
|
||||
|
||||
test("a session that holds fewer messages never reads past the oldest", () => {
|
||||
const { shown, in_input } = walk({
|
||||
texts: ["newest"],
|
||||
presses: ["up", "down"],
|
||||
state: { index: 3, draft: "my draft" },
|
||||
});
|
||||
|
||||
expect(shown).toEqual([null, "my draft"]);
|
||||
expect(in_input).toEqual("my draft");
|
||||
});
|
||||
|
||||
test("the state it hands back is what the next press starts from", () => {
|
||||
const first = stepComposerHistory({
|
||||
state: EmptyComposerHistory,
|
||||
texts,
|
||||
direction: "up",
|
||||
draft: "draft",
|
||||
empty: true,
|
||||
});
|
||||
|
||||
expect(first?.state).toEqual({ index: 1, draft: "draft" });
|
||||
expect(first?.text).toEqual("third");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Where the Up and Down arrows stand in the user's previous messages: 0 is
|
||||
* what they were typing, 1 the newest message recalled, 2 the one before it.
|
||||
*/
|
||||
export type ComposerHistoryState = {
|
||||
index: number;
|
||||
/**
|
||||
* What was in the input when the newest message was recalled, put back
|
||||
* when the arrows come down past it again.
|
||||
*/
|
||||
draft: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The input as the user left it: what they type is theirs, not a message
|
||||
* from before.
|
||||
*/
|
||||
export const EmptyComposerHistory: ComposerHistoryState = { index: 0, draft: "" };
|
||||
|
||||
/**
|
||||
* One press of an arrow through the user's previous messages, oldest last:
|
||||
* Up recalls the newest from an empty input and older ones from there, Down
|
||||
* walks back to the draft. Null when the key is the editor's own (nothing
|
||||
* to recall, no older message, or text in the input the user is editing).
|
||||
*/
|
||||
export default function stepComposerHistory({
|
||||
state,
|
||||
texts,
|
||||
direction,
|
||||
draft,
|
||||
empty,
|
||||
}: {
|
||||
state: ComposerHistoryState;
|
||||
/** What the user typed before, oldest first. */
|
||||
texts: string[];
|
||||
direction: "up" | "down";
|
||||
/** What's in the input now. */
|
||||
draft: string;
|
||||
/** Whether the input has nothing in it. */
|
||||
empty: boolean;
|
||||
}): { state: ComposerHistoryState; text: string } | null {
|
||||
const count = texts.length;
|
||||
|
||||
if (!state.index) {
|
||||
/**
|
||||
* Text being edited keeps Up for moving the cursor: only an empty
|
||||
* input starts walking back through the messages.
|
||||
*/
|
||||
if (direction == "down" || !empty || !count) return null;
|
||||
|
||||
return { state: { index: 1, draft }, text: texts[count - 1]! };
|
||||
}
|
||||
|
||||
/**
|
||||
* A session the input followed may hold fewer messages than the one the
|
||||
* arrows started in: the oldest one left is as far back as it goes.
|
||||
*/
|
||||
const index = Math.min(state.index, count);
|
||||
|
||||
if (direction == "up") {
|
||||
if (index >= count) return null;
|
||||
|
||||
return {
|
||||
state: { ...state, index: index + 1 },
|
||||
text: texts[count - (index + 1)]!,
|
||||
};
|
||||
}
|
||||
|
||||
if (index <= 1) return { state: EmptyComposerHistory, text: state.draft };
|
||||
|
||||
return {
|
||||
state: { ...state, index: index - 1 },
|
||||
text: texts[count - (index - 1)]!,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import composerHistoryTexts from "./composer-history-texts";
|
||||
|
||||
const sent = (text: string) => ({ author: "user" as const, text });
|
||||
const answered = (text: string) => ({ author: "bot" as const, text });
|
||||
|
||||
describe("composerHistoryTexts", () => {
|
||||
test("keeps what the user typed, oldest first", () => {
|
||||
const texts = composerHistoryTexts({
|
||||
messages: [
|
||||
sent("plan the migration"),
|
||||
answered("Here's the plan"),
|
||||
sent("ship it tonight"),
|
||||
],
|
||||
});
|
||||
|
||||
expect(texts).toEqual(["plan the migration", "ship it tonight"]);
|
||||
});
|
||||
|
||||
test("leaves out the bot's answers and blank messages", () => {
|
||||
const texts = composerHistoryTexts({
|
||||
messages: [answered("Morning"), sent(" "), sent(""), sent("real text")],
|
||||
});
|
||||
|
||||
expect(texts).toEqual(["real text"]);
|
||||
});
|
||||
|
||||
test("leaves out what a chatroom or an install request wrote on the user's side", () => {
|
||||
const texts = composerHistoryTexts({
|
||||
messages: [
|
||||
sent("ask the crew"),
|
||||
{ author: "user" as const, text: "Room closed: the answer", from_chatroom_id: 12 },
|
||||
{ author: "user" as const, text: "Installed numpy", from_install_request_id: 3 },
|
||||
],
|
||||
});
|
||||
|
||||
expect(texts).toEqual(["ask the crew"]);
|
||||
});
|
||||
|
||||
test("trims a message's text around it", () => {
|
||||
const texts = composerHistoryTexts({ messages: [sent(" keep this ")] });
|
||||
|
||||
expect(texts).toEqual(["keep this"]);
|
||||
});
|
||||
|
||||
test("is empty for a session with nothing sent yet", () => {
|
||||
expect(composerHistoryTexts({ messages: [answered("Hello")] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import isCrewMessage from "@/src/utils/is-crew-message";
|
||||
|
||||
/**
|
||||
* A message the Up arrow can recall: only what the user typed here. A
|
||||
* chatroom's outcome and an install request's answer are stored on the
|
||||
* user's side, but the user wrote neither.
|
||||
*/
|
||||
export type ComposerHistoryMessage = Pick<
|
||||
BotMessageWithAttachments,
|
||||
"author" | "text" | "from_chatroom_id" | "from_install_request_id"
|
||||
>;
|
||||
|
||||
/**
|
||||
* What the user typed, oldest first, so the newest message Up recalls is
|
||||
* its last entry.
|
||||
*/
|
||||
export default function composerHistoryTexts({
|
||||
messages,
|
||||
}: {
|
||||
messages: ComposerHistoryMessage[];
|
||||
}) {
|
||||
const texts: string[] = [];
|
||||
|
||||
for (const message of messages) {
|
||||
if (message.author != "user" || isCrewMessage({ message })) continue;
|
||||
|
||||
const text = message.text?.trim();
|
||||
|
||||
if (text) texts.push(text);
|
||||
}
|
||||
|
||||
return texts;
|
||||
}
|
||||
@@ -13,11 +13,13 @@ import {
|
||||
} from "@/src/utils/link-computer-refs";
|
||||
import { parseFolderRefHref } from "@/src/utils/folder-ref";
|
||||
import { botQuestionRefId } from "@/src/utils/bot-question-ref";
|
||||
import { botSuggestionRefId } from "@/src/utils/bot-suggestion-ref";
|
||||
import { graphicRefId } from "@/src/utils/graphic-ref";
|
||||
import { chatroomRefId } from "@/src/utils/chatroom-ref";
|
||||
import { taskRefId } from "@/src/utils/task-ref";
|
||||
import { generalSettingsRefId } from "@/src/utils/general-settings-ref";
|
||||
import BotQuestionRefChip from "../(partials)/bot-question-ref-chip";
|
||||
import BotSuggestionsRef from "../(partials)/bot-suggestions-ref";
|
||||
import BotRefChip from "../(partials)/bot-ref-chip";
|
||||
import ChatroomRefChip from "../(partials)/chatroom-ref-chip";
|
||||
import ComputerRefChip from "../(partials)/computer-ref-chip";
|
||||
@@ -39,7 +41,8 @@ import WorkspaceRefChip from "../(partials)/workspace-ref-chip";
|
||||
* computer, a bot or workspace a link to it, a file a chip that previews
|
||||
* it, a folder a chip that opens it in the files browser, a proposal a chip
|
||||
* that opens the confirm card, a secret a masked chip, a secret request or
|
||||
* questions a chip that opens their card, a graphic the graphic itself, a
|
||||
* questions a chip that opens their card, suggested next steps the
|
||||
* buttons that fill the input, a graphic the graphic itself, a
|
||||
* chatroom or task a chip that opens it, a setting a pill to that group of
|
||||
* Settings > General. Null for any other link.
|
||||
*/
|
||||
@@ -110,6 +113,9 @@ export default function refChipForHref({ href }: { href?: string }): ReactNode |
|
||||
const question_id = botQuestionRefId({ href });
|
||||
if (question_id) return <BotQuestionRefChip question_id={question_id} />;
|
||||
|
||||
const suggestion_id = botSuggestionRefId({ href });
|
||||
if (suggestion_id) return <BotSuggestionsRef suggestion_id={suggestion_id} />;
|
||||
|
||||
const chatroom_id = chatroomRefId({ href });
|
||||
|
||||
if (chatroom_id) return <ChatroomRefChip chatroom_id={chatroom_id} />;
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabBotSuggestionView from "@/src/functions/backend/db/bot-suggestions/grab-bot-suggestion-view";
|
||||
import { BotSuggestionIdSchema } from "@/src/schemas/bot-suggestion-schema";
|
||||
import type { BotSuggestionView } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* `GET ?suggestion_id=`: next steps a bot suggested to the session user,
|
||||
* as their buttons show them. Nobody else reads them.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<BotSuggestionView>> = async ({ req, query }) => {
|
||||
try {
|
||||
if (req.method != "GET") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
const { suggestion_id } = parseWithSchema({ schema: BotSuggestionIdSchema, data: query });
|
||||
|
||||
return { success: true, singleRes: await grabBotSuggestionView({ suggestion_id, user_id: user.id }) };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import { z } from "zod";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
/**
|
||||
* The next steps a bot suggests (`suggest_next_steps`), as it writes them
|
||||
* and as they're stored: short enough to read as a button, distinct so a
|
||||
* step is never offered twice.
|
||||
*/
|
||||
export const BotSuggestionStepsSchema = z
|
||||
.array(z.string().trim().min(1).max(AppData.BotSuggestionStepMaxChars, `Keep each step under ${AppData.BotSuggestionStepMaxChars} characters`))
|
||||
.min(1, "Suggest at least one next step")
|
||||
.max(AppData.BotSuggestionMaxSteps, `Suggest at most ${AppData.BotSuggestionMaxSteps} next steps`)
|
||||
.refine((steps) => new Set(steps.map((step) => step.toLowerCase())).size == steps.length, "Steps must differ");
|
||||
|
||||
export const BotSuggestionIdSchema = z.object({
|
||||
suggestion_id: z.coerce.number().int().positive("Pick the suggestions"),
|
||||
});
|
||||
|
||||
export type BotSuggestionIdRequest = z.infer<typeof BotSuggestionIdSchema>;
|
||||
@@ -836,6 +836,18 @@ export type BotQuestionView = {
|
||||
bot_name: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Next steps a bot suggested under its answer (`[suggestion:ID]`), shown
|
||||
* as buttons that put the step in the user's input.
|
||||
*/
|
||||
export type BotSuggestionView = {
|
||||
id: number;
|
||||
title: string;
|
||||
steps: string[];
|
||||
bot_id: number;
|
||||
bot_name: string;
|
||||
};
|
||||
|
||||
export type SecretRequestView = {
|
||||
id: number;
|
||||
key: string;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
type Params = {
|
||||
id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* How a bot names next steps it suggested: `[suggestion:4]`. The chat
|
||||
* turns it into a link (`linkComputerRefs`) that renders as a row of
|
||||
* buttons putting each step in the user's input.
|
||||
*/
|
||||
export default function botSuggestionRef({ id }: Params) {
|
||||
return `[suggestion:${id}]`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The link target a suggestion ref becomes, e.g. `#suggestion-4`.
|
||||
*/
|
||||
export const BotSuggestionRefHrefPrefix = "#suggestion-";
|
||||
|
||||
/**
|
||||
* The id in a suggestion ref's link target, or null.
|
||||
*/
|
||||
export function botSuggestionRefId({ href }: { href?: string | null }) {
|
||||
if (!href?.startsWith(BotSuggestionRefHrefPrefix)) return null;
|
||||
|
||||
const id = Number(href.slice(BotSuggestionRefHrefPrefix.length));
|
||||
|
||||
return Number.isInteger(id) && id > 0 ? id : null;
|
||||
}
|
||||
@@ -36,6 +36,10 @@ describe("exportMessageText", () => {
|
||||
expect(exportMessageText({ text: "Pick: [question:4]", ...names, heading_offset: 0 })).toBe("Pick: (questions 4)");
|
||||
});
|
||||
|
||||
test("words suggested next steps by number", () => {
|
||||
expect(exportMessageText({ text: "Then: [suggestion:4]", ...names, heading_offset: 0 })).toBe("Then: (next steps 4)");
|
||||
});
|
||||
|
||||
test("words a task once, even after the bot's own word for it", () => {
|
||||
expect(exportMessageText({ text: "Task [task:27] and [task:3]", ...names, heading_offset: 0 })).toBe(
|
||||
"Task #27 and task #3",
|
||||
|
||||
@@ -87,6 +87,7 @@ function wordRefs({
|
||||
.replace(/\[secret:(\d+)\](?!\()/g, "(secret $1, hidden)")
|
||||
.replace(/\[secret-request:(\d+)\](?!\()/g, "(secret request $1)")
|
||||
.replace(/\[question:(\d+)\](?!\()/g, "(questions $1)")
|
||||
.replace(/\[suggestion:(\d+)\](?!\()/g, "(next steps $1)")
|
||||
.replace(/\[graphic:(\d+)\](?!\()/g, "(graphic $1)")
|
||||
.replace(
|
||||
/(\btask\s+)?\[task:(\d+)\](?!\()/gi,
|
||||
|
||||
@@ -8,6 +8,7 @@ import proposalRef from "./proposal-ref";
|
||||
import secretRef from "./secret-ref";
|
||||
import secretRequestRef from "./secret-request-ref";
|
||||
import botQuestionRef from "./bot-question-ref";
|
||||
import botSuggestionRef from "./bot-suggestion-ref";
|
||||
import takeOverRef from "./take-over-ref";
|
||||
import generalSettingsRef from "./general-settings-ref";
|
||||
|
||||
@@ -61,6 +62,13 @@ describe("linkComputerRefs", () => {
|
||||
expect(linkComputerRefs({ text: "See `[question:4]`" })).toBe("See [questions 4](#question-4)");
|
||||
});
|
||||
|
||||
test("links the next steps a bot suggested, also when quoted alone in code", () => {
|
||||
expect(linkComputerRefs({ text: `Done. ${botSuggestionRef({ id: 4 })}` })).toBe(
|
||||
"Done. [next steps 4](#suggestion-4)",
|
||||
);
|
||||
expect(linkComputerRefs({ text: "See `[suggestion:4]`" })).toBe("See [next steps 4](#suggestion-4)");
|
||||
});
|
||||
|
||||
test("links take-over requests", () => {
|
||||
expect(
|
||||
linkComputerRefs({
|
||||
|
||||
@@ -69,7 +69,7 @@ export const SecretRequestRefHrefPrefix = "#secret-request-";
|
||||
/**
|
||||
* The kinds of ref a message can carry, as written before the colon.
|
||||
*/
|
||||
const RefKinds = "computer|take-over|bot|workspace|proposal|hook-proposal|secret|secret-request|question|graphic|room|task|setting|file|folder";
|
||||
const RefKinds = "computer|take-over|bot|workspace|proposal|hook-proposal|secret|secret-request|question|suggestion|graphic|room|task|setting|file|folder";
|
||||
|
||||
/**
|
||||
* A code span holding nothing but one ref (`` `[file:12]` ``): bots often
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { BotQuestionRefHrefPrefix } from "./bot-question-ref";
|
||||
import { BotSuggestionRefHrefPrefix } from "./bot-suggestion-ref";
|
||||
import { ChatroomRefHrefPrefix } from "./chatroom-ref";
|
||||
import { GeneralSettingsRefHrefPrefix } from "./general-settings-ref";
|
||||
import { GraphicRefHrefPrefix } from "./graphic-ref";
|
||||
@@ -22,7 +23,8 @@ import {
|
||||
* (`[workspace:2]`), file ref (`[file:12]`), folder ref
|
||||
* (`[folder:computer:3:seo/raw]`), proposal ref (`[proposal:7]`) and hook
|
||||
* proposal ref (`[hook-proposal:4]`), secret ref (`[secret:12]`) and secret
|
||||
* request ref (`[secret-request:4]`), question ref (`[question:4]`), graphic ref (`[graphic:5]`) and
|
||||
* request ref (`[secret-request:4]`), question ref (`[question:4]`), suggestion ref (`[suggestion:4]`),
|
||||
* graphic ref (`[graphic:5]`) and
|
||||
* chatroom ref (`[room:<id>]`) and task ref (`[task:20]`), and a setting
|
||||
* ref (`[setting:run-limits:reply_steps]`, pointing at that section of
|
||||
* Settings > General) in a stretch of message text (never code) into a
|
||||
@@ -66,6 +68,10 @@ export default function linkRefsInText({ text }: { text: string }) {
|
||||
/\[question:(\d+)\](?!\()/g,
|
||||
(_, id: string) => `[questions ${id}](${BotQuestionRefHrefPrefix}${id})`,
|
||||
)
|
||||
.replace(
|
||||
/\[suggestion:(\d+)\](?!\()/g,
|
||||
(_, id: string) => `[next steps ${id}](${BotSuggestionRefHrefPrefix}${id})`,
|
||||
)
|
||||
.replace(/\[graphic:(\d+)\](?!\()/g, (_, id: string) => `[graphic ${id}](${GraphicRefHrefPrefix}${id})`)
|
||||
.replace(/\[room:(\d+)\](?!\()/g, (_, id: string) => `[room ${id}](${ChatroomRefHrefPrefix}${id})`)
|
||||
.replace(/\[task:(\d+)\](?!\()/g, (_, id: string) => `[task ${id}](${TaskRefHrefPrefix}${id})`)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import parseBotSuggestionRow from "./parse-bot-suggestion-row";
|
||||
|
||||
describe("parseBotSuggestionRow", () => {
|
||||
test("reads the suggested steps", () => {
|
||||
expect(parseBotSuggestionRow({ row: { steps: JSON.stringify(["Write the report", "Email the team"]) } })).toEqual({
|
||||
steps: ["Write the report", "Email the team"],
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps only readable strings", () => {
|
||||
expect(parseBotSuggestionRow({ row: { steps: JSON.stringify(["Write it", 4, "", " "]) } })).toEqual({ steps: ["Write it"] });
|
||||
});
|
||||
|
||||
test("reads nothing from a missing or broken column", () => {
|
||||
expect(parseBotSuggestionRow({ row: { steps: null } })).toEqual({ steps: [] });
|
||||
expect(parseBotSuggestionRow({ row: { steps: "{" } })).toEqual({ steps: [] });
|
||||
expect(parseBotSuggestionRow({ row: { steps: JSON.stringify({ a: 1 }) } })).toEqual({ steps: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
type Params = {
|
||||
row: { steps?: string | null };
|
||||
};
|
||||
|
||||
/**
|
||||
* A `bot_suggestions` row's stored JSON read back: the steps it holds, and
|
||||
* none if the column isn't readable.
|
||||
*/
|
||||
export default function parseBotSuggestionRow({ row }: Params): { steps: string[] } {
|
||||
if (!row.steps) return { steps: [] };
|
||||
|
||||
try {
|
||||
const steps = JSON.parse(row.steps) as unknown;
|
||||
|
||||
return {
|
||||
steps: Array.isArray(steps)
|
||||
? steps.filter((step): step is string => typeof step == "string" && Boolean(step.trim()))
|
||||
: [],
|
||||
};
|
||||
} catch {
|
||||
return { steps: [] };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user