Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d57ba560c | ||
|
|
c1c307e51c | ||
|
|
7bc74dfe8e |
@@ -167,7 +167,7 @@ A secret URL, `POST /api/hooks/<token>` (`src/pages/api/hooks/[token].ts`, publi
|
||||
|
||||
### Tasks (the to-do tracker)
|
||||
|
||||
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`); a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id` when it directs work, else `hand_over_task` for a task of its own; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there) as to do, with no job: a hand-over never starts the work. Only `start: true` (the UI's "Start it now" toggle, or a bot passing it after the user said so) sets it doing and queues a job with `params.tracker_task_id`; when the user asked for the move but not for the work to start, bots ask first with one `ask_user` card for every task they named, since a worker can't start a task once it has left its list; `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
|
||||
`tasks` (**a task belongs to a bot by default**, the coordinator included: a bot's own list is `bot_id` alone, a workspace's task has `workspace_id` plus the `bot_id` that has it there; the one exception is a **workspace-wide** task (`workspace_id`, `bot_id` null), only when asked for (`workspace_wide`, enforced by `taskScopeValues`), which every bot working there sees and works on; a worker reaches its own plus the workspace-wide ones in its workspaces, a workspace admin all of that workspace's, the coordinator all, `botTaskScopesSql`; on a workspace-wide task `update_task` logs each call's status move and filed files as a note under the bot (`task_notes.bot_id`), and `list_tasks` with `task_id` reads the whole log with who and when; the coordinator and a workspace's admin bot (`update_task` `workspace_wide`) or a crew manager (Make workspace-wide, `api/admin/tasks/make-workspace-wide`) turn a bot's open workspace task workspace-wide (`makeTaskWorkspaceWide`, noted in its log; never a bot's own list), and hand-over gives one back to a single bot; it can be split into **subtasks** (`parent_task_id`, one level, `subtaskLinkProblem`): each one an ordinary task of one bot in that workspace (`create_task`/`save-task` `parent_task_id`, cap `AppData.TaskSubtaskMaxPerParent`, listed under the parent in `TaskDetailModal` and marked `Subtask of #N` in lists), and a task a bot already has joins one the same way (`linkSubtask`, `api/admin/tasks/link-subtask` from the panel's "Make it a subtask of..." picker, `subtaskAttachProblem` refusing a closed task, another subtask, or a task with subtasks of its own; the parent logs who took which piece), loose again with `detach-subtask`/`update_task` `unlink_parent`; the parent stays open until someone verifies it, and its subtasks never close it. Only a task with no subtasks and no parent moves (`subtaskMoveProblem`, so making it workspace-wide or handing it on is refused until the subtasks are unlinked) and a parent with subtasks is never handed its own work back on deletion (`subtaskDeleteProblem`: all subtasks finished first, then they go with it, children deleted explicitly since foreign keys are off outside the server); a bot removed from a workspace or deleted passes its own tasks there to the workspace's admin bot, else the coordinator (`passOnBotTasks`), workspace-wide ones stay), `task_notes`, `task_media` (deliverable|reference). Not the same as `bot_tasks`/`bots_queue` (those record jobs). Visibility SQL in `src/utils/task-access/`. Helpers in `src/functions/backend/db/tasks/`; tools `list_tasks`/`create_task`/`update_task` (which also renames a task and rewrites its brief, refusing an open twin's title, and unlinks bot files with `unlink_file_ids`: a task holds `AppData.TaskMediaMaxPerTask` files; `list_tasks` with `task_id` lists them) and, in chat replies the user follows only (never routines, hook calls or rooms), `delete_task`; API `api/admin/tasks/` (`userAuth` -> `isReadOnlyUser` -> `assertUserReachesTask` -> `safeErrorMessage`). UI in the workspace dashboard and the header's Tasks modal (shared components in `src/components/general/`), the dashboard's list ordered by `workspaceTaskSections` (workspace-wide first, then one section per bot by name) and capped at `AppData.TaskSectionShown`, its View all opening `WorkspaceTasksModal` with the same sections uncut, and a workspace-wide row wearing the workspace's picture (`WorkspaceAvatar`, its icon when it has none) since it is nobody's; a card's title opens `TaskDetailModal` with everything about the task and its status moves (a modal over the list, never swapped in place), a wide task's panel listing the first `AppData.TaskSubtasksShown` subtasks with `TaskSubtasksModal` behind its View all, and a subtask's own modal walking up to it through its Parent task fact (Escape closes only the modal on top, `TopModalEscape`). **Hand-over:** `handOverTask` (bot: `delegate_task` with `task_id` when it directs work, else `hand_over_task` for a task of its own; UI: Hand over, crew managers) moves an open task to the new bot (a workspace's stays in the workspace, now the new bot's, and is worked there) as to do, with no job: a hand-over never starts the work. Only `start: true` (the UI's "Start it now" toggle, or a bot passing it after the user said so) sets it doing and queues a job with `params.tracker_task_id`; when the user asked for the move but not for the work to start, bots ask first with one `ask_user` card for every task they named, since a worker can't start a task once it has left its list; `noteTrackerTask` notes the job's end on it, blocks it on failure, and blocks it too when the run used every step it had without finishing (`trackerTaskEnding`, so a run measured to its last step no longer leaves the task silently open). **Not built yet:** task steps, `server:task-changed` pushes, a `/admin/tasks` page.
|
||||
|
||||
### Envs
|
||||
|
||||
|
||||
+35
-7
@@ -805,7 +805,7 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
{
|
||||
tableName: "tasks",
|
||||
tableDescription: `The crew's to-do list: work that is tracked until it's done. A bot's own list (\`bot_id\` alone), or a workspace's tasks (\`workspace_id\`, with \`bot_id\` naming the bot there that has it, or null for a workspace-wide task every bot there works on, made only when asked for). A bot reaches its own list and, in each workspace it works in, its tasks there and the workspace-wide ones; a workspace admin every task in its workspace; the coordinator every task. Not the same thing as \`bot_tasks\` or \`bots_queue\`: those record a queued job, this records the work`,
|
||||
tableDescription: `The crew's to-do list: work that is tracked until it's done. A bot's own list (\`bot_id\` alone), or a workspace's tasks (\`workspace_id\`, with \`bot_id\` naming the bot there that has it, or null for a workspace-wide task every bot there works on, made only when asked for). A workspace-wide task can be split into subtasks (\`parent_task_id\`): one piece is a bot's own task in the same workspace, and only one level of splitting exists. A bot reaches its own list and, in each workspace it works in, its tasks there and the workspace-wide ones; a workspace admin every task in its workspace; the coordinator every task. Not the same thing as \`bot_tasks\` or \`bots_queue\`: those record a queued job, this records the work`,
|
||||
fields: [
|
||||
{
|
||||
fieldName: "bot_id",
|
||||
@@ -831,6 +831,18 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
foreignKeyName: "tasks_workspace_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "parent_task_id",
|
||||
fieldDescription: `The workspace-wide task this one is a part of: a bot's own task in the same workspace, one piece of that work. Null for a task that isn't a subtask; a subtask of a subtask is refused (one level, no nesting), and its parent always stays workspace-wide`,
|
||||
dataType: "INTEGER",
|
||||
foreignKey: {
|
||||
cascadeDelete: true,
|
||||
destinationTableName: "tasks",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "tasks_parent_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
fieldName: "title",
|
||||
dataType: "TEXT",
|
||||
@@ -883,6 +895,10 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
indexName: "idx_tasks_workspace_id_status",
|
||||
indexTableFields: ["workspace_id", "status"],
|
||||
},
|
||||
{
|
||||
indexName: "idx_tasks_parent_task_id",
|
||||
indexTableFields: ["parent_task_id"],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -1233,7 +1249,7 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
},
|
||||
{
|
||||
fieldName: "message_id",
|
||||
fieldDescription: `The message the run ended in, filled when the job completes: the debug logs tab of its Details modal reads them. No foreign key, so a message's rows wait for the prune rather than cascade`,
|
||||
fieldDescription: `The message the run ended in, filled when the job completes: the debug logs tab of its Details modal reads them. No foreign key, so a message's rows wait for the prune rather than cascade`,
|
||||
dataType: "INTEGER",
|
||||
},
|
||||
{
|
||||
@@ -3267,7 +3283,10 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
{
|
||||
alias: "one_browser_slug_per_user",
|
||||
constraintName: "A user's browsers have different slugs",
|
||||
constraintTableFields: [{ value: "user_id" }, { value: "slug" }],
|
||||
constraintTableFields: [
|
||||
{ value: "user_id" },
|
||||
{ value: "slug" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -3460,7 +3479,13 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
{
|
||||
fieldName: "status",
|
||||
dataType: "TEXT",
|
||||
options: ["pending", "confirmed", "rejected", "replaced", "failed"],
|
||||
options: [
|
||||
"pending",
|
||||
"confirmed",
|
||||
"rejected",
|
||||
"replaced",
|
||||
"failed",
|
||||
],
|
||||
defaultValue: "pending",
|
||||
},
|
||||
{
|
||||
@@ -3815,7 +3840,8 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
destinationTableName: "knowledgebases",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "knowledgebase_documents_knowledgebases_fk",
|
||||
foreignKeyName:
|
||||
"knowledgebase_documents_knowledgebases_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -4011,7 +4037,8 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
destinationTableName: "workspaces",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "workspace_knowledgebases_workspaces_fk",
|
||||
foreignKeyName:
|
||||
"workspace_knowledgebases_workspaces_fk",
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -4022,7 +4049,8 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
|
||||
destinationTableName: "knowledgebases",
|
||||
destinationTableColumnName: "id",
|
||||
destinationTableColumnType: "INTEGER",
|
||||
foreignKeyName: "workspace_knowledgebases_knowledgebases_fk",
|
||||
foreignKeyName:
|
||||
"workspace_knowledgebases_knowledgebases_fk",
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -535,6 +535,10 @@ export type BUN_SQLITE_COBBLE_TASKS = {
|
||||
* The workspace the task is in; null for a bot's own list
|
||||
*/
|
||||
workspace_id?: number | "";
|
||||
/**
|
||||
* The workspace-wide task this one is a part of: a bot's own task in the same workspace, one piece of that work. Null for a task that isn't a subtask; a subtask of a subtask is refused (one level, no nesting), and its parent always stays workspace-wide
|
||||
*/
|
||||
parent_task_id?: number | "";
|
||||
title?: string;
|
||||
/**
|
||||
* The brief (markdown): what to do, where, and how you'll know it's done
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.21.2",
|
||||
"version": "0.21.3",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import Form from "@moduletrace/twui/form/Form";
|
||||
import Select from "@moduletrace/twui/form/Select";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
|
||||
import AddFormActions from "@/src/layouts/bots/(partials)/add-form-actions";
|
||||
import type { TaskDetail, TaskWithNames } from "@/src/types";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* The bot's task being made a subtask of a workspace-wide one.
|
||||
*/
|
||||
task: TaskDetail;
|
||||
onLinked: (task: TaskDetail, msg: string) => void;
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Picks which open workspace-wide task of the same workspace a bot's task
|
||||
* becomes a subtask of (`linkSubtask`), the way the task's own bot can with
|
||||
* `update_task`. The parents load when the form opens, so the page's props
|
||||
* stay small.
|
||||
*/
|
||||
export default function SubtaskLinkForm({ task, onLinked, onCancel }: Props) {
|
||||
const [parents, setParents] = useState<TaskWithNames[]>();
|
||||
const [parent_task_id, setParentTaskId] = useState<number>();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
postAdminApi<TaskWithNames>({ path: "tasks/subtask-parents", body: { task_id: Number(task.id) } }).then((res) => {
|
||||
if (!res.success) {
|
||||
setError(res.msg || "Couldn't load the workspace-wide tasks.");
|
||||
setParents([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const list = (res.payload || []) as TaskWithNames[];
|
||||
|
||||
setParents(list);
|
||||
setParentTaskId(list[0]?.id ? Number(list[0].id) : undefined);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const submit = async () => {
|
||||
if (loading) return;
|
||||
|
||||
const parent = parents?.find((it) => Number(it.id) == parent_task_id);
|
||||
|
||||
if (!parent) {
|
||||
setError("Pick the workspace-wide task it belongs to.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!window.confirm(`Make "${task.title}" a subtask of "${parent.title}"? It stays ${task.bot_name || "its bot"}'s, and the parent stays open until someone verifies all its subtasks.`))
|
||||
return;
|
||||
|
||||
setLoading(true);
|
||||
setError(undefined);
|
||||
|
||||
const res = await postAdminApi<TaskDetail>({
|
||||
path: "tasks/link-subtask",
|
||||
body: { task_id: Number(task.id), parent_task_id: Number(parent.id) },
|
||||
});
|
||||
|
||||
setLoading(false);
|
||||
|
||||
if (!res.success || !res.singleRes) {
|
||||
setError(res.msg || "Couldn't make it a subtask of that task.");
|
||||
return;
|
||||
}
|
||||
|
||||
onLinked(res.singleRes, res.msg || `It's a subtask of task #${parent.id} now.`);
|
||||
};
|
||||
|
||||
return (
|
||||
<Form onSubmit={submit} className="w-full gap-3! items-stretch">
|
||||
<Stack className="gap-3! items-stretch">
|
||||
{!parents ? (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">Loading the workspace-wide tasks...</Span>
|
||||
) : parents.length ? (
|
||||
<Select
|
||||
key={parents.length}
|
||||
label="Parent task"
|
||||
showLabel
|
||||
options={parents.map((it) => ({
|
||||
title: `#${it.id} ${it.title || ""}`.trim(),
|
||||
value: String(it.id),
|
||||
default: Number(it.id) == parent_task_id,
|
||||
}))}
|
||||
changeHandler={(value) => setParentTaskId(Number(value))}
|
||||
/>
|
||||
) : (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
This workspace has no open workspace-wide task to join. Make one first, then split it.
|
||||
</Span>
|
||||
)}
|
||||
<AddFormActions submit_label="Make it a subtask" loading={loading} error={error} onCancel={onCancel} />
|
||||
</Stack>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -35,7 +35,16 @@ type Props = {
|
||||
export default function TaskDetailModal({ task, can_manage, onClose, onLoaded, onChanged, onDeleted }: Props) {
|
||||
const [detail, set_detail] = useState<TaskDetail | null>(null);
|
||||
const [error, set_error] = useState<string>();
|
||||
const task_id = task?.id ? Number(task.id) : 0;
|
||||
/**
|
||||
* A subtask opened from the task on show: the modal walks into it and back
|
||||
* out with the list's own click.
|
||||
*/
|
||||
const [opened, set_opened] = useState<Partial<TaskWithNames> | null>(null);
|
||||
const task_id = Number(opened?.id || task?.id || 0);
|
||||
|
||||
useEffect(() => {
|
||||
set_opened(null);
|
||||
}, [task?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
set_detail(null);
|
||||
@@ -67,13 +76,20 @@ export default function TaskDetailModal({ task, can_manage, onClose, onLoaded, o
|
||||
}, [task_id]);
|
||||
|
||||
const shown = detail || task;
|
||||
/**
|
||||
* The task it is a subtask of, when it is one: the modal walks into that as
|
||||
* it walks into a subtask.
|
||||
*/
|
||||
const part_of = detail?.parent_task_id
|
||||
? ` · Parent task #${detail.parent_task_id}${detail.parent_title ? ` ${detail.parent_title}` : ""}`
|
||||
: "";
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
open={Boolean(task_id)}
|
||||
setOpen={(open) => !open && onClose()}
|
||||
title={shown?.title || (task_id ? `Task ${task_id}` : "Task")}
|
||||
description={shown ? taskPlaceLabel({ task: shown }) : undefined}
|
||||
description={shown ? `${taskPlaceLabel({ task: shown })}${part_of}` : undefined}
|
||||
>
|
||||
<Stack className="w-full mt-4 gap-0! items-stretch">
|
||||
{detail ? (
|
||||
@@ -81,6 +97,8 @@ export default function TaskDetailModal({ task, can_manage, onClose, onLoaded, o
|
||||
key={detail.id}
|
||||
task={detail}
|
||||
can_manage={can_manage}
|
||||
onOpenSubtask={(subtask) => set_opened(subtask)}
|
||||
onOpenParent={(parent) => set_opened(parent)}
|
||||
onChanged={(saved, msg) => {
|
||||
set_detail(saved);
|
||||
onChanged({ task: saved, msg });
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { TaskDetail } from "@/src/types";
|
||||
import TaskDetailPanel from "./task-detail-panel";
|
||||
|
||||
function detail(fields: Partial<TaskDetail>): TaskDetail {
|
||||
return {
|
||||
id: 12,
|
||||
created_at: 1,
|
||||
updated_at: 2,
|
||||
title: "Ship the release",
|
||||
status: "doing",
|
||||
notes: [],
|
||||
files: [],
|
||||
subtasks: [],
|
||||
...fields,
|
||||
};
|
||||
}
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
describe("TaskDetailPanel", () => {
|
||||
test("a split workspace-wide task lists its subtasks with how many are still open", () => {
|
||||
const html = renderToString(
|
||||
<TaskDetailPanel
|
||||
task={detail({
|
||||
bot_id: "",
|
||||
workspace_id: 7,
|
||||
subtasks: [
|
||||
{ id: 31, title: "The intro", status: "doing", bot_id: 3, bot_name: "Software Engineer" },
|
||||
{ id: 32, title: "The appendix", status: "done", bot_id: 4, bot_name: "SEO Expert" },
|
||||
],
|
||||
})}
|
||||
onChanged={noop}
|
||||
onDeleted={noop}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Subtasks (2, 1 open)");
|
||||
expect(html).toContain("The intro");
|
||||
expect(html).toContain("Software Engineer");
|
||||
});
|
||||
|
||||
test("a wide task nobody split yet says so", () => {
|
||||
const html = renderToString(
|
||||
<TaskDetailPanel task={detail({ bot_id: "", workspace_id: 7 })} onChanged={noop} onDeleted={noop} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Not split yet");
|
||||
});
|
||||
|
||||
test("a task with more subtasks than the panel shows offers them all", () => {
|
||||
const total = AppData.TaskSubtasksShown + 2;
|
||||
const subtasks = Array.from({ length: total }, (unused, index) => ({
|
||||
id: 40 + index,
|
||||
title: `Piece ${index + 1}`,
|
||||
status: "todo" as const,
|
||||
bot_id: 3 + index,
|
||||
bot_name: `Bot ${3 + index}`,
|
||||
}));
|
||||
|
||||
const html = renderToString(
|
||||
<TaskDetailPanel
|
||||
task={detail({ bot_id: "", workspace_id: 7, subtasks })}
|
||||
onOpenSubtask={noop}
|
||||
onChanged={noop}
|
||||
onDeleted={noop}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain(`Subtasks (${total}, ${total} open)`);
|
||||
expect(html).toContain("Piece 1");
|
||||
expect(html).toContain(`Piece ${AppData.TaskSubtasksShown}`);
|
||||
expect(html).not.toContain(`Piece ${AppData.TaskSubtasksShown + 1}`);
|
||||
expect(html).toContain(`View all ${total} subtasks`);
|
||||
});
|
||||
|
||||
test("a subtask says which task it belongs to, and opens it", () => {
|
||||
const html = renderToString(
|
||||
<TaskDetailPanel
|
||||
task={detail({ bot_id: 3, workspace_id: 7, parent_task_id: 12, parent_title: "Ship the release" })}
|
||||
onOpenParent={noop}
|
||||
onChanged={noop}
|
||||
onDeleted={noop}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(html).toContain("Parent task");
|
||||
expect(html).toContain("#12 Ship the release");
|
||||
expect(html).toContain("Open the task this is a subtask of");
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Textarea from "@moduletrace/twui/form/Textarea";
|
||||
import { OpenTaskStatuses } from "@/src/dict/task-dict";
|
||||
import type { TaskDetail, TaskFile } from "@/src/types";
|
||||
import type { TaskDetail, TaskFile, TaskWithNames } from "@/src/types";
|
||||
import TaskFileRow from "@/src/components/general/task-file-row";
|
||||
import HandOverForm from "@/src/components/general/hand-over-form";
|
||||
import TaskForm from "@/src/components/general/task-form";
|
||||
@@ -14,9 +14,13 @@ import TaskStatusMoves from "@/src/components/general/task-status-moves";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import TaskFactRow from "@/src/components/general/task-fact-row";
|
||||
import TaskNoteRow from "@/src/components/general/task-note-row";
|
||||
import TaskSubtaskRow from "@/src/components/general/task-subtask-row";
|
||||
import TaskSubtasksModal from "@/src/components/general/task-subtasks-modal";
|
||||
import SubtaskLinkForm from "@/src/components/general/subtask-link-form";
|
||||
import TaskMarkdown from "@/src/components/general/task-markdown";
|
||||
import type { BotFace } from "@/src/dict/bot-dict";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
import relativeTime from "@/src/utils/relative-time";
|
||||
import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi";
|
||||
@@ -28,6 +32,14 @@ type Props = {
|
||||
* A crew manager can change it, file onto it and delete it.
|
||||
*/
|
||||
can_manage?: boolean;
|
||||
/**
|
||||
* Opens one of its subtasks in place, so a split task is one click deep.
|
||||
*/
|
||||
onOpenSubtask?: (subtask: TaskWithNames) => void;
|
||||
/**
|
||||
* Opens the workspace-wide task it is a subtask of, when it is one.
|
||||
*/
|
||||
onOpenParent?: (parent: { id: number; title?: string }) => void;
|
||||
onChanged: (task: TaskDetail, msg?: string) => void;
|
||||
onDeleted: () => void;
|
||||
};
|
||||
@@ -37,28 +49,42 @@ type Props = {
|
||||
* when it last moved, what it is, its files (each opening its bytes), its
|
||||
* notes oldest first, a box to add a note, and edit or delete. A crew
|
||||
* manager can file a new deliverable straight onto it, hand an open one to
|
||||
* another bot, which starts on it, or make a bot's open workspace task
|
||||
* workspace-wide.
|
||||
* another bot, which starts on it, make a bot's open workspace task
|
||||
* workspace-wide, and split a workspace-wide one into subtasks: each piece a
|
||||
* bot's own task, opened from here, or unlinked again to stand alone.
|
||||
*/
|
||||
export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted }: Props) {
|
||||
export default function TaskDetailPanel({
|
||||
task,
|
||||
can_manage,
|
||||
onOpenSubtask,
|
||||
onOpenParent,
|
||||
onChanged,
|
||||
onDeleted,
|
||||
}: Props) {
|
||||
const { pageProps } = useContext(AppContext);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [handing_over, setHandingOver] = useState(false);
|
||||
const [linking, setLinking] = useState(false);
|
||||
const [showing_parts, setShowingParts] = useState(false);
|
||||
const [note, setNote] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<string>();
|
||||
const file_input = useRef<HTMLInputElement>(null);
|
||||
|
||||
const run = async (params: { path: string; body: Record<string, unknown>; done: string }) => {
|
||||
const run = async (params: {
|
||||
path: string;
|
||||
body: Record<string, unknown>;
|
||||
done: string;
|
||||
}) => {
|
||||
if (busy) return;
|
||||
|
||||
setBusy(true);
|
||||
setStatus(undefined);
|
||||
|
||||
const res = await fetchApi<Record<string, unknown>, APIResponseObject<TaskDetail>>(
|
||||
`/api/admin/${params.path}`,
|
||||
{ method: "POST", body: params.body },
|
||||
);
|
||||
const res = await fetchApi<
|
||||
Record<string, unknown>,
|
||||
APIResponseObject<TaskDetail>
|
||||
>(`/api/admin/${params.path}`, { method: "POST", body: params.body });
|
||||
|
||||
setBusy(false);
|
||||
|
||||
@@ -74,7 +100,11 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
const addNote = async () => {
|
||||
if (!note.trim()) return;
|
||||
|
||||
await run({ path: "tasks/add-note", body: { task_id: Number(task.id), text: note }, done: "Note added." });
|
||||
await run({
|
||||
path: "tasks/add-note",
|
||||
body: { task_id: Number(task.id), text: note },
|
||||
done: "Note added.",
|
||||
});
|
||||
setNote("");
|
||||
};
|
||||
|
||||
@@ -95,13 +125,21 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
|
||||
await run({
|
||||
path: "tasks/attach-file",
|
||||
body: { task_id: Number(task.id), data_url, name: file.name, kind: "deliverable" },
|
||||
body: {
|
||||
task_id: Number(task.id),
|
||||
data_url,
|
||||
name: file.name,
|
||||
kind: "deliverable",
|
||||
},
|
||||
done: `${file.name} added as a deliverable.`,
|
||||
});
|
||||
};
|
||||
|
||||
const detach = async ({ file }: { file: TaskFile }) => {
|
||||
if (!window.confirm(`Unlink ${file.name || "this file"} from the task?`)) return;
|
||||
if (
|
||||
!window.confirm(`Unlink ${file.name || "this file"} from the task?`)
|
||||
)
|
||||
return;
|
||||
|
||||
await run({
|
||||
path: "tasks/detach-file",
|
||||
@@ -141,8 +179,29 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
);
|
||||
}
|
||||
|
||||
if (linking) {
|
||||
return (
|
||||
<SubtaskLinkForm
|
||||
task={task}
|
||||
onCancel={() => setLinking(false)}
|
||||
onLinked={(saved, msg) => {
|
||||
setLinking(false);
|
||||
onChanged(saved, msg);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const deliverables = task.files.filter((file) => file.kind != "reference");
|
||||
const references = task.files.filter((file) => file.kind == "reference");
|
||||
const subtasks = task.subtasks || [];
|
||||
const open_parts = subtasks.filter((subtask) =>
|
||||
(OpenTaskStatuses as readonly string[]).includes(subtask.status || ""),
|
||||
).length;
|
||||
const is_task_linked_to_another_task =
|
||||
Boolean(task.parent_task_id) ||
|
||||
Boolean(Number(task.subtask_count || 0));
|
||||
const is_tasks_disabled = busy || is_task_linked_to_another_task;
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-4! items-stretch">
|
||||
@@ -155,7 +214,10 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
onMove={(next) =>
|
||||
run({
|
||||
path: "tasks/save-task",
|
||||
body: { task_id: Number(task.id), status: next },
|
||||
body: {
|
||||
task_id: Number(task.id),
|
||||
status: next,
|
||||
},
|
||||
done: "Status changed.",
|
||||
})
|
||||
}
|
||||
@@ -163,21 +225,32 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
) : null}
|
||||
{can_manage ? (
|
||||
<Row className="ml-auto shrink-0 gap-1! flex-nowrap">
|
||||
{(OpenTaskStatuses as readonly string[]).includes(task.status || "") ? (
|
||||
{(OpenTaskStatuses as readonly string[]).includes(
|
||||
task.status || "",
|
||||
) ? (
|
||||
<Button
|
||||
title="Hand the task to another bot"
|
||||
title={
|
||||
is_task_linked_to_another_task
|
||||
? "Task is linked to another task. Unlink first before handover"
|
||||
: "Hand the task to another bot"
|
||||
}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
disabled={busy}
|
||||
disabled={is_tasks_disabled}
|
||||
onClick={() => setHandingOver(true)}
|
||||
className="px-2! text-[12px]"
|
||||
>
|
||||
Hand over
|
||||
</Button>
|
||||
) : null}
|
||||
{task.workspace_id && task.bot_id && (OpenTaskStatuses as readonly string[]).includes(task.status || "") ? (
|
||||
{task.workspace_id &&
|
||||
task.bot_id &&
|
||||
!task.parent_task_id &&
|
||||
(OpenTaskStatuses as readonly string[]).includes(
|
||||
task.status || "",
|
||||
) ? (
|
||||
<Button
|
||||
title="Make it workspace-wide: every bot in the workspace works on it"
|
||||
type="button"
|
||||
@@ -204,6 +277,50 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
Make workspace-wide
|
||||
</Button>
|
||||
) : null}
|
||||
{can_manage &&
|
||||
task.workspace_id &&
|
||||
task.bot_id &&
|
||||
!task.parent_task_id ? (
|
||||
<Button
|
||||
title="Make it a subtask of a workspace-wide task: the piece this bot took on"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
disabled={busy}
|
||||
onClick={() => setLinking(true)}
|
||||
className="px-2! text-[12px]"
|
||||
>
|
||||
Make it a subtask of...
|
||||
</Button>
|
||||
) : null}
|
||||
{task.parent_task_id ? (
|
||||
<Button
|
||||
title="Take it out of its workspace-wide task: it becomes a task of its own"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (
|
||||
!window.confirm(
|
||||
`Unlink "${task.title}" from task #${task.parent_task_id}? It becomes a task of its own.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
run({
|
||||
path: "tasks/detach-subtask",
|
||||
body: { task_id: Number(task.id) },
|
||||
done: "It's a task of its own now.",
|
||||
}).catch(() => {});
|
||||
}}
|
||||
className="px-2! text-[12px]"
|
||||
>
|
||||
Unlink from parent
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
title="Edit the task"
|
||||
type="button"
|
||||
@@ -224,13 +341,21 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
size="small"
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
if (!window.confirm(`Delete "${task.title}"? Its notes and links go with it.`)) return;
|
||||
if (
|
||||
!window.confirm(
|
||||
`Delete "${task.title}"? Its notes and links go with it.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
setBusy(true);
|
||||
const res = await fetchApi<Record<string, unknown>, APIResponseObject>(
|
||||
"/api/admin/tasks/delete-task",
|
||||
{ method: "POST", body: { task_id: Number(task.id) } },
|
||||
);
|
||||
const res = await fetchApi<
|
||||
Record<string, unknown>,
|
||||
APIResponseObject
|
||||
>("/api/admin/tasks/delete-task", {
|
||||
method: "POST",
|
||||
body: { task_id: Number(task.id) },
|
||||
});
|
||||
setBusy(false);
|
||||
|
||||
if (!res.success) {
|
||||
@@ -254,38 +379,76 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
<>
|
||||
<BotAvatar
|
||||
image_media_id={task.bot_image_media_id}
|
||||
{...botStoneProps({ color: task.bot_color, stone: task.bot_stone, hue: task.bot_hue })}
|
||||
{...botStoneProps({
|
||||
color: task.bot_color,
|
||||
stone: task.bot_stone,
|
||||
hue: task.bot_hue,
|
||||
})}
|
||||
face={(task.bot_face || "idle") as BotFace}
|
||||
size={18}
|
||||
/>
|
||||
<Span className="min-w-0 truncate">{task.bot_name || `Bot ${task.bot_id}`}</Span>
|
||||
<Span className="min-w-0 truncate">
|
||||
{task.bot_name || `Bot ${task.bot_id}`}
|
||||
</Span>
|
||||
</>
|
||||
) : (
|
||||
<Span className="text-ink-secondary">
|
||||
{task.workspace_id ? "Every bot in the workspace (workspace-wide)" : "No bot"}
|
||||
{task.workspace_id
|
||||
? "Every bot in the workspace (workspace-wide)"
|
||||
: "No bot"}
|
||||
</Span>
|
||||
)}
|
||||
</TaskFactRow>
|
||||
<TaskFactRow label="Where">
|
||||
<Span className="min-w-0 truncate">
|
||||
{task.workspace_id
|
||||
? task.workspace_name || `Workspace ${task.workspace_id}`
|
||||
? task.workspace_name ||
|
||||
`Workspace ${task.workspace_id}`
|
||||
: `${task.bot_name || "The bot"}'s own list`}
|
||||
</Span>
|
||||
</TaskFactRow>
|
||||
{task.parent_task_id ? (
|
||||
<TaskFactRow label="Parent task">
|
||||
{onOpenParent ? (
|
||||
<Button
|
||||
title="Open the task this is a subtask of"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
size="small"
|
||||
onClick={() =>
|
||||
onOpenParent({
|
||||
id: Number(task.parent_task_id),
|
||||
title: task.parent_title || undefined,
|
||||
})
|
||||
}
|
||||
className="px-0! h-auto! py-0! text-[13px]! font-normal! leading-[18px]! text-ink! hover:underline"
|
||||
>
|
||||
{`#${task.parent_task_id}${task.parent_title ? ` ${task.parent_title}` : ""}`}
|
||||
</Button>
|
||||
) : (
|
||||
<Span className="min-w-0 truncate">
|
||||
{`#${task.parent_task_id}${task.parent_title ? ` ${task.parent_title}` : ""}`}
|
||||
</Span>
|
||||
)}
|
||||
</TaskFactRow>
|
||||
) : null}
|
||||
<TaskFactRow label="Added">
|
||||
<Span className="min-w-0 truncate">
|
||||
{[
|
||||
task.created_by_bot_id
|
||||
? `By ${task.created_by_bot_name || `bot ${task.created_by_bot_id}`}`
|
||||
: task.created_by_user_id
|
||||
? task.created_by_user_id == pageProps?.user?.id
|
||||
? task.created_by_user_id ==
|
||||
pageProps?.user?.id
|
||||
? "By you"
|
||||
: `By ${task.created_by_user_name || "a user"}`
|
||||
: task.origin == "bot"
|
||||
? "By a bot"
|
||||
: "By hand",
|
||||
task.created_at ? relativeTime({ at: Number(task.created_at) }) : null,
|
||||
task.created_at
|
||||
? relativeTime({ at: Number(task.created_at) })
|
||||
: null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
@@ -293,12 +456,16 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
</TaskFactRow>
|
||||
{task.updated_at ? (
|
||||
<TaskFactRow label="Last moved">
|
||||
<Span>{relativeTime({ at: Number(task.updated_at) })}</Span>
|
||||
<Span>
|
||||
{relativeTime({ at: Number(task.updated_at) })}
|
||||
</Span>
|
||||
</TaskFactRow>
|
||||
) : null}
|
||||
{task.completed_at ? (
|
||||
<TaskFactRow label="Finished">
|
||||
<Span>{relativeTime({ at: Number(task.completed_at) })}</Span>
|
||||
<Span>
|
||||
{relativeTime({ at: Number(task.completed_at) })}
|
||||
</Span>
|
||||
</TaskFactRow>
|
||||
) : null}
|
||||
</Stack>
|
||||
@@ -307,13 +474,67 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
<Span className="text-[13px] leading-[18px] text-ink">{`Waiting on you: ${task.blocked_reason}`}</Span>
|
||||
) : null}
|
||||
|
||||
{task.description ? (
|
||||
<TaskMarkdown text={task.description} />
|
||||
{task.description ? <TaskMarkdown text={task.description} /> : null}
|
||||
|
||||
{task.workspace_id && !task.bot_id ? (
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Span className="text-[12px] font-bold leading-4 text-ink-secondary">
|
||||
{subtasks.length
|
||||
? `Subtasks (${subtasks.length}${open_parts ? `, ${open_parts} open` : ", all done"})`
|
||||
: "Subtasks"}
|
||||
</Span>
|
||||
{subtasks.length ? (
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
{subtasks
|
||||
.slice(0, AppData.TaskSubtasksShown)
|
||||
.map((subtask) => (
|
||||
<TaskSubtaskRow
|
||||
key={subtask.id}
|
||||
subtask={subtask}
|
||||
onOpen={() => onOpenSubtask?.(subtask)}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
Not split yet: every bot here works on it as one
|
||||
task.
|
||||
</Span>
|
||||
)}
|
||||
{subtasks.length > AppData.TaskSubtasksShown ? (
|
||||
<Row className="justify-end">
|
||||
<Button
|
||||
title="Open every subtask of this task"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setShowingParts(true)}
|
||||
className="px-2! text-[12px]"
|
||||
>
|
||||
{`View all ${subtasks.length} subtasks`}
|
||||
</Button>
|
||||
</Row>
|
||||
) : null}
|
||||
</Stack>
|
||||
) : null}
|
||||
|
||||
<TaskSubtasksModal
|
||||
open={showing_parts}
|
||||
setOpen={setShowingParts}
|
||||
task={task}
|
||||
subtasks={subtasks}
|
||||
onOpenSubtask={(subtask) => {
|
||||
setShowingParts(false);
|
||||
onOpenSubtask?.(subtask);
|
||||
}}
|
||||
/>
|
||||
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Span className="text-[12px] font-bold leading-4 text-ink-secondary">
|
||||
{task.files.length ? `Files (${task.files.length})` : "Files"}
|
||||
{task.files.length
|
||||
? `Files (${task.files.length})`
|
||||
: "Files"}
|
||||
</Span>
|
||||
{deliverables.length || references.length ? (
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
@@ -322,12 +543,18 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
key={file.id}
|
||||
file={file}
|
||||
busy={busy}
|
||||
onDetach={can_manage ? () => detach({ file }) : undefined}
|
||||
onDetach={
|
||||
can_manage
|
||||
? () => detach({ file })
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">Nothing filed yet.</Span>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
Nothing filed yet.
|
||||
</Span>
|
||||
)}
|
||||
{can_manage ? (
|
||||
<Row className="gap-2! flex-nowrap items-center">
|
||||
@@ -359,7 +586,9 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Span className="text-[12px] font-bold leading-4 text-ink-secondary">
|
||||
{task.notes.length ? `Notes (${task.notes.length})` : "Notes"}
|
||||
{task.notes.length
|
||||
? `Notes (${task.notes.length})`
|
||||
: "Notes"}
|
||||
</Span>
|
||||
{task.notes.length ? (
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
@@ -368,7 +597,9 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">No notes yet.</Span>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
No notes yet.
|
||||
</Span>
|
||||
)}
|
||||
<Textarea
|
||||
placeholder="Add a note"
|
||||
@@ -394,7 +625,10 @@ export default function TaskDetailPanel({ task, can_manage, onChanged, onDeleted
|
||||
</Stack>
|
||||
|
||||
{status ? (
|
||||
<Span role="status" className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
<Span
|
||||
role="status"
|
||||
className="text-[13px] leading-[18px] text-ink-secondary"
|
||||
>
|
||||
{status}
|
||||
</Span>
|
||||
) : null}
|
||||
|
||||
@@ -29,6 +29,11 @@ type Props = {
|
||||
* works on. A task goes to a bot unless that's picked.
|
||||
*/
|
||||
bots?: { id?: number | string | null; name?: string | null }[];
|
||||
/**
|
||||
* The workspace-wide tasks here a new one can be a subtask of (only the
|
||||
* open ones: a closed task can't be split). Adding, never editing.
|
||||
*/
|
||||
parents?: { id?: number | string | null; title?: string | null }[];
|
||||
/**
|
||||
* Edits this task; adds one when not given.
|
||||
*/
|
||||
@@ -46,6 +51,7 @@ export default function TaskForm({
|
||||
bot_id,
|
||||
workspace_id,
|
||||
bots = [],
|
||||
parents = [],
|
||||
task,
|
||||
onSaved,
|
||||
onCancel,
|
||||
@@ -65,6 +71,9 @@ export default function TaskForm({
|
||||
);
|
||||
const workspace_wide = pick_bot && picked == WorkspaceWideValue;
|
||||
const picked_bot_id = pick_bot && !workspace_wide ? Number(picked) || undefined : bot_id || undefined;
|
||||
const pick_parent = !task && parents.length > 0;
|
||||
const [picked_parent, setPickedParent] = useState<string>("");
|
||||
const parent_task_id = pick_parent && picked_parent ? Number(picked_parent) || undefined : undefined;
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>();
|
||||
|
||||
@@ -94,6 +103,7 @@ export default function TaskForm({
|
||||
bot_id: task || workspace_wide ? undefined : picked_bot_id,
|
||||
workspace_id: task ? undefined : workspace_id || undefined,
|
||||
workspace_wide: task ? undefined : workspace_wide || undefined,
|
||||
parent_task_id,
|
||||
title,
|
||||
description,
|
||||
status,
|
||||
@@ -145,6 +155,32 @@ export default function TaskForm({
|
||||
changeHandler={(value) => setPicked(String(value))}
|
||||
/>
|
||||
) : null}
|
||||
{pick_parent ? (
|
||||
<Select
|
||||
title="Parent task"
|
||||
label="Parent task"
|
||||
showLabel
|
||||
options={[
|
||||
{
|
||||
title: "A task of its own",
|
||||
value: "",
|
||||
default: !picked_parent,
|
||||
},
|
||||
...parents.map((parent) => ({
|
||||
title: `#${parent.id} ${parent.title || ""}`.trim(),
|
||||
value: String(parent.id),
|
||||
default: String(parent.id) == picked_parent,
|
||||
})),
|
||||
]}
|
||||
changeHandler={(value) => {
|
||||
const next = String(value);
|
||||
|
||||
setPickedParent(next);
|
||||
|
||||
if (next && workspace_wide && default_bot_id) setPicked(String(default_bot_id));
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<CodeEditor
|
||||
mode="markdown"
|
||||
className="h-[500px]"
|
||||
|
||||
@@ -35,4 +35,42 @@ describe("TaskListItem", () => {
|
||||
expect(html).toContain("Workspace wide");
|
||||
expect(html).toContain("#42");
|
||||
});
|
||||
|
||||
test("a workspace-wide task wears the workspace's picture, or its icon when it has none", () => {
|
||||
const pictured = renderToString(
|
||||
<TaskListItem
|
||||
task={{ ...base_task, title: "Ship it", bot_id: "", workspace_id: 7, workspace_image_media_id: 31 }}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(pictured).toContain("/media/31/thumbnail");
|
||||
|
||||
const plain = renderToString(<TaskListItem task={{ ...base_task, title: "Ship it", bot_id: "", workspace_id: 7 }} />);
|
||||
|
||||
expect(plain).not.toContain("/media/");
|
||||
});
|
||||
|
||||
test("a subtask says which task it belongs to, and a split task how many subtasks are open", () => {
|
||||
const part = renderToString(
|
||||
<TaskListItem task={{ ...base_task, title: "The intro", parent_task_id: 12, parent_title: "Ship it" }} />,
|
||||
);
|
||||
|
||||
expect(part).toContain("Subtask of #12");
|
||||
|
||||
const parent = renderToString(
|
||||
<TaskListItem
|
||||
task={{ ...base_task, title: "Ship it", bot_id: "", workspace_id: 7, subtask_count: 3, subtask_open_count: 2 }}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(parent).toContain("2 of 3 subtasks open");
|
||||
|
||||
const finished = renderToString(
|
||||
<TaskListItem
|
||||
task={{ ...base_task, title: "Ship it", bot_id: "", workspace_id: 7, subtask_count: 2, subtask_open_count: 0 }}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(finished).toContain("all 2 subtasks done");
|
||||
});
|
||||
});
|
||||
@@ -7,13 +7,14 @@ import Button from "@moduletrace/twui/layout/Button";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import BotAvatar from "@/src/components/general/bot-avatar";
|
||||
import WorkspaceAvatar from "@/src/components/general/workspace-avatar";
|
||||
import type { BotFace } from "@/src/dict/bot-dict";
|
||||
import botStoneProps from "@/src/utils/bot-stone-props";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import relativeTime from "@/src/utils/relative-time";
|
||||
import taskPlaceLabel from "@/src/utils/task-place-label";
|
||||
import Center from "@moduletrace/twui/layout/Center";
|
||||
import { Trash2, Users } from "lucide-react";
|
||||
|
||||
import { Trash2 } from "lucide-react";
|
||||
import RowIconButton from "./row-icon-button";
|
||||
import TaskStatusChip from "./task-status-chip";
|
||||
import TaskStatusMoves from "./task-status-moves";
|
||||
@@ -37,8 +38,8 @@ type Props = {
|
||||
};
|
||||
|
||||
/**
|
||||
* One task: whose it is (a bot's stone, or a crew mark when it's
|
||||
* workspace-wide), its title and status, where it
|
||||
* One task: whose it is (a bot's stone, or the workspace's own picture when
|
||||
* it's workspace-wide and nobody's), its title and status, where it
|
||||
* is and who has it, what it's blocked on, its latest note and how long ago it
|
||||
* moved. Its title opens it in a modal.
|
||||
*/
|
||||
@@ -57,9 +58,12 @@ export default function TaskListItem({ task, onOpen, onStatusChange, onDelete, b
|
||||
size={28}
|
||||
/>
|
||||
) : (
|
||||
<Center title="Workspace-wide: every bot here works on it" className="size-7 shrink-0 text-ink-secondary">
|
||||
<Users size={18} />
|
||||
</Center>
|
||||
<Span
|
||||
title="Workspace-wide: every bot here works on it"
|
||||
className="flex size-7 shrink-0 items-center justify-center"
|
||||
>
|
||||
<WorkspaceAvatar image_media_id={task.workspace_image_media_id} size="md" />
|
||||
</Span>
|
||||
)}
|
||||
<Stack className="grow min-w-0 gap-0.5! items-stretch">
|
||||
<Row className="w-full gap-2! flex-nowrap items-center">
|
||||
@@ -99,6 +103,24 @@ export default function TaskListItem({ task, onOpen, onStatusChange, onDelete, b
|
||||
<Span className="shrink-0 text-xs leading-4 text-ink-secondary truncate">
|
||||
{taskPlaceLabel({ task })}
|
||||
</Span>
|
||||
{task.parent_task_id ? (
|
||||
<Span
|
||||
title={`Subtask of task ${task.parent_task_id}${task.parent_title ? `: ${task.parent_title}` : ""}`}
|
||||
className="shrink-0 text-[11px] leading-4 text-ink-secondary"
|
||||
>
|
||||
{`Subtask of #${task.parent_task_id}`}
|
||||
</Span>
|
||||
) : null}
|
||||
{Number(task.subtask_count || 0) ? (
|
||||
<Span
|
||||
title={`${task.subtask_count} subtask(s), ${task.subtask_open_count || 0} still open`}
|
||||
className="shrink-0 text-[11px] leading-4 text-ink-secondary"
|
||||
>
|
||||
{Number(task.subtask_open_count || 0)
|
||||
? `${task.subtask_open_count} of ${task.subtask_count} subtasks open`
|
||||
: `all ${task.subtask_count} subtasks done`}
|
||||
</Span>
|
||||
) : null}
|
||||
{task.status == "blocked" && task.blocked_reason ? (
|
||||
<Span className="min-w-0 text-xs leading-4 text-ink truncate">
|
||||
{`Waiting on you: ${task.blocked_reason}`}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import TaskStatusChip from "./task-status-chip";
|
||||
|
||||
type Props = {
|
||||
/**
|
||||
* One subtask of a workspace-wide task.
|
||||
*/
|
||||
subtask: TaskWithNames;
|
||||
/**
|
||||
* Opens it in the task modal.
|
||||
*/
|
||||
onOpen: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One subtask under its workspace-wide task: its status, its title and the bot
|
||||
* that has it (or nobody yet). Clicking it opens the subtask.
|
||||
*/
|
||||
export default function TaskSubtaskRow({ subtask, onOpen }: Props) {
|
||||
const done = subtask.status == "done" || subtask.status == "cancelled";
|
||||
|
||||
return (
|
||||
<Row className="w-full gap-2! flex-nowrap items-center py-1">
|
||||
<TaskStatusChip status={subtask.status} />
|
||||
<Button
|
||||
title={`Open ${subtask.title || `task ${subtask.id}`}`}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
onClick={onOpen}
|
||||
className={twMerge(
|
||||
"grow min-w-0 justify-start px-0! h-auto! py-0! text-[13px]! font-normal! leading-[18px]! truncate text-left hover:bg-transparent! hover:underline",
|
||||
"[&_.twui-button-content-wrapper]:min-w-0 [&_.twui-button-content-wrapper]:gap-1.5",
|
||||
done ? "text-ink-secondary! line-through" : "text-ink!",
|
||||
)}
|
||||
>
|
||||
<Span className="truncate">{subtask.title || `Task ${subtask.id}`}</Span>
|
||||
<Span
|
||||
title={`Task ${subtask.id}`}
|
||||
className="shrink-0 text-[11px] leading-4 font-normal text-ink-secondary tabular-nums"
|
||||
>
|
||||
{`#${subtask.id}`}
|
||||
</Span>
|
||||
</Button>
|
||||
<Span className="shrink-0 text-[11px] leading-4 text-ink-secondary">
|
||||
{subtask.bot_name || (subtask.bot_id ? `Bot ${subtask.bot_id}` : "Nobody")}
|
||||
</Span>
|
||||
</Row>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { OpenTaskStatuses } from "@/src/dict/task-dict";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import TaskSubtaskRow from "./task-subtask-row";
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
/**
|
||||
* The workspace-wide task they belong to.
|
||||
*/
|
||||
task: TaskWithNames;
|
||||
/**
|
||||
* Every subtask of it, in the order the task keeps them.
|
||||
*/
|
||||
subtasks: TaskWithNames[];
|
||||
/**
|
||||
* Opens one of them in the task modal.
|
||||
*/
|
||||
onOpenSubtask: (subtask: TaskWithNames) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Every subtask of a workspace-wide task: the whole list, when the task itself
|
||||
* only shows the first few.
|
||||
*/
|
||||
export default function TaskSubtasksModal({ open, setOpen, task, subtasks, onOpenSubtask }: Props) {
|
||||
const open_parts = subtasks.filter((subtask) => (OpenTaskStatuses as readonly string[]).includes(subtask.status || ""))
|
||||
.length;
|
||||
const count = `${subtasks.length} subtask${subtasks.length == 1 ? "" : "s"}`;
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
open={open}
|
||||
setOpen={setOpen}
|
||||
title={`Subtasks of task #${task.id}`}
|
||||
description={`${task.title ? `"${task.title}": ` : ""}${count}, ${open_parts ? `${open_parts} still open` : "all done"}. Each one is a bot's own task, and the parent stays open until someone verifies them.`}
|
||||
>
|
||||
<Stack className="w-full mt-4 max-h-[50vh] gap-0! items-stretch overflow-y-auto">
|
||||
{subtasks.map((subtask) => (
|
||||
<TaskSubtaskRow key={subtask.id} subtask={subtask} onOpen={() => onOpenSubtask(subtask)} />
|
||||
))}
|
||||
</Stack>
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
|
||||
|
||||
type Props = {
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Keeps Escape on the modal on top of a stack: twui's modal closes every open
|
||||
* one, so a part opened from a task (or a task from the workspace's list)
|
||||
* would take the one below it away too. Mounted only while its modal is open,
|
||||
* it closes that one alone and the press goes no further.
|
||||
*/
|
||||
export default function TopModalEscape({ onClose }: Props) {
|
||||
useTopModalEscape({ onClose });
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import profileImageUrls from "@/src/utils/profile-image-urls";
|
||||
const WorkspaceAvatarSizes = {
|
||||
xs: { box: "size-[18px] min-w-[18px] rounded-[4px]", icon: 12 },
|
||||
sm: { box: "size-8 min-w-8 rounded-default-sm", icon: 16 },
|
||||
md: { box: "size-7 min-w-7 rounded-default-sm", icon: 15 },
|
||||
lg: { box: "size-14 min-w-14 rounded-default", icon: 24 },
|
||||
} as const;
|
||||
|
||||
|
||||
@@ -435,6 +435,22 @@ export const AppData = {
|
||||
TaskNoteMaxLength: 4000,
|
||||
TaskMaxPerScope: 200,
|
||||
TaskMediaMaxPerTask: 20,
|
||||
/**
|
||||
* Parts one workspace-wide task can be split into, so a crew that keeps
|
||||
* splitting never turns one task into a hundred. A part can't be split
|
||||
* again, so this is the whole tree.
|
||||
*/
|
||||
TaskSubtaskMaxPerParent: 12,
|
||||
/**
|
||||
* Tasks a workspace page lists at a time, before the View all button
|
||||
* opens the rest in a modal: wide ones first, then each bot's.
|
||||
*/
|
||||
TaskSectionShown: 5,
|
||||
/**
|
||||
* Subtasks a workspace-wide task's own panel lists inline, before its
|
||||
* View all button opens every one of them in a modal.
|
||||
*/
|
||||
TaskSubtasksShown: 7,
|
||||
/**
|
||||
* Open tasks a chat reply carries as a digest for its reminder, and how
|
||||
* many `list_tasks` hands back at once.
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import subtaskLinkProblem from "@/src/utils/task-subtasks/subtask-link-problem";
|
||||
import grabTaskRow from "./grab-task-scope";
|
||||
|
||||
type Params = {
|
||||
parent_task_id: number | string;
|
||||
/**
|
||||
* Who would have the subtask (a subtask always belongs to one bot).
|
||||
*/
|
||||
bot_id?: number | string | null;
|
||||
/**
|
||||
* The workspace it would be created in.
|
||||
*/
|
||||
workspace_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* The task a new subtask would belong to, checked: a workspace-wide task that
|
||||
* isn't itself a subtask, open, in the subtask's workspace
|
||||
* (`subtaskLinkProblem`). The caller checked who is asking reaches the
|
||||
* parent. Returns the parent's row.
|
||||
*/
|
||||
export default async function assertSubtaskParent({ parent_task_id, bot_id, workspace_id }: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
|
||||
const parent = await grabTaskRow({ task_id: parent_task_id });
|
||||
const problem = subtaskLinkProblem({ parent, bot_id, workspace_id });
|
||||
|
||||
if (problem) throw new AppError(problem);
|
||||
|
||||
return parent;
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import AppError from "@/src/utils/app-error";
|
||||
import grabCrewRole from "../access/grab-crew-role";
|
||||
import grabTask from "./grab-task";
|
||||
import assertBotWorksThere from "./assert-bot-works-there";
|
||||
import assertSubtaskParent from "./assert-subtask-parent";
|
||||
import grabSubtaskCounts from "./grab-subtask-counts";
|
||||
import taskScopeValues from "./task-scope-values";
|
||||
|
||||
type Params = {
|
||||
@@ -24,6 +26,11 @@ type Params = {
|
||||
* it (`taskScopeValues`). Only when asked for.
|
||||
*/
|
||||
workspace_wide?: boolean;
|
||||
/**
|
||||
* The workspace-wide task this one is a subtask of (`assertSubtaskParent`):
|
||||
* one piece of that work, a bot's own task in the same workspace.
|
||||
*/
|
||||
parent_task_id?: number | string | null;
|
||||
/**
|
||||
* The bot creating it with its tool; none for a user's manual add.
|
||||
*/
|
||||
@@ -46,6 +53,7 @@ export default async function createTask({
|
||||
description,
|
||||
status,
|
||||
workspace_wide,
|
||||
parent_task_id,
|
||||
created_by_bot_id,
|
||||
}: Params): Promise<TaskDetail> {
|
||||
const scope = taskScopeValues({ bot_id, workspace_id, workspace_wide });
|
||||
@@ -59,6 +67,18 @@ export default async function createTask({
|
||||
await assertBotWorksThere({ bot_id: scope.bot_id, workspace_id: scope.workspace_id });
|
||||
}
|
||||
|
||||
if (parent_task_id) {
|
||||
await assertSubtaskParent({ parent_task_id, bot_id: scope.bot_id, workspace_id: scope.workspace_id });
|
||||
|
||||
const { linked } = await grabSubtaskCounts({ task_id: parent_task_id });
|
||||
|
||||
if (linked >= AppData.TaskSubtaskMaxPerParent) {
|
||||
throw new AppError(
|
||||
`Task #${parent_task_id} already has ${AppData.TaskSubtaskMaxPerParent} subtasks: work on one of those, or unlink one first.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const count = Number(
|
||||
(
|
||||
await BunSQLite.sql<{ n: number }>({
|
||||
@@ -80,6 +100,7 @@ export default async function createTask({
|
||||
{
|
||||
bot_id: scope.bot_id || undefined,
|
||||
workspace_id: scope.workspace_id || undefined,
|
||||
parent_task_id: parent_task_id ? Number(parent_task_id) : undefined,
|
||||
title: title.trim().slice(0, AppData.TaskTitleMaxLength),
|
||||
description: description || undefined,
|
||||
status: status || "todo",
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_TASK_MEDIA } from "@/db/types/db";
|
||||
import type { BUN_SQLITE_COBBLE_TASK_MEDIA, BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import subtaskDeleteProblem from "@/src/utils/task-subtasks/subtask-delete-problem";
|
||||
import grabCrewRole from "../access/grab-crew-role";
|
||||
import deleteMedia from "../media/delete-media";
|
||||
import grabSubtaskCounts from "./grab-subtask-counts";
|
||||
import grabTaskRow from "./grab-task-scope";
|
||||
|
||||
type Params = {
|
||||
@@ -16,9 +18,12 @@ type Params = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a task with its notes and file links (cascades). The files
|
||||
* themselves stay where they are: a `task_media` link is not the bytes'
|
||||
* owner, so a bot file's folder keeps its file and only the link goes.
|
||||
* Deletes a task with its notes and file links (cascades), and with its
|
||||
* subtasks when they are all finished: refused while any subtask is still open
|
||||
* (`subtaskDeleteProblem`), so a delete never throws away work someone is
|
||||
* on. The files themselves stay where they are: a `task_media` link is not
|
||||
* the bytes' owner, so a bot file's folder keeps its file and only the
|
||||
* link goes.
|
||||
*/
|
||||
export default async function deleteTask({ user_id, task_id, deleted_by_bot_id }: Params) {
|
||||
const task = await grabTaskRow({ task_id });
|
||||
@@ -28,24 +33,50 @@ export default async function deleteTask({ user_id, task_id, deleted_by_bot_id }
|
||||
throw new AppError(`Only an admin can delete a task.`);
|
||||
}
|
||||
|
||||
const { open } = await grabSubtaskCounts({ task_id: task.id! });
|
||||
const problem = subtaskDeleteProblem({ task, open_subtasks: open });
|
||||
|
||||
if (problem) throw new AppError(problem);
|
||||
|
||||
const children = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_TASKS>({
|
||||
sql: `SELECT * FROM tasks WHERE parent_task_id = ?`,
|
||||
values: [Number(task.id)],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
const child_ids = children.map((child) => Number(child.id));
|
||||
|
||||
/**
|
||||
* Read before the delete: the links go with the task, and the media
|
||||
* Read before the delete: the links go with the tasks, and the media
|
||||
* rows a chat upload left are deleted with them (a bot file's bytes
|
||||
* belong to its folder, not to the task).
|
||||
*/
|
||||
const links = (
|
||||
await BunSQLite.sql<BUN_SQLITE_COBBLE_TASK_MEDIA>({
|
||||
sql: `SELECT * FROM task_media WHERE task_id = ?`,
|
||||
values: [Number(task_id)],
|
||||
sql: `SELECT * FROM task_media WHERE task_id = ? OR task_id IN (${child_ids.map(() => "?").join(", ") || "NULL"})`,
|
||||
values: [Number(task.id), ...child_ids],
|
||||
})
|
||||
).payload || [];
|
||||
|
||||
const res = await BunSQLite.sql({ sql: `DELETE FROM tasks WHERE id = ?`, values: [Number(task_id)] });
|
||||
const res = await BunSQLite.sql({ sql: `DELETE FROM tasks WHERE id = ?`, values: [Number(task.id)] });
|
||||
|
||||
if (!res.success) {
|
||||
throw new AppError(`Couldn't delete the task: ${res.msg || res.error}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The subtasks go explicitly, children first: foreign keys are off outside
|
||||
* the server process, so nothing cascades on its own.
|
||||
*/
|
||||
if (child_ids.length) {
|
||||
const marks = child_ids.map(() => "?").join(", ");
|
||||
|
||||
await BunSQLite.sql({ sql: `DELETE FROM task_notes WHERE task_id IN (${marks})`, values: child_ids });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM task_media WHERE task_id IN (${marks})`, values: child_ids });
|
||||
await BunSQLite.sql({ sql: `DELETE FROM tasks WHERE id IN (${marks})`, values: child_ids });
|
||||
}
|
||||
|
||||
const uploads = links.filter((link) => !link.bot_file_id).map((link) => Number(link.media_id));
|
||||
|
||||
if (uploads.length) {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import addTaskNote from "./add-task-note";
|
||||
import grabTaskRow from "./grab-task-scope";
|
||||
|
||||
type Params = {
|
||||
task_id: number | string;
|
||||
/**
|
||||
* The bot unlinking it with its tool; none when a crew manager does.
|
||||
*/
|
||||
by_bot_id?: number | string | null;
|
||||
/**
|
||||
* Who does, by name, for the log.
|
||||
*/
|
||||
by_name: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Takes a subtask out of its workspace-wide task, leaving an ordinary task of
|
||||
* its bot in that workspace, with a note saying it was unlinked. The only
|
||||
* way a subtask stops being one: a task that has subtasks can't be moved until
|
||||
* they are, and a subtask is never moved itself. The caller checked who is
|
||||
* asking may. Returns the row as it is now.
|
||||
*/
|
||||
export default async function detachSubtask({ task_id, by_bot_id, by_name }: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
|
||||
const task = await grabTaskRow({ task_id });
|
||||
|
||||
if (!task.parent_task_id) {
|
||||
throw new AppError(`Task #${task.id} isn't a subtask of another task.`);
|
||||
}
|
||||
|
||||
const res = await BunSQLite.sql({
|
||||
sql: `UPDATE tasks SET parent_task_id = NULL, updated_at = ? WHERE id = ?`,
|
||||
values: [Date.now(), Number(task.id)],
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
throw new AppError(`Couldn't unlink the task: ${res.msg || res.error}`);
|
||||
}
|
||||
|
||||
await addTaskNote({
|
||||
task_id: task.id!,
|
||||
text: `${by_name} unlinked this from task #${task.parent_task_id}: it's a task of its own now.`,
|
||||
author: by_bot_id ? "bot" : "user",
|
||||
bot_id: by_bot_id || null,
|
||||
});
|
||||
|
||||
return await grabTaskRow({ task_id: task.id! });
|
||||
}
|
||||
@@ -36,4 +36,16 @@ describe("findDuplicateTask", () => {
|
||||
expect(findDuplicateTask({ tasks, title: "Check the invoices", bot_id: 2 })).toBeNull();
|
||||
expect(findDuplicateTask({ tasks, title: "Check the invoices", workspace_id: 9, bot_id: 3 })?.id).toBe(7);
|
||||
});
|
||||
|
||||
test("two parts of different parents may share a title, the same parent's may not", () => {
|
||||
const tasks = [task({ id: 8, bot_id: 2, workspace_id: 9, parent_task_id: 12, title: "Write the intro" })];
|
||||
|
||||
expect(
|
||||
findDuplicateTask({ tasks, title: "Write the intro", workspace_id: 9, bot_id: 2, parent_task_id: 12 })?.id,
|
||||
).toBe(8);
|
||||
expect(
|
||||
findDuplicateTask({ tasks, title: "Write the intro", workspace_id: 9, bot_id: 2, parent_task_id: 13 }),
|
||||
).toBeNull();
|
||||
expect(findDuplicateTask({ tasks, title: "Write the intro", workspace_id: 9, bot_id: 2 })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,6 +8,11 @@ type Params = {
|
||||
*/
|
||||
bot_id?: number | null;
|
||||
workspace_id?: number | null;
|
||||
/**
|
||||
* The subtask's parent: two subtasks of different parents may share a title
|
||||
* ("Write the intro" under two releases), the same parent's may not.
|
||||
*/
|
||||
parent_task_id?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -15,7 +20,7 @@ type Params = {
|
||||
* `ActionCheckNote` gets real behaviour: a bot updates the existing task
|
||||
* instead of adding a second one for the same work.
|
||||
*/
|
||||
export default function findDuplicateTask({ tasks, title, bot_id, workspace_id }: Params) {
|
||||
export default function findDuplicateTask({ tasks, title, bot_id, workspace_id, parent_task_id }: Params) {
|
||||
const wanted = title.trim().toLowerCase();
|
||||
|
||||
return (
|
||||
@@ -27,6 +32,8 @@ export default function findDuplicateTask({ tasks, title, bot_id, workspace_id }
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Number(task.parent_task_id || 0) != Number(parent_task_id || 0)) return false;
|
||||
|
||||
return (task.title || "").trim().toLowerCase() == wanted;
|
||||
}) || null
|
||||
);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { OpenTaskStatuses } from "@/src/dict/task-dict";
|
||||
|
||||
type Params = {
|
||||
task_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* How many tasks are subtasks of this one, and how many of those still need
|
||||
* work: what the move and delete checks read (`subtaskMoveProblem`,
|
||||
* `subtaskDeleteProblem`) and what a list shows as its progress.
|
||||
*/
|
||||
export default async function grabSubtaskCounts({ task_id }: Params): Promise<{ linked: number; open: number }> {
|
||||
const res = await BunSQLite.sql<{ linked: number; open: number }>({
|
||||
sql: `SELECT COUNT(*) AS linked,
|
||||
COALESCE(SUM(CASE WHEN status IN (${OpenTaskStatuses.map(() => "?").join(", ")}) THEN 1 ELSE 0 END), 0) AS open
|
||||
FROM tasks WHERE parent_task_id = ?`,
|
||||
values: [...OpenTaskStatuses, Number(task_id)],
|
||||
});
|
||||
|
||||
const row = res.payload?.[0];
|
||||
|
||||
return { linked: Number(row?.linked || 0), open: Number(row?.open || 0) };
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import grabTasks from "./grab-tasks";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The user asking: they must reach the workspace.
|
||||
*/
|
||||
user_id: number | string;
|
||||
/**
|
||||
* The task that would become a subtask: its own workspace's wide tasks are
|
||||
* the only ones it can join.
|
||||
*/
|
||||
task: { id?: number | string | null; workspace_id?: number | string | null };
|
||||
};
|
||||
|
||||
/**
|
||||
* The workspace-wide tasks a bot's task in that workspace can be attached
|
||||
* to: the open ones, the user's to pick from when the picker opens.
|
||||
*/
|
||||
export default async function grabSubtaskParents({ user_id, task }: Params): Promise<TaskWithNames[]> {
|
||||
if (!task.workspace_id) return [];
|
||||
|
||||
const tasks = await grabTasks({ user_id, only_workspace_id: task.workspace_id, open_only: true });
|
||||
|
||||
return tasks.filter((candidate) => !candidate.bot_id && Number(candidate.id) != Number(task.id || 0));
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { TaskDetail } from "@/src/types";
|
||||
import { OpenTaskStatuses } from "@/src/dict/task-dict";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import botFaceSql from "@/src/utils/bot-face-sql";
|
||||
import taskScopesSql from "@/src/utils/task-access/task-scopes-sql";
|
||||
import grabCrewRole from "../access/grab-crew-role";
|
||||
import grabTaskMedia from "./grab-task-media";
|
||||
import grabTaskNotes from "./grab-task-notes";
|
||||
import grabTasks from "./grab-tasks";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -17,7 +19,8 @@ type Params = {
|
||||
|
||||
/**
|
||||
* One task with its notes (oldest first, each with the bot that wrote it),
|
||||
* its files and who added it, only if the user
|
||||
* its files, who added it and its subtasks when it is workspace-wide (each as a
|
||||
* list shows it, only the ones the user reaches), only if the user
|
||||
* reaches the bot or workspace it belongs to (`taskScopesSql`, the same
|
||||
* condition the lists use).
|
||||
*/
|
||||
@@ -27,17 +30,21 @@ export default async function grabTask({ user_id, task_id }: Params): Promise<Ta
|
||||
|
||||
const row_res = await BunSQLite.sql<TaskDetail>({
|
||||
sql: `SELECT t.*, b.name AS bot_name, b.kind AS bot_kind, b.hue AS bot_hue, b.color AS bot_color, b.stone AS bot_stone,
|
||||
b.image_media_id AS bot_image_media_id, ${face.sql}, w.name AS workspace_name,
|
||||
b.image_media_id AS bot_image_media_id, ${face.sql}, w.name AS workspace_name, w.image_media_id AS workspace_image_media_id,
|
||||
p.title AS parent_title, p.status AS parent_status,
|
||||
(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id) AS subtask_count,
|
||||
(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id AND st.status IN (${OpenTaskStatuses.map(() => "?").join(", ")})) AS subtask_open_count,
|
||||
cb.name AS created_by_bot_name,
|
||||
NULLIF(TRIM(COALESCE(cu.first_name, '') || ' ' || COALESCE(cu.last_name, '')), '') AS created_by_user_name
|
||||
FROM tasks t
|
||||
LEFT JOIN bots b ON b.id = t.bot_id
|
||||
LEFT JOIN workspaces w ON w.id = t.workspace_id
|
||||
LEFT JOIN tasks p ON p.id = t.parent_task_id
|
||||
LEFT JOIN bots cb ON cb.id = t.created_by_bot_id
|
||||
LEFT JOIN users cu ON cu.id = t.created_by_user_id
|
||||
WHERE t.id = ? AND ${access.sql}
|
||||
LIMIT 1`,
|
||||
values: [...face.values, Number(task_id), ...access.values],
|
||||
values: [...face.values, ...OpenTaskStatuses, Number(task_id), ...access.values],
|
||||
});
|
||||
|
||||
const row = row_res.payload?.[0];
|
||||
@@ -46,7 +53,11 @@ export default async function grabTask({ user_id, task_id }: Params): Promise<Ta
|
||||
throw new AppError(`Task not found.`);
|
||||
}
|
||||
|
||||
const [notes, files] = await Promise.all([grabTaskNotes({ task_id }), grabTaskMedia({ task_id })]);
|
||||
const [notes, files, subtasks] = await Promise.all([
|
||||
grabTaskNotes({ task_id }),
|
||||
grabTaskMedia({ task_id }),
|
||||
grabTasks({ user_id, only_parent_task_id: Number(task_id) }),
|
||||
]);
|
||||
|
||||
return { ...row, notes, files };
|
||||
return { ...row, notes, files, subtasks };
|
||||
}
|
||||
|
||||
@@ -35,6 +35,10 @@ type Params = {
|
||||
* Only one workspace's tasks.
|
||||
*/
|
||||
only_workspace_id?: number | string | null;
|
||||
/**
|
||||
* Only the tasks that are subtasks of this one, for a parent's detail.
|
||||
*/
|
||||
only_parent_task_id?: number | string | null;
|
||||
/**
|
||||
* Only bots' own lists, outside any workspace.
|
||||
*/
|
||||
@@ -63,6 +67,7 @@ export default async function grabTasks({
|
||||
only_bot_id,
|
||||
with_workspace_wide,
|
||||
only_workspace_id,
|
||||
only_parent_task_id,
|
||||
own_list,
|
||||
statuses,
|
||||
open_only,
|
||||
@@ -95,6 +100,11 @@ export default async function grabTasks({
|
||||
values.push(Number(only_workspace_id));
|
||||
}
|
||||
|
||||
if (only_parent_task_id) {
|
||||
where.push(`t.parent_task_id = ?`);
|
||||
values.push(Number(only_parent_task_id));
|
||||
}
|
||||
|
||||
const wanted = open_only ? [...OpenTaskStatuses] : statuses?.length ? statuses : null;
|
||||
|
||||
if (wanted) {
|
||||
@@ -106,7 +116,10 @@ export default async function grabTasks({
|
||||
|
||||
const res = await BunSQLite.sql<TaskWithNames>({
|
||||
sql: `SELECT t.*, b.name AS bot_name, b.kind AS bot_kind, b.hue AS bot_hue, b.color AS bot_color, b.stone AS bot_stone,
|
||||
b.image_media_id AS bot_image_media_id, ${face.sql}, w.name AS workspace_name,
|
||||
b.image_media_id AS bot_image_media_id, ${face.sql}, w.name AS workspace_name, w.image_media_id AS workspace_image_media_id,
|
||||
p.title AS parent_title,
|
||||
(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id) AS subtask_count,
|
||||
(SELECT COUNT(*) FROM tasks st WHERE st.parent_task_id = t.id AND st.status IN (${OpenTaskStatuses.map(() => "?").join(", ")})) AS subtask_open_count,
|
||||
(SELECT n.text FROM task_notes n WHERE n.task_id = t.id ORDER BY n.id DESC LIMIT 1) AS latest_note,
|
||||
(SELECT CASE WHEN n.author = 'user' THEN NULL ELSE COALESCE(nb.name, 'Bot ' || n.bot_id) END
|
||||
FROM task_notes n LEFT JOIN bots nb ON nb.id = n.bot_id
|
||||
@@ -115,11 +128,12 @@ export default async function grabTasks({
|
||||
FROM tasks t
|
||||
LEFT JOIN bots b ON b.id = t.bot_id
|
||||
LEFT JOIN workspaces w ON w.id = t.workspace_id
|
||||
LEFT JOIN tasks p ON p.id = t.parent_task_id
|
||||
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
|
||||
ORDER BY CASE t.status WHEN 'blocked' THEN 0 WHEN 'doing' THEN 1 WHEN 'todo' THEN 2 WHEN 'done' THEN 3 ELSE 4 END,
|
||||
t.updated_at DESC, t.id DESC
|
||||
${limit ? `LIMIT ${Number(limit)}` : ""}`,
|
||||
values: [...face.values, ...values],
|
||||
values: [...face.values, ...OpenTaskStatuses, ...values],
|
||||
});
|
||||
|
||||
return res.payload || [];
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { TaskDetail } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import subtaskAttachProblem from "@/src/utils/task-subtasks/subtask-attach-problem";
|
||||
import addTaskNote from "./add-task-note";
|
||||
import grabSubtaskCounts from "./grab-subtask-counts";
|
||||
import grabTask from "./grab-task";
|
||||
import grabTaskRow from "./grab-task-scope";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The user attaching it; they must reach the task.
|
||||
*/
|
||||
user_id: number | string;
|
||||
task_id: number | string;
|
||||
/**
|
||||
* The workspace-wide task it becomes a subtask of.
|
||||
*/
|
||||
parent_task_id: number | string;
|
||||
/**
|
||||
* The bot's run doing it; none for the user. Either way, the caller
|
||||
* checked the run or user reaches the task.
|
||||
*/
|
||||
by_bot_id?: number | string | null;
|
||||
/**
|
||||
* Who did it, for the two logs.
|
||||
*/
|
||||
by_name: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Attaches a bot's open task in a workspace to a workspace-wide task there:
|
||||
* the subtask of it that bot took on (`subtaskAttachProblem` says when it
|
||||
* can't). Both logs say who joined which, since the parent's own log is
|
||||
* where a crew manager sees how the split work is going.
|
||||
*/
|
||||
export default async function linkSubtask({
|
||||
user_id,
|
||||
task_id,
|
||||
parent_task_id,
|
||||
by_bot_id,
|
||||
by_name,
|
||||
}: Params): Promise<TaskDetail> {
|
||||
const task = await grabTaskRow({ task_id });
|
||||
/**
|
||||
* Read the same way: a missing parent throws "Task not found" before
|
||||
* anything is written.
|
||||
*/
|
||||
const parent = await grabTaskRow({ task_id: parent_task_id });
|
||||
const [{ linked }, own] = await Promise.all([
|
||||
grabSubtaskCounts({ task_id: parent_task_id }),
|
||||
grabSubtaskCounts({ task_id }),
|
||||
]);
|
||||
const problem = subtaskAttachProblem({ task, parent, task_subtasks: own.linked });
|
||||
|
||||
if (problem) throw new AppError(problem);
|
||||
|
||||
if (linked >= AppData.TaskSubtaskMaxPerParent) {
|
||||
throw new AppError(
|
||||
`Task #${parent.id} already has ${AppData.TaskSubtaskMaxPerParent} subtasks: work on one of those, or unlink one first.`,
|
||||
);
|
||||
}
|
||||
|
||||
const res = await BunSQLite.sql({
|
||||
sql: `UPDATE tasks SET parent_task_id = ?, updated_at = ? WHERE id = ?`,
|
||||
values: [Number(parent.id), Date.now(), Number(task.id)],
|
||||
});
|
||||
|
||||
if (!res.success) {
|
||||
throw new AppError(`Couldn't link the task: ${res.msg || res.error}`);
|
||||
}
|
||||
|
||||
const author = by_bot_id ? "bot" : "user";
|
||||
const parent_label = `task #${parent.id}${parent.title ? ` "${parent.title}"` : ""}`;
|
||||
|
||||
await addTaskNote({
|
||||
task_id: Number(task.id),
|
||||
text: `${by_name} made this a subtask of ${parent_label}.`,
|
||||
author,
|
||||
bot_id: by_bot_id ? Number(by_bot_id) : null,
|
||||
});
|
||||
|
||||
await addTaskNote({
|
||||
task_id: Number(parent.id),
|
||||
text: `${by_name} took on task #${task.id}${task.title ? ` "${task.title}"` : ""} as a subtask.`,
|
||||
author,
|
||||
bot_id: by_bot_id ? Number(by_bot_id) : null,
|
||||
});
|
||||
|
||||
return await grabTask({ user_id, task_id });
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import subtaskMoveProblem from "@/src/utils/task-subtasks/subtask-move-problem";
|
||||
import assertBotWorksThere from "./assert-bot-works-there";
|
||||
import findDuplicateTask from "./find-duplicate-task";
|
||||
import grabSubtaskCounts from "./grab-subtask-counts";
|
||||
import grabTaskRow from "./grab-task-scope";
|
||||
import taskScopeValues from "./task-scope-values";
|
||||
|
||||
@@ -20,13 +22,20 @@ type Params = {
|
||||
/**
|
||||
* Moves a task to another list or bot, with its notes and files. Refused
|
||||
* when it changes list and the destination already has an open task with
|
||||
* that title, so a hand-over never leaves two of the same. The caller checked who is
|
||||
* that title, so a hand-over never leaves two of the same, and when it's a
|
||||
* subtask of another task or has subtasks of its own (`subtaskMoveProblem`): only
|
||||
* a task that is neither moves. The caller checked who is
|
||||
* asking reaches both. Returns the row as it is now.
|
||||
*/
|
||||
export default async function moveTask({ task_id, bot_id, workspace_id, workspace_wide }: Params): Promise<BUN_SQLITE_COBBLE_TASKS> {
|
||||
const task = await grabTaskRow({ task_id });
|
||||
const place = taskScopeValues({ bot_id, workspace_id, workspace_wide });
|
||||
|
||||
const { linked } = await grabSubtaskCounts({ task_id: task.id! });
|
||||
const problem = subtaskMoveProblem({ task, linked_subtasks: linked });
|
||||
|
||||
if (problem) throw new AppError(problem);
|
||||
|
||||
if (Number(task.bot_id || 0) == Number(place.bot_id || 0) && Number(task.workspace_id || 0) == Number(place.workspace_id || 0)) {
|
||||
return task;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ type Args = {
|
||||
bot_id?: number;
|
||||
workspace_id?: number;
|
||||
workspace_wide?: boolean;
|
||||
parent_task_id?: number;
|
||||
status?: TaskStatus;
|
||||
};
|
||||
|
||||
@@ -147,8 +148,8 @@ export default function createTaskTool({
|
||||
return {
|
||||
name: "create_task",
|
||||
description: is_coordinator
|
||||
? `Add a task: to a worker's own list (bot_id: ${crew || "no workers yet"}), to a workspace (workspace_id: ${places || "no workspaces yet"}) for one of its bots (with bot_id; without, it's yours there) or workspace-wide (workspace_wide: true, no bot_id), or to your own list (leave both ids out${workspace_id ? "; here, leaving them out makes it yours in this workspace" : ""}). A task belongs to one bot unless it's workspace-wide: then every bot in that workspace sees it, works on it and logs what it did. Write the description as a brief: what to do, where, and how you'll know it's done.`
|
||||
: `Add a task: ${workspace_id ? `in this workspace, yours by default${team ? `, a member's as this workspace's admin (bot_id: ${team})` : ""}, or workspace-wide (workspace_wide: true) when it's work for the whole crew here: every bot in the workspace sees it, works on it and logs what it did` : `on your own list (bot_id ${bot_id}, the default)`}. Write the description as a brief: what to do, where, and how you'll know it's done.`,
|
||||
? `Add a task: to a worker's own list (bot_id: ${crew || "no workers yet"}), to a workspace (workspace_id: ${places || "no workspaces yet"}) for one of its bots (with bot_id; without, it's yours there) or workspace-wide (workspace_wide: true, no bot_id), or to your own list (leave both ids out${workspace_id ? "; here, leaving them out makes it yours in this workspace" : ""}). A task belongs to one bot unless it's workspace-wide: then every bot in that workspace sees it, works on it and logs what it did. When that workspace-wide task is too much for one bot, split it: add each piece with parent_task_id (the wide task's id), one bot per piece, and the parent stays open until you verify the parts. Write the description as a brief: what to do, where, and how you'll know it's done.`
|
||||
: `Add a task: ${workspace_id ? `in this workspace, yours by default${team ? `, a member's as this workspace's admin (bot_id: ${team})` : ""}, or workspace-wide (workspace_wide: true) when it's work for the whole crew here: every bot in the workspace sees it, works on it and logs what it did` : `on your own list (bot_id ${bot_id}, the default)`}. To take one piece of a workspace-wide task here, add it with parent_task_id (that task's id), one bot per piece: the parent stays open until its parts are verified. Write the description as a brief: what to do, where, and how you'll know it's done.`,
|
||||
schema: z.object({
|
||||
title: z.string().trim().min(1).max(AppData.TaskTitleMaxLength).describe(`A short label`),
|
||||
description: z
|
||||
@@ -175,13 +176,26 @@ export default function createTaskTool({
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(`In a workspace: nobody's, for every bot there to work on and log. Only when the work is the whole crew's; defaults to false.`),
|
||||
parent_task_id: z
|
||||
.number()
|
||||
.int()
|
||||
.optional()
|
||||
.describe(
|
||||
`The workspace-wide task this one is one piece of (its id, which list_tasks shows): a subtask, in that task's workspace, with a bot of its own. Use it instead of workspace_wide: a subtask belongs to one bot, and only a workspace-wide task can be split.`,
|
||||
),
|
||||
status: z.enum(TaskStatusValues).optional().describe(`Defaults to to do`),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
if (args.parent_task_id && args.workspace_wide) {
|
||||
return `A subtask belongs to one bot: leave workspace_wide out and pass parent_task_id with the bot it's for.`;
|
||||
}
|
||||
|
||||
const place = resolvePlace({ args, bot_id, workspace_id, is_coordinator, members });
|
||||
|
||||
if (typeof place == "string") return place;
|
||||
|
||||
const parent_task_id = args.parent_task_id ? Number(args.parent_task_id) : null;
|
||||
|
||||
const existing = await grabTasks({
|
||||
bot_id,
|
||||
is_coordinator,
|
||||
@@ -189,6 +203,7 @@ export default function createTaskTool({
|
||||
only_bot_id: place.workspace_id ? undefined : place.bot_id,
|
||||
only_workspace_id: place.workspace_id,
|
||||
own_list: !place.workspace_id,
|
||||
only_parent_task_id: parent_task_id || undefined,
|
||||
open_only: true,
|
||||
});
|
||||
|
||||
@@ -197,6 +212,7 @@ export default function createTaskTool({
|
||||
title: args.title,
|
||||
bot_id: place.bot_id,
|
||||
workspace_id: place.workspace_id || null,
|
||||
parent_task_id,
|
||||
});
|
||||
|
||||
if (twin) {
|
||||
@@ -210,6 +226,7 @@ export default function createTaskTool({
|
||||
bot_id: place.bot_id,
|
||||
workspace_id: place.workspace_id,
|
||||
workspace_wide: !place.bot_id,
|
||||
parent_task_id,
|
||||
title: args.title,
|
||||
description: args.description,
|
||||
status: args.status as never,
|
||||
@@ -224,7 +241,7 @@ export default function createTaskTool({
|
||||
? "to your list"
|
||||
: `to bot ${place.bot_id}'s list`;
|
||||
|
||||
return `Task #${task.id} "${task.title}" added ${where}. Check it with list_tasks before you mention it to the user.`;
|
||||
return `Task #${task.id} "${task.title}" added ${where}${parent_task_id ? `, as a subtask of task #${parent_task_id} (the parent stays open until someone verifies all the parts)` : ""}. Check it with list_tasks before you mention it to the user.`;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,4 +22,31 @@ describe("describeTaskLog", () => {
|
||||
test("leaves the files out when there are none", () => {
|
||||
expect(describeTaskLog({ task, notes: [], bot_id: 21 })).not.toContain("Files");
|
||||
});
|
||||
|
||||
test("a subtask says which task it belongs to and that the parent stays open", () => {
|
||||
const text = describeTaskLog({
|
||||
task: { ...task, parent_task_id: 12, parent_title: "Ship the release" },
|
||||
notes: [],
|
||||
bot_id: 21,
|
||||
});
|
||||
|
||||
expect(text).toContain('A subtask of task #12 "Ship the release"');
|
||||
expect(text).toContain("don't mark it done from here");
|
||||
});
|
||||
|
||||
test("a split task lists its subtasks with their owners and which are open", () => {
|
||||
const text = describeTaskLog({
|
||||
task: { ...task, bot_id: "", workspace_id: 3 },
|
||||
notes: [],
|
||||
bot_id: 21,
|
||||
parts: [
|
||||
{ id: 31, status: "doing", title: "The intro", bot_id: 21, bot_name: "Software Engineer" },
|
||||
{ id: 32, status: "done", title: "The appendix", bot_id: 22, bot_name: "SEO Expert" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(text).toContain("Subtasks (2):");
|
||||
expect(text).toContain("- #31 [doing] (open) The intro, Software Engineer (yours)");
|
||||
expect(text).toContain("- #32 [done] The appendix, SEO Expert");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,28 @@
|
||||
import type { BUN_SQLITE_COBBLE_TASKS } from "@/db/types/db";
|
||||
import type { TaskFile, TaskNote } from "@/src/types";
|
||||
import type { TaskFile, TaskNote, TaskWithNames } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
task: BUN_SQLITE_COBBLE_TASKS;
|
||||
/**
|
||||
* The task row, with `parent_title` when it is a subtask (`grab-tasks`).
|
||||
*/
|
||||
task: BUN_SQLITE_COBBLE_TASKS & {
|
||||
/**
|
||||
* Its parent's title, read for a subtask (`grab-tasks`' join, or the
|
||||
* caller's lookup).
|
||||
*/
|
||||
parent_title?: string | null;
|
||||
};
|
||||
notes: TaskNote[];
|
||||
/**
|
||||
* What's filed on it (`grabTaskMedia`), so a bot can name, check and
|
||||
* unlink them.
|
||||
*/
|
||||
files?: TaskFile[];
|
||||
/**
|
||||
* Its subtasks, when it is workspace-wide: each with its status and
|
||||
* whose it is, so a bot sees what is already split off.
|
||||
*/
|
||||
parts?: TaskWithNames[];
|
||||
/**
|
||||
* The run's own bot, named "you" in the log.
|
||||
*/
|
||||
@@ -21,7 +35,7 @@ type Params = {
|
||||
* on a workspace-wide task sees what the others already did, and its files
|
||||
* (a bot file by its `[file:ID]` ref, a user's upload by name).
|
||||
*/
|
||||
export default function describeTaskLog({ task, notes, files = [], bot_id }: Params) {
|
||||
export default function describeTaskLog({ task, notes, files = [], parts = [], bot_id }: Params) {
|
||||
const who = task.bot_id
|
||||
? task.bot_id == Number(bot_id)
|
||||
? "yours"
|
||||
@@ -53,10 +67,25 @@ export default function describeTaskLog({ task, notes, files = [], bot_id }: Par
|
||||
.join("\n")
|
||||
: "";
|
||||
|
||||
const split = parts.length
|
||||
? parts
|
||||
.map((subtask) => {
|
||||
const owner = subtask.bot_id ? subtask.bot_name || `bot ${subtask.bot_id}` : "nobody";
|
||||
const open = subtask.status == "done" || subtask.status == "cancelled" ? "" : " (open)";
|
||||
|
||||
return `- #${subtask.id} [${subtask.status}]${open} ${subtask.title}, ${owner}${Number(subtask.bot_id || 0) == Number(bot_id) ? " (yours)" : ""}`;
|
||||
})
|
||||
.join("\n")
|
||||
: "";
|
||||
|
||||
return [
|
||||
`#${task.id} [${task.status}] ${task.title} (${task.workspace_id ? `in workspace ${task.workspace_id}, ` : ""}${who})`,
|
||||
task.parent_task_id
|
||||
? `A subtask of task #${task.parent_task_id}${task.parent_title ? ` "${task.parent_title}"` : ""}: one piece of that work. The parent stays open until someone verifies all its subtasks, so don't mark it done from here.`
|
||||
: "",
|
||||
task.status == "blocked" && task.blocked_reason ? `Blocked: ${task.blocked_reason}` : "",
|
||||
`Brief:\n${task.description?.trim() || "(none)"}`,
|
||||
split ? `Subtasks (${parts.length}):\n${split}` : "",
|
||||
filed ? `Files (${files.length}):\n${filed}` : "",
|
||||
`Log, oldest first:\n${log}`,
|
||||
]
|
||||
|
||||
@@ -7,6 +7,7 @@ import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
|
||||
import grabTaskNotes from "@/src/functions/backend/db/tasks/grab-task-notes";
|
||||
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
|
||||
import grabTaskMedia from "@/src/functions/backend/db/tasks/grab-task-media";
|
||||
import grabTaskRow from "@/src/functions/backend/db/tasks/grab-task-scope";
|
||||
import describeTaskLog from "./describe-task-log";
|
||||
import type { HarnessTool } from "../../../types";
|
||||
|
||||
@@ -69,10 +70,19 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
|
||||
|
||||
onTask?.({ task_id: Number(task.id) });
|
||||
|
||||
const [notes, files, parts] = await Promise.all([
|
||||
grabTaskNotes({ task_id: task.id! }),
|
||||
grabTaskMedia({ task_id: task.id! }),
|
||||
grabTasks({ bot_id, is_coordinator, admin_workspace_ids, only_parent_task_id: task.id! }),
|
||||
]);
|
||||
|
||||
const parent = task.parent_task_id ? await grabTaskRow({ task_id: task.parent_task_id }) : null;
|
||||
|
||||
return describeTaskLog({
|
||||
task,
|
||||
notes: await grabTaskNotes({ task_id: task.id! }),
|
||||
files: await grabTaskMedia({ task_id: task.id! }),
|
||||
task: parent ? { ...task, parent_title: parent.title } : task,
|
||||
notes,
|
||||
files,
|
||||
parts,
|
||||
bot_id,
|
||||
});
|
||||
}
|
||||
@@ -113,6 +123,11 @@ export default function listTasksTool({ bot_id, user_id, is_coordinator, admin_w
|
||||
`[${task.status}]`,
|
||||
task.title,
|
||||
`(${where})`,
|
||||
Number(task.subtask_count || 0)
|
||||
? `a subtask of #${task.parent_task_id}`
|
||||
: task.workspace_id && !task.bot_id && Number(task.subtask_open_count || 0)
|
||||
? `split into ${task.subtask_count} subtasks, ${task.subtask_open_count} still open`
|
||||
: "",
|
||||
Number(task.media_count || 0) ? `${task.media_count} file(s)` : "",
|
||||
task.status == "blocked" && task.blocked_reason ? `blocked: ${task.blocked_reason}` : "",
|
||||
task.latest_note
|
||||
|
||||
@@ -28,6 +28,13 @@ describe("updateTaskTool", () => {
|
||||
expect(tool.description).toContain(`holds ${AppData.TaskMediaMaxPerTask} files`);
|
||||
});
|
||||
|
||||
test("takes a parent to become a subtask of, and says so", () => {
|
||||
expect(tool.schema?.safeParse({ task_id: 20, parent_task_id: 16 }).success).toBe(true);
|
||||
expect(tool.schema?.safeParse({ task_id: 20, parent_task_id: 0 }).success).toBe(false);
|
||||
expect(tool.description).toContain("parent_task_id");
|
||||
expect(tool.description).toContain("unlink_parent");
|
||||
});
|
||||
|
||||
test("tells the bot to rename rather than add a second task", () => {
|
||||
expect(tool.description).toContain("Rename it with title");
|
||||
expect(tool.description).toContain("never create a second task");
|
||||
|
||||
@@ -3,10 +3,12 @@ import { AppData } from "@/src/data/app-data";
|
||||
import { type TaskStatus, TaskStatusValues } from "@/src/dict/task-dict";
|
||||
import addTaskNote from "@/src/functions/backend/db/tasks/add-task-note";
|
||||
import attachTaskFile from "@/src/functions/backend/db/tasks/attach-task-file";
|
||||
import detachSubtask from "@/src/functions/backend/db/tasks/detach-subtask";
|
||||
import detachTaskFile from "@/src/functions/backend/db/tasks/detach-task-file";
|
||||
import findDuplicateTask from "@/src/functions/backend/db/tasks/find-duplicate-task";
|
||||
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
|
||||
import grabRunTask from "@/src/functions/backend/db/tasks/grab-run-task";
|
||||
import linkSubtask from "@/src/functions/backend/db/tasks/link-subtask";
|
||||
import grabTaskMedia from "@/src/functions/backend/db/tasks/grab-task-media";
|
||||
import makeTaskWorkspaceWide from "@/src/functions/backend/db/tasks/make-task-workspace-wide";
|
||||
import grabBotById from "@/src/functions/backend/db/bots/grab-bot-by-id";
|
||||
@@ -44,6 +46,8 @@ type Args = {
|
||||
reference_file_ids?: number[];
|
||||
unlink_file_ids?: number[];
|
||||
workspace_wide?: boolean;
|
||||
parent_task_id?: number;
|
||||
unlink_parent?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -65,7 +69,7 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
|
||||
|
||||
return {
|
||||
name: "update_task",
|
||||
description: `Move a task along. Rename it with title or rewrite its brief with description (never create a second task for the same work just to fix its name). Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number. A task holds ${AppData.TaskMediaMaxPerTask} files: to make room, or to drop a superseded version, unlink files with unlink_file_ids (list_tasks with task_id shows what's filed; the file stays in its folder). Unlink first, then file, in the same call.${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
|
||||
description: `Move a task along. Rename it with title or rewrite its brief with description (never create a second task for the same work just to fix its name). Set its status (blocked needs a reason: what the user has to do), log a note of what you did or found, and file the files it produced. Call it as the work advances, not only at the end; every note is what the user sees on the task. A workspace-wide task is shared by every bot in its workspace: log a note for each part you do (it's recorded under your name and id, with the time) so the others see who did what, and don't mark it done while parts others are on are still open. Mark done only once you've verified the work (see the check note): starting a task isn't finishing it. To file a deliverable, save it first with write_file, make_pdf or generate_image, then pass its [file:ID] number. A task holds ${AppData.TaskMediaMaxPerTask} files: to make room, or to drop a superseded version, unlink files with unlink_file_ids (list_tasks with task_id shows what's filed; the file stays in its folder). Unlink first, then file, in the same call. A part of a workspace-wide task (its row says so) is one piece of that work: log your notes on it like any task, and unlink_parent: true takes it out of the parent if it stops being part of it. parent_task_id: N makes a task of your own the part you took on of the workspace-wide task #N in its workspace (one piece each, and the parent stays open until someone verifies them all).${can_share ? ` As ${is_coordinator ? "the coordinator" : "a workspace's admin"}, workspace_wide: true turns a bot's open task in ${is_coordinator ? "a" : "your"} workspace into a workspace-wide one every bot there works on (hand it to one bot again with delegate_task).` : ""}`,
|
||||
schema: z.object({
|
||||
task_id: z.number().int(),
|
||||
title: z
|
||||
@@ -111,6 +115,20 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
|
||||
? `true to make a bot's open task in ${is_coordinator ? "a" : "a workspace you're admin of"} workspace workspace-wide: nobody's, for every bot there to work on and log. Only true does anything.`
|
||||
: `Only the coordinator or a workspace's admin bot can use this; leave it out.`,
|
||||
),
|
||||
parent_task_id: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe(
|
||||
`N attaches this task to the open workspace-wide task #N in its workspace: the piece of it you took on. Only tasks a bot has in a workspace can join one, and a task with subtasks of its own can't.`,
|
||||
),
|
||||
unlink_parent: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
`For a subtask of a workspace-wide task: true takes it out of that task, leaving it a task of its own in the workspace. Only true does anything.`,
|
||||
),
|
||||
}),
|
||||
run: async ({ args }) => {
|
||||
const task = await grabRunTask({ task_id: args.task_id, bot_id, is_coordinator, admin_workspace_ids });
|
||||
@@ -136,6 +154,40 @@ export default function updateTaskTool({ user_id, bot_id, is_coordinator, admin_
|
||||
said.push(`it's workspace-wide now, every bot in workspace ${task.workspace_id} works on it`);
|
||||
}
|
||||
|
||||
if (args.parent_task_id) {
|
||||
if (args.unlink_parent) {
|
||||
return `Pass parent_task_id to make it a subtask of a task, or unlink_parent to take it out of one, not both.`;
|
||||
}
|
||||
|
||||
try {
|
||||
await linkSubtask({
|
||||
user_id,
|
||||
task_id: task.id!,
|
||||
parent_task_id: args.parent_task_id,
|
||||
by_bot_id: bot_id,
|
||||
by_name: (await grabBotById({ bot_id }))?.name || `Bot ${bot_id}`,
|
||||
});
|
||||
said.push(`it's a subtask of task #${args.parent_task_id} now`);
|
||||
} catch (error: unknown) {
|
||||
return error instanceof Error
|
||||
? error.message
|
||||
: `Couldn't make task #${task.id} a subtask of task #${args.parent_task_id}.`;
|
||||
}
|
||||
}
|
||||
|
||||
if (args.unlink_parent) {
|
||||
if (!task.parent_task_id) {
|
||||
return `Task #${task.id} isn't a subtask of another task: nothing to unlink it from.`;
|
||||
}
|
||||
|
||||
await detachSubtask({
|
||||
task_id: task.id!,
|
||||
by_bot_id: bot_id,
|
||||
by_name: (await grabBotById({ bot_id }))?.name || `Bot ${bot_id}`,
|
||||
});
|
||||
said.push(`it's a task of its own now, out of task #${task.parent_task_id}`);
|
||||
}
|
||||
|
||||
const title = args.title?.trim();
|
||||
const renamed = Boolean(title) && title != (task.title || "").trim();
|
||||
const rewritten = args.description != undefined && args.description != (task.description || "");
|
||||
|
||||
@@ -3,6 +3,7 @@ import Modal from "@moduletrace/twui/elements/Modal";
|
||||
import H2 from "@moduletrace/twui/layout/H2";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import TopModalEscape from "@/src/components/general/top-modal-escape";
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
@@ -23,6 +24,7 @@ export default function AddModalShell({ open, setOpen, title, description, child
|
||||
setOpen={(next) => setOpen(typeof next == "function" ? next(open) : next)}
|
||||
className="max-w-lg bg-paper p-6"
|
||||
>
|
||||
{open ? <TopModalEscape onClose={() => setOpen(false)} /> : null}
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">{title}</H2>
|
||||
{description ? (
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import WorkspaceTaskSection from "./workspace-task-section";
|
||||
|
||||
const wide: TaskWithNames = {
|
||||
id: 12,
|
||||
created_at: 1,
|
||||
updated_at: 2,
|
||||
workspace_id: 7,
|
||||
title: "Ship the release",
|
||||
status: "doing",
|
||||
};
|
||||
|
||||
const intro: TaskWithNames = {
|
||||
id: 30,
|
||||
created_at: 1,
|
||||
updated_at: 2,
|
||||
bot_id: 3,
|
||||
bot_name: "A",
|
||||
title: "The intro",
|
||||
status: "done",
|
||||
};
|
||||
|
||||
const tasks: TaskWithNames[] = [wide, intro];
|
||||
|
||||
describe("WorkspaceTaskSection", () => {
|
||||
test("its heading, its task count and how many are still open", () => {
|
||||
const html = renderToString(<WorkspaceTaskSection section={{ key: "wide", title: "Workspace-wide", tasks }} onOpenTask={() => {}} />);
|
||||
|
||||
expect(html).toContain("Workspace-wide");
|
||||
expect(html).toContain("2 tasks, 1 open");
|
||||
});
|
||||
|
||||
test("one task reads in the singular", () => {
|
||||
const html = renderToString(
|
||||
<WorkspaceTaskSection section={{ key: "bot:3", title: "Software Engineer", tasks: [intro] }} onOpenTask={() => {}} />,
|
||||
);
|
||||
|
||||
expect(html).toContain("Software Engineer");
|
||||
expect(html).toContain("1 task");
|
||||
expect(html).not.toContain("1 tasks");
|
||||
});
|
||||
|
||||
test("a section with nothing open says only how many it holds", () => {
|
||||
const html = renderToString(
|
||||
<WorkspaceTaskSection section={{ key: "bot:3", title: "Software Engineer", tasks: [intro] }} onOpenTask={() => {}} />,
|
||||
);
|
||||
|
||||
expect(html).not.toContain(" open");
|
||||
});
|
||||
|
||||
test("each task is a row of its own, its title and id in it", () => {
|
||||
const html = renderToString(<WorkspaceTaskSection section={{ key: "wide", title: "Workspace-wide", tasks }} onOpenTask={() => {}} />);
|
||||
|
||||
expect(html).toContain("Ship the release");
|
||||
expect(html).toContain("#12");
|
||||
expect(html).toContain("The intro");
|
||||
expect(html).toContain("#30");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import TaskListItem from "@/src/components/general/task-list-item";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import type { WorkspaceTaskSection as Section } from "@/src/utils/task-sections/workspace-task-sections";
|
||||
|
||||
type Props = {
|
||||
section: Section;
|
||||
onOpenTask: (task: TaskWithNames) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* One heading and its tasks in the all-tasks modal: the workspace-wide ones
|
||||
* under "Workspace-wide", then one section per bot (`workspaceTaskSections`
|
||||
* decides which and in what order). The heading says how many are open, so a
|
||||
* bot's list reads at a glance.
|
||||
*/
|
||||
export default function WorkspaceTaskSection({ section, onOpenTask }: Props) {
|
||||
const open = section.tasks.filter((task) => task.status != "done" && task.status != "cancelled").length;
|
||||
|
||||
return (
|
||||
<Stack className="w-full gap-1! items-stretch">
|
||||
<Row className="w-full items-baseline justify-between gap-2!">
|
||||
<Span className="text-[12px] font-bold leading-4 text-ink">{section.title}</Span>
|
||||
<Span className="shrink-0 text-[12px] leading-4 text-ink-secondary">
|
||||
{`${section.tasks.length} task${section.tasks.length == 1 ? "" : "s"}${open ? `, ${open} open` : ""}`}
|
||||
</Span>
|
||||
</Row>
|
||||
<Stack className="w-full gap-0! items-stretch">
|
||||
{section.tasks.map((task) => (
|
||||
<TaskListItem key={task.id} task={task} onOpen={() => onOpenTask(task)} />
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import Button from "@moduletrace/twui/layout/Button";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { OpenTaskStatuses } from "@/src/dict/task-dict";
|
||||
import type { TaskDetail, TaskWithNames } from "@/src/types";
|
||||
import TaskDetailModal from "@/src/components/general/task-detail-modal";
|
||||
import TaskForm from "@/src/components/general/task-form";
|
||||
@@ -15,6 +16,9 @@ import SettingsList from "@/src/pages/admin/settings/(partials)/settings-list";
|
||||
import SettingsStatus from "@/src/pages/admin/settings/(partials)/settings-status";
|
||||
import { AppContext } from "@/src/pages/__root";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import compareTasks from "@/src/utils/task-sections/compare-tasks";
|
||||
import shownWorkspaceTasks from "@/src/utils/task-sections/shown-workspace-tasks";
|
||||
import WorkspaceTasksModal from "@/src/pages/admin/workspaces/[workspace_id]/(partials)/workspace-tasks-modal";
|
||||
|
||||
type Props = {
|
||||
workspace_id: number;
|
||||
@@ -31,7 +35,9 @@ type Props = {
|
||||
/**
|
||||
* Every task in a workspace, whichever bot has it: a task belongs to one
|
||||
* bot, which sees only its own, unless it's workspace-wide (every bot there
|
||||
* sees it; the workspace's admin bot sees all).
|
||||
* sees it; the workspace's admin bot sees all). The list starts with the
|
||||
* workspace-wide ones, then each bot's, and shows only the first few: the
|
||||
* rest are a click away in View all.
|
||||
* Add and change one by hand here; the bots
|
||||
* keep it up to date themselves as they work.
|
||||
*/
|
||||
@@ -41,11 +47,45 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [status, setStatus] = useState<{ error?: boolean; success?: boolean; msg: string }>();
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [showing_all, setShowingAll] = useState(false);
|
||||
const [open_task, setOpenTask] = useState<TaskWithNames | null>(null);
|
||||
const can_manage = canManageCrew({ user_types: pageProps?.user_types });
|
||||
|
||||
/**
|
||||
* What the page lists: the order the all-tasks modal uses, cut to
|
||||
* `AppData.TaskSectionShown` rows.
|
||||
*/
|
||||
const shown = shownWorkspaceTasks({ tasks: items });
|
||||
|
||||
/**
|
||||
* The workspace-wide tasks here a new task can be a subtask of: the open
|
||||
* ones, a closed task having nothing left to split.
|
||||
*/
|
||||
const parents = items
|
||||
.filter(
|
||||
(task) =>
|
||||
!task.bot_id &&
|
||||
Boolean(task.workspace_id) &&
|
||||
(OpenTaskStatuses as readonly string[]).includes(task.status || ""),
|
||||
)
|
||||
.map((task) => ({ id: task.id, title: task.title }));
|
||||
|
||||
const replace = ({ task }: { task: TaskWithNames }) =>
|
||||
setItems((prev) => [task, ...prev.filter((item) => item.id != task.id)].sort(order));
|
||||
setItems((prev) => [task, ...prev.filter((item) => item.id != task.id)].sort(compareTasks));
|
||||
|
||||
/**
|
||||
* Reads the workspace's tasks again: one change can move more than the
|
||||
* task that was open, since a subtask joining or leaving reshapes its
|
||||
* parent's counts.
|
||||
*/
|
||||
const refresh = async () => {
|
||||
const res = await fetchApi<Record<string, unknown>, APIResponseObject<TaskWithNames>>(
|
||||
`/api/admin/tasks/list-tasks?workspace_id=${workspace_id}`,
|
||||
{ method: "GET" },
|
||||
);
|
||||
|
||||
if (res.success && res.payload) setItems(res.payload);
|
||||
};
|
||||
|
||||
const move = async ({ task, next }: { task: TaskWithNames; next: string }) => {
|
||||
if (busy) return;
|
||||
@@ -113,7 +153,7 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
</Row>
|
||||
) : null}
|
||||
<SettingsList is_empty={!items.length} empty="No tasks in this workspace yet.">
|
||||
{items.map((task) => (
|
||||
{shown.map((task) => (
|
||||
<TaskListItem
|
||||
key={task.id}
|
||||
task={task}
|
||||
@@ -124,8 +164,29 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
/>
|
||||
))}
|
||||
</SettingsList>
|
||||
{items.length > shown.length ? (
|
||||
<Row className="justify-end">
|
||||
<Button
|
||||
title="Every task in this workspace, the workspace-wide ones first"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="gray"
|
||||
size="small"
|
||||
onClick={() => setShowingAll(true)}
|
||||
className="px-2! text-[12px]"
|
||||
>
|
||||
View all {items.length} tasks
|
||||
</Button>
|
||||
</Row>
|
||||
) : null}
|
||||
<SettingsStatus status={status} />
|
||||
</Stack>
|
||||
<WorkspaceTasksModal
|
||||
open={showing_all}
|
||||
setOpen={setShowingAll}
|
||||
tasks={items}
|
||||
onOpenTask={(task) => setOpenTask(task)}
|
||||
/>
|
||||
<TaskDetailModal
|
||||
task={open_task}
|
||||
can_manage={can_manage}
|
||||
@@ -133,6 +194,7 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
onChanged={({ task, msg }) => {
|
||||
replace({ task });
|
||||
setStatus(msg ? { success: true, msg } : undefined);
|
||||
refresh().catch(() => {});
|
||||
}}
|
||||
onDeleted={({ task_id }) => {
|
||||
setItems((prev) => prev.filter((item) => item.id != task_id));
|
||||
@@ -144,11 +206,12 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
open={adding}
|
||||
setOpen={setAdding}
|
||||
title="Add a task"
|
||||
description="Pick the bot that has it, or make it workspace-wide: every bot here sees it, works on it and logs what it did. Hand it over later to give it to one bot."
|
||||
description="Pick the bot that has it, or make it workspace-wide: every bot here sees it, works on it and logs what it did. Hand it over later to give it to one bot. To split a workspace-wide task into pieces, add each piece with 'Part of' set to it: one bot per piece, and the parent stays open until you verify them."
|
||||
>
|
||||
<TaskForm
|
||||
workspace_id={workspace_id}
|
||||
bots={bots}
|
||||
parents={parents}
|
||||
onCancel={() => setAdding(false)}
|
||||
onSaved={(task, msg) => {
|
||||
replace({ task });
|
||||
@@ -160,15 +223,3 @@ export default function WorkspaceTasksGroup({ workspace_id, tasks, bots }: Props
|
||||
</SettingsGroup>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocked, then doing, then to do, then finished: the order a list reads
|
||||
* in.
|
||||
*/
|
||||
function order(a: TaskWithNames, b: TaskWithNames) {
|
||||
const rank = (task: TaskWithNames) =>
|
||||
task.status == "blocked" ? 0 : task.status == "doing" ? 1 : task.status == "todo" ? 2 : 3;
|
||||
const diff = rank(a) - rank(b);
|
||||
|
||||
return diff != 0 ? diff : Number(b.updated_at || b.id || 0) - Number(a.updated_at || a.id || 0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import workspaceTaskSections from "@/src/utils/task-sections/workspace-task-sections";
|
||||
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
|
||||
import WorkspaceTaskSection from "@/src/pages/admin/workspaces/[workspace_id]/(partials)/workspace-task-section";
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
/**
|
||||
* Every task in the workspace, not only the ones the page lists.
|
||||
*/
|
||||
tasks: TaskWithNames[];
|
||||
onOpenTask: (task: TaskWithNames) => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Every task in a workspace, sectioned the way the page's own list is but
|
||||
* without its cap: the workspace-wide ones first, then one section per bot.
|
||||
* A row opens the task's own modal over this one, which stays behind it.
|
||||
*/
|
||||
export default function WorkspaceTasksModal({ open, setOpen, tasks, onOpenTask }: Props) {
|
||||
const sections = workspaceTaskSections({ tasks });
|
||||
|
||||
return (
|
||||
<AddModalShell
|
||||
open={open}
|
||||
setOpen={setOpen}
|
||||
title="All tasks"
|
||||
description="Everything in this workspace: the workspace-wide tasks first (every bot here works on those), then each bot's own list. Open tasks come before finished ones."
|
||||
>
|
||||
<Stack className="max-h-[60vh] w-full gap-4! items-stretch overflow-y-auto">
|
||||
{sections.map((section) => (
|
||||
<WorkspaceTaskSection key={section.key} section={section} onOpenTask={onOpenTask} />
|
||||
))}
|
||||
</Stack>
|
||||
</AddModalShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
|
||||
import detachSubtask from "@/src/functions/backend/db/tasks/detach-subtask";
|
||||
import grabTask from "@/src/functions/backend/db/tasks/grab-task";
|
||||
import { DetachSubtaskRequestSchema } from "@/src/schemas/task-schema";
|
||||
import type { TaskDetail } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* Takes a subtask out of its workspace-wide task, leaving a task of its own
|
||||
* bot in the workspace (`detachSubtask`): the only way a parent with subtasks
|
||||
* is ever moved, and the button a crew manager has for it. Crew managers
|
||||
* only, like every other change to a task by hand. Returns the task as it
|
||||
* is now.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (isReadOnlyUser({ user_types: user_types || [] })) {
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
if (!canManageCrew({ user_types: user_types || [] })) {
|
||||
throw new AppError(`Only an admin can unlink a subtask from its task.`);
|
||||
}
|
||||
|
||||
const { task_id } = parseWithSchema({ schema: DetachSubtaskRequestSchema, data: body });
|
||||
|
||||
await assertUserReachesTask({ user_id: user.id, task_id });
|
||||
await detachSubtask({ task_id, by_name: user.first_name || user.username || "The user" });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: await grabTask({ user_id: user.id, task_id }),
|
||||
msg: `It's a task of its own now.`,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
|
||||
import linkSubtask from "@/src/functions/backend/db/tasks/link-subtask";
|
||||
import { LinkSubtaskRequestSchema } from "@/src/schemas/task-schema";
|
||||
import type { TaskDetail } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* Attaches a bot's open task in a workspace to a workspace-wide task there,
|
||||
* so the manager of the work sees who took which piece (`linkSubtask`): what
|
||||
* a bot does with `update_task`'s `parent_task_id`, and what a crew manager
|
||||
* has a picker for. Both ends are reached-checked, since the id alone would
|
||||
* let someone join another crew's task. Returns the task as it is now.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (isReadOnlyUser({ user_types: user_types || [] })) {
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
if (!canManageCrew({ user_types: user_types || [] })) {
|
||||
throw new AppError(`Only an admin can make a task a subtask of another.`);
|
||||
}
|
||||
|
||||
const { task_id, parent_task_id } = parseWithSchema({ schema: LinkSubtaskRequestSchema, data: body });
|
||||
|
||||
await assertUserReachesTask({ user_id: user.id, task_id });
|
||||
await assertUserReachesTask({ user_id: user.id, task_id: parent_task_id });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: await linkSubtask({
|
||||
user_id: user.id,
|
||||
task_id,
|
||||
parent_task_id,
|
||||
by_name: user.first_name || user.username || "The user",
|
||||
}),
|
||||
msg: `It's a subtask of task #${parent_task_id} now.`,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -55,11 +55,19 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = asy
|
||||
};
|
||||
}
|
||||
|
||||
const { bot_id, workspace_id, workspace_wide, title, description, status } = parseWithSchema({
|
||||
const { bot_id, workspace_id, workspace_wide, parent_task_id, title, description, status } = parseWithSchema({
|
||||
schema: CreateTaskRequestSchema,
|
||||
data,
|
||||
});
|
||||
|
||||
/**
|
||||
* A subtask hangs off a task the user has to reach too, or they could
|
||||
* split another crew's task by id.
|
||||
*/
|
||||
if (parent_task_id) {
|
||||
await assertUserReachesTask({ user_id: user.id, task_id: parent_task_id });
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
singleRes: await createTask({
|
||||
@@ -67,11 +75,12 @@ export const handler: BunextAPIRouteHandler<APIResponseObject<TaskDetail>> = asy
|
||||
bot_id,
|
||||
workspace_id,
|
||||
workspace_wide,
|
||||
parent_task_id,
|
||||
title,
|
||||
description,
|
||||
status: status as never,
|
||||
}),
|
||||
msg: `Task added.`,
|
||||
msg: parent_task_id ? `Subtask added.` : `Task added.`,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import assertUserReachesTask from "@/src/functions/backend/db/tasks/assert-user-reaches-task";
|
||||
import grabSubtaskParents from "@/src/functions/backend/db/tasks/grab-subtask-parents";
|
||||
import { TaskIdRequestSchema } from "@/src/schemas/task-schema";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
|
||||
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
* What a bot's task can be made a subtask of: its workspace's open
|
||||
* workspace-wide tasks (`grabSubtaskParents`), loaded when the picker opens
|
||||
* so the page's props stay small. Crew managers only, since it's their
|
||||
* picker.
|
||||
*/
|
||||
export const handler: BunextAPIRouteHandler<APIResponseObject<TaskWithNames>> = async ({ req, body }) => {
|
||||
try {
|
||||
if (req.method != "POST") {
|
||||
throw new AppError(`Method not allowed`);
|
||||
}
|
||||
|
||||
const { user, user_types } = await userAuth({ req });
|
||||
|
||||
if (!user?.logged_in_status || !user.id) {
|
||||
return { success: false, msg: `Unauthorized`, logoutUser: true };
|
||||
}
|
||||
|
||||
if (isReadOnlyUser({ user_types: user_types || [] })) {
|
||||
throw new AppError(`This user can only read records.`);
|
||||
}
|
||||
|
||||
if (!canManageCrew({ user_types: user_types || [] })) {
|
||||
throw new AppError(`Only an admin can make a task a subtask of another.`);
|
||||
}
|
||||
|
||||
const { task_id } = parseWithSchema({ schema: TaskIdRequestSchema, data: body });
|
||||
const task = await assertUserReachesTask({ user_id: user.id, task_id });
|
||||
|
||||
return { success: true, payload: await grabSubtaskParents({ user_id: user.id, task }) };
|
||||
} catch (error: unknown) {
|
||||
return { success: false, msg: safeErrorMessage({ error }) };
|
||||
}
|
||||
};
|
||||
@@ -19,6 +19,11 @@ const scope = {
|
||||
|
||||
export const CreateTaskRequestSchema = z.object({
|
||||
...scope,
|
||||
/**
|
||||
* The workspace-wide task it is a part of (`assertSubtaskParent`), when
|
||||
* it is one.
|
||||
*/
|
||||
parent_task_id: z.number().int().positive().optional(),
|
||||
title: z.string().trim().min(1).max(AppData.TaskTitleMaxLength),
|
||||
description: z.string().max(AppData.TaskDescriptionMaxLength).optional(),
|
||||
status: z.enum(status_values).optional(),
|
||||
@@ -36,6 +41,21 @@ export const DeleteTaskRequestSchema = z.object({
|
||||
task_id: z.number().int().positive(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Taking a part out of its workspace-wide task (`detachSubtask`).
|
||||
*/
|
||||
export const DetachSubtaskRequestSchema = z.object({
|
||||
task_id: z.number().int().positive(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Attaching a bot's task to a workspace-wide one (`linkSubtask`).
|
||||
*/
|
||||
export const LinkSubtaskRequestSchema = z.object({
|
||||
task_id: z.number().int().positive(),
|
||||
parent_task_id: z.number().int().positive(),
|
||||
});
|
||||
|
||||
export const TaskNoteRequestSchema = z.object({
|
||||
task_id: z.number().int().positive(),
|
||||
text: z.string().trim().min(1).max(AppData.TaskNoteMaxLength),
|
||||
|
||||
+19
-2
@@ -209,6 +209,11 @@ export type TaskWithNames = BUN_SQLITE_COBBLE_TASKS & {
|
||||
bot_face?: string | null;
|
||||
bot_image_media_id?: number | null;
|
||||
workspace_name?: string | null;
|
||||
/**
|
||||
* The workspace's picture, for a workspace-wide task's mark: it is
|
||||
* nobody's, so it wears the workspace's face rather than a bot's.
|
||||
*/
|
||||
workspace_image_media_id?: number | null;
|
||||
/**
|
||||
* Its newest note's text, for the row's second line.
|
||||
*/
|
||||
@@ -221,6 +226,17 @@ export type TaskWithNames = BUN_SQLITE_COBBLE_TASKS & {
|
||||
* How many files it carries.
|
||||
*/
|
||||
media_count?: number | null;
|
||||
/**
|
||||
* The workspace-wide task it is a part of, when it is one.
|
||||
*/
|
||||
parent_title?: string | null;
|
||||
parent_status?: string | null;
|
||||
/**
|
||||
* Its parts, when it is workspace-wide: how many and how many still
|
||||
* need work.
|
||||
*/
|
||||
subtask_count?: number | null;
|
||||
subtask_open_count?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -253,14 +269,15 @@ export type TaskNote = BUN_SQLITE_COBBLE_TASK_NOTES & {
|
||||
};
|
||||
|
||||
/**
|
||||
* A task with its notes and files and who added it: what the task modal
|
||||
* renders.
|
||||
* A task with its notes and files and who added it, and its parts when it
|
||||
* is workspace-wide: what the task modal renders.
|
||||
*/
|
||||
export type TaskDetail = TaskWithNames & {
|
||||
created_by_bot_name?: string | null;
|
||||
created_by_user_name?: string | null;
|
||||
notes: TaskNote[];
|
||||
files: TaskFile[];
|
||||
subtasks: TaskWithNames[];
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
|
||||
/**
|
||||
* Blocked, then doing, then to do, then finished, each newest first: the
|
||||
* order a task list reads in.
|
||||
*/
|
||||
export default function compareTasks(a: TaskWithNames, b: TaskWithNames) {
|
||||
const rank = (task: TaskWithNames) =>
|
||||
task.status == "blocked" ? 0 : task.status == "doing" ? 1 : task.status == "todo" ? 2 : 3;
|
||||
const diff = rank(a) - rank(b);
|
||||
|
||||
return diff != 0 ? diff : Number(b.updated_at || b.id || 0) - Number(a.updated_at || a.id || 0);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import shownWorkspaceTasks from "./shown-workspace-tasks";
|
||||
|
||||
function task(fields: Partial<TaskWithNames>): TaskWithNames {
|
||||
return { id: 1, created_at: 1, updated_at: 2, status: "todo", ...fields };
|
||||
}
|
||||
|
||||
describe("shownWorkspaceTasks", () => {
|
||||
test("keeps the workspace-wide tasks before any bot's, then cuts to the cap", () => {
|
||||
const tasks = [
|
||||
task({ id: 1, bot_id: 3, bot_name: "A", title: "bot 1" }),
|
||||
task({ id: 2, workspace_id: 7, title: "wide 1" }),
|
||||
task({ id: 3, bot_id: 4, bot_name: "B", title: "bot 2" }),
|
||||
task({ id: 4, workspace_id: 7, title: "wide 2" }),
|
||||
];
|
||||
|
||||
expect(shownWorkspaceTasks({ tasks, shown: 3 }).map((it) => it.id)).toEqual([2, 4, 1]);
|
||||
});
|
||||
|
||||
test("a list shorter than the cap is left whole", () => {
|
||||
const tasks = [task({ id: 1, workspace_id: 7 }), task({ id: 2, bot_id: 3, bot_name: "A" })];
|
||||
|
||||
expect(shownWorkspaceTasks({ tasks }).map((it) => it.id)).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
test("the default cap is the app setting", () => {
|
||||
const tasks = Array.from({ length: AppData.TaskSectionShown + 3 }, (_, index) =>
|
||||
task({ id: index + 1, workspace_id: 7, updated_at: 100 - index }),
|
||||
);
|
||||
|
||||
expect(shownWorkspaceTasks({ tasks })).toHaveLength(AppData.TaskSectionShown);
|
||||
});
|
||||
|
||||
test("no tasks, nothing to show", () => {
|
||||
expect(shownWorkspaceTasks({ tasks: [] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import workspaceTaskSections from "./workspace-task-sections";
|
||||
|
||||
type Params = {
|
||||
tasks: TaskWithNames[];
|
||||
/**
|
||||
* How many to keep; `AppData.TaskSectionShown` unless a caller says.
|
||||
*/
|
||||
shown?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The rows a workspace page lists before its View all button: the
|
||||
* workspace-wide tasks first, then each bot's own, open ones first, cut to
|
||||
* the cap.
|
||||
*/
|
||||
export default function shownWorkspaceTasks({ tasks, shown = AppData.TaskSectionShown }: Params): TaskWithNames[] {
|
||||
return workspaceTaskSections({ tasks })
|
||||
.flatMap((section) => section.tasks)
|
||||
.slice(0, shown);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import workspaceTaskSections from "./workspace-task-sections";
|
||||
|
||||
function task(fields: Partial<TaskWithNames>): TaskWithNames {
|
||||
return { id: 1, created_at: 1, updated_at: 2, status: "todo", ...fields };
|
||||
}
|
||||
|
||||
describe("workspaceTaskSections", () => {
|
||||
test("the workspace-wide tasks come first, then one section per bot by name", () => {
|
||||
const sections = workspaceTaskSections({
|
||||
tasks: [
|
||||
task({ id: 5, bot_id: 9, bot_name: "SEO Expert", title: "Meta" }),
|
||||
task({ id: 2, workspace_id: 3, title: "Ship it" }),
|
||||
task({ id: 4, bot_id: 3, bot_name: "Software Engineer", title: "Header" }),
|
||||
task({ id: 6, bot_id: 3, bot_name: "Software Engineer", title: "Footer" }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(sections.map((section) => section.title)).toEqual([
|
||||
"Workspace-wide",
|
||||
"SEO Expert",
|
||||
"Software Engineer",
|
||||
]);
|
||||
expect(sections[1]?.tasks.map((it) => it.id)).toEqual([5]);
|
||||
expect(sections[2]?.tasks.map((it) => it.id)).toEqual([4, 6]);
|
||||
});
|
||||
|
||||
test("a workspace with no wide task starts with its bots", () => {
|
||||
const sections = workspaceTaskSections({ tasks: [task({ id: 4, bot_id: 3, bot_name: "Software Engineer" })] });
|
||||
|
||||
expect(sections.map((section) => section.key)).toEqual(["bot:3"]);
|
||||
});
|
||||
|
||||
test("a bot without a name is named by its id", () => {
|
||||
const sections = workspaceTaskSections({ tasks: [task({ id: 4, bot_id: 3 })] });
|
||||
|
||||
expect(sections[0]?.title).toBe("Bot 3");
|
||||
});
|
||||
|
||||
test("each section is open first, blocked before doing before to do", () => {
|
||||
const sections = workspaceTaskSections({
|
||||
tasks: [
|
||||
task({ id: 1, bot_id: 3, bot_name: "A", status: "done" }),
|
||||
task({ id: 2, bot_id: 3, bot_name: "A", status: "todo" }),
|
||||
task({ id: 3, bot_id: 3, bot_name: "A", status: "blocked" }),
|
||||
task({ id: 4, bot_id: 3, bot_name: "A", status: "doing" }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(sections[0]?.tasks.map((it) => it.id)).toEqual([3, 4, 2, 1]);
|
||||
});
|
||||
|
||||
test("no tasks, no sections", () => {
|
||||
expect(workspaceTaskSections({ tasks: [] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { TaskWithNames } from "@/src/types";
|
||||
import compareTasks from "./compare-tasks";
|
||||
|
||||
export type WorkspaceTaskSection = {
|
||||
/**
|
||||
* `wide`, or `bot:<id>`: stable across renders and renames.
|
||||
*/
|
||||
key: string;
|
||||
title: string;
|
||||
tasks: TaskWithNames[];
|
||||
};
|
||||
|
||||
/**
|
||||
* A workspace's tasks as the page lists them: the workspace-wide ones first
|
||||
* (nobody's: every bot there works on them), then each bot's own, one
|
||||
* section per bot in the order of their names, the tasks in each in the
|
||||
* usual open-first order. Empty sections are left out.
|
||||
*/
|
||||
export default function workspaceTaskSections({ tasks }: { tasks: TaskWithNames[] }): WorkspaceTaskSection[] {
|
||||
const wide = tasks.filter((task) => !task.bot_id).sort(compareTasks);
|
||||
|
||||
const by_bot = new Map<number, WorkspaceTaskSection>();
|
||||
|
||||
for (const task of tasks) {
|
||||
if (!task.bot_id) continue;
|
||||
|
||||
const bot_id = Number(task.bot_id);
|
||||
const section = by_bot.get(bot_id) || {
|
||||
key: `bot:${bot_id}`,
|
||||
title: task.bot_name || `Bot ${bot_id}`,
|
||||
tasks: [],
|
||||
};
|
||||
|
||||
section.tasks.push(task);
|
||||
by_bot.set(bot_id, section);
|
||||
}
|
||||
|
||||
const sections = [...by_bot.values()]
|
||||
.map((section) => ({ ...section, tasks: section.tasks.sort(compareTasks) }))
|
||||
.sort((a, b) => a.title.localeCompare(b.title));
|
||||
|
||||
return wide.length ? [{ key: "wide", title: "Workspace-wide", tasks: wide }, ...sections] : sections;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import subtaskAttachProblem from "./subtask-attach-problem";
|
||||
|
||||
const parent = {
|
||||
id: 12,
|
||||
title: "Ship the release",
|
||||
bot_id: null,
|
||||
workspace_id: 4,
|
||||
parent_task_id: null,
|
||||
status: "doing",
|
||||
};
|
||||
|
||||
const task = {
|
||||
id: 30,
|
||||
title: "The intro",
|
||||
bot_id: 7,
|
||||
workspace_id: 4,
|
||||
parent_task_id: null,
|
||||
status: "todo",
|
||||
};
|
||||
|
||||
describe("subtaskAttachProblem", () => {
|
||||
test("an open task of a bot in the parent's workspace can join it", () => {
|
||||
expect(subtaskAttachProblem({ task, parent })).toBeNull();
|
||||
});
|
||||
|
||||
test("a task that isn't there can't join anything", () => {
|
||||
expect(subtaskAttachProblem({ task: null, parent })).toContain("doesn't exist");
|
||||
});
|
||||
|
||||
test("a task can't be a subtask of itself", () => {
|
||||
expect(subtaskAttachProblem({ task: parent, parent })).toContain("subtask of itself");
|
||||
});
|
||||
|
||||
test("a subtask of another task is unlinked first", () => {
|
||||
expect(subtaskAttachProblem({ task: { ...task, parent_task_id: 9 }, parent })).toContain(
|
||||
"already a subtask of task #9",
|
||||
);
|
||||
});
|
||||
|
||||
test("a task with parts of its own can't become one", () => {
|
||||
expect(subtaskAttachProblem({ task, parent, task_subtasks: 2 })).toContain("a subtask can't be a parent");
|
||||
});
|
||||
|
||||
test("only a bot's task in a workspace can join one", () => {
|
||||
expect(subtaskAttachProblem({ task: { ...task, bot_id: null }, parent })).toContain("nothing to be a subtask of");
|
||||
expect(subtaskAttachProblem({ task: { ...task, workspace_id: null }, parent })).toContain(
|
||||
"nothing to be a subtask of",
|
||||
);
|
||||
});
|
||||
|
||||
test("a closed task can't become a subtask", () => {
|
||||
expect(subtaskAttachProblem({ task: { ...task, status: "done" }, parent })).toContain("closed task");
|
||||
});
|
||||
|
||||
test("the parent still has to be a splittable workspace-wide task", () => {
|
||||
expect(subtaskAttachProblem({ task, parent: { ...parent, bot_id: 7 } })).toContain("isn't workspace-wide");
|
||||
expect(subtaskAttachProblem({ task: { ...task, workspace_id: 5 }, parent })).toContain("same workspace");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { OpenTaskStatuses } from "@/src/dict/task-dict";
|
||||
import subtaskLinkProblem from "./subtask-link-problem";
|
||||
|
||||
type TaskLike = {
|
||||
id?: number | string | null;
|
||||
title?: string | null;
|
||||
bot_id?: number | string | null;
|
||||
workspace_id?: number | string | null;
|
||||
parent_task_id?: number | string | null;
|
||||
status?: string | null;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The task that would become a subtask, read as it is.
|
||||
*/
|
||||
task?: TaskLike | null;
|
||||
/**
|
||||
* The workspace-wide task it would join.
|
||||
*/
|
||||
parent?: TaskLike | null;
|
||||
/**
|
||||
* How many subtasks the task itself has of its own (`grabSubtaskCounts`):
|
||||
* a task with subtasks can't become one, since splitting goes one level
|
||||
* deep.
|
||||
*/
|
||||
task_subtasks?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why that task can't be attached to that workspace-wide one, or null when
|
||||
* it can. The parent has to be a wide, open task that isn't itself a subtask
|
||||
* (`subtaskLinkProblem`), and this side has to be an open task of one bot in
|
||||
* the same workspace that has no subtasks of its own: one level of splitting.
|
||||
*/
|
||||
export default function subtaskAttachProblem({ task, parent, task_subtasks }: Params): string | null {
|
||||
if (!task?.id) return `That task doesn't exist, so it can't become a subtask of anything.`;
|
||||
|
||||
const label = `Task #${task.id}${task.title ? ` "${task.title}"` : ""}`;
|
||||
|
||||
if (Number(task.id) == Number(parent?.id || 0)) {
|
||||
return `${label} can't be a subtask of itself.`;
|
||||
}
|
||||
|
||||
if (task.parent_task_id) {
|
||||
return `${label} is already a subtask of task #${task.parent_task_id}: unlink it from that one first.`;
|
||||
}
|
||||
|
||||
if (Number(task_subtasks || 0)) {
|
||||
return `${label} has ${task_subtasks} subtask(s) of its own: a subtask can't be a parent, so unlink them first.`;
|
||||
}
|
||||
|
||||
if (!task.bot_id || !task.workspace_id) {
|
||||
return `${label} isn't a bot's task in a workspace, so it has nothing to be a subtask of: only a task a bot has there can join a workspace-wide one.`;
|
||||
}
|
||||
|
||||
if (!OpenTaskStatuses.includes(task.status as (typeof OpenTaskStatuses)[number])) {
|
||||
return `${label} is ${task.status}: a closed task can't become a subtask.`;
|
||||
}
|
||||
|
||||
return subtaskLinkProblem({ parent, bot_id: task.bot_id, workspace_id: task.workspace_id });
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import subtaskDeleteProblem from "./subtask-delete-problem";
|
||||
|
||||
describe("subtaskDeleteProblem", () => {
|
||||
test("a task whose parts are all finished can go", () => {
|
||||
expect(subtaskDeleteProblem({ task: { id: 12, title: "Ship the release" }, open_subtasks: 0 })).toBeNull();
|
||||
});
|
||||
|
||||
test("open parts hold the delete back", () => {
|
||||
expect(subtaskDeleteProblem({ task: { id: 12, title: "Ship the release" }, open_subtasks: 2 })).toContain(
|
||||
"still has 2 open subtasks",
|
||||
);
|
||||
|
||||
expect(subtaskDeleteProblem({ task: { id: 12 }, open_subtasks: 1 })).toContain("1 open subtask:");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
type TaskLike = {
|
||||
id?: number | string | null;
|
||||
title?: string | null;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
task: TaskLike;
|
||||
/**
|
||||
* How many of its subtasks are still open (to do, doing or blocked).
|
||||
*/
|
||||
open_subtasks: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why a workspace-wide task can't be deleted, or null when it can. Deleting
|
||||
* it takes its subtasks with it, so none of them may be work someone is still
|
||||
* on: finish or cancel them first.
|
||||
*/
|
||||
export default function subtaskDeleteProblem({ task, open_subtasks }: Params): string | null {
|
||||
if (open_subtasks <= 0) return null;
|
||||
|
||||
const label = `Task #${task.id}${task.title ? ` "${task.title}"` : ""}`;
|
||||
|
||||
return `${label} still has ${open_subtasks} open subtask${open_subtasks == 1 ? "" : "s"}: finish, cancel or unlink ${open_subtasks == 1 ? "it" : "them"} before deleting it.`;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import subtaskLinkProblem from "./subtask-link-problem";
|
||||
|
||||
const parent = {
|
||||
id: 12,
|
||||
title: "Ship the release",
|
||||
bot_id: null,
|
||||
workspace_id: 4,
|
||||
parent_task_id: null,
|
||||
status: "doing",
|
||||
};
|
||||
|
||||
describe("subtaskLinkProblem", () => {
|
||||
test("a bot's task in the parent's workspace can be a subtask of it", () => {
|
||||
expect(subtaskLinkProblem({ parent, bot_id: 7, workspace_id: 4 })).toBeNull();
|
||||
});
|
||||
|
||||
test("a parent that isn't there is refused", () => {
|
||||
expect(subtaskLinkProblem({ parent: null, bot_id: 7, workspace_id: 4 })).toContain("doesn't exist");
|
||||
});
|
||||
|
||||
test("only a workspace-wide task can be split", () => {
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, bot_id: 7 }, bot_id: 7, workspace_id: 4 }),
|
||||
).toContain("isn't workspace-wide");
|
||||
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, workspace_id: null }, bot_id: 7, workspace_id: 4 }),
|
||||
).toContain("isn't workspace-wide");
|
||||
});
|
||||
|
||||
test("a subtask can't be split again", () => {
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, parent_task_id: 3 }, bot_id: 7, workspace_id: 4 }),
|
||||
).toContain("can't be split again");
|
||||
|
||||
// A real subtask has a bot, which is no reason to call it something else.
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, bot_id: 7, parent_task_id: 3 }, bot_id: 8, workspace_id: 4 }),
|
||||
).toContain("can't be split again");
|
||||
});
|
||||
|
||||
test("a subtask belongs to one bot", () => {
|
||||
expect(subtaskLinkProblem({ parent, bot_id: null, workspace_id: 4 })).toContain("belongs to one bot");
|
||||
});
|
||||
|
||||
test("a subtask stays in its parent's workspace", () => {
|
||||
expect(subtaskLinkProblem({ parent, bot_id: 7, workspace_id: 9 })).toContain("same workspace");
|
||||
expect(subtaskLinkProblem({ parent, bot_id: 7, workspace_id: null })).toContain("same workspace");
|
||||
});
|
||||
|
||||
test("a closed task can't be split", () => {
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, status: "done" }, bot_id: 7, workspace_id: 4 }),
|
||||
).toContain("can't be split");
|
||||
|
||||
expect(
|
||||
subtaskLinkProblem({ parent: { ...parent, status: "cancelled" }, bot_id: 7, workspace_id: 4 }),
|
||||
).toContain("can't be split");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { OpenTaskStatuses } from "@/src/dict/task-dict";
|
||||
|
||||
type ParentLike = {
|
||||
id?: number | string | null;
|
||||
title?: string | null;
|
||||
bot_id?: number | string | null;
|
||||
workspace_id?: number | string | null;
|
||||
parent_task_id?: number | string | null;
|
||||
status?: string | null;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The task it would be a subtask of, read as it is; none when the id names
|
||||
* nothing.
|
||||
*/
|
||||
parent?: ParentLike | null;
|
||||
/**
|
||||
* Who would have the subtask.
|
||||
*/
|
||||
bot_id?: number | string | null;
|
||||
/**
|
||||
* The workspace the subtask would be created in.
|
||||
*/
|
||||
workspace_id?: number | string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why a task can't be a subtask of that one, or null when it can. A subtask is a
|
||||
* bot's own task in its parent's workspace, and its parent is a
|
||||
* workspace-wide task that is no one's and isn't itself a subtask: one level
|
||||
* of splitting, so a subtask can never be split again or drift to another
|
||||
* workspace.
|
||||
*/
|
||||
export default function subtaskLinkProblem({ parent, bot_id, workspace_id }: Params): string | null {
|
||||
if (!parent?.id) return `That task doesn't exist, so nothing can be a subtask of it.`;
|
||||
|
||||
const label = `Task #${parent.id}${parent.title ? ` "${parent.title}"` : ""}`;
|
||||
|
||||
if (parent.parent_task_id) {
|
||||
return `${label} is itself a subtask of task #${parent.parent_task_id}: a subtask can't be split again.`;
|
||||
}
|
||||
|
||||
if (parent.bot_id || !parent.workspace_id) {
|
||||
return `${label} isn't workspace-wide, so it has no subtasks: only a workspace-wide task can be split.`;
|
||||
}
|
||||
|
||||
if (!bot_id) {
|
||||
return `A subtask belongs to one bot: say which bot has it (leave workspace-wide out).`;
|
||||
}
|
||||
|
||||
if (Number(parent.workspace_id) != Number(workspace_id || 0)) {
|
||||
return `${label} is in ${parent.workspace_id == null ? "no workspace" : `workspace ${parent.workspace_id}`}: a subtask of it has to be in that same workspace.`;
|
||||
}
|
||||
|
||||
if (!OpenTaskStatuses.includes(parent.status as (typeof OpenTaskStatuses)[number])) {
|
||||
return `${label} is ${parent.status}: a closed task can't be split.`;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import subtaskMoveProblem from "./subtask-move-problem";
|
||||
|
||||
describe("subtaskMoveProblem", () => {
|
||||
test("a task with no parts and no parent moves freely", () => {
|
||||
expect(subtaskMoveProblem({ task: { id: 5, title: "Check the invoices" }, linked_subtasks: 0 })).toBeNull();
|
||||
});
|
||||
|
||||
test("a subtask is never moved", () => {
|
||||
expect(
|
||||
subtaskMoveProblem({ task: { id: 8, title: "The invoices", parent_task_id: 12 }, linked_subtasks: 0 }),
|
||||
).toContain("unlink it from the parent first");
|
||||
});
|
||||
|
||||
test("a task with parts stays until they're unlinked", () => {
|
||||
expect(subtaskMoveProblem({ task: { id: 12, title: "Ship the release" }, linked_subtasks: 3 })).toContain(
|
||||
"has 3 subtasks",
|
||||
);
|
||||
|
||||
expect(subtaskMoveProblem({ task: { id: 12 }, linked_subtasks: 1 })).toContain("has 1 subtask:");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
type TaskLike = {
|
||||
id?: number | string | null;
|
||||
title?: string | null;
|
||||
parent_task_id?: number | string | null;
|
||||
};
|
||||
|
||||
type Params = {
|
||||
task: TaskLike;
|
||||
/**
|
||||
* How many tasks are subtasks of it (`parent_task_id` pointing at it),
|
||||
* open or not.
|
||||
*/
|
||||
linked_subtasks: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why a task can't be moved to another bot or list (handed over, made
|
||||
* workspace-wide), or null when it can. A workspace-wide task with subtasks
|
||||
* stays where it is until every subtask is unlinked, and a subtask itself is
|
||||
* never moved: it is one piece of its parent's work, and a task that can be
|
||||
* moved has no subtasks attached either way.
|
||||
*/
|
||||
export default function subtaskMoveProblem({ task, linked_subtasks }: Params): string | null {
|
||||
const label = `Task #${task.id}${task.title ? ` "${task.title}"` : ""}`;
|
||||
|
||||
if (task.parent_task_id) {
|
||||
return `${label} is a subtask of task #${task.parent_task_id}: unlink it from the parent first, then move it.`;
|
||||
}
|
||||
|
||||
if (linked_subtasks > 0) {
|
||||
return `${label} has ${linked_subtasks} subtask${linked_subtasks == 1 ? "" : "s"}: unlink ${linked_subtasks == 1 ? "it" : "them all"} first, then move it.`;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user