Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ca070ccc35 | ||
|
|
3268f049f9 | ||
|
|
2d57ba560c | ||
|
|
c1c307e51c | ||
|
|
7bc74dfe8e | ||
|
|
c705da17a1 | ||
|
|
f9f2a9b0b6 | ||
|
|
5d2ac342f0 | ||
|
|
f453796a8d | ||
|
|
fac3f66896 | ||
|
|
4292a2fa40 | ||
|
|
0d2c683933 |
@@ -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
|
||||
|
||||
@@ -95,7 +95,7 @@ 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), `[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`.
|
||||
@@ -125,7 +125,7 @@ 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`). 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 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.
|
||||
|
||||
@@ -135,11 +135,11 @@ Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`),
|
||||
|
||||
### 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 +167,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 +275,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.
|
||||
|
||||
+36
-8
@@ -805,7 +805,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 +831,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 +895,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 +1249,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",
|
||||
},
|
||||
{
|
||||
@@ -3030,7 +3046,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 +3283,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 +3479,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 +3840,8 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
destinationTableName: "knowledgebases",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "knowledgebase_documents_knowledgebases_fk",
|
||||
foreignKeyName:
|
||||
"knowledgebase_documents_knowledgebases_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -4011,7 +4037,8 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
destinationTableName: "workspaces",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "workspace_knowledgebases_workspaces_fk",
|
||||
foreignKeyName:
|
||||
"workspace_knowledgebases_workspaces_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -4022,7 +4049,8 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
destinationTableName: "knowledgebases",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "workspace_knowledgebases_knowledgebases_fk",
|
||||
foreignKeyName:
|
||||
"workspace_knowledgebases_knowledgebases_fk",
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -535,6 +535,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
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.21.1",
|
||||
"version": "0.21.4",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -30,6 +30,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";
|
||||
@@ -493,6 +494,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 });
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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}
|
||||
|
||||
@@ -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]"
|
||||
|
||||
@@ -35,4 +35,42 @@ describe("TaskListItem", () => {
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -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">
|
||||
@@ -99,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;
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -441,6 +441,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
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 = ?
|
||||
|
||||
@@ -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" };
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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." }]);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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}`,
|
||||
]
|
||||
|
||||
@@ -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 || "");
|
||||
|
||||
@@ -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"');
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -1,40 +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 { HookProposalView } from "@/src/types";
|
||||
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
proposal_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook 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<HookProposalView | null>>();
|
||||
|
||||
function loadProposal({ proposal_id }: Params) {
|
||||
const cached = loaded.get(proposal_id);
|
||||
|
||||
if (cached) return cached;
|
||||
|
||||
const pending = fetchApi<{}, APIResponseObject<HookProposalView>>(
|
||||
`/api/admin/hook-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;
|
||||
}
|
||||
|
||||
/**
|
||||
* A hook a bot proposed (`[hook-proposal:ID]`), for its chip and confirm
|
||||
* card: read when the chip renders, so it shows whether it's still
|
||||
* waiting. Only the user it was proposed to can read it; anyone else gets
|
||||
* null.
|
||||
* 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 useHookProposal({ proposal_id }: Params) {
|
||||
const [view, setViewState] = useState<HookProposalView | null>(null);
|
||||
@@ -43,7 +20,12 @@ export default function useHookProposal({ proposal_id }: Params) {
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
|
||||
loadProposal({ proposal_id }).then((result) => {
|
||||
setLoading(true);
|
||||
|
||||
loadRefView<HookProposalView>({
|
||||
key: `hook-proposal:${proposal_id}`,
|
||||
url: `/api/admin/hook-proposals/get-proposal?proposal_id=${proposal_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
setViewState(result);
|
||||
setLoading(false);
|
||||
@@ -56,11 +38,11 @@ export default function useHookProposal({ proposal_id }: Params) {
|
||||
|
||||
const setView = useCallback(
|
||||
(next: HookProposalView) => {
|
||||
loaded.set(proposal_id, Promise.resolve(next));
|
||||
primeRefView({ key: `hook-proposal:${proposal_id}`, view: next });
|
||||
setViewState(next);
|
||||
},
|
||||
[proposal_id],
|
||||
);
|
||||
|
||||
return { view, loading, setView };
|
||||
}
|
||||
}
|
||||
@@ -1,37 +1,16 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import { useEffect, useState } from "react";
|
||||
import type { SecretRefView } from "@/src/types";
|
||||
import loadRefView from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
env_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Secret refs already read, by id. Only the key and whether the viewer may
|
||||
* reveal it: the value is fetched on Reveal or Copy and never cached here.
|
||||
*/
|
||||
const loaded = new Map<number, Promise<SecretRefView | null>>();
|
||||
|
||||
function loadSecret({ env_id }: Params) {
|
||||
const cached = loaded.get(env_id);
|
||||
|
||||
if (cached) return cached;
|
||||
|
||||
const pending = fetchApi<{}, APIResponseObject<SecretRefView>>(
|
||||
`/api/admin/secrets/get-secret?env_id=${env_id}`,
|
||||
{ method: "GET" },
|
||||
)
|
||||
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
|
||||
.catch(() => null);
|
||||
|
||||
loaded.set(env_id, pending);
|
||||
|
||||
return pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* A secret a bot showed (`[secret:ID]`), for its masked chip.
|
||||
* A secret a bot showed (`[secret:ID]`), for its masked chip. Only the key
|
||||
* and whether the viewer may reveal it: the value is fetched on Reveal or
|
||||
* Copy and never read here. A read that failed or hung is tried again
|
||||
* (`loadRefView`), so the chip isn't left saying nothing until a reload.
|
||||
*/
|
||||
export default function useSecretRef({ env_id }: Params) {
|
||||
const [view, setView] = useState<SecretRefView | null>(null);
|
||||
@@ -40,7 +19,12 @@ export default function useSecretRef({ env_id }: Params) {
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
|
||||
loadSecret({ env_id }).then((result) => {
|
||||
setLoading(true);
|
||||
|
||||
loadRefView<SecretRefView>({
|
||||
key: `secret:${env_id}`,
|
||||
url: `/api/admin/secrets/get-secret?env_id=${env_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
setView(result);
|
||||
setLoading(false);
|
||||
@@ -52,4 +36,4 @@ export default function useSecretRef({ env_id }: Params) {
|
||||
}, [env_id]);
|
||||
|
||||
return { view, loading };
|
||||
}
|
||||
}
|
||||
@@ -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 { SecretRequestView } from "@/src/types";
|
||||
import loadRefView, { primeRefView } from "../(utils)/ref-view-loader";
|
||||
|
||||
type Params = {
|
||||
request_id: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Secret requests already read, by id, so a thread naming one twice asks
|
||||
* once. An answer replaces its entry.
|
||||
*/
|
||||
const loaded = new Map<number, Promise<SecretRequestView | null>>();
|
||||
|
||||
function loadRequest({ request_id }: Params) {
|
||||
const cached = loaded.get(request_id);
|
||||
|
||||
if (cached) return cached;
|
||||
|
||||
const pending = fetchApi<{}, APIResponseObject<SecretRequestView>>(
|
||||
`/api/admin/secret-requests/get-request?request_id=${request_id}`,
|
||||
{ method: "GET" },
|
||||
)
|
||||
.then((res) => (res?.success && res.singleRes ? res.singleRes : null))
|
||||
.catch(() => null);
|
||||
|
||||
loaded.set(request_id, pending);
|
||||
|
||||
return pending;
|
||||
}
|
||||
|
||||
/**
|
||||
* A secret a bot asked for (`[secret-request:ID]`), for its chip and card:
|
||||
* read when the chip renders, so it shows whether it's still waiting.
|
||||
* Only the user it was asked of can read it; anyone else gets null.
|
||||
* Only the user it was asked of 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 useSecretRequest({ request_id }: Params) {
|
||||
const [view, setViewState] = useState<SecretRequestView | null>(null);
|
||||
@@ -42,7 +20,12 @@ export default function useSecretRequest({ request_id }: Params) {
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
|
||||
loadRequest({ request_id }).then((result) => {
|
||||
setLoading(true);
|
||||
|
||||
loadRefView<SecretRequestView>({
|
||||
key: `secret-request:${request_id}`,
|
||||
url: `/api/admin/secret-requests/get-request?request_id=${request_id}`,
|
||||
}).then((result) => {
|
||||
if (!live) return;
|
||||
setViewState(result);
|
||||
setLoading(false);
|
||||
@@ -55,11 +38,11 @@ export default function useSecretRequest({ request_id }: Params) {
|
||||
|
||||
const setView = useCallback(
|
||||
(next: SecretRequestView) => {
|
||||
loaded.set(request_id, Promise.resolve(next));
|
||||
primeRefView({ key: `secret-request:${request_id}`, view: next });
|
||||
setViewState(next);
|
||||
},
|
||||
[request_id],
|
||||
);
|
||||
|
||||
return { view, loading, setView };
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
import conversationHref from "@/src/utils/conversation-href";
|
||||
import askPreviousSessionId from "@/src/utils/ask-previous-session-id";
|
||||
import type { AskOverview } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
@@ -17,8 +18,8 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Above the composer of a session a crew request opened: the way back to
|
||||
* the conversation the user was in before it, which `startBotSession`
|
||||
* At the top of a session a crew request opened: the way back to the
|
||||
* conversation the user was in before it, which `startBotSession`
|
||||
* closed to give the request a thread of its own.
|
||||
*/
|
||||
export default function AskSessionBar({ bot_id, workspace_id, session_id }: Props) {
|
||||
@@ -48,8 +49,20 @@ export default function AskSessionBar({ bot_id, workspace_id, session_id }: Prop
|
||||
|
||||
if (!ask?.previous_session_id) return null;
|
||||
|
||||
/**
|
||||
* A bot with no conversation there before the request has nothing to
|
||||
* lead back to, so its thread carries no bar: only a real earlier
|
||||
* session is one.
|
||||
*/
|
||||
const previous_session_id = askPreviousSessionId({
|
||||
previous_session_id: ask.previous_session_id,
|
||||
session_id,
|
||||
});
|
||||
|
||||
if (!previous_session_id) return null;
|
||||
|
||||
return (
|
||||
<Stack className="shrink-0 gap-0! items-stretch border-0 border-t border-solid border-hairline">
|
||||
<Stack className="shrink-0 gap-0! items-stretch border-0 border-b border-solid border-hairline">
|
||||
<Row className="w-full max-w-container mx-auto py-3 gap-3! md:gap-4! flex-nowrap items-center justify-between px-3 md:px-6">
|
||||
<Span className="min-w-0 text-sm text-ink-secondary truncate">
|
||||
{ask.requester_name
|
||||
@@ -63,7 +76,7 @@ export default function AskSessionBar({ bot_id, workspace_id, session_id }: Prop
|
||||
href={conversationHref({
|
||||
bot_id,
|
||||
workspace_id,
|
||||
session_id: ask.previous_session_id,
|
||||
session_id: previous_session_id,
|
||||
})}
|
||||
beforeIcon={<ArrowLeft size={14} aria-hidden />}
|
||||
variant="outlined"
|
||||
|
||||
@@ -81,8 +81,13 @@ export default function BotModelsModal({
|
||||
const [form_key, setFormKey] = useState(0);
|
||||
|
||||
const in_workspace = Boolean(workspace?.id);
|
||||
const is_coordinator = bot.kind == "coordinator" && !in_workspace;
|
||||
const can_edit = is_coordinator
|
||||
/**
|
||||
* The coordinator has no models of its own: outside a workspace the
|
||||
* modal edits the defaults, inside one the workspace's.
|
||||
*/
|
||||
const edits_defaults = bot.kind == "coordinator" && !in_workspace;
|
||||
const edits_workspace = bot.kind == "coordinator" && in_workspace;
|
||||
const can_edit = edits_defaults
|
||||
? isPassThroughUser({ user_types: pageProps?.user_types })
|
||||
: canManageCrew({ user_types: pageProps?.user_types });
|
||||
const name = bot.name || "This bot";
|
||||
@@ -106,14 +111,16 @@ export default function BotModelsModal({
|
||||
if (!bot.id) return null;
|
||||
|
||||
const title = can_edit
|
||||
? in_workspace
|
||||
? edits_workspace
|
||||
? `Change ${workspace?.name || "the workspace"}'s models`
|
||||
: is_coordinator
|
||||
: edits_defaults
|
||||
? "Change the default models"
|
||||
: `Change ${name}'s models`
|
||||
: is_coordinator
|
||||
: edits_defaults
|
||||
? `${name} uses the default models. A super admin can change them in Settings, under Models.`
|
||||
: `An admin can change the models ${name} uses.`;
|
||||
: edits_workspace
|
||||
? `An admin can change the models in ${workspace?.name || "this workspace"}.`
|
||||
: `An admin can change the models ${name} uses.`;
|
||||
|
||||
const target = meta_text ? (
|
||||
<HeaderMetaItem
|
||||
@@ -155,18 +162,20 @@ export default function BotModelsModal({
|
||||
>
|
||||
<Stack className="w-full gap-1! items-stretch pb-2">
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">
|
||||
{in_workspace
|
||||
{edits_workspace
|
||||
? `Models in ${workspace?.name || "this workspace"}`
|
||||
: is_coordinator
|
||||
: edits_defaults
|
||||
? "Default models"
|
||||
: `${name}'s models`}
|
||||
</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{in_workspace
|
||||
? `Every bot working in ${workspace?.name || "this workspace"} uses these, the coordinator too. Left on "Same as the default", ${name} uses its own models, else the defaults.`
|
||||
: is_coordinator
|
||||
{edits_workspace
|
||||
? `Every bot working in ${workspace?.name || "this workspace"} without models of its own uses these, the coordinator too. A bot's own models, set in its models here, win.`
|
||||
: edits_defaults
|
||||
? `${name} and every bot left on the default use these. The text model chats, plans and drives computers; the others read media, transcribe, speak and make images for it. Providers are in Settings, under Models.`
|
||||
: `${name} uses the default models unless you pick its own. The text model chats, plans and drives computers; the others read media, transcribe, speak and make images for it.`}
|
||||
: in_workspace
|
||||
? `${name} inherits ${workspace?.name || "this workspace"}'s models here until you pick its own, and its own win wherever it works. The text model chats, plans and drives computers; the others read media, transcribe, speak and make images for it.`
|
||||
: `${name} uses the default models unless you pick its own. The text model chats, plans and drives computers; the others read media, transcribe, speak and make images for it.`}
|
||||
</Span>
|
||||
</Stack>
|
||||
{harnesses?.length ? (
|
||||
|
||||
@@ -434,6 +434,13 @@ export default function Conversation() {
|
||||
model={text_model}
|
||||
onModelChange={setTextModel}
|
||||
/>
|
||||
{moved_to_session_id ? null : (
|
||||
<AskSessionBar
|
||||
bot_id={Number(bot.id)}
|
||||
workspace_id={workspace_id}
|
||||
session_id={session_id}
|
||||
/>
|
||||
)}
|
||||
{history.loading ? (
|
||||
<LoadingLine label="Loading the conversation" />
|
||||
) : null}
|
||||
@@ -475,67 +482,60 @@ export default function Conversation() {
|
||||
moved_to_session_id={moved_to_session_id}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<AskSessionBar
|
||||
bot_id={Number(bot.id)}
|
||||
workspace_id={workspace_id}
|
||||
session_id={session_id}
|
||||
/>
|
||||
<Composer
|
||||
handle_ref={composer}
|
||||
bot={bot}
|
||||
workspace_id={workspace_id}
|
||||
extensions={pageProps?.bot_extensions}
|
||||
voice={pageProps?.bot_voice}
|
||||
has_browsers={Boolean(pageProps?.has_browsers)}
|
||||
max_chars={pageProps?.message_max_chars}
|
||||
previous_messages={thread_messages}
|
||||
reply_to={reply_to}
|
||||
onCancelReply={() => setReplyTo(null)}
|
||||
onSendStart={({ message }) =>
|
||||
setPendingMessages((prev) => [
|
||||
...prev,
|
||||
message,
|
||||
])
|
||||
}
|
||||
onSendFailed={({ temp_id }) =>
|
||||
setPendingMessages((prev) =>
|
||||
prev.filter(
|
||||
(message) =>
|
||||
message.id != temp_id,
|
||||
),
|
||||
)
|
||||
}
|
||||
onSent={({ message }) => {
|
||||
setReplyTo(null);
|
||||
setPendingMessages((prev) =>
|
||||
dropSentMessage({
|
||||
pending: prev,
|
||||
<Composer
|
||||
handle_ref={composer}
|
||||
bot={bot}
|
||||
workspace_id={workspace_id}
|
||||
extensions={pageProps?.bot_extensions}
|
||||
voice={pageProps?.bot_voice}
|
||||
has_browsers={Boolean(pageProps?.has_browsers)}
|
||||
max_chars={pageProps?.message_max_chars}
|
||||
previous_messages={thread_messages}
|
||||
reply_to={reply_to}
|
||||
onCancelReply={() => setReplyTo(null)}
|
||||
onSendStart={({ message }) =>
|
||||
setPendingMessages((prev) => [
|
||||
...prev,
|
||||
message,
|
||||
}),
|
||||
);
|
||||
|
||||
if (
|
||||
startsNewSession(message) &&
|
||||
message.session_id != session_id
|
||||
) {
|
||||
following_send.current = true;
|
||||
setSessionId(
|
||||
Number(message.session_id),
|
||||
);
|
||||
setMessages([message]);
|
||||
history.retry();
|
||||
return;
|
||||
])
|
||||
}
|
||||
onSendFailed={({ temp_id }) =>
|
||||
setPendingMessages((prev) =>
|
||||
prev.filter(
|
||||
(message) =>
|
||||
message.id != temp_id,
|
||||
),
|
||||
)
|
||||
}
|
||||
onSent={({ message }) => {
|
||||
setReplyTo(null);
|
||||
setPendingMessages((prev) =>
|
||||
dropSentMessage({
|
||||
pending: prev,
|
||||
message,
|
||||
}),
|
||||
);
|
||||
|
||||
setMessages((prev) =>
|
||||
prev.some((m) => m.id == message.id)
|
||||
? prev
|
||||
: [...prev, message],
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
if (
|
||||
startsNewSession(message) &&
|
||||
message.session_id != session_id
|
||||
) {
|
||||
following_send.current = true;
|
||||
setSessionId(
|
||||
Number(message.session_id),
|
||||
);
|
||||
setMessages([message]);
|
||||
history.retry();
|
||||
return;
|
||||
}
|
||||
|
||||
setMessages((prev) =>
|
||||
prev.some((m) => m.id == message.id)
|
||||
? prev
|
||||
: [...prev, message],
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
</BotMessageActionsContext.Provider>
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import loadRefView, { primeRefView } from "./ref-view-loader";
|
||||
|
||||
/**
|
||||
* A read standing in for the app's: one answer per call, in order, and a
|
||||
* count of how many times it was asked.
|
||||
*/
|
||||
function reader({ answers }: { answers: (unknown | null)[] }) {
|
||||
const asked: string[] = [];
|
||||
|
||||
const readOnce = async ({ url }: { url: string }) => {
|
||||
asked.push(url);
|
||||
|
||||
return answers[Math.min(asked.length - 1, answers.length - 1)] ?? null;
|
||||
};
|
||||
|
||||
return { asked, readOnce };
|
||||
}
|
||||
|
||||
describe("loadRefView", () => {
|
||||
test("reads a view once and keeps it, so a thread naming it twice asks once", async () => {
|
||||
const { asked, readOnce } = reader({ answers: [{ id: 5, steps: ["One"] }] });
|
||||
|
||||
const first = await loadRefView({ key: "test:kept", url: "/get?id=5", readOnce, retryDelaysMs: [] });
|
||||
const second = await loadRefView({ key: "test:kept", url: "/get?id=5", readOnce, retryDelaysMs: [] });
|
||||
|
||||
expect(first).toEqual({ id: 5, steps: ["One"] });
|
||||
expect(second).toEqual(first);
|
||||
expect(asked).toEqual(["/get?id=5"]);
|
||||
});
|
||||
|
||||
test("forgets a read that failed, so the next chip asks again instead of showing nothing", async () => {
|
||||
const { asked, readOnce } = reader({ answers: [null, null, { id: 7 }] });
|
||||
|
||||
expect(await loadRefView({ key: "test:forgotten", url: "/get?id=7", readOnce, retryDelaysMs: [] })).toBeNull();
|
||||
expect(await loadRefView({ key: "test:forgotten", url: "/get?id=7", readOnce, retryDelaysMs: [] })).toBeNull();
|
||||
expect(await loadRefView({ key: "test:forgotten", url: "/get?id=7", readOnce, retryDelaysMs: [] })).toEqual({
|
||||
id: 7,
|
||||
});
|
||||
expect(asked).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("tries a failed read again before giving up on it", async () => {
|
||||
const { asked, readOnce } = reader({ answers: [null, { id: 9, steps: ["Two"] }] });
|
||||
|
||||
const view = await loadRefView({ key: "test:retried", url: "/get?id=9", readOnce, retryDelaysMs: [0] });
|
||||
|
||||
expect(view).toEqual({ id: 9, steps: ["Two"] });
|
||||
expect(asked).toHaveLength(2);
|
||||
|
||||
await loadRefView({ key: "test:retried", url: "/get?id=9", readOnce, retryDelaysMs: [0] });
|
||||
|
||||
expect(asked).toHaveLength(2);
|
||||
});
|
||||
|
||||
test("shares one read between callers asking for the same view at once", async () => {
|
||||
let release: (value: unknown) => void = () => {};
|
||||
let asked = 0;
|
||||
|
||||
const readOnce = () => {
|
||||
asked += 1;
|
||||
|
||||
return new Promise<unknown | null>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
};
|
||||
|
||||
const first = loadRefView({ key: "test:shared", url: "/get?id=11", readOnce, retryDelaysMs: [] });
|
||||
const second = loadRefView({ key: "test:shared", url: "/get?id=11", readOnce, retryDelaysMs: [] });
|
||||
|
||||
release({ id: 11 });
|
||||
|
||||
expect(await first).toEqual({ id: 11 });
|
||||
expect(await second).toEqual({ id: 11 });
|
||||
expect(asked).toBe(1);
|
||||
});
|
||||
|
||||
test("hands back a view the page already has, without asking", async () => {
|
||||
let asked = 0;
|
||||
const readOnce = async () => {
|
||||
asked += 1;
|
||||
|
||||
return { id: 13 };
|
||||
};
|
||||
|
||||
primeRefView({ key: "test:primed", view: { id: 13, status: "answered" } });
|
||||
|
||||
expect(await loadRefView({ key: "test:primed", url: "/get?id=13", readOnce, retryDelaysMs: [] })).toEqual({
|
||||
id: 13,
|
||||
status: "answered",
|
||||
});
|
||||
expect(asked).toBe(0);
|
||||
});
|
||||
|
||||
test("reads one view per key, not one per id string", async () => {
|
||||
const { asked, readOnce } = reader({ answers: [{ id: 15 }, { id: 16 }] });
|
||||
|
||||
await loadRefView({ key: "question:15", url: "/get-question?question_id=15", readOnce, retryDelaysMs: [] });
|
||||
await loadRefView({ key: "suggestion:15", url: "/get-suggestion?suggestion_id=15", readOnce, retryDelaysMs: [] });
|
||||
|
||||
expect(asked).toEqual(["/get-question?question_id=15", "/get-suggestion?suggestion_id=15"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type RefView = { [k: string]: any };
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* What the view is, e.g. `suggestion:12`, so two chips naming the same
|
||||
* one ask once.
|
||||
*/
|
||||
key: string;
|
||||
url: string;
|
||||
/**
|
||||
* How to read it once. The real one asks the app over HTTP.
|
||||
*/
|
||||
readOnce?: (params: { url: string }) => Promise<unknown | null>;
|
||||
/**
|
||||
* Waits between tries, the last one after the final try; tests pass
|
||||
* their own.
|
||||
*/
|
||||
retryDelaysMs?: readonly number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Views already read, by key, so a thread naming one twice asks once, and
|
||||
* the reads in flight. Only what was read is kept: a read that failed is
|
||||
* forgotten, so the next chip naming it asks again instead of sitting on
|
||||
* "(not available)" for the life of the page.
|
||||
*/
|
||||
const known = new Map<string, unknown>();
|
||||
const inFlight = new Map<string, Promise<unknown | null>>();
|
||||
|
||||
/**
|
||||
* Keeps a view the page already has (a question answered in its card, its
|
||||
* chip now saying so) without asking the app for it again.
|
||||
*/
|
||||
export function primeRefView({ key, view }: { key: string; view: unknown }) {
|
||||
known.set(key, view);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a ref's view (`[suggestion:ID]`, `[question:ID]`, ...), once here
|
||||
* and over HTTP after. A read that fails or hangs is tried again, since
|
||||
* the ref can be named before its row is written (a bot writing its own
|
||||
* id, a page woken from a long sleep mid-request), and the reload that
|
||||
* used to be the only cure is what this saves the user.
|
||||
*/
|
||||
export default async function loadRefView<T extends RefView>({
|
||||
key,
|
||||
url,
|
||||
readOnce = readRefViewOnce,
|
||||
retryDelaysMs = AppData.BotRefViewRetryDelaysMs,
|
||||
}: Params): Promise<T | null> {
|
||||
const cached = known.get(key);
|
||||
|
||||
if (cached) return cached as T;
|
||||
|
||||
const reading = inFlight.get(key);
|
||||
|
||||
if (reading) return reading as Promise<T | null>;
|
||||
|
||||
const request = readWithRetries({ url, readOnce, retryDelaysMs })
|
||||
.then((view) => {
|
||||
inFlight.delete(key);
|
||||
|
||||
if (view) known.set(key, view);
|
||||
|
||||
return view as T | null;
|
||||
})
|
||||
.catch(() => {
|
||||
inFlight.delete(key);
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
inFlight.set(key, request);
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
async function readWithRetries({ url, readOnce, retryDelaysMs }: Required<Pick<Params, "url" | "readOnce" | "retryDelaysMs">>) {
|
||||
for (let attempt = 0; ; attempt += 1) {
|
||||
if (attempt) await sleep({ ms: retryDelaysMs[attempt - 1] || 0 });
|
||||
|
||||
const view = await readOnce({ url }).catch(() => null);
|
||||
|
||||
if (view || attempt >= retryDelaysMs.length) return view;
|
||||
}
|
||||
}
|
||||
|
||||
async function readRefViewOnce({ url }: { url: string }): Promise<unknown | null> {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), AppData.BotRefViewTimeoutMs);
|
||||
|
||||
try {
|
||||
const res = await fetchApi<{}, APIResponseObject<RefView>>(url, {
|
||||
method: "GET",
|
||||
fetchOptions: { signal: controller.signal },
|
||||
});
|
||||
|
||||
return res?.success && res.singleRes ? res.singleRes : null;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
function sleep({ ms }: { ms: number }) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -143,7 +143,7 @@ To make this rarer, a super admin can open **Settings, Models**:
|
||||
- Add a provider with your own API key (OpenRouter, OpenAI, Anthropic, Gemini and others), so paid models are there when free ones rest.
|
||||
- Pick a model for the text harness instead of automatic, and keep **fallback** on so the automatic picks still step in.
|
||||
|
||||
A bot's own models (the model icon in its chat header) win over the defaults, and a workspace's win over a bot's.`,
|
||||
A bot's own models (the model icon in its chat header) win over the workspace's and the defaults.`,
|
||||
},
|
||||
{
|
||||
id: "routine-time",
|
||||
|
||||
@@ -8,8 +8,9 @@ import saveWorkspaceHarnessSettings from "@/src/functions/frontend/save-workspac
|
||||
type Props = {
|
||||
bot: BotWithLastMessage;
|
||||
/**
|
||||
* In a workspace the form saves the workspace's models, for every bot
|
||||
* working there.
|
||||
* The workspace the bot is being set up in, when the form is opened
|
||||
* from its conversation there: the bot's own models still win, and the
|
||||
* workspace's are what it inherits.
|
||||
*/
|
||||
workspace_id?: number | null;
|
||||
/**
|
||||
@@ -30,9 +31,10 @@ type Props = {
|
||||
|
||||
/**
|
||||
* The Models settings form (`HarnessSettingsForm`) for one bot. A worker
|
||||
* saves its own picks ("same as the default" drops one). The coordinator
|
||||
* runs on the defaults, so it saves the defaults themselves, which only a
|
||||
* super admin can.
|
||||
* saves its own picks ("same as the default" drops one), in a workspace
|
||||
* too: those win over the workspace's models, which it inherits until
|
||||
* then. The coordinator runs on the defaults (or, in a workspace, on the
|
||||
* workspace's models), which only a super admin can change.
|
||||
*/
|
||||
export default function BotHarnessForm({
|
||||
bot,
|
||||
@@ -62,21 +64,21 @@ export default function BotHarnessForm({
|
||||
notice={notice}
|
||||
onDirtyChange={onDirtyChange}
|
||||
save={async ({ settings }) => {
|
||||
if (workspace_id) {
|
||||
const res = await saveWorkspaceHarnessSettings({
|
||||
workspace_id,
|
||||
settings: settings.map((setting) => ({
|
||||
...setting,
|
||||
inherit: Boolean(setting.inherit),
|
||||
})),
|
||||
});
|
||||
|
||||
if (res.success && res.singleRes) saved(res.singleRes.harnesses, res.msg);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
if (bot.kind == "coordinator") {
|
||||
if (workspace_id) {
|
||||
const res = await saveWorkspaceHarnessSettings({
|
||||
workspace_id,
|
||||
settings: settings.map((setting) => ({
|
||||
...setting,
|
||||
inherit: Boolean(setting.inherit),
|
||||
})),
|
||||
});
|
||||
|
||||
if (res.success && res.singleRes) saved(res.singleRes.harnesses, res.msg);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
const res = await postHarnessApi({
|
||||
path: "save-settings",
|
||||
body: { settings },
|
||||
@@ -89,6 +91,7 @@ export default function BotHarnessForm({
|
||||
|
||||
const res = await saveBotHarnessSettings({
|
||||
bot_id: Number(bot.id),
|
||||
workspace_id: workspace_id || undefined,
|
||||
settings: settings.map((setting) => ({
|
||||
...setting,
|
||||
inherit: Boolean(setting.inherit),
|
||||
|
||||
@@ -56,7 +56,7 @@ export default function BotSettingsSection() {
|
||||
description={
|
||||
is_coordinator
|
||||
? "The coordinator and every bot left on the default use these. The text model chats, plans and drives computers; the others read media, transcribe, speak and make images."
|
||||
: "Uses the default models unless you pick its own. In a workspace, that workspace's models win. The text model chats, plans and drives computers; the others read, transcribe, speak and make images."
|
||||
: "Uses the default models unless you pick its own. In a workspace, its own still win, and it inherits the workspace's until then. The text model chats, plans and drives computers; the others read, transcribe, speak and make images."
|
||||
}
|
||||
/>
|
||||
<BotHarnessForm bot={bot} harnesses={harnesses} />
|
||||
|
||||
@@ -9,9 +9,9 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Which model each harness uses in the workspace. These win over a bot's
|
||||
* own models; "Same as the default" leaves each bot on its own, else the
|
||||
* defaults.
|
||||
* Which model each harness uses in the workspace. These are what its
|
||||
* bots use without models of their own, "Same as the default" leaving
|
||||
* them on the defaults.
|
||||
*/
|
||||
export default function WorkspaceModels({ workspace_id, harnesses: initial }: Props) {
|
||||
const [harnesses, setHarnesses] = useState(initial);
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import WorkspaceTaskSection from "./workspace-task-section";
|
||||
|
||||
const wide: TaskWithNames = {
|
||||
id: 12,
|
||||
created_at: 1,
|
||||
updated_at: 2,
|
||||
workspace_id: 7,
|
||||
title: "Ship the release",
|
||||
status: "doing",
|
||||
};
|
||||
|
||||
const intro: TaskWithNames = {
|
||||
id: 30,
|
||||
created_at: 1,
|
||||
updated_at: 2,
|
||||
bot_id: 3,
|
||||
bot_name: "A",
|
||||
title: "The intro",
|
||||
status: "done",
|
||||
};
|
||||
|
||||
const tasks: TaskWithNames[] = [wide, intro];
|
||||
|
||||
describe("WorkspaceTaskSection", () => {
|
||||
test("its heading, its task count and how many are still open", () => {
|
||||
const html = renderToString(<WorkspaceTaskSection section={{ key: "wide", title: "Workspace-wide", tasks }} onOpenTask={() => {}} />);
|
||||
|
||||
expect(html).toContain("Workspace-wide");
|
||||
expect(html).toContain("2 tasks, 1 open");
|
||||
});
|
||||
|
||||
test("one task reads in the singular", () => {
|
||||
const html = renderToString(
|
||||
<WorkspaceTaskSection section={{ key: "bot:3", title: "Software Engineer", tasks: [intro] }} onOpenTask={() => {}} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Software Engineer");
|
||||
expect(html).toContain("1 task");
|
||||
expect(html).not.toContain("1 tasks");
|
||||
});
|
||||
|
||||
test("a section with nothing open says only how many it holds", () => {
|
||||
const html = renderToString(
|
||||
<WorkspaceTaskSection section={{ key: "bot:3", title: "Software Engineer", tasks: [intro] }} onOpenTask={() => {}} />,
|
||||
);
|
||||
|
||||
expect(html).not.toContain(" open");
|
||||
});
|
||||
|
||||
test("each task is a row of its own, its title and id in it", () => {
|
||||
const html = renderToString(<WorkspaceTaskSection section={{ key: "wide", title: "Workspace-wide", tasks }} onOpenTask={() => {}} />);
|
||||
|
||||
expect(html).toContain("Ship the release");
|
||||
expect(html).toContain("#12");
|
||||
expect(html).toContain("The intro");
|
||||
expect(html).toContain("#30");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import TaskListItem from "@/src/components/general/task-list-item";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import type { WorkspaceTaskSection as Section } from "@/src/utils/task-sections/workspace-task-sections";
|
||||
|
||||
type Props = {
|
||||
section: Section;
|
||||
onOpenTask: (task: TaskWithNames) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One heading and its tasks in the all-tasks modal: the workspace-wide ones
|
||||
* under "Workspace-wide", then one section per bot (`workspaceTaskSections`
|
||||
* decides which and in what order). The heading says how many are open, so a
|
||||
* bot's list reads at a glance.
|
||||
*/
|
||||
export default function WorkspaceTaskSection({ section, onOpenTask }: Props) {
|
||||
const open = section.tasks.filter((task) => task.status != "done" && task.status != "cancelled").length;
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Row className="w-full items-baseline justify-between gap-2!">
|
||||
<Span className="text-[12px] font-bold leading-4 text-ink">{section.title}</Span>
|
||||
<Span className="shrink-0 text-[12px] leading-4 text-ink-secondary">
|
||||
{`${section.tasks.length} task${section.tasks.length == 1 ? "" : "s"}${open ? `, ${open} open` : ""}`}
|
||||
</Span>
|
||||
</Row>
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
{section.tasks.map((task) => (
|
||||
<TaskListItem key={task.id} task={task} onOpen={() => onOpenTask(task)} />
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { OpenTaskStatuses } from "@/src/dict/task-dict";
|
||||
import type { TaskDetail, TaskWithNames } from "@/src/types";
|
||||
import TaskDetailModal from "@/src/components/general/task-detail-modal";
|
||||
import TaskForm from "@/src/components/general/task-form";
|
||||
@@ -15,6 +16,9 @@ import SettingsList from "@/src/pages/admin/settings/(partials)/settings-list";
|
||||
import SettingsStatus from "@/src/pages/admin/settings/(partials)/settings-status";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import compareTasks from "@/src/utils/task-sections/compare-tasks";
|
||||
import shownWorkspaceTasks from "@/src/utils/task-sections/shown-workspace-tasks";
|
||||
import WorkspaceTasksModal from "@/src/pages/admin/workspaces/[workspace_id]/(partials)/workspace-tasks-modal";
|
||||
|
||||
type Props = {
|
||||
workspace_id: number;
|
||||
@@ -31,7 +35,9 @@ type Props = {
|
||||
/**
|
||||
* Every task in a workspace, whichever bot has it: a task belongs to one
|
||||
* bot, which sees only its own, unless it's workspace-wide (every bot there
|
||||
* sees it; the workspace's admin bot sees all).
|
||||
* sees it; the workspace's admin bot sees all). The list starts with the
|
||||
* workspace-wide ones, then each bot's, and shows only the first few: the
|
||||
* rest are a click away in View all.
|
||||
* Add and change one by hand here; the bots
|
||||
* keep it up to date themselves as they work.
|
||||
*/
|
||||
@@ -41,11 +47,45 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<{ error?: boolean; success?: boolean; msg: string }>();
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [showing_all, setShowingAll] = useState(false);
|
||||
const [open_task, setOpenTask] = useState<TaskWithNames | null>(null);
|
||||
const can_manage = canManageCrew({ user_types: pageProps?.user_types });
|
||||
|
||||
/**
|
||||
* What the page lists: the order the all-tasks modal uses, cut to
|
||||
* `AppData.TaskSectionShown` rows.
|
||||
*/
|
||||
const shown = shownWorkspaceTasks({ tasks: items });
|
||||
|
||||
/**
|
||||
* The workspace-wide tasks here a new task can be a subtask of: the open
|
||||
* ones, a closed task having nothing left to split.
|
||||
*/
|
||||
const parents = items
|
||||
.filter(
|
||||
(task) =>
|
||||
!task.bot_id &&
|
||||
Boolean(task.workspace_id) &&
|
||||
(OpenTaskStatuses as readonly string[]).includes(task.status || ""),
|
||||
)
|
||||
.map((task) => ({ id: task.id, title: task.title }));
|
||||
|
||||
const replace = ({ task }: { task: TaskWithNames }) =>
|
||||
setItems((prev) => [task, ...prev.filter((item) => item.id != task.id)].sort(order));
|
||||
setItems((prev) => [task, ...prev.filter((item) => item.id != task.id)].sort(compareTasks));
|
||||
|
||||
/**
|
||||
* Reads the workspace's tasks again: one change can move more than the
|
||||
* task that was open, since a subtask joining or leaving reshapes its
|
||||
* parent's counts.
|
||||
*/
|
||||
const refresh = async () => {
|
||||
const res = await fetchApi<Record<string, unknown>, APIResponseObject<TaskWithNames>>(
|
||||
`/api/admin/tasks/list-tasks?workspace_id=${workspace_id}`,
|
||||
{ method: "GET" },
|
||||
);
|
||||
|
||||
if (res.success && res.payload) setItems(res.payload);
|
||||
};
|
||||
|
||||
const move = async ({ task, next }: { task: TaskWithNames; next: string }) => {
|
||||
if (busy) return;
|
||||
@@ -113,7 +153,7 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
</Row>
|
||||
) : null}
|
||||
<SettingsList is_empty={!items.length} empty="No tasks in this workspace yet.">
|
||||
{items.map((task) => (
|
||||
{shown.map((task) => (
|
||||
<TaskListItem
|
||||
key={task.id}
|
||||
task={task}
|
||||
@@ -124,8 +164,29 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
{items.length > shown.length ? (
|
||||
<Row className="justify-end">
|
||||
<Button
|
||||
title="Every task in this workspace, the workspace-wide ones first"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setShowingAll(true)}
|
||||
className="px-2! text-[12px]"
|
||||
>
|
||||
View all {items.length} tasks
|
||||
</Button>
|
||||
</Row>
|
||||
) : null}
|
||||
<SettingsStatus status={status} />
|
||||
</Stack>
|
||||
<WorkspaceTasksModal
|
||||
open={showing_all}
|
||||
setOpen={setShowingAll}
|
||||
tasks={items}
|
||||
onOpenTask={(task) => setOpenTask(task)}
|
||||
/>
|
||||
<TaskDetailModal
|
||||
task={open_task}
|
||||
can_manage={can_manage}
|
||||
@@ -133,6 +194,7 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
onChanged={({ task, msg }) => {
|
||||
replace({ task });
|
||||
setStatus(msg ? { success: true, msg } : undefined);
|
||||
refresh().catch(() => {});
|
||||
}}
|
||||
onDeleted={({ task_id }) => {
|
||||
setItems((prev) => prev.filter((item) => item.id != task_id));
|
||||
@@ -144,11 +206,12 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
open={adding}
|
||||
setOpen={setAdding}
|
||||
title="Add a task"
|
||||
description="Pick the bot that has it, or make it workspace-wide: every bot here sees it, works on it and logs what it did. Hand it over later to give it to one bot."
|
||||
description="Pick the bot that has it, or make it workspace-wide: every bot here sees it, works on it and logs what it did. Hand it over later to give it to one bot. To split a workspace-wide task into pieces, add each piece with 'Part of' set to it: one bot per piece, and the parent stays open until you verify them."
|
||||
>
|
||||
<TaskForm
|
||||
workspace_id={workspace_id}
|
||||
bots={bots}
|
||||
parents={parents}
|
||||
onCancel={() => setAdding(false)}
|
||||
onSaved={(task, msg) => {
|
||||
replace({ task });
|
||||
@@ -160,15 +223,3 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocked, then doing, then to do, then finished: the order a list reads
|
||||
* in.
|
||||
*/
|
||||
function order(a: TaskWithNames, b: TaskWithNames) {
|
||||
const rank = (task: TaskWithNames) =>
|
||||
task.status == "blocked" ? 0 : task.status == "doing" ? 1 : task.status == "todo" ? 2 : 3;
|
||||
const diff = rank(a) - rank(b);
|
||||
|
||||
return diff != 0 ? diff : Number(b.updated_at || b.id || 0) - Number(a.updated_at || a.id || 0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import workspaceTaskSections from "@/src/utils/task-sections/workspace-task-sections";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import WorkspaceTaskSection from "@/src/pages/admin/workspaces/[workspace_id]/(partials)/workspace-task-section";
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
/**
|
||||
* Every task in the workspace, not only the ones the page lists.
|
||||
*/
|
||||
tasks: TaskWithNames[];
|
||||
onOpenTask: (task: TaskWithNames) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Every task in a workspace, sectioned the way the page's own list is but
|
||||
* without its cap: the workspace-wide ones first, then one section per bot.
|
||||
* A row opens the task's own modal over this one, which stays behind it.
|
||||
*/
|
||||
export default function WorkspaceTasksModal({ open, setOpen, tasks, onOpenTask }: Props) {
|
||||
const sections = workspaceTaskSections({ tasks });
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
open={open}
|
||||
setOpen={setOpen}
|
||||
title="All tasks"
|
||||
description="Everything in this workspace: the workspace-wide tasks first (every bot here works on those), then each bot's own list. Open tasks come before finished ones."
|
||||
>
|
||||
<Stack className="max-h-[60vh] w-full gap-4! items-stretch overflow-y-auto">
|
||||
{sections.map((section) => (
|
||||
<WorkspaceTaskSection key={section.key} section={section} onOpenTask={onOpenTask} />
|
||||
))}
|
||||
</Stack>
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import grabUserBot from "@/src/functions/backend/db/bots/grab-user-bot";
|
||||
import grabWorkspaceBot from "@/src/functions/backend/db/workspaces/grab-workspace-bot";
|
||||
import grabBotHarnessOverview from "@/src/functions/backend/db/harness/grab-bot-harness-overview";
|
||||
import grabHarnessSetting from "@/src/functions/backend/db/harness/grab-harness-setting";
|
||||
import saveBotHarnessSetting from "@/src/functions/backend/db/harness/save-bot-harness-setting";
|
||||
@@ -43,7 +44,7 @@ export const handler: BunextAPIRouteHandler<
|
||||
throw new AppError(`Only an admin can do that.`);
|
||||
}
|
||||
|
||||
const { bot_id, settings } = parseWithSchema({
|
||||
const { bot_id, workspace_id, settings } = parseWithSchema({
|
||||
schema: SaveBotHarnessSettingsRequestSchema,
|
||||
data: body,
|
||||
});
|
||||
@@ -92,10 +93,24 @@ export const handler: BunextAPIRouteHandler<
|
||||
ip_address: grabRequestIP(req),
|
||||
});
|
||||
|
||||
/**
|
||||
* The workspace the form was opened in, when the user works there:
|
||||
* what the bot inherits there, shown with the fresh overview. The
|
||||
* save is the bot's own either way.
|
||||
*/
|
||||
const membership = workspace_id
|
||||
? await grabWorkspaceBot({ workspace_id, bot_id, user_id: user.id })
|
||||
: null;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg: `Saved.`,
|
||||
singleRes: await grabBotHarnessOverview({ bot_id: bot.id }),
|
||||
singleRes: await grabBotHarnessOverview({
|
||||
bot_id: bot.id,
|
||||
workspace_id: membership?.workspace.id
|
||||
? Number(membership.workspace.id)
|
||||
: undefined,
|
||||
}),
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
|
||||
import detachSubtask from "@/src/functions/backend/db/tasks/detach-subtask";
|
||||
import grabTask from "@/src/functions/backend/db/tasks/grab-task";
|
||||
import { DetachSubtaskRequestSchema } from "@/src/schemas/task-schema";
|
||||
import type { TaskDetail } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* Takes a subtask out of its workspace-wide task, leaving a task of its own
|
||||
* bot in the workspace (`detachSubtask`): the only way a parent with subtasks
|
||||
* is ever moved, and the button a crew manager has for it. Crew managers
|
||||
* only, like every other change to a task by hand. Returns the task as it
|
||||
* is now.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (isReadOnlyUser({ user_types: user_types || [] })) {
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
if (!canManageCrew({ user_types: user_types || [] })) {
|
||||
throw new AppError(`Only an admin can unlink a subtask from its task.`);
|
||||
}
|
||||
|
||||
const { task_id } = parseWithSchema({ schema: DetachSubtaskRequestSchema, data: body });
|
||||
|
||||
await assertUserReachesTask({ user_id: user.id, task_id });
|
||||
await detachSubtask({ task_id, by_name: user.first_name || user.username || "The user" });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: await grabTask({ user_id: user.id, task_id }),
|
||||
msg: `It's a task of its own now.`,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
|
||||
import linkSubtask from "@/src/functions/backend/db/tasks/link-subtask";
|
||||
import { LinkSubtaskRequestSchema } from "@/src/schemas/task-schema";
|
||||
import type { TaskDetail } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* Attaches a bot's open task in a workspace to a workspace-wide task there,
|
||||
* so the manager of the work sees who took which piece (`linkSubtask`): what
|
||||
* a bot does with `update_task`'s `parent_task_id`, and what a crew manager
|
||||
* has a picker for. Both ends are reached-checked, since the id alone would
|
||||
* let someone join another crew's task. Returns the task as it is now.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (isReadOnlyUser({ user_types: user_types || [] })) {
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
if (!canManageCrew({ user_types: user_types || [] })) {
|
||||
throw new AppError(`Only an admin can make a task a subtask of another.`);
|
||||
}
|
||||
|
||||
const { task_id, parent_task_id } = parseWithSchema({ schema: LinkSubtaskRequestSchema, data: body });
|
||||
|
||||
await assertUserReachesTask({ user_id: user.id, task_id });
|
||||
await assertUserReachesTask({ user_id: user.id, task_id: parent_task_id });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: await linkSubtask({
|
||||
user_id: user.id,
|
||||
task_id,
|
||||
parent_task_id,
|
||||
by_name: user.first_name || user.username || "The user",
|
||||
}),
|
||||
msg: `It's a subtask of task #${parent_task_id} now.`,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -55,11 +55,19 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = asy
|
||||
};
|
||||
}
|
||||
|
||||
const { bot_id, workspace_id, workspace_wide, title, description, status } = parseWithSchema({
|
||||
const { bot_id, workspace_id, workspace_wide, parent_task_id, title, description, status } = parseWithSchema({
|
||||
schema: CreateTaskRequestSchema,
|
||||
data,
|
||||
});
|
||||
|
||||
/**
|
||||
* A subtask hangs off a task the user has to reach too, or they could
|
||||
* split another crew's task by id.
|
||||
*/
|
||||
if (parent_task_id) {
|
||||
await assertUserReachesTask({ user_id: user.id, task_id: parent_task_id });
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: await createTask({
|
||||
@@ -67,11 +75,12 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = asy
|
||||
bot_id,
|
||||
workspace_id,
|
||||
workspace_wide,
|
||||
parent_task_id,
|
||||
title,
|
||||
description,
|
||||
status: status as never,
|
||||
}),
|
||||
msg: `Task added.`,
|
||||
msg: parent_task_id ? `Subtask added.` : `Task added.`,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
|
||||
import grabSubtaskParents from "@/src/functions/backend/db/tasks/grab-subtask-parents";
|
||||
import { TaskIdRequestSchema } from "@/src/schemas/task-schema";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* What a bot's task can be made a subtask of: its workspace's open
|
||||
* workspace-wide tasks (`grabSubtaskParents`), loaded when the picker opens
|
||||
* so the page's props stay small. Crew managers only, since it's their
|
||||
* picker.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<TaskWithNames>> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (isReadOnlyUser({ user_types: user_types || [] })) {
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
if (!canManageCrew({ user_types: user_types || [] })) {
|
||||
throw new AppError(`Only an admin can make a task a subtask of another.`);
|
||||
}
|
||||
|
||||
const { task_id } = parseWithSchema({ schema: TaskIdRequestSchema, data: body });
|
||||
const task = await assertUserReachesTask({ user_id: user.id, task_id });
|
||||
|
||||
return { success: true, payload: await grabSubtaskParents({ user_id: user.id, task }) };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -19,8 +19,8 @@ import type {
|
||||
|
||||
/**
|
||||
* Saves which model each harness uses in one of the session user's
|
||||
* workspaces. A workspace's models win over its bots' own, for the
|
||||
* coordinator too.
|
||||
* workspaces. They are what its bots use without models of their own, the
|
||||
* coordinator there too.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<
|
||||
APIResponseObject<BotHarnessOverviewPayload>
|
||||
|
||||
@@ -93,6 +93,12 @@ export const SaveHarnessSettingsRequestSchema = z.object({
|
||||
*/
|
||||
export const SaveBotHarnessSettingsRequestSchema = z.object({
|
||||
bot_id: z.coerce.number().int().positive(),
|
||||
/**
|
||||
* The workspace the form was opened in. It changes nothing: the save
|
||||
* is the bot's own, which wins there, and the workspace's models are
|
||||
* what it inherits. Used to answer with the fresh overview in context.
|
||||
*/
|
||||
workspace_id: z.coerce.number().int().positive().optional(),
|
||||
settings: z
|
||||
.array(
|
||||
SaveHarnessSettingsRequestSchema.shape.settings.element.extend({
|
||||
|
||||
@@ -19,6 +19,11 @@ const scope = {
|
||||
|
||||
export const CreateTaskRequestSchema = z.object({
|
||||
...scope,
|
||||
/**
|
||||
* The workspace-wide task it is a part of (`assertSubtaskParent`), when
|
||||
* it is one.
|
||||
*/
|
||||
parent_task_id: z.number().int().positive().optional(),
|
||||
title: z.string().trim().min(1).max(AppData.TaskTitleMaxLength),
|
||||
description: z.string().max(AppData.TaskDescriptionMaxLength).optional(),
|
||||
status: z.enum(status_values).optional(),
|
||||
@@ -36,6 +41,21 @@ export const DeleteTaskRequestSchema = z.object({
|
||||
task_id: z.number().int().positive(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Taking a part out of its workspace-wide task (`detachSubtask`).
|
||||
*/
|
||||
export const DetachSubtaskRequestSchema = z.object({
|
||||
task_id: z.number().int().positive(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Attaching a bot's task to a workspace-wide one (`linkSubtask`).
|
||||
*/
|
||||
export const LinkSubtaskRequestSchema = z.object({
|
||||
task_id: z.number().int().positive(),
|
||||
parent_task_id: z.number().int().positive(),
|
||||
});
|
||||
|
||||
export const TaskNoteRequestSchema = z.object({
|
||||
task_id: z.number().int().positive(),
|
||||
text: z.string().trim().min(1).max(AppData.TaskNoteMaxLength),
|
||||
|
||||
+19
-2
@@ -209,6 +209,11 @@ export type TaskWithNames = BUN_SQLITE_COBBLE_TASKS & {
|
||||
bot_face?: string | null;
|
||||
bot_image_media_id?: number | null;
|
||||
workspace_name?: string | null;
|
||||
/**
|
||||
* The workspace's picture, for a workspace-wide task's mark: it is
|
||||
* nobody's, so it wears the workspace's face rather than a bot's.
|
||||
*/
|
||||
workspace_image_media_id?: number | null;
|
||||
/**
|
||||
* Its newest note's text, for the row's second line.
|
||||
*/
|
||||
@@ -221,6 +226,17 @@ export type TaskWithNames = BUN_SQLITE_COBBLE_TASKS & {
|
||||
* How many files it carries.
|
||||
*/
|
||||
media_count?: number | null;
|
||||
/**
|
||||
* The workspace-wide task it is a part of, when it is one.
|
||||
*/
|
||||
parent_title?: string | null;
|
||||
parent_status?: string | null;
|
||||
/**
|
||||
* Its parts, when it is workspace-wide: how many and how many still
|
||||
* need work.
|
||||
*/
|
||||
subtask_count?: number | null;
|
||||
subtask_open_count?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -253,14 +269,15 @@ export type TaskNote = BUN_SQLITE_COBBLE_TASK_NOTES & {
|
||||
};
|
||||
|
||||
/**
|
||||
* A task with its notes and files and who added it: what the task modal
|
||||
* renders.
|
||||
* A task with its notes and files and who added it, and its parts when it
|
||||
* is workspace-wide: what the task modal renders.
|
||||
*/
|
||||
export type TaskDetail = TaskWithNames & {
|
||||
created_by_bot_name?: string | null;
|
||||
created_by_user_name?: string | null;
|
||||
notes: TaskNote[];
|
||||
files: TaskFile[];
|
||||
subtasks: TaskWithNames[];
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import askPreviousSessionId from "./ask-previous-session-id";
|
||||
|
||||
describe("askPreviousSessionId", () => {
|
||||
test("a session the bot was in before the request is the way back", () => {
|
||||
expect(askPreviousSessionId({ previous_session_id: 12, session_id: 15 })).toBe(12);
|
||||
});
|
||||
|
||||
test("a bot with no session before the request has nothing to go back to", () => {
|
||||
expect(askPreviousSessionId({ previous_session_id: null, session_id: 15 })).toBeNull();
|
||||
expect(askPreviousSessionId({ session_id: 15 })).toBeNull();
|
||||
expect(askPreviousSessionId({ previous_session_id: 0, session_id: 15 })).toBeNull();
|
||||
});
|
||||
|
||||
test("the request's own session is never its previous one", () => {
|
||||
expect(askPreviousSessionId({ previous_session_id: 15, session_id: 15 })).toBeNull();
|
||||
});
|
||||
|
||||
test("ids arriving as text are read as numbers", () => {
|
||||
expect(askPreviousSessionId({ previous_session_id: "12", session_id: "15" })).toBe(12);
|
||||
expect(askPreviousSessionId({ previous_session_id: "15", session_id: "15" })).toBeNull();
|
||||
expect(askPreviousSessionId({ previous_session_id: "", session_id: "15" })).toBeNull();
|
||||
});
|
||||
|
||||
test("no session on screen leaves nothing to lead back to", () => {
|
||||
expect(askPreviousSessionId({ previous_session_id: 12, session_id: null })).toBe(12);
|
||||
expect(askPreviousSessionId({ previous_session_id: null, session_id: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
type Params = {
|
||||
/**
|
||||
* The session the conversation was in before the request took one.
|
||||
*/
|
||||
previous_session_id?: number | string | null;
|
||||
/**
|
||||
* The session the request took: a session is never its own previous one
|
||||
* (`startBotSession` keeps an empty active session as it is), and a
|
||||
* request from a bot with no session before it has none at all.
|
||||
*/
|
||||
session_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The session a crew request's bar leads back to, or null when there is
|
||||
* nothing to lead back to. Null hides the bar: a bot that had no session
|
||||
* before the request opened one has no conversation to return to.
|
||||
*/
|
||||
export default function askPreviousSessionId({
|
||||
previous_session_id,
|
||||
session_id,
|
||||
}: Params): number | null {
|
||||
const previous = Number(previous_session_id) || null;
|
||||
const current = Number(session_id) || null;
|
||||
|
||||
if (!previous) return null;
|
||||
if (previous === current) return null;
|
||||
|
||||
return previous;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
|
||||
/**
|
||||
* Blocked, then doing, then to do, then finished, each newest first: the
|
||||
* order a task list reads in.
|
||||
*/
|
||||
export default function compareTasks(a: TaskWithNames, b: TaskWithNames) {
|
||||
const rank = (task: TaskWithNames) =>
|
||||
task.status == "blocked" ? 0 : task.status == "doing" ? 1 : task.status == "todo" ? 2 : 3;
|
||||
const diff = rank(a) - rank(b);
|
||||
|
||||
return diff != 0 ? diff : Number(b.updated_at || b.id || 0) - Number(a.updated_at || a.id || 0);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import shownWorkspaceTasks from "./shown-workspace-tasks";
|
||||
|
||||
function task(fields: Partial<TaskWithNames>): TaskWithNames {
|
||||
return { id: 1, created_at: 1, updated_at: 2, status: "todo", ...fields };
|
||||
}
|
||||
|
||||
describe("shownWorkspaceTasks", () => {
|
||||
test("keeps the workspace-wide tasks before any bot's, then cuts to the cap", () => {
|
||||
const tasks = [
|
||||
task({ id: 1, bot_id: 3, bot_name: "A", title: "bot 1" }),
|
||||
task({ id: 2, workspace_id: 7, title: "wide 1" }),
|
||||
task({ id: 3, bot_id: 4, bot_name: "B", title: "bot 2" }),
|
||||
task({ id: 4, workspace_id: 7, title: "wide 2" }),
|
||||
];
|
||||
|
||||
expect(shownWorkspaceTasks({ tasks, shown: 3 }).map((it) => it.id)).toEqual([2, 4, 1]);
|
||||
});
|
||||
|
||||
test("a list shorter than the cap is left whole", () => {
|
||||
const tasks = [task({ id: 1, workspace_id: 7 }), task({ id: 2, bot_id: 3, bot_name: "A" })];
|
||||
|
||||
expect(shownWorkspaceTasks({ tasks }).map((it) => it.id)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
test("the default cap is the app setting", () => {
|
||||
const tasks = Array.from({ length: AppData.TaskSectionShown + 3 }, (_, index) =>
|
||||
task({ id: index + 1, workspace_id: 7, updated_at: 100 - index }),
|
||||
);
|
||||
|
||||
expect(shownWorkspaceTasks({ tasks })).toHaveLength(AppData.TaskSectionShown);
|
||||
});
|
||||
|
||||
test("no tasks, nothing to show", () => {
|
||||
expect(shownWorkspaceTasks({ tasks: [] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import workspaceTaskSections from "./workspace-task-sections";
|
||||
|
||||
type Params = {
|
||||
tasks: TaskWithNames[];
|
||||
/**
|
||||
* How many to keep; `AppData.TaskSectionShown` unless a caller says.
|
||||
*/
|
||||
shown?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The rows a workspace page lists before its View all button: the
|
||||
* workspace-wide tasks first, then each bot's own, open ones first, cut to
|
||||
* the cap.
|
||||
*/
|
||||
export default function shownWorkspaceTasks({ tasks, shown = AppData.TaskSectionShown }: Params): TaskWithNames[] {
|
||||
return workspaceTaskSections({ tasks })
|
||||
.flatMap((section) => section.tasks)
|
||||
.slice(0, shown);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import workspaceTaskSections from "./workspace-task-sections";
|
||||
|
||||
function task(fields: Partial<TaskWithNames>): TaskWithNames {
|
||||
return { id: 1, created_at: 1, updated_at: 2, status: "todo", ...fields };
|
||||
}
|
||||
|
||||
describe("workspaceTaskSections", () => {
|
||||
test("the workspace-wide tasks come first, then one section per bot by name", () => {
|
||||
const sections = workspaceTaskSections({
|
||||
tasks: [
|
||||
task({ id: 5, bot_id: 9, bot_name: "SEO Expert", title: "Meta" }),
|
||||
task({ id: 2, workspace_id: 3, title: "Ship it" }),
|
||||
task({ id: 4, bot_id: 3, bot_name: "Software Engineer", title: "Header" }),
|
||||
task({ id: 6, bot_id: 3, bot_name: "Software Engineer", title: "Footer" }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(sections.map((section) => section.title)).toEqual([
|
||||
"Workspace-wide",
|
||||
"SEO Expert",
|
||||
"Software Engineer",
|
||||
]);
|
||||
expect(sections[1]?.tasks.map((it) => it.id)).toEqual([5]);
|
||||
expect(sections[2]?.tasks.map((it) => it.id)).toEqual([4, 6]);
|
||||
});
|
||||
|
||||
test("a workspace with no wide task starts with its bots", () => {
|
||||
const sections = workspaceTaskSections({ tasks: [task({ id: 4, bot_id: 3, bot_name: "Software Engineer" })] });
|
||||
|
||||
expect(sections.map((section) => section.key)).toEqual(["bot:3"]);
|
||||
});
|
||||
|
||||
test("a bot without a name is named by its id", () => {
|
||||
const sections = workspaceTaskSections({ tasks: [task({ id: 4, bot_id: 3 })] });
|
||||
|
||||
expect(sections[0]?.title).toBe("Bot 3");
|
||||
});
|
||||
|
||||
test("each section is open first, blocked before doing before to do", () => {
|
||||
const sections = workspaceTaskSections({
|
||||
tasks: [
|
||||
task({ id: 1, bot_id: 3, bot_name: "A", status: "done" }),
|
||||
task({ id: 2, bot_id: 3, bot_name: "A", status: "todo" }),
|
||||
task({ id: 3, bot_id: 3, bot_name: "A", status: "blocked" }),
|
||||
task({ id: 4, bot_id: 3, bot_name: "A", status: "doing" }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(sections[0]?.tasks.map((it) => it.id)).toEqual([3, 4, 2, 1]);
|
||||
});
|
||||
|
||||
test("no tasks, no sections", () => {
|
||||
expect(workspaceTaskSections({ tasks: [] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import compareTasks from "./compare-tasks";
|
||||
|
||||
export type WorkspaceTaskSection = {
|
||||
/**
|
||||
* `wide`, or `bot:<id>`: stable across renders and renames.
|
||||
*/
|
||||
key: string;
|
||||
title: string;
|
||||
tasks: TaskWithNames[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A workspace's tasks as the page lists them: the workspace-wide ones first
|
||||
* (nobody's: every bot there works on them), then each bot's own, one
|
||||
* section per bot in the order of their names, the tasks in each in the
|
||||
* usual open-first order. Empty sections are left out.
|
||||
*/
|
||||
export default function workspaceTaskSections({ tasks }: { tasks: TaskWithNames[] }): WorkspaceTaskSection[] {
|
||||
const wide = tasks.filter((task) => !task.bot_id).sort(compareTasks);
|
||||
|
||||
const by_bot = new Map<number, WorkspaceTaskSection>();
|
||||
|
||||
for (const task of tasks) {
|
||||
if (!task.bot_id) continue;
|
||||
|
||||
const bot_id = Number(task.bot_id);
|
||||
const section = by_bot.get(bot_id) || {
|
||||
key: `bot:${bot_id}`,
|
||||
title: task.bot_name || `Bot ${bot_id}`,
|
||||
tasks: [],
|
||||
};
|
||||
|
||||
section.tasks.push(task);
|
||||
by_bot.set(bot_id, section);
|
||||
}
|
||||
|
||||
const sections = [...by_bot.values()]
|
||||
.map((section) => ({ ...section, tasks: section.tasks.sort(compareTasks) }))
|
||||
.sort((a, b) => a.title.localeCompare(b.title));
|
||||
|
||||
return wide.length ? [{ key: "wide", title: "Workspace-wide", tasks: wide }, ...sections] : sections;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import subtaskAttachProblem from "./subtask-attach-problem";
|
||||
|
||||
const parent = {
|
||||
id: 12,
|
||||
title: "Ship the release",
|
||||
bot_id: null,
|
||||
workspace_id: 4,
|
||||
parent_task_id: null,
|
||||
status: "doing",
|
||||
};
|
||||
|
||||
const task = {
|
||||
id: 30,
|
||||
title: "The intro",
|
||||
bot_id: 7,
|
||||
workspace_id: 4,
|
||||
parent_task_id: null,
|
||||
status: "todo",
|
||||
};
|
||||
|
||||
describe("subtaskAttachProblem", () => {
|
||||
test("an open task of a bot in the parent's workspace can join it", () => {
|
||||
expect(subtaskAttachProblem({ task, parent })).toBeNull();
|
||||
});
|
||||
|
||||
test("a task that isn't there can't join anything", () => {
|
||||
expect(subtaskAttachProblem({ task: null, parent })).toContain("doesn't exist");
|
||||
});
|
||||
|
||||
test("a task can't be a subtask of itself", () => {
|
||||
expect(subtaskAttachProblem({ task: parent, parent })).toContain("subtask of itself");
|
||||
});
|
||||
|
||||
test("a subtask of another task is unlinked first", () => {
|
||||
expect(subtaskAttachProblem({ task: { ...task, parent_task_id: 9 }, parent })).toContain(
|
||||
"already a subtask of task #9",
|
||||
);
|
||||
});
|
||||
|
||||
test("a task with parts of its own can't become one", () => {
|
||||
expect(subtaskAttachProblem({ task, parent, task_subtasks: 2 })).toContain("a subtask can't be a parent");
|
||||
});
|
||||
|
||||
test("only a bot's task in a workspace can join one", () => {
|
||||
expect(subtaskAttachProblem({ task: { ...task, bot_id: null }, parent })).toContain("nothing to be a subtask of");
|
||||
expect(subtaskAttachProblem({ task: { ...task, workspace_id: null }, parent })).toContain(
|
||||
"nothing to be a subtask of",
|
||||
);
|
||||
});
|
||||
|
||||
test("a closed task can't become a subtask", () => {
|
||||
expect(subtaskAttachProblem({ task: { ...task, status: "done" }, parent })).toContain("closed task");
|
||||
});
|
||||
|
||||
test("the parent still has to be a splittable workspace-wide task", () => {
|
||||
expect(subtaskAttachProblem({ task, parent: { ...parent, bot_id: 7 } })).toContain("isn't workspace-wide");
|
||||
expect(subtaskAttachProblem({ task: { ...task, workspace_id: 5 }, parent })).toContain("same workspace");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { OpenTaskStatuses } from "@/src/dict/task-dict";
|
||||
import subtaskLinkProblem from "./subtask-link-problem";
|
||||
|
||||
type TaskLike = {
|
||||
id?: number | string | null;
|
||||
title?: string | null;
|
||||
bot_id?: number | string | null;
|
||||
workspace_id?: number | string | null;
|
||||
parent_task_id?: number | string | null;
|
||||
status?: string | null;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The task that would become a subtask, read as it is.
|
||||
*/
|
||||
task?: TaskLike | null;
|
||||
/**
|
||||
* The workspace-wide task it would join.
|
||||
*/
|
||||
parent?: TaskLike | null;
|
||||
/**
|
||||
* How many subtasks the task itself has of its own (`grabSubtaskCounts`):
|
||||
* a task with subtasks can't become one, since splitting goes one level
|
||||
* deep.
|
||||
*/
|
||||
task_subtasks?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why that task can't be attached to that workspace-wide one, or null when
|
||||
* it can. The parent has to be a wide, open task that isn't itself a subtask
|
||||
* (`subtaskLinkProblem`), and this side has to be an open task of one bot in
|
||||
* the same workspace that has no subtasks of its own: one level of splitting.
|
||||
*/
|
||||
export default function subtaskAttachProblem({ task, parent, task_subtasks }: Params): string | null {
|
||||
if (!task?.id) return `That task doesn't exist, so it can't become a subtask of anything.`;
|
||||
|
||||
const label = `Task #${task.id}${task.title ? ` "${task.title}"` : ""}`;
|
||||
|
||||
if (Number(task.id) == Number(parent?.id || 0)) {
|
||||
return `${label} can't be a subtask of itself.`;
|
||||
}
|
||||
|
||||
if (task.parent_task_id) {
|
||||
return `${label} is already a subtask of task #${task.parent_task_id}: unlink it from that one first.`;
|
||||
}
|
||||
|
||||
if (Number(task_subtasks || 0)) {
|
||||
return `${label} has ${task_subtasks} subtask(s) of its own: a subtask can't be a parent, so unlink them first.`;
|
||||
}
|
||||
|
||||
if (!task.bot_id || !task.workspace_id) {
|
||||
return `${label} isn't a bot's task in a workspace, so it has nothing to be a subtask of: only a task a bot has there can join a workspace-wide one.`;
|
||||
}
|
||||
|
||||
if (!OpenTaskStatuses.includes(task.status as (typeof OpenTaskStatuses)[number])) {
|
||||
return `${label} is ${task.status}: a closed task can't become a subtask.`;
|
||||
}
|
||||
|
||||
return subtaskLinkProblem({ parent, bot_id: task.bot_id, workspace_id: task.workspace_id });
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import subtaskDeleteProblem from "./subtask-delete-problem";
|
||||
|
||||
describe("subtaskDeleteProblem", () => {
|
||||
test("a task whose parts are all finished can go", () => {
|
||||
expect(subtaskDeleteProblem({ task: { id: 12, title: "Ship the release" }, open_subtasks: 0 })).toBeNull();
|
||||
});
|
||||
|
||||
test("open parts hold the delete back", () => {
|
||||
expect(subtaskDeleteProblem({ task: { id: 12, title: "Ship the release" }, open_subtasks: 2 })).toContain(
|
||||
"still has 2 open subtasks",
|
||||
);
|
||||
|
||||
expect(subtaskDeleteProblem({ task: { id: 12 }, open_subtasks: 1 })).toContain("1 open subtask:");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
type TaskLike = {
|
||||
id?: number | string | null;
|
||||
title?: string | null;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
task: TaskLike;
|
||||
/**
|
||||
* How many of its subtasks are still open (to do, doing or blocked).
|
||||
*/
|
||||
open_subtasks: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why a workspace-wide task can't be deleted, or null when it can. Deleting
|
||||
* it takes its subtasks with it, so none of them may be work someone is still
|
||||
* on: finish or cancel them first.
|
||||
*/
|
||||
export default function subtaskDeleteProblem({ task, open_subtasks }: Params): string | null {
|
||||
if (open_subtasks <= 0) return null;
|
||||
|
||||
const label = `Task #${task.id}${task.title ? ` "${task.title}"` : ""}`;
|
||||
|
||||
return `${label} still has ${open_subtasks} open subtask${open_subtasks == 1 ? "" : "s"}: finish, cancel or unlink ${open_subtasks == 1 ? "it" : "them"} before deleting it.`;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import subtaskLinkProblem from "./subtask-link-problem";
|
||||
|
||||
const parent = {
|
||||
id: 12,
|
||||
title: "Ship the release",
|
||||
bot_id: null,
|
||||
workspace_id: 4,
|
||||
parent_task_id: null,
|
||||
status: "doing",
|
||||
};
|
||||
|
||||
describe("subtaskLinkProblem", () => {
|
||||
test("a bot's task in the parent's workspace can be a subtask of it", () => {
|
||||
expect(subtaskLinkProblem({ parent, bot_id: 7, workspace_id: 4 })).toBeNull();
|
||||
});
|
||||
|
||||
test("a parent that isn't there is refused", () => {
|
||||
expect(subtaskLinkProblem({ parent: null, bot_id: 7, workspace_id: 4 })).toContain("doesn't exist");
|
||||
});
|
||||
|
||||
test("only a workspace-wide task can be split", () => {
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, bot_id: 7 }, bot_id: 7, workspace_id: 4 }),
|
||||
).toContain("isn't workspace-wide");
|
||||
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, workspace_id: null }, bot_id: 7, workspace_id: 4 }),
|
||||
).toContain("isn't workspace-wide");
|
||||
});
|
||||
|
||||
test("a subtask can't be split again", () => {
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, parent_task_id: 3 }, bot_id: 7, workspace_id: 4 }),
|
||||
).toContain("can't be split again");
|
||||
|
||||
// A real subtask has a bot, which is no reason to call it something else.
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, bot_id: 7, parent_task_id: 3 }, bot_id: 8, workspace_id: 4 }),
|
||||
).toContain("can't be split again");
|
||||
});
|
||||
|
||||
test("a subtask belongs to one bot", () => {
|
||||
expect(subtaskLinkProblem({ parent, bot_id: null, workspace_id: 4 })).toContain("belongs to one bot");
|
||||
});
|
||||
|
||||
test("a subtask stays in its parent's workspace", () => {
|
||||
expect(subtaskLinkProblem({ parent, bot_id: 7, workspace_id: 9 })).toContain("same workspace");
|
||||
expect(subtaskLinkProblem({ parent, bot_id: 7, workspace_id: null })).toContain("same workspace");
|
||||
});
|
||||
|
||||
test("a closed task can't be split", () => {
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, status: "done" }, bot_id: 7, workspace_id: 4 }),
|
||||
).toContain("can't be split");
|
||||
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, status: "cancelled" }, bot_id: 7, workspace_id: 4 }),
|
||||
).toContain("can't be split");
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user