Compare commits

...
2 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 63d25337f5 Release v0.12.3
Release image / image (release) Canceled after 0s
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 16:41:24 +01:00
tbenandClaude Opus 5.5 3cbfb4e3da Restore workspace-wide tasks, set by admin bots or by hand
A task still belongs to one bot by default. A workspace task can now be
workspace-wide (no bot) when asked for: every bot working there sees it,
works on it and logs what it did. On such a task update_task records each
call's status move and filed files as a note under the bot, and list_tasks
with task_id reads the whole log with who and when.

The coordinator and a workspace's admin bot (update_task workspace_wide)
or a crew manager (Make workspace-wide) turn a bot's open workspace task
workspace-wide; hand-over gives one back to a single bot. Other bots can't
switch or claim tasks. The boot step that gave bot-less tasks a bot is
gone, and a leaving bot's workspace-wide tasks stay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-03 16:41:24 +01:00
39 changed files with 503 additions and 137 deletions
+1 -1
View File
@@ -156,7 +156,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
### Tasks (the to-do tracker)
`tasks` (**every task belongs to a bot**, the coordinator included, never shared: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there, enforced by `taskScopeValues`; a worker reaches only its own, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; a bot removed from a workspace or deleted passes its tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`, also run at boot for rows without a bot)), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id`; `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id`; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there), sets it doing and queues a job with `params.tracker_task_id`; `noteTrackerTask` notes the job's end on it and blocks it on failure. **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
### Envs
+2 -2
View File
@@ -791,11 +791,11 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
{
tableName: "tasks",
tableDescription: `The crew's to-do list: work that is tracked until it's done. A bot's own list (\`bot_id\` alone), or a workspace's tasks (\`workspace_id\`, with \`bot_id\` naming the bot there that has it, or null while it's shared). A bot reaches its own list and, in each workspace it works in, its tasks there and the shared ones; a workspace admin every task in its workspace; the coordinator every task. Not the same thing as \`bot_tasks\` or \`bots_queue\`: those record a queued job, this records the work`,
tableDescription: `The crew's to-do list: work that is tracked until it's done. A bot's own list (\`bot_id\` alone), or a workspace's tasks (\`workspace_id\`, with \`bot_id\` naming the bot there that has it, or null for a workspace-wide task every bot there works on, made only when asked for). A bot reaches its own list and, in each workspace it works in, its tasks there and the workspace-wide ones; a workspace admin every task in its workspace; the coordinator every task. Not the same thing as \`bot_tasks\` or \`bots_queue\`: those record a queued job, this records the work`,
fields: [
{
fieldName: "bot_id",
fieldDescription: `The bot that has the task: its own list's, or with \`workspace_id\` its task in that workspace; null for a workspace's shared task nobody has yet`,
fieldDescription: `The bot that has the task: its own list's, or with \`workspace_id\` its task in that workspace; null for a workspace-wide task, which every bot in that workspace works on and logs (\`task_notes.bot_id\`)`,
dataType: "INTEGER",
foreignKey: {
cascadeDelete: true,
+1 -1
View File
@@ -512,7 +512,7 @@ export type BUN_SQLITE_COBBLE_TASKS = {
*/
updated_at?: number | "";
/**
* The bot that has the task: its own list's, or with `workspace_id` its task in that workspace; null for a workspace's shared task nobody has yet
* The bot that has the task: its own list's, or with `workspace_id` its task in that workspace; null for a workspace-wide task, which every bot in that workspace works on and logs (`task_notes.bot_id`)
*/
bot_id?: number | "";
/**
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.12.2",
"version": "0.12.3",
"module": "index.ts",
"type": "module",
"private": true,
+33 -3
View File
@@ -35,8 +35,9 @@ type Props = {
* One task opened: its status (a crew manager moves it along), who has it and where, who added it and
* when it last moved, what it is, its files (each opening its bytes), its
* notes oldest first, a box to add a note, and edit or delete. A crew
* manager can file a new deliverable straight onto it, or hand an open
* one to another bot, which starts on it.
* manager can file a new deliverable straight onto it, hand an open one to
* another bot, which starts on it, or make a bot's open workspace task
* workspace-wide.
*/
export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted }: Props) {
const { pageProps } = useContext(AppContext);
@@ -174,6 +175,33 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
Hand over
</Button>
) : null}
{task.workspace_id && task.bot_id && (OpenTaskStatuses as readonly string[]).includes(task.status || "") ? (
<Button
title="Make it workspace-wide: every bot in the workspace works on it"
type="button"
variant="ghost"
color="gray"
size="small"
disabled={busy}
onClick={() => {
if (
!window.confirm(
`Make "${task.title}" workspace-wide? It stops being ${task.bot_name || "this bot"}'s, and every bot in ${task.workspace_name || "the workspace"} works on it.`,
)
)
return;
run({
path: "tasks/make-workspace-wide",
body: { task_id: Number(task.id) },
done: "It's workspace-wide now.",
}).catch(() => {});
}}
className="px-2! text-[12px]"
>
Make workspace-wide
</Button>
) : null}
<Button
title="Edit the task"
type="button"
@@ -231,7 +259,9 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
<Span className="min-w-0 truncate">{task.bot_name || `Bot ${task.bot_id}`}</Span>
</>
) : (
<Span className="text-ink-secondary">No bot</Span>
<Span className="text-ink-secondary">
{task.workspace_id ? "Every bot in the workspace (workspace-wide)" : "No bot"}
</Span>
)}
</TaskFactRow>
<TaskFactRow label="Where">
+30 -13
View File
@@ -12,6 +12,11 @@ import { TaskStatuses, type TaskStatus } from "@/src/dict/task-dict";
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
import type { TaskDetail } from "@/src/types";
/**
* The picker's value for a workspace-wide task, which no bot has.
*/
const WorkspaceWideValue = "workspace";
type Props = {
/**
* The list it's added to: a bot's own, or a workspace's.
@@ -19,8 +24,9 @@ type Props = {
bot_id?: number | null;
workspace_id?: number | null;
/**
* Adding to a workspace without a `bot_id`: the bots there to pick who
* has it, since every task belongs to a bot.
* Adding to a workspace: the bots there to pick who has it (`bot_id`,
* when given, first), plus the workspace-wide choice every bot there
* works on. A task goes to a bot unless that's picked.
*/
bots?: { id?: number | string | null; name?: string | null }[];
/**
@@ -52,10 +58,13 @@ export default function TaskForm({
const [blocked_reason, setBlockedReason] = useState(
task?.blocked_reason || "",
);
const pick_bot = !task && !bot_id && Boolean(workspace_id);
const [picked_bot_id, setPickedBotId] = useState<number | undefined>(
bots[0]?.id ? Number(bots[0].id) : undefined,
const pick_bot = !task && Boolean(workspace_id);
const default_bot_id = bot_id || (bots[0]?.id ? Number(bots[0].id) : undefined);
const [picked, setPicked] = useState<string>(
default_bot_id ? String(default_bot_id) : WorkspaceWideValue,
);
const workspace_wide = pick_bot && picked == WorkspaceWideValue;
const picked_bot_id = pick_bot && !workspace_wide ? Number(picked) || undefined : bot_id || undefined;
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
@@ -67,7 +76,7 @@ export default function TaskForm({
return;
}
if (pick_bot && !picked_bot_id) {
if (pick_bot && !workspace_wide && !picked_bot_id) {
setError("Pick the bot that has it.");
return;
}
@@ -82,8 +91,9 @@ export default function TaskForm({
method: "POST",
body: {
task_id: task?.id ? Number(task.id) : undefined,
bot_id: task ? undefined : bot_id || picked_bot_id || undefined,
bot_id: task || workspace_wide ? undefined : picked_bot_id,
workspace_id: task ? undefined : workspace_id || undefined,
workspace_wide: task ? undefined : workspace_wide || undefined,
title,
description,
status,
@@ -120,12 +130,19 @@ export default function TaskForm({
title="Who has it"
label="Who has it"
showLabel
options={bots.map((bot) => ({
title: bot.name || `Bot ${bot.id}`,
value: String(bot.id),
default: Number(bot.id) == picked_bot_id,
}))}
changeHandler={(value) => setPickedBotId(Number(value) || undefined)}
options={[
...bots.map((bot) => ({
title: bot.name || `Bot ${bot.id}`,
value: String(bot.id),
default: String(bot.id) == picked,
})),
{
title: "Every bot here (workspace-wide)",
value: WorkspaceWideValue,
default: workspace_wide,
},
]}
changeHandler={(value) => setPicked(String(value))}
/>
) : null}
<CodeEditor
+19 -9
View File
@@ -12,7 +12,8 @@ import botStoneProps from "@/src/utils/bot-stone-props";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import relativeTime from "@/src/utils/relative-time";
import taskPlaceLabel from "@/src/utils/task-place-label";
import { Trash2 } from "lucide-react";
import Center from "@moduletrace/twui/layout/Center";
import { Trash2, Users } from "lucide-react";
import RowIconButton from "./row-icon-button";
import TaskStatusChip from "./task-status-chip";
import TaskStatusMoves from "./task-status-moves";
@@ -36,7 +37,8 @@ type Props = {
};
/**
* One task: whose it is (a bot's stone), its title and status, where it
* One task: whose it is (a bot's stone, or a crew mark when it's
* workspace-wide), its title and status, where it
* is and who has it, what it's blocked on, its latest note and how long ago it
* moved. Its title opens it in a modal.
*/
@@ -47,12 +49,18 @@ export default function TaskListItem({ task, onOpen, onStatusChange, onDelete, b
return (
<Row className="w-full gap-3! flex-nowrap items-start px-3 py-3 border-0 border-b border-solid border-hairline last:border-b-0">
<BotAvatar
image_media_id={task.bot_image_media_id}
{...botStoneProps({ color: task.bot_color, stone: task.bot_stone, hue: task.bot_hue })}
face={(task.bot_face || "idle") as BotFace}
size={28}
/>
{task.bot_id ? (
<BotAvatar
image_media_id={task.bot_image_media_id}
{...botStoneProps({ color: task.bot_color, stone: task.bot_stone, hue: task.bot_hue })}
face={(task.bot_face || "idle") as BotFace}
size={28}
/>
) : (
<Center title="Workspace-wide: every bot here works on it" className="size-7 shrink-0 text-ink-secondary">
<Users size={18} />
</Center>
)}
<Stack className="grow min-w-0 gap-0.5! items-stretch">
<Row className="w-full gap-2! flex-nowrap items-center">
<Button
@@ -94,7 +102,9 @@ export default function TaskListItem({ task, onOpen, onStatusChange, onDelete, b
) : null}
</Row>
{task.latest_note ? (
<Span className="text-xs leading-4 text-ink-secondary line-clamp-2">{task.latest_note}</Span>
<Span className="text-xs leading-4 text-ink-secondary line-clamp-2">
{task.latest_note_by ? `${task.latest_note_by}: ${task.latest_note}` : task.latest_note}
</Span>
) : null}
{can_manage && onStatusChange ? (
<TaskStatusMoves status={task.status} disabled={busy} onMove={onStatusChange} className="pt-0.5" />
+2 -1
View File
@@ -241,11 +241,12 @@ You are working through a task on your own; the user isn't watching. Use your to
*/
export const TasksNote = `# Tasks
Tasks are the crew's to-do list. Every task belongs to one bot, on its own list or in a workspace. You see your own; a workspace's admin sees every task in that workspace, and the coordinator sees everything.
Tasks are the crew's to-do list. A task belongs to one bot, on its own list or in a workspace, unless it's workspace-wide: then it's nobody's, and every bot in that workspace sees it and works on it. You see your own and the workspace-wide ones in your workspaces; a workspace's admin sees every task in that workspace, and the coordinator sees everything.
- list_tasks shows what's open: yours, a workspace's, or (as the coordinator) all of it. Check it before you plan work, so you don't start something already tracked.
- create_task adds one, with a brief: what to do, where, and what done looks like. Only add a task for work that will take more than this reply; never one for something you're doing now.
- update_task moves it along. Set doing when you start, blocked with a reason when only the user can unblock it, and done only once the work is verified (see the check note above). Add a note as you go: it's what the user reads on the task, so one short line per real step, not a play-by-play.
- On a workspace-wide task, read its log first (list_tasks with task_id) to see which bot did what and when, take a part nobody has done yet, and log each part you finish with update_task. Every note is recorded under your name and id, so the log is how the crew stays in step.
- A deliverable is a file: save it first with write_file, make_pdf or generate_image, then pass its [file:ID] ref in deliverable_file_ids, so the task carries what it produced.`;
/**
+3 -2
View File
@@ -1,6 +1,7 @@
/**
* A task's status. Tasks are the crew's to-do list, every task one bot's
* (on its own list or in a workspace), and every move through this list is a step in the
* A task's status. Tasks are the crew's to-do list, a task one bot's (on
* its own list or in a workspace) unless it's workspace-wide (every bot
* there works on it), and every move through this list is a step in the
* work: `blocked` is what a bot (or the user) sets when only the user can
* unblock it, and `done` is only ever set once the work was verified.
*/
@@ -1,10 +0,0 @@
import passOnBotTasks from "./pass-on-bot-tasks";
/**
* At boot: every task belongs to a bot. Workspace tasks left without one
* by earlier versions ("shared") go to the workspace's admin bot, else the
* coordinator.
*/
export default async function assignOwnerlessTasks() {
return await passOnBotTasks({});
}
@@ -19,6 +19,11 @@ type Params = {
title: string;
description?: string;
status?: TaskStatus;
/**
* In a workspace, nobody's: every bot working there sees it and works on
* it (`taskScopeValues`). Only when asked for.
*/
workspace_wide?: boolean;
/**
* The bot creating it with its tool; none for a user's manual add.
*/
@@ -27,7 +32,7 @@ type Params = {
/**
* Adds a task to a bot's own list or a workspace's, there for one of its
* bots (`bot_id` too): every task belongs to a bot. A user adds one to a bot they chat with or
* bots (`bot_id` too), or workspace-wide when asked (`workspace_wide`). A user adds one to a bot they chat with or
* a workspace they're in; a bot's run adds one to its own list or to a
* workspace it works in (its tool checks that). A workspace's task can
* only go to a bot working there. Caps a list at `TaskMaxPerScope` open and
@@ -40,9 +45,10 @@ export default async function createTask({
title,
description,
status,
workspace_wide,
created_by_bot_id,
}: Params): Promise<TaskDetail> {
const scope = taskScopeValues({ bot_id, workspace_id });
const scope = taskScopeValues({ bot_id, workspace_id, workspace_wide });
const role = await grabCrewRole({ user_id });
if (!created_by_bot_id && role == "member") {
@@ -12,7 +12,7 @@ type Params = {
/**
* Who takes over a workspace task whose bot is gone: the workspace's admin
* bot, else the coordinator. Every task belongs to a bot, so none is left
* bot, else the coordinator. A bot's task stays a bot's, so none is left
* without one.
*/
export default async function grabTaskHeir({ workspace_id, except_bot_id }: Params) {
@@ -0,0 +1,21 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { TaskNote } from "@/src/types";
type Params = {
task_id: number | string;
};
/**
* A task's log, oldest first, each note with the bot that wrote it. The
* caller checked who is asking reaches the task.
*/
export default async function grabTaskNotes({ task_id }: Params): Promise<TaskNote[]> {
const res = await BunSQLite.sql<TaskNote>({
sql: `SELECT n.*, nb.name AS bot_name FROM task_notes n
LEFT JOIN bots nb ON nb.id = n.bot_id
WHERE n.task_id = ? ORDER BY n.id ASC`,
values: [Number(task_id)],
});
return res.payload || [];
}
+4 -11
View File
@@ -1,10 +1,11 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { TaskDetail, TaskNote } from "@/src/types";
import type { TaskDetail } from "@/src/types";
import AppError from "@/src/utils/app-error";
import botFaceSql from "@/src/utils/bot-face-sql";
import taskScopesSql from "@/src/utils/task-access/task-scopes-sql";
import grabCrewRole from "../access/grab-crew-role";
import grabTaskMedia from "./grab-task-media";
import grabTaskNotes from "./grab-task-notes";
type Params = {
/**
@@ -45,15 +46,7 @@ export default async function grabTask({ user_id, task_id }: Params): Promise<Ta
throw new AppError(`Task not found.`);
}
const [notes_res, files] = await Promise.all([
BunSQLite.sql<TaskNote>({
sql: `SELECT n.*, nb.name AS bot_name FROM task_notes n
LEFT JOIN bots nb ON nb.id = n.bot_id
WHERE n.task_id = ? ORDER BY n.id ASC`,
values: [Number(task_id)],
}),
grabTaskMedia({ task_id }),
]);
const [notes, files] = await Promise.all([grabTaskNotes({ task_id }), grabTaskMedia({ task_id })]);
return { ...row, notes: notes_res.payload || [], files };
return { ...row, notes, files };
}
+10 -2
View File
@@ -27,6 +27,10 @@ type Params = {
* Only the tasks this bot has (anywhere, unless narrowed).
*/
only_bot_id?: number | string | null;
/**
* With `only_bot_id`: also the workspace-wide tasks (no bot) it reaches.
*/
with_workspace_wide?: boolean;
/**
* Only one workspace's tasks.
*/
@@ -48,7 +52,7 @@ type Params = {
/**
* Tasks with what a list shows beside them: the bot (its face as this user
* sees it), the workspace and the newest note. Open ones first, blocked
* sees it), the workspace and the newest note with the bot that wrote it. Open ones first, blocked
* before doing before to do, then the oldest.
*/
export default async function grabTasks({
@@ -57,6 +61,7 @@ export default async function grabTasks({
is_coordinator,
admin_workspace_ids,
only_bot_id,
with_workspace_wide,
only_workspace_id,
own_list,
statuses,
@@ -77,7 +82,7 @@ export default async function grabTasks({
}
if (only_bot_id) {
where.push(`t.bot_id = ?`);
where.push(with_workspace_wide ? `(t.bot_id = ? OR (t.bot_id IS NULL AND t.workspace_id IS NOT NULL))` : `t.bot_id = ?`);
values.push(Number(only_bot_id));
}
@@ -103,6 +108,9 @@ export default async function grabTasks({
sql: `SELECT t.*, b.name AS bot_name, b.kind AS bot_kind, b.hue AS bot_hue, b.color AS bot_color, b.stone AS bot_stone,
b.image_media_id AS bot_image_media_id, ${face.sql}, w.name AS workspace_name,
(SELECT n.text FROM task_notes n WHERE n.task_id = t.id ORDER BY n.id DESC LIMIT 1) AS latest_note,
(SELECT CASE WHEN n.author = 'user' THEN NULL ELSE COALESCE(nb.name, 'Bot ' || n.bot_id) END
FROM task_notes n LEFT JOIN bots nb ON nb.id = n.bot_id
WHERE n.task_id = t.id ORDER BY n.id DESC LIMIT 1) AS latest_note_by,
(SELECT COUNT(*) FROM task_media tm WHERE tm.task_id = t.id) AS media_count
FROM tasks t
LEFT JOIN bots b ON b.id = t.bot_id
@@ -0,0 +1,59 @@
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
import AppError from "@/src/utils/app-error";
import grabBotById from "../bots/grab-bot-by-id";
import addTaskNote from "./add-task-note";
import grabTaskRow, { isOpenTask } from "./grab-task-scope";
import moveTask from "./move-task";
type Params = {
task_id: number | string;
/**
* Who switches it, for the log: the bot's run (also the note's author),
* or none when a user does.
*/
by_bot_id?: number | string | null;
/**
* Who switches it, by name, for the log.
*/
by_name: string;
};
/**
* Turns a bot's open task in a workspace into a workspace-wide one, which
* every bot there sees and works on, with a note saying who did it and
* whose it was. The caller checked who is asking may: a crew manager, the
* coordinator, or that workspace's admin bot. A task on a bot's own list
* has no workspace to belong to and is refused. Returns the row as it is
* now.
*/
export default async function makeTaskWorkspaceWide({
task_id,
by_bot_id,
by_name,
}: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
const task = await grabTaskRow({ task_id });
if (!task.workspace_id) {
throw new AppError(`Task #${task.id} is on a bot's own list, not in a workspace, so it can't be workspace-wide.`);
}
if (!task.bot_id) {
throw new AppError(`Task #${task.id} is already workspace-wide.`);
}
if (!isOpenTask({ status: task.status })) {
throw new AppError(`Task #${task.id} is ${task.status}. Only an open task can be made workspace-wide.`);
}
const was = (await grabBotById({ bot_id: task.bot_id }))?.name || `bot ${task.bot_id}`;
const moved = await moveTask({ task_id: task.id!, workspace_id: task.workspace_id, workspace_wide: true });
await addTaskNote({
task_id: task.id!,
text: `${by_name} made this workspace-wide (it was ${was}'s): every bot in the workspace works on it now.`,
author: by_bot_id ? "bot" : "user",
bot_id: by_bot_id || null,
});
return moved;
}
+4 -3
View File
@@ -10,10 +10,11 @@ type Params = {
task_id: number | string;
/**
* Where it goes: a bot's own list (`bot_id` alone), or a workspace,
* with the bot that has it there (always one).
* with the bot that has it there, or nobody (`workspace_wide`).
*/
bot_id?: number | string | null;
workspace_id?: number | string | null;
workspace_wide?: boolean;
};
/**
@@ -22,9 +23,9 @@ type Params = {
* that title, so a hand-over never leaves two of the same. The caller checked who is
* asking reaches both. Returns the row as it is now.
*/
export default async function moveTask({ task_id, bot_id, workspace_id }: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
export default async function moveTask({ task_id, bot_id, workspace_id, workspace_wide }: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
const task = await grabTaskRow({ task_id });
const place = taskScopeValues({ bot_id, workspace_id });
const place = taskScopeValues({ bot_id, workspace_id, workspace_wide });
if (Number(task.bot_id || 0) == Number(place.bot_id || 0) && Number(task.workspace_id || 0) == Number(place.workspace_id || 0)) {
return task;
@@ -5,9 +5,9 @@ import grabTaskHeir from "./grab-task-heir";
type Params = {
/**
* The bot leaving; none for tasks that have no bot at all.
* The bot leaving. Workspace-wide tasks (no bot) are nobody's and stay.
*/
bot_id?: number | string | null;
bot_id: number | string;
/**
* Only its tasks in this workspace; none for every workspace.
*/
@@ -19,13 +19,13 @@ type Params = {
};
/**
* Gives a leaving bot's workspace tasks (or ones with no bot) to the
* workspace's admin bot, else the coordinator, with a note on each. Its own
* list is left alone. Returns how many moved.
* Gives a leaving bot's workspace tasks to the workspace's admin bot, else
* the coordinator, with a note on each. Its own list is left alone, and so
* are the workspace-wide ones. Returns how many moved.
*/
export default async function passOnBotTasks({ bot_id, workspace_id, bot_name }: Params) {
const where = [`workspace_id IS NOT NULL`, bot_id ? `bot_id = ?` : `bot_id IS NULL`];
const values: number[] = bot_id ? [Number(bot_id)] : [];
const where = [`workspace_id IS NOT NULL`, `bot_id = ?`];
const values: number[] = [Number(bot_id)];
if (workspace_id) {
where.push(`workspace_id = ?`);
@@ -7,8 +7,14 @@ describe("taskScopeValues", () => {
expect(taskScopeValues({ bot_id: "3", workspace_id: "11" })).toEqual({ bot_id: 3, workspace_id: 11 });
});
test("a workspace task without a bot is refused", () => {
test("a workspace task without a bot is refused unless asked for as workspace-wide", () => {
expect(() => taskScopeValues({ workspace_id: 11 })).toThrow();
expect(() => taskScopeValues({})).toThrow();
});
test("a workspace-wide task has its workspace and no bot", () => {
expect(taskScopeValues({ workspace_id: 11, workspace_wide: true })).toEqual({ bot_id: null, workspace_id: 11 });
expect(() => taskScopeValues({ workspace_wide: true })).toThrow();
expect(() => taskScopeValues({ bot_id: 3, workspace_id: 11, workspace_wide: true })).toThrow();
});
});
@@ -3,18 +3,36 @@ import AppError from "@/src/utils/app-error";
type Params = {
bot_id?: number | string | null;
workspace_id?: number | string | null;
/**
* A workspace's task nobody has: every bot working there sees it, works
* on it and logs what it did. Only ever asked for, never the fallback.
*/
workspace_wide?: boolean;
};
/**
* Where a task lives and who has it. Every task belongs to a bot: a bot's
* own list is `bot_id` alone, a workspace's task has `workspace_id` plus
* the `bot_id` that has it there. Checked in the helpers rather than the
* schema.
* Where a task lives and who has it. A task belongs to a bot by default: a
* bot's own list is `bot_id` alone, a workspace's task has `workspace_id`
* plus the `bot_id` that has it there. The one exception is a workspace-wide
* task (`workspace_id` with no bot), which must be asked for. Checked in the
* helpers rather than the schema.
*/
export default function taskScopeValues({ bot_id, workspace_id }: Params) {
export default function taskScopeValues({ bot_id, workspace_id, workspace_wide }: Params) {
const bot = bot_id ? Number(bot_id) : null;
const workspace = workspace_id ? Number(workspace_id) : null;
if (workspace_wide) {
if (!workspace) {
throw new AppError(`A workspace-wide task needs its workspace.`);
}
if (bot) {
throw new AppError(`A workspace-wide task is nobody's: leave the bot out, or give it to that bot instead.`);
}
return { bot_id: null, workspace_id: workspace };
}
if (!bot) {
throw new AppError(`Say which bot has the task.`);
}
+32 -13
View File
@@ -39,18 +39,20 @@ type Args = {
description: string;
bot_id?: number;
workspace_id?: number;
workspace_wide?: boolean;
status?: TaskStatus;
};
type Place = { bot_id: number; workspace_id?: number };
type Place = { bot_id: number | null; workspace_id?: number };
/**
* Worked out from the arguments and who is asking: where the task goes and
* who has it, or why it can't. Every task belongs to a bot. Outside a
* workspace a worker adds only to its own list. In one the task stays in
* that workspace: its own by default, or a member's as the workspace's
* admin. The coordinator adds to any worker's own list or any workspace,
* for one of its bots or itself.
* who has it, or why it can't. A task belongs to a bot unless it's asked
* to be workspace-wide. Outside a workspace a worker adds only to its own
* list. In one the task stays in that workspace: its own by default, a
* member's as the workspace's admin, or workspace-wide (no bot: every bot
* there works on it). The coordinator adds to any worker's own list or any
* workspace, for one of its bots, itself or workspace-wide.
*/
function resolvePlace({
args,
@@ -68,9 +70,19 @@ function resolvePlace({
const target_bot = args.bot_id ? Number(args.bot_id) : null;
const target_workspace = args.workspace_id ? Number(args.workspace_id) : null;
if (args.workspace_wide && target_bot) {
return `A workspace-wide task is nobody's: leave bot_id out, or drop workspace_wide to give it to that bot.`;
}
if (is_coordinator) {
const place_workspace = target_workspace || (workspace_id ? Number(workspace_id) : null);
if (args.workspace_wide) {
return place_workspace
? { workspace_id: place_workspace, bot_id: null }
: `A workspace-wide task needs its workspace: pass workspace_id.`;
}
if (place_workspace) {
return { workspace_id: place_workspace, bot_id: target_bot || Number(bot_id) };
}
@@ -79,7 +91,7 @@ function resolvePlace({
}
if (!workspace_id) {
if (target_workspace) {
if (target_workspace || args.workspace_wide) {
return `You're not in a workspace here, so a task can only go on your own list (bot_id ${bot_id}).`;
}
@@ -94,6 +106,8 @@ function resolvePlace({
return `You can only add tasks in this workspace (#${workspace_id}).`;
}
if (args.workspace_wide) return { workspace_id: Number(workspace_id), bot_id: null };
const is_member = members.some((member) => member.id == target_bot);
if (target_bot && target_bot != Number(bot_id) && !is_member) {
@@ -107,8 +121,8 @@ function resolvePlace({
/**
* Lets a bot add a task to a list it works on: its own, or in a workspace
* its own there (a member's as its admin). The coordinator can add to any
* worker's list and any workspace. Every task belongs to a bot.
* its own there (a member's as its admin) or a workspace-wide one. The
* coordinator can add to any worker's list and any workspace.
*/
export default function createTaskTool({
user_id,
@@ -127,8 +141,8 @@ export default function createTaskTool({
return {
name: "create_task",
description: is_coordinator
? `Add a task: to a worker's own list (bot_id: ${crew || "no workers yet"}), to a workspace (workspace_id: ${places || "no workspaces yet"}) for one of its bots (with bot_id; without, it's yours there), or to your own list (leave both ids out${workspace_id ? "; here, leaving them out makes it yours in this workspace" : ""}). Every task belongs to one bot. Write the description as a brief: what to do, where, and how you'll know it's done.`
: `Add a task: ${workspace_id ? `in this workspace, yours by default${team ? `, or a member's as this workspace's admin (bot_id: ${team})` : ""}` : `on your own list (bot_id ${bot_id}, the default)`}. Write the description as a brief: what to do, where, and how you'll know it's done.`,
? `Add a task: to a worker's own list (bot_id: ${crew || "no workers yet"}), to a workspace (workspace_id: ${places || "no workspaces yet"}) for one of its bots (with bot_id; without, it's yours there) or workspace-wide (workspace_wide: true, no bot_id), or to your own list (leave both ids out${workspace_id ? "; here, leaving them out makes it yours in this workspace" : ""}). A task belongs to one bot unless it's workspace-wide: then every bot in that workspace sees it, works on it and logs what it did. Write the description as a brief: what to do, where, and how you'll know it's done.`
: `Add a task: ${workspace_id ? `in this workspace, yours by default${team ? `, a member's as this workspace's admin (bot_id: ${team})` : ""}, or workspace-wide (workspace_wide: true) when it's work for the whole crew here: every bot in the workspace sees it, works on it and logs what it did` : `on your own list (bot_id ${bot_id}, the default)`}. Write the description as a brief: what to do, where, and how you'll know it's done.`,
schema: z.object({
title: z.string().trim().min(1).max(AppData.TaskTitleMaxLength).describe(`A short label`),
description: z
@@ -151,6 +165,10 @@ export default function createTaskTool({
? `The workspace it's in, when it isn't a bot's own list.`
: `This workspace (${workspace_id || "none"}); leaving it out has the same effect.`,
),
workspace_wide: z
.boolean()
.optional()
.describe(`In a workspace: nobody's, for every bot there to work on and log. Only when the work is the whole crew's; defaults to false.`),
status: z.enum(TaskStatusValues).optional().describe(`Defaults to to do`),
}),
run: async ({ args }) => {
@@ -171,7 +189,7 @@ export default function createTaskTool({
const twin = findDuplicateTask({
tasks: existing,
title: args.title,
bot_id: place.bot_id || null,
bot_id: place.bot_id,
workspace_id: place.workspace_id || null,
});
@@ -183,6 +201,7 @@ export default function createTaskTool({
user_id,
bot_id: place.bot_id,
workspace_id: place.workspace_id,
workspace_wide: !place.bot_id,
title: args.title,
description: args.description,
status: args.status as never,
@@ -190,7 +209,7 @@ export default function createTaskTool({
});
const where = place.workspace_id
? `in workspace ${place.workspace_id}, ${place.bot_id == Number(bot_id) ? "yours" : `bot ${place.bot_id}'s`}`
? `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)
? "to your list"
: `to bot ${place.bot_id}'s list`;
@@ -0,0 +1,49 @@
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
import type { TaskNote } from "@/src/types";
type Params = {
task: BUN_SQLITE_COBBLE_TASKS;
notes: TaskNote[];
/**
* The run's own bot, named "you" in the log.
*/
bot_id: number | string;
};
/**
* One task for a bot's run: where it is, its brief and its whole log, each
* note with who wrote it (bot name and id, or the user) and when, so a bot
* on a workspace-wide task sees what the others already did.
*/
export default function describeTaskLog({ task, notes, bot_id }: Params) {
const who = task.bot_id
? task.bot_id == Number(bot_id)
? "yours"
: `bot ${task.bot_id}'s`
: "workspace-wide: every bot in the workspace works on it";
const log = notes.length
? notes
.map((note) => {
const by =
note.author == "user"
? "the user"
: Number(note.bot_id || 0) == Number(bot_id)
? `you (bot ${bot_id})`
: `${note.bot_name || "a bot"} (bot ${note.bot_id || "?"})`;
const at = note.created_at ? new Date(Number(note.created_at)).toISOString().slice(0, 16).replace("T", " ") : "?";
return `- ${at} UTC, ${by}: ${String(note.text || "").trim()}`;
})
.join("\n")
: "- Nothing logged yet.";
return [
`#${task.id} [${task.status}] ${task.title} (${task.workspace_id ? `in workspace ${task.workspace_id}, ` : ""}${who})`,
task.status == "blocked" && task.blocked_reason ? `Blocked: ${task.blocked_reason}` : "",
`Brief:\n${task.description?.trim() || "(none)"}`,
`Log, oldest first:\n${log}`,
]
.filter(Boolean)
.join("\n\n");
}
@@ -25,8 +25,8 @@ type Params = {
/**
* The task tools every run gets (`src/harness/tools/bot/tasks/`): the
* to-do list (every task belongs to one bot: its own list and its tasks in
* each workspace; an admin's whole workspace), so a chat reply, a task and a scheduled run all read it,
* to-do list (its own list, its tasks in each workspace and the
* workspace-wide ones there; an admin's whole workspace), so a chat reply, a task and a scheduled run all read it,
* move it along and file what they produced. The coordinator's create_task
* may target any worker or workspace; its update_task may link any file it
* can reach. A workspace admin's may give tasks there to the other members.
+25 -7
View File
@@ -3,7 +3,10 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_WORKSPACES } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import { type TaskStatus, TaskStatusValues } from "@/src/dict/task-dict";
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
import grabTaskNotes from "@/src/functions/backend/db/tasks/grab-task-notes";
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
import describeTaskLog from "./describe-task-log";
import type { HarnessTool } from "../../../types";
type Params = {
@@ -21,6 +24,7 @@ type Params = {
};
type Args = {
task_id?: number;
scope?: "mine" | "workspace" | "all";
status?: TaskStatus;
open_only?: boolean;
@@ -28,19 +32,25 @@ type Args = {
/**
* Lets a bot read the tasks it can work on: its own (its list and what it
* has in workspaces), every task of a workspace it's admin of, or for the
* coordinator the whole install. Used
* both to plan work and to remind the user of what's pending.
* has in workspaces), the workspace-wide ones in its workspaces, every task
* of a workspace it's admin of, or for the coordinator the whole install.
* 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> {
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, 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. 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.`,
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.`,
schema: z.object({
task_id: z
.number()
.int()
.optional()
.describe(`Read one task instead: its brief and its whole log, each note with the bot (or user) that wrote it and when.`),
scope: z
.enum(["mine", "workspace", "all"])
.optional()
.describe(`"mine" for the tasks you have (your own list and in workspaces), "workspace" for ${workspace_id ? "this workspace's" : "a workspace's (none open)"}, "all" for everything you reach. Defaults to "all".`),
.describe(`"mine" for the tasks you have (your own list and in workspaces; not the workspace-wide ones), "workspace" for ${workspace_id ? "this workspace's" : "a workspace's (none open)"}, "all" for everything you reach. Defaults to "all".`),
status: z.enum(TaskStatusValues).optional(),
open_only: z
.boolean()
@@ -48,6 +58,12 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
.describe(`Only the open ones (to do, doing, blocked). Defaults to false.`),
}),
run: async ({ args }) => {
if (args.task_id) {
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
return describeTaskLog({ task, notes: await grabTaskNotes({ task_id: task.id! }), bot_id });
}
const scope = args.scope || "all";
const only_workspace_id =
scope == "workspace" && workspace_id ? Number(workspace_id) : undefined;
@@ -75,7 +91,7 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
return tasks
.map((task) => {
const who = task.bot_name || `bot ${task.bot_id}`;
const who = task.bot_id ? task.bot_name || `bot ${task.bot_id}` : "workspace-wide, every bot there";
const where = task.workspace_id
? `in ${names.get(Number(task.workspace_id)) || `workspace ${task.workspace_id}`}, ${who}`
: `on ${who}'s list`;
@@ -86,7 +102,9 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
`(${where})`,
Number(task.media_count || 0) ? `${task.media_count} file(s)` : "",
task.status == "blocked" && task.blocked_reason ? `blocked: ${task.blocked_reason}` : "",
task.latest_note ? `latest: ${oneLine({ text: task.latest_note })}` : "",
task.latest_note
? `latest${task.latest_note_by ? ` by ${task.latest_note_by}` : " by the user"}: ${oneLine({ text: task.latest_note })}`
: "",
];
return `- ${bits.filter(Boolean).join(" ")}`;
@@ -5,6 +5,8 @@ import addTaskNote from "@/src/functions/backend/db/tasks/add-task-note";
import attachTaskFile from "@/src/functions/backend/db/tasks/attach-task-file";
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
import grabTaskMedia from "@/src/functions/backend/db/tasks/grab-task-media";
import makeTaskWorkspaceWide from "@/src/functions/backend/db/tasks/make-task-workspace-wide";
import grabBotById from "@/src/functions/backend/db/bots/grab-bot-by-id";
import updateTask from "@/src/functions/backend/db/tasks/update-task";
import type { StorageScope } from "@/src/utils/storage-access";
import type { HarnessTool } from "../../../types";
@@ -30,17 +32,27 @@ type Args = {
note?: string;
deliverable_file_ids?: number[];
reference_file_ids?: number[];
workspace_wide?: boolean;
};
/**
* Lets a bot move a task along: set its status, say what's blocking it, log
* a progress note, and file the deliverables it produced. One call does all
* of them, so a step in the work is a step in the log.
* of them, so a step in the work is a step in the log. On a workspace-wide
* task, which every bot there works on, the call's status move and filed
* files go into the log too, under the bot that did them, so the log says
* 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 = [] }: Params): HarnessTool<Args> {
/**
* Only the coordinator and workspace admins get the switch at all.
*/
const can_share = is_coordinator || admin_workspace_ids.length > 0;
return {
name: "update_task",
description: `Move a task along. Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number.`,
description: `Move a task along. Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number.${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
schema: z.object({
task_id: z.number().int(),
status: z.enum(TaskStatusValues).optional(),
@@ -62,10 +74,36 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
.array(z.number().int())
.optional()
.describe(`The [file:ID] refs of files it works from`),
workspace_wide: z
.boolean()
.optional()
.describe(
can_share
? `true to make a bot's open task in ${is_coordinator ? "a" : "a workspace you're admin of"} workspace workspace-wide: nobody's, for every bot there to work on and log. Only true does anything.`
: `Only the coordinator or a workspace's admin bot can use this; leave it out.`,
),
}),
run: async ({ args }) => {
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
const said: string[] = [];
const workspace_wide = !task.bot_id && Boolean(task.workspace_id);
/**
* On a workspace-wide task: what this call did, for the log.
*/
const done: string[] = [];
if (args.workspace_wide) {
if (!can_share || (!is_coordinator && !admin_workspace_ids.includes(Number(task.workspace_id || 0)))) {
return `Only the coordinator or this workspace's admin bot can make a task workspace-wide.`;
}
await makeTaskWorkspaceWide({
task_id: task.id!,
by_bot_id: bot_id,
by_name: (await grabBotById({ bot_id }))?.name || `Bot ${bot_id}`,
});
said.push(`it's workspace-wide now, every bot in workspace ${task.workspace_id} works on it`);
}
if (args.status || args.blocked_reason !== undefined) {
if (args.status == "blocked" && !args.blocked_reason?.trim()) {
@@ -82,12 +120,13 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
if (args.status) {
said.push(task.status == args.status ? `status was already ${args.status}` : `status is now ${args.status}`);
}
}
if (args.note?.trim()) {
await addTaskNote({ task_id: task.id!, text: args.note, author: "bot", bot_id });
said.push(`note logged`);
if (task.status != args.status) {
done.push(
`Moved it from ${task.status} to ${args.status}${args.status == "blocked" && args.blocked_reason?.trim() ? `: ${args.blocked_reason.trim()}` : ""}.`,
);
}
}
}
for (const [kind, ids] of [
@@ -106,6 +145,8 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
});
said.push(`${existed ? "already linked" : "linked"} ${kind} "${file.name}"`);
if (!existed) done.push(`Filed ${kind} "${file.name}".`);
} catch (error: unknown) {
said.push(
`couldn't link file ${file_id}: ${error instanceof Error ? error.message : "unknown error"}`,
@@ -114,6 +155,13 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
}
}
const note = [args.note?.trim(), workspace_wide ? done.join(" ") : ""].filter(Boolean).join("\n\n");
if (note) {
await addTaskNote({ task_id: task.id!, text: note, author: "bot", bot_id });
said.push(args.note?.trim() ? `note logged` : `logged under your name`);
}
if (!said.length) {
return `Nothing to change on #${task.id}.`;
}
@@ -15,7 +15,7 @@ type Params = {
/**
* A conversation's tasks: a bot's own list, or in a workspace the ones it
* has there. Loaded on open and refreshed after every change,
* has there plus the workspace's workspace-wide ones. Loaded on open and refreshed after every change,
* never part of the page props.
*/
export default function useBotTasks({ bot_id, workspace_id, enabled = true }: Params) {
@@ -31,7 +31,7 @@ type Props = {
/**
* The tasks this conversation works on: a bot's own list, or in a workspace
* the ones it has there. Open it from the header menu; the list loads
* the ones it has there and the workspace-wide ones. Open it from the header menu; the list loads
* then, so the page's props stay small. A crew manager adds, moves, edits
* and deletes; a card opens the task in a modal of its own with everything
* about it.
@@ -157,7 +157,7 @@ export default function BotTasksModal({ bot, workspace, menu, on_open }: Props)
</Row>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{workspace?.id
? `What ${name} has in ${workspace.name || "this workspace"}. The workspace shows every bot's.`
? `What ${name} has in ${workspace.name || "this workspace"}, and the workspace-wide tasks every bot there works on. The workspace shows every bot's.`
: `What ${name} is working through, and what it's waiting on.`}
</Span>
</Stack>
@@ -167,6 +167,7 @@ export default function BotTasksModal({ bot, workspace, menu, on_open }: Props)
<TaskForm
bot_id={Number(bot.id)}
workspace_id={workspace?.id ? Number(workspace.id) : null}
bots={[{ id: bot.id, name }]}
onCancel={() => set_adding(false)}
onSaved={(saved, msg) => {
replace({ task: saved });
@@ -29,8 +29,9 @@ type Props = {
};
/**
* Every task in a workspace, whichever bot has it: every task belongs to
* one bot, which sees only its own (the workspace's admin bot sees all).
* Every task in a workspace, whichever bot has it: a task belongs to one
* bot, which sees only its own, unless it's workspace-wide (every bot there
* sees it; the workspace's admin bot sees all).
* Add and change one by hand here; the bots
* keep it up to date themselves as they work.
*/
@@ -94,19 +95,18 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
<SettingsGroup
id="tasks"
title="Tasks"
description="Every task in this workspace, whichever bot has it. Each bot sees only its own; the workspace's admin bot and the coordinator see them all."
description="Every task in this workspace, whichever bot has it. Each bot sees its own and the workspace-wide ones, which every bot here works on and logs; the workspace's admin bot and the coordinator see them all."
>
<Stack className="w-full gap-2! items-stretch">
{can_manage ? (
<Row className="justify-end">
<Button
title={bots.length ? "Add a task" : "Add a bot to this workspace first"}
title="Add a task"
type="button"
variant="outlined"
color="gray"
size="small"
onClick={() => setAdding(true)}
disabled={!bots.length}
>
Add task
</Button>
@@ -144,7 +144,7 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
open={adding}
setOpen={setAdding}
title="Add a task"
description="Pick the bot that has it. Hand it over later to give it to another."
description="Pick the bot that has it, or make it workspace-wide: every bot here sees it, works on it and logs what it did. Hand it over later to give it to one bot."
>
<TaskForm
workspace_id={workspace_id}
+3 -1
View File
@@ -6,7 +6,8 @@ import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bune
/**
* The user's tasks: a bot's own list (`?bot_id=`), a workspace's
* (`?workspace_id=`), one bot's there (`?workspace_id=&bot_id=`), or every
* (`?workspace_id=`), one bot's there with the workspace-wide ones
* (`?workspace_id=&bot_id=`), or every
* task they reach. `?status=` narrows to one
* status, `?open=1` to the open ones.
*/
@@ -33,6 +34,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<TaskWithNames>> =
payload: await grabTasks({
user_id: user.id,
only_bot_id: bot_id,
with_workspace_wide: Boolean(bot_id && workspace_id),
only_workspace_id: workspace_id,
own_list: Boolean(bot_id && !workspace_id),
statuses: status ? [status] : undefined,
@@ -0,0 +1,52 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
import grabTask from "@/src/functions/backend/db/tasks/grab-task";
import makeTaskWorkspaceWide from "@/src/functions/backend/db/tasks/make-task-workspace-wide";
import { TaskIdRequestSchema } from "@/src/schemas/task-schema";
import type { TaskDetail } from "@/src/types";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* Turns a bot's open task in a workspace into a workspace-wide one, which
* every bot there works on (`makeTaskWorkspaceWide`). Crew managers only,
* like every other change to a task by hand. Returns the task as it is now.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const { user, user_types } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (isReadOnlyUser({ user_types: user_types || [] })) {
throw new AppError(`This user can only read records.`);
}
if (!canManageCrew({ user_types: user_types || [] })) {
throw new AppError(`Only an admin can make a task workspace-wide.`);
}
const { task_id } = parseWithSchema({ schema: TaskIdRequestSchema, data: body });
await assertUserReachesTask({ user_id: user.id, task_id });
await makeTaskWorkspaceWide({ task_id, by_name: user.first_name || user.username || "The user" });
return {
success: true,
singleRes: await grabTask({ user_id: user.id, task_id }),
msg: `It's workspace-wide now: every bot in the workspace works on it.`,
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+4 -3
View File
@@ -11,8 +11,8 @@ import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* Adds a task to a bot's list (`bot_id`) or a bot's in a workspace (with
* `workspace_id`), or changes one (`task_id`). Returns the task with its
* Adds a task to a bot's list (`bot_id`), a bot's in a workspace (with
* `workspace_id`) or a workspace-wide one (`workspace_id`, `workspace_wide`), or changes one (`task_id`). Returns the task with its
* notes and files.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = async ({ req, body }) => {
@@ -55,7 +55,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = asy
};
}
const { bot_id, workspace_id, title, description, status } = parseWithSchema({
const { bot_id, workspace_id, workspace_wide, title, description, status } = parseWithSchema({
schema: CreateTaskRequestSchema,
data,
});
@@ -66,6 +66,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = asy
user_id: user.id,
bot_id,
workspace_id,
workspace_wide,
title,
description,
status: status as never,
+5 -3
View File
@@ -6,13 +6,15 @@ const status_values = TaskStatuses.map((status) => status.value) as [string, ...
const media_kind_values = TaskMediaKinds.map((kind) => kind.value) as [string, ...string[]];
/**
* Where it goes: a bot's own list (`bot_id`) or a bot's task in a
* workspace (both). Every task has a bot: the helper refuses one without
* (`taskScopeValues`).
* Where it goes: a bot's own list (`bot_id`), a bot's task in a workspace
* (both), or a workspace-wide one (`workspace_id` with `workspace_wide`).
* The helper refuses a task with no bot unless it's asked to be
* workspace-wide (`taskScopeValues`).
*/
const scope = {
bot_id: z.number().int().positive().optional(),
workspace_id: z.number().int().positive().optional(),
workspace_wide: z.boolean().optional(),
};
export const CreateTaskRequestSchema = z.object({
-4
View File
@@ -10,7 +10,6 @@ import fileIngest from "./file-ingest";
import liveRelay from "./live-relay";
import enableForeignKeys from "./functions/backend/db/enable-foreign-keys";
import migrateBotTypes from "./functions/backend/db/bot-types/migrate-bot-types";
import assignOwnerlessTasks from "./functions/backend/db/tasks/assign-ownerless-tasks";
import clearImplicitSessionLinks from "./functions/backend/db/bot-sessions/clear-implicit-session-links";
import dropStoredFileText from "./functions/backend/db/stored-text/drop-stored-file-text";
import syncKnowledgebaseFts from "./functions/backend/db/knowledgebases/fts/sync-knowledgebase-fts";
@@ -39,9 +38,6 @@ await enableForeignKeys();
await migrateBotTypes().catch((error) =>
logError({ title: "Could not migrate bot types", error }).catch(() => {}),
);
await assignOwnerlessTasks().catch((error) =>
logError({ title: "Could not assign tasks without a bot", error }).catch(() => {}),
);
await clearImplicitSessionLinks().catch((error) =>
logError({ title: "Could not clear implicit session links", error }).catch(() => {}),
);
+4
View File
@@ -210,6 +210,10 @@ export type TaskWithNames = BUN_SQLITE_COBBLE_TASKS & {
* Its newest note's text, for the row's second line.
*/
latest_note?: string | null;
/**
* The bot that wrote it; null when the user did.
*/
latest_note_by?: string | null;
/**
* How many files it carries.
*/
+6 -5
View File
@@ -19,10 +19,11 @@ type Params = {
};
/**
* The tasks a bot's run reaches. Every task belongs to one bot: a worker
* reaches its own list and the tasks it has in the workspaces it still
* works in, never another bot's. A workspace admin also reaches every task
* in that workspace; the coordinator every task in the install.
* The tasks a bot's run reaches. A task belongs to one bot by default: a
* worker reaches its own list and the tasks it has in the workspaces it
* still works in, never another bot's, plus every workspace-wide task (no
* bot) in those workspaces. A workspace admin also reaches every task in
* that workspace; the coordinator every task in the install.
*/
export default function botTaskScopesSql({
bot_id,
@@ -41,7 +42,7 @@ export default function botTaskScopesSql({
sql: `(
(${alias}.bot_id = ? AND ${alias}.workspace_id IS NULL)
OR (${alias}.workspace_id IS NOT NULL
AND ${alias}.bot_id = ?
AND (${alias}.bot_id = ? OR ${alias}.bot_id IS NULL)
AND ${alias}.workspace_id IN (SELECT workspace_id FROM workspace_bots WHERE bot_id = ?))
${admin_sql}
)`,
+12
View File
@@ -85,3 +85,15 @@ describe("botTaskScopesSql for a workspace admin", () => {
db.run(`DELETE FROM workspace_bots WHERE bot_id = 4`);
});
});
describe("workspace-wide tasks", () => {
test("every bot working there reaches one, no bot elsewhere does, and users see it with the workspace", () => {
db.run(`INSERT INTO tasks VALUES (114, NULL, 11, NULL)`);
expect(ids({ condition: botTaskScopesSql({ bot_id: 3, is_coordinator: false }) })).toEqual([102, 110, 112, 114]);
expect(ids({ condition: botTaskScopesSql({ bot_id: 2, is_coordinator: false }) })).toEqual([101]);
expect(ids({ condition: botTaskScopesSql({ bot_id: 1, is_coordinator: true }) })).toContain(114);
expect(ids({ condition: taskScopesSql({ role: "member", user_id: 7 }) })).toEqual([101, 111, 112, 113, 114]);
expect(ids({ condition: taskScopesSql({ role: "member", user_id: 9 }) })).toEqual([102]);
db.run(`DELETE FROM tasks WHERE id = 114`);
});
});
+2 -2
View File
@@ -10,8 +10,8 @@ export type SqlCondition = {
/**
* Where a task is: a bot's own list (`bot_id` alone), or a workspace
* (`workspace_id`, with the `bot_id` that has it there). Every task has a
* bot.
* (`workspace_id`, with the `bot_id` that has it there, or none for a
* workspace-wide task every bot there works on).
*/
export type TaskScope = {
bot_id?: number | null;
+2 -2
View File
@@ -12,7 +12,7 @@ describe("taskPlaceLabel", () => {
);
});
test("says shared for a workspace task nobody has yet", () => {
expect(taskPlaceLabel({ task: { workspace_id: 5, workspace_name: "Launch" } })).toBe("Shared in Launch");
test("says every bot for a workspace-wide task", () => {
expect(taskPlaceLabel({ task: { workspace_id: 5, workspace_name: "Launch" } })).toBe("Every bot in Launch");
});
});
+3 -3
View File
@@ -9,8 +9,8 @@ type Params = {
/**
* Where a task is and who has it, for a list row: "Ada" for a bot's own
* list, "Ada in Launch" for a bot's task in a workspace, "Shared in
* Launch" for one nobody there has yet.
* list, "Ada in Launch" for a bot's task in a workspace, "Every bot in
* Launch" for a workspace-wide one.
*/
export default function taskPlaceLabel({ task }: Params) {
const bot = task.bot_id ? task.bot_name || `Bot ${task.bot_id}` : null;
@@ -19,5 +19,5 @@ export default function taskPlaceLabel({ task }: Params) {
const workspace = task.workspace_name || `Workspace ${task.workspace_id}`;
return `${bot || "Shared"} in ${workspace}`;
return `${bot || "Every bot"} in ${workspace}`;
}