Compare commits

...
19 Commits
Author SHA1 Message Date
tben 99f47ffe36 Bump version
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-16 12:32:36 +01:00
tben f068f7f58e Plan hard work with the user, then work it a step per reply
Replies that tried to do everything at once came out long and hard to
follow. A bot can now lay the work out as a plan instead.

`create_plan` stores one plan per conversation (`bot_plans`) and the reply
shows it as a card: its steps, where they stand and what it is for. The plan
goes nowhere until the user acts on it there, and they can rewrite its steps
first (steps already done stay as they are, `planStepsRewriteProblem`).

Once approved, each step is its own reply job (`params.plan_id`) with the
bot's tools, memory and browsers, one step per reply with a short report,
and `continueBotPlan` queues the next one: nothing follows while the user is
being asked something, while work was handed off (`WorkStartingTools`), or
when the plan was paused, ended or a reply already waits in the conversation.
A routine gets its plan approved at once and works it to the end in the run
(`ScheduledPlanNote`).

Bots are also told to keep a plan in memory when the same work comes back,
so a way of working survives as a runbook.

The card is built from spans, since its ref sits inside the message's
paragraph.
2026-11-16 07:39:22 +01:00
tben b860dfe859 Catch a forged app record by its shape, so the correction can be sent
A reply that claimed a start_task it never called was rightly stopped, but the
check searched the whole answer for the phrase, so the bot's own correction -
"the [App record: ...] line was mine, not the app's" - tripped the same fault.
Three faults, the rewrites ran out and the job failed: the lie stayed in the
thread and the apology never reached the user (message #801, run #468).

- app-record-claims: only a line in the app's record shape naming tools this
  reply didn't call is unsupported. A line the record supports - the old lie
  quoted after really calling start_task - and a mention inside a sentence or
  code span pass; strip-app-records now shares that one line shape.
- A fault note never quotes the text it faults or says "a report will follow",
  which is itself pattern 4: the note had been teaching the model the string
  that re-faulted it, and every reply's prompt already ships that shape in
  ActionCheckNote. Tests pin both.
- ask_crew left over from 03e062d's rename in WritingToolNames,
  WorkStartingTools, HandOverTaskNote and the hand-over description: a reply
  that really had asked the crew was faulted for saying it was working.
  tool-name-lists.test.ts pins those lists to the tools the harness declares.

Verification: bun run typecheck clean; bun run test 2052 pass, 0 fail
2026-11-16 06:07:33 +01:00
tben 5ba7747e11 Catch a reply that says it started a run it never started
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
A reply claimed "I'm starting the hydration work as a single-route proof"
with no tool call behind it and the run ended there, so nothing ran. The
review missed it twice over: `claimsWorkUnderWay` had no pattern for the
phrasing (only "once the run is back|done|finished|complete", never
"once the run reports"), and the model wrote the app's own
"[App record: ...]" line itself, naming `update_task, start_task`, which
made the debug view read as tools having run.

The record line is the app's to write, so an answer forging one that
claims tools is now faulted and sent back; a mimic that only says
"called no tools" is still just stripped, so a formatting habit cannot
burn rewrites or fail a reply.

`update_task` also never moved `updated_at`, so a task whose status just
changed did not rise: `grab-tasks` orders by it, and the other task
helpers set it themselves.
2026-11-15 19:07:05 +01:00
tben ca070ccc35 v0.21.4
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-15 17:36:23 +01:00
tben 3268f049f9 Retry a ref chip's read, so its steps and card show without a reload
A failed or hung read was kept as a miss for the life of the page, so a [suggestion:ID] or [question:ID] pushed with a run showed 'not available', or nothing at all, until the page was reloaded. One loader now keeps only what was read, aborts a read that hangs, and tries again.
2026-11-15 17:36:23 +01:00
tben 2d57ba560c v0.21.3
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-15 10:34:59 +01:00
tben c1c307e51c Call a split task's work subtasks, and let a subtask open its parent 2026-11-15 10:32:39 +01:00
tben 7bc74dfe8e Split a workspace-wide task into parts, and let any task join or leave one
A workspace-wide task (`workspace_id`, `bot_id` null) can now be split into
parts: one bot each, one level deep, with `tasks.parent_task_id` pointing at
it. A bot task joins or leaves a parent through `update_task`
(`parent_task_id`, `unlink_parent`) and crew managers through "Make it a part
of..." and "Unlink from parent" on the task's panel; both sides get a note.

The parent stays open until someone verifies every part, and the rules live
in one place each: `subtaskLinkProblem`, `subtaskAttachProblem`,
`subtaskMoveProblem` (refused by `moveTask`, so promotion and hand-over both
decline a task that is a part or has parts) and `subtaskDeleteProblem`
(deletion takes finished parts with it, refuses while one is open).
`AppData.TaskSubtaskMaxPerParent` caps a parent's parts.

The workspace dashboard's task list now starts with the workspace-wide tasks
and then each bot's, cut to `AppData.TaskSectionShown` rows with the rest in
`WorkspaceTasksModal`, and a wide row wears the workspace's picture
(`WorkspaceAvatar`) instead of a crew glyph.
2026-11-15 10:04:53 +01:00
tben c705da17a1 v0.21.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-15 07:58:31 +01:00
tben f9f2a9b0b6 Hide a crew request's bar when there's no session to return to 2026-11-15 07:58:31 +01:00
tben 5d2ac342f0 Take a dropped session's job rows with it
Foreign keys are off outside the server process, so a helper that deletes a
parent row deletes its children. A crew request's hidden review session was
dropped with only its traces and tasks, leaving the review job that had just
ended, its queue updates and what its calls were billed pointing at a session
that no longer existed: the next `bun db:schema` refused the database
(bots_queue -> bot_sessions, token_usages -> bot_sessions).

The empty review session now goes through deleteSessionRows, and so does the
empty active session reopening closes, which had the same bare delete. Checked
against a copy of a real database: the review's session, job, updates, traces
and billed calls go together, while a session with an open job, with a message
or an answer's own session stays.
2026-11-15 07:50:58 +01:00
tben f453796a8d Let a bot's own models win in a workspace
Picking a model for one bot inside a workspace changed it for every bot
there: the Models modal saved the workspace's setting when it was opened
in a workspace (bot_harness_form), and resolution read the workspace row
before the bot's, so the group setting shadowed any per-bot pick.

A bot's own models now win, its workspace's apply to the bots that have
none of their own (the coordinator there included), then the defaults.
The modal in a workspace saves the bot's own models again ("Same as the
default" drops them), the workspace's Models page stays the group
fallback and the coordinator in a workspace still edits it, and the modals
name whose models they change. The picker that decides the order is its
own module, tested.
2026-11-15 07:44:25 +01:00
tben fac3f66896 Never send an answer the review still faults
The gate ran once per run, so a model that repeated itself word for
word had its claim delivered: a reply said a run was under way, was
sent back for it, and came back identical to the user.

Review now checks every answer the run writes, a bounded number of
times (AppData.HarnessReviewRewrites), tells a model that wrote the
same message back that it did (repeatedAnswerNote), and past the
bound returns review_note instead of the text: the reply job fails and
says so (BotJobFatalError), so nothing the app knows is wrong goes out.
2026-11-15 07:36:55 +01:00
tben 4292a2fa40 Spin the rail row of a bot that has work running
The face alone was too quiet at 32px: a bot answering elsewhere or working
on a task looked idle in the rail. A working bot now shows an arc in its own
colour where its relative time was, and the time comes back when the work
ends. Nothing goes on the stone: no ring, badge or corner mark.
2026-11-15 07:28:11 +01:00
tben 0d2c683933 Show a crew request's bar at the top of its conversation 2026-11-15 07:09:44 +01:00
tben 381e5d3107 v0.21.1
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-14 16:28:07 +01:00
tben c14df6c049 Show a task's id in the task list
A bot's list named its tasks by title alone, so a user reading a task's
`[task:ID]` in a message, a report or a debug log had no way to match it to
the row. Every row now carries `#<id>` after its title (a task with no title
keeps `Task <id>`), inside the same button, so clicking it opens the task.
The button's content wrapper shrinks, so a long title truncates and the id
stays visible.

Pinned by task-list-item.render.test.tsx.
2026-11-14 16:26:38 +01:00
tben ece7cdd36f Keep a question in the conversation it was asked in
A delegated job's report was relayed verbatim into the requester's
conversation, so a worker's [question:ID] showed the same card in two
sessions: answered in one, left waiting in the other (and the card sent
its answers to whichever bot's page was open, so the worker that asked
never heard).

stripQuestionRefs takes those refs out of text copied into another bot's
conversation (a relayed report, a crew request's outcome, an install
request's answer) and the relay says which bot is waiting instead. The
answer and skip routes now post the user's message into the question's
own session (postBotQuestionAnswers), never the page's bot.
2026-11-14 16:25:53 +01:00
178 changed files with 6773 additions and 531 deletions
+11 -10
View File
@@ -79,7 +79,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- Bots, workspaces and computers belong to the install; their `user_id` is only the creator. Users reach them only through grants: `bot_users` (a worker's own chat) and `workspace_users` (every bot in that workspace).
- `crewRole` (`src/utils/rbac/crew-role.ts`): `super_admin` reaches everything and is the **only** one who chats with the coordinator; `admin` reaches every worker and workspace; `member` only their grants. `canManageCrew` (super admin + admin) creates/edits/deletes crew and grants access; DB helpers check it themselves (`assertCrewManager`).
- Access SQL lives in `src/utils/crew-access/` (tested against SQLite) and backs `grabChatBot`, `grabUserBot`, `grabUserWorkspace(s)`, `grabWorkspaceBot`, `grabBots`, `grabUserComputer(s)`.
- Conversations, faces and status lines are **per user** (`bot_sessions.user_id`, `bot_user_faces`). A job runs for its session's user, with that user's memory and reach. Page reads overlay the viewer's face (`botFaceSql`). Status lines never name a task.
- Conversations, faces and status lines are **per user** (`bot_sessions.user_id`, `bot_user_faces`). A job runs for its session's user, with that user's memory and reach. Page reads overlay the viewer's face (`botFaceSql`). Status lines never name a task. The rail row marks work with a spinner (`WorkingSpinner`) in the time's slot, from the face alone (`working`, so work anywhere for that user), and the time returns when it ends; the unread dot stays beside it. Nothing goes on the stone: no ring, badge or corner mark.
### Bot types
@@ -87,7 +87,7 @@ 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`.
- **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_plans` (a plan a bot wrote for work in pieces, its steps and their state), `bot_job_traces` (a run's debug view, 7 days by default). Enums in `src/dict/bot-dict.ts` and `src/dict/bot-plan-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; 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]/bots/[bot_id]` same conversation scoped to the workspace.
@@ -95,12 +95,13 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **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, 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), `[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 another bot passed on keep working.
- **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), `[plan:ID]` (a plan, as its card: steps, the one being worked, and the buttons to approve or change them), `[graphic:ID]` (a bot graphic, framed inline), `[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`. A chip reads its own row through `(utils)/ref-view-loader.ts`, which keeps only what it read: a read that failed or hung is retried (`AppData.BotRefViewRetryDelaysMs`, each after `BotRefViewTimeoutMs`), so a chip pushed with a run shows its steps or card without a reload. 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 another bot passed on 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 a crew request's run (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).
- **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. **The card belongs to the conversation it was asked in:** the answer and skip routes post that message into the question's own session (`postBotQuestionAnswers`), never the page's bot (a card answered on the requester's page woke the wrong bot), and `stripQuestionRefs` takes `[question:ID]` out of text copied into another bot's conversation (`relayJobToRequester`, a crew request's outcome, an install request's answer), which would otherwise show the same card in two sessions, answered in one and left waiting in the other. Replies and user-started tasks only: never routines, hook calls or a crew request's run (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`. 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.
- **Plans:** work with several pieces that build on each other is written down before it starts, and worked one step per reply, since a bot answering such a request in one message is how a reply turns into a wall of text. `create_plan` (title, goal, 3 to `AppData.BotPlanMaxSteps` steps) -> `bot_plans` (one open plan per conversation, `BotPlanOpenStates`) -> `[plan:ID]` (`BotPlanCard`); nothing of it runs until the user approves it there, and they change the steps first (`BotPlanEditModal` -> `save-plan`), though a step already worked stays at the top with its note (`planStepsRewriteProblem`). Approving queues the first step as an ordinary **reply** job with `params.plan_id`, in the same conversation, so it has the bot's tools, computers, memory and files; the run gets `PlanStepNote` and works that step alone, `complete_plan_step` marks it done with what it produced (the card checks it off, `pushBotPlan` -> `server:bot-plan`), and `continueBotPlan` (from `process-bot-job`, after the notice) queues the next one. It stops on its own when the user is needed (`needs_you`), when the reply handed work to a run (`WorkStartingTools`), or when an unanswered reply already waits in the session, and never counts an approval as a step: `done` is the app's call once no step is pending. A run that is a plan's step can't write or cancel a plan, only work it, change it (`update_plan`) or finish its step. An ordinary reply in a conversation whose plan is open gets `PlanWaitingNote`/`PlanActiveNote`/`PlanPausedNote` instead of plan tools, so a plan is only ever advanced by the app. A **routine** writes its plan with `approve: true` (`ScheduledPlanNote`): nobody is there to approve it, so it starts itself and the run works every step, reporting at the end. Plan tools are not closing tools: the card and one sentence about it are the reply. When a plan is one the work comes back to, the bot saves its steps with `update_memory` (`PlansNote`); a repeating job is a routine instead. `bot_plans` is deleted with its session (`deleteBotPlanRows`, from `deleteSessionRows`).
- **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.
@@ -125,21 +126,21 @@ Every run also gets `RequestScopeNote` (`src/data/harness-prompts.ts`): the user
- Handler `src/bots-queue/index.ts`: separate reply/task slots, heartbeat, a per-attempt deadline for replies (`AppData.BotJobAttemptTimeoutMs`; a task run has none, since its script may run for hours, and Stop ends it), one task per computer and one reply per session (`createKeyLock`). Work in `run-bot-job.ts` -> `run-bot-reply.ts` / `run-bot-task.ts`. Throw `BotJobFatalError` for failures retrying can't fix. A computer that's down (`isComputerDown`: failed, dead, exited) is one: `start_task` refuses it and a task run on it fails at once.
- Every model turn is a step in `bots_queue_updates` (tool names, never arguments; `describe-job-step.ts`, labels in `JobStepToolLabels`), pushed as `server:bot-job-update` by the live relay only. Steps feed the live working row alone: the `clear-job-steps` cron deletes them `AppData.BotJobStepsKeepMs` after the job ends, however it ended, keeping their count on `bots_queue.steps`. Never delete them the moment a job ends (the relay would miss the last ones).
- **A task run plans before it starts:** `planBotTask` (from `run-bot-task`) spends one turn, no tools, on the very system prompt the run then sends, so the provider's cache serves it and it costs little more than the plan. The answer is a bounded JSON plan (`BotTaskPlanSchema`, caps in `AppData.BotTaskPlan*`) that opens the run as `taskPlanNote` and shows as its first step line; `shouldPlanBotTask` keeps it off short runs (`AppData.BotTaskPlanMinSteps`). A plan that can't be written or read starts the run unplanned, never blocks it. **The wrap up is told what is on disk:** a task run passes `Params.wrap_up_note`, which runs `worktreeSummary` over the run's folders (`git status --porcelain` and `git diff --stat` per repository, nested ones included, at most 5) and puts the machine's own account in front of the wrap-up prompt, so the report is written from the tree and not from the run's memory of writing it.
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`). Before a reply goes out, `reviewBotReply` (the loop's `review`, once per run) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_bot` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
- **A bot can't vouch for itself:** a run's tool calls (`tool_uses`, names and ok, never arguments) go to the wrap-up turn when steps run out and onto the result message as `bot_messages.tool_log`; history follows each recorded bot message with an `[App record: ...]` line (`botMessagesToHarness`), and copies of that line in an answer are stripped (`stripAppRecords`, which shares the line shape with `appRecordLines`). Before a reply goes out, `reviewBotReply` (the loop's `review`) sends it back when it names a `[file:ID]`/`[task:ID]` that doesn't exist for the user, a `[setting:...]` ref the app can't resolve (`unresolvedSettingRefs`), or says work is under way or a report will follow (`claimsWorkUnderWay`) with no `start_task`/`delegate_task`/`ask_bot` this reply and nothing open from the session: bots wrote "I'm scanning now" plus made-up results in one answer. Review runs on every answer it writes, up to `AppData.HarnessReviewRewrites` rewrites (a repeat of the faulted message is told so, `repeatedAnswerNote`); past that the answer is never sent and the reply job fails instead (`review_note` -> `BotJobFatalError`), since a model that kept writing the same thing sends the claim anyway. **A fault must be something the bot can stop making:** only a whole line in the app's own record shape naming tools this reply didn't call is a forgery (`unsupportedAppRecordLines`) - the same text quoted inside a sentence is the bot naming its mistake, and job #468 faulted three rewrites in a row for that quote alone, so the lie stayed and the correction never reached the user. No fault note may itself contain the shape it faults or a `claimsWorkUnderWay` phrase. Tool names copied into a list (`WorkStartingTools`, `WritingToolNames`, `WrapUp*ToolNames`) are pinned to the tools the harness declares by `src/harness/tools/tool-name-lists.test.ts` (`ask_crew` outlived its rename to `ask_bot`, so a reply that really had asked the crew was faulted for saying so). A long bot message whose run called no tools shows "No tools used" (`MessageNoToolsChip`).
- **`start_task`/`delegate_task` jobs are runs, not tasks:** their results say `Run #<job id>` and that `list_tasks` doesn't show them (bots sent users to the tracker for them). `start_task` refuses a second open run in its session on the same computer unless `separate` (it would only wait behind it) and says how many runs are ahead on that computer. Its `max_steps` (`params.max_steps`) caps the run below the install's limit; the brief alone never did. Nothing wakes a bot when a run ends, so different follow-up work is queued at once with `separate`, never promised for later (`start_task`, `chatReplyNote`).
- **Replies take in messages sent mid-run** (`incoming`, `IncomingMessagesNote`, redraft); separate requests are acknowledged with `send_message` (interim). A queued reply finishes silently only when a finished reply already read every user message (`hasUnansweredMessage`), never by who wrote last. **Task runs take them in too** (`taskIncoming`, only runs the user follows: no routines, hook calls or rooms): everything the user wrote since the run was queued, at the start, between steps, past a report not yet out and by the wrap up (`incoming_notes`, `TaskIncomingNote`); a correction changes the work, anything else is left to the chat, and crew messages to the reply they wake. A reply is told which runs open in its session hear the user (`openRunsNote`), so a correction never starts a second run.
### Live updates
Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), `pushBotUpdated` (to the bot's whole audience), `server:bot-created|removed`, `server:workspace-created|updated|removed`, `server:computer-updated`, and the debug view's `server:bot-trace` (just the job and its session). Deletions push to the audience read **before** the delete. `liveRelay` (`src/live-relay/`) polls the DB every `AppData.LiveRelayPollMs` so work from other processes shows; clients dedupe by id. `useLiveBots` keeps rail and header current.
Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), `pushBotUpdated` (to the bot's whole audience), `server:bot-created|removed`, `server:workspace-created|updated|removed`, `server:computer-updated`, the debug view's `server:bot-trace` (just the job and its session), and a plan's card `server:bot-plan` (just its id and conversation). Deletions push to the audience read **before** the delete. `liveRelay` (`src/live-relay/`) polls the DB every `AppData.LiveRelayPollMs` so work from other processes shows; clients dedupe by id. `useLiveBots` keeps rail and header current.
### Crew requests (`bot_asks`)
A worker reaches another bot **only through the coordinator's gate**: `ask_bot` (every worker run with a session except hook calls; never the coordinator) queues a request (`createAsk`) for the run's user and place. Who can be asked is the app's call (`askableBots`): in a workspace its members, else every worker the user reaches. Whether the request should be passed on is the coordinator's judgement, in its instructions (`AskGateNote`); reach, membership, depth and the open cap are the app's. The gate is one turn of the coordinator with no tools (`runAskReview`, queued by `enqueueAskReview`, dispatched from `run-bot-job` on `params.stage == "review"`) answering bounded JSON (`AskDecisionSchema`: `approve`, `redirect` or `refuse`, the bot, and a one-sentence reason) which `applyAskDecision` carries out. A refusal ends the request (`refused`) with its reason; an approval or a redirect sends the brief to the target (`enqueueAskAnswer`) as one reply job in **a new session of the target's conversation with that user for the request's workspace** (`startBotSession` with `workspace_id`, so the run keeps its workspace context and the conversation they were in closes; never a hidden session), titled from the request, where the brief lands as a crew message naming that workspace (`from_ask_id`, `askRequestMessage`, pushed live) and the answer as the bot's reply; the target's own chat (and any other place it is read from) shows the request's row, whose `Open` link appears only outside the request's own thread (`answer_ask.session_id != session_id`), while the session carries `AskSessionBar`, built from `previous_session_id` (recorded when the request took its session), back to the conversation the user was in; an outcome message carries the `[ask:ID]` pill (`askRef`, `AskRefChip`, `api/admin/bots/ask`) which opens the session it ran in, in the bot that answered it; only the gate's own review run uses a throwaway session (`ensureAskSession`, status `ask`, deleted when empty). Stopping the target's run ends the request too (`stopBotJobs` reads `params.ask_id`, then `stopAsk`), and the bot that asked is told why and woken for it (`stopAsk`'s `reason` into `askOutcomeMessage`); stopping the asking run still ends it silently, since that bot is the one that was stopped. The outcome goes back to the bot that asked as a crew message in the conversation it asked from, which wakes it (`finishAsk`), except when the user stopped it. **Every session query that lists or picks a conversation must exclude hook sessions** (`visibleSessionSql`); an answer run is a normal conversation on purpose. The gate fails closed: a decision that can't be written or read, or a run that can't happen, ends the request as `failed` (`onAskJobEnded`, from complete/fail) rather than leaving it open. Files the answer cites that the asker can't reach but the target can are copied into the asker's folder (`crew/ask-<id>/`) and the refs repointed (`shareAskFiles`). Caps: `AppData.AskMaxDepth` (nested requests, `parent_ask_id`; a bot waiting up the chain can't be asked), `AskMaxOpenPerBot`, `AskBriefMaxChars`. A request's run shows on the target bot's face and in its thread (the thinking row says `SEO Expert is answering Software Engineer's request in Moduletrace LTD…` with Stop, from `grabConversationAsk`; `answer_ask` in the page props, `answering_ask` in `botBusyState`) and pushes no message or notification of its own (the brief is an ordinary conversation message), and counts like any reply when a face is put back after another job (`grabRunningBotJobFace` excludes hook runs only); a hook call can't ask. A bot reads its own requests with `list_asks` (ids and statuses from the app, never its memory), so it stops guessing what it sent. A task run (which sees only its brief) gets its bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`), so it doesn't ask twice. The user sees an outcome only in the asking bot's conversation (there is no page for requests) and can Stop the run that asked (`stopAsk`, `stopAsks`). **Retention:** ended requests go after the app setting `ask_keep_days` (daily `prune-asks`) and past `ask_max_per_place` per place, oldest first (`pruneAsksSql`; pending and working requests, and ones a pending request was asked from, are never pruned; deletion through `deleteAskRows` -> `deleteSessionRows`, which clears each session's job steps, traces, jobs, billed `token_usages` and messages first, so no child row is left behind for the next `db:schema`). Sessions from before this feature (`bot_sessions.status = 'chatroom'`) are deleted at boot by `migrateChatroomsToAsks`.
A worker reaches another bot **only through the coordinator's gate**: `ask_bot` (every worker run with a session except hook calls; never the coordinator) queues a request (`createAsk`) for the run's user and place. Who can be asked is the app's call (`askableBots`): in a workspace its members, else every worker the user reaches. Whether the request should be passed on is the coordinator's judgement, in its instructions (`AskGateNote`); reach, membership, depth and the open cap are the app's. The gate is one turn of the coordinator with no tools (`runAskReview`, queued by `enqueueAskReview`, dispatched from `run-bot-job` on `params.stage == "review"`) answering bounded JSON (`AskDecisionSchema`: `approve`, `redirect` or `refuse`, the bot, and a one-sentence reason) which `applyAskDecision` carries out. A refusal ends the request (`refused`) with its reason; an approval or a redirect sends the brief to the target (`enqueueAskAnswer`) as one reply job in **a new session of the target's conversation with that user for the request's workspace** (`startBotSession` with `workspace_id`, so the run keeps its workspace context and the conversation they were in closes; never a hidden session), titled from the request, where the brief lands as a crew message naming that workspace (`from_ask_id`, `askRequestMessage`, pushed live) and the answer as the bot's reply; the target's own chat (and any other place it is read from) shows the request's row, whose `Open` link appears only outside the request's own thread (`answer_ask.session_id != session_id`), while the session carries `AskSessionBar`, built from `previous_session_id` (recorded when the request took its session, null when the bot had no conversation there before it, an empty active session counted as the request's own, `askPreviousSessionId`: with nothing to go back to, the bar is not shown at all), back to the conversation the user was in; an outcome message carries the `[ask:ID]` pill (`askRef`, `AskRefChip`, `api/admin/bots/ask`) which opens the session it ran in, in the bot that answered it; only the gate's own review run uses a throwaway session (`ensureAskSession`, status `ask`, deleted when empty). Stopping the target's run ends the request too (`stopBotJobs` reads `params.ask_id`, then `stopAsk`), and the bot that asked is told why and woken for it (`stopAsk`'s `reason` into `askOutcomeMessage`); stopping the asking run still ends it silently, since that bot is the one that was stopped. The outcome goes back to the bot that asked as a crew message in the conversation it asked from, which wakes it (`finishAsk`), except when the user stopped it. **Every session query that lists or picks a conversation must exclude hook sessions** (`visibleSessionSql`); an answer run is a normal conversation on purpose. The gate fails closed: a decision that can't be written or read, or a run that can't happen, ends the request as `failed` (`onAskJobEnded`, from complete/fail) rather than leaving it open. Files the answer cites that the asker can't reach but the target can are copied into the asker's folder (`crew/ask-<id>/`) and the refs repointed (`shareAskFiles`). Caps: `AppData.AskMaxDepth` (nested requests, `parent_ask_id`; a bot waiting up the chain can't be asked), `AskMaxOpenPerBot`, `AskBriefMaxChars`. A request's run shows on the target bot's face and in its thread (the thinking row says `SEO Expert is answering Software Engineer's request in Moduletrace LTD…` with Stop, from `grabConversationAsk`; `answer_ask` in the page props, `answering_ask` in `botBusyState`) and pushes no message or notification of its own (the brief is an ordinary conversation message), and counts like any reply when a face is put back after another job (`grabRunningBotJobFace` excludes hook runs only); a hook call can't ask. A bot reads its own requests with `list_asks` (ids and statuses from the app, never its memory), so it stops guessing what it sent. A task run (which sees only its brief) gets its bot's open and recent requests (`grabCrewRequests`, `crewRequestsNote`), so it doesn't ask twice. The user sees an outcome only in the asking bot's conversation (there is no page for requests) and can Stop the run that asked (`stopAsk`, `stopAsks`). **Retention:** ended requests go after the app setting `ask_keep_days` (daily `prune-asks`) and past `ask_max_per_place` per place, oldest first (`pruneAsksSql`; pending and working requests, and ones a pending request was asked from, are never pruned; deletion through `deleteAskRows` -> `deleteSessionRows`, which clears each session's job steps, traces, jobs, billed `token_usages` and messages first, so no child row is left behind for the next `db:schema`). Sessions from before this feature (`bot_sessions.status = 'chatroom'`) are deleted at boot by `migrateChatroomsToAsks`.
### Workspaces
`workspaces` (`description`, shared `system_prompt`, default `computer_id` (not an FK), `archived`), `workspace_bots` (per-bot instructions and memory there; coordinator is an implicit member), `workspace_computers`. First computer linked becomes the default. Workspace models win over a bot's own, then the defaults. **A user's role in a workspace** (`workspace_user_roles`, plain text, one per user and workspace) tells every bot there who it's working for; it's not their bio, the user never sees or sets it, and only crew managers set it, an admin never a super admin's (`canSetWorkspaceUserRole`, checked in `setWorkspaceUserRole`). Set from the workspace's settings (People, everyone who works there: `workspacePeopleSql`), the user's settings (Roles in workspaces) and by the coordinator (`list_workspace_people`/`set_user_workspace_role`, replies and tasks, saved as the run's user so the same rule holds). It stays when access is taken away, shown and used only while they work there. A bot's instructions and memory there (`WorkspaceBotModal`/`WorkspaceBotForm`, crew managers) open from the workspace's settings, the bot's settings and the conversation menu's "Instructions here" (loaded on open). Helpers in `src/functions/backend/db/workspaces/` are access-checked; structural ones are crew-manager only.
`workspaces` (`description`, shared `system_prompt`, default `computer_id` (not an FK), `archived`), `workspace_bots` (per-bot instructions and memory there; coordinator is an implicit member), `workspace_computers`. First computer linked becomes the default. A workspace's models are what its bots use without models of their own, then the defaults. **A user's role in a workspace** (`workspace_user_roles`, plain text, one per user and workspace) tells every bot there who it's working for; it's not their bio, the user never sees or sets it, and only crew managers set it, an admin never a super admin's (`canSetWorkspaceUserRole`, checked in `setWorkspaceUserRole`). Set from the workspace's settings (People, everyone who works there: `workspacePeopleSql`), the user's settings (Roles in workspaces) and by the coordinator (`list_workspace_people`/`set_user_workspace_role`, replies and tasks, saved as the run's user so the same rule holds). It stays when access is taken away, shown and used only while they work there. A bot's instructions and memory there (`WorkspaceBotModal`/`WorkspaceBotForm`, crew managers) open from the workspace's settings, the bot's settings and the conversation menu's "Instructions here" (loaded on open). Helpers in `src/functions/backend/db/workspaces/` are access-checked; structural ones are crew-manager only.
### Computers
@@ -167,7 +168,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
### Tasks (the to-do tracker)
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id` when it directs work, else `hand_over_task` for a task of its own; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there) as to do, with no job: a hand-over never starts the work. Only `start: true` (the UI's "Start it now" toggle, or a bot passing it after the user said so) sets it doing and queues a job with `params.tracker_task_id`; when the user asked for the move but not for the work to start, bots ask first with one `ask_user` card for every task they named, since a worker can't start a task once it has left its list; `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; it can be split into **subtasks** (`parent_task_id`, one level, `subtaskLinkProblem`): each one an ordinary task of one bot in that workspace (`create_task`/`save-task` `parent_task_id`, cap `AppData.TaskSubtaskMaxPerParent`, listed under the parent in `TaskDetailModal` and marked `Subtask of #N` in lists), and a task a bot already has joins one the same way (`linkSubtask`, `api/admin/tasks/link-subtask` from the panel's "Make it a subtask of..." picker, `subtaskAttachProblem` refusing a closed task, another subtask, or a task with subtasks of its own; the parent logs who took which piece), loose again with `detach-subtask`/`update_task` `unlink_parent`; the parent stays open until someone verifies it, and its subtasks never close it. Only a task with no subtasks and no parent moves (`subtaskMoveProblem`, so making it workspace-wide or handing it on is refused until the subtasks are unlinked) and a parent with subtasks is never handed its own work back on deletion (`subtaskDeleteProblem`: all subtasks finished first, then they go with it, children deleted explicitly since foreign keys are off outside the server); a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`), the dashboard's list ordered by `workspaceTaskSections` (workspace-wide first, then one section per bot by name) and capped at `AppData.TaskSectionShown`, its View all opening `WorkspaceTasksModal` with the same sections uncut, and a workspace-wide row wearing the workspace's picture (`WorkspaceAvatar`, its icon when it has none) since it is nobody's; a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place), a wide task's panel listing the first `AppData.TaskSubtasksShown` subtasks with `TaskSubtasksModal` behind its View all, and a subtask's own modal walking up to it through its Parent task fact (Escape closes only the modal on top, `TopModalEscape`). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id` when it directs work, else `hand_over_task` for a task of its own; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there) as to do, with no job: a hand-over never starts the work. Only `start: true` (the UI's "Start it now" toggle, or a bot passing it after the user said so) sets it doing and queues a job with `params.tracker_task_id`; when the user asked for the move but not for the work to start, bots ask first with one `ask_user` card for every task they named, since a worker can't start a task once it has left its list; `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
### Envs
@@ -275,7 +276,7 @@ Route-local code under `src/pages` goes in non-routed meta folders: `(sections)`
- **Chunk classes with `twMerge`**, one chunk per claim: base first, one string per conditional, caller override last. Never concatenate conditional classes with template literals or `+`, never one long mixed string: `className={twMerge("w-full flex-col gap-0! rounded-default py-1", selected && "bg-ink/5")}`.
- **twui `Checkbox` calls `changeHandler` on mount.** Harmless for local state; anything that saves or confirms goes on `clickDispatchHandler`.
- **Theming:** colours, radii and fonts change only in `src/styles/main.css` (`:root`/`.dark` vars exposed as `paper`, `surface`, `sunken`, `ink`, `ink-secondary`, `ink-disabled`, `hairline`, `hairline-strong`, `on-ink`, `hue-<name>`, `shadow-popover`, `--m-fast/base/slow`). Never hardcode hex colours, radii or font stacks. Hues are bot identity only, never state.
- **The one exception:** a bot's user-chosen colour reaches `BotStone` and `UnreadDot` as an SVG `fill` attribute. Nothing else may take a colour that way, and `src/utils/bot-color.ts` is the only place a colour string is validated.
- **The one exception:** a bot's user-chosen colour reaches `BotStone`, `UnreadDot` and `WorkingSpinner` as an SVG `fill`/`stroke` attribute. Nothing else may take a colour that way, and `src/utils/bot-color.ts` is the only place a colour string is validated.
- **Screenshots:** `docs/readme/{hero,workspace}-{light,dark}.png` are real screenshots (1440px at 2x, downscaled to 1600px). Retake them from a seeded dev instance when the UI changes, same names. Never use handoff screens.
- **Logo:** `public/logos/logo.svg` is the single source; after changing it run `bun run gen:favicon`.
- **Site name:** interpolate `SiteData["SiteName"]` in titles, emails and copy; never hardcode the brand.
+95 -8
View File
@@ -38,6 +38,7 @@ import {
import type { BUN_SQLITE_DatabaseSchemaType } from "@moduletrace/bun-sqlite/types";
import { EnvParadigms, SecretRequestStatuses } from "@/src/dict/env-dict";
import { BotQuestionStatuses } from "@/src/dict/bot-question-dict";
import { BotPlanStates } from "@/src/dict/bot-plan-dict";
import { McpServerStatuses, McpTransports } from "@/src/dict/mcp-dict";
import {
CustomToolKinds,
@@ -805,7 +806,7 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
{
tableName: "tasks",
tableDescription: `The crew's to-do list: work that is tracked until it's done. A bot's own list (\`bot_id\` alone), or a workspace's tasks (\`workspace_id\`, with \`bot_id\` naming the bot there that has it, or null for a workspace-wide task every bot there works on, made only when asked for). A bot reaches its own list and, in each workspace it works in, its tasks there and the workspace-wide ones; a workspace admin every task in its workspace; the coordinator every task. Not the same thing as \`bot_tasks\` or \`bots_queue\`: those record a queued job, this records the work`,
tableDescription: `The crew's to-do list: work that is tracked until it's done. A bot's own list (\`bot_id\` alone), or a workspace's tasks (\`workspace_id\`, with \`bot_id\` naming the bot there that has it, or null for a workspace-wide task every bot there works on, made only when asked for). A workspace-wide task can be split into subtasks (\`parent_task_id\`): one piece is a bot's own task in the same workspace, and only one level of splitting exists. A bot reaches its own list and, in each workspace it works in, its tasks there and the workspace-wide ones; a workspace admin every task in its workspace; the coordinator every task. Not the same thing as \`bot_tasks\` or \`bots_queue\`: those record a queued job, this records the work`,
fields: [
{
fieldName: "bot_id",
@@ -831,6 +832,18 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
foreignKeyName: "tasks_workspace_fk",
},
},
{
fieldName: "parent_task_id",
fieldDescription: `The workspace-wide task this one is a part of: a bot's own task in the same workspace, one piece of that work. Null for a task that isn't a subtask; a subtask of a subtask is refused (one level, no nesting), and its parent always stays workspace-wide`,
dataType: "INTEGER",
foreignKey: {
cascadeDelete: true,
destinationTableName: "tasks",
destinationTableColumnName: "id",
destinationTableColumnType: "INTEGER",
foreignKeyName: "tasks_parent_fk",
},
},
{
fieldName: "title",
dataType: "TEXT",
@@ -883,6 +896,10 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
indexName: "idx_tasks_workspace_id_status",
indexTableFields: ["workspace_id", "status"],
},
{
indexName: "idx_tasks_parent_task_id",
indexTableFields: ["parent_task_id"],
},
],
},
{
@@ -1233,7 +1250,7 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
{
fieldName: "message_id",
fieldDescription: `The message the run ended in, filled when the job completes: the debug logs tab of its Details modal reads them. No foreign key, so a message's rows wait for the prune rather than cascade`,
fieldDescription: `The message the run ended in, filled when the job completes: the debug logs tab of its Details modal reads them. No foreign key, so a message's rows wait for the prune rather than cascade`,
dataType: "INTEGER",
},
{
@@ -1943,6 +1960,64 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
],
},
{
tableName: "bot_plans",
tableDescription: `A plan a bot broke complex work into in a conversation (\`create_plan\`): an ordered list of steps it works one at a time, reporting each as it goes. Written as \`planned\` and approved on its card by the user, who may change the steps first; only one is open in a conversation at a time. Visible to the user it was made for`,
fields: [
{
fieldName: "title",
fieldDescription: `A short name for the work, in the bot's words`,
dataType: "TEXT",
},
{
fieldName: "goal",
fieldDescription: `What the plan is for, and what \"done\" means`,
dataType: "TEXT",
},
{
fieldName: "steps",
fieldDescription: `JSON array of { text, state (pending | done | skipped), note } in the order they're worked; the note is what a finished step produced`,
dataType: "TEXT",
},
{
fieldName: "status",
dataType: "TEXT",
options: BotPlanStates.map((state) => state.value),
defaultValue: "planned",
},
{
fieldName: "decided_at",
fieldDescription: `When the user approved (or stopped) it; null while it waits on them`,
dataType: "INTEGER",
},
{
fieldName: "user_id",
fieldDescription: `The user it was made for, who alone sees it and approves it. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "bot_id",
fieldDescription: `The bot that wrote it and works it. Not a foreign key`,
dataType: "INTEGER",
},
{
fieldName: "session_id",
fieldDescription: `The conversation it belongs to, which it never leaves. 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_plans_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\``,
@@ -3030,7 +3105,7 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
{
tableName: "workspace_harness_settings",
tableDescription: `A workspace's models. They win over the bot's own and the defaults for every run in the workspace`,
tableDescription: `A workspace's models. Bots there with none of their own use these instead of the defaults`,
fields: [
{
fieldName: "workspace_id",
@@ -3267,7 +3342,10 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
{
alias: "one_browser_slug_per_user",
constraintName: "A user's browsers have different slugs",
constraintTableFields: [{ value: "user_id" }, { value: "slug" }],
constraintTableFields: [
{ value: "user_id" },
{ value: "slug" },
],
},
],
},
@@ -3460,7 +3538,13 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
{
fieldName: "status",
dataType: "TEXT",
options: ["pending", "confirmed", "rejected", "replaced", "failed"],
options: [
"pending",
"confirmed",
"rejected",
"replaced",
"failed",
],
defaultValue: "pending",
},
{
@@ -3815,7 +3899,8 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
destinationTableName: "knowledgebases",
destinationTableColumnName: "id",
destinationTableColumnType: "INTEGER",
foreignKeyName: "knowledgebase_documents_knowledgebases_fk",
foreignKeyName:
"knowledgebase_documents_knowledgebases_fk",
},
},
{
@@ -4011,7 +4096,8 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
destinationTableName: "workspaces",
destinationTableColumnName: "id",
destinationTableColumnType: "INTEGER",
foreignKeyName: "workspace_knowledgebases_workspaces_fk",
foreignKeyName:
"workspace_knowledgebases_workspaces_fk",
},
},
{
@@ -4022,7 +4108,8 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
destinationTableName: "knowledgebases",
destinationTableColumnName: "id",
destinationTableColumnType: "INTEGER",
foreignKeyName: "workspace_knowledgebases_knowledgebases_fk",
foreignKeyName:
"workspace_knowledgebases_knowledgebases_fk",
},
},
],
+54 -1
View File
@@ -26,6 +26,7 @@ export const BunSQLiteTables = [
"install_requests",
"bot_questions",
"bot_suggestions",
"bot_plans",
"bot_graphics",
"workspaces",
"workspace_bots",
@@ -535,6 +536,10 @@ export type BUN_SQLITE_COBBLE_TASKS = {
* The workspace the task is in; null for a bot's own list
*/
workspace_id?: number | "";
/**
* The workspace-wide task this one is a part of: a bot's own task in the same workspace, one piece of that work. Null for a task that isn't a subtask; a subtask of a subtask is refused (one level, no nesting), and its parent always stays workspace-wide
*/
parent_task_id?: number | "";
title?: string;
/**
* The brief (markdown): what to do, where, and how you'll know it's done
@@ -1267,6 +1272,54 @@ export type BUN_SQLITE_COBBLE_BOT_SUGGESTIONS = {
workspace_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_PLANS = {
/**
* 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 name for the work, in the bot's words
*/
title?: string;
/**
* What the plan is for, and what "done" means
*/
goal?: string;
/**
* JSON array of { text, state (pending | done | skipped), note } in the order they're worked; the note is what a finished step produced
*/
steps?: string;
status?: "planned" | "active" | "paused" | "done" | "cancelled" | "";
/**
* When the user approved (or stopped) it; null while it waits on them
*/
decided_at?: number | "";
/**
* The user it was made for, who alone sees it and approves it. Not a foreign key
*/
user_id?: number | "";
/**
* The bot that wrote it and works it. Not a foreign key
*/
bot_id?: number | "";
/**
* The conversation it belongs to, which it never leaves. 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.
@@ -2929,4 +2982,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_BOT_ASKS & 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_BOT_JOB_TRACES & 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
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_BOT_ASKS & 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_BOT_JOB_TRACES & 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_PLANS & 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
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.21.0",
"version": "0.22.0",
"module": "index.ts",
"type": "module",
"private": true,
+19
View File
@@ -31,6 +31,8 @@ import grabJobUserId from "@/src/functions/backend/db/bots-queue/grab-job-user-i
import runBotJob from "./run-bot-job";
import parseJobJson from "./parse-job-json";
import nameBotSession from "./name-bot-session";
import wakeBotsQueue from "./wake-bots-queue";
import continueBotPlan from "@/src/functions/backend/db/bot-plans/continue-bot-plan";
import pushBotSession from "./push-bot-session";
import grabSessionAskId from "@/src/functions/backend/db/bot-sessions/grab-session-ask-id";
import { registerJobAbort, unregisterJobAbort } from "./job-abort-registry";
@@ -299,6 +301,23 @@ export default async function processBotJob({
await pushBotNotice({ bot_id, ...completion });
/**
* A run that worked a step of a plan hands it on: the next step is
* queued here, once this reply is out, so each step is its own
* message (`continueBotPlan` holds it when the user is needed or
* the run started work of its own).
*/
if (outcome.plan_id) {
await continueBotPlan({
plan_id: outcome.plan_id,
session_id: Number(completion.message?.session_id || job.session_id),
needs_you: Boolean(outcome.needs_you),
tool_names: (outcome.tool_log || []).map((use) => use.name),
}).then((job_id) => {
if (job_id) wakeBotsQueue();
});
}
/**
* Once the first exchange is sent, the bot names the session and
* previews it. After the reply is pushed, so it never waits on it;
+26
View File
@@ -0,0 +1,26 @@
import type { BotPlanChangedData } from "@/src/types";
import pushToSessionUser from "./push-to-session-user";
type Params = {
plan_id: number | string;
session_id: number | string;
bot_id: number | string;
};
/**
* Tells the open tabs of the user a plan belongs to that it changed
* (written, a step done, approved, edited), so every card of it reloads
* what it shows. A plan only ever shows in its own conversation.
*/
export default async function pushBotPlan({ plan_id, session_id, bot_id }: Params) {
const data: BotPlanChangedData = {
plan_id: Number(plan_id),
session_id: Number(session_id),
bot_id: Number(bot_id),
};
await pushToSessionUser({
session_id,
data: { event: "server:bot-plan", data },
});
}
+74 -2
View File
@@ -22,6 +22,11 @@ import {
workspaceAdminNote,
WorkspaceLearningNote,
openRunsNote,
PlansNote,
PlanWaitingNote,
PlanStepNote,
PlanActiveNote,
PlanPausedNote,
} from "@/src/data/harness-prompts";
import grabBotRunPowers from "@/src/functions/backend/db/bot-types/grab-bot-run-powers";
import workspaceAdminsNote from "./workspace-admins-note";
@@ -30,6 +35,7 @@ import { grabContextBudgetTokens, grabReplyMaxToolSteps, grabRunMaxPromptTokens
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
import grabBotPrompt from "@/src/functions/backend/db/bots/grab-bot-prompt";
import grabBotComputers from "@/src/functions/backend/db/computers/grab-bot-computers";
import BotJobFatalError from "@/src/bots-queue/bot-job-fatal-error";
import runTextLoop from "@/src/harness/text/run-text-loop";
import grabBotChatTools from "@/src/harness/tools/bot/grab-bot-chat-tools";
import grabBotFileTools from "@/src/harness/tools/storage/grab-bot-file-tools";
@@ -66,6 +72,10 @@ 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 grabBotPlanTools from "@/src/harness/tools/bot/plans/grab-bot-plan-tools";
import grabSessionPlan from "@/src/functions/backend/db/bot-plans/grab-session-plan";
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
import toBotPlanView from "@/src/functions/backend/db/bot-plans/to-bot-plan-view";
import type { BotMessageWithAttachments } from "@/src/types";
import type { HarnessMessage } from "@/src/harness/types";
import type { BotJobContext, BotJobOutcome } from "./types";
@@ -122,7 +132,32 @@ export default async function runBotReply({
const answered_id = await grabAnsweredMessageId({ session_id });
if (!hasUnansweredMessage({ history, answered_id })) {
const job_params = parseJobJson({ text: job.params }) || {};
/**
* The plan this job was queued for (`enqueuePlanStep`): the run works
* that plan's current step, whether or not the user wrote anything.
*/
const on_plan_step = Number(job_params.plan_id) > 0;
if (!on_plan_step && !hasUnansweredMessage({ history, answered_id })) {
return { result: "", silent: true };
}
/**
* The conversation's plan: the one this job works, else the one open
* here, which the run reads and reports on.
*/
const plan_row = on_plan_step
? await grabBotPlan({ plan_id: Number(job_params.plan_id) }).catch(() => null)
: await grabSessionPlan({ session_id });
const plan = plan_row ? toBotPlanView({ row: plan_row }) : null;
/**
* A step job queued before the user paused (or dropped) the plan has
* nothing to do: it ends without a word, rather than reporting a step
* nobody asked for any more.
*/
if (on_plan_step && (plan?.status != "active" || plan?.current_step == null)) {
return { result: "", silent: true };
}
@@ -222,6 +257,11 @@ export default async function runBotReply({
* always carries, without needing the user.
*/
const shown: string[] = [];
/**
* The plan it wrote in this reply: on its card and waiting for the user
* to approve it, so the reply needs them.
*/
const plan_refs: string[] = [];
/**
* Files the bot wrote and asked to send with its reply.
*/
@@ -383,6 +423,14 @@ export default async function runBotReply({
can_hand_over ? HandOverTaskNote : "",
ActionCheckNote,
RequestScopeNote({ can_ask: Boolean(attended) && !asked }),
attended && !asked ? PlansNote : "",
attended && !asked && plan?.status == "planned" ? PlanWaitingNote({ plan }) : "",
attended && !asked && plan?.status == "paused" ? PlanPausedNote({ plan }) : "",
attended && !asked && plan?.status == "active"
? on_plan_step
? PlanStepNote({ plan })
: PlanActiveNote({ plan })
: "",
attended ? QuestionsNote : "",
SecretsNote,
SettingsNote,
@@ -459,6 +507,21 @@ export default async function runBotReply({
}),
]
: []),
...(attended && !asked
? grabBotPlanTools({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
on_step: on_plan_step,
/**
* A plan nobody approved yet needs the user, so
* it goes with the refs that set `needs_you`: the
* bot is waiting on them, not on itself.
*/
onPlan: ({ ref, waiting }) => (waiting ? plan_refs.push(ref) : shown.push(ref)),
})
: []),
...(has_past_sessions
? [searchPastSessionsTool(past_scope), readPastSessionTool(past_scope)]
: []),
@@ -493,6 +556,14 @@ export default async function runBotReply({
reviewBotReply({ text, tool_uses, bot_id: bot.id!, user_id, session_id, scopes }),
});
/**
* An answer the review kept faulting is never sent: the run stops
* with why instead (`review_note`), and the job fails saying so. The
* user gets an honest failure, not a claim the app knows is false.
*/
if (result.review_note)
throw new BotJobFatalError(`The answer didn't hold up against the app's record, so it wasn't sent.`);
if (job.id && answering_id) {
await markReplyAnswered({ job_id: job.id, message_id: answering_id });
}
@@ -500,12 +571,13 @@ export default async function runBotReply({
return {
...withTakeOverRefs({
text: stripAppRecords({ text: result.text }),
refs: [...take_overs, ...proposals],
refs: [...take_overs, ...proposals, ...plan_refs],
shown,
}),
attachments: attachments.length ? attachments : undefined,
tool_log: result.tool_uses,
task_ids,
plan_id: on_plan_step ? plan?.id : undefined,
};
} finally {
await extensions.close();
+19
View File
@@ -14,6 +14,7 @@ import {
botFilesNote,
ComputerFilesNote,
ScheduledRunNote,
ScheduledPlanNote,
HookRunNote,
InstallRequestNote,
TasksNote,
@@ -56,6 +57,7 @@ import askToTakeOverTool from "@/src/harness/tools/computer/ask-to-take-over-too
import importFileTool from "@/src/harness/tools/computer/import-file-tool";
import searchComputersTool from "@/src/harness/tools/computer/search-computers-tool";
import grabBotFileTools from "@/src/harness/tools/storage/grab-bot-file-tools";
import grabBotPlanTools from "@/src/harness/tools/bot/plans/grab-bot-plan-tools";
import grabBotGraphicTools from "@/src/harness/tools/graphics/grab-bot-graphic-tools";
import reportRunFailedTool from "@/src/harness/tools/bot/report-run-failed-tool";
import answerInstallRequestTool from "@/src/harness/tools/bot/answer-install-request-tool";
@@ -348,6 +350,22 @@ export default async function runBotTask({
job_id: job.id || null,
onGraphic: ({ ref }) => shown.push(ref),
}),
/**
* A routine's plan is approved at once and worked through in
* the run, since nobody is there to approve it on a card
* (`ScheduledPlanNote`). A hook call gets none: its thread is a
* log of calls, not a conversation to read a plan in.
*/
...(scheduled && session_id
? grabBotPlanTools({
user_id,
bot_id: bot.id,
session_id,
workspace_id,
approve: true,
onPlan: ({ ref }) => shown.push(ref),
})
: []),
];
extensions = await openBotExtensions({
@@ -437,6 +455,7 @@ export default async function runBotTask({
TaskRunNote,
steps_note,
scheduled ? ScheduledRunNote : "",
scheduled ? ScheduledPlanNote : "",
hooked ? HookRunNote : "",
install_request_id ? InstallRequestNote : "",
botFilesNote({ bot_id: bot.id }),
+6
View File
@@ -74,6 +74,12 @@ export type BotJobOutcome = {
* (`noteTrackerTask`).
*/
exhausted?: boolean;
/**
* The plan this run worked a step of (`params.plan_id`): the app queues
* its next step once the reply is out (`continueBotPlan`), unless the
* run asked for the user or started work that runs on its own.
*/
plan_id?: number;
};
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
@@ -0,0 +1,103 @@
import { useEffect, useState } from "react";
import Form from "@moduletrace/twui/form/Form";
import Select from "@moduletrace/twui/form/Select";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
import type { TaskDetail, TaskWithNames } from "@/src/types";
type Props = {
/**
* The bot's task being made a subtask of a workspace-wide one.
*/
task: TaskDetail;
onLinked: (task: TaskDetail, msg: string) => void;
onCancel: () => void;
};
/**
* Picks which open workspace-wide task of the same workspace a bot's task
* becomes a subtask of (`linkSubtask`), the way the task's own bot can with
* `update_task`. The parents load when the form opens, so the page's props
* stay small.
*/
export default function SubtaskLinkForm({ task, onLinked, onCancel }: Props) {
const [parents, setParents] = useState<TaskWithNames[]>();
const [parent_task_id, setParentTaskId] = useState<number>();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
useEffect(() => {
postAdminApi<TaskWithNames>({ path: "tasks/subtask-parents", body: { task_id: Number(task.id) } }).then((res) => {
if (!res.success) {
setError(res.msg || "Couldn't load the workspace-wide tasks.");
setParents([]);
return;
}
const list = (res.payload || []) as TaskWithNames[];
setParents(list);
setParentTaskId(list[0]?.id ? Number(list[0].id) : undefined);
});
}, []);
const submit = async () => {
if (loading) return;
const parent = parents?.find((it) => Number(it.id) == parent_task_id);
if (!parent) {
setError("Pick the workspace-wide task it belongs to.");
return;
}
if (!window.confirm(`Make "${task.title}" a subtask of "${parent.title}"? It stays ${task.bot_name || "its bot"}'s, and the parent stays open until someone verifies all its subtasks.`))
return;
setLoading(true);
setError(undefined);
const res = await postAdminApi<TaskDetail>({
path: "tasks/link-subtask",
body: { task_id: Number(task.id), parent_task_id: Number(parent.id) },
});
setLoading(false);
if (!res.success || !res.singleRes) {
setError(res.msg || "Couldn't make it a subtask of that task.");
return;
}
onLinked(res.singleRes, res.msg || `It's a subtask of task #${parent.id} now.`);
};
return (
<Form onSubmit={submit} className="w-full gap-3! items-stretch">
<Stack className="gap-3! items-stretch">
{!parents ? (
<Span className="text-[13px] leading-[18px] text-ink-secondary">Loading the workspace-wide tasks...</Span>
) : parents.length ? (
<Select
key={parents.length}
label="Parent task"
showLabel
options={parents.map((it) => ({
title: `#${it.id} ${it.title || ""}`.trim(),
value: String(it.id),
default: Number(it.id) == parent_task_id,
}))}
changeHandler={(value) => setParentTaskId(Number(value))}
/>
) : (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
This workspace has no open workspace-wide task to join. Make one first, then split it.
</Span>
)}
<AddFormActions submit_label="Make it a subtask" loading={loading} error={error} onCancel={onCancel} />
</Stack>
</Form>
);
}
+20 -2
View File
@@ -35,7 +35,16 @@ type Props = {
export default function TaskDetailModal({ task, can_manage, onClose, onLoaded, onChanged, onDeleted }: Props) {
const [detail, set_detail] = useState<TaskDetail | null>(null);
const [error, set_error] = useState<string>();
const task_id = task?.id ? Number(task.id) : 0;
/**
* A subtask opened from the task on show: the modal walks into it and back
* out with the list's own click.
*/
const [opened, set_opened] = useState<Partial<TaskWithNames> | null>(null);
const task_id = Number(opened?.id || task?.id || 0);
useEffect(() => {
set_opened(null);
}, [task?.id]);
useEffect(() => {
set_detail(null);
@@ -67,13 +76,20 @@ export default function TaskDetailModal({ task, can_manage, onClose, onLoaded, o
}, [task_id]);
const shown = detail || task;
/**
* The task it is a subtask of, when it is one: the modal walks into that as
* it walks into a subtask.
*/
const part_of = detail?.parent_task_id
? ` · Parent task #${detail.parent_task_id}${detail.parent_title ? ` ${detail.parent_title}` : ""}`
: "";
return (
<AddModalShell
open={Boolean(task_id)}
setOpen={(open) => !open && onClose()}
title={shown?.title || (task_id ? `Task ${task_id}` : "Task")}
description={shown ? taskPlaceLabel({ task: shown }) : undefined}
description={shown ? `${taskPlaceLabel({ task: shown })}${part_of}` : undefined}
>
<Stack className="w-full mt-4 gap-0! items-stretch">
{detail ? (
@@ -81,6 +97,8 @@ export default function TaskDetailModal({ task, can_manage, onClose, onLoaded, o
key={detail.id}
task={detail}
can_manage={can_manage}
onOpenSubtask={(subtask) => set_opened(subtask)}
onOpenParent={(parent) => set_opened(parent)}
onChanged={(saved, msg) => {
set_detail(saved);
onChanged({ task: saved, msg });
@@ -0,0 +1,93 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import { AppData } from "@/src/data/app-data";
import type { TaskDetail } from "@/src/types";
import TaskDetailPanel from "./task-detail-panel";
function detail(fields: Partial<TaskDetail>): TaskDetail {
return {
id: 12,
created_at: 1,
updated_at: 2,
title: "Ship the release",
status: "doing",
notes: [],
files: [],
subtasks: [],
...fields,
};
}
const noop = () => {};
describe("TaskDetailPanel", () => {
test("a split workspace-wide task lists its subtasks with how many are still open", () => {
const html = renderToString(
<TaskDetailPanel
task={detail({
bot_id: "",
workspace_id: 7,
subtasks: [
{ id: 31, title: "The intro", status: "doing", bot_id: 3, bot_name: "Software Engineer" },
{ id: 32, title: "The appendix", status: "done", bot_id: 4, bot_name: "SEO Expert" },
],
})}
onChanged={noop}
onDeleted={noop}
/>,
);
expect(html).toContain("Subtasks (2, 1 open)");
expect(html).toContain("The intro");
expect(html).toContain("Software Engineer");
});
test("a wide task nobody split yet says so", () => {
const html = renderToString(
<TaskDetailPanel task={detail({ bot_id: "", workspace_id: 7 })} onChanged={noop} onDeleted={noop} />,
);
expect(html).toContain("Not split yet");
});
test("a task with more subtasks than the panel shows offers them all", () => {
const total = AppData.TaskSubtasksShown + 2;
const subtasks = Array.from({ length: total }, (unused, index) => ({
id: 40 + index,
title: `Piece ${index + 1}`,
status: "todo" as const,
bot_id: 3 + index,
bot_name: `Bot ${3 + index}`,
}));
const html = renderToString(
<TaskDetailPanel
task={detail({ bot_id: "", workspace_id: 7, subtasks })}
onOpenSubtask={noop}
onChanged={noop}
onDeleted={noop}
/>,
);
expect(html).toContain(`Subtasks (${total}, ${total} open)`);
expect(html).toContain("Piece 1");
expect(html).toContain(`Piece ${AppData.TaskSubtasksShown}`);
expect(html).not.toContain(`Piece ${AppData.TaskSubtasksShown + 1}`);
expect(html).toContain(`View all ${total} subtasks`);
});
test("a subtask says which task it belongs to, and opens it", () => {
const html = renderToString(
<TaskDetailPanel
task={detail({ bot_id: 3, workspace_id: 7, parent_task_id: 12, parent_title: "Ship the release" })}
onOpenParent={noop}
onChanged={noop}
onDeleted={noop}
/>,
);
expect(html).toContain("Parent task");
expect(html).toContain("#12 Ship the release");
expect(html).toContain("Open the task this is a subtask of");
});
});
+272 -38
View File
@@ -5,7 +5,7 @@ import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import Textarea from "@moduletrace/twui/form/Textarea";
import { OpenTaskStatuses } from "@/src/dict/task-dict";
import type { TaskDetail, TaskFile } from "@/src/types";
import type { TaskDetail, TaskFile, TaskWithNames } from "@/src/types";
import TaskFileRow from "@/src/components/general/task-file-row";
import HandOverForm from "@/src/components/general/hand-over-form";
import TaskForm from "@/src/components/general/task-form";
@@ -14,9 +14,13 @@ import TaskStatusMoves from "@/src/components/general/task-status-moves";
import BotAvatar from "@/src/components/general/bot-avatar";
import TaskFactRow from "@/src/components/general/task-fact-row";
import TaskNoteRow from "@/src/components/general/task-note-row";
import TaskSubtaskRow from "@/src/components/general/task-subtask-row";
import TaskSubtasksModal from "@/src/components/general/task-subtasks-modal";
import SubtaskLinkForm from "@/src/components/general/subtask-link-form";
import TaskMarkdown from "@/src/components/general/task-markdown";
import type { BotFace } from "@/src/dict/bot-dict";
import { AppContext } from "@/src/pages/__root";
import { AppData } from "@/src/data/app-data";
import botStoneProps from "@/src/utils/bot-stone-props";
import relativeTime from "@/src/utils/relative-time";
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
@@ -28,6 +32,14 @@ type Props = {
* A crew manager can change it, file onto it and delete it.
*/
can_manage?: boolean;
/**
* Opens one of its subtasks in place, so a split task is one click deep.
*/
onOpenSubtask?: (subtask: TaskWithNames) => void;
/**
* Opens the workspace-wide task it is a subtask of, when it is one.
*/
onOpenParent?: (parent: { id: number; title?: string }) => void;
onChanged: (task: TaskDetail, msg?: string) => void;
onDeleted: () => void;
};
@@ -37,28 +49,42 @@ type Props = {
* when it last moved, what it is, its files (each opening its bytes), its
* notes oldest first, a box to add a note, and edit or delete. A crew
* manager can file a new deliverable straight onto it, hand an open one to
* another bot, which starts on it, or make a bot's open workspace task
* workspace-wide.
* another bot, which starts on it, make a bot's open workspace task
* workspace-wide, and split a workspace-wide one into subtasks: each piece a
* bot's own task, opened from here, or unlinked again to stand alone.
*/
export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted }: Props) {
export default function TaskDetailPanel({
task,
can_manage,
onOpenSubtask,
onOpenParent,
onChanged,
onDeleted,
}: Props) {
const { pageProps } = useContext(AppContext);
const [editing, setEditing] = useState(false);
const [handing_over, setHandingOver] = useState(false);
const [linking, setLinking] = useState(false);
const [showing_parts, setShowingParts] = useState(false);
const [note, setNote] = useState("");
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<string>();
const file_input = useRef<HTMLInputElement>(null);
const run = async (params: { path: string; body: Record<string, unknown>; done: string }) => {
const run = async (params: {
path: string;
body: Record<string, unknown>;
done: string;
}) => {
if (busy) return;
setBusy(true);
setStatus(undefined);
const res = await fetchApi<Record<string, unknown>, APIResponseObject<TaskDetail>>(
`/api/admin/${params.path}`,
{ method: "POST", body: params.body },
);
const res = await fetchApi<
Record<string, unknown>,
APIResponseObject<TaskDetail>
>(`/api/admin/${params.path}`, { method: "POST", body: params.body });
setBusy(false);
@@ -74,7 +100,11 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
const addNote = async () => {
if (!note.trim()) return;
await run({ path: "tasks/add-note", body: { task_id: Number(task.id), text: note }, done: "Note added." });
await run({
path: "tasks/add-note",
body: { task_id: Number(task.id), text: note },
done: "Note added.",
});
setNote("");
};
@@ -95,13 +125,21 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
await run({
path: "tasks/attach-file",
body: { task_id: Number(task.id), data_url, name: file.name, kind: "deliverable" },
body: {
task_id: Number(task.id),
data_url,
name: file.name,
kind: "deliverable",
},
done: `${file.name} added as a deliverable.`,
});
};
const detach = async ({ file }: { file: TaskFile }) => {
if (!window.confirm(`Unlink ${file.name || "this file"} from the task?`)) return;
if (
!window.confirm(`Unlink ${file.name || "this file"} from the task?`)
)
return;
await run({
path: "tasks/detach-file",
@@ -141,8 +179,29 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
);
}
if (linking) {
return (
<SubtaskLinkForm
task={task}
onCancel={() => setLinking(false)}
onLinked={(saved, msg) => {
setLinking(false);
onChanged(saved, msg);
}}
/>
);
}
const deliverables = task.files.filter((file) => file.kind != "reference");
const references = task.files.filter((file) => file.kind == "reference");
const subtasks = task.subtasks || [];
const open_parts = subtasks.filter((subtask) =>
(OpenTaskStatuses as readonly string[]).includes(subtask.status || ""),
).length;
const is_task_linked_to_another_task =
Boolean(task.parent_task_id) ||
Boolean(Number(task.subtask_count || 0));
const is_tasks_disabled = busy || is_task_linked_to_another_task;
return (
<Stack className="w-full gap-4! items-stretch">
@@ -155,7 +214,10 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
onMove={(next) =>
run({
path: "tasks/save-task",
body: { task_id: Number(task.id), status: next },
body: {
task_id: Number(task.id),
status: next,
},
done: "Status changed.",
})
}
@@ -163,21 +225,32 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
) : null}
{can_manage ? (
<Row className="ml-auto shrink-0 gap-1! flex-nowrap">
{(OpenTaskStatuses as readonly string[]).includes(task.status || "") ? (
{(OpenTaskStatuses as readonly string[]).includes(
task.status || "",
) ? (
<Button
title="Hand the task to another bot"
title={
is_task_linked_to_another_task
? "Task is linked to another task. Unlink first before handover"
: "Hand the task to another bot"
}
type="button"
variant="ghost"
color="gray"
size="small"
disabled={busy}
disabled={is_tasks_disabled}
onClick={() => setHandingOver(true)}
className="px-2! text-[12px]"
>
Hand over
</Button>
) : null}
{task.workspace_id && task.bot_id && (OpenTaskStatuses as readonly string[]).includes(task.status || "") ? (
{task.workspace_id &&
task.bot_id &&
!task.parent_task_id &&
(OpenTaskStatuses as readonly string[]).includes(
task.status || "",
) ? (
<Button
title="Make it workspace-wide: every bot in the workspace works on it"
type="button"
@@ -204,6 +277,50 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
Make workspace-wide
</Button>
) : null}
{can_manage &&
task.workspace_id &&
task.bot_id &&
!task.parent_task_id ? (
<Button
title="Make it a subtask of a workspace-wide task: the piece this bot took on"
type="button"
variant="ghost"
color="gray"
size="small"
disabled={busy}
onClick={() => setLinking(true)}
className="px-2! text-[12px]"
>
Make it a subtask of...
</Button>
) : null}
{task.parent_task_id ? (
<Button
title="Take it out of its workspace-wide task: it becomes a task of its own"
type="button"
variant="ghost"
color="gray"
size="small"
disabled={busy}
onClick={() => {
if (
!window.confirm(
`Unlink "${task.title}" from task #${task.parent_task_id}? It becomes a task of its own.`,
)
)
return;
run({
path: "tasks/detach-subtask",
body: { task_id: Number(task.id) },
done: "It's a task of its own now.",
}).catch(() => {});
}}
className="px-2! text-[12px]"
>
Unlink from parent
</Button>
) : null}
<Button
title="Edit the task"
type="button"
@@ -224,13 +341,21 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
size="small"
disabled={busy}
onClick={async () => {
if (!window.confirm(`Delete "${task.title}"? Its notes and links go with it.`)) return;
if (
!window.confirm(
`Delete "${task.title}"? Its notes and links go with it.`,
)
)
return;
setBusy(true);
const res = await fetchApi<Record<string, unknown>, APIResponseObject>(
"/api/admin/tasks/delete-task",
{ method: "POST", body: { task_id: Number(task.id) } },
);
const res = await fetchApi<
Record<string, unknown>,
APIResponseObject
>("/api/admin/tasks/delete-task", {
method: "POST",
body: { task_id: Number(task.id) },
});
setBusy(false);
if (!res.success) {
@@ -254,38 +379,76 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
<>
<BotAvatar
image_media_id={task.bot_image_media_id}
{...botStoneProps({ color: task.bot_color, stone: task.bot_stone, hue: task.bot_hue })}
{...botStoneProps({
color: task.bot_color,
stone: task.bot_stone,
hue: task.bot_hue,
})}
face={(task.bot_face || "idle") as BotFace}
size={18}
/>
<Span className="min-w-0 truncate">{task.bot_name || `Bot ${task.bot_id}`}</Span>
<Span className="min-w-0 truncate">
{task.bot_name || `Bot ${task.bot_id}`}
</Span>
</>
) : (
<Span className="text-ink-secondary">
{task.workspace_id ? "Every bot in the workspace (workspace-wide)" : "No bot"}
{task.workspace_id
? "Every bot in the workspace (workspace-wide)"
: "No bot"}
</Span>
)}
</TaskFactRow>
<TaskFactRow label="Where">
<Span className="min-w-0 truncate">
{task.workspace_id
? task.workspace_name || `Workspace ${task.workspace_id}`
? task.workspace_name ||
`Workspace ${task.workspace_id}`
: `${task.bot_name || "The bot"}'s own list`}
</Span>
</TaskFactRow>
{task.parent_task_id ? (
<TaskFactRow label="Parent task">
{onOpenParent ? (
<Button
title="Open the task this is a subtask of"
type="button"
variant="ghost"
color="text"
size="small"
onClick={() =>
onOpenParent({
id: Number(task.parent_task_id),
title: task.parent_title || undefined,
})
}
className="px-0! h-auto! py-0! text-[13px]! font-normal! leading-[18px]! text-ink! hover:underline"
>
{`#${task.parent_task_id}${task.parent_title ? ` ${task.parent_title}` : ""}`}
</Button>
) : (
<Span className="min-w-0 truncate">
{`#${task.parent_task_id}${task.parent_title ? ` ${task.parent_title}` : ""}`}
</Span>
)}
</TaskFactRow>
) : null}
<TaskFactRow label="Added">
<Span className="min-w-0 truncate">
{[
task.created_by_bot_id
? `By ${task.created_by_bot_name || `bot ${task.created_by_bot_id}`}`
: task.created_by_user_id
? task.created_by_user_id == pageProps?.user?.id
? task.created_by_user_id ==
pageProps?.user?.id
? "By you"
: `By ${task.created_by_user_name || "a user"}`
: task.origin == "bot"
? "By a bot"
: "By hand",
task.created_at ? relativeTime({ at: Number(task.created_at) }) : null,
task.created_at
? relativeTime({ at: Number(task.created_at) })
: null,
]
.filter(Boolean)
.join(" · ")}
@@ -293,12 +456,16 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
</TaskFactRow>
{task.updated_at ? (
<TaskFactRow label="Last moved">
<Span>{relativeTime({ at: Number(task.updated_at) })}</Span>
<Span>
{relativeTime({ at: Number(task.updated_at) })}
</Span>
</TaskFactRow>
) : null}
{task.completed_at ? (
<TaskFactRow label="Finished">
<Span>{relativeTime({ at: Number(task.completed_at) })}</Span>
<Span>
{relativeTime({ at: Number(task.completed_at) })}
</Span>
</TaskFactRow>
) : null}
</Stack>
@@ -307,13 +474,67 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
<Span className="text-[13px] leading-[18px] text-ink">{`Waiting on you: ${task.blocked_reason}`}</Span>
) : null}
{task.description ? (
<TaskMarkdown text={task.description} />
{task.description ? <TaskMarkdown text={task.description} /> : null}
{task.workspace_id && !task.bot_id ? (
<Stack className="w-full gap-1! items-stretch">
<Span className="text-[12px] font-bold leading-4 text-ink-secondary">
{subtasks.length
? `Subtasks (${subtasks.length}${open_parts ? `, ${open_parts} open` : ", all done"})`
: "Subtasks"}
</Span>
{subtasks.length ? (
<Stack className="w-full gap-0! items-stretch">
{subtasks
.slice(0, AppData.TaskSubtasksShown)
.map((subtask) => (
<TaskSubtaskRow
key={subtask.id}
subtask={subtask}
onOpen={() => onOpenSubtask?.(subtask)}
/>
))}
</Stack>
) : (
<Span className="text-[13px] leading-[18px] text-ink-secondary">
Not split yet: every bot here works on it as one
task.
</Span>
)}
{subtasks.length > AppData.TaskSubtasksShown ? (
<Row className="justify-end">
<Button
title="Open every subtask of this task"
type="button"
variant="ghost"
color="gray"
size="small"
onClick={() => setShowingParts(true)}
className="px-2! text-[12px]"
>
{`View all ${subtasks.length} subtasks`}
</Button>
</Row>
) : null}
</Stack>
) : null}
<TaskSubtasksModal
open={showing_parts}
setOpen={setShowingParts}
task={task}
subtasks={subtasks}
onOpenSubtask={(subtask) => {
setShowingParts(false);
onOpenSubtask?.(subtask);
}}
/>
<Stack className="w-full gap-1! items-stretch">
<Span className="text-[12px] font-bold leading-4 text-ink-secondary">
{task.files.length ? `Files (${task.files.length})` : "Files"}
{task.files.length
? `Files (${task.files.length})`
: "Files"}
</Span>
{deliverables.length || references.length ? (
<Stack className="w-full gap-0! items-stretch">
@@ -322,12 +543,18 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
key={file.id}
file={file}
busy={busy}
onDetach={can_manage ? () => detach({ file }) : undefined}
onDetach={
can_manage
? () => detach({ file })
: undefined
}
/>
))}
</Stack>
) : (
<Span className="text-[13px] leading-[18px] text-ink-secondary">Nothing filed yet.</Span>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
Nothing filed yet.
</Span>
)}
{can_manage ? (
<Row className="gap-2! flex-nowrap items-center">
@@ -359,7 +586,9 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
<Stack className="w-full gap-1! items-stretch">
<Span className="text-[12px] font-bold leading-4 text-ink-secondary">
{task.notes.length ? `Notes (${task.notes.length})` : "Notes"}
{task.notes.length
? `Notes (${task.notes.length})`
: "Notes"}
</Span>
{task.notes.length ? (
<Stack className="w-full gap-0! items-stretch">
@@ -368,7 +597,9 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
))}
</Stack>
) : (
<Span className="text-[13px] leading-[18px] text-ink-secondary">No notes yet.</Span>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
No notes yet.
</Span>
)}
<Textarea
placeholder="Add a note"
@@ -394,7 +625,10 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
</Stack>
{status ? (
<Span role="status" className="text-[13px] leading-[18px] text-ink-secondary">
<Span
role="status"
className="text-[13px] leading-[18px] text-ink-secondary"
>
{status}
</Span>
) : null}
+36
View File
@@ -29,6 +29,11 @@ type Props = {
* works on. A task goes to a bot unless that's picked.
*/
bots?: { id?: number | string | null; name?: string | null }[];
/**
* The workspace-wide tasks here a new one can be a subtask of (only the
* open ones: a closed task can't be split). Adding, never editing.
*/
parents?: { id?: number | string | null; title?: string | null }[];
/**
* Edits this task; adds one when not given.
*/
@@ -46,6 +51,7 @@ export default function TaskForm({
bot_id,
workspace_id,
bots = [],
parents = [],
task,
onSaved,
onCancel,
@@ -65,6 +71,9 @@ export default function TaskForm({
);
const workspace_wide = pick_bot && picked == WorkspaceWideValue;
const picked_bot_id = pick_bot && !workspace_wide ? Number(picked) || undefined : bot_id || undefined;
const pick_parent = !task && parents.length > 0;
const [picked_parent, setPickedParent] = useState<string>("");
const parent_task_id = pick_parent && picked_parent ? Number(picked_parent) || undefined : undefined;
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -94,6 +103,7 @@ export default function TaskForm({
bot_id: task || workspace_wide ? undefined : picked_bot_id,
workspace_id: task ? undefined : workspace_id || undefined,
workspace_wide: task ? undefined : workspace_wide || undefined,
parent_task_id,
title,
description,
status,
@@ -145,6 +155,32 @@ export default function TaskForm({
changeHandler={(value) => setPicked(String(value))}
/>
) : null}
{pick_parent ? (
<Select
title="Parent task"
label="Parent task"
showLabel
options={[
{
title: "A task of its own",
value: "",
default: !picked_parent,
},
...parents.map((parent) => ({
title: `#${parent.id} ${parent.title || ""}`.trim(),
value: String(parent.id),
default: String(parent.id) == picked_parent,
})),
]}
changeHandler={(value) => {
const next = String(value);
setPickedParent(next);
if (next && workspace_wide && default_bot_id) setPicked(String(default_bot_id));
}}
/>
) : null}
<CodeEditor
mode="markdown"
className="h-[500px]"
@@ -0,0 +1,76 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import type { TaskWithNames } from "@/src/types";
import TaskListItem from "./task-list-item";
const base_task: TaskWithNames = {
id: 42,
created_at: 1,
updated_at: 2,
bot_id: 3,
bot_name: "Software Engineer",
status: "todo",
};
describe("TaskListItem", () => {
test("appends the task's id to its title, so the list can be matched to a [task:ID]", () => {
const html = renderToString(<TaskListItem task={{ ...base_task, title: "Fix the header" }} />);
expect(html).toContain("Fix the header");
expect(html).toContain("#42");
});
test("an untitled task is named by its id alone, never twice", () => {
const html = renderToString(<TaskListItem task={{ ...base_task, title: "" }} />);
expect(html).toContain("Task 42");
expect(html).not.toContain("#42");
});
test("a dropped workspace task shows its id too", () => {
const html = renderToString(
<TaskListItem task={{ ...base_task, title: "Workspace wide", bot_id: "", workspace_id: 7 }} />,
);
expect(html).toContain("Workspace wide");
expect(html).toContain("#42");
});
test("a workspace-wide task wears the workspace's picture, or its icon when it has none", () => {
const pictured = renderToString(
<TaskListItem
task={{ ...base_task, title: "Ship it", bot_id: "", workspace_id: 7, workspace_image_media_id: 31 }}
/>,
);
expect(pictured).toContain("/media/31/thumbnail");
const plain = renderToString(<TaskListItem task={{ ...base_task, title: "Ship it", bot_id: "", workspace_id: 7 }} />);
expect(plain).not.toContain("/media/");
});
test("a subtask says which task it belongs to, and a split task how many subtasks are open", () => {
const part = renderToString(
<TaskListItem task={{ ...base_task, title: "The intro", parent_task_id: 12, parent_title: "Ship it" }} />,
);
expect(part).toContain("Subtask of #12");
const parent = renderToString(
<TaskListItem
task={{ ...base_task, title: "Ship it", bot_id: "", workspace_id: 7, subtask_count: 3, subtask_open_count: 2 }}
/>,
);
expect(parent).toContain("2 of 3 subtasks open");
const finished = renderToString(
<TaskListItem
task={{ ...base_task, title: "Ship it", bot_id: "", workspace_id: 7, subtask_count: 2, subtask_open_count: 0 }}
/>,
);
expect(finished).toContain("all 2 subtasks done");
});
});
+38 -7
View File
@@ -7,13 +7,14 @@ import Button from "@moduletrace/twui/layout/Button";
import type { TaskWithNames } from "@/src/types";
import { AppContext } from "@/src/pages/__root";
import BotAvatar from "@/src/components/general/bot-avatar";
import WorkspaceAvatar from "@/src/components/general/workspace-avatar";
import type { BotFace } from "@/src/dict/bot-dict";
import botStoneProps from "@/src/utils/bot-stone-props";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import relativeTime from "@/src/utils/relative-time";
import taskPlaceLabel from "@/src/utils/task-place-label";
import Center from "@moduletrace/twui/layout/Center";
import { Trash2, Users } from "lucide-react";
import { Trash2 } from "lucide-react";
import RowIconButton from "./row-icon-button";
import TaskStatusChip from "./task-status-chip";
import TaskStatusMoves from "./task-status-moves";
@@ -37,8 +38,8 @@ type Props = {
};
/**
* One task: whose it is (a bot's stone, or a crew mark when it's
* workspace-wide), its title and status, where it
* One task: whose it is (a bot's stone, or the workspace's own picture when
* it's workspace-wide and nobody's), its title and status, where it
* is and who has it, what it's blocked on, its latest note and how long ago it
* moved. Its title opens it in a modal.
*/
@@ -57,9 +58,12 @@ export default function TaskListItem({ task, onOpen, onStatusChange, onDelete, b
size={28}
/>
) : (
<Center title="Workspace-wide: every bot here works on it" className="size-7 shrink-0 text-ink-secondary">
<Users size={18} />
</Center>
<Span
title="Workspace-wide: every bot here works on it"
className="flex size-7 shrink-0 items-center justify-center"
>
<WorkspaceAvatar image_media_id={task.workspace_image_media_id} size="md" />
</Span>
)}
<Stack className="grow min-w-0 gap-0.5! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
@@ -71,10 +75,19 @@ export default function TaskListItem({ task, onOpen, onStatusChange, onDelete, b
onClick={onOpen}
className={twMerge(
"grow min-w-0 justify-start px-0! h-auto! py-0! text-sm! font-bold! leading-5! truncate text-left hover:bg-transparent! hover:underline",
"[&_.twui-button-content-wrapper]:min-w-0 [&_.twui-button-content-wrapper]:gap-1.5",
done ? "text-ink-secondary! line-through" : "text-ink!",
)}
>
<Span className="truncate">{task.title || `Task ${task.id}`}</Span>
{task.title ? (
<Span
title={`Task ${task.id}`}
className="shrink-0 text-[11px] leading-4 font-normal text-ink-secondary tabular-nums"
>
{`#${task.id}`}
</Span>
) : null}
</Button>
<TaskStatusChip status={task.status} />
{can_manage && onDelete ? (
@@ -90,6 +103,24 @@ export default function TaskListItem({ task, onOpen, onStatusChange, onDelete, b
<Span className="shrink-0 text-xs leading-4 text-ink-secondary truncate">
{taskPlaceLabel({ task })}
</Span>
{task.parent_task_id ? (
<Span
title={`Subtask of task ${task.parent_task_id}${task.parent_title ? `: ${task.parent_title}` : ""}`}
className="shrink-0 text-[11px] leading-4 text-ink-secondary"
>
{`Subtask of #${task.parent_task_id}`}
</Span>
) : null}
{Number(task.subtask_count || 0) ? (
<Span
title={`${task.subtask_count} subtask(s), ${task.subtask_open_count || 0} still open`}
className="shrink-0 text-[11px] leading-4 text-ink-secondary"
>
{Number(task.subtask_open_count || 0)
? `${task.subtask_open_count} of ${task.subtask_count} subtasks open`
: `all ${task.subtask_count} subtasks done`}
</Span>
) : null}
{task.status == "blocked" && task.blocked_reason ? (
<Span className="min-w-0 text-xs leading-4 text-ink truncate">
{`Waiting on you: ${task.blocked_reason}`}
@@ -0,0 +1,54 @@
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Button from "@moduletrace/twui/layout/Button";
import { twMerge } from "tailwind-merge";
import type { TaskWithNames } from "@/src/types";
import TaskStatusChip from "./task-status-chip";
type Props = {
/**
* One subtask of a workspace-wide task.
*/
subtask: TaskWithNames;
/**
* Opens it in the task modal.
*/
onOpen: () => void;
};
/**
* One subtask under its workspace-wide task: its status, its title and the bot
* that has it (or nobody yet). Clicking it opens the subtask.
*/
export default function TaskSubtaskRow({ subtask, onOpen }: Props) {
const done = subtask.status == "done" || subtask.status == "cancelled";
return (
<Row className="w-full gap-2! flex-nowrap items-center py-1">
<TaskStatusChip status={subtask.status} />
<Button
title={`Open ${subtask.title || `task ${subtask.id}`}`}
type="button"
variant="ghost"
color="text"
onClick={onOpen}
className={twMerge(
"grow min-w-0 justify-start px-0! h-auto! py-0! text-[13px]! font-normal! leading-[18px]! truncate text-left hover:bg-transparent! hover:underline",
"[&_.twui-button-content-wrapper]:min-w-0 [&_.twui-button-content-wrapper]:gap-1.5",
done ? "text-ink-secondary! line-through" : "text-ink!",
)}
>
<Span className="truncate">{subtask.title || `Task ${subtask.id}`}</Span>
<Span
title={`Task ${subtask.id}`}
className="shrink-0 text-[11px] leading-4 font-normal text-ink-secondary tabular-nums"
>
{`#${subtask.id}`}
</Span>
</Button>
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
{subtask.bot_name || (subtask.bot_id ? `Bot ${subtask.bot_id}` : "Nobody")}
</Span>
</Row>
);
}
@@ -0,0 +1,47 @@
import Stack from "@moduletrace/twui/layout/Stack";
import { OpenTaskStatuses } from "@/src/dict/task-dict";
import type { TaskWithNames } from "@/src/types";
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
import TaskSubtaskRow from "./task-subtask-row";
type Props = {
open: boolean;
setOpen: (open: boolean) => void;
/**
* The workspace-wide task they belong to.
*/
task: TaskWithNames;
/**
* Every subtask of it, in the order the task keeps them.
*/
subtasks: TaskWithNames[];
/**
* Opens one of them in the task modal.
*/
onOpenSubtask: (subtask: TaskWithNames) => void;
};
/**
* Every subtask of a workspace-wide task: the whole list, when the task itself
* only shows the first few.
*/
export default function TaskSubtasksModal({ open, setOpen, task, subtasks, onOpenSubtask }: Props) {
const open_parts = subtasks.filter((subtask) => (OpenTaskStatuses as readonly string[]).includes(subtask.status || ""))
.length;
const count = `${subtasks.length} subtask${subtasks.length == 1 ? "" : "s"}`;
return (
<AddModalShell
open={open}
setOpen={setOpen}
title={`Subtasks of task #${task.id}`}
description={`${task.title ? `"${task.title}": ` : ""}${count}, ${open_parts ? `${open_parts} still open` : "all done"}. Each one is a bot's own task, and the parent stays open until someone verifies them.`}
>
<Stack className="w-full mt-4 max-h-[50vh] gap-0! items-stretch overflow-y-auto">
{subtasks.map((subtask) => (
<TaskSubtaskRow key={subtask.id} subtask={subtask} onOpen={() => onOpenSubtask(subtask)} />
))}
</Stack>
</AddModalShell>
);
}
@@ -0,0 +1,17 @@
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
type Props = {
onClose: () => void;
};
/**
* Keeps Escape on the modal on top of a stack: twui's modal closes every open
* one, so a part opened from a task (or a task from the workspace's list)
* would take the one below it away too. Mounted only while its modal is open,
* it closes that one alone and the press goes no further.
*/
export default function TopModalEscape({ onClose }: Props) {
useTopModalEscape({ onClose });
return null;
}
@@ -7,6 +7,7 @@ import profileImageUrls from "@/src/utils/profile-image-urls";
const WorkspaceAvatarSizes = {
xs: { box: "size-[18px] min-w-[18px] rounded-[4px]", icon: 12 },
sm: { box: "size-8 min-w-8 rounded-default-sm", icon: 16 },
md: { box: "size-7 min-w-7 rounded-default-sm", icon: 15 },
lg: { box: "size-14 min-w-14 rounded-default", icon: 24 },
} as const;
+64
View File
@@ -435,6 +435,22 @@ export const AppData = {
TaskNoteMaxLength: 4000,
TaskMaxPerScope: 200,
TaskMediaMaxPerTask: 20,
/**
* Parts one workspace-wide task can be split into, so a crew that keeps
* splitting never turns one task into a hundred. A part can't be split
* again, so this is the whole tree.
*/
TaskSubtaskMaxPerParent: 12,
/**
* Tasks a workspace page lists at a time, before the View all button
* opens the rest in a modal: wide ones first, then each bot's.
*/
TaskSectionShown: 5,
/**
* Subtasks a workspace-wide task's own panel lists inline, before its
* View all button opens every one of them in a modal.
*/
TaskSubtasksShown: 7,
/**
* Open tasks a chat reply carries as a digest for its reminder, and how
* many `list_tasks` hands back at once.
@@ -561,6 +577,15 @@ export const AppData = {
* row, each repeat resending the whole transcript.
*/
HarnessSameFailureRetries: 1,
/**
* How many times the review may send an answer back to be written again
* before the run stops without an answer. A note fixes most answers; the
* second rewrite is for the one that dropped the claim but named a file
* that isn't there. Past this the answer is never sent and the job fails
* saying so (`reviewBotReply`): a reply claimed a resumed run was under
* way, was sent back for it, and came back byte for byte to the user.
*/
HarnessReviewRewrites: 2,
/**
* The working context: how many tokens (estimated) of system prompt,
* tool definitions and transcript a run sends per turn before old tool
@@ -807,6 +832,18 @@ export const AppData = {
* How many of a session's latest messages that check reads.
*/
BotReplyCatchUpMessages: 20,
/**
* How long one read of a chip's view (the next steps a bot suggested,
* the questions it asked) may hang before it is dropped and asked
* again: a chip read as its message was pushed, on a phone waking up,
* once said "(not available)" until the page was reloaded.
*/
BotRefViewTimeoutMs: 8000,
/**
* How long to wait between those reads, one more read after each, so
* a ref named before its row was written heals itself in seconds.
*/
BotRefViewRetryDelaysMs: [800, 2500],
/**
* A window regaining focus and its tab becoming visible are often one
* return, and each may fire more than once: a second signal this soon
@@ -1061,6 +1098,33 @@ export const AppData = {
* Longest heading a bot may give its suggested next steps.
*/
BotSuggestionTitleMaxChars: 120,
/**
* Most steps one plan may hold (`create_plan`). Short enough that a
* user reads the whole thing before approving it.
*/
BotPlanMaxSteps: 10,
/**
* Longest title a plan may have.
*/
BotPlanTitleMaxChars: 120,
/**
* Longest goal a plan may state (what "done" means).
*/
BotPlanGoalMaxChars: 300,
/**
* Longest one plan step may be.
*/
BotPlanStepMaxChars: 240,
/**
* Longest line a bot may keep on a finished step, saying what it
* produced.
*/
BotPlanStepNoteMaxChars: 400,
/**
* Plans shown in a conversation's prompt as earlier ones, so a bot
* remembers work it already broke down.
*/
BotPlanPastShown: 3,
/**
* Longest dictation the composer records before it stops on its own.
*/
+63
View File
@@ -17,6 +17,12 @@ import {
TaskWrapUpIncomingNote,
TasksNote,
wrapUpWorktreeNote,
PlansNote,
PlanStepNote,
PlanWaitingNote,
PlanActiveNote,
PlanPausedNote,
ScheduledPlanNote,
} from "./harness-prompts";
import computerRunDirs from "@/src/utils/computer-work-dirs";
@@ -245,3 +251,60 @@ describe("AskGateRequest", () => {
expect(text).toContain("List your open tasks.");
});
});
/**
* A plan is the answer to a bot that answers a long request with one wall of
* text: the notes hold it to one step per reply and a report of two or three
* sentences, and the card behind them shows the rest.
*/
const plan = {
id: 4,
title: "Audit the pricing pages",
goal: "Know which pages price badly",
status: "active" as const,
steps: [
{ text: "Collect the pages", state: "done" as const, note: "14 pages" },
{ text: "Score them", state: "pending" as const, note: "" },
{ text: "Write it up", state: "pending" as const, note: "" },
],
current_step: 1,
};
describe("plan notes", () => {
test("waits for the user's approval, and says a plan that is open stays open", () => {
expect(PlanWaitingNote({ plan: { ...plan, status: "planned", current_step: 1 } })).toContain(
"Plan #4 \"Audit the pricing pages\"",
);
expect(PlansNote).toContain("nothing of it starts until the user approves it");
});
test("tells the run to work its step only, then report in two or three sentences", () => {
const note = PlanStepNote({ plan });
expect(note).toContain("This reply works step 2 only: Score them");
expect(note).toContain("One step per reply");
expect(note).toContain("two or three sentences");
expect(note).toContain("complete_plan_step");
});
test("lists the steps with where each one stands and what it produced", () => {
const note = PlanStepNote({ plan });
expect(note).toContain("1. [done] Collect the pages - 14 pages");
expect(note).toContain("2. [now] Score them");
expect(note).toContain("3. [pending] Write it up");
});
test("an active plan elsewhere in the conversation leaves the plan where it is", () => {
expect(PlanActiveNote({ plan })).toContain("leave the plan where it is");
});
test("a paused plan is the user's to resume", () => {
expect(PlanPausedNote({ plan: { ...plan, status: "paused" } })).toContain("paused by the user");
});
test("a routine's plan is approved at once and worked through in the run", () => {
expect(ScheduledPlanNote).toContain("approved at once");
expect(ScheduledPlanNote).toContain("work its steps in this run");
});
});
+120 -1
View File
@@ -1,4 +1,6 @@
import { AppData } from "@/src/data/app-data";
import type { BotPlanState } from "@/src/dict/bot-plan-dict";
import type { BotPlanStepRecord } from "@/src/utils/parse-bot-plan-steps";
import botRef from "@/src/utils/bot-ref";
import folderRef from "@/src/utils/folder-ref";
import computerWorkerAccount from "@/src/utils/computer-worker-account";
@@ -441,6 +443,7 @@ Nothing has run since that could change that answer, so calling it once more onl
* 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.`;
export const repeatedAnswerNote = `This is the message the app just sent back, word for word: nothing has changed since, so it will not go out either. Write it again from what the app's record shows. Take out what that record cannot support, and if the work still needs doing, call the tool that does it now rather than saying it is under way.`;
/**
* Told once, when the prompt no longer fits the working context even after
@@ -565,7 +568,7 @@ A task on your own list can go to another bot with hand_over_task: it moves to t
- When they asked for the move but not whether to start it, ask first: put one ask_user card with every task they named ("hand over and start", "hand over to wait", "leave it") and hand over only once they've answered. Once a task has left your list you can't start it any more.
- The task_id comes from list_tasks, and it has to be your own open task. You can't create work for another bot, and you can't move a workspace-wide task.
- Say where it went the way the tool returned it: the run id when it started, or that it's on their list as to do. Never say a task was handed over, or that someone picked work up, without it.
- Handing over is not asking: when you only need an answer from another bot, use ask_crew.`;
- Handing over is not asking: when you only need an answer from another bot, use ask_bot.`;
/**
* Added after `TaskRunNote` when the task is a scheduled run (a routine):
@@ -793,3 +796,119 @@ Title: ${title}
The request:
${request}`;
/**
* A plan as the prompts read it (`BotPlanView` without the bot's own name):
* its steps parsed and the one being worked.
*/
type PlanPrompt = {
id: number;
title: string;
goal: string;
status: BotPlanState;
steps: BotPlanStepRecord[];
current_step: number | null;
};
/**
* A plan's steps as a run reads them in its prompt: numbered, with what is
* done, what it is on, and what is left.
*/
const planStepLines = ({ plan }: { plan: PlanPrompt }) =>
plan.steps
.map((step, index) => {
const mark = index == plan.current_step ? "now" : step.state;
return `${index + 1}. [${mark}] ${step.text}${step.note ? ` - ${step.note}` : ""}`;
})
.join("\n");
/**
* Added to a chat reply: when to break work into a plan instead of a long
* answer, and what to keep of a plan that will be used again.
*/
export const PlansNote = `# Plans, for work that comes in pieces
Some requests are several pieces of work that build on each other, and answering them in one long message is how a reply ends up confusing: the user can't see where it is going, and nothing of it is checked. For those, call create_plan before starting:
- the work has three or more pieces that depend on each other (find out, then decide, then change), or
- the user's answer will cost real time or money and they should see the shape of it first, or
- you would otherwise be listing everything you're about to do.
Don't plan a question you can answer, one change, or work you're handing to a run (start_task): that is already broken down.
A plan is a title, the goal that says what finished looks like, and 3 to 6 steps, one line each, in the order you'd do them, each naming what it produces in the user's words. The steps are what the user reads, so write them for them, not for you.
It goes up as a card in the conversation and nothing of it starts until the user approves it (they can change the steps first). Say in one sentence that you wrote the plan and that it's theirs to change; don't repeat the steps in your text, the card shows them, and don't work a step in that reply.
Then the app wakes you one step at a time, each step in its own reply, and the card ticks along as you go.
## Plans worth keeping
When a plan you worked through is one the same work comes back to (a new project, a new client, the same check every month), save it before the conversation moves on: put the steps in as a short checklist with update_memory, in your memory of this user when it's how they work, in your core memory when it's the install's way. Say in a line that you kept it. A job that repeats on a schedule isn't memory: that's a routine, and create_schedule makes one once the user agrees.`;
/**
* A plan waiting on the user: the bot wrote it and may not start it yet,
* whatever the user writes in the meantime.
*/
export const PlanWaitingNote = ({ plan }: { plan: PlanPrompt }) => `# Your plan is waiting on the user
Plan #${plan.id} "${plan.title}" is on its card in this conversation, waiting for the user to approve it or change its steps. Its steps are not work yet: don't start them, don't report on them, and don't write another plan. Answer what the user wrote; if they asked for changes to the plan, they make them on the card.`;
/**
* Given to the run that works one step of an approved plan: that step only,
* a short report of it, and nothing else. This is where a reply stops being
* a wall of text.
*/
export const PlanStepNote = ({ plan }: { plan: PlanPrompt }) => {
const index = plan.current_step ?? 0;
const step = plan.steps[index];
return `# Your plan, step ${index + 1} of ${plan.steps.length}
Plan #${plan.id} "${plan.title}".${plan.goal ? ` Goal: ${plan.goal}` : ""}
${planStepLines({ plan })}
This reply works step ${index + 1} only: ${step?.text || ""}
- One step per reply. The app wakes you for the next one when this finishes, so don't start it now and don't do two.
- Finish it with complete_plan_step: one or two lines on what it produced (the number, the path, the link). Then write your report to the user.
- Your report is two or three sentences: what this step did and what it produced. No heading, no recap of the plan, and never "next, I'll...". The card above the report shows the plan and the step after this one, so repeating it only makes the reply longer than it needs to be.
- If the step can't be done from here (it needs the user, a login or a decision they alone can make), don't finish it: ask one question with ask_user and say the plan is holding at this step.
- If what you found means the rest of the plan is wrong, change it with update_plan, in the same reply, and say what changed.`;
};
/**
* Given to any other run in a conversation whose plan is approved and being
* worked: the plan is in the prompt, and the user's own message comes first.
*/
export const PlanActiveNote = ({ plan }: { plan: PlanPrompt }) => {
const index = plan.current_step;
return `# The plan in this conversation
Plan #${plan.id} "${plan.title}" is approved and in progress${index == null ? "" : `, on step ${index + 1} of ${plan.steps.length}`}.
${planStepLines({ plan })}
- If the user's message is about this plan's work, work that step and only that step, then complete_plan_step with what it produced, then a short report.
- If they asked something else, answer that and leave the plan where it is: it carries on from there.
- The steps are theirs to change on the card. If the work moved on from one of them, update_plan and say what changed.`;
};
/**
* A paused plan: the user stopped it, so its steps wait until they say
* otherwise. The bot still answers them.
*/
export const PlanPausedNote = ({ plan }: { plan: PlanPrompt }) => `# A paused plan
Plan #${plan.id} "${plan.title}" is paused by the user at step ${(plan.current_step ?? 0) + 1} of ${plan.steps.length}. Don't work its steps and don't finish them: answer what the user asks, and leave picking it back up to them (they resume it from the card).`;
/**
* Added to a routine's run: nobody is there to approve a plan, so the bot
* writes one and works all of it in the run, reporting at the end.
*/
export const ScheduledPlanNote = `# A plan in a scheduled run
Nobody is watching this run, so a plan can't wait for approval. If this run's work is several pieces that build on each other, write it with create_plan anyway (it is approved at once here) and work its steps in this run: complete_plan_step after each one, with what it produced, so the conversation shows how far it got. Nothing interleaves with your run, so don't stop after one step. Your report at the end covers the whole plan: what each step produced and what is left.`;
+64
View File
@@ -0,0 +1,64 @@
/**
* Where a plan stands. A bot writes one as `planned` and the user approves
* it on its card, which makes it `active`: from there the bot works one
* step at a time and reports each (`complete_plan_step`). `paused` stops it
* where it is until the user resumes it, `done` is every step finished or
* skipped, and `cancelled` is a plan nobody carries on.
*/
export const BotPlanStates = [
{
title: "Waiting for you",
value: "planned",
},
{
title: "In progress",
value: "active",
},
{
title: "Paused",
value: "paused",
},
{
title: "Done",
value: "done",
},
{
title: "Cancelled",
value: "cancelled",
},
] as const;
export type BotPlanState = (typeof BotPlanStates)[number]["value"];
/**
* The states a plan can still be worked in: only one of them is open in a
* conversation at a time.
*/
export const BotPlanOpenStates: BotPlanState[] = ["planned", "active", "paused"];
/**
* A step of a plan: it waits, it's done (with a line on what it produced),
* or it was skipped (the work made it unnecessary).
*/
export const BotPlanStepStates = [
{
title: "Done",
value: "done",
},
{
title: "Skipped",
value: "skipped",
},
{
title: "Pending",
value: "pending",
},
] as const;
export type BotPlanStepState = (typeof BotPlanStepStates)[number]["value"];
/**
* The states the user sets from a plan's card: approve it, pause it or end
* it. `done` is the app's own call, set when the last step is finished.
*/
export const BotPlanSettableStates: BotPlanState[] = ["active", "paused", "cancelled"];
+1 -1
View File
@@ -84,7 +84,7 @@ export const BotTypePermissionMatrix: Record<BotRole, BotPermission[]> = {
/**
* A worker can't hand out work: it passes on a task it already has
* (`hand_over_task`), and asks the crew for anything else through the
* coordinator (`ask_crew`).
* coordinator (`ask_bot`).
*/
worker: ["hand_over_task"],
};
@@ -8,6 +8,7 @@ import startBotSession from "../bot-sessions/start-bot-session";
import grabWorkspaceName from "../workspaces/grab-workspace-name";
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
import grabActiveBotSession from "../bot-sessions/grab-active-bot-session";
import askPreviousSessionId from "@/src/utils/ask-previous-session-id";
type Params = {
ask: BUN_SQLITE_COBBLE_BOT_ASKS;
@@ -29,7 +30,10 @@ type Params = {
* (instructions, memory, files, computers) and the answer is posted where
* the work belongs. Every request starts a new session
* (`startBotSession`), so the conversation the user was in is left where it
* was. Opened with the brief as a user-side crew message. The ask is
* was, and that session is what the session's bar leads back to: a bot with
* no conversation there before the request (or one still empty, which
* `startBotSession` keeps as it is) gets no way back, so its thread shows no
* bar at all. Opened with the brief as a user-side crew message. The ask is
* `working` from here until that run ends (`onAskJobEnded`).
*/
export default async function enqueueAskAnswer({ ask, target, requester_name, gate_note }: Params) {
@@ -46,6 +50,15 @@ export default async function enqueueAskAnswer({ ask, target, requester_name, ga
workspace_id,
});
/**
* Null when there was nothing to go back to: no session before the
* request, or an empty one `startBotSession` kept as the request's own.
*/
const previous_session_id = askPreviousSessionId({
previous_session_id: previous?.id,
session_id: session.id,
});
/**
* Titled from the request, so the sessions list says what it is before
* the bot answers (`nameBotSession` renames it from the exchange).
@@ -114,7 +127,7 @@ export default async function enqueueAskAnswer({ ask, target, requester_name, ga
Number(target.id),
Number(session.id),
job_id,
previous ? Number(previous.id) : null,
previous_session_id,
gate_note || null,
Date.now(),
Number(ask.id),
+10 -1
View File
@@ -9,6 +9,7 @@ import grabUserBot from "../bots/grab-user-bot";
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
import insertUserMessage from "../bots/insert-user-message";
import askOutcomeMessage from "./ask-outcome-message";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
type Params = {
ask: BUN_SQLITE_COBBLE_BOT_ASKS;
@@ -93,7 +94,15 @@ async function tellRequester({
bot_id: requester.id,
session_id: session.id,
workspace_id: Number(ask.workspace_id) || null,
text: askOutcomeMessage({ ask, status, outcome }),
/**
* A question the answer names stays in the conversation it was
* asked in: its card here would answer into this one.
*/
text: askOutcomeMessage({
ask,
status,
outcome: outcome ? stripQuestionRefs({ text: outcome }).text : outcome,
}),
from_ask_id: Number(ask.id),
});
@@ -0,0 +1,85 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import AppError from "@/src/utils/app-error";
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
import grabBotPlan from "./grab-bot-plan";
type Params = {
plan_id: number | string;
/**
* The conversation the run is in: a plan is only worked where it was
* written.
*/
session_id: number | string;
/**
* What the step produced, in a line or two.
*/
summary: string;
};
/**
* The bot finished the plan's current step: it's marked done with what it
* produced, and the plan moves to the next one. The last step done ends
* the plan.
*
* A step is only ever finished inside a run that did the work, one at a
* time: a plan waiting on the user can't be worked, and neither can one
* that's paused, ended, or has nothing left.
*/
export default async function completeBotPlanStep({ plan_id, session_id, summary }: Params) {
const row = await grabBotPlan({ plan_id });
if (Number(row.session_id) != Number(session_id)) {
throw new AppError(`Plan #${row.id} belongs to another conversation: work that conversation's plan.`);
}
if (row.status == "planned") {
throw new AppError(
`Plan #${row.id} is waiting for the user to approve it on its card: don't work its steps yet. Answer them and let them decide.`,
);
}
if (row.status != "active") {
throw new AppError(`Plan #${row.id} is ${row.status}: there's no step to finish.`);
}
const steps = parseBotPlanSteps({ text: row.steps });
const index = currentPlanStepIndex({ steps });
if (index == null) {
throw new AppError(`Every step of plan #${row.id} is already done.`);
}
const note = summary.trim().slice(0, AppData.BotPlanStepNoteMaxChars);
const working = steps[index];
if (!working) {
throw new AppError(`Every step of plan #${row.id} is already done.`);
}
steps[index] = { text: working.text, state: "done", note };
const next = currentPlanStepIndex({ steps });
const now = Date.now();
await BunSQLite.sql({
sql: `UPDATE bot_plans SET steps = ?, status = ?, updated_at = ? WHERE id = ?`,
values: [JSON.stringify(steps), next == null ? "done" : "active", now, Number(row.id)],
});
return {
plan_id: Number(row.id),
session_id: Number(row.session_id),
bot_id: Number(row.bot_id),
index,
step: working.text,
note,
/**
* The step to work next: null once the plan is finished.
*/
next_step: next,
done: next == null,
steps,
};
}
@@ -0,0 +1,60 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
import shouldContinuePlan from "@/src/utils/should-continue-plan";
import enqueuePlanStep from "./enqueue-plan-step";
import grabBotPlan from "./grab-bot-plan";
type Params = {
plan_id: number | string;
session_id: number | string;
/**
* The reply asked the user something (`ask_user`), so it waits on them
* rather than carrying on.
*/
needs_you?: boolean;
/**
* The tools the run called: one that starts work (a task, a hand-over,
* a request to another bot) has a report still to come, so the plan
* waits for it instead of talking over it.
*/
tool_names?: string[];
};
/**
* Carries a plan on after a run finished a step: the bot reports the step it
* finished, and this wakes it for the next one, so the work runs through the
* plan step by step without the user nudging it each time.
*
* Nothing is queued when the run is waiting on the user, when it started
* work whose report is still to come, when the plan was paused or cancelled
* meanwhile, or when the conversation already has a reply waiting (a message
* the user sent mid-step, whose own run picks the plan up from there).
*/
export default async function continueBotPlan({ plan_id, session_id, needs_you, tool_names }: Params) {
const row = await grabBotPlan({ plan_id });
const steps = parseBotPlanSteps({ text: row.steps });
const waiting = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bots_queue
WHERE session_id = ? AND kind = 'reply' AND status IN ('pending', 'processing')
LIMIT 1`,
values: [Number(session_id)],
})
).payload?.[0];
const carry_on = shouldContinuePlan({
status: row.status || "",
needs_you,
tool_names,
plan_session_id: row.session_id,
session_id,
has_pending_step: currentPlanStepIndex({ steps }) != null,
has_waiting_reply: Boolean(waiting),
});
if (!carry_on) return null;
return await enqueuePlanStep({ plan_id: row.id });
}
@@ -0,0 +1,57 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_PLANS, BunSQLiteTables } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
import type { BotPlanStepRecord } from "@/src/utils/parse-bot-plan-steps";
import grabSessionPlan from "./grab-session-plan";
type Params = {
user_id: number | string;
bot_id: number | string;
session_id: number | string;
workspace_id?: number | string | null;
title: string;
goal?: string;
/**
* The steps in the order they're worked.
*/
steps: string[];
};
/**
* Stores a plan a bot wrote, waiting for the user's approval (`planned`).
* One plan is open in a conversation at a time: the bot works the one it
* has before writing another. Returns the plan's id.
*/
export default async function createBotPlan({ user_id, bot_id, session_id, workspace_id, title, goal, steps }: Params) {
const open = await grabSessionPlan({ session_id });
if (open) {
throw new AppError(
`There's already a plan open in this conversation (#${open.id}, "${open.title || "untitled"}"): work that one, or cancel it before writing another.`,
);
}
const records: BotPlanStepRecord[] = steps.map((step) => ({ text: step, state: "pending", note: "" }));
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_PLANS, (typeof BunSQLiteTables)[number]>({
table: "bot_plans",
data: [
{
title,
goal: goal || "",
steps: JSON.stringify(records),
status: "planned",
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 plan: ${res.msg}`);
return id;
}
@@ -0,0 +1,21 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
session_ids: number[];
};
/**
* Deletes the plans of sessions that are going away, with the conversation
* they belonged to (foreign keys are off outside the server process, so a
* parent's children go explicitly).
*/
export default async function deleteBotPlanRows({ session_ids }: Params) {
const ids = session_ids.map(Number).filter(Boolean);
if (!ids.length) return;
await BunSQLite.sql({
sql: `DELETE FROM bot_plans WHERE session_id IN (${ids.map(() => "?").join(", ")})`,
values: ids,
});
}
@@ -0,0 +1,43 @@
import { BotReplyJobTitle } from "@/src/dict/bot-queue-dict";
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
import enqueueBotJob from "../bots-queue/enqueue-bot-job";
import grabBotPlan from "./grab-bot-plan";
type Params = {
plan_id: number | string;
};
/**
* Wakes the bot for its plan's current step: one reply job, which works
* that step and reports it. Nothing is queued for a plan that isn't
* running, or one with no step left, so approving a finished plan, a double
* click or a stop never leaves a run with nothing to do.
*
* The step itself is read by the run from the conversation's plan, never
* from here: a run that starts late still works the step that's actually
* next.
*/
export default async function enqueuePlanStep({ plan_id }: Params) {
const row = await grabBotPlan({ plan_id });
if (row.status != "active") return null;
const steps = parseBotPlanSteps({ text: row.steps });
if (currentPlanStepIndex({ steps }) == null) return null;
const user_id = Number(row.user_id);
const job_id = await enqueueBotJob({
kind: "reply",
user_id,
bot_id: Number(row.bot_id),
session_id: Number(row.session_id),
title: BotReplyJobTitle,
instructions: "Work the current step of the plan in this conversation, then report it.",
params: { plan_id: Number(row.id) },
});
return job_id;
}
@@ -0,0 +1,21 @@
import type { BotPlanView } from "@/src/types";
import grabBotPlan from "./grab-bot-plan";
import toBotPlanView from "./to-bot-plan-view";
type Params = {
plan_id: number | string;
/**
* Only the user it was made for reads it.
*/
user_id: number | string;
};
/**
* A plan as its card shows it, for the user it was made for. Throws
* otherwise.
*/
export default async function grabBotPlanView({ plan_id, user_id }: Params) {
const row = await grabBotPlan({ plan_id, user_id });
return toBotPlanView({ row }) as BotPlanView;
}
@@ -0,0 +1,44 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_PLANS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
type Params = {
plan_id: number | string;
/**
* Only the user a plan was made for reads it. Left out by a run, which
* already works that user's conversation.
*/
user_id?: number | string | null;
};
/**
* A plan as the helpers read it: its id and the places it belongs to are
* there once it's been found, which the typedef can't say on its own.
*/
export type BotPlanRow = BUN_SQLITE_COBBLE_BOT_PLANS & {
id: number;
user_id: number;
bot_id: number;
session_id: number;
title: string;
};
/**
* A plan by its id, with the name of the bot that wrote it (a run's prompt
* and the card both name it). Throws when it isn't there, or isn't the
* user's.
*/
export default async function grabBotPlan({ plan_id, user_id }: Params) {
const row = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_PLANS & { bot_name?: string }>({
sql: `SELECT bp.*, b.name AS bot_name FROM bot_plans bp
LEFT JOIN bots b ON b.id = bp.bot_id
WHERE bp.id = ?${user_id ? " AND bp.user_id = ?" : ""} LIMIT 1`,
values: user_id ? [Number(plan_id), Number(user_id)] : [Number(plan_id)],
})
).payload?.[0];
if (!row?.id) throw new AppError(`That plan isn't yours or no longer exists.`);
return row as BotPlanRow;
}
@@ -0,0 +1,26 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_PLANS } from "@/db/types/db";
import { BotPlanOpenStates } from "@/src/dict/bot-plan-dict";
type Params = {
session_id: number | string;
};
/**
* The plan open in a conversation: the one the bot is waiting on the user
* to approve, or is working. A conversation has at most one, so a run
* always knows which plan it is on. Null when the conversation has none
* (finished and cancelled plans are history, not work).
*/
export default async function grabSessionPlan({ session_id }: Params) {
const row = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_PLANS>({
sql: `SELECT * FROM bot_plans
WHERE session_id = ? AND status IN (${BotPlanOpenStates.map(() => "?").join(", ")})
ORDER BY id DESC LIMIT 1`,
values: [Number(session_id), ...BotPlanOpenStates],
})
).payload?.[0];
return row?.id ? row : null;
}
@@ -0,0 +1,64 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import AppError from "@/src/utils/app-error";
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
import planStepsRewriteProblem from "@/src/utils/plan-steps-rewrite-problem";
import parseBotPlanSteps, { type BotPlanStepRecord } from "@/src/utils/parse-bot-plan-steps";
import grabBotPlan from "./grab-bot-plan";
type Params = {
plan_id: number | string;
user_id: number | string;
title: string;
goal?: string;
/**
* The plan's steps as the user wants them, in order.
*/
steps: string[];
};
/**
* The user changed a plan's steps on its card, before the bot starts or
* while it's working. A step already done (or skipped) is the record of work
* that really happened: it stays where it is and keeps its note, so it may
* not be changed or dropped, and the steps before it are its own. Everything
* after is theirs to rewrite, reorder, add to or cut. A plan left with
* nothing to work is done.
*/
export default async function saveBotPlanSteps({ plan_id, user_id, title, goal, steps }: Params) {
const row = await grabBotPlan({ plan_id, user_id });
if (row.status != "planned" && row.status != "active" && row.status != "paused") {
throw new AppError(`This plan is ${row.status}: there's nothing left to change in it.`);
}
const existing = parseBotPlanSteps({ text: row.steps });
const finished = existing.filter((step) => step.state != "pending");
const by_text = new Map(finished.map((step) => [step.text.toLowerCase(), step]));
const next: BotPlanStepRecord[] = steps.map((text) => {
const kept = by_text.get(text.toLowerCase());
return kept ? { ...kept } : { text, state: "pending" as const, note: "" };
});
const rewrite_problem = planStepsRewriteProblem({ finished, next });
if (rewrite_problem) throw new AppError(rewrite_problem);
const now = Date.now();
const done = currentPlanStepIndex({ steps: next }) == null;
await BunSQLite.sql({
sql: `UPDATE bot_plans SET title = ?, goal = ?, steps = ?, status = ?, updated_at = ? WHERE id = ?`,
values: [
title,
goal || "",
JSON.stringify(next),
done ? "done" : row.status,
now,
Number(row.id),
],
});
return await grabBotPlan({ plan_id: row.id, user_id });
}
@@ -0,0 +1,70 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BotPlanState } from "@/src/dict/bot-plan-dict";
import AppError from "@/src/utils/app-error";
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
import grabBotPlan from "./grab-bot-plan";
type Params = {
plan_id: number | string;
user_id: number | string;
status: BotPlanState;
};
/**
* The user moved a plan from its card: approved it (which starts it),
* paused it where it is, picked it back up, or ended it. Only the moves
* that mean something from where it stands are allowed, so a double click
* changes nothing and a finished plan never comes back.
*
* Returns the row as it now stands and whether it just started, which is
* when the bot is woken for its first step.
*/
export default async function setBotPlanStatus({ plan_id, user_id, status }: Params) {
const row = await grabBotPlan({ plan_id, user_id });
const current = row.status as BotPlanState;
if (current == status) return { row, started: false };
if (current == "done" || current == "cancelled") {
throw new AppError(`This plan is ${current}: it can't be picked up again.`);
}
const steps = parseBotPlanSteps({ text: row.steps });
const caught_up = currentPlanStepIndex({ steps }) == null;
if (status == "active") {
if (current != "planned" && current != "paused") {
throw new AppError(`This plan is ${current}: it isn't paused.`);
}
if (caught_up) {
throw new AppError(`Every step of this plan is already done: there's nothing to start.`);
}
}
if (status == "paused" && current != "active") {
throw new AppError(`Only a plan that's running can be paused.`);
}
const now = Date.now();
await BunSQLite.sql({
sql: `UPDATE bot_plans SET status = ?, decided_at = ?, updated_at = ? WHERE id = ?`,
values: [
status,
status == "active" || status == "cancelled" ? now : row.decided_at || null,
now,
Number(row.id),
],
});
return {
row: await grabBotPlan({ plan_id: row.id, user_id }),
/**
* Approved for the first time: the bot picks the plan up now. A
* resume after a pause is the same move from the user's side.
*/
started: status == "active",
};
}
@@ -0,0 +1,39 @@
import type { BUN_SQLITE_COBBLE_BOT_PLANS } from "@/db/types/db";
import type { BotPlanState } from "@/src/dict/bot-plan-dict";
import type { BotPlanView } from "@/src/types";
import currentPlanStepIndex from "@/src/utils/current-plan-step-index";
import parseBotPlanSteps from "@/src/utils/parse-bot-plan-steps";
import planStepCounts from "@/src/utils/plan-step-counts";
type Params = {
row: BUN_SQLITE_COBBLE_BOT_PLANS & { bot_name?: string };
};
/**
* A plan's row as the card and a prompt read it: its steps parsed, where it
* stands, and how much of it is behind it. One shape for both, so the card
* never shows something the bot wasn't told.
*/
export default function toBotPlanView({ row }: Params): BotPlanView {
const steps = parseBotPlanSteps({ text: row.steps });
const counts = planStepCounts({ steps });
return {
id: Number(row.id),
title: row.title || "",
goal: row.goal || "",
steps,
status: (row.status || "planned") as BotPlanState,
current_step: currentPlanStepIndex({ steps }),
finished_steps: counts.finished,
total_steps: counts.total,
decided_at: row.decided_at ? Number(row.decided_at) : null,
created_at: Number(row.created_at) || 0,
updated_at: Number(row.updated_at) || 0,
user_id: Number(row.user_id),
bot_id: Number(row.bot_id),
bot_name: row.bot_name || "",
session_id: Number(row.session_id),
workspace_id: row.workspace_id ? Number(row.workspace_id) : null,
};
}
@@ -0,0 +1,88 @@
import type { BUN_SQLITE_COBBLE_BOT_QUESTIONS, BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
import { logError } from "@/src/functions/backend/logger";
import pushBotNotice from "@/src/bots-queue/push-bot-notice";
import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
import type { BotQuestionView } from "@/src/types";
import botQuestionAnswersText from "@/src/utils/bot-question-answers-text";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
import insertUserMessage from "../bots/insert-user-message";
import enqueueBotReply from "../bots-queue/enqueue-bot-reply";
import grabBotQuestion from "./grab-bot-question";
type Params = {
view: BotQuestionView;
user_id: number | string;
};
/**
* Tells the bot, in the conversation its questions were asked in, what the
* user answered (or that they skipped them): the user's chat message there,
* which wakes it. The route posts this, not the card's page: the same
* conversation can be on screen in several places, and an answer belongs
* where the question was asked, never to whichever bot's page was open.
* Best effort: a failure is logged and never undoes the answer.
*/
export default async function postBotQuestionAnswers({ view, user_id }: Params) {
try {
const row = await grabBotQuestion({ question_id: view.id, user_id });
if (!row.bot_id) return;
const session = await pickSession({ row, user_id });
const message = await insertUserMessage({
bot_id: Number(row.bot_id),
session_id: Number(session.id),
workspace_id: session.workspace_id || null,
text: botQuestionAnswersText({ view }),
});
await pushBotNotice({ bot_id: row.bot_id, message });
await enqueueBotReply({
user_id,
bot_id: row.bot_id,
session_id: Number(session.id),
message_id: Number(message.id),
});
wakeBotsQueue();
} catch (error: unknown) {
await logError({
title: `A bot's question answers didn't reach it`,
error,
metadata: { question_id: view.id },
}).catch(() => {});
}
}
/**
* The session the questions were asked in while it's still where the bot
* talks; otherwise its conversation's active one, so the answer isn't left
* in a closed thread.
*/
async function pickSession({
row,
user_id,
}: {
row: Pick<BUN_SQLITE_COBBLE_BOT_QUESTIONS, "bot_id" | "session_id" | "workspace_id">;
user_id: number | string;
}): Promise<BUN_SQLITE_COBBLE_BOT_SESSIONS> {
const origin = row.session_id
? await grabUserBotSession({ session_id: row.session_id, user_id })
: null;
/**
* A hidden session (a crew request's, a hook's) is only read there.
*/
if (origin?.id && origin.status == "active" && !origin.ask_id && !origin.hook_id) {
return origin;
}
return await ensureBotSession({
user_id,
bot_id: row.bot_id!,
workspace_id: row.workspace_id || null,
});
}
@@ -1,4 +1,5 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import deleteSessionRows from "./delete-session-rows";
type Params = {
session_id: number | string;
@@ -8,8 +9,10 @@ type Params = {
* Drops a crew request's hidden session when nothing ever landed in it:
* the coordinator's review runs in one, and it writes no message there.
* Only a session with no messages and no open job goes, so an answer's
* session is never touched. Foreign keys are off outside the server
* process, so its job rows go explicitly.
* session is never touched. It goes the way any other session does
* (`deleteSessionRows`): the review job that just ended, its queue updates
* and what its calls were billed leave with it, since foreign keys are off
* outside the server process.
*/
export default async function deleteEmptyAskSession({ session_id }: Params) {
const res = await BunSQLite.sql({
@@ -27,9 +30,7 @@ export default async function deleteEmptyAskSession({ session_id }: Params) {
if (!id) return false;
await BunSQLite.sql({ sql: `DELETE FROM bot_job_traces WHERE session_id = ?`, values: [id] });
await BunSQLite.sql({ sql: `DELETE FROM bot_tasks WHERE session_id = ?`, values: [id] });
await BunSQLite.sql({ sql: `DELETE FROM bot_sessions WHERE id = ?`, values: [id] });
await deleteSessionRows({ session_ids: [Number(id)] });
return true;
}
@@ -1,5 +1,6 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import deleteUnlinkedAttachmentMedia from "../media/delete-unlinked-attachment-media";
import deleteBotPlanRows from "../bot-plans/delete-bot-plan-rows";
type Params = {
session_ids: number[];
@@ -105,6 +106,7 @@ export default async function deleteSessionRows({ session_ids }: Params) {
sql: `DELETE FROM bot_tasks WHERE session_id IN (${session_placeholders})`,
values: ids,
});
await deleteBotPlanRows({ session_ids: ids });
await BunSQLite.sql({
sql: `DELETE FROM bot_sessions WHERE id IN (${session_placeholders})`,
values: ids,
@@ -2,6 +2,7 @@ import type { BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
import BunSQLite from "@moduletrace/bun-sqlite";
import AppError from "@/src/utils/app-error";
import grabUserBotSession from "./grab-user-bot-session";
import deleteSessionRows from "./delete-session-rows";
type Params = {
session_id: number | string;
@@ -52,11 +53,19 @@ export default async function reopenBotSession({
const now = Date.now();
const workspace_id = session.workspace_id || null;
await BunSQLite.sql({
sql: `DELETE FROM bot_sessions WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND status = 'active'
AND NOT EXISTS (SELECT 1 FROM bot_messages m WHERE m.session_id = bot_sessions.id)`,
values: [session.user_id!, session.bot_id!, workspace_id],
});
/**
* The empty one goes with its own rows (`deleteSessionRows`): a job it
* still held would otherwise point at a session that is gone.
*/
const emptied = (
await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM bot_sessions WHERE user_id = ? AND bot_id = ? AND workspace_id IS ? AND status = 'active'
AND NOT EXISTS (SELECT 1 FROM bot_messages m WHERE m.session_id = bot_sessions.id)`,
values: [session.user_id!, session.bot_id!, workspace_id],
})
).payload || [];
await deleteSessionRows({ session_ids: emptied.map((row) => Number(row.id)) });
await BunSQLite.sql({
sql: `UPDATE bot_sessions SET status = 'closed', unread = 0, updated_at = ?
@@ -6,6 +6,7 @@ import type {
} from "@/db/types/db";
import insertBotMessage from "../bots/insert-bot-message";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
type Params = {
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
@@ -66,13 +67,24 @@ export default async function relayJobToRequester({ job, text, failed, task_ids
const name = worker?.name || "A crew member";
const title = job.title || "the job";
/**
* The worker's questions stay in its own conversation: a card here
* would be answered into this one, and the worker would never hear.
*/
const report = stripQuestionRefs({ text });
const where = report.removed
? `\n\n_They asked you something in their own conversation: [bot:${job.bot_id}]._`
: "";
const message = await insertBotMessage({
bot_id: requester.id,
session_id: Number(session.id),
workspace_id,
text: failed
? `${name} couldn't finish **${title}**. ${text}`.trim()
: `${name} finished **${title}**. Their report:\n\n${text}`,
text:
(failed
? `${name} couldn't finish **${title}**. ${report.text}`
: `${name} finished **${title}**. Their report:\n\n${report.text}`
).trim() + where,
needs_you: failed,
task_ids,
});
@@ -1,24 +1,27 @@
import { Harnesses } from "@/src/dict/harness-dict";
import type { BotHarnessOverviewPayload } from "@/src/types";
import grabHarnessModelEntries from "./grab-harness-model-entries";
import grabHarnessOverviewItem from "./grab-harness-overview-item";
import grabHarnessSetting from "./grab-harness-setting";
import type { HarnessSettingSource } from "./pick-harness-setting-row";
/**
* Only what a bot or workspace may set: install-wide harnesses are the
* defaults' alone.
*/
const OwnHarnesses = Harnesses.filter((harness) => !harness.install_wide);
import type { BotHarnessOverviewPayload } from "@/src/types";
import grabHarnessModelEntries from "./grab-harness-model-entries";
import grabHarnessOverviewItem from "./grab-harness-overview-item";
import grabHarnessSetting from "./grab-harness-setting";
type Params = {
/**
* A worker bot the caller has checked belongs to the session user.
* A worker bot the caller has checked belongs to the session user. Its
* own models are what the form edits; in a workspace the workspace's
* are what it inherits.
*/
bot_id?: number;
/**
* A workspace the caller has checked belongs to the session user. Then
* the settings shown are the workspace's own, over what it inherits:
* the bot's (when given) or the defaults.
* A workspace the caller has checked belongs to the session user. With
* no bot, the form edits the workspace's own models; with a bot, the
* workspace's are the bot's default there.
*/
workspace_id?: number;
};
@@ -34,24 +37,28 @@ export default async function grabBotHarnessOverview({
workspace_id,
}: Params): Promise<BotHarnessOverviewPayload> {
/**
* In a workspace, "the default" is what a run there gets without the
* workspace's own setting: the bot's, else the defaults.
* The setting the form edits: the bot's own when it names one, else
* the workspace's own (or, on a workspace's page, the workspace's).
*/
const inherited_bot_id = workspace_id ? bot_id : undefined;
const own_context = { bot_id, workspace_id };
/**
* What the owner runs on without its own setting. A bot in a workspace
* inherits the workspace's models; a workspace (or a bot outside one)
* inherits the defaults.
*/
const inherited_context = bot_id ? { workspace_id } : {};
const own_source: HarnessSettingSource = bot_id ? "bot" : "workspace";
const [own, defaults] = await Promise.all([
Promise.all(
OwnHarnesses.map((harness) =>
grabHarnessSetting({
harness: harness.value,
bot_id: workspace_id ? undefined : bot_id,
workspace_id,
}),
grabHarnessSetting({ harness: harness.value, ...own_context }),
),
),
Promise.all(
OwnHarnesses.map((harness) =>
grabHarnessSetting({ harness: harness.value, bot_id: inherited_bot_id }),
grabHarnessSetting({ harness: harness.value, ...inherited_context }),
),
),
]);
@@ -70,20 +77,19 @@ export default async function grabBotHarnessOverview({
harness: setting.harness,
setting,
entries,
bot_id,
workspace_id,
...own_context,
}),
grabHarnessOverviewItem({
harness: setting.harness,
setting: defaults[index]!,
entries,
bot_id: inherited_bot_id,
...inherited_context,
}),
]);
return {
...item,
inherit: setting.source == "default",
inherit: setting.source != own_source,
default: {
enabled: default_item.enabled,
current: default_item.current,
@@ -93,4 +99,4 @@ export default async function grabBotHarnessOverview({
}),
),
};
}
}
@@ -7,6 +7,9 @@ import type {
import { isInstallWideHarness, type HarnessKind } from "@/src/dict/harness-dict";
import parseJobJson from "@/src/bots-queue/parse-job-json";
import grabDefaultHarnessProviderId from "./grab-default-harness-provider-id";
import pickHarnessSettingRow, {
type HarnessSettingSource,
} from "./pick-harness-setting-row";
export type HarnessSetting = {
harness: HarnessKind;
@@ -23,10 +26,10 @@ export type HarnessSetting = {
enabled: boolean;
options: Record<string, unknown>;
/**
* `workspace` when the call's workspace sets this harness, `bot` when a
* worker bot overrides the default for it.
* `bot` when a worker bot sets this harness, `workspace` when the
* call's workspace does, `default` when neither does.
*/
source: "default" | "bot" | "workspace";
source: HarnessSettingSource;
};
type Params = {
@@ -37,8 +40,8 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in. Its setting wins over the bot's, for
* the coordinator too.
* The workspace the call is in. Its setting applies to the bots that
* have none of their own, the coordinator too.
*/
workspace_id?: number | string | null;
};
@@ -49,8 +52,8 @@ type SettingRow = Pick<
>;
/**
* A harness's setting for a call: the workspace's, else the bot's, else
* the default. With no row it is automatic on the default provider
* A harness's setting for a call: the bot's own, else its workspace's,
* else the default. With no row it is automatic on the default provider
* (OpenRouter), on, with fallback. Text is always on. An install-wide
* harness (embeddings) always takes the default: rows a bot or workspace
* saved before it was one are ignored.
@@ -62,37 +65,34 @@ export default async function grabHarnessSetting({
}: Params): Promise<HarnessSetting> {
const install_wide = isInstallWideHarness({ harness });
const workspace_row = workspace_id && !install_wide
? await grabWorkspaceOverride({ harness, workspace_id })
: undefined;
const bot_row =
!install_wide && bot_id ? await grabBotOverride({ harness, bot_id }) : undefined;
if (workspace_row) {
return toSetting({ harness, row: workspace_row, source: "workspace" });
}
const workspace_row =
!bot_row && !install_wide && workspace_id
? await grabWorkspaceOverride({ harness, workspace_id })
: undefined;
const bot_row = bot_id && !install_wide
? await grabBotOverride({ harness, bot_id })
: undefined;
const default_row =
bot_row || workspace_row
? undefined
: (
await BunSQLite.sql<BUN_SQLITE_COBBLE_HARNESS_SETTINGS>({
sql: `SELECT * FROM harness_settings WHERE harness = ? LIMIT 1`,
values: [harness],
})
).payload?.[0];
if (bot_row) {
return toSetting({ harness, row: bot_row, source: "bot" });
}
const picked = pickHarnessSettingRow({ bot_row, workspace_row, default_row });
const row = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_HARNESS_SETTINGS>({
sql: `SELECT * FROM harness_settings WHERE harness = ? LIMIT 1`,
values: [harness],
})
).payload?.[0];
if (!row) {
if (!picked.row) {
return {
...toSetting({ harness, source: "default" }),
...toSetting({ harness, source: picked.source }),
provider_id: await grabDefaultHarnessProviderId(),
};
}
return toSetting({ harness, row, source: "default" });
return toSetting({ harness, row: picked.row, source: picked.source });
}
async function grabWorkspaceOverride({
@@ -0,0 +1,35 @@
import { describe, expect, test } from "bun:test";
import pickHarnessSettingRow from "./pick-harness-setting-row";
const bot_row = { owner: "bot" };
const workspace_row = { owner: "workspace" };
const default_row = { owner: "default" };
describe("pickHarnessSettingRow", () => {
test("a bot's own pick wins, in a workspace too", () => {
expect(
pickHarnessSettingRow({ bot_row, workspace_row, default_row }),
).toEqual({ row: bot_row, source: "bot" });
});
test("without its own pick a bot in a workspace inherits the workspace's", () => {
expect(pickHarnessSettingRow({ workspace_row, default_row })).toEqual({
row: workspace_row,
source: "workspace",
});
});
test("the defaults come last", () => {
expect(pickHarnessSettingRow({ default_row })).toEqual({
row: default_row,
source: "default",
});
});
test("no rows at all is still the defaults", () => {
expect(pickHarnessSettingRow({})).toEqual({
row: undefined,
source: "default",
});
});
});
@@ -0,0 +1,39 @@
/**
* Whose saved setting a harness call uses: a worker bot's own wins, then
* the models of the workspace it works in, then the install defaults.
*/
export type HarnessSettingSource = "bot" | "workspace" | "default";
type Params<Row> = {
/**
* The bot's own row (`bot_harness_settings`), when the call names a
* worker bot.
*/
bot_row?: Row;
/**
* The workspace's row (`workspace_harness_settings`), when the call is
* in a workspace.
*/
workspace_row?: Row;
/**
* The install's row (`harness_settings`), when it has one.
*/
default_row?: Row;
};
/**
* The row a call runs on and where it came from. A bot's own pick wins
* over its workspace's for every run in that workspace, so setting one
* bot's model there never changes another's.
*/
export default function pickHarnessSettingRow<Row>({
bot_row,
workspace_row,
default_row,
}: Params<Row>): { row?: Row; source: HarnessSettingSource } {
if (bot_row) return { row: bot_row, source: "bot" };
if (workspace_row) return { row: workspace_row, source: "workspace" };
if (default_row) return { row: default_row, source: "default" };
return { row: undefined, source: "default" };
}
@@ -10,6 +10,7 @@ import parseInstallPackages from "@/src/utils/parse-install-packages";
import ensureBotSession from "../bot-sessions/ensure-bot-session";
import insertUserMessage from "../bots/insert-user-message";
import enqueueBotReply from "../bots-queue/enqueue-bot-reply";
import stripQuestionRefs from "@/src/utils/strip-question-refs";
type Params = {
job: Pick<BUN_SQLITE_COBBLE_BOTS_QUEUE, "id">;
@@ -63,7 +64,11 @@ export default async function settleInstallRequest({ job, text, failed }: Params
request_id: request.id,
status: (request.status || "failed") as InstallRequestStatus,
asked: installRequestAsked({ packages: parseInstallPackages({ text: request.packages }) }),
answer: request.answer,
/**
* A question the coordinator asked stays in its own
* conversation: a card here would answer into this one.
*/
answer: request.answer ? stripQuestionRefs({ text: request.answer }).text : request.answer,
}),
from_install_request_id: request.id,
});
@@ -0,0 +1,31 @@
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
import subtaskLinkProblem from "@/src/utils/task-subtasks/subtask-link-problem";
import grabTaskRow from "./grab-task-scope";
type Params = {
parent_task_id: number | string;
/**
* Who would have the subtask (a subtask always belongs to one bot).
*/
bot_id?: number | string | null;
/**
* The workspace it would be created in.
*/
workspace_id?: number | string | null;
};
/**
* The task a new subtask would belong to, checked: a workspace-wide task that
* isn't itself a subtask, open, in the subtask's workspace
* (`subtaskLinkProblem`). The caller checked who is asking reaches the
* parent. Returns the parent's row.
*/
export default async function assertSubtaskParent({ parent_task_id, bot_id, workspace_id }: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
const parent = await grabTaskRow({ task_id: parent_task_id });
const problem = subtaskLinkProblem({ parent, bot_id, workspace_id });
if (problem) throw new AppError(problem);
return parent;
}
@@ -7,6 +7,8 @@ import AppError from "@/src/utils/app-error";
import grabCrewRole from "../access/grab-crew-role";
import grabTask from "./grab-task";
import assertBotWorksThere from "./assert-bot-works-there";
import assertSubtaskParent from "./assert-subtask-parent";
import grabSubtaskCounts from "./grab-subtask-counts";
import taskScopeValues from "./task-scope-values";
type Params = {
@@ -24,6 +26,11 @@ type Params = {
* it (`taskScopeValues`). Only when asked for.
*/
workspace_wide?: boolean;
/**
* The workspace-wide task this one is a subtask of (`assertSubtaskParent`):
* one piece of that work, a bot's own task in the same workspace.
*/
parent_task_id?: number | string | null;
/**
* The bot creating it with its tool; none for a user's manual add.
*/
@@ -46,6 +53,7 @@ export default async function createTask({
description,
status,
workspace_wide,
parent_task_id,
created_by_bot_id,
}: Params): Promise<TaskDetail> {
const scope = taskScopeValues({ bot_id, workspace_id, workspace_wide });
@@ -59,6 +67,18 @@ export default async function createTask({
await assertBotWorksThere({ bot_id: scope.bot_id, workspace_id: scope.workspace_id });
}
if (parent_task_id) {
await assertSubtaskParent({ parent_task_id, bot_id: scope.bot_id, workspace_id: scope.workspace_id });
const { linked } = await grabSubtaskCounts({ task_id: parent_task_id });
if (linked >= AppData.TaskSubtaskMaxPerParent) {
throw new AppError(
`Task #${parent_task_id} already has ${AppData.TaskSubtaskMaxPerParent} subtasks: work on one of those, or unlink one first.`,
);
}
}
const count = Number(
(
await BunSQLite.sql<{ n: number }>({
@@ -80,6 +100,7 @@ export default async function createTask({
{
bot_id: scope.bot_id || undefined,
workspace_id: scope.workspace_id || undefined,
parent_task_id: parent_task_id ? Number(parent_task_id) : undefined,
title: title.trim().slice(0, AppData.TaskTitleMaxLength),
description: description || undefined,
status: status || "todo",
+39 -8
View File
@@ -1,8 +1,10 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_TASK_MEDIA } from "@/db/types/db";
import type { BUN_SQLITE_COBBLE_TASK_MEDIA, BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
import subtaskDeleteProblem from "@/src/utils/task-subtasks/subtask-delete-problem";
import grabCrewRole from "../access/grab-crew-role";
import deleteMedia from "../media/delete-media";
import grabSubtaskCounts from "./grab-subtask-counts";
import grabTaskRow from "./grab-task-scope";
type Params = {
@@ -16,9 +18,12 @@ type Params = {
};
/**
* Deletes a task with its notes and file links (cascades). The files
* themselves stay where they are: a `task_media` link is not the bytes'
* owner, so a bot file's folder keeps its file and only the link goes.
* Deletes a task with its notes and file links (cascades), and with its
* subtasks when they are all finished: refused while any subtask is still open
* (`subtaskDeleteProblem`), so a delete never throws away work someone is
* on. The files themselves stay where they are: a `task_media` link is not
* the bytes' owner, so a bot file's folder keeps its file and only the
* link goes.
*/
export default async function deleteTask({ user_id, task_id, deleted_by_bot_id }: Params) {
const task = await grabTaskRow({ task_id });
@@ -28,24 +33,50 @@ export default async function deleteTask({ user_id, task_id, deleted_by_bot_id }
throw new AppError(`Only an admin can delete a task.`);
}
const { open } = await grabSubtaskCounts({ task_id: task.id! });
const problem = subtaskDeleteProblem({ task, open_subtasks: open });
if (problem) throw new AppError(problem);
const children = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_TASKS>({
sql: `SELECT * FROM tasks WHERE parent_task_id = ?`,
values: [Number(task.id)],
})
).payload || [];
const child_ids = children.map((child) => Number(child.id));
/**
* Read before the delete: the links go with the task, and the media
* Read before the delete: the links go with the tasks, and the media
* rows a chat upload left are deleted with them (a bot file's bytes
* belong to its folder, not to the task).
*/
const links = (
await BunSQLite.sql<BUN_SQLITE_COBBLE_TASK_MEDIA>({
sql: `SELECT * FROM task_media WHERE task_id = ?`,
values: [Number(task_id)],
sql: `SELECT * FROM task_media WHERE task_id = ? OR task_id IN (${child_ids.map(() => "?").join(", ") || "NULL"})`,
values: [Number(task.id), ...child_ids],
})
).payload || [];
const res = await BunSQLite.sql({ sql: `DELETE FROM tasks WHERE id = ?`, values: [Number(task_id)] });
const res = await BunSQLite.sql({ sql: `DELETE FROM tasks WHERE id = ?`, values: [Number(task.id)] });
if (!res.success) {
throw new AppError(`Couldn't delete the task: ${res.msg || res.error}`);
}
/**
* The subtasks go explicitly, children first: foreign keys are off outside
* the server process, so nothing cascades on its own.
*/
if (child_ids.length) {
const marks = child_ids.map(() => "?").join(", ");
await BunSQLite.sql({ sql: `DELETE FROM task_notes WHERE task_id IN (${marks})`, values: child_ids });
await BunSQLite.sql({ sql: `DELETE FROM task_media WHERE task_id IN (${marks})`, values: child_ids });
await BunSQLite.sql({ sql: `DELETE FROM tasks WHERE id IN (${marks})`, values: child_ids });
}
const uploads = links.filter((link) => !link.bot_file_id).map((link) => Number(link.media_id));
if (uploads.length) {
@@ -0,0 +1,50 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
import addTaskNote from "./add-task-note";
import grabTaskRow from "./grab-task-scope";
type Params = {
task_id: number | string;
/**
* The bot unlinking it with its tool; none when a crew manager does.
*/
by_bot_id?: number | string | null;
/**
* Who does, by name, for the log.
*/
by_name: string;
};
/**
* Takes a subtask out of its workspace-wide task, leaving an ordinary task of
* its bot in that workspace, with a note saying it was unlinked. The only
* way a subtask stops being one: a task that has subtasks can't be moved until
* they are, and a subtask is never moved itself. The caller checked who is
* asking may. Returns the row as it is now.
*/
export default async function detachSubtask({ task_id, by_bot_id, by_name }: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
const task = await grabTaskRow({ task_id });
if (!task.parent_task_id) {
throw new AppError(`Task #${task.id} isn't a subtask of another task.`);
}
const res = await BunSQLite.sql({
sql: `UPDATE tasks SET parent_task_id = NULL, updated_at = ? WHERE id = ?`,
values: [Date.now(), Number(task.id)],
});
if (!res.success) {
throw new AppError(`Couldn't unlink the task: ${res.msg || res.error}`);
}
await addTaskNote({
task_id: task.id!,
text: `${by_name} unlinked this from task #${task.parent_task_id}: it's a task of its own now.`,
author: by_bot_id ? "bot" : "user",
bot_id: by_bot_id || null,
});
return await grabTaskRow({ task_id: task.id! });
}
@@ -36,4 +36,16 @@ describe("findDuplicateTask", () => {
expect(findDuplicateTask({ tasks, title: "Check the invoices", bot_id: 2 })).toBeNull();
expect(findDuplicateTask({ tasks, title: "Check the invoices", workspace_id: 9, bot_id: 3 })?.id).toBe(7);
});
test("two parts of different parents may share a title, the same parent's may not", () => {
const tasks = [task({ id: 8, bot_id: 2, workspace_id: 9, parent_task_id: 12, title: "Write the intro" })];
expect(
findDuplicateTask({ tasks, title: "Write the intro", workspace_id: 9, bot_id: 2, parent_task_id: 12 })?.id,
).toBe(8);
expect(
findDuplicateTask({ tasks, title: "Write the intro", workspace_id: 9, bot_id: 2, parent_task_id: 13 }),
).toBeNull();
expect(findDuplicateTask({ tasks, title: "Write the intro", workspace_id: 9, bot_id: 2 })).toBeNull();
});
});
@@ -8,6 +8,11 @@ type Params = {
*/
bot_id?: number | null;
workspace_id?: number | null;
/**
* The subtask's parent: two subtasks of different parents may share a title
* ("Write the intro" under two releases), the same parent's may not.
*/
parent_task_id?: number | null;
};
/**
@@ -15,7 +20,7 @@ type Params = {
* `ActionCheckNote` gets real behaviour: a bot updates the existing task
* instead of adding a second one for the same work.
*/
export default function findDuplicateTask({ tasks, title, bot_id, workspace_id }: Params) {
export default function findDuplicateTask({ tasks, title, bot_id, workspace_id, parent_task_id }: Params) {
const wanted = title.trim().toLowerCase();
return (
@@ -27,6 +32,8 @@ export default function findDuplicateTask({ tasks, title, bot_id, workspace_id }
return false;
}
if (Number(task.parent_task_id || 0) != Number(parent_task_id || 0)) return false;
return (task.title || "").trim().toLowerCase() == wanted;
}) || null
);
@@ -0,0 +1,24 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { OpenTaskStatuses } from "@/src/dict/task-dict";
type Params = {
task_id: number | string;
};
/**
* How many tasks are subtasks of this one, and how many of those still need
* work: what the move and delete checks read (`subtaskMoveProblem`,
* `subtaskDeleteProblem`) and what a list shows as its progress.
*/
export default async function grabSubtaskCounts({ task_id }: Params): Promise<{ linked: number; open: number }> {
const res = await BunSQLite.sql<{ linked: number; open: number }>({
sql: `SELECT COUNT(*) AS linked,
COALESCE(SUM(CASE WHEN status IN (${OpenTaskStatuses.map(() => "?").join(", ")}) THEN 1 ELSE 0 END), 0) AS open
FROM tasks WHERE parent_task_id = ?`,
values: [...OpenTaskStatuses, Number(task_id)],
});
const row = res.payload?.[0];
return { linked: Number(row?.linked || 0), open: Number(row?.open || 0) };
}
@@ -0,0 +1,26 @@
import type { TaskWithNames } from "@/src/types";
import grabTasks from "./grab-tasks";
type Params = {
/**
* The user asking: they must reach the workspace.
*/
user_id: number | string;
/**
* The task that would become a subtask: its own workspace's wide tasks are
* the only ones it can join.
*/
task: { id?: number | string | null; workspace_id?: number | string | null };
};
/**
* The workspace-wide tasks a bot's task in that workspace can be attached
* to: the open ones, the user's to pick from when the picker opens.
*/
export default async function grabSubtaskParents({ user_id, task }: Params): Promise<TaskWithNames[]> {
if (!task.workspace_id) return [];
const tasks = await grabTasks({ user_id, only_workspace_id: task.workspace_id, open_only: true });
return tasks.filter((candidate) => !candidate.bot_id && Number(candidate.id) != Number(task.id || 0));
}
+16 -5
View File
@@ -1,11 +1,13 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { TaskDetail } from "@/src/types";
import { OpenTaskStatuses } from "@/src/dict/task-dict";
import AppError from "@/src/utils/app-error";
import botFaceSql from "@/src/utils/bot-face-sql";
import taskScopesSql from "@/src/utils/task-access/task-scopes-sql";
import grabCrewRole from "../access/grab-crew-role";
import grabTaskMedia from "./grab-task-media";
import grabTaskNotes from "./grab-task-notes";
import grabTasks from "./grab-tasks";
type Params = {
/**
@@ -17,7 +19,8 @@ type Params = {
/**
* One task with its notes (oldest first, each with the bot that wrote it),
* its files and who added it, only if the user
* its files, who added it and its subtasks when it is workspace-wide (each as a
* list shows it, only the ones the user reaches), only if the user
* reaches the bot or workspace it belongs to (`taskScopesSql`, the same
* condition the lists use).
*/
@@ -27,17 +30,21 @@ export default async function grabTask({ user_id, task_id }: Params): Promise<Ta
const row_res = await BunSQLite.sql<TaskDetail>({
sql: `SELECT t.*, b.name AS bot_name, b.kind AS bot_kind, b.hue AS bot_hue, b.color AS bot_color, b.stone AS bot_stone,
b.image_media_id AS bot_image_media_id, ${face.sql}, w.name AS workspace_name,
b.image_media_id AS bot_image_media_id, ${face.sql}, w.name AS workspace_name, w.image_media_id AS workspace_image_media_id,
p.title AS parent_title, p.status AS parent_status,
(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id) AS subtask_count,
(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id AND st.status IN (${OpenTaskStatuses.map(() => "?").join(", ")})) AS subtask_open_count,
cb.name AS created_by_bot_name,
NULLIF(TRIM(COALESCE(cu.first_name, '') || ' ' || COALESCE(cu.last_name, '')), '') AS created_by_user_name
FROM tasks t
LEFT JOIN bots b ON b.id = t.bot_id
LEFT JOIN workspaces w ON w.id = t.workspace_id
LEFT JOIN tasks p ON p.id = t.parent_task_id
LEFT JOIN bots cb ON cb.id = t.created_by_bot_id
LEFT JOIN users cu ON cu.id = t.created_by_user_id
WHERE t.id = ? AND ${access.sql}
LIMIT 1`,
values: [...face.values, Number(task_id), ...access.values],
values: [...face.values, ...OpenTaskStatuses, Number(task_id), ...access.values],
});
const row = row_res.payload?.[0];
@@ -46,7 +53,11 @@ export default async function grabTask({ user_id, task_id }: Params): Promise<Ta
throw new AppError(`Task not found.`);
}
const [notes, files] = await Promise.all([grabTaskNotes({ task_id }), grabTaskMedia({ task_id })]);
const [notes, files, subtasks] = await Promise.all([
grabTaskNotes({ task_id }),
grabTaskMedia({ task_id }),
grabTasks({ user_id, only_parent_task_id: Number(task_id) }),
]);
return { ...row, notes, files };
return { ...row, notes, files, subtasks };
}
+16 -2
View File
@@ -35,6 +35,10 @@ type Params = {
* Only one workspace's tasks.
*/
only_workspace_id?: number | string | null;
/**
* Only the tasks that are subtasks of this one, for a parent's detail.
*/
only_parent_task_id?: number | string | null;
/**
* Only bots' own lists, outside any workspace.
*/
@@ -63,6 +67,7 @@ export default async function grabTasks({
only_bot_id,
with_workspace_wide,
only_workspace_id,
only_parent_task_id,
own_list,
statuses,
open_only,
@@ -95,6 +100,11 @@ export default async function grabTasks({
values.push(Number(only_workspace_id));
}
if (only_parent_task_id) {
where.push(`t.parent_task_id = ?`);
values.push(Number(only_parent_task_id));
}
const wanted = open_only ? [...OpenTaskStatuses] : statuses?.length ? statuses : null;
if (wanted) {
@@ -106,7 +116,10 @@ export default async function grabTasks({
const res = await BunSQLite.sql<TaskWithNames>({
sql: `SELECT t.*, b.name AS bot_name, b.kind AS bot_kind, b.hue AS bot_hue, b.color AS bot_color, b.stone AS bot_stone,
b.image_media_id AS bot_image_media_id, ${face.sql}, w.name AS workspace_name,
b.image_media_id AS bot_image_media_id, ${face.sql}, w.name AS workspace_name, w.image_media_id AS workspace_image_media_id,
p.title AS parent_title,
(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id) AS subtask_count,
(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id AND st.status IN (${OpenTaskStatuses.map(() => "?").join(", ")})) AS subtask_open_count,
(SELECT n.text FROM task_notes n WHERE n.task_id = t.id ORDER BY n.id DESC LIMIT 1) AS latest_note,
(SELECT CASE WHEN n.author = 'user' THEN NULL ELSE COALESCE(nb.name, 'Bot ' || n.bot_id) END
FROM task_notes n LEFT JOIN bots nb ON nb.id = n.bot_id
@@ -115,11 +128,12 @@ export default async function grabTasks({
FROM tasks t
LEFT JOIN bots b ON b.id = t.bot_id
LEFT JOIN workspaces w ON w.id = t.workspace_id
LEFT JOIN tasks p ON p.id = t.parent_task_id
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
ORDER BY CASE t.status WHEN 'blocked' THEN 0 WHEN 'doing' THEN 1 WHEN 'todo' THEN 2 WHEN 'done' THEN 3 ELSE 4 END,
t.updated_at DESC, t.id DESC
${limit ? `LIMIT ${Number(limit)}` : ""}`,
values: [...face.values, ...values],
values: [...face.values, ...OpenTaskStatuses, ...values],
});
return res.payload || [];
@@ -0,0 +1,92 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import { AppData } from "@/src/data/app-data";
import type { TaskDetail } from "@/src/types";
import AppError from "@/src/utils/app-error";
import subtaskAttachProblem from "@/src/utils/task-subtasks/subtask-attach-problem";
import addTaskNote from "./add-task-note";
import grabSubtaskCounts from "./grab-subtask-counts";
import grabTask from "./grab-task";
import grabTaskRow from "./grab-task-scope";
type Params = {
/**
* The user attaching it; they must reach the task.
*/
user_id: number | string;
task_id: number | string;
/**
* The workspace-wide task it becomes a subtask of.
*/
parent_task_id: number | string;
/**
* The bot's run doing it; none for the user. Either way, the caller
* checked the run or user reaches the task.
*/
by_bot_id?: number | string | null;
/**
* Who did it, for the two logs.
*/
by_name: string;
};
/**
* Attaches a bot's open task in a workspace to a workspace-wide task there:
* the subtask of it that bot took on (`subtaskAttachProblem` says when it
* can't). Both logs say who joined which, since the parent's own log is
* where a crew manager sees how the split work is going.
*/
export default async function linkSubtask({
user_id,
task_id,
parent_task_id,
by_bot_id,
by_name,
}: Params): Promise<TaskDetail> {
const task = await grabTaskRow({ task_id });
/**
* Read the same way: a missing parent throws "Task not found" before
* anything is written.
*/
const parent = await grabTaskRow({ task_id: parent_task_id });
const [{ linked }, own] = await Promise.all([
grabSubtaskCounts({ task_id: parent_task_id }),
grabSubtaskCounts({ task_id }),
]);
const problem = subtaskAttachProblem({ task, parent, task_subtasks: own.linked });
if (problem) throw new AppError(problem);
if (linked >= AppData.TaskSubtaskMaxPerParent) {
throw new AppError(
`Task #${parent.id} already has ${AppData.TaskSubtaskMaxPerParent} subtasks: work on one of those, or unlink one first.`,
);
}
const res = await BunSQLite.sql({
sql: `UPDATE tasks SET parent_task_id = ?, updated_at = ? WHERE id = ?`,
values: [Number(parent.id), Date.now(), Number(task.id)],
});
if (!res.success) {
throw new AppError(`Couldn't link the task: ${res.msg || res.error}`);
}
const author = by_bot_id ? "bot" : "user";
const parent_label = `task #${parent.id}${parent.title ? ` "${parent.title}"` : ""}`;
await addTaskNote({
task_id: Number(task.id),
text: `${by_name} made this a subtask of ${parent_label}.`,
author,
bot_id: by_bot_id ? Number(by_bot_id) : null,
});
await addTaskNote({
task_id: Number(parent.id),
text: `${by_name} took on task #${task.id}${task.title ? ` "${task.title}"` : ""} as a subtask.`,
author,
bot_id: by_bot_id ? Number(by_bot_id) : null,
});
return await grabTask({ user_id, task_id });
}
+10 -1
View File
@@ -1,8 +1,10 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
import subtaskMoveProblem from "@/src/utils/task-subtasks/subtask-move-problem";
import assertBotWorksThere from "./assert-bot-works-there";
import findDuplicateTask from "./find-duplicate-task";
import grabSubtaskCounts from "./grab-subtask-counts";
import grabTaskRow from "./grab-task-scope";
import taskScopeValues from "./task-scope-values";
@@ -20,13 +22,20 @@ type Params = {
/**
* Moves a task to another list or bot, with its notes and files. Refused
* when it changes list and the destination already has an open task with
* that title, so a hand-over never leaves two of the same. The caller checked who is
* that title, so a hand-over never leaves two of the same, and when it's a
* subtask of another task or has subtasks of its own (`subtaskMoveProblem`): only
* a task that is neither moves. The caller checked who is
* asking reaches both. Returns the row as it is now.
*/
export default async function moveTask({ task_id, bot_id, workspace_id, workspace_wide }: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
const task = await grabTaskRow({ task_id });
const place = taskScopeValues({ bot_id, workspace_id, workspace_wide });
const { linked } = await grabSubtaskCounts({ task_id: task.id! });
const problem = subtaskMoveProblem({ task, linked_subtasks: linked });
if (problem) throw new AppError(problem);
if (Number(task.bot_id || 0) == Number(place.bot_id || 0) && Number(task.workspace_id || 0) == Number(place.workspace_id || 0)) {
return task;
}
@@ -82,6 +82,14 @@ export default async function updateTask({
return await grabTask({ user_id, task_id });
}
/**
* `tasks` list rows by `updated_at` (`grabTasks`), so a status change
* that leaves it alone never rises; the move and hand-over helpers set
* it themselves.
*/
fields.push(`updated_at = ?`);
values.push(Date.now());
const res = await BunSQLite.sql({
sql: `UPDATE tasks SET ${fields.join(", ")} WHERE id = ?`,
values: [...values, Number(task_id)],
+1 -1
View File
@@ -18,7 +18,7 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
};
+1 -1
View File
@@ -20,7 +20,7 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
};
+1 -1
View File
@@ -18,7 +18,7 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
};
+1 -1
View File
@@ -22,7 +22,7 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
};
+1 -1
View File
@@ -24,7 +24,7 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
};
+1 -1
View File
@@ -20,7 +20,7 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
};
@@ -25,7 +25,7 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
};
+1 -1
View File
@@ -49,7 +49,7 @@ export type GenerateTextParams = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
};
+1 -1
View File
@@ -15,7 +15,7 @@ type Params = {
/**
* A model's generation settings for one call: what is saved in the
* harness's setting (the workspace's, the bot's, else the default), else
* harness's setting (the bot's, else its workspace's, else the default), else
* `HarnessParameterDefaults` so a fresh install is ready to go. Keyed by
* the field sent on the wire, keeping only what the model says it takes
* (a default only where the model explicitly advertises it). `source`
@@ -38,7 +38,7 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
read_image?: typeof readImage;
+56 -4
View File
@@ -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, answerNotSentNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import { alreadyRanToolNote, answerNotSentNote, contextTrimmedNote, DroppedToolImageNote, oversizedRequestNote, repeatedAnswerNote, SupersededSnapshotNote, ToolImagesNote } from "@/src/data/harness-prompts";
import HarnessError from "../harness-error";
import type { HarnessCandidate, HarnessTool } from "../types";
import type { HarnessTrace } from "../trace/types";
@@ -700,7 +700,7 @@ describe("runTextLoop", () => {
expect(last.indexOf("Late correction.")).toBeLessThan(last.indexOf("You've used every step"));
});
test("writes an answer the review faults again, once, with its note and the tool calls", async () => {
test("writes an answer the review faults again, with its note and the tool calls", async () => {
const { generate, seen } = scripted([
{ text: null, tool_calls: [{ id: "c1", name: "remember", arguments: '{"note":"x"}' }] },
{ text: "I'm scanning now. Scan done: 5 contests." },
@@ -717,18 +717,70 @@ describe("runTextLoop", () => {
resolveCandidates,
review: async ({ text, tool_uses }) => {
reviewed.push({ text, tools: tool_uses.map((use) => use.name) });
return "Not sent: nothing scanned.";
return text.includes("Scan done") ? "Not sent: nothing scanned." : null;
},
});
expect(result.text).toBe("I haven't scanned yet.");
expect(reviewed).toEqual([{ text: "I'm scanning now. Scan done: 5 contests.", tools: ["remember"] }]);
expect(reviewed).toEqual([
{ text: "I'm scanning now. Scan done: 5 contests.", tools: ["remember"] },
{ text: "I haven't scanned yet.", tools: ["remember"] },
]);
expect(seen[2]!.messages.slice(-2)).toEqual([
{ role: "assistant", content: "I'm scanning now. Scan done: 5 contests." },
{ role: "user", content: "Not sent: nothing scanned." },
]);
});
test("stops without an answer once every rewrite is faulted, and says why", async () => {
const { generate } = scripted([
{ text: "I'm resuming the export now." },
{ text: "I'm still resuming the export." },
{ text: "Resuming." },
{ text: "never reached" },
]);
let reviews = 0;
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Export it." }],
generate,
resolveCandidates,
review: async () => {
reviews++;
return "Not sent: nothing is running.";
},
});
expect(reviews).toBe(AppData.HarnessReviewRewrites + 1);
expect(result.text).toBe("");
expect(result.review_note).toBe("Not sent: nothing is running.");
});
test("tells a model that wrote the same message back it did, rather than spending a rewrite on a copy", async () => {
const { generate, seen } = scripted([
{ text: "I'm resuming now and will report back." },
{ text: "I'm resuming now and will report back." },
{ text: "Nothing is running." },
{ text: "never reached" },
]);
const result = await runTextLoop({
system: "s",
messages: [{ role: "user", content: "Export it." }],
generate,
resolveCandidates,
review: async ({ text }) => (text === "Nothing is running." ? null : "Not sent: nothing is running."),
});
expect(result.text).toBe("Nothing is running.");
expect(seen[1]!.messages.at(-1)!.content).toBe("Not sent: nothing is running.");
expect(seen[2]!.messages.at(-1)!.content).toBe(
`Not sent: nothing is running.\n\n${repeatedAnswerNote}`,
);
expect(seen.length).toBe(3);
});
test("lets the answer through when the review passes it or throws", async () => {
for (const review of [async () => null, async () => Promise.reject(new Error("db down"))]) {
const { generate, seen } = scripted([{ text: "Fine." }]);
+80 -23
View File
@@ -6,6 +6,7 @@ import {
contextTrimmedNote,
failedToolCallNote,
oversizedRequestNote,
repeatedAnswerNote,
tokensLowNote,
} from "@/src/data/harness-prompts";
import { isUnlimitedLimit, type RunLimit, UnlimitedLimit } from "@/src/utils/run-limit";
@@ -113,9 +114,10 @@ type Params = {
wrap_up_note?: () => Promise<string> | string;
/**
* Checks an answer before it's returned, with the tool calls the run
* made. A note sends the answer back to be written again with it, once
* per run; null lets it through. Not on the wrap up, and a check that
* throws lets the answer through.
* made. A note sends the answer back to be written again with it, up to
* `AppData.HarnessReviewRewrites` times; null lets it through. Past that
* the answer is never sent and the run returns its note (`review_note`).
* Not on the wrap up, and a check that throws lets the answer through.
*/
review?: (params: { text: string; tool_uses: HarnessToolUse[] }) => Promise<string | null | undefined>;
/**
@@ -123,7 +125,7 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
generate?: typeof generateText;
@@ -146,6 +148,13 @@ export type TextLoopResult = {
* Every tool call the run made, in order, and whether it went through.
*/
tool_uses: HarnessToolUse[];
/**
* Why there is no answer: `review` faulted every one the run wrote, up to
* `AppData.HarnessReviewRewrites`. `text` is empty and must not be shown;
* the caller fails the job with this instead of delivering an answer the
* app knows is wrong.
*/
review_note?: string;
};
/**
@@ -273,7 +282,9 @@ Don't repeat tool calls you have already made.`;
* then one with none. With neither set (unlimited), the run ends when the
* model answers without calling a tool, or when its job's deadline or its
* abort signal ends it. An answer `review` finds fault
* with is written again once.
* with is written again, a bounded number of times
* (`AppData.HarnessReviewRewrites`); one it still finds fault with is never
* sent, and the run returns why instead (`review_note`).
*
* Every turn resends everything, so the run keeps it small: only the
* newest page snapshot of each browser stays (`supersedeToolOutputs`),
@@ -387,7 +398,12 @@ export default async function runTextLoop({
const warn_at = isUnlimitedLimit(max_steps) ? 0 : stepsLowWarningLeft({ max_steps });
let prefer_key: string | undefined;
let reviewed = false;
/**
* How many answers the review has sent back, and the last one it faulted,
* whitespace collapsed, to see a model that wrote the same message back.
*/
let review_rewrites = 0;
let faulted_answer: string | null = null;
/**
* A run that wrote a message and then called a tool has been told, once,
* that the message never went out (`answerNotSentNote`).
@@ -454,6 +470,37 @@ export default async function runTextLoop({
}
};
/**
* The answer checked against the app's own record before it goes out:
* files, tasks and settings it names, and work it says is under way. A
* note comes back and the answer is written again with it, up to
* `AppData.HarnessReviewRewrites`; a model that writes the same message
* back is told it did (`repeatedAnswerNote`) rather than spending its
* next rewrite on a copy. Past that the run stops: an answer the app
* knows is wrong is never sent (`review_note`).
*/
const checkAnswer = async ({ text, index }: { text: string; index: number }) => {
if (!review) return { verdict: "passed" as const };
const note = await review({ text, tool_uses }).catch(() => null);
if (!note) return { verdict: "passed" as const };
await traced({ kind: "event", index, name: "review", text: note });
const written = text.replace(/\s+/g, " ").trim();
const repeated = written !== "" && written === faulted_answer;
faulted_answer = written;
review_rewrites += 1;
if (review_rewrites > AppData.HarnessReviewRewrites) return { verdict: "refused" as const, note };
pushUserTurn({ transcript, content: repeated ? `${note}\n\n${repeatedAnswerNote}` : note });
return { verdict: "sent_back" as const };
};
for (let index = 0; index <= step_ceiling + 1 + WrapUpSavingTurns; index++) {
if (signal.aborted) {
throw new HarnessError({ message: `Cancelled.`, code: "aborted" });
@@ -642,16 +689,22 @@ export default async function runTextLoop({
continue;
}
if (!tool_calls.length && !wrap_up && review && !reviewed) {
reviewed = true;
if (!tool_calls.length && !wrap_up) {
const check = await checkAnswer({ text: answer.text || "", index });
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;
if (check.verdict === "refused") {
return {
text: "",
review_note: check.note,
messages: transcript,
steps: index + 1,
candidate: answer.candidate,
usage,
tool_uses,
};
}
if (check.verdict === "sent_back") continue;
}
if (!tool_calls.length) {
@@ -764,18 +817,22 @@ export default async function runTextLoop({
* back and the answer is written again (the card stays on the
* reply, its ref is already recorded).
*/
if (review && !reviewed) {
reviewed = true;
const check = await checkAnswer({ text: answer.text, index });
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;
}
if (check.verdict === "refused") {
return {
text: "",
review_note: check.note,
messages: transcript,
steps: index + 1,
candidate: answer.candidate,
usage,
tool_uses,
};
}
if (check.verdict === "sent_back") continue;
return {
text: answer.text,
messages: transcript,
+1 -1
View File
@@ -66,7 +66,7 @@ export default function handOverTaskTool({ user_id, bot, session_id, powers, wor
return {
name: "hand_over_task",
description: `Hand over a task on your own list to another bot, when the user asked for that task to go to them. Pass its task_id (list_tasks) and the bot: the task moves to their list as to do, and their result is reported back here. Handing it over never starts it: pass start: true only when the user asked for the work to begin now. When they asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it), and hand over only once they've answered: a task that has left your list can't be started by you any more. Only a task of your own, and only an open one. To ask a bot something without giving it a task, use ask_crew; to have work made for another bot, ask the user. Crew you can hand to: ${crew || "none"}.`,
description: `Hand over a task on your own list to another bot, when the user asked for that task to go to them. Pass its task_id (list_tasks) and the bot: the task moves to their list as to do, and their result is reported back here. Handing it over never starts it: pass start: true only when the user asked for the work to begin now. When they asked for the move but not for it to start, ask first with ask_user (one card, every task they named: hand over and start, hand over to wait, leave it), and hand over only once they've answered: a task that has left your list can't be started by you any more. Only a task of your own, and only an open one. To ask a bot something without giving it a task, use ask_bot; to have work made for another bot, ask the user. Crew you can hand to: ${crew || "none"}.`,
schema: z.object({
task_id: z.number().int().describe("An open task on your own list (list_tasks)"),
bot_id: z.number().int(),
@@ -0,0 +1,45 @@
import { z } from "zod";
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
import setBotPlanStatus from "@/src/functions/backend/db/bot-plans/set-bot-plan-status";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import AppError from "@/src/utils/app-error";
import type { HarnessTool } from "../../../types";
type Params = {
user_id: number | string;
bot_id: number | string;
session_id: number | string;
};
type Args = {
plan_id: number;
reason: string;
};
/**
* The user dropped the plan (they said so, or the work it was for is gone),
* so the bot ends it rather than leaving a card that will never move. Its
* steps stop there: nothing more is queued for it.
*/
export default function cancelPlanTool({ user_id, bot_id, session_id }: Params): HarnessTool<Args> {
return {
name: "cancel_plan",
description: `End a plan in this conversation, once the user has said the work it was for is off or they want it dropped. Never to make a plan that is going badly look finished: a plan you can't carry on with is theirs to end too, so ask them. Say in a line that it's cancelled, and why.`,
schema: z.object({
plan_id: z.number().int().positive().describe(`The plan's id, as your prompt gives it`),
reason: z.string().trim().min(1).max(300).describe(`Why it's off, in one line`),
}),
run: async ({ args }) => {
const row = await grabBotPlan({ plan_id: args.plan_id });
if (Number(row.session_id) != Number(session_id)) {
throw new AppError(`Plan #${args.plan_id} belongs to another conversation: cancel that conversation's plan.`);
}
await setBotPlanStatus({ plan_id: args.plan_id, user_id, status: "cancelled" });
await pushBotPlan({ plan_id: args.plan_id, session_id, bot_id });
return `Plan #${args.plan_id} is cancelled (${args.reason}) and its card says so. Nothing more runs for it. Say in a line that it's off and what stands done, then answer normally.`;
},
};
}
@@ -0,0 +1,80 @@
import { z } from "zod";
import { AppData } from "@/src/data/app-data";
import completeBotPlanStep from "@/src/functions/backend/db/bot-plans/complete-bot-plan-step";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import type { HarnessTool } from "../../../types";
type Params = {
bot_id: number | string;
session_id: number | string;
/**
* The step is finished inside a run that works the whole plan itself (a
* routine), so this isn't the reply that ends it: the run carries on
* into the next step, and one run can finish more than one.
*/
in_run?: boolean;
};
type Args = {
plan_id: number;
summary: string;
};
/**
* The plan's current step is finished: the card checks it off with what it
* produced, and the app wakes the bot for the next one after this reply.
* A step is only ever finished by a run that did the work, one at a time.
*/
export default function completePlanStepTool({ bot_id, session_id, in_run }: Params): HarnessTool<Args> {
let completed = false;
return {
name: "complete_plan_step",
description: in_run
? `Finish one step of the plan, once you have actually done it, before you start the next. Give one or two lines on what it produced (the number, the path, the link). You work this plan yourself here, so call it after each step and keep going.`
: `Finish the plan's current step, once you have actually done it. Give one or two lines on what it produced (the number, the path, the link). Call it before you write your report: the report is this reply's last message. One step per reply. Never call it for a step you didn't do, and never for one after the current step.`,
schema: z.object({
plan_id: z.number().int().positive().describe(`The plan's id, as your prompt gives it`),
summary: z
.string()
.trim()
.min(1, `Say what the step produced`)
.max(
AppData.BotPlanStepNoteMaxChars,
`Keep it under ${AppData.BotPlanStepNoteMaxChars} characters`,
)
.describe(`What the step produced, in a line or two`),
}),
run: async ({ args }) => {
if (completed && !in_run) {
throw new Error(`You already finished a step of this plan in this reply. One step per reply.`);
}
const done = await completeBotPlanStep({
plan_id: args.plan_id,
session_id,
summary: args.summary,
});
completed = true;
/**
* The card is already in the thread above, from the message that
* wrote or changed the plan: this reply needs no copy of it, and
* the push keeps the one that's there current.
*/
await pushBotPlan({ plan_id: done.plan_id, session_id, bot_id });
if (done.done) {
return `Step ${done.index + 1} is done and it was the last one: the plan is finished on its card. Write your report now, two or three sentences on what the plan produced. If this plan will come back (the same work, the next project or the next month), save its steps now with update_memory as a short checklist, and say in a line that you kept them.`;
}
const next = done.steps[done.next_step ?? 0];
if (in_run) {
return `Step ${done.index + 1} is done: the card shows it. Carry on with step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}. Save your report for the end, when every step is done.`;
}
return `Step ${done.index + 1} is done: the card shows it. The next step starts on its own after this reply (step ${(done.next_step ?? 0) + 1}: ${next?.text || ""}), so don't start it now. Write your report: two or three sentences on what this step produced.`;
},
};
}
@@ -0,0 +1,76 @@
import { z } from "zod";
import createBotPlan from "@/src/functions/backend/db/bot-plans/create-bot-plan";
import setBotPlanStatus from "@/src/functions/backend/db/bot-plans/set-bot-plan-status";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import { BotPlanGoalSchema, BotPlanStepTextsSchema, BotPlanTitleSchema } from "@/src/schemas/bot-plan-schema";
import botPlanRef from "@/src/utils/bot-plan-ref";
import type { HarnessTool } from "../../../types";
type Params = {
user_id: number | string;
bot_id: number | string;
session_id: number | string;
workspace_id?: number | string | null;
/**
* A scheduled run, which nobody watches: the plan is approved at once,
* since there is no card for someone to approve it on.
*/
approve?: boolean;
/**
* Called with the plan's ref, so the message carries its card. `waiting`
* says nobody approved it yet: the user is needed for it to go on.
*/
onPlan: (params: { ref: string; waiting?: boolean }) => void;
};
type Args = {
title: string;
goal?: string;
steps: z.infer<typeof BotPlanStepTextsSchema>;
};
/**
* The bot broke work into a plan. In a chat it waits on its card for the
* user to approve (or change) it, and the app then wakes the bot one step at
* a time. In a scheduled run nobody is there to approve anything, so the
* plan starts itself and the run works through it.
*/
export default function createPlanTool({ user_id, bot_id, session_id, workspace_id, approve, onPlan }: Params): HarnessTool<Args> {
return {
name: "create_plan",
description: approve
? `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. Nobody is watching this run, so it's approved at once and you work it here: call complete_plan_step after each step.`
: `Write the plan for work that is several steps, before starting it: the goal that says what finished looks like, and 3 to 6 steps in the order you'd do them, one line each, each naming what it produces. It goes to the user as a card in this conversation, and nothing of it runs until they approve it (they can change the steps first). Write the plan instead of answering with a long list of everything you're about to do. Only when a plan is already open in this conversation, work it instead.`,
schema: z.object({
title: BotPlanTitleSchema.describe(`A short name for the work, e.g. "Audit the pricing pages"`),
goal: BotPlanGoalSchema.describe(`What the plan is for and what "done" means, in one sentence`),
steps: BotPlanStepTextsSchema.describe(`The steps in the order they're worked, each one line`),
}),
run: async ({ args }) => {
const plan_id = await createBotPlan({
user_id,
bot_id,
session_id,
workspace_id,
title: args.title,
goal: args.goal,
steps: args.steps,
});
if (approve) {
await setBotPlanStatus({ plan_id, user_id, status: "active" });
}
onPlan({ ref: botPlanRef({ plan_id }), waiting: !approve });
await pushBotPlan({ plan_id, session_id, bot_id });
const count = args.steps.length;
if (approve) {
return `Plan #${plan_id} is written (${count} step${count == 1 ? "" : "s"}), and it's approved already because this run isn't watched. Work its steps in this run, calling complete_plan_step after each with what it produced.`;
}
return `Plan #${plan_id} is on its card in the conversation (${count} step${count == 1 ? "" : "s"}) and nothing of it runs until the user approves it. Say in one sentence that you wrote it and that they can change it before it starts; don't repeat the steps and don't work any of them now. When they approve it, you'll be woken for the first step.`;
},
};
}
@@ -0,0 +1,42 @@
import { describe, expect, test } from "bun:test";
import grabBotPlanTools from "./grab-bot-plan-tools";
/**
* A run working a plan's step may only work it: writing another plan, or
* cancelling the one it was woken for, is the user's call on the card. A
* scheduled run has no card to approve anything on, so its plan starts
* itself and nothing is left for the bot to cancel.
*/
const names = (tools: { name: string }[]) => tools.map((tool) => tool.name);
const build = (overrides: Parameters<typeof grabBotPlanTools>[0] | {} = {}) =>
grabBotPlanTools({
user_id: 1,
bot_id: 2,
session_id: 3,
workspace_id: null,
onPlan: () => {},
...overrides,
});
describe("grabBotPlanTools", () => {
test("a chat reply can write a plan, change it, end it and finish its steps", () => {
expect(names(build())).toEqual(["create_plan", "cancel_plan", "update_plan", "complete_plan_step"]);
});
test("a run working a step can only change the plan and finish its step", () => {
expect(names(build({ on_step: true }))).toEqual(["update_plan", "complete_plan_step"]);
});
test("a scheduled run writes a plan that's already approved, and can't cancel it", () => {
expect(names(build({ approve: true }))).toEqual(["create_plan", "update_plan", "complete_plan_step"]);
});
test("a plan the app writes shows its card on the message", () => {
const refs: string[] = [];
build({ onPlan: ({ ref }) => refs.push(ref) });
expect(refs).toEqual([]);
});
});
@@ -0,0 +1,54 @@
import type { HarnessTool } from "../../../types";
import cancelPlanTool from "./cancel-plan-tool";
import completePlanStepTool from "./complete-plan-step-tool";
import createPlanTool from "./create-plan-tool";
import updatePlanTool from "./update-plan-tool";
type Params = {
user_id: number | string;
bot_id: number | string;
session_id: number | string;
workspace_id?: number | string | null;
/**
* The run is a plan's own step: it has a plan to finish, and no reason
* to write one or end one.
*/
on_step?: boolean;
/**
* A scheduled run, which nobody watches: a plan it writes is approved
* at once and worked through in the run (`ScheduledPlanNote`).
*/
approve?: boolean;
/**
* Called with each plan's ref, so the message carries its card.
*/
onPlan: (params: { ref: string; waiting?: boolean }) => void;
};
/**
* The tools a bot plans with: `create_plan` when work is several steps,
* `update_plan` when what it found makes the rest wrong, and
* `complete_plan_step` to finish the step it worked. A chat reply's plan
* waits on its card for the user; a scheduled run's is approved at once,
* since nobody is there to approve it.
*
* A run that is itself working a plan gets neither `create_plan` (the
* conversation already has one open) nor `cancel_plan` (whether the plan
* stands is the user's call), so the only thing it can do is work it.
*/
export default function grabBotPlanTools({ user_id, bot_id, session_id, workspace_id, on_step, approve, onPlan }: Params) {
const tools: HarnessTool[] = [];
if (!on_step) {
tools.push(createPlanTool({ user_id, bot_id, session_id, workspace_id, approve, onPlan }));
if (!approve) {
tools.push(cancelPlanTool({ user_id, bot_id, session_id }));
}
}
tools.push(updatePlanTool({ user_id, bot_id, session_id, onPlan }));
tools.push(completePlanStepTool({ bot_id, session_id, in_run: approve }));
return tools;
}
@@ -0,0 +1,61 @@
import { z } from "zod";
import grabBotPlan from "@/src/functions/backend/db/bot-plans/grab-bot-plan";
import saveBotPlanSteps from "@/src/functions/backend/db/bot-plans/save-bot-plan-steps";
import pushBotPlan from "@/src/bots-queue/push-bot-plan";
import { BotPlanGoalSchema, BotPlanStepTextsSchema, BotPlanTitleSchema } from "@/src/schemas/bot-plan-schema";
import AppError from "@/src/utils/app-error";
import botPlanRef from "@/src/utils/bot-plan-ref";
import type { HarnessTool } from "../../../types";
type Params = {
user_id: number | string;
bot_id: number | string;
session_id: number | string;
onPlan: (params: { ref: string }) => void;
};
type Args = {
plan_id: number;
steps: z.infer<typeof BotPlanStepTextsSchema>;
title?: string;
goal?: string;
};
/**
* The bot changed the plan it is working, because the work showed the plan
* was wrong. The same rules the user's edits follow hold: a step already
* done is a record of work that happened, so it stays at the top with its
* note, and everything after it is the bot's to rewrite.
*/
export default function updatePlanTool({ user_id, bot_id, session_id, onPlan }: Params): HarnessTool<Args> {
return {
name: "update_plan",
description: `Change the plan you're working when what you found makes the rest of it wrong. Send the whole list of steps, in order, the steps already done first and unchanged (their notes are what was worked). Say in your reply what changed and why, in a line. Don't use it to make the plan look finished.`,
schema: z.object({
plan_id: z.number().int().positive().describe(`The plan's id, as your prompt gives it`),
steps: BotPlanStepTextsSchema.describe(`The plan's steps as they should now read, done ones first and unchanged`),
title: BotPlanTitleSchema.optional().describe(`A new title, only when the work turned out to be something else`),
goal: BotPlanGoalSchema.describe(`A new goal, only when what "done" means has changed`),
}),
run: async ({ args }) => {
const row = await grabBotPlan({ plan_id: args.plan_id });
if (Number(row.session_id) != Number(session_id)) {
throw new AppError(`Plan #${args.plan_id} belongs to another conversation: change that conversation's plan.`);
}
await saveBotPlanSteps({
plan_id: args.plan_id,
user_id,
title: args.title?.trim() || row.title || "",
goal: args.goal?.trim() || row.goal || "",
steps: args.steps,
});
onPlan({ ref: botPlanRef({ plan_id: args.plan_id }) });
await pushBotPlan({ plan_id: args.plan_id, session_id, bot_id });
return `Plan #${args.plan_id} is updated and its card shows the new steps. Say in a line what changed and why, then carry on with the step you're on.`;
},
};
}
@@ -45,6 +45,7 @@ type Args = {
bot_id?: number;
workspace_id?: number;
workspace_wide?: boolean;
parent_task_id?: number;
status?: TaskStatus;
};
@@ -147,8 +148,8 @@ export default function createTaskTool({
return {
name: "create_task",
description: is_coordinator
? `Add a task: to a worker's own list (bot_id: ${crew || "no workers yet"}), to a workspace (workspace_id: ${places || "no workspaces yet"}) for one of its bots (with bot_id; without, it's yours there) or workspace-wide (workspace_wide: true, no bot_id), or to your own list (leave both ids out${workspace_id ? "; here, leaving them out makes it yours in this workspace" : ""}). A task belongs to one bot unless it's workspace-wide: then every bot in that workspace sees it, works on it and logs what it did. Write the description as a brief: what to do, where, and how you'll know it's done.`
: `Add a task: ${workspace_id ? `in this workspace, yours by default${team ? `, a member's as this workspace's admin (bot_id: ${team})` : ""}, or workspace-wide (workspace_wide: true) when it's work for the whole crew here: every bot in the workspace sees it, works on it and logs what it did` : `on your own list (bot_id ${bot_id}, the default)`}. Write the description as a brief: what to do, where, and how you'll know it's done.`,
? `Add a task: to a worker's own list (bot_id: ${crew || "no workers yet"}), to a workspace (workspace_id: ${places || "no workspaces yet"}) for one of its bots (with bot_id; without, it's yours there) or workspace-wide (workspace_wide: true, no bot_id), or to your own list (leave both ids out${workspace_id ? "; here, leaving them out makes it yours in this workspace" : ""}). A task belongs to one bot unless it's workspace-wide: then every bot in that workspace sees it, works on it and logs what it did. When that workspace-wide task is too much for one bot, split it: add each piece with parent_task_id (the wide task's id), one bot per piece, and the parent stays open until you verify the parts. Write the description as a brief: what to do, where, and how you'll know it's done.`
: `Add a task: ${workspace_id ? `in this workspace, yours by default${team ? `, a member's as this workspace's admin (bot_id: ${team})` : ""}, or workspace-wide (workspace_wide: true) when it's work for the whole crew here: every bot in the workspace sees it, works on it and logs what it did` : `on your own list (bot_id ${bot_id}, the default)`}. To take one piece of a workspace-wide task here, add it with parent_task_id (that task's id), one bot per piece: the parent stays open until its parts are verified. Write the description as a brief: what to do, where, and how you'll know it's done.`,
schema: z.object({
title: z.string().trim().min(1).max(AppData.TaskTitleMaxLength).describe(`A short label`),
description: z
@@ -175,13 +176,26 @@ export default function createTaskTool({
.boolean()
.optional()
.describe(`In a workspace: nobody's, for every bot there to work on and log. Only when the work is the whole crew's; defaults to false.`),
parent_task_id: z
.number()
.int()
.optional()
.describe(
`The workspace-wide task this one is one piece of (its id, which list_tasks shows): a subtask, in that task's workspace, with a bot of its own. Use it instead of workspace_wide: a subtask belongs to one bot, and only a workspace-wide task can be split.`,
),
status: z.enum(TaskStatusValues).optional().describe(`Defaults to to do`),
}),
run: async ({ args }) => {
if (args.parent_task_id && args.workspace_wide) {
return `A subtask belongs to one bot: leave workspace_wide out and pass parent_task_id with the bot it's for.`;
}
const place = resolvePlace({ args, bot_id, workspace_id, is_coordinator, members });
if (typeof place == "string") return place;
const parent_task_id = args.parent_task_id ? Number(args.parent_task_id) : null;
const existing = await grabTasks({
bot_id,
is_coordinator,
@@ -189,6 +203,7 @@ export default function createTaskTool({
only_bot_id: place.workspace_id ? undefined : place.bot_id,
only_workspace_id: place.workspace_id,
own_list: !place.workspace_id,
only_parent_task_id: parent_task_id || undefined,
open_only: true,
});
@@ -197,6 +212,7 @@ export default function createTaskTool({
title: args.title,
bot_id: place.bot_id,
workspace_id: place.workspace_id || null,
parent_task_id,
});
if (twin) {
@@ -210,6 +226,7 @@ export default function createTaskTool({
bot_id: place.bot_id,
workspace_id: place.workspace_id,
workspace_wide: !place.bot_id,
parent_task_id,
title: args.title,
description: args.description,
status: args.status as never,
@@ -224,7 +241,7 @@ export default function createTaskTool({
? "to your list"
: `to bot ${place.bot_id}'s list`;
return `Task #${task.id} "${task.title}" added ${where}. Check it with list_tasks before you mention it to the user.`;
return `Task #${task.id} "${task.title}" added ${where}${parent_task_id ? `, as a subtask of task #${parent_task_id} (the parent stays open until someone verifies all the parts)` : ""}. Check it with list_tasks before you mention it to the user.`;
},
};
}
@@ -22,4 +22,31 @@ describe("describeTaskLog", () => {
test("leaves the files out when there are none", () => {
expect(describeTaskLog({ task, notes: [], bot_id: 21 })).not.toContain("Files");
});
test("a subtask says which task it belongs to and that the parent stays open", () => {
const text = describeTaskLog({
task: { ...task, parent_task_id: 12, parent_title: "Ship the release" },
notes: [],
bot_id: 21,
});
expect(text).toContain('A subtask of task #12 "Ship the release"');
expect(text).toContain("don't mark it done from here");
});
test("a split task lists its subtasks with their owners and which are open", () => {
const text = describeTaskLog({
task: { ...task, bot_id: "", workspace_id: 3 },
notes: [],
bot_id: 21,
parts: [
{ id: 31, status: "doing", title: "The intro", bot_id: 21, bot_name: "Software Engineer" },
{ id: 32, status: "done", title: "The appendix", bot_id: 22, bot_name: "SEO Expert" },
],
});
expect(text).toContain("Subtasks (2):");
expect(text).toContain("- #31 [doing] (open) The intro, Software Engineer (yours)");
expect(text).toContain("- #32 [done] The appendix, SEO Expert");
});
});
@@ -1,14 +1,28 @@
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
import type { TaskFile, TaskNote } from "@/src/types";
import type { TaskFile, TaskNote, TaskWithNames } from "@/src/types";
type Params = {
task: BUN_SQLITE_COBBLE_TASKS;
/**
* The task row, with `parent_title` when it is a subtask (`grab-tasks`).
*/
task: BUN_SQLITE_COBBLE_TASKS & {
/**
* Its parent's title, read for a subtask (`grab-tasks`' join, or the
* caller's lookup).
*/
parent_title?: string | null;
};
notes: TaskNote[];
/**
* What's filed on it (`grabTaskMedia`), so a bot can name, check and
* unlink them.
*/
files?: TaskFile[];
/**
* Its subtasks, when it is workspace-wide: each with its status and
* whose it is, so a bot sees what is already split off.
*/
parts?: TaskWithNames[];
/**
* The run's own bot, named "you" in the log.
*/
@@ -21,7 +35,7 @@ type Params = {
* on a workspace-wide task sees what the others already did, and its files
* (a bot file by its `[file:ID]` ref, a user's upload by name).
*/
export default function describeTaskLog({ task, notes, files = [], bot_id }: Params) {
export default function describeTaskLog({ task, notes, files = [], parts = [], bot_id }: Params) {
const who = task.bot_id
? task.bot_id == Number(bot_id)
? "yours"
@@ -53,10 +67,25 @@ export default function describeTaskLog({ task, notes, files = [], bot_id }: Par
.join("\n")
: "";
const split = parts.length
? parts
.map((subtask) => {
const owner = subtask.bot_id ? subtask.bot_name || `bot ${subtask.bot_id}` : "nobody";
const open = subtask.status == "done" || subtask.status == "cancelled" ? "" : " (open)";
return `- #${subtask.id} [${subtask.status}]${open} ${subtask.title}, ${owner}${Number(subtask.bot_id || 0) == Number(bot_id) ? " (yours)" : ""}`;
})
.join("\n")
: "";
return [
`#${task.id} [${task.status}] ${task.title} (${task.workspace_id ? `in workspace ${task.workspace_id}, ` : ""}${who})`,
task.parent_task_id
? `A subtask of task #${task.parent_task_id}${task.parent_title ? ` "${task.parent_title}"` : ""}: one piece of that work. The parent stays open until someone verifies all its subtasks, so don't mark it done from here.`
: "",
task.status == "blocked" && task.blocked_reason ? `Blocked: ${task.blocked_reason}` : "",
`Brief:\n${task.description?.trim() || "(none)"}`,
split ? `Subtasks (${parts.length}):\n${split}` : "",
filed ? `Files (${files.length}):\n${filed}` : "",
`Log, oldest first:\n${log}`,
]
+18 -3
View File
@@ -7,6 +7,7 @@ import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
import grabTaskNotes from "@/src/functions/backend/db/tasks/grab-task-notes";
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
import grabTaskMedia from "@/src/functions/backend/db/tasks/grab-task-media";
import grabTaskRow from "@/src/functions/backend/db/tasks/grab-task-scope";
import describeTaskLog from "./describe-task-log";
import type { HarnessTool } from "../../../types";
@@ -69,10 +70,19 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
onTask?.({ task_id: Number(task.id) });
const [notes, files, parts] = await Promise.all([
grabTaskNotes({ task_id: task.id! }),
grabTaskMedia({ task_id: task.id! }),
grabTasks({ bot_id, is_coordinator, admin_workspace_ids, only_parent_task_id: task.id! }),
]);
const parent = task.parent_task_id ? await grabTaskRow({ task_id: task.parent_task_id }) : null;
return describeTaskLog({
task,
notes: await grabTaskNotes({ task_id: task.id! }),
files: await grabTaskMedia({ task_id: task.id! }),
task: parent ? { ...task, parent_title: parent.title } : task,
notes,
files,
parts,
bot_id,
});
}
@@ -113,6 +123,11 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
`[${task.status}]`,
task.title,
`(${where})`,
Number(task.subtask_count || 0)
? `a subtask of #${task.parent_task_id}`
: task.workspace_id && !task.bot_id && Number(task.subtask_open_count || 0)
? `split into ${task.subtask_count} subtasks, ${task.subtask_open_count} still open`
: "",
Number(task.media_count || 0) ? `${task.media_count} file(s)` : "",
task.status == "blocked" && task.blocked_reason ? `blocked: ${task.blocked_reason}` : "",
task.latest_note
@@ -28,6 +28,13 @@ describe("updateTaskTool", () => {
expect(tool.description).toContain(`holds ${AppData.TaskMediaMaxPerTask} files`);
});
test("takes a parent to become a subtask of, and says so", () => {
expect(tool.schema?.safeParse({ task_id: 20, parent_task_id: 16 }).success).toBe(true);
expect(tool.schema?.safeParse({ task_id: 20, parent_task_id: 0 }).success).toBe(false);
expect(tool.description).toContain("parent_task_id");
expect(tool.description).toContain("unlink_parent");
});
test("tells the bot to rename rather than add a second task", () => {
expect(tool.description).toContain("Rename it with title");
expect(tool.description).toContain("never create a second task");
@@ -3,10 +3,12 @@ import { AppData } from "@/src/data/app-data";
import { type TaskStatus, TaskStatusValues } from "@/src/dict/task-dict";
import addTaskNote from "@/src/functions/backend/db/tasks/add-task-note";
import attachTaskFile from "@/src/functions/backend/db/tasks/attach-task-file";
import detachSubtask from "@/src/functions/backend/db/tasks/detach-subtask";
import detachTaskFile from "@/src/functions/backend/db/tasks/detach-task-file";
import findDuplicateTask from "@/src/functions/backend/db/tasks/find-duplicate-task";
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
import linkSubtask from "@/src/functions/backend/db/tasks/link-subtask";
import grabTaskMedia from "@/src/functions/backend/db/tasks/grab-task-media";
import makeTaskWorkspaceWide from "@/src/functions/backend/db/tasks/make-task-workspace-wide";
import grabBotById from "@/src/functions/backend/db/bots/grab-bot-by-id";
@@ -44,6 +46,8 @@ type Args = {
reference_file_ids?: number[];
unlink_file_ids?: number[];
workspace_wide?: boolean;
parent_task_id?: number;
unlink_parent?: boolean;
};
/**
@@ -65,7 +69,7 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
return {
name: "update_task",
description: `Move a task along. Rename it with title or rewrite its brief with description (never create a second task for the same work just to fix its name). Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number. A task holds ${AppData.TaskMediaMaxPerTask} files: to make room, or to drop a superseded version, unlink files with unlink_file_ids (list_tasks with task_id shows what's filed; the file stays in its folder). Unlink first, then file, in the same call.${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
description: `Move a task along. Rename it with title or rewrite its brief with description (never create a second task for the same work just to fix its name). Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number. A task holds ${AppData.TaskMediaMaxPerTask} files: to make room, or to drop a superseded version, unlink files with unlink_file_ids (list_tasks with task_id shows what's filed; the file stays in its folder). Unlink first, then file, in the same call. A part of a workspace-wide task (its row says so) is one piece of that work: log your notes on it like any task, and unlink_parent: true takes it out of the parent if it stops being part of it. parent_task_id: N makes a task of your own the part you took on of the workspace-wide task #N in its workspace (one piece each, and the parent stays open until someone verifies them all).${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
schema: z.object({
task_id: z.number().int(),
title: z
@@ -111,6 +115,20 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
? `true to make a bot's open task in ${is_coordinator ? "a" : "a workspace you're admin of"} workspace workspace-wide: nobody's, for every bot there to work on and log. Only true does anything.`
: `Only the coordinator or a workspace's admin bot can use this; leave it out.`,
),
parent_task_id: z
.number()
.int()
.positive()
.optional()
.describe(
`N attaches this task to the open workspace-wide task #N in its workspace: the piece of it you took on. Only tasks a bot has in a workspace can join one, and a task with subtasks of its own can't.`,
),
unlink_parent: z
.boolean()
.optional()
.describe(
`For a subtask of a workspace-wide task: true takes it out of that task, leaving it a task of its own in the workspace. Only true does anything.`,
),
}),
run: async ({ args }) => {
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
@@ -136,6 +154,40 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
said.push(`it's workspace-wide now, every bot in workspace ${task.workspace_id} works on it`);
}
if (args.parent_task_id) {
if (args.unlink_parent) {
return `Pass parent_task_id to make it a subtask of a task, or unlink_parent to take it out of one, not both.`;
}
try {
await linkSubtask({
user_id,
task_id: task.id!,
parent_task_id: args.parent_task_id,
by_bot_id: bot_id,
by_name: (await grabBotById({ bot_id }))?.name || `Bot ${bot_id}`,
});
said.push(`it's a subtask of task #${args.parent_task_id} now`);
} catch (error: unknown) {
return error instanceof Error
? error.message
: `Couldn't make task #${task.id} a subtask of task #${args.parent_task_id}.`;
}
}
if (args.unlink_parent) {
if (!task.parent_task_id) {
return `Task #${task.id} isn't a subtask of another task: nothing to unlink it from.`;
}
await detachSubtask({
task_id: task.id!,
by_bot_id: bot_id,
by_name: (await grabBotById({ bot_id }))?.name || `Bot ${bot_id}`,
});
said.push(`it's a task of its own now, out of task #${task.parent_task_id}`);
}
const title = args.title?.trim();
const renamed = Boolean(title) && title != (task.title || "").trim();
const rewritten = args.description != undefined && args.description != (task.description || "");
+46
View File
@@ -0,0 +1,46 @@
import { describe, expect, test } from "bun:test";
import { WrapUpHandOffToolNames, WrapUpSaveToolNames } from "@/src/harness/text/run-text-loop";
import { WritingToolNames } from "./writing-tool-names";
import { WorkStartingTools } from "@/src/utils/reply-claim-problems";
/**
* Tool names written straight into a list go stale when a tool is renamed:
* `ask_crew` became `ask_bot` and three lists kept the old name, one of
* them (`WorkStartingTools`) enough that a reply which really had asked the
* crew was faulted for claiming work it did. The lists are checked against
* the tools the harness declares, so a rename can't leave one behind.
*/
async function declaredToolNames() {
const names = new Set<string>();
for (const file of new Bun.Glob("**/*.ts").scanSync({ cwd: import.meta.dir, absolute: true })) {
if (file.endsWith(".test.ts")) continue;
for (const matched of (await Bun.file(file).text()).matchAll(/name:\s*"([a-z][a-z0-9_]{2,})"/g)) {
names.add(matched[1]!);
}
}
return names;
}
const Lists: Record<string, readonly string[]> = {
WorkStartingTools,
WritingToolNames,
WrapUpSaveToolNames,
WrapUpHandOffToolNames,
};
describe("harness tool name lists", () => {
test("every name in one is a tool the harness declares", async () => {
const declared = await declaredToolNames();
const entries: [string, readonly string[]][] = Object.entries(Lists);
const stale = entries
.map(([list, names]) => [list, names.filter((name) => !declared.has(name))] as const)
.filter(([, names]) => names.length > 0);
expect(stale).toEqual([]);
});
});
+1 -1
View File
@@ -42,7 +42,7 @@ export const WritingToolNames: readonly string[] = [
"answer_install_request",
"start_task",
"delegate_task",
"ask_crew",
"ask_bot",
"create_bot",
"update_bot",
"delete_bot",
+1 -1
View File
@@ -25,7 +25,7 @@ type Params = {
*/
bot_id?: number | string;
/**
* The workspace the call is in: its models win over the bot's.
* The workspace the call is in: its models apply to the bots with none of their own.
*/
workspace_id?: number | string | null;
};
@@ -3,6 +3,7 @@ import Modal from "@moduletrace/twui/elements/Modal";
import H2 from "@moduletrace/twui/layout/H2";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import TopModalEscape from "@/src/components/general/top-modal-escape";
type Props = {
open: boolean;
@@ -23,6 +24,7 @@ export default function AddModalShell({ open, setOpen, title, description, child
setOpen={(next) => setOpen(typeof next == "function" ? next(open) : next)}
className="max-w-lg bg-paper p-6"
>
{open ? <TopModalEscape onClose={() => setOpen(false)} /> : null}
<Stack className="w-full gap-1! items-stretch">
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">{title}</H2>
{description ? (
@@ -0,0 +1,77 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import type { BotWithLastMessage } from "@/src/types";
import relativeTime from "@/src/utils/relative-time";
import BotRow from "./bot-row";
function bot(overrides: Partial<BotWithLastMessage>): BotWithLastMessage {
return {
id: 1,
name: "Ember",
color: "#c2410c",
stone: "ember",
face: "idle",
...overrides,
} as BotWithLastMessage;
}
const three_hours_ago = Date.now() - 3 * 60 * 60 * 1000;
/**
* The rail row's right column: time normally, the bot's spinner while it has
* work running. The face is the user's, so it covers work elsewhere, and the
* time comes back once the work ends.
*/
describe("BotRow", () => {
test("a working bot shows the spinner instead of the time", () => {
const html = renderToString(
<BotRow bot={bot({ face: "working", last_message_at: three_hours_ago })} />,
);
expect(html).toContain('aria-label="Working"');
expect(html).not.toContain(`>${relativeTime({ at: three_hours_ago })}<`);
});
test("the spinner keeps the bot's colour", () => {
const html = renderToString(<BotRow bot={bot({ face: "working", color: "#16a394" })} />);
expect(html).toContain('stroke="#16a394"');
});
test("the coordinator has no colour, so its spinner takes the row's ink", () => {
const html = renderToString(<BotRow bot={bot({ face: "working", color: undefined })} />);
expect(html).toContain('stroke="currentColor"');
});
test("an idle bot keeps the time and shows no spinner", () => {
const html = renderToString(
<BotRow bot={bot({ face: "idle", last_message_at: three_hours_ago })} />,
);
expect(html).not.toContain('aria-label="Working"');
expect(html).toContain(`>${relativeTime({ at: three_hours_ago })}<`);
});
test("a working bot keeps its unread marker: the spinner takes the time's slot alone", () => {
const html = renderToString(
<BotRow bot={bot({ face: "working", unread: 2, last_message_at: three_hours_ago })} />,
);
expect(html).toContain('aria-label="Working"');
expect(html).toContain('aria-label="Unread"');
});
test("a bot that never spoke shows neither a spinner nor a time while it rests", () => {
const html = renderToString(<BotRow bot={bot({ face: "idle" })} />);
expect(html).not.toContain('aria-label="Working"');
expect(html).toContain("Ember");
});
test("a working bot with no conversation yet still spins", () => {
const html = renderToString(<BotRow bot={bot({ face: "working" })} />);
expect(html).toContain('aria-label="Working"');
});
});
+14 -4
View File
@@ -11,6 +11,7 @@ import messagePreview from "@/src/utils/message-preview";
import relativeTime from "@/src/utils/relative-time";
import UnreadDot from "./unread-dot";
import AdminShield from "@/src/components/general/admin-shield";
import WorkingSpinner from "./working-spinner";
type Props = {
bot: BotWithLastMessage;
@@ -27,9 +28,10 @@ type Props = {
};
/**
* 48px rail row. Status is the face and the subtitle (the bot's status
* line while it has one): no badges, spinners or state dots. A workspace's
* admin has its shield beside its name: a role, not a status.
* 48px rail row. Status is the face, the spinner that takes the time's slot
* while the bot has work running, and the subtitle (the bot's status line
* while it has one): no badges or state dots. A workspace's admin has its
* shield beside its name: a role, not a status.
* The selected background (ink at 5%, never a hue) is painted by
* RailBotCard, which also holds the sessions.
*/
@@ -42,6 +44,12 @@ export default function BotRow({ bot, href, selected, subtitle }: Props) {
bot.role ||
"";
const at = bot.last_message_at || bot.last_activity_at;
/**
* The face is the user's, not this conversation's: it says the bot has
* work running anywhere for them (a reply here or elsewhere, a task),
* which is what the row marks.
*/
const working = bot.face == "working";
return (
<Link
@@ -68,7 +76,9 @@ export default function BotRow({ bot, href, selected, subtitle }: Props) {
</Span>
</Stack>
<Stack className="hidden @rail:flex shrink-0 self-stretch items-end justify-start gap-1.5! pt-1.5">
{at ? (
{working ? (
<WorkingSpinner color={stone_props.color} />
) : at ? (
<Span className="text-[11px] leading-4 text-ink-secondary">
{relativeTime({ at: Number(at) })}
</Span>
@@ -0,0 +1,48 @@
import Span from "@moduletrace/twui/layout/Span";
type Props = {
/**
* The bot's colour (`#rrggbb`), painted straight onto the turning arc:
* a free colour has no token to point at, so it's a stroke attribute
* here rather than a `stroke-*` class. The coordinator has no colour, so
* its arc takes the row's ink.
*/
color?: string | null;
};
/**
* A working bot's spinner, in the rail row's time slot: it turns while the
* bot has work running and says nothing about what that work is (the status
* line under the name does). A stone is never given a ring or a badge, so
* this sits beside it rather than on it. Its track is the hairline, not a
* hue: the bot's colour is its identity, and the movement is the state.
*/
export default function WorkingSpinner({ color }: Props) {
return (
<Span role="img" aria-label="Working" className="shrink-0 inline-flex">
<svg
width={12}
height={12}
viewBox="0 0 12 12"
aria-hidden="true"
className="animate-spin motion-reduce:animate-none"
>
<circle
cx={6}
cy={6}
r={4.5}
fill="none"
strokeWidth={1.5}
className="stroke-hairline-strong opacity-40"
/>
<path
d="M6 1.5A4.5 4.5 0 0 1 10.5 6"
fill="none"
strokeWidth={1.5}
strokeLinecap="round"
stroke={color || "currentColor"}
/>
</svg>
</Span>
);
}
@@ -0,0 +1,17 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import type { BotPlanView } from "@/src/types";
type Params = {
plan_id: number;
};
/**
* One plan a bot wrote (`api/admin/bot-plans/get-plan`), for its card.
*/
export default async function fetchBotPlan({ plan_id }: Params) {
return await fetchApi<{}, APIResponseObject<BotPlanView>>(
`/api/admin/bot-plans/get-plan?plan_id=${encodeURIComponent(String(plan_id))}`,
{ method: "GET" },
);
}
@@ -0,0 +1,21 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import type { BotPlanView } from "@/src/types";
type Params = {
plan_id: number;
title: string;
goal?: string;
steps: string[];
};
/**
* The user changed a plan's steps on its card, before approving it or while
* it runs. Returns the plan as it now stands.
*/
export default async function saveBotPlan({ plan_id, title, goal, steps }: Params) {
return await fetchApi<Omit<Params, "plan_id"> & { plan_id: number }, APIResponseObject<BotPlanView>>(
`/api/admin/bot-plans/save-plan`,
{ method: "POST", body: { plan_id, title, goal, steps } },
);
}
@@ -0,0 +1,23 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import type { BotPlanState } from "@/src/dict/bot-plan-dict";
import type { BotPlanView } from "@/src/types";
type Params = {
plan_id: number;
/**
* Approve it, pick it back up, pause it, or end it.
*/
status: Extract<BotPlanState, "active" | "paused" | "cancelled">;
};
/**
* Moves a plan from its card. Approving it (or picking it back up) wakes
* the bot for the step it stands on, so the plan carries on by itself.
*/
export default async function setBotPlanState({ plan_id, status }: Params) {
return await fetchApi<Params, APIResponseObject<BotPlanView>>(`/api/admin/bot-plans/set-plan-status`, {
method: "POST",
body: { plan_id, status },
});
}
@@ -0,0 +1,76 @@
import { useCallback, useEffect, useRef, useState } from "react";
import type { BotPlanChangedData, BotPlanView } from "@/src/types";
import useServerEvent from "@/src/hooks/use-server-event";
import fetchBotPlan from "../(functions)/fetch-bot-plan";
type Params = {
plan_id: number;
};
/**
* A plan as its card shows it (`[plan:ID]`). Read when the card renders,
* then kept current from the app's pushes (`server:bot-plan`, sent while a
* run works a step and when the user moves the plan), since the same card
* sits in several messages and its steps change under them. A failed read
* gives up rather than blocking the card forever; a push retries it.
*
* Read here rather than through `loadRefView`, whose cache never expires:
* a plan is alive, and a card left showing yesterday's step is worse than
* one that asks again.
*/
export default function useBotPlan({ plan_id }: Params) {
const [view, setViewState] = useState<BotPlanView | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string>();
const mounted = useRef(true);
const read = useCallback(async () => {
try {
const res = await fetchBotPlan({ plan_id });
if (!mounted.current) return;
if (res.success && res.singleRes) {
setViewState(res.singleRes);
setError(undefined);
} else {
setError(res.msg || `This plan isn't available.`);
}
} catch (e: unknown) {
if (mounted.current) setError(e instanceof Error ? e.message : `This plan isn't available.`);
} finally {
if (mounted.current) setLoading(false);
}
}, [plan_id]);
useEffect(() => {
mounted.current = true;
setLoading(true);
void read();
return () => {
mounted.current = false;
};
}, [read]);
useServerEvent({
event: "server:bot-plan",
onData: (data: BotPlanChangedData) => {
if (Number(data?.plan_id) != plan_id) return;
void read();
},
});
/**
* The card's own moves replace what was read, so it shows the change
* without asking the app again.
*/
const setView = useCallback((next: BotPlanView) => {
setViewState(next);
setError(undefined);
}, []);
return { view, loading, error, setView, reload: read };
}
@@ -1,39 +1,17 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useCallback, useEffect, useState } from "react";
import type { BotQuestionView } from "@/src/types";
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
type Params = {
question_id: number;
};
/**
* Questions already read, by id, so a thread naming them twice asks once.
* An answer replaces their entry.
*/
const loaded = new Map<number, Promise<BotQuestionView | null>>();
function loadQuestion({ question_id }: Params) {
const cached = loaded.get(question_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<BotQuestionView>>(
`/api/admin/bot-questions/get-question?question_id=${question_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(question_id, pending);
return pending;
}
/**
* Questions a bot asked (`[question:ID]`), for their chip and card: read
* when the chip renders, so it shows whether they're still waiting. Only
* the user they were asked of can read them; anyone else gets null.
* the user they were asked of can read them; anyone else gets null. A
* read that failed or hung is tried again (`loadRefView`) instead of
* leaving the card unopenable until the page is reloaded.
*/
export default function useBotQuestion({ question_id }: Params) {
const [view, setViewState] = useState<BotQuestionView | null>(null);
@@ -42,7 +20,12 @@ export default function useBotQuestion({ question_id }: Params) {
useEffect(() => {
let live = true;
loadQuestion({ question_id }).then((result) => {
setLoading(true);
loadRefView<BotQuestionView>({
key: `question:${question_id}`,
url: `/api/admin/bot-questions/get-question?question_id=${question_id}`,
}).then((result) => {
if (!live) return;
setViewState(result);
setLoading(false);
@@ -53,13 +36,17 @@ export default function useBotQuestion({ question_id }: Params) {
};
}, [question_id]);
/**
* The card's own answers replace what was read, so its chip says they
* were answered without asking the app again.
*/
const setView = useCallback(
(next: BotQuestionView) => {
loaded.set(question_id, Promise.resolve(next));
primeRefView({ key: `question:${question_id}`, view: next });
setViewState(next);
},
[question_id],
);
return { view, loading, setView };
}
}
@@ -1,38 +1,17 @@
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";
import loadRefView from "../(utils)/ref-view-loader";
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.
* gets null. A read that failed or hung is tried again before the buttons
* give up on it (`loadRefView`), so a missed push or a sleeping phone no
* longer needs the page reloaded.
*/
export default function useBotSuggestion({ suggestion_id }: Params) {
const [view, setView] = useState<BotSuggestionView | null>(null);
@@ -41,7 +20,12 @@ export default function useBotSuggestion({ suggestion_id }: Params) {
useEffect(() => {
let live = true;
loadSuggestion({ suggestion_id }).then((result) => {
setLoading(true);
loadRefView<BotSuggestionView>({
key: `suggestion:${suggestion_id}`,
url: `/api/admin/bot-suggestions/get-suggestion?suggestion_id=${suggestion_id}`,
}).then((result) => {
if (!live) return;
setView(result);
setLoading(false);
@@ -1,40 +1,18 @@
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
import type { APIResponseObject } from "@moduletrace/bunext/types";
import { useCallback, useEffect, useState } from "react";
import type { ExtensionProposalView } from "@/src/types";
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
type Params = {
proposal_id: number;
};
/**
* Proposals already read, by id, so a thread naming one twice (or a
* re-render) asks once. A decision replaces its entry.
*/
const loaded = new Map<number, Promise<ExtensionProposalView | null>>();
function loadProposal({ proposal_id }: Params) {
const cached = loaded.get(proposal_id);
if (cached) return cached;
const pending = fetchApi<{}, APIResponseObject<ExtensionProposalView>>(
`/api/admin/extension-proposals/get-proposal?proposal_id=${proposal_id}`,
{ method: "GET" },
)
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
.catch(() => null);
loaded.set(proposal_id, pending);
return pending;
}
/**
* An MCP server or tool the coordinator proposed (`[proposal:ID]`), for
* its chip and confirm card: read when the chip renders, so it shows
* whether it's still waiting. Only the super admin it was proposed to can
* read it; anyone else gets null.
* An extension a bot proposed (`[proposal:ID]`), for its chip and confirm
* card: read when the chip renders, so it shows whether it's still
* waiting. Only the super admin it was proposed to can read it; anyone
* else gets null. A read that failed or hung is tried again
* (`loadRefView`), so the card isn't unopenable until the page is
* reloaded.
*/
export default function useExtensionProposal({ proposal_id }: Params) {
const [view, setViewState] = useState<ExtensionProposalView | null>(null);
@@ -43,7 +21,12 @@ export default function useExtensionProposal({ proposal_id }: Params) {
useEffect(() => {
let live = true;
loadProposal({ proposal_id }).then((result) => {
setLoading(true);
loadRefView<ExtensionProposalView>({
key: `extension-proposal:${proposal_id}`,
url: `/api/admin/extension-proposals/get-proposal?proposal_id=${proposal_id}`,
}).then((result) => {
if (!live) return;
setViewState(result);
setLoading(false);
@@ -56,11 +39,11 @@ export default function useExtensionProposal({ proposal_id }: Params) {
const setView = useCallback(
(next: ExtensionProposalView) => {
loaded.set(proposal_id, Promise.resolve(next));
primeRefView({ key: `extension-proposal:${proposal_id}`, view: next });
setViewState(next);
},
[proposal_id],
);
return { view, loading, setView };
}
}

Some files were not shown because too many files have changed in this diff Show More