Tasks
Issues and tasks on pipelines, with identifiers, parents without cycles, several assignees, priority 0 to 4, estimates, start, end and due dates, locking, projects, iterations, batched edits and a progress tree.
tasks is the task and issue record of Linear, Jira, GitHub issues and monday items: a title, a body, a parent, assignees, a priority, an estimate, start, end and due dates, and a stage on a pipeline. Items can belong to a team, a project and an iteration (a cycle or a sprint). Their identifier is TASK-12, or the format of a work_item entity in numbering.
When option-sets is installed, the priority is a field of its own: each organization can rename the five levels, add more items and give them colors and icons. The task keeps the level in priority and the chosen item in priority_option_id, so sorting and filters on priority do not change.
Reading needs tasks.read, creating, editing and assigning needs tasks.write, and projects, iterations and deleting someone else's item need tasks.manage. Admins get every permission, and members get tasks.read and tasks.write.
Two actions take their own key when you set one. permissions.create gates creating an item and falls back to the write key, and permissions.delete gates deleting one and falls back to the manage key. The author of an item can always delete it; set options.authorCanDelete: false to make the author need the delete key too:
tasks: {
permissions: { create: "task.create", delete: "task.delete" },
options: { authorCanDelete: false },
},better-supabase add tasksThe module needs tenant, access, subjects and pipelines. Installing it binds the work_item type in the pipelines module with one pipeline per team (scope: "team_id") and the categories of Linear's workflow states:
| Category | Outcome | Default stages |
|---|---|---|
triage | open | Triage |
backlog | open | Backlog |
unstarted | open | Todo |
started | open | In progress, In review |
completed | success | Done |
canceled | failure | Canceled |
A stage's category sets the item's state, so a list or a policy reads state and never a stage name. Set blocks.pipelines.on.work_item to rename the stages or start with your own, such as Todo, In progress, On hold and Done; your keys are merged over the defaults.
Installing the block registers work items as the work_item subject, ranked by stage. Set the page a search result links to on the entity:
export default defineConfig({
blocks: { tasks: { names: { work_item: { url: "/tasks/{id}" } } } },
});The block registers the subject under the entity's final name, so after names: { work_item: "task" } it registers task. A config.recordTypes.task entry then clashes with it and the config is refused. Keep one of the two: remove the records entry, or set names: { work_item: { name: "task", subject: false } } and register the type yourself in config.recordTypes.
Create, edit and assign
Server code calls the tasks instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useTasks } = defineDataHooks(
"tasks",
(db: AppDb) => db.tasks,
);import { createTasks } from "better-supabase/blocks/tasks";
const epic = await db.tasks
.create(organizationId, { title: "Checkout v2", teamId, priority: 2 })
.orThrow();
const task = await db.tasks
.create(
organizationId,
{ title: "Payment API", parentId: epic.id, teamId, dueAt },
[userId],
)
.orThrow();
const { accepted, rejected } = await db.tasks
.update({
changes: [
{ taskId: task.id, field: "stageId", value: inProgressStageId },
{ taskId: task.id, field: "endAt", value: friday },
],
})
.orThrow();"use client";
import { useTasks } from "@/lib/supabase/hooks";
const rows = useTasks({ limit: 50 });create takes the extra columns of your table under fields, as update does. The locked column is optional: map it to null in blocks.tasks.columns.items and the table has no lock, so dates always change.
update({ changes }) applies grid edits and Gantt drags one by one and returns the refused ones with their hint. The table refuses a parent that would put an item under itself (TASK_PARENT_CYCLE) and date changes on a locked item (TASK_LOCKED). Moving to a completed or canceled stage stamps closedAt and a close reason (completed, or not_planned for canceled; pass closeReason: "duplicate" with the move to mark a duplicate) and records task.closed. Moving back to an open stage clears both and records task.reopened.
A Gantt drag that moves both ends sends one window change, { startAt, endAt }, which writes the two dates in one update. Two separate changes would fail the endAt >= startAt check halfway when the bar moves past its old end. Either key can be left out or null. Pass atomic: true when a batch must apply in full or not at all: the first refused change then fails the whole call with its hint, and nothing is written.
await db.tasks
.update({
changes: [{ taskId: task.id, field: "window", value: { startAt, endAt } }],
atomic: true,
})
.orThrow();Without atomic, a refused change comes back in rejected and the others stay applied. Pass strict: true to get the first refused change as the error instead, with its hint as the raised code, so an action can return it as it is.
A change takes an optional expectedVersion, the updatedAt of the item as you read it. When the item changed since, that change is refused with the hint STALE_WRITE (a conflict error under strict, see stale writes). Every change of one batch compares to the item as it was before the batch, so two changes to one item don't refuse each other.
create takes an idempotencyKey when createTasks gets the idempotency option (createIdempotency(...) from better-supabase/blocks/queue). A retry with the same key and input returns the first task, a retry that overlaps the first answers conflict (IDEMPOTENCY_KEY_IN_USE), and the same key with other input answers validation (IDEMPOTENCY_KEY_REUSED).
move({ taskId, stageId }) is update with one stageId change and strict, so a refused board drag comes back as the error.
assign(id, userIds) replaces the assignees. Each one watches the item, and the people newly assigned get a work_item.assigned notification. The task.assigned event is recorded only when the call adds someone: assigneeIds holds everyone assigned now and addedIds the people the call added. options.maxAssignees caps the list (TASK_ASSIGNEES_LIMIT), and 1 gives the single-assignee shape of Linear and Jira.
The notification carries the item's title as its subject label, and options.actionPath sets its action path from a template with {id} and {identifier}, such as "/tasks/{id}". Set options.notify: false when the app sends its own assignment notifications; the assignees still watch the item.
create takes custom, a map from custom field definition id to value. The values are set on the new task through the customFields port that createBlocks passes when the custom-fields block is installed (hint TASKS_CUSTOM_FIELDS_MISSING without it). When a value is refused, the task is removed again and the error returned.
await tasks
.create({
organizationId,
input: { title: "Ship" },
custom: { [priorityFieldId]: "high" },
})
.orThrow();Archive, restore or remove many items
archive({ taskIds, archived }), restore(taskIds) and remove(taskIds) take a list and run as one statement each, so the access check runs once for the whole set and each records its events as before. They return { ids, skipped }: ids are the items that changed, and skipped are the ids that don't exist or that you can't edit. Calling with an id list in a loop is no longer needed. In SQL they are archive_tasks(ids uuid[], archived boolean) and delete_tasks(ids uuid[]), which return the same shape as jsonb.
const { ids, skipped } = await tasks.archive({ taskIds }).orThrow();bulk(ids, action, options) is the same set calls in the shape every block with a bulk call shares (ADR 0854). action is archive, restore or remove, and the result is { succeeded, failed: [{ id, error }] }: the ids the set call skipped are failed with not_found. More ids than options.limit (500 by default) fail with BULK_TOO_MANY before anything runs.
const { succeeded, failed } = await tasks.bulk(taskIds, "archive").orThrow();Lists, trees, projects and iterations
list(organizationId, { teamId, projectId, iterationId, parentId, assigneeId, states, open, search }) returns active items, newest first, 50 per page; pass the last item's id as after for the next page. tree(rootId) returns an item and everything under it with its depth; an item without its own progress rolls up the share of its open and completed children that are completed, for a Gantt group.
Dependencies between items are relations: link(design, build, { kind: "blocks" }) is a finish-to-start dependency, and edges("blocks") reads them for the chart.
saveProject(organizationId, { key, name, status, startOn, targetOn }) keeps a project (PAY) with the share of its items that are completed. A project can carry a budget (a Money) and budgetHours, which billable time compares its costs to. With accounting installed, saving a project keeps a value of the project dimension in step, coded by the project id, so expense and bill lines can name it. saveIteration(organizationId, { name, teamId, startsOn, endsOn }) keeps a cycle or a sprint. Turn either table off with tables: { projects: null } or tables: { iterations: null }.
Checklists, files, repeat rules and watchers
const draft = await items
.saveChecklistItem(task.id, { title: "Draft the copy" })
.orThrow();
await items.saveChecklistItem(task.id, { done: true }, draft.id).orThrow();
const steps = await items.checklist(task.id).orThrow();saveChecklistItem(taskId, input, checklistItemId?) adds a step at the end, or edits the one you name: its title, done (which stamps doneAt and doneBy) or rank. removeChecklistItem(id) deletes one, and checklist(taskId) lists them in rank order. Every item a read returns carries checklist: { total, done }, and get(id) reads one item. An app that keeps its own subtasks maps tables.checklist to null: the module then creates no checklist table or functions, reads return checklist: null, and repeat copies no steps. A checklist change records task.updated with fields: ["checklist"].
On the work item's own page, the block's record binding (taskChecklistBinding) loads the steps for the item as the subject ({ type: "task", id }, or the renamed type) and reads again on task.updated. taskChecklistOptimistic is its useOptimistic reducer: { type: "save", item } adds or replaces a step in rank order and { type: "remove", id } drops one.
With the attachments block installed, create takes attachmentIds and update takes an attachments change with a list of ids. Upload the files first without a subject, then link them: the block links only files the caller uploaded that have no subject yet (TASK_ATTACHMENTS_INVALID). A bucket whose path template uses {subject_type} or {subject_id} can't move a file after upload, so link through attachments.upload with the item as the subject instead (TASK_ATTACHMENTS_PATH).
With the reminders block installed, setRecurrence(id, { rrule, tzid }) gives an item a repeat rule, such as FREQ=MONTHLY;BYMONTHDAY=1, and setRecurrence(id, null) removes it. Items carry the rule as recurrence. A repeating item makes its next copy when it is completed, like Asana and Todoist: relay the block's events to taskRecurrenceSink, built on a service transport.
import { createTasks, taskRecurrenceSink } from "better-supabase/blocks/tasks";
const serviceItems = createTasks({ transport: serviceTransport });
outbox.relay("tasks", taskRecurrenceSink(serviceItems));The sink calls repeat(id, dueAt) with the rule's first occurrence after the completed item's due date. repeat copies the title, body, parent, team, project, priority, estimate, assignees, extra columns and an unchecked checklist, shifts the start and end dates by the same amount, and moves the rule to the copy, so a COUNT keeps counting. The copy's recursFromId names the item it repeats, and a second repeat of the same item returns the same copy, so a redelivered event changes nothing. After names: { work_item: "task" }, pass { type: "task.closed" }.
With the notifications block installed, watch(id, "all") follows an item, watch(id, "ignore") mutes it, watch(id, null) goes back to the default, and watchers(id) lists who follows it. Assignees already watch their items.
Extra columns
Columns you add to tasks with alter table in your own schema files are fields of the block (details):, such as a customer_id. Every item a read returns carries them in fields.
Coordinate work between people and agents
These methods are for a queue that several workers, human or agent, pull from. Each is a SQL function with the same permission checks as the rest of the block, and a read-only actor (a support, impersonation or read-only agent session) is refused on every write.
Prerequisites
With options.needs: { kind: "blocks" } and the relations block, setNeeds({ taskId, needs }) replaces the tasks that block one. The waiting_on column counts the open prerequisites, the ready list filter returns open tasks nothing blocks, waiting returns open tasks that still wait on one, and task.unblocked is sent when the count reaches zero. A cycle or a prerequisite from another organization is refused with TASK_NEEDS_INVALID. A prerequisite that is canceled or failed keeps its dependents blocked, and deleting one unblocks them. refuse sets what an unready task refuses: claims (default), started or none; the refusal is TASK_NOT_READY. Setting needs takes the relations manage permission.
Create a plan
createPlan({ organizationId, plan, idempotencyKey }) creates up to 100 tasks in one transaction. Entries name each other with key, in parentId and needs. The plan is checked before the first write, so a bad one creates nothing (TASK_PLAN_INVALID, TASK_PLAN_TOO_LARGE). A replay with the same idempotencyKey returns the first result. The method is createPlan because createMany is a retired data-contract verb.
Claims
claim({ taskId, lease, profile }) takes a lease (options.claims.lease and maxLease, in seconds) and returns a token. A live claim of someone else is TASK_CLAIMED, a held task is TASK_HELD. claimNext({ organizationId, filter }) takes the oldest ready task by number, and concurrent callers get different tasks. options.claims.next is "assigned" by default, so a caller picks only tasks assigned to it; "any" also takes unassigned ones. An agent session always picks assigned tasks (TASK_NOT_ASSIGNED, and TASK_FILTER_FORBIDDEN for another assignee). A session counts as an agent when its act claim has the kind agent. options.claims.agents adds other session kinds: "oauth-client" for a token with client_id or an act claim without a kind (an MCP client), and "api-key" for an app API key. Such a session then claims only tasks assigned to its user, by id and with claimNext, and can't take over a reserved task. filter.delegateProfile picks tasks reserved for a profile. renew and release need the token and raise TASK_CLAIM_LOST after the lease ran out or someone else took over. Every new claim bumps epoch. startStage and expiredStage move the task when a claim starts or expires, and take a stage key or { category }. delegate({ taskId, toUserId, toProfile }) assigns the task and ends the claim. With toProfile the task is reserved for that profile of that user: anyone else gets TASK_RESERVED, except a person with write access, who takes it over. The task reads back delegateProfile: { name, userId }, and a re-delegate, an unassign and a close clear it.
Who acts
profile: { kind, name } labels who acted, such as { kind: "agent", name: "scout" }. It is a label on claims and events and never grants access. A session with an act claim of kind agent also shows as agent in audit rows and timeline entries (actorKind, actorName); before this it showed as an impersonation.
Hold
hold({ taskId, kind, note, askUserIds }) puts a task on hold to ask a person. The note goes through messaging and mentions askUserIds, who must be able to read the task. options.hold.kinds lists the accepted kinds (TASK_HOLD_INVALID otherwise). With options.hold.stage, a key or { category }, the task moves to that stage until releaseHold. Releasing, moving out of the stage and closing cancel a pending approval request; doctor rule BS245 reports a stage that does not exist. A manual move into that stage is not a hold, and a manual move out of it clears one.
With the approvals block installed, options.hold.approval files each hold as an approval request of the subject type task_hold. true asks one approver, a member with the manage permission; { policy } takes an approvals policy without run, and kinds limits which hold kinds open a request. An approval releases the task, and a rejection cancels it, or with onReject: "keep" leaves it on hold. kinds can also be a record from hold kind to true or { policy, onReject }, so each kind files under its own policy and settles a rejection its own way; a kind without a field takes the block-wide policy and onReject. The record needs the hold_kind column. Nobody needs the write permission to decide: approvals checks the approver, and the task changes through an internal function that is granted to no role. A decision on a task that is no longer on hold is refused. The option needs the held_at column and fails at render without the approvals block. task.held then carries the request as approvalId.
// better-supabase.config.ts
blocks: {
tasks: { options: { hold: { stage: "blocked", approval: { onReject: "cancel" } } } },
}// better-supabase.config.ts: a spend hold keeps the task on hold when it is rejected
blocks: {
tasks: {
options: {
claims: { agents: ["oauth-client", "api-key"] },
hold: {
kinds: ["review", "spend", "input"],
approval: {
onReject: "cancel",
kinds: { review: true, spend: { onReject: "keep" } },
},
},
},
},
}Outcomes
complete, cancel and fail take a note, kept in closeNote and sent with the event. fail closes the task in a canceled stage with the close reason failed and sends task.closed and task.failed. When the pipeline has no canceled stage it raises TASK_OUTCOME_UNAVAILABLE.
Ordering
move({ taskId, stageId, beforeId, afterId }) places a task in a lane, and moveMany({ moves }) applies several moves in one call: the refused ones come back in rejected with a hint, and the others apply. A rank clash is TASK_RANK_CONFLICT.
Stage times and live changes
stageTimes(taskId) lists the stages a task has been in with the seconds spent in each, and the open stage counts up to now. Changes to tasks broadcast { id, change, table } on the realtime topic tasks:{organizationId}; subscribe with the topic and refetch.
Events and errors
New events: task.unblocked, task.claimed, task.released, task.claim_expired, task.failed, task.delegated, task.held and task.hold_released. New hints: TASK_NOT_READY, TASK_CLAIMED, TASK_CLAIM_LOST, TASK_CLAIM_NOT_HELD, TASK_NOTHING_READY, TASK_HELD, TASK_NOT_HELD, TASK_HOLD_INVALID, TASK_HOLD_STAGE_MISSING, TASK_HOLD_MESSAGING_MISSING, TASK_NEEDS_INVALID, TASK_NEEDS_UNSUPPORTED, TASK_PLAN_INVALID, TASK_PLAN_TOO_LARGE, TASK_OUTCOME_INVALID, TASK_OUTCOME_UNAVAILABLE, TASK_MOVE_INVALID, TASK_RANK_CONFLICT, TASK_DELEGATE_INVALID, TASK_RESERVED, TASK_NOT_ASSIGNED, TASK_FILTER_FORBIDDEN and ACTOR_READ_ONLY.
Events
| Event | Data |
|---|---|
task.created, task.updated, task.assigned, task.reopened, task.archived, task.restored, task.deleted | organizationId, taskId, subjectType, subjectId, title, fields, assigneeIds, addedIds |
task.closed | the same, with state and closeReason |
blocks.tasks.events.payload adds columns of the task row to an event, such as { "task.created": { customerId: "customer_id" } } (details).
Hooks
The module calls before_task_create(tenant, attrs jsonb), after_task_create(work_item uuid), before_task_update(work_item uuid, field text, value jsonb) and after_task_update(work_item uuid, field text). A before_ hook raises to refuse; in update, that refuses only its change. before_task_close(work_item uuid, outcome text, note text) runs once on every path that closes an item, from a trigger, and raising refuses the close. Templates are skipped.
Wire it to ReUI
The ReUI Kanban blocks commit a drag through onValueCommit: call rank.move("task", id, { previous, next, group: stageId }). The Gantt blocks commit a move or resize through onEventUpdate: send startAt and endAt through update, and return false when the change comes back in rejected (a locked bar). Read the Gantt rows from tree, and its arrows from the blocks relations.
Errors
| Hint | Cause |
|---|---|
TASK_FORBIDDEN | the caller lacks the permission |
TASK_TITLE_REQUIRED | the title is empty |
TASK_ATTRS_INVALID | a field has an invalid value |
TASK_NOT_FOUND | no item the caller can edit |
TASK_FIELD_UNKNOWN | update names a field it doesn't write |
TASK_PARENT_CYCLE | the parent would put the item under itself |
TASK_PARENT_INVALID | the parent is in another organization |
TASK_LOCKED | a locked item's dates don't change |
STALE_WRITE | the item changed since expectedVersion was read |
TASK_ASSIGNEES_LIMIT | more assignees than maxAssignees |
TASK_PROJECT_*, TASK_ITERATION_* | a project or iteration is missing, taken or invalid |
TASK_CHECKLIST_ITEM_INVALID | a checklist step has no title or an invalid rank |
TASK_CHECKLIST_ITEM_NOT_FOUND | no such step on this item |
TASK_ATTACHMENTS_INVALID | a file isn't the caller's or already has a subject |
TASK_ATTACHMENTS_UNAVAILABLE | the attachments block isn't installed |
TASK_ATTACHMENTS_PATH | the bucket's paths name the subject |
TASK_RECURRENCE_INVALID | the rule isn't an RRULE or the time zone is unknown |
Your own columns
Add columns to the work item table with alter table ... add column in your own schema files
(column name to SQL type), then pass a Standard Schema for them as fields.
create, and update with the column name as field validates and writes them, and every method that returns an item return them parsed under
fields. The block also takes hooks around its methods; see
extending blocks.
import { createTasks } from "better-supabase/blocks/tasks";
import { z } from "zod";
const client = createTasks({
transport,
fields: z.object({ priority: z.enum(["low", "high"]) }),
});Without the client
db.tasks is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createTasks } from "better-supabase/blocks/tasks";
const items = createTasks({ transport });
const epic = await items
.create(organizationId, { title: "Checkout v2", teamId, priority: 2 })
.orThrow();
const task = await items
.create(
organizationId,
{ title: "Payment API", parentId: epic.id, teamId, dueAt },
[userId],
)
.orThrow();
const { accepted, rejected } = await items
.update({
changes: [
{ taskId: task.id, field: "stageId", value: inProgressStageId },
{ taskId: task.id, field: "endAt", value: friday },
],
})
.orThrow();Close and reopen an item
complete, cancel and reopen take { taskId, stageId }. Each one moves the item (a refused move comes back as the error) and then reads it, so a stage of the wrong category fails with invalid_input instead of leaving the board in a state the app didn't mean.
await tasks.complete({ taskId, stageId: doneStageId }).orThrow();
await tasks.reopen({ taskId, stageId: todoStageId }).orThrow();Specification lines and materials
A work item can carry ordered specification lines and material lines. A
specification line has a description, a quantity, a unit and an estimate. A
material line points at a catalog variant, with its
quantity and unit. Both are ordered by rank. Map a table to null to leave
it out, and map a column to rename it:
tasks: {
tables: { specification: null },
columns: { items: { estimatedMinutes: "minutes" } },
},estimated_minutes is optional, the same way estimate is. Mapping it to
null leaves the column out. It stores a whole number of minutes.
Assign to yourself
tasks.assignToMe({ taskId, userId }) adds a user to the item's assignees and keeps the others, where
assign replaces them. The client has no signed-in user of its own, so the caller passes the id, for
example ctx.user.id in an action. It returns the assignee count and does nothing when the user is
already assigned.
Paging tasks and projects
page({ organizationId }) pages tasks by keyset. Sorts are number, title, dueAt and createdAt. Filters are state, priority, teamId, projectId, iterationId, parentId, assigneeId, open, dueFrom, dueTo, triage and milestoneId. Facets are state and priority, and q searches the title and the identifier. facets, count and getTask follow the contract; get keeps returning undefined for a missing task, and getTask returns a not_found error. Projects live in this block: pageProjects, projectFacets, countProjects and getProject page them by status and q. A project is a subject, so comments, files, tags and the timeline can attach to it. pageIterations and getIteration read cycles. Checklist items have no page. list is deprecated. The SQL functions are page_tasks, page_projects, get_project and page_iterations.
const page = await tasks
.page({
organizationId,
filters: { state: ["todo", "doing"] },
sort: { by: "dueAt" },
})
.orThrow();Last updated on
Collections
Favorites (a member's starred records, ranked for a sidebar), saved items (a member's records to come back to, with a note and a reminder) and lists (named, static collections of one record type owned by a user, a team or the organization) on any registered record.
Service levels
First response, next response and resolution clocks on any record, from a policy per record type and priority, in business hours, paused while the record waits, with warnings and breaches a job records.