Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c924ff9776 | ||
|
|
5d79c379dd | ||
|
|
ebc9ade7e0 | ||
|
|
ea4b5c1bf2 | ||
|
|
4063cd3b22 |
@@ -96,7 +96,8 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
|
||||
- **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.
|
||||
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
|
||||
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
|
||||
- **File preview:** every file link (chips, attachments, files modal, task files, `/admin/files`) is a `FilePreviewLink`: a plain click opens `FilePreviewModal` (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.
|
||||
- **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.
|
||||
- **Asking before acting:** `ask_user` (`QuestionsNote`) puts up to `AppData.BotQuestionMaxQuestions` multiple-choice questions (`single` = radios, `multiple` = checkboxes, optional typed "Other") on one card, once per run -> `bot_questions` -> `[question:ID]` chip opening `BotQuestionCard`; the message needs the user. Answers are checked against the questions (`checkBotQuestionAnswers`) and stored, then sent as the user's chat message (`botQuestionAnswersText`); Skip says so. Replies and user-started tasks only: never routines, hook calls or chatroom sessions (no one sees those).
|
||||
- **Quoting:** selected text quotes into the composer through `quotableText`, which reads each ref chip as one inline label (`MarkdownLink` wraps chips with `QuoteInlineAttribute`; `Selection.toString()` broke a quote into a paragraph per chip).
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
"@modelcontextprotocol/sdk": "^1.32.1",
|
||||
"@moduletrace/bun-sqlite": "^1.3.0",
|
||||
"@moduletrace/bunext": "^1.3.5",
|
||||
"@moduletrace/twui": "^0.1.9",
|
||||
"@moduletrace/twui": "^0.1.10",
|
||||
"@tiptap/extension-bubble-menu": "3.32.0",
|
||||
"@tiptap/extension-mention": "3.32.0",
|
||||
"@tiptap/extension-placeholder": "3.32.0",
|
||||
@@ -279,7 +279,7 @@
|
||||
|
||||
"@moduletrace/bunext": ["@moduletrace/[email protected]", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Fbunext/-/1.3.5/bunext-1.3.5.tgz", { "dependencies": { "@tailwindcss/postcss": "^4.3.3", "@types/bun": "1.3.14", "@types/node": "^24.10.0", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", "bun-plugin-tailwind": "^0.1.2", "chalk": "^5.6.2", "chokidar": "^5.0.0", "commander": "^14.0.2", "esbuild": "^0.28.2", "lightningcss-wasm": "^1.32.0", "lodash": "^4.18.1", "ora": "^9.0.0", "postcss": "^8.5.30", "react": "^19.3.0", "react-dom": "^19.3.0", "tailwindcss": "^4.3.3", "typescript": "^5.0.0", "uuid": "^14.0.2" }, "bin": { "bunext": "dist/commands/index.js" } }, "sha512-Es59Dvq3/eF726+SOHPiKtlJ87UFmyJZI4gpeciW/fA/3ZwOWws2Mm3oD6eZnOj9BP/zlBKOWA9DPTl35IP3lg=="],
|
||||
|
||||
"@moduletrace/twui": ["@moduletrace/[email protected].9", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.9/twui-0.1.9.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-HN/emdqSCxQclzFEojDsaujjgO+dkQy4wC7Rk6gCQH/fK2Hv0CQ5DLOdOB8oDE7nu+m7/0qKo878UeufBbEotg=="],
|
||||
"@moduletrace/twui": ["@moduletrace/[email protected].10", "https://git.tben.me/api/packages/Moduletrace/npm/%40moduletrace%2Ftwui/-/0.1.10/twui-0.1.10.tgz", { "dependencies": { "lodash": "^4.18.1", "tailwind-merge": "^3.7.0" }, "peerDependencies": { "ace-builds": "^1.40.0", "lucide-react": ">=0.577.0", "next-mdx-remote": "^6.0.0", "openai": ">=6.0.0", "react": ">=18", "react-dom": ">=18", "react-markdown": ">=9.0.0", "rehype-prism-plus": "^2.0.0", "remark-gfm": "^4.0.0", "tailwindcss": "^4" }, "optionalPeers": ["ace-builds", "next-mdx-remote", "openai", "react-markdown", "rehype-prism-plus", "remark-gfm"] }, "sha512-eShpG6jK7qr2+oG7Pq4PvHnvAOUPkbxMCf9BVfiuJqUdtuaQSo2jqcggGAonGDu4p8Nn/KWTd2KrypE/+W4wTg=="],
|
||||
|
||||
"@next/mdx": ["@next/[email protected]", "", { "dependencies": { "source-map": "^0.7.0" }, "peerDependencies": { "@mdx-js/loader": ">=0.15.0", "@mdx-js/react": ">=0.15.0" }, "optionalPeers": ["@mdx-js/loader", "@mdx-js/react"] }, "sha512-Vpfuf928ACvx4AOdDXWx/cj13Ak6xlvMn3QCkjvfQMmLnQWCesQTeY01CPDbIyZvjY+NOwP7bvbvJ2ghkj/3GA=="],
|
||||
|
||||
|
||||
@@ -592,6 +592,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
fieldDescription: `JSON \`[{ name, ok }]\`: every tool call the run behind a bot message made (names only, never arguments), told to the bot with the message in later turns so it can't build on work it never did. Null: not recorded (user messages, interim ones, older messages)`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "task_ids",
|
||||
fieldDescription: `JSON \`[id, ...]\`: the tracker tasks (\`tasks\`) the run behind a bot message worked on (created, moved along, read in full or handed over, and the task a handed-over job was started for), shown as chips under the message so the user sees which tasks it's about. Not foreign keys: a deleted task's chip is left out. Null: none`,
|
||||
dataType: "TEXT",
|
||||
},
|
||||
{
|
||||
fieldName: "from_chatroom_id",
|
||||
fieldDescription: `Set on the message that brings a chatroom's outcome back into the asking bot's conversation: the room. Such a message is stored as the user's side of the conversation (the bot answers it) but shown as coming from the coordinator, and the model reads it as data. Not a foreign key`,
|
||||
|
||||
@@ -412,6 +412,10 @@ export type BUN_SQLITE_COBBLE_BOT_MESSAGES = {
|
||||
* JSON `[{ name, ok }]`: every tool call the run behind a bot message made (names only, never arguments), told to the bot with the message in later turns so it can't build on work it never did. Null: not recorded (user messages, interim ones, older messages)
|
||||
*/
|
||||
tool_log?: string;
|
||||
/**
|
||||
* JSON `[id, ...]`: the tracker tasks (`tasks`) the run behind a bot message worked on (created, moved along, read in full or handed over, and the task a handed-over job was started for), shown as chips under the message so the user sees which tasks it's about. Not foreign keys: a deleted task's chip is left out. Null: none
|
||||
*/
|
||||
task_ids?: string;
|
||||
/**
|
||||
* Set on the message that brings a chatroom's outcome back into the asking bot's conversation: the room. Such a message is stored as the user's side of the conversation (the bot answers it) but shown as coming from the coordinator, and the model reads it as data. Not a foreign key
|
||||
*/
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.16.2",
|
||||
"version": "0.16.3",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
@@ -45,7 +45,7 @@
|
||||
"@modelcontextprotocol/sdk": "^1.32.1",
|
||||
"@moduletrace/bun-sqlite": "^1.3.0",
|
||||
"@moduletrace/bunext": "^1.3.5",
|
||||
"@moduletrace/twui": "^0.1.9",
|
||||
"@moduletrace/twui": "^0.1.10",
|
||||
"@tiptap/extension-bubble-menu": "3.32.0",
|
||||
"@tiptap/extension-mention": "3.32.0",
|
||||
"@tiptap/extension-placeholder": "3.32.0",
|
||||
|
||||
@@ -237,6 +237,7 @@ export default async function processBotJob({
|
||||
silent: outcome.silent,
|
||||
attachments: outcome.attachments,
|
||||
tool_log: outcome.tool_log,
|
||||
task_ids: outcome.task_ids,
|
||||
});
|
||||
|
||||
await pushBotNotice({ bot_id, ...completion });
|
||||
|
||||
@@ -5,6 +5,7 @@ import notifyBotMessage from "@/src/push/notify-bot-message";
|
||||
import notifyBotFace from "@/src/push/notify-bot-face";
|
||||
import pushBotUpdated from "./push-bot-updated";
|
||||
import pushToSessionUser from "./push-to-session-user";
|
||||
import withSessionMessageTasks from "./with-session-message-tasks";
|
||||
import grabSessionChatroomId from "@/src/functions/backend/db/chatrooms/grab-session-chatroom-id";
|
||||
import pushChatroomMessage from "@/src/functions/backend/db/chatrooms/push-chatroom-message";
|
||||
import grabSessionHookId from "@/src/functions/backend/db/bot-hooks/grab-session-hook-id";
|
||||
@@ -66,7 +67,10 @@ async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
|
||||
} else if (message && !hook_id) {
|
||||
await pushToSessionUser({
|
||||
session_id: message.session_id,
|
||||
data: { event: "server:bot-message", data: message },
|
||||
/**
|
||||
* With its task chips, like a loaded message.
|
||||
*/
|
||||
data: { event: "server:bot-message", data: await withSessionMessageTasks({ message }) },
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -78,7 +82,7 @@ async function push({ bot_id, message, bot, relay, quiet_push }: Params) {
|
||||
if (relay) {
|
||||
await pushToSessionUser({
|
||||
session_id: relay.message.session_id,
|
||||
data: { event: "server:bot-message", data: relay.message },
|
||||
data: { event: "server:bot-message", data: await withSessionMessageTasks({ message: relay.message }) },
|
||||
});
|
||||
|
||||
if (!quiet_push) void notifyBotMessage({ message: relay.message });
|
||||
|
||||
@@ -217,6 +217,10 @@ export default async function runBotReply({
|
||||
* Files the bot wrote and asked to send with its reply.
|
||||
*/
|
||||
const attachments: number[] = [];
|
||||
/**
|
||||
* The tracker tasks the reply worked on, linked under it.
|
||||
*/
|
||||
const task_ids: number[] = [];
|
||||
|
||||
/**
|
||||
* The files this run reaches: its file tools and the pictures it may
|
||||
@@ -260,6 +264,7 @@ export default async function runBotReply({
|
||||
led = admin;
|
||||
},
|
||||
onChatroom: ({ ref }) => shown.push(ref),
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -451,6 +456,7 @@ export default async function runBotReply({
|
||||
}),
|
||||
attachments: attachments.length ? attachments : undefined,
|
||||
tool_log: result.tool_uses,
|
||||
task_ids,
|
||||
};
|
||||
} finally {
|
||||
await extensions.close();
|
||||
|
||||
@@ -111,6 +111,10 @@ export default async function runBotTask({
|
||||
* changed, whose chips the report always carries.
|
||||
*/
|
||||
const shown: string[] = [];
|
||||
/**
|
||||
* The tracker tasks the run worked on, linked under its report.
|
||||
*/
|
||||
const task_ids: number[] = [];
|
||||
|
||||
const computer = job.computer_id
|
||||
? await openComputerTools({
|
||||
@@ -194,7 +198,14 @@ export default async function runBotTask({
|
||||
*/
|
||||
const admin_tools =
|
||||
!powers.is_coordinator && workspace_id && powers.is_workspace_admin
|
||||
? (await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, scopes })).tools
|
||||
? (await grabWorkspaceAdminTools({
|
||||
bot,
|
||||
user_id,
|
||||
workspace_id,
|
||||
powers,
|
||||
scopes,
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
})).tools
|
||||
: [];
|
||||
|
||||
const tools = [
|
||||
@@ -208,6 +219,7 @@ export default async function runBotTask({
|
||||
admin_workspace_ids: powers.admin_workspace_ids,
|
||||
scopes,
|
||||
hooked,
|
||||
onTask: ({ task_id }) => task_ids.push(task_id),
|
||||
})),
|
||||
...admin_tools,
|
||||
...(powers.is_coordinator
|
||||
@@ -473,6 +485,7 @@ export default async function runBotTask({
|
||||
}),
|
||||
attachments: attachments.length ? attachments : undefined,
|
||||
tool_log: result.tool_uses,
|
||||
task_ids,
|
||||
};
|
||||
} finally {
|
||||
await extensions?.close();
|
||||
|
||||
@@ -57,6 +57,11 @@ export type BotJobOutcome = {
|
||||
* the result message as `tool_log`.
|
||||
*/
|
||||
tool_log?: HarnessToolUse[];
|
||||
/**
|
||||
* The tracker tasks the run worked on (`onTask` from its task tools),
|
||||
* kept on the result message as `task_ids`.
|
||||
*/
|
||||
task_ids?: number[];
|
||||
};
|
||||
|
||||
export type BotJobRunner = (context: BotJobContext) => Promise<BotJobOutcome>;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES, BUN_SQLITE_COBBLE_BOT_SESSIONS } from "@/db/types/db";
|
||||
import withMessageTasks from "@/src/functions/backend/db/bots/with-message-tasks";
|
||||
|
||||
type Params = {
|
||||
message: BUN_SQLITE_COBBLE_BOT_MESSAGES;
|
||||
};
|
||||
|
||||
/**
|
||||
* A message about to be pushed, with the tracker tasks it's about as its
|
||||
* session's user sees them (`withMessageTasks`). Without any, or when the
|
||||
* session is gone, it's returned as it is.
|
||||
*/
|
||||
export default async function withSessionMessageTasks({ message }: Params) {
|
||||
if (!message.task_ids || !message.session_id) return message;
|
||||
|
||||
const session = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_BOT_SESSIONS>({
|
||||
sql: `SELECT user_id FROM bot_sessions WHERE id = ? LIMIT 1`,
|
||||
values: [message.session_id],
|
||||
})
|
||||
).payload?.[0];
|
||||
|
||||
if (!session?.user_id) return message;
|
||||
|
||||
return (await withMessageTasks({ messages: [message], user_id: session.user_id }))[0] ?? message;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
|
||||
type Props = {
|
||||
size?: number;
|
||||
/**
|
||||
* Where the file sits (`bots/3/reports/q3.md`).
|
||||
*/
|
||||
full_path?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The line under a previewed file's name: its size and its full path,
|
||||
* whichever of them is known. The path wraps rather than cuts off, so all
|
||||
* of it can be read (and selected to copy).
|
||||
*/
|
||||
export default function FilePreviewDetails({ size, full_path }: Props) {
|
||||
const text = [size ? formatBytes({ bytes: size }) : "", full_path || ""].filter(Boolean).join(" · ");
|
||||
|
||||
if (!text) return null;
|
||||
|
||||
return (
|
||||
<Span title={full_path || undefined} className="w-full text-[13px] leading-[18px] text-ink-secondary break-all">
|
||||
{text}
|
||||
</Span>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,10 @@ type Props = {
|
||||
url: string;
|
||||
media_type?: string | null;
|
||||
size?: number;
|
||||
/**
|
||||
* Where the file sits (`bots/3/reports/q3.md`), for the preview.
|
||||
*/
|
||||
full_path?: string;
|
||||
/**
|
||||
* The images it sits among (`imagePreviewGallery`), for Previous and
|
||||
* Next in the preview.
|
||||
@@ -24,7 +28,17 @@ type Props = {
|
||||
* plain click. It stays a real link to the bytes, so a middle click or
|
||||
* Ctrl/Cmd click still opens the file in a new tab.
|
||||
*/
|
||||
export default function FilePreviewLink({ name, url, media_type, size, gallery, title, className, children }: Props) {
|
||||
export default function FilePreviewLink({
|
||||
name,
|
||||
url,
|
||||
media_type,
|
||||
size,
|
||||
full_path,
|
||||
gallery,
|
||||
title,
|
||||
className,
|
||||
children,
|
||||
}: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
@@ -50,6 +64,7 @@ export default function FilePreviewLink({ name, url, media_type, size, gallery,
|
||||
url={url}
|
||||
media_type={media_type}
|
||||
size={size}
|
||||
full_path={full_path}
|
||||
gallery={gallery}
|
||||
onClose={() => setOpen(false)}
|
||||
/>
|
||||
|
||||
@@ -11,9 +11,9 @@ import usePreloadImages from "@/src/hooks/use-preload-images";
|
||||
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
|
||||
import type { FilePreviewItem } from "@/src/types";
|
||||
import filePreviewKind from "@/src/utils/file-preview-kind";
|
||||
import formatBytes from "@/src/utils/format-bytes";
|
||||
import galleryIndex from "@/src/utils/gallery-index";
|
||||
import FilePreviewBody from "./file-preview-body";
|
||||
import FilePreviewDetails from "./file-preview-details";
|
||||
import FilePreviewStepper from "./file-preview-stepper";
|
||||
|
||||
type Props = {
|
||||
@@ -21,6 +21,10 @@ type Props = {
|
||||
url: string;
|
||||
media_type?: string | null;
|
||||
size?: number;
|
||||
/**
|
||||
* Where the file sits (`bots/3/reports/q3.md`), shown beside its size.
|
||||
*/
|
||||
full_path?: string;
|
||||
/**
|
||||
* The images it was opened among (a folder's, a message's). When the
|
||||
* file is one of them, Previous and Next (and the arrow keys) step
|
||||
@@ -34,7 +38,7 @@ const ActionClassName =
|
||||
"shrink-0 inline-flex items-center gap-1.5 px-2 py-1.5 text-[13px] leading-[18px] text-ink-secondary hover:text-ink rounded-default hover:bg-sunken no-underline";
|
||||
|
||||
/**
|
||||
* A file over the page: markdown rendered, a CSV as a table, an image,
|
||||
* A file over the page, its full path beside its size: markdown rendered, a CSV as a table, an image,
|
||||
* PDF, audio or video in place, other text as code, with ways to download
|
||||
* it or open it in a new tab. A file it can't show offers those only.
|
||||
* Opened from a gallery, it steps through its images; each one opens fresh
|
||||
@@ -44,7 +48,7 @@ export default function FilePreviewModal({ gallery, onClose, ...opened }: Props)
|
||||
const [index, set_index] = useState(() => galleryIndex({ gallery, url: opened.url }));
|
||||
const stepping = Boolean(gallery && index >= 0 && gallery.length > 1);
|
||||
const shown: FilePreviewItem = (stepping && gallery?.[index]) || opened;
|
||||
const { name, url, media_type, size } = shown;
|
||||
const { name, url, media_type, size, full_path } = shown;
|
||||
const kind = filePreviewKind({ name, media_type });
|
||||
const base_name = name.split("/").pop() || name;
|
||||
const count = gallery?.length || 0;
|
||||
@@ -77,11 +81,7 @@ export default function FilePreviewModal({ gallery, onClose, ...opened }: Props)
|
||||
>
|
||||
{base_name}
|
||||
</H2>
|
||||
{size ? (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{formatBytes({ bytes: size })}
|
||||
</Span>
|
||||
) : null}
|
||||
<FilePreviewDetails size={size} full_path={full_path} />
|
||||
</Stack>
|
||||
{stepping ? (
|
||||
<FilePreviewStepper
|
||||
|
||||
@@ -2,6 +2,7 @@ import { expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import FilePreviewBody from "./file-preview-body";
|
||||
import FilePreviewDetails from "./file-preview-details";
|
||||
import FilePreviewLink from "./file-preview-link";
|
||||
import FilePreviewMarkdown from "./file-preview-markdown";
|
||||
import FilePreviewTable from "./file-preview-table";
|
||||
@@ -86,3 +87,12 @@ test("a gallery's stepper says where the image stands and stops at the ends", ()
|
||||
expect((first.match(/disabled=""/g) || []).length).toBe(1);
|
||||
expect((last.match(/disabled=""/g) || []).length).toBe(1);
|
||||
});
|
||||
|
||||
test("the preview names the file's full path beside its size", () => {
|
||||
const html = renderToString(<FilePreviewDetails size={2048} full_path="bots/3/reports/q3.md" />);
|
||||
|
||||
expect(html).toContain("2.0 KB");
|
||||
expect(html).toContain("bots/3/reports/q3.md");
|
||||
expect(renderToString(<FilePreviewDetails full_path="media/1/a.pdf" />)).toContain("media/1/a.pdf");
|
||||
expect(renderToString(<FilePreviewDetails />)).toBe("");
|
||||
});
|
||||
|
||||
@@ -61,6 +61,7 @@ export default function StorageEntryRow({ entry, selected, gallery, onOpenFolder
|
||||
url={entry.url || ""}
|
||||
media_type={entry.media_type}
|
||||
size={entry.size}
|
||||
full_path={entry.full_path}
|
||||
gallery={gallery}
|
||||
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
|
||||
>
|
||||
|
||||
@@ -43,6 +43,8 @@ export default function TaskFileRow({ file, onDetach, busy }: Props) {
|
||||
name={file.name || `File ${file.media_id}`}
|
||||
url={`/media/${file.media_id}`}
|
||||
media_type={file.media_type}
|
||||
size={file.size}
|
||||
full_path={file.full_path}
|
||||
className="grow min-w-0 text-[13px] leading-[18px] text-ink truncate hover:underline"
|
||||
>
|
||||
{file.name || `File ${file.media_id}`}
|
||||
|
||||
@@ -20,7 +20,7 @@ A chat reply is short: about eight tool steps. Anything long, multi-step or on a
|
||||
- Hand work that fits a worker to them with \`delegate_task\`. It runs in the background and is reported back here when they finish or fail.
|
||||
- Say that work is under way, not done, and say who is on it.
|
||||
|
||||
If the request is clear, start. Ask one short question only when missing information would change the outcome; otherwise pick a sensible default and state the assumption when it matters. Keep decisions and constraints from earlier messages unless the user changes them.
|
||||
If the request is clear, start. When missing information would change the outcome, or a choice is the user's to make, ask with \`ask_user\` (a card of multiple-choice questions they answer in a click) instead of picking for them. For details that don't change the outcome, pick a sensible default and state the assumption when it matters. Keep decisions and constraints from earlier messages unless the user changes them.
|
||||
|
||||
Permission to draft is not permission to send, permission to analyze is not permission to modify, and permission to configure a bot is not permission to grant unrelated access.
|
||||
|
||||
@@ -85,7 +85,7 @@ Done means the operation ran, the tool confirmed it, the artifact exists, the cr
|
||||
|
||||
## 7. Approval, safety, privacy
|
||||
|
||||
Ask before anything destructive, hard to undo, externally visible or beyond the task's data scope: sending email or messages, publishing, payments, deleting consequential data, changing a live site, sharing private data outside. Say what you'll do and what it costs, in one line.
|
||||
Ask before anything destructive, hard to undo, externally visible or beyond the task's data scope: sending email or messages, publishing, payments, deleting consequential data, changing a live site, sharing private data outside. Use \`ask_user\` for it, saying what you'll do and what it costs in one line.
|
||||
|
||||
A clear request can authorize a well-defined action, so don't ask twice unless the scope or the risk changes. Negative instructions are binding: never bundle a declined action into an approved one, and never re-offer what the user just turned down.
|
||||
|
||||
@@ -105,7 +105,7 @@ Interrupt only for a decision that changes the outcome, information that can't b
|
||||
|
||||
Write in short, plain sentences: no filler, no hype, no emoji. Lead with the outcome, the blocker or the decision needed. Be candid about limits, use relative times, and don't dress up uncertainty as confidence. For ongoing work report needs-you, then in progress, then done, then blocked or failed, and omit empty groups.
|
||||
|
||||
Lead: after each report, suggest one concrete next step or ask the one question that settles the direction. Don't create bots, workspaces, tasks or setup steps nobody asked for, don't re-suggest what was declined, and stop when the job is done.
|
||||
Lead: after each report, offer the next step with \`ask_user\`: the concrete next steps, or the one question that settles the direction, as options with your suggestion first. Don't create bots, workspaces, tasks or setup steps nobody asked for, don't re-suggest what was declined, and stop when the job is done.
|
||||
|
||||
**Be proactive in execution, rigorous in verification, economical with the user's attention, and completely honest about what happened.**
|
||||
`;
|
||||
|
||||
@@ -72,7 +72,7 @@ You are chatting with the user. Answer their latest messages directly and briefl
|
||||
|
||||
## Keep the work moving
|
||||
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step: one concrete suggestion or a short question about what to do next, e.g. "Want me to draft the reply as well?" or "Should I check the other two accounts the same way?". Base it on what the user is trying to get done, not on generic options. Offer one step, not a menu. Skip it when you've already asked the user something in this reply, when you've just started a task (its result will suggest what's next), or when the user is clearly wrapping up.`;
|
||||
Be proactive. Follow where the conversation is heading and, once you've answered, offer the next step with ask_user, not as a question in your text: one question whose options are the concrete next steps, the one you'd suggest first and marked as suggested, e.g. "Draft the reply as well (suggested)" and "Check the other two accounts the same way". Base them on what the user is trying to get done, not on generic options, and keep it to two to four. Skip it when you've already called ask_user in this reply, when you've just started a task (its result will offer what's next), or when the user is clearly wrapping up.`;
|
||||
|
||||
/**
|
||||
* Added to every run, chat replies and tasks alike: where its files live,
|
||||
@@ -200,7 +200,13 @@ Anything you read or write goes to your model provider, so secret values (passwo
|
||||
*/
|
||||
export const QuestionsNote = `# Asking before acting
|
||||
|
||||
Be sure of what the user wants before you act on it. When a request could mean more than one thing, when a choice is theirs to make, or before work that is hard to undo, costly or seen by others, and you can't tell what they'd pick, ask with ask_user: a card of multiple-choice questions (one pick or several, with "Other" for their own words) they answer in a click. Give options that are concrete and distinct, put the one you'd suggest first and say so in it ("Staging (suggested)"). Ask everything you need in one card, then wait for their answers before acting on what you asked. Don't ask about what they already said, what you can find out yourself, or small choices any sensible answer settles: just do those. If they skip the questions, don't guess: do only the part that's clear and say what you still need.`;
|
||||
Be proactive about moving the work forward, but let the user steer it: whenever what happens next is theirs to decide, check with ask_user instead of deciding for them or asking in your text. ask_user puts a card of multiple-choice questions in the chat (one pick or several, with "Other" for their own words) that they answer in a click, so asking costs them little. Use it:
|
||||
|
||||
- when a request could mean more than one thing, or leaves out something that changes the result (which target, which items, how far to go, what form it takes);
|
||||
- before work that is hard to undo, costly or seen by others;
|
||||
- to offer the next step once you've answered or reported: the concrete next steps as options.
|
||||
|
||||
When you're unsure whether to ask, ask. Give options that are concrete and distinct, put the one you'd suggest first and say so in it ("Staging (suggested)"). Ask everything you need in one card, then wait for their answers before acting on what you asked. Don't ask about what they already said, what you can find out yourself, or details that don't change the result (a file name, wording they can tweak later): just do those. If they skip the questions, don't guess: do only the part that's clear and say what you still need.`;
|
||||
|
||||
/**
|
||||
* Added to every run: bots can show a concept as a visual the chat
|
||||
@@ -215,7 +221,7 @@ When a concept, comparison, process, timeline or set of numbers is easier to see
|
||||
* `bot_id` is the coordinator itself, so the ref example it copies is its
|
||||
* own rather than a worker's.
|
||||
*/
|
||||
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next: the next piece of work, which bot would take it, or a question that settles the direction. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
|
||||
export const coordinatorReplyNote = ({ bot_id }: { bot_id: number | string }) => `As the coordinator, hand work that fits a crew member's role to them with delegate_task. Work that is already a task on a list goes over as that task (delegate_task with its task_id), never as a copy; a routine of yours that belongs with a worker goes with hand_over_schedule. They post the result in their own conversation, and it's reported back here when they finish or fail, so tell the user who is on it and where: a task with no workspace_id runs in that bot's own chat, on its own memory, files and directly assigned computers; one with workspace_id runs in the workspace, on the workspace's context, files and computers as well as the bot's, and lands in that project's conversation. Never swap one for the other without saying so. When a report comes back, pass on what matters to the user, follow up on anything left, and propose what comes next with ask_user: the next piece of work, which bot would take it, or the question that settles the direction, as options for the user to pick. Once the user agrees, you can also grow the crew with create_bot, put a worker in a workspace with add_bot_to_workspace, and create or change a workspace with create_workspace and update_workspace. When you name a crew member, write its ref instead of its name, e.g. ${botRef({ id: bot_id })} for yourself: the user sees it as the bot's name, linked to its conversation.`;
|
||||
|
||||
/**
|
||||
* Added to the coordinator's chat prompt instead while it has no workers,
|
||||
@@ -250,7 +256,7 @@ export const workspaceAdminsLine = ({ admins }: { admins: { id?: number | "" }[]
|
||||
*/
|
||||
export const TaskRunNote = `# Working on a task
|
||||
|
||||
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest, as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
|
||||
You are working through a task on your own; the user isn't watching. Use your tools until the task is done, then answer with the report for the user: what you did, what you found, and anything left for them. The report is posted straight to them, so write to them ("you"), never about them by name or as "the user". End it with the next step you'd suggest: offered with ask_user when you have it (the concrete next steps as options, your suggestion first), otherwise as a short question the user can say yes to. Keep the report short and in markdown. If you're blocked on something only the user can give you, stop and ask for it in the report. The same goes for being stuck: when several different tries at the same thing (a search, a page, a fix) leave you no closer, stop there and report what you tried and what you need, rather than spending the run on more of the same. If they need to do it on the computer themselves (log in, a captcha, a code), call ask_user_to_take_over first.`;
|
||||
|
||||
/**
|
||||
* Told to a task run with what the user wrote in its conversation since
|
||||
|
||||
@@ -4,6 +4,7 @@ import grabMediaURL from "../../media/grab-media-url";
|
||||
import grabBotFileQuotaBytes, { grabBotFileQuotaMb } from "./grab-bot-file-quota-bytes";
|
||||
import grabStorageUsage from "./grab-storage-usage";
|
||||
import listBotFiles from "./list-bot-files";
|
||||
import botFileFullPath from "@/src/utils/bot-file-full-path";
|
||||
|
||||
type Params = {
|
||||
bot_id: number;
|
||||
@@ -55,6 +56,7 @@ export default async function grabConversationFiles({
|
||||
owner_id: Number(file.owner_id) || 0,
|
||||
created_at: Number(file.created_at) || 0,
|
||||
url: media_url || "",
|
||||
full_path: botFileFullPath({ scope: file.scope, owner_id: file.owner_id, path: file.path }),
|
||||
};
|
||||
}),
|
||||
folders: [],
|
||||
|
||||
@@ -17,6 +17,7 @@ import grabSessionChatroomId from "../chatrooms/grab-session-chatroom-id";
|
||||
import onChatroomJobEnded from "../chatrooms/on-chatroom-job-ended";
|
||||
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import jobTrackerTaskId from "./job-tracker-task-id";
|
||||
|
||||
type Params = {
|
||||
job_id: number | string;
|
||||
@@ -42,6 +43,10 @@ type Params = {
|
||||
* Every tool call the run made, kept on the message.
|
||||
*/
|
||||
tool_log?: HarnessToolUse[];
|
||||
/**
|
||||
* The tracker tasks the run worked on, linked under the message.
|
||||
*/
|
||||
task_ids?: number[];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -63,6 +68,7 @@ export default async function completeBotJob({
|
||||
silent,
|
||||
attachments,
|
||||
tool_log,
|
||||
task_ids = [],
|
||||
}: Params) {
|
||||
const job = await grabLockedBotJob({ job_id, worker });
|
||||
|
||||
@@ -86,6 +92,11 @@ export default async function completeBotJob({
|
||||
values: [result, now, job.id],
|
||||
});
|
||||
|
||||
/**
|
||||
* A handed-over task's run is about that task, whatever its tools did.
|
||||
*/
|
||||
const message_task_ids = [jobTrackerTaskId({ job }), ...task_ids];
|
||||
|
||||
if (job.task_id) {
|
||||
await BunSQLite.sql({
|
||||
sql: `UPDATE bot_tasks SET status = 'done', updated_at = ? WHERE id = ?`,
|
||||
@@ -103,6 +114,7 @@ export default async function completeBotJob({
|
||||
needs_you,
|
||||
media_ids: attachments,
|
||||
tool_log,
|
||||
task_ids: message_task_ids,
|
||||
});
|
||||
|
||||
if (job.id && inserted?.id) {
|
||||
@@ -164,7 +176,7 @@ export default async function completeBotJob({
|
||||
|
||||
await recordHookCallResponse({ job, status: "done", response: result, message_id: inserted?.id });
|
||||
|
||||
const relay = silent ? null : await relayJobToRequester({ job, text: result });
|
||||
const relay = silent ? null : await relayJobToRequester({ job, text: result, task_ids: message_task_ids });
|
||||
|
||||
await onChatroomJobEnded({ job, text: silent ? "" : result });
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
|
||||
import parseJobJson from "@/src/bots-queue/parse-job-json";
|
||||
|
||||
type Params = {
|
||||
job: Pick<BUN_SQLITE_COBBLE_BOTS_QUEUE, "params">;
|
||||
};
|
||||
|
||||
/**
|
||||
* The tracker task a job was started for (`params.tracker_task_id`, set
|
||||
* by `handOverTask`), or null.
|
||||
*/
|
||||
export default function jobTrackerTaskId({ job }: Params): number | null {
|
||||
const id = Number(parseJobJson({ text: job.params })?.tracker_task_id || 0);
|
||||
|
||||
return Number.isInteger(id) && id > 0 ? id : null;
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOTS_QUEUE } from "@/db/types/db";
|
||||
import parseJobJson from "@/src/bots-queue/parse-job-json";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import { logError } from "@/src/functions/backend/logger";
|
||||
import grabBotById from "../bots/grab-bot-by-id";
|
||||
@@ -7,6 +6,7 @@ import addTaskNote from "../tasks/add-task-note";
|
||||
import grabTaskRow, { isOpenTask } from "../tasks/grab-task-scope";
|
||||
import updateTask from "../tasks/update-task";
|
||||
import grabJobUserId from "./grab-job-user-id";
|
||||
import jobTrackerTaskId from "./job-tracker-task-id";
|
||||
|
||||
type Params = {
|
||||
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
|
||||
@@ -25,7 +25,7 @@ type Params = {
|
||||
* the job's wrap-up.
|
||||
*/
|
||||
export default async function noteTrackerTask({ job, failure }: Params) {
|
||||
const tracker_task_id = Number(parseJobJson({ text: job.params })?.tracker_task_id || 0);
|
||||
const tracker_task_id = jobTrackerTaskId({ job });
|
||||
|
||||
if (!tracker_task_id || !job.bot_id) return;
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import grabSessionChatroomId from "../chatrooms/grab-session-chatroom-id";
|
||||
import onChatroomJobEnded from "../chatrooms/on-chatroom-job-ended";
|
||||
import grabSessionHookId from "../bot-hooks/grab-session-hook-id";
|
||||
import settleInstallRequest from "../install-requests/settle-install-request";
|
||||
import jobTrackerTaskId from "./job-tracker-task-id";
|
||||
|
||||
type Params = {
|
||||
job: BUN_SQLITE_COBBLE_BOTS_QUEUE;
|
||||
@@ -40,6 +41,11 @@ export default async function notifyBotJobFailed({
|
||||
values: [Date.now(), job.id],
|
||||
});
|
||||
|
||||
/**
|
||||
* A handed-over task's failed run links to that task.
|
||||
*/
|
||||
const task_ids = [jobTrackerTaskId({ job })];
|
||||
|
||||
const message = await insertBotMessage({
|
||||
bot_id: job.bot_id,
|
||||
session_id: await jobSessionId({ job }),
|
||||
@@ -55,6 +61,7 @@ export default async function notifyBotJobFailed({
|
||||
.filter(Boolean)
|
||||
.join(" "),
|
||||
needs_you: true,
|
||||
task_ids,
|
||||
});
|
||||
|
||||
const user_id = await grabJobUserId({ job });
|
||||
@@ -84,6 +91,7 @@ export default async function notifyBotJobFailed({
|
||||
job,
|
||||
text: failure_message || job.last_error || "",
|
||||
failed: true,
|
||||
task_ids,
|
||||
});
|
||||
|
||||
await onChatroomJobEnded({ job, text: failure_message || job.last_error || "", failed: true });
|
||||
|
||||
@@ -14,6 +14,10 @@ type Params = {
|
||||
*/
|
||||
text: string;
|
||||
failed?: boolean;
|
||||
/**
|
||||
* The tracker tasks the job worked on, linked under the report.
|
||||
*/
|
||||
task_ids?: (number | null)[];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -24,7 +28,7 @@ type Params = {
|
||||
* failed. Returns the message for the live push, or null when nobody
|
||||
* handed the job over.
|
||||
*/
|
||||
export default async function relayJobToRequester({ job, text, failed }: Params) {
|
||||
export default async function relayJobToRequester({ job, text, failed, task_ids }: Params) {
|
||||
if (!job.requested_by_bot_id || !job.bot_id || job.requested_by_bot_id == job.bot_id) {
|
||||
return null;
|
||||
}
|
||||
@@ -70,6 +74,7 @@ export default async function relayJobToRequester({ job, text, failed }: Params)
|
||||
? `${name} couldn't finish **${title}**. ${text}`.trim()
|
||||
: `${name} finished **${title}**. Their report:\n\n${text}`,
|
||||
needs_you: failed,
|
||||
task_ids,
|
||||
});
|
||||
|
||||
return { bot_id: requester.id, message };
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
|
||||
import type { BotMessageWithAttachments } from "@/src/types";
|
||||
import type { BotMessageWithAttachments, MessageTask } from "@/src/types";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import grabMessageUsage from "../usage/grab-message-usage";
|
||||
import grabMessagesMedia from "./grab-messages-media";
|
||||
import grabMessagesReactions from "./grab-messages-reactions";
|
||||
import grabMessagesReplies from "./grab-messages-replies";
|
||||
import grabMessagesTasks from "./grab-messages-tasks";
|
||||
import mediaToAttachment, { grabAttachmentFileIds } from "./media-to-attachment";
|
||||
|
||||
type Params = {
|
||||
@@ -33,7 +34,8 @@ type Params = {
|
||||
/**
|
||||
* The latest messages of a session (or the latest before `before_id`),
|
||||
* oldest first, with their attachments,
|
||||
* what each replies to, and (when `user_id` is given) its reactions.
|
||||
* what each replies to, and (when `user_id` is given) its reactions and
|
||||
* the tracker tasks it's about that the user reaches.
|
||||
*/
|
||||
export default async function grabBotMessages({
|
||||
session_id,
|
||||
@@ -77,13 +79,16 @@ export default async function grabBotMessages({
|
||||
const messages = res.payload || [];
|
||||
const message_ids = messages.map((message) => Number(message.id));
|
||||
|
||||
const [media, replies, reactions, usage] = await Promise.all([
|
||||
const [media, replies, reactions, usage, tasks] = await Promise.all([
|
||||
grabMessagesMedia({ message_ids }),
|
||||
grabMessagesReplies({ message_ids }),
|
||||
user_id
|
||||
? grabMessagesReactions({ message_ids, user_id })
|
||||
: Promise.resolve(new Map()),
|
||||
grabMessageUsage({ message_ids }),
|
||||
user_id
|
||||
? grabMessagesTasks({ messages, user_id })
|
||||
: Promise.resolve(new Map<number, MessageTask[]>()),
|
||||
]);
|
||||
|
||||
/**
|
||||
@@ -100,6 +105,7 @@ export default async function grabBotMessages({
|
||||
const reply_to = replies.get(id);
|
||||
|
||||
const spent = usage.get(id);
|
||||
const linked = tasks.get(id);
|
||||
|
||||
return {
|
||||
...message,
|
||||
@@ -116,6 +122,7 @@ export default async function grabBotMessages({
|
||||
...(reply_to ? { reply_to } : {}),
|
||||
...(user_id ? { reactions: reactions.get(id) || [] } : {}),
|
||||
...(spent ? { usage: spent } : {}),
|
||||
...(linked ? { tasks: linked } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
|
||||
import type { MessageTask } from "@/src/types";
|
||||
import messageTaskIds from "@/src/utils/message-task-ids";
|
||||
import taskScopesSql from "@/src/utils/task-access/task-scopes-sql";
|
||||
import grabCrewRole from "../access/grab-crew-role";
|
||||
|
||||
type Params = {
|
||||
messages: Pick<BUN_SQLITE_COBBLE_BOT_MESSAGES, "id" | "task_ids">[];
|
||||
/**
|
||||
* Whose conversation it is: only the tasks they reach are named.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The tracker tasks each message is about (`task_ids`), by message id,
|
||||
* each with its title and status for its chip. A task the user doesn't
|
||||
* reach, or that was deleted, is left out, so a chip never names a task
|
||||
* the user couldn't open. Messages naming none are not in the map.
|
||||
*/
|
||||
export default async function grabMessagesTasks({ messages, user_id }: Params) {
|
||||
const by_message = new Map<number, MessageTask[]>();
|
||||
const wanted = new Map<number, number[]>();
|
||||
|
||||
for (const message of messages) {
|
||||
const ids = messageTaskIds({ task_ids: message.task_ids });
|
||||
|
||||
if (message.id && ids.length) wanted.set(Number(message.id), ids);
|
||||
}
|
||||
|
||||
const all_ids = [...new Set([...wanted.values()].flat())];
|
||||
|
||||
if (!all_ids.length) return by_message;
|
||||
|
||||
const access = taskScopesSql({ role: await grabCrewRole({ user_id }), user_id });
|
||||
|
||||
const res = await BunSQLite.sql<MessageTask>({
|
||||
sql: `SELECT t.id, t.title, t.status FROM tasks t
|
||||
WHERE t.id IN (${all_ids.map(() => "?").join(", ")}) AND ${access.sql}`,
|
||||
values: [...all_ids, ...access.values],
|
||||
});
|
||||
|
||||
const tasks = new Map((res.payload || []).map((task) => [Number(task.id), task]));
|
||||
|
||||
for (const [message_id, ids] of wanted) {
|
||||
const found = ids.map((id) => tasks.get(id)).filter((task): task is MessageTask => Boolean(task));
|
||||
|
||||
if (found.length) by_message.set(message_id, found);
|
||||
}
|
||||
|
||||
return by_message;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
} from "@/db/types/db";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { HarnessToolUse } from "@/src/harness/types";
|
||||
import messageTaskIds from "@/src/utils/message-task-ids";
|
||||
|
||||
type Params = {
|
||||
bot_id: number;
|
||||
@@ -28,6 +29,11 @@ type Params = {
|
||||
* message in later turns (`botMessagesToHarness`).
|
||||
*/
|
||||
tool_log?: HarnessToolUse[];
|
||||
/**
|
||||
* The tracker tasks the message is about (the run worked on them),
|
||||
* shown as chips under it.
|
||||
*/
|
||||
task_ids?: (number | string | null | undefined)[];
|
||||
/**
|
||||
* Opens a session the conversation moved into
|
||||
* (`carryOverBotSession`): the session it carries on from.
|
||||
@@ -48,12 +54,15 @@ export default async function insertBotMessage({
|
||||
interim,
|
||||
media_ids = [],
|
||||
tool_log,
|
||||
task_ids,
|
||||
carried_from_session_id,
|
||||
}: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES> {
|
||||
const now = Date.now();
|
||||
const needs_you_flag = needs_you ? 1 : 0;
|
||||
const interim_flag = interim ? 1 : 0;
|
||||
const tool_log_json = tool_log ? JSON.stringify(tool_log) : undefined;
|
||||
const tidy_task_ids = messageTaskIds({ task_ids });
|
||||
const task_ids_json = tidy_task_ids.length ? JSON.stringify(tidy_task_ids) : undefined;
|
||||
|
||||
const res = await BunSQLite.insert<
|
||||
BUN_SQLITE_COBBLE_BOT_MESSAGES,
|
||||
@@ -70,6 +79,7 @@ export default async function insertBotMessage({
|
||||
needs_you: needs_you_flag,
|
||||
interim: interim_flag,
|
||||
tool_log: tool_log_json,
|
||||
task_ids: task_ids_json,
|
||||
carried_from_session_id,
|
||||
},
|
||||
],
|
||||
@@ -112,6 +122,7 @@ export default async function insertBotMessage({
|
||||
needs_you: needs_you_flag,
|
||||
interim: interim_flag,
|
||||
tool_log: tool_log_json,
|
||||
task_ids: task_ids_json,
|
||||
carried_from_session_id,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_FILES, BUN_SQLITE_COBBLE_MEDIA } from "@/db/types/db";
|
||||
import grabMediaURL from "@/src/functions/backend/media/grab-media-url";
|
||||
import mediaFilePlace from "@/src/functions/backend/media/media-file-place";
|
||||
import type { BotMessageAttachment, MediaType } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
@@ -14,7 +15,8 @@ type Params = {
|
||||
|
||||
/**
|
||||
* A `media` row as a chat attachment: its original name (`title`), type
|
||||
* and the private URLs it's served at. A file saved in a bot's folder
|
||||
* and the private URLs it's served at, with where it sits on the data
|
||||
* volume and its size for the preview. A file saved in a bot's folder
|
||||
* carries its `file_id`, so the chip can open the file's page.
|
||||
*/
|
||||
export default function mediaToAttachment({ media, file_id }: Params): BotMessageAttachment {
|
||||
@@ -27,6 +29,7 @@ export default function mediaToAttachment({ media, file_id }: Params): BotMessag
|
||||
url: media_url || "",
|
||||
thumbnail_url: media_thumbnail_url,
|
||||
file_id: file_id || undefined,
|
||||
...mediaFilePlace({ write_path: media.media_write_path }),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
|
||||
import type { MessageTask } from "@/src/types";
|
||||
import grabMessagesTasks from "./grab-messages-tasks";
|
||||
|
||||
type Params<T extends BUN_SQLITE_COBBLE_BOT_MESSAGES> = {
|
||||
messages: T[];
|
||||
/**
|
||||
* Whose conversation they're in.
|
||||
*/
|
||||
user_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The messages with the tracker tasks they're about (`tasks`), for a live
|
||||
* push: a pushed bot message must carry its task chips like a loaded one
|
||||
* (`grabBotMessages`), or they show only after a reload. Messages naming
|
||||
* no task are left as they are.
|
||||
*/
|
||||
export default async function withMessageTasks<T extends BUN_SQLITE_COBBLE_BOT_MESSAGES>({
|
||||
messages,
|
||||
user_id,
|
||||
}: Params<T>): Promise<(T & { tasks?: MessageTask[] })[]> {
|
||||
if (!messages.some((message) => message.task_ids)) return messages;
|
||||
|
||||
const tasks = await grabMessagesTasks({ messages, user_id });
|
||||
|
||||
return messages.map((message) => {
|
||||
const found = tasks.get(Number(message.id));
|
||||
|
||||
return found ? { ...message, tasks: found } : message;
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { TaskFile } from "@/src/types";
|
||||
import mediaFilePlace from "@/src/functions/backend/media/media-file-place";
|
||||
|
||||
type Params = {
|
||||
task_id: number | string;
|
||||
@@ -7,13 +8,13 @@ type Params = {
|
||||
|
||||
/**
|
||||
* A task's files with what a row shows: the `media` row's type, mime and
|
||||
* size, and whether that row is still there (a failed cleanup or a
|
||||
* size, where the file sits on the data volume, and whether that row is still there (a failed cleanup or a
|
||||
* deleted file leaves the link behind, listed as missing rather than
|
||||
* hiding it).
|
||||
*/
|
||||
export default async function grabTaskMedia({ task_id }: Params): Promise<TaskFile[]> {
|
||||
const res = await BunSQLite.sql<TaskFile>({
|
||||
sql: `SELECT tm.*, m.media_type, m.mime_type, m.title AS media_title
|
||||
const res = await BunSQLite.sql<TaskFile & { media_write_path?: string | null }>({
|
||||
sql: `SELECT tm.*, m.media_type, m.mime_type, m.title AS media_title, m.media_write_path
|
||||
FROM task_media tm
|
||||
LEFT JOIN media m ON m.id = tm.media_id
|
||||
WHERE tm.task_id = ?
|
||||
@@ -21,9 +22,10 @@ export default async function grabTaskMedia({ task_id }: Params): Promise<TaskFi
|
||||
values: [Number(task_id)],
|
||||
});
|
||||
|
||||
return (res.payload || []).map((file) => ({
|
||||
return (res.payload || []).map(({ media_write_path, ...file }) => ({
|
||||
...file,
|
||||
name: file.name || file.media_title || `File ${file.media_id}`,
|
||||
missing: !file.media_type,
|
||||
...mediaFilePlace({ write_path: media_write_path }),
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -178,6 +178,7 @@ export default async function handOverTask({
|
||||
session_id: Number(session.id),
|
||||
workspace_id: run_workspace_id,
|
||||
text: `${handed_by} handed me task #${task.id}: **${title}**${start ? "" : ". It's on my list; I'll start when you say."}`,
|
||||
task_ids: [Number(task.id)],
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { statSync } from "node:fs";
|
||||
import mediaFilePath from "@/src/utils/media-file-path";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* A `media` row's `media_write_path`, relative to the data directory.
|
||||
*/
|
||||
write_path?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Where a media row's file sits on the data volume and how big it is, for
|
||||
* the file preview. Nothing for a row whose path is unsafe or whose file
|
||||
* is gone.
|
||||
*/
|
||||
export default function mediaFilePlace({ write_path }: Params): { full_path?: string; size?: number } {
|
||||
const absolute = mediaFilePath({ write_path });
|
||||
|
||||
if (!absolute || !write_path) return {};
|
||||
|
||||
try {
|
||||
const stats = statSync(absolute);
|
||||
|
||||
if (!stats.isFile()) return {};
|
||||
|
||||
return { full_path: write_path.replace(/^\/+/, ""), size: stats.size };
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import computerFolderLabel from "@/src/utils/computer-folder-label";
|
||||
import computerPathAllowed from "@/src/utils/computer-path-allowed";
|
||||
import { isInsideRoot } from "./resolve-storage-path";
|
||||
import type { ResolvedStorageSpec } from "./resolve-storage-spec";
|
||||
import type { StorageEntry } from "@/src/types";
|
||||
import dataVolumePath from "@/src/utils/data-volume-path";
|
||||
import {
|
||||
storageSpecHref,
|
||||
type StorageSpec,
|
||||
@@ -34,32 +36,7 @@ type Params = {
|
||||
offset?: number;
|
||||
};
|
||||
|
||||
export type StorageEntry = {
|
||||
name: string;
|
||||
/**
|
||||
* Where it is, inside the volume's root, e.g. `seo/coderank/raw`.
|
||||
*/
|
||||
path: string;
|
||||
kind: "file" | "folder";
|
||||
size: number;
|
||||
modified_at: number;
|
||||
media_type?: string;
|
||||
/**
|
||||
* The `bot_files` row, when one of the bot's own files is that path, so
|
||||
* it keeps opening through its own media record.
|
||||
*/
|
||||
file_id?: number;
|
||||
/**
|
||||
* Where to open it: a `bot_files` row's media URL, else the volume
|
||||
* browser's own streaming route.
|
||||
*/
|
||||
url?: string;
|
||||
/**
|
||||
* What an id folder in a computer's workspace is: the bot's, user's or
|
||||
* workspace's name.
|
||||
*/
|
||||
label?: string;
|
||||
};
|
||||
export type { StorageEntry };
|
||||
|
||||
/**
|
||||
* One directory on the data volume, for the files browser: its entries
|
||||
@@ -150,6 +127,7 @@ export default async function listStorageEntries({
|
||||
media_type: file?.media_type || undefined,
|
||||
file_id: file?.id ? Number(file.id) : undefined,
|
||||
url: media_url || fileUrl({ spec: resolved.spec, path: entry_path }),
|
||||
full_path: dataVolumePath({ absolute: entry_absolute }),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -53,6 +53,11 @@ type Params = {
|
||||
*/
|
||||
is_coordinator?: boolean;
|
||||
admin_workspace_ids?: number[];
|
||||
/**
|
||||
* Called with a task it hands over, so the message the run posts links
|
||||
* to it (`bot_messages.task_ids`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -98,6 +103,7 @@ export default function delegateTaskTool({
|
||||
grabTargets = ({ workspace_id }) => grabCrewWorkers({ workspace_id }),
|
||||
is_coordinator = false,
|
||||
admin_workspace_ids = [],
|
||||
onTask,
|
||||
}: Params): HarnessTool<Args> {
|
||||
const crew = workers
|
||||
.map((bot) => `${bot.id}: ${bot.name}${bot.role ? ` (${bot.role})` : ""}`)
|
||||
@@ -195,6 +201,8 @@ export default function delegateTaskTool({
|
||||
start: args.start !== false,
|
||||
});
|
||||
|
||||
onTask?.({ task_id: Number(task.id) });
|
||||
|
||||
const where = handed.workspace_id ? ` in workspace ${handed.workspace_id}` : " in their own chat";
|
||||
|
||||
if (!handed.job_id) {
|
||||
|
||||
@@ -81,6 +81,11 @@ type Params = {
|
||||
* Called with the ref of each chatroom the bot opened (`ask_crew`).
|
||||
*/
|
||||
onChatroom?: (params: { ref: string }) => void;
|
||||
/**
|
||||
* Called with each tracker task the run worked on, so the message it
|
||||
* posts links to it (`bot_messages.task_ids`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -120,6 +125,7 @@ export default async function grabBotChatTools({
|
||||
onPropose,
|
||||
onWorkspaceAdmin,
|
||||
onChatroom,
|
||||
onTask,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
const bot_id = bot.id || 0;
|
||||
const tools = [
|
||||
@@ -135,6 +141,7 @@ export default async function grabBotChatTools({
|
||||
can_delete_tasks: Boolean(attended),
|
||||
onPropose,
|
||||
onChatroom,
|
||||
onTask,
|
||||
})),
|
||||
startTaskTool({
|
||||
user_id,
|
||||
@@ -160,7 +167,7 @@ export default async function grabBotChatTools({
|
||||
if (!powers.is_coordinator) {
|
||||
if (!workspace_id || !powers.is_workspace_admin) return tools;
|
||||
|
||||
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes });
|
||||
const admin = await grabWorkspaceAdminTools({ bot, user_id, workspace_id, powers, session_id, scopes, onTask });
|
||||
|
||||
onWorkspaceAdmin?.(admin);
|
||||
tools.push(...admin.tools);
|
||||
@@ -195,6 +202,7 @@ export default async function grabBotChatTools({
|
||||
requester_name: bot.name || "The coordinator",
|
||||
workers,
|
||||
is_coordinator: true,
|
||||
onTask,
|
||||
}));
|
||||
tools.push(handOverScheduleTool({
|
||||
user_id,
|
||||
@@ -236,6 +244,7 @@ export default async function grabBotChatTools({
|
||||
workers,
|
||||
workspaces,
|
||||
is_coordinator: true,
|
||||
onTask,
|
||||
}),
|
||||
handOverScheduleTool({
|
||||
user_id,
|
||||
|
||||
@@ -62,6 +62,11 @@ type Params = {
|
||||
* (`ask_crew`), so the reply carries its chip.
|
||||
*/
|
||||
onChatroom?: (params: { ref: string }) => void;
|
||||
/**
|
||||
* Called with each tracker task the run worked on, so the message it
|
||||
* posts links to it (`bot_messages.task_ids`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -84,6 +89,7 @@ export default async function grabBotTools({
|
||||
can_delete_tasks,
|
||||
onPropose,
|
||||
onChatroom,
|
||||
onTask,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
return [
|
||||
setPictureTool({ user_id, bot_id, scopes, is_coordinator }),
|
||||
@@ -112,6 +118,7 @@ export default async function grabBotTools({
|
||||
admin_workspace_ids,
|
||||
workspace_id,
|
||||
can_delete: Boolean(can_delete_tasks) && !hooked,
|
||||
onTask,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -21,6 +21,11 @@ type Params = {
|
||||
*/
|
||||
session_id?: number | string;
|
||||
scopes?: StorageScope[];
|
||||
/**
|
||||
* Called with each tracker task the run worked on, so the message it
|
||||
* posts links to it (`bot_messages.task_ids`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
};
|
||||
|
||||
export type WorkspaceAdminTools = {
|
||||
@@ -46,6 +51,7 @@ export default async function grabWorkspaceAdminTools({
|
||||
powers,
|
||||
session_id,
|
||||
scopes = [],
|
||||
onTask,
|
||||
}: Params): Promise<WorkspaceAdminTools> {
|
||||
const workspace = await grabUserWorkspace({ workspace_id, user_id });
|
||||
|
||||
@@ -69,6 +75,7 @@ export default async function grabWorkspaceAdminTools({
|
||||
workers: members,
|
||||
grabTargets,
|
||||
admin_workspace_ids: powers.admin_workspace_ids,
|
||||
onTask,
|
||||
}),
|
||||
handOverScheduleTool({
|
||||
user_id,
|
||||
|
||||
@@ -40,8 +40,10 @@ export default function askUserTool({ user_id, bot_id, session_id, workspace_id,
|
||||
|
||||
return {
|
||||
name: "ask_user",
|
||||
description: `Ask the user multiple-choice questions to be sure what they want before you act, shown as a card in the chat they answer by picking options. Use it when the request is ambiguous or open to more than one reading, when a choice is theirs to make (which target, which items, how far to go), or before something that is hard to undo, costly or visible to others, and you can't tell what they'd pick. Don't ask what they already told you, what you can find out yourself, or what any sensible choice would settle. Put every question in one call (at most one per reply). Their answers arrive as their next message${
|
||||
in_task ? `. In a task, ask, then stop and report that you're waiting for their answers.` : `: after asking, end your reply and wait; don't act on what you asked about until they answer.`
|
||||
description: `Ask the user multiple-choice questions, shown as a card in the chat they answer in a click. Use it whenever what happens next is theirs to decide: when the request is ambiguous or leaves out something that changes the result (which target, which items, how far to go), before something that is hard to undo, costly or visible to others, and to offer the next step once you've answered or reported (the concrete next steps as options, your suggestion first). When you're unsure whether to ask, ask. Don't ask what they already told you, what you can find out yourself, or details that don't change the result. Put every question in one call (at most one per run). Their answers arrive as their next message${
|
||||
in_task
|
||||
? `. In a task, ask, then stop working on what you asked about and finish your report; the card goes out with it.`
|
||||
: `: after asking, end your reply and wait; don't act on what you asked about until they answer.`
|
||||
}`,
|
||||
schema: z.object({
|
||||
title: z.string().trim().max(120).optional().describe("A short heading for the card, e.g. \"Before I deploy\""),
|
||||
@@ -73,7 +75,7 @@ export default function askUserTool({ user_id, bot_id, session_id, workspace_id,
|
||||
|
||||
return `Asked the user ${count} question${count == 1 ? "" : "s"}: the card is on your message. ${
|
||||
in_task
|
||||
? `Stop here and report that you're waiting for their answers.`
|
||||
? `Stop working on what you asked about and finish with your report (if you asked to settle something before going on, say you're waiting for their answers).`
|
||||
: `End your reply now with a short line saying what you need settled; their answers arrive as their next message.`
|
||||
} Don't repeat the questions or options in your text.`;
|
||||
},
|
||||
|
||||
@@ -32,6 +32,11 @@ type Params = {
|
||||
* it may add to.
|
||||
*/
|
||||
members?: BUN_SQLITE_COBBLE_BOTS[];
|
||||
/**
|
||||
* Called with each task the run worked on through this tool, so the
|
||||
* message it posts links to it (\`bot_messages.task_ids\`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -133,6 +138,7 @@ export default function createTaskTool({
|
||||
workspaces = [],
|
||||
admin_workspace_ids = [],
|
||||
members = [],
|
||||
onTask,
|
||||
}: Params): HarnessTool<Args> {
|
||||
const crew = workers.map((worker) => `${worker.id}: ${worker.name}`).join("; ");
|
||||
const places = workspaces.map((workspace) => `${workspace.id}: ${workspace.name}`).join("; ");
|
||||
@@ -194,6 +200,8 @@ export default function createTaskTool({
|
||||
});
|
||||
|
||||
if (twin) {
|
||||
onTask?.({ task_id: Number(twin.id) });
|
||||
|
||||
return `Task #${twin.id} "${twin.title}" is already open with that title. Update it with update_task instead of adding a second one for the same work.`;
|
||||
}
|
||||
|
||||
@@ -208,6 +216,8 @@ export default function createTaskTool({
|
||||
created_by_bot_id: bot_id,
|
||||
});
|
||||
|
||||
onTask?.({ task_id: Number(task.id) });
|
||||
|
||||
const where = place.workspace_id
|
||||
? `in workspace ${place.workspace_id}, ${!place.bot_id ? "workspace-wide (every bot there works on it)" : place.bot_id == Number(bot_id) ? "yours" : `bot ${place.bot_id}'s`}`
|
||||
: place.bot_id == Number(bot_id)
|
||||
|
||||
@@ -27,6 +27,11 @@ type Params = {
|
||||
* routine, a hook call or a chatroom run.
|
||||
*/
|
||||
can_delete?: boolean;
|
||||
/**
|
||||
* Called with each task the run reads in full, adds or moves along, so
|
||||
* the message it posts links to them (\`bot_messages.task_ids\`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -45,6 +50,7 @@ export default async function grabBotTaskTools({
|
||||
admin_workspace_ids = [],
|
||||
workspace_id,
|
||||
can_delete,
|
||||
onTask,
|
||||
}: Params): Promise<HarnessTool[]> {
|
||||
let workers: BUN_SQLITE_COBBLE_BOTS[] = [];
|
||||
let members: BUN_SQLITE_COBBLE_BOTS[] = [];
|
||||
@@ -72,7 +78,7 @@ export default async function grabBotTaskTools({
|
||||
});
|
||||
|
||||
return [
|
||||
listTasksTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id }),
|
||||
listTasksTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, workspace_id, onTask }),
|
||||
createTaskTool({
|
||||
user_id,
|
||||
bot_id,
|
||||
@@ -82,8 +88,9 @@ export default async function grabBotTaskTools({
|
||||
workspaces,
|
||||
admin_workspace_ids,
|
||||
members,
|
||||
onTask,
|
||||
}),
|
||||
updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, scopes }),
|
||||
updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids, scopes, onTask }),
|
||||
...(can_delete ? [deleteTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids })] : []),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -22,6 +22,11 @@ type Params = {
|
||||
* The workspace the run is in, if any.
|
||||
*/
|
||||
workspace_id?: number | string | null;
|
||||
/**
|
||||
* Called with each task the run worked on through this tool, so the
|
||||
* message it posts links to it (\`bot_messages.task_ids\`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -38,7 +43,7 @@ type Args = {
|
||||
* Used both to plan work and to remind the user of what's pending. With
|
||||
* `task_id`, one task with its brief and whole log (who did what, when).
|
||||
*/
|
||||
export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_workspace_ids, workspace_id }: Params): HarnessTool<Args> {
|
||||
export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_workspace_ids, workspace_id, onTask }: Params): HarnessTool<Args> {
|
||||
return {
|
||||
name: "list_tasks",
|
||||
description: `List tasks: yours (your own list and the ones you have in workspaces), the ones in ${workspace_id ? "this workspace" : "a workspace"}, or ${is_coordinator ? "every task in the install" : "every task you can reach (yours, the workspace-wide ones in your workspaces, and as a workspace's admin every task there)"}. Each line is its id, status, title, whose it is, its files and its latest note with who wrote it. Open ones come first (blocked, then doing, then to do). Use it to plan work, and to check what's still pending when the user says hello or asks what's next. A workspace-wide task is worked on by every bot in its workspace: before you work on one, read it with task_id to see its brief and its whole log (which bot did what, and when), so you pick up where the others left off instead of redoing their part.`,
|
||||
@@ -62,6 +67,8 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
|
||||
if (args.task_id) {
|
||||
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
|
||||
|
||||
onTask?.({ task_id: Number(task.id) });
|
||||
|
||||
return describeTaskLog({
|
||||
task,
|
||||
notes: await grabTaskNotes({ task_id: task.id! }),
|
||||
|
||||
@@ -26,6 +26,11 @@ type Params = {
|
||||
* The run's folders, for linking a deliverable by its `[file:ID]` ref.
|
||||
*/
|
||||
scopes?: StorageScope[];
|
||||
/**
|
||||
* Called with each task the run worked on through this tool, so the
|
||||
* message it posts links to it (\`bot_messages.task_ids\`).
|
||||
*/
|
||||
onTask?: (params: { task_id: number }) => void;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
@@ -52,7 +57,7 @@ type Args = {
|
||||
* which bot did what and when. The coordinator and a workspace's admin bot
|
||||
* can also turn a bot's task there into a workspace-wide one.
|
||||
*/
|
||||
export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids = [], scopes = [] }: Params): HarnessTool<Args> {
|
||||
export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_workspace_ids = [], scopes = [], onTask }: Params): HarnessTool<Args> {
|
||||
/**
|
||||
* Only the coordinator and workspace admins get the switch at all.
|
||||
*/
|
||||
@@ -110,6 +115,8 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
|
||||
run: async ({ args }) => {
|
||||
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
|
||||
const said: string[] = [];
|
||||
|
||||
onTask?.({ task_id: Number(task.id) });
|
||||
const workspace_wide = !task.bot_id && Boolean(task.workspace_id);
|
||||
/**
|
||||
* On a workspace-wide task: what this call did, for the log.
|
||||
|
||||
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db";
|
||||
import grabMessagesReplies from "@/src/functions/backend/db/bots/grab-messages-replies";
|
||||
import withMessageUsage from "@/src/functions/backend/db/usage/with-message-usage";
|
||||
import withMessageTasks from "@/src/functions/backend/db/bots/with-message-tasks";
|
||||
import { sendToUser } from "@/src/websocket/(functions)/send-to-user";
|
||||
|
||||
type Params = {
|
||||
@@ -29,10 +30,23 @@ export default async function relayNewBotMessages({ after_id, users }: Params) {
|
||||
* With what each one spent, like a loaded message, so the thread shows
|
||||
* its tokens without a reload.
|
||||
*/
|
||||
const rows = await withMessageUsage({
|
||||
const spent = await withMessageUsage({
|
||||
messages: read.filter((row) => users.has(String(row.user_id))),
|
||||
});
|
||||
|
||||
/**
|
||||
* And the tracker tasks each one is about, as its own user sees them.
|
||||
*/
|
||||
const rows = (
|
||||
await Promise.all(
|
||||
[...new Set(spent.map((row) => row.user_id))].map((user_id) =>
|
||||
withMessageTasks({ messages: spent.filter((row) => row.user_id == user_id), user_id }),
|
||||
),
|
||||
)
|
||||
)
|
||||
.flat()
|
||||
.sort((a, b) => Number(a.id) - Number(b.id));
|
||||
|
||||
const replies = await grabMessagesReplies({
|
||||
message_ids: rows
|
||||
.filter((row) => row.reply_to_message_id)
|
||||
|
||||
@@ -14,6 +14,7 @@ import MessageActions from "./message-actions";
|
||||
import MessageReactions from "./message-reactions";
|
||||
import MessageReplyQuote from "./message-reply-quote";
|
||||
import MessageNoToolsChip from "./message-no-tools-chip";
|
||||
import MessageTaskChips from "./message-task-chips";
|
||||
import MessageUsageChip from "./message-usage-chip";
|
||||
import NeedsYouChip from "./needs-you-chip";
|
||||
import SpeakMessageButton from "./speak-message-button";
|
||||
@@ -38,8 +39,8 @@ type Props = {
|
||||
* One bot message, rendered from markdown (GFM; raw HTML is never
|
||||
* rendered). The summary opening a session the bot moved into is
|
||||
* headed by a link to the session it carries on from. Computers it names (`computerRef`) show as buttons that
|
||||
* switch the bot to them. A quoted reply sits above it, its reactions
|
||||
* below, and a row under it replies, reacts, reads it aloud and shows
|
||||
* switch the bot to them. A quoted reply sits above it, the tracker tasks
|
||||
* it's about and its reactions below, and a row under it replies, reacts, reads it aloud and shows
|
||||
* why it needs you. Its text can be selected and quoted.
|
||||
*
|
||||
* Memoized: a message only renders (and parses its markdown) again when
|
||||
@@ -75,6 +76,7 @@ function BotMessageLine({ message, bot_name, at }: Props) {
|
||||
{linkComputerRefs({ text: message.text || "" })}
|
||||
</Markdown>
|
||||
</Stack>
|
||||
<MessageTaskChips tasks={message.tasks} />
|
||||
{message.id ? (
|
||||
<MessageReactions
|
||||
message_id={message.id}
|
||||
|
||||
@@ -34,16 +34,29 @@ const OtherValue = "other";
|
||||
* radios (one pick) or checkboxes (several), with "Other" and a field to
|
||||
* type into when the bot allows it. Once answered, what the user picked.
|
||||
*/
|
||||
export default function BotQuestionField({ question_id, index, item, draft, answer, open, onChange }: Props) {
|
||||
export default function BotQuestionField({
|
||||
question_id,
|
||||
index,
|
||||
item,
|
||||
draft,
|
||||
answer,
|
||||
open,
|
||||
onChange,
|
||||
}: Props) {
|
||||
const single = item.kind == "single";
|
||||
const picked = answer
|
||||
? [...answer.choices.map((choice) => item.options[choice]), answer.other ? `Other: ${answer.other}` : ""].filter(Boolean)
|
||||
? [
|
||||
...answer.choices.map((choice) => item.options[choice]),
|
||||
answer.other ? `Other: ${answer.other}` : "",
|
||||
].filter(Boolean)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
<MessageDetailsHeading>{`${index + 1}. ${single ? "Pick one" : "Pick any"}`}</MessageDetailsHeading>
|
||||
<Span className="whitespace-pre-wrap text-[13px] leading-5 font-bold text-ink break-words">{item.question}</Span>
|
||||
<Span className="whitespace-pre-wrap text-[13px] leading-5 font-bold text-ink break-words">
|
||||
{item.question}
|
||||
</Span>
|
||||
|
||||
{open ? (
|
||||
<Stack className="mt-2 w-full gap-2! items-stretch">
|
||||
@@ -51,18 +64,37 @@ export default function BotQuestionField({ question_id, index, item, draft, answ
|
||||
<Radios
|
||||
name={`question-${question_id}-${index}`}
|
||||
values={[
|
||||
...item.options.map((option, choice) => ({ value: String(choice), title: option })),
|
||||
...(item.allow_other ? [{ value: OtherValue, title: "Other" }] : []),
|
||||
...item.options.map((option, choice) => ({
|
||||
value: String(choice),
|
||||
title: option,
|
||||
})),
|
||||
...(item.allow_other
|
||||
? [{ value: OtherValue, title: "Other" }]
|
||||
: []),
|
||||
]}
|
||||
wrapperProps={{ className: "w-full flex-col items-start gap-2!" }}
|
||||
labelProps={{ className: "text-[13px] leading-5 text-ink break-words cursor-pointer" }}
|
||||
wrapperProps={{
|
||||
className: "w-full flex-col items-start gap-2!",
|
||||
}}
|
||||
labelProps={{
|
||||
className:
|
||||
"text-[13px] leading-5 text-ink break-words cursor-pointer",
|
||||
}}
|
||||
changeHandler={(value) =>
|
||||
onChange(
|
||||
value == OtherValue
|
||||
? { ...draft, choices: [], other_on: true }
|
||||
: { ...draft, choices: [Number(value)], other_on: false },
|
||||
? {
|
||||
...draft,
|
||||
choices: [],
|
||||
other_on: true,
|
||||
}
|
||||
: {
|
||||
...draft,
|
||||
choices: [Number(value)],
|
||||
other_on: false,
|
||||
},
|
||||
)
|
||||
}
|
||||
wrap
|
||||
/>
|
||||
) : (
|
||||
<Stack className="w-full gap-2! items-stretch">
|
||||
@@ -75,8 +107,15 @@ export default function BotQuestionField({ question_id, index, item, draft, answ
|
||||
onChange({
|
||||
...draft,
|
||||
choices: checked
|
||||
? [...new Set([...draft.choices, choice])]
|
||||
: draft.choices.filter((c) => c != choice),
|
||||
? [
|
||||
...new Set([
|
||||
...draft.choices,
|
||||
choice,
|
||||
]),
|
||||
]
|
||||
: draft.choices.filter(
|
||||
(c) => c != choice,
|
||||
),
|
||||
})
|
||||
}
|
||||
/>
|
||||
@@ -85,7 +124,12 @@ export default function BotQuestionField({ question_id, index, item, draft, answ
|
||||
<BotQuestionOption
|
||||
label="Other"
|
||||
checked={draft.other_on}
|
||||
onChange={(checked) => onChange({ ...draft, other_on: checked })}
|
||||
onChange={(checked) =>
|
||||
onChange({
|
||||
...draft,
|
||||
other_on: checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</Stack>
|
||||
@@ -98,7 +142,9 @@ export default function BotQuestionField({ question_id, index, item, draft, answ
|
||||
placeholder="Your own answer"
|
||||
maxLength={AppData.BotQuestionOtherMaxChars}
|
||||
value={draft.other}
|
||||
onChange={(e) => onChange({ ...draft, other: e.target.value })}
|
||||
onChange={(e) =>
|
||||
onChange({ ...draft, other: e.target.value })
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</Stack>
|
||||
|
||||
@@ -92,6 +92,7 @@ export default function FileRefChip({ file_id }: Props) {
|
||||
url={file.url}
|
||||
media_type={file.media_type}
|
||||
size={file.size}
|
||||
full_path={file.full_path}
|
||||
className="inline-flex h-6 max-w-full gap-1.5 items-center px-1.5 align-middle rounded-default-xs border-0 bg-sunken text-[13px] font-bold leading-4 text-ink hover:opacity-80"
|
||||
>
|
||||
<AttachmentIcon media_type={file.media_type as MediaType} />
|
||||
|
||||
@@ -38,6 +38,7 @@ export default function FileRow({ file, can_manage, busy, gallery, onDelete }: P
|
||||
url={file.url}
|
||||
media_type={file.media_type}
|
||||
size={file.size}
|
||||
full_path={file.full_path}
|
||||
gallery={gallery}
|
||||
className="text-[13px] font-bold leading-5 text-ink break-words hover:opacity-80"
|
||||
>
|
||||
|
||||
@@ -14,11 +14,22 @@ export default function MessageAttachment({
|
||||
media_type,
|
||||
url,
|
||||
thumbnail_url,
|
||||
size,
|
||||
full_path,
|
||||
gallery,
|
||||
}: BotMessageAttachment & { gallery?: FilePreviewItem[] }) {
|
||||
if (media_type == "image") {
|
||||
return (
|
||||
<FilePreviewLink name={name} url={url} media_type={media_type} gallery={gallery} title={name} className="block">
|
||||
<FilePreviewLink
|
||||
name={name}
|
||||
url={url}
|
||||
media_type={media_type}
|
||||
size={size}
|
||||
full_path={full_path}
|
||||
gallery={gallery}
|
||||
title={name}
|
||||
className="block"
|
||||
>
|
||||
<Img
|
||||
src={thumbnail_url || url}
|
||||
alt={name}
|
||||
@@ -33,6 +44,8 @@ export default function MessageAttachment({
|
||||
name={name}
|
||||
url={url}
|
||||
media_type={media_type}
|
||||
size={size}
|
||||
full_path={full_path}
|
||||
title={name}
|
||||
className="flex max-w-64 items-center gap-2 rounded-default-lg border border-solid border-hairline bg-surface px-3 py-2 text-[13px] leading-[18px] text-ink no-underline hover:border-hairline-strong"
|
||||
>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { MessageTask } from "@/src/types";
|
||||
import TaskRefChip from "./task-ref-chip";
|
||||
|
||||
type Props = MessageTask;
|
||||
|
||||
/**
|
||||
* One tracker task linked under a bot message: its chip with title and
|
||||
* status, opening the task.
|
||||
*/
|
||||
export default function MessageTaskChip({ id, title, status }: Props) {
|
||||
return <TaskRefChip task_id={id} title={title} status={status} />;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import type { MessageTask } from "@/src/types";
|
||||
import MessageTaskChip from "./message-task-chip";
|
||||
|
||||
type Props = {
|
||||
tasks?: MessageTask[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The tracker tasks a bot message is about, under it: every task the run
|
||||
* behind it read in full, added, moved along or handed over (and the one a
|
||||
* handed-over run was for), recorded by the app rather than written by the
|
||||
* bot, so a message always says which tasks it concerns. Each opens the
|
||||
* task.
|
||||
*/
|
||||
export default function MessageTaskChips({ tasks }: Props) {
|
||||
if (!tasks?.length) return null;
|
||||
|
||||
return (
|
||||
<Row className="gap-1.5! items-center flex-wrap max-w-full">
|
||||
<Span className="text-[11px] leading-4 text-ink-secondary whitespace-nowrap">
|
||||
{tasks.length == 1 ? "Task" : "Tasks"}
|
||||
</Span>
|
||||
{/* Keyed by what it shows, so a reload with a new title or status redraws it. */}
|
||||
{tasks.map((task) => (
|
||||
<MessageTaskChip key={`${task.id}:${task.status}:${task.title}`} {...task} />
|
||||
))}
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +1,40 @@
|
||||
import { useContext, useState } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { ListChecks } from "lucide-react";
|
||||
import TaskDetailModal from "@/src/components/general/task-detail-modal";
|
||||
import { TaskStatuses } from "@/src/dict/task-dict";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
|
||||
type Props = {
|
||||
task_id: number;
|
||||
/**
|
||||
* Its title, when the page already has it (a message's linked tasks):
|
||||
* shown at once instead of "Task <id>".
|
||||
*/
|
||||
title?: string;
|
||||
/**
|
||||
* Its status, when known: shown after the title, and kept current as
|
||||
* the task is changed in its modal.
|
||||
*/
|
||||
status?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A task on the tracker named in a message (`taskRef`): a chip that opens
|
||||
* the task in its own modal, read when it opens. One the user doesn't
|
||||
* reach says so there.
|
||||
* A task on the tracker named in a message (`taskRef`) or linked under it
|
||||
* (`MessageTaskChips`): a chip that opens the task in its own modal, read
|
||||
* when it opens. One the user doesn't reach says so there.
|
||||
*/
|
||||
export default function TaskRefChip({ task_id }: Props) {
|
||||
export default function TaskRefChip({ task_id, title: initial_title, status: initial_status }: Props) {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [title, setTitle] = useState<string>();
|
||||
const [title, setTitle] = useState<string | undefined>(initial_title || undefined);
|
||||
const [status, setStatus] = useState<string | undefined>(initial_status || undefined);
|
||||
const [deleted, setDeleted] = useState(false);
|
||||
const label = title ? `#${task_id} ${title}` : `Task ${task_id}`;
|
||||
const status_title = status ? TaskStatuses.find((it) => it.value == status)?.title : undefined;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -30,17 +44,37 @@ export default function TaskRefChip({ task_id }: Props) {
|
||||
title={deleted ? "This task was deleted" : "Open the task"}
|
||||
disabled={deleted}
|
||||
onClick={() => setOpen(true)}
|
||||
className="inline-flex h-6 max-w-full gap-1.5! flex-nowrap items-center px-1.5! py-0! align-middle rounded-default-xs border-0 bg-sunken text-[13px] font-bold leading-4 text-ink whitespace-nowrap hover:opacity-80 [&_.twui-button-content-wrapper]:min-w-0"
|
||||
className={twMerge(
|
||||
"inline-flex h-6 max-w-full gap-1.5! flex-nowrap items-center px-1.5! py-0! align-middle rounded-default-xs border-0",
|
||||
"text-[13px] font-bold leading-4 whitespace-nowrap hover:opacity-80 [&_.twui-button-content-wrapper]:min-w-0",
|
||||
/**
|
||||
* The ghost button sets its own dark fill and text
|
||||
* (\`dark:bg-transparent\`, \`dark:text-primary-dark-text\`),
|
||||
* so the chip's colours are given for both themes, like
|
||||
* the link chips beside it.
|
||||
*/
|
||||
"bg-sunken dark:bg-sunken hover:bg-sunken dark:hover:bg-sunken",
|
||||
"text-ink dark:text-ink",
|
||||
)}
|
||||
>
|
||||
<ListChecks size={13} aria-hidden className="shrink-0" />
|
||||
<Span className="min-w-0 truncate">{deleted ? `Task ${task_id} (deleted)` : label}</Span>
|
||||
{status_title && !deleted ? (
|
||||
<Span className="shrink-0 font-normal text-ink-secondary">{status_title}</Span>
|
||||
) : null}
|
||||
</Button>
|
||||
<TaskDetailModal
|
||||
task={open ? { id: task_id } : null}
|
||||
can_manage={canManageCrew({ user_types: pageProps?.user_types })}
|
||||
onClose={() => setOpen(false)}
|
||||
onLoaded={({ task }) => setTitle(task.title || undefined)}
|
||||
onChanged={({ task }) => setTitle(task.title || undefined)}
|
||||
onLoaded={({ task }) => {
|
||||
setTitle(task.title || undefined);
|
||||
if (initial_status) setStatus(task.status || undefined);
|
||||
}}
|
||||
onChanged={({ task }) => {
|
||||
setTitle(task.title || undefined);
|
||||
if (initial_status) setStatus(task.status || undefined);
|
||||
}}
|
||||
onDeleted={() => {
|
||||
setDeleted(true);
|
||||
setOpen(false);
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { BotFileScopesPayload } from "@/src/types";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { BotFileScope } from "@/src/dict/bot-file-dict";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
import botFileFullPath from "@/src/utils/bot-file-full-path";
|
||||
|
||||
/**
|
||||
* A conversation's files: the bot's own, or a workspace's shared ones.
|
||||
@@ -134,6 +135,7 @@ function toPublicFile({ file }: { file: BotFileWithMediaLite }) {
|
||||
owner_id: Number(file.owner_id) || 0,
|
||||
created_at: Number(file.created_at) || 0,
|
||||
url: media_url || "",
|
||||
full_path: botFileFullPath({ scope: file.scope, owner_id: file.owner_id, path: file.path }),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -235,6 +235,12 @@ export type TaskFile = BUN_SQLITE_COBBLE_TASK_MEDIA & {
|
||||
* Whether the `media` row is still there.
|
||||
*/
|
||||
missing?: boolean;
|
||||
/**
|
||||
* Where it sits on the data volume, and its size in bytes, when the
|
||||
* file is on disk.
|
||||
*/
|
||||
full_path?: string;
|
||||
size?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1470,6 +1476,11 @@ export type PublicBotFile = {
|
||||
* Where the bytes are served (`/media/<media id>`, private).
|
||||
*/
|
||||
url: string;
|
||||
/**
|
||||
* Where it sits on the data volume (`bots/3/reports/q3.md`), shown in
|
||||
* the file preview.
|
||||
*/
|
||||
full_path: string;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1496,6 +1507,12 @@ export type FilePreviewItem = {
|
||||
url: string;
|
||||
media_type?: string | null;
|
||||
size?: number;
|
||||
/**
|
||||
* Where the file sits on the data volume (`bots/3/reports/q3.md`), or
|
||||
* its absolute path when it lives outside it. The preview shows it
|
||||
* beside the size.
|
||||
*/
|
||||
full_path?: string;
|
||||
};
|
||||
|
||||
export type StorageEntry = {
|
||||
@@ -1523,6 +1540,11 @@ export type StorageEntry = {
|
||||
* workspace's name.
|
||||
*/
|
||||
label?: string;
|
||||
/**
|
||||
* Where it sits on the data volume (`computers/2/bots/5/notes.md`), or
|
||||
* its absolute path when the volume's root is elsewhere.
|
||||
*/
|
||||
full_path?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1694,6 +1716,14 @@ export type BotMessageAttachment = {
|
||||
* The bot file it is, when it was saved in one of the bot's folders.
|
||||
*/
|
||||
file_id?: number;
|
||||
/**
|
||||
* Where it sits on the data volume (`media/1/1793027689070.pdf`).
|
||||
*/
|
||||
full_path?: string;
|
||||
/**
|
||||
* Its size in bytes, when the file is on disk.
|
||||
*/
|
||||
size?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1726,6 +1756,21 @@ export type BotMessageWithAttachments = BUN_SQLITE_COBBLE_BOT_MESSAGES & {
|
||||
* summed. Only on bot messages that took at least one call.
|
||||
*/
|
||||
usage?: TokenUsageSummary | null;
|
||||
/**
|
||||
* The tracker tasks the message is about (\`task_ids\`) that the viewer
|
||||
* reaches, in order, for the chips under it. Only on bot messages that
|
||||
* name one.
|
||||
*/
|
||||
tasks?: MessageTask[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A tracker task linked under a bot message: enough for its chip.
|
||||
*/
|
||||
export type MessageTask = {
|
||||
id: number;
|
||||
title: string;
|
||||
status: string;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import botFileFullPath from "./bot-file-full-path";
|
||||
|
||||
describe("botFileFullPath", () => {
|
||||
test("a bot's file sits under bots/<id>", () => {
|
||||
expect(botFileFullPath({ scope: "bot", owner_id: 3, path: "reports/q3.md" })).toBe("bots/3/reports/q3.md");
|
||||
});
|
||||
|
||||
test("a workspace's file sits under workspaces/<id>", () => {
|
||||
expect(botFileFullPath({ scope: "workspace", owner_id: "7", path: "/brief.md" })).toBe(
|
||||
"workspaces/7/brief.md",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
|
||||
type Params = {
|
||||
scope?: string | null;
|
||||
owner_id?: number | string | null;
|
||||
path?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Where a bot file sits on the data volume: its folder (`bots/<id>` or
|
||||
* `workspaces/<id>`) and its path inside it, e.g. `bots/3/reports/q3.md`.
|
||||
*/
|
||||
export default function botFileFullPath({ scope, owner_id, path }: Params) {
|
||||
const dir = scope == "workspace" ? AppData.WorkspaceDataDir : AppData.BotDataDir;
|
||||
const inside = (path || "").replace(/^\/+/, "");
|
||||
|
||||
return [dir, String(Number(owner_id) || 0), inside].filter(Boolean).join("/");
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import dataVolumePath from "./data-volume-path";
|
||||
|
||||
describe("dataVolumePath", () => {
|
||||
test("a file on the data volume reads from its root", () => {
|
||||
expect(dataVolumePath({ absolute: "/data/computers/2/bots/5/notes.md", data_dir: "/data" })).toBe(
|
||||
"computers/2/bots/5/notes.md",
|
||||
);
|
||||
});
|
||||
|
||||
test("a file elsewhere keeps its absolute path", () => {
|
||||
expect(dataVolumePath({ absolute: "/srv/main/notes.md", data_dir: "/data" })).toBe("/srv/main/notes.md");
|
||||
expect(dataVolumePath({ absolute: "/database/cobble.db", data_dir: "/data" })).toBe("/database/cobble.db");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import path from "node:path";
|
||||
import grabDirNames from "./grab-dir-names";
|
||||
import { isInsideRoot } from "./resolve-bot-path";
|
||||
|
||||
type Params = {
|
||||
absolute: string;
|
||||
/**
|
||||
* The data directory, else `DATA_DIR` (tests pass their own).
|
||||
*/
|
||||
data_dir?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* How the file preview names a file on disk: its path on the data volume
|
||||
* (`computers/2/bots/5/notes.md`), the way bots' and media rows' paths
|
||||
* read, or the absolute path when it lives elsewhere (a computer whose
|
||||
* home was mounted from outside the data directory).
|
||||
*/
|
||||
export default function dataVolumePath({ absolute, data_dir }: Params) {
|
||||
const root = path.resolve(data_dir || grabDirNames().DATA_DIR);
|
||||
const resolved = path.resolve(absolute);
|
||||
|
||||
if (resolved == root || !isInsideRoot({ root, absolute: resolved })) return resolved;
|
||||
|
||||
return path.relative(root, resolved).split(path.sep).join("/");
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import messageTaskIds from "./message-task-ids";
|
||||
|
||||
describe("messageTaskIds", () => {
|
||||
test("reads a stored list", () => {
|
||||
expect(messageTaskIds({ task_ids: "[3,12]" })).toEqual([3, 12]);
|
||||
});
|
||||
|
||||
test("keeps each id once, in first-touched order", () => {
|
||||
expect(messageTaskIds({ task_ids: [12, 3, 12, "3", 7] })).toEqual([12, 3, 7]);
|
||||
});
|
||||
|
||||
test("drops what isn't a task id", () => {
|
||||
expect(messageTaskIds({ task_ids: [0, -2, 1.5, "x", null, undefined, 4] })).toEqual([4]);
|
||||
});
|
||||
|
||||
test("reads nothing from an empty or broken value", () => {
|
||||
expect(messageTaskIds({ task_ids: null })).toEqual([]);
|
||||
expect(messageTaskIds({ task_ids: "" })).toEqual([]);
|
||||
expect(messageTaskIds({ task_ids: "not json" })).toEqual([]);
|
||||
expect(messageTaskIds({ task_ids: '{"id":3}' })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
type Params = {
|
||||
/**
|
||||
* A bot message's `task_ids` (JSON list of task ids), or a list of ids
|
||||
* to tidy before it's stored.
|
||||
*/
|
||||
task_ids?: string | (number | string | null | undefined)[] | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The tracker task ids a bot message is about: positive integers, each
|
||||
* once, in the order they were first touched. Anything unreadable reads as
|
||||
* none, so a bad row never breaks the thread.
|
||||
*/
|
||||
export default function messageTaskIds({ task_ids }: Params): number[] {
|
||||
let list: unknown = task_ids;
|
||||
|
||||
if (typeof task_ids == "string") {
|
||||
try {
|
||||
list = JSON.parse(task_ids);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(list)) return [];
|
||||
|
||||
const ids = list.map((id) => Number(id)).filter((id) => Number.isInteger(id) && id > 0);
|
||||
|
||||
return [...new Set(ids)];
|
||||
}
|
||||
Reference in New Issue
Block a user