Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat: let Room members cancel a background Task

LeoXing502440f49a84
diff --git a/apps/teamhub/internal/app/contract_server_room_run_control.go b/apps/teamhub/internal/app/contract_server_room_run_control.go
index a7e9b472..88cde22a 100644
--- a/apps/teamhub/internal/app/contract_server_room_run_control.go
+++ b/apps/teamhub/internal/app/contract_server_room_run_control.go
@@ -8,6 +8,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/simplexai-labs/linger/apps/teamhub/internal/agentruntimestate"
"github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/taskdelegation"
httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
)
@@ -34,6 +35,24 @@ func (a *App) listRoomBackgroundTasks(c *gin.Context) {
c.JSON(http.StatusOK, httpapi.RoomBackgroundTaskList{Items: items})
}
+// cancelRoomBackgroundTask stops one Task running for the Room on a Human
+// member's request; the Task stays resumable by its Meta.
+func (a *App) cancelRoomBackgroundTask(c *gin.Context) {
+ taskID := c.Param("taskId")
+ status, err := a.taskDelegation.CancelFromRoom(c.Request.Context(), currentPrincipal(c).Session.AccountID, c.Param("roomId"), taskID)
+ switch {
+ case errors.Is(err, taskdelegation.ErrNotFound):
+ a.writeError(c, http.StatusNotFound, "NOT_FOUND", "Room was not found")
+ return
+ case errors.Is(err, taskdelegation.ErrConflict):
+ a.writeError(c, http.StatusConflict, "CONFLICT", "The Task changed at the same time; retry")
+ return
+ case a.notFoundOrError(c, "cancel Room background Task", err):
+ return
+ }
+ c.JSON(http.StatusOK, httpapi.RoomBackgroundTaskCancelResult{TaskId: taskID, Status: httpapi.RoomBackgroundTaskCancelResultStatus(status)})
+}
+
func (a *App) cancelRoomRun(c *gin.Context) {
roomID := c.Param("roomId")
runID := c.Param("runId")
diff --git a/apps/teamhub/internal/app/routes_public.go b/apps/teamhub/internal/app/routes_public.go
index 13e43976..28794308 100644
--- a/apps/teamhub/internal/app/routes_public.go
+++ b/apps/teamhub/internal/app/routes_public.go
@@ -88,6 +88,7 @@ func (a *App) publicRoutes() []contractRoute {
route(http.MethodPatch, "/v0/rooms/:roomId", nil, session, a.updateRoom),
route(http.MethodGet, "/v0/rooms/:roomId/active-voice-capture", nil, session, a.getActiveVoiceCapture),
route(http.MethodGet, "/v0/rooms/:roomId/background-tasks", nil, session, a.listRoomBackgroundTasks),
+ route(http.MethodPost, "/v0/rooms/:roomId/background-tasks/:taskId/cancel", nil, session, a.cancelRoomBackgroundTask),
route(http.MethodGet, "/v0/rooms/:roomId/documents", httpapi.ListRoomDocumentsParams{}, session, a.listRoomDocuments),
route(http.MethodPost, "/v0/rooms/:roomId/documents", nil, session, a.createRoomDocument),
route(http.MethodPut, "/v0/rooms/:roomId/documents/:documentId", nil, session, a.bindDocumentToRoom),
diff --git a/apps/teamhub/internal/taskdelegation/room_cancel.go b/apps/teamhub/internal/taskdelegation/room_cancel.go
new file mode 100644
index 00000000..be912913
--- /dev/null
+++ b/apps/teamhub/internal/taskdelegation/room_cancel.go
@@ -0,0 +1,66 @@
+package taskdelegation
+
+import (
+ "context"
+ "errors"
+ "slices"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/jobs"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/taskexecution"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard"
+)
+
+// Statuses CancelFromRoom reports.
+const (
+ RoomTaskCanceled = "canceled"
+ RoomTaskNotRunning = "not_running"
+)
+
+// CancelFromRoom lets a Human member of a Room cancel one of the Tasks
+// running for it. The Task is stopped as its Meta's task stop does, so it
+// stays resumable, and the Meta is told who canceled it. A Task that is no
+// longer running is left alone and reported not_running.
+func (s *Service) CancelFromRoom(ctx context.Context, accountID, roomID, taskID string) (string, error) {
+ if s == nil || s.pool == nil {
+ return "", ErrUnavailable
+ }
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return "", err
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ queries := store.New(tx)
+ account := pgtype.Text{String: accountID, Valid: accountID != ""}
+ room, err := queries.GetRoomForAccount(ctx, store.GetRoomForAccountParams{ID: roomID, AccountID: account})
+ if errors.Is(err, pgx.ErrNoRows) {
+ return "", ErrNotFound
+ }
+ if err != nil {
+ return "", err
+ }
+ human, err := queries.GetHumanActor(ctx, store.GetHumanActorParams{TenantID: room.TenantID, AccountID: account})
+ if err != nil {
+ return "", err
+ }
+ running, err := queries.ListRoomRunningTasks(ctx, store.ListRoomRunningTasksParams{RoomID: roomID, TenantID: room.TenantID})
+ if err != nil {
+ return "", err
+ }
+ if !slices.ContainsFunc(running, func(row store.ListRoomRunningTasksRow) bool { return row.ID == taskID }) {
+ return RoomTaskNotRunning, nil
+ }
+ if _, err := taskexecution.CancelTaskByHuman(ctx, queries, taskID, human); err != nil {
+ return "", mapTaskExecutionError(err)
+ }
+ // Canceling expires the cards the AlterEgo was waiting on.
+ if err := jobs.InsertTx(ctx, tx, typedcard.StoppedTaskApprovalsArgs{TenantID: room.TenantID, TaskID: taskID}, nil); err != nil {
+ return "", err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return "", err
+ }
+ return RoomTaskCanceled, nil
+}
diff --git a/apps/teamhub/internal/taskexecution/delegated.go b/apps/teamhub/internal/taskexecution/delegated.go
index 04978dce..e21b0952 100644
--- a/apps/teamhub/internal/taskexecution/delegated.go
+++ b/apps/teamhub/internal/taskexecution/delegated.go
@@ -268,6 +268,28 @@ func StopTask(ctx context.Context, queries *store.Queries, taskID, actorID strin
return setDelegatedTaskStatus(ctx, queries, snapshot, status, "canceled", "stopped", "stopped", actorID, payload)
}
+// CancelTaskByHuman stops a delegated Task's current turn exactly as
+// StopTask does, so the Task stays resumable, then tells its coordinating
+// Meta who canceled it. Canceling a canceled Task changes nothing and
+// returns revision 0.
+func CancelTaskByHuman(ctx context.Context, queries *store.Queries, taskID string, human store.Actor) (int64, error) {
+ if human.ID == "" || human.Kind != "human" {
+ return 0, ErrInvalid
+ }
+ revision, err := StopTask(ctx, queries, taskID, human.ID)
+ if err != nil || revision == 0 {
+ return revision, err
+ }
+ snapshot, err := queries.LockTaskExecutionSnapshot(ctx, taskID)
+ if err != nil {
+ return 0, err
+ }
+ notice := human.DisplayName + " canceled Task " + snapshot.Title + " (" + taskID + "). " +
+ "Its current turn was stopped; its session and ./playground/" + taskID + "/ are kept, so it can be resumed. " +
+ "Tell the user it was canceled, then follow what they want next."
+ return revision, appendTaskCallback(ctx, queries, snapshot, snapshot.TaskExecutionGeneration.Int64, human.ID, notice)
+}
+
// setDelegatedTaskStatus records a Meta-driven change outside the Worker
// lease: the fact, the Task snapshot (releasing any lease) and its Event.
func setDelegatedTaskStatus(
@@ -306,6 +328,10 @@ func setDelegatedTaskStatus(
// which wakes the coordinating Meta of the Task's origin Room. A Task
// without a coordinator has nobody to report to.
func appendTaskReport(ctx context.Context, queries *store.Queries, snapshot store.LockTaskExecutionSnapshotRow, generation int64, body string) error {
+ return appendTaskCallback(ctx, queries, snapshot, generation, snapshot.ResultAgentActorID, body)
+}
+
+func appendTaskCallback(ctx context.Context, queries *store.Queries, snapshot store.LockTaskExecutionSnapshotRow, generation int64, authorActorID, body string) error {
body = truncateRunes(body, taskReportMaxRunes)
segments, err := json.Marshal([]map[string]string{{"type": "text", "content": body}})
if err != nil {
@@ -318,7 +344,7 @@ func appendTaskReport(ctx context.Context, queries *store.Queries, snapshot stor
}
_, err = AppendMetaCallback(ctx, queries, MetaCallbackAppendInput{
TaskID: snapshot.TaskID, TenantID: snapshot.TenantID, Generation: generation,
- AuthorActorID: snapshot.ResultAgentActorID, Body: body, Segments: segments,
+ AuthorActorID: authorActorID, Body: body, Segments: segments,
})
if errors.Is(err, pgx.ErrNoRows) {
return nil
diff --git a/apps/teamhub/tests/integration/task_delegation_lifecycle_test.go b/apps/teamhub/tests/integration/task_delegation_lifecycle_test.go
index f916f99f..0a95b963 100644
--- a/apps/teamhub/tests/integration/task_delegation_lifecycle_test.go
+++ b/apps/teamhub/tests/integration/task_delegation_lifecycle_test.go
@@ -449,3 +449,43 @@ func TestApprovalResultWakesDelegatedTask(t *testing.T) {
t.Fatalf("another Agent's approval result err=%v", err)
}
}
+
+func TestHumanCancelsBackgroundTask(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ env, alice, issued, roomID := newAgentCLIIdentity(t)
+ created := createDelegatedTask(t, env, issued, "human-cancel", "Draft the plan", "Draft the plan.", roomID)
+ cancelPath := "/v0/rooms/" + roomID + "/background-tasks/" + created.TaskID + "/cancel"
+
+ code, _, body := env.request(alice, http.MethodPost, cancelPath, nil, "")
+ if code != http.StatusOK || !strings.Contains(string(body), `"status":"canceled"`) {
+ t.Fatalf("cancel=%d %s", code, body)
+ }
+ // Canceling stops the Task as the Meta's task stop does.
+ assertDelegatedTaskState(t, env, created.TaskID, "canceled", "stopped")
+ if got := countRows(t, env, `SELECT count(*) FROM task_meta_callback_messages message
+ JOIN actors author ON author.id=message.author_actor_id AND author.kind='human'
+ WHERE message.task_id=$1 AND message.body LIKE '% canceled Task Draft the plan (' || $1 || ')%'`, created.TaskID); got != 1 {
+ t.Fatalf("Meta cancel notices=%d want=1", got)
+ }
+
+ // A Task that no longer runs is left alone.
+ code, _, body = env.request(alice, http.MethodPost, cancelPath, nil, "")
+ if code != http.StatusOK || !strings.Contains(string(body), `"status":"not_running"`) {
+ t.Fatalf("repeated cancel=%d %s", code, body)
+ }
+ if got := countRows(t, env, `SELECT count(*) FROM task_meta_callback_messages WHERE task_id=$1`, created.TaskID); got != 1 {
+ t.Fatalf("repeated cancel notified again: %d", got)
+ }
+
+ // The Meta can resume it.
+ started := sendDelegatedTask(t, env, issued, roomID, "human-cancel-resume", created.TaskID, "The user wants it after all.", false)
+ if started["delivery"] != "started" || started["status"] != "running" {
+ t.Fatalf("resume send=%v", started)
+ }
+
+ // Only a member of the Room reaches it.
+ code, _, body = env.request(alice, http.MethodPost, "/v0/rooms/room-missing/background-tasks/"+created.TaskID+"/cancel", nil, "")
+ if code != http.StatusNotFound {
+ t.Fatalf("cancel in unknown Room=%d %s", code, body)
+ }
+}
diff --git a/apps/web/src/features/rooms/chat/background-tasks-indicator.test.tsx b/apps/web/src/features/rooms/chat/background-tasks-indicator.test.tsx
index eb1cd5a2..297a7153 100644
--- a/apps/web/src/features/rooms/chat/background-tasks-indicator.test.tsx
+++ b/apps/web/src/features/rooms/chat/background-tasks-indicator.test.tsx
@@ -9,6 +9,7 @@ import {
import { describe, expect, it, vi } from "vitest";
import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
+import type { TestRouteRequest } from "@/test/teamhub-test-server";
import type { TeamHubRoomBackgroundTask } from "@/features/teamhub/teamhub-types";
import {
BackgroundTasksIndicator,
@@ -80,8 +81,18 @@ describe("BackgroundTasksPill", () => {
describe("BackgroundTasksIndicator", () => {
function renderIndicator(items: TeamHubRoomBackgroundTask[]) {
const { client, server } = createTestTeamHubRuntime();
- const list = vi.fn(() => ({ items }));
+ let current = items;
+ const list = vi.fn(() => ({ items: current }));
+ const cancel = vi.fn(({ params }: TestRouteRequest) => {
+ current = current.filter((task) => task.id !== params.taskId);
+ return { task_id: params.taskId, status: "canceled" };
+ });
server.on("GET", "/v0/rooms/{roomId}/background-tasks", list);
+ server.on(
+ "POST",
+ "/v0/rooms/{roomId}/background-tasks/{taskId}/cancel",
+ cancel,
+ );
const view = render(
<QueryClientProvider
client={
@@ -95,7 +106,7 @@ describe("BackgroundTasksIndicator", () => {
/>
</QueryClientProvider>,
);
- return { list, ...view };
+ return { cancel, list, ...view };
}
it("shows nothing when no background Task runs", async () => {
@@ -116,6 +127,32 @@ describe("BackgroundTasksIndicator", () => {
}),
).toBeVisible();
});
+
+ it("cancels one Task and drops it from the list", async () => {
+ const { cancel } = renderIndicator(tasks);
+ fireEvent.click(
+ await screen.findByRole("button", {
+ name: "2 tasks running in the background",
+ }),
+ );
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Cancel Draft the launch email to Lena",
+ }),
+ );
+ await waitFor(() =>
+ expect(cancel).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: { roomId: "room-1", taskId: "task-2" },
+ }),
+ ),
+ );
+ expect(
+ await screen.findByRole("button", {
+ name: "1 task running in the background",
+ }),
+ ).toBeVisible();
+ });
});
describe("runningFor", () => {
diff --git a/apps/web/src/features/rooms/chat/background-tasks-indicator.tsx b/apps/web/src/features/rooms/chat/background-tasks-indicator.tsx
index 36ba27ee..7608809e 100644
--- a/apps/web/src/features/rooms/chat/background-tasks-indicator.tsx
+++ b/apps/web/src/features/rooms/chat/background-tasks-indicator.tsx
@@ -1,16 +1,22 @@
import { ArrowUp01Icon } from "@hugeicons/core-free-icons";
+import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useId, useRef, useState } from "react";
+import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icon";
import { cn } from "@/lib/cn";
+import { teamHubData } from "@/features/teamhub/teamhub-api";
import type { TeamHubClient } from "@/features/teamhub/teamhub-client";
import type { TeamHubRoomBackgroundTask } from "@/features/teamhub/teamhub-types";
-import { useRoomBackgroundTasks } from "./use-room-background-tasks";
+import {
+ roomBackgroundTasksQueryKey,
+ useRoomBackgroundTasks,
+} from "./use-room-background-tasks";
/**
* One floating line above the composer while this Room's Meta has background
- * Tasks running. It opens a short list of what each one is doing,
- * and disappears once every Task is done.
+ * Tasks running. It opens a short list of what each one is doing, where
+ * each can be canceled, and disappears once every Task is done.
*/
export function BackgroundTasksIndicator({
client,
@@ -21,21 +27,35 @@ export function BackgroundTasksIndicator({
roomId: string;
tenantId: string;
}) {
+ const queryClient = useQueryClient();
const tasks = useRoomBackgroundTasks({ client, roomId, tenantId });
if (!tasks.length) return null;
+ const cancel = async (taskId: string) => {
+ await teamHubData(
+ client.api.POST("/v0/rooms/{roomId}/background-tasks/{taskId}/cancel", {
+ params: { path: { roomId, taskId } },
+ }),
+ );
+ await queryClient.invalidateQueries({
+ queryKey: roomBackgroundTasksQueryKey(tenantId, roomId),
+ });
+ };
return (
// Floats over the bottom of the timeline instead of pushing the composer.
<div className="relative h-0">
- <BackgroundTasksPill tasks={tasks} />
+ <BackgroundTasksPill onCancel={cancel} tasks={tasks} />
</div>
);
}
export function BackgroundTasksPill({
now = Date.now(),
+ onCancel,
tasks,
}: {
now?: number;
+ /** Stops one Task; it settles once the Task has left the list. */
+ onCancel?: (taskId: string) => Promise<void>;
tasks: readonly TeamHubRoomBackgroundTask[];
}) {
const [open, setOpen] = useState(false);
@@ -74,7 +94,7 @@ export function BackgroundTasksPill({
<ul className="flex flex-col">
{tasks.map((task) => (
<li
- className="grid grid-cols-[6px_minmax(0,1fr)_auto] items-baseline gap-x-2.5 rounded-md px-2 py-1.5 hover:bg-muted"
+ className="grid grid-cols-[6px_minmax(0,1fr)_auto_auto] items-baseline gap-x-2.5 rounded-md px-2 py-1.5 hover:bg-muted"
key={task.id}
>
<span
@@ -87,6 +107,14 @@ export function BackgroundTasksPill({
<span className="text-[12px] leading-[18px] text-app-muted tabular-nums">
{runningFor(task.created_at, now)}
</span>
+ <span className="row-span-2 self-center">
+ {onCancel ? (
+ <CancelTaskButton
+ cancel={() => onCancel(task.id)}
+ title={task.title}
+ />
+ ) : null}
+ </span>
<span className="col-span-2 col-start-2 truncate text-[12px] leading-[18px] text-app-muted">
{task.requirement}
</span>
@@ -122,6 +150,50 @@ export function BackgroundTasksPill({
);
}
+/**
+ * Cancels one Task's current turn. The Room's Meta is told and can resume
+ * it later, so no confirmation is asked.
+ */
+function CancelTaskButton({
+ cancel,
+ title,
+}: {
+ cancel: () => Promise<void>;
+ title: string;
+}) {
+ const [state, setState] = useState<"idle" | "pending" | "error">("idle");
+ return (
+ <Button
+ aria-label={
+ state === "error"
+ ? `Cancel of ${title} was not confirmed; retry`
+ : `Cancel ${title}`
+ }
+ className={cn(
+ "h-7 px-1.5 text-[12px] font-medium hover:bg-transparent hover:text-app-danger",
+ state === "error" ? "text-app-danger" : "text-app-muted",
+ )}
+ disabled={state === "pending"}
+ onClick={() => {
+ setState("pending");
+ cancel().then(
+ () => setState("idle"),
+ () => setState("error"),
+ );
+ }}
+ size="compact"
+ tone="ghost"
+ type="button"
+ >
+ {state === "pending"
+ ? "Canceling"
+ : state === "error"
+ ? "Retry"
+ : "Cancel"}
+ </Button>
+ );
+}
+
/** How long a Task has been running, in the coarsest unit that fits. */
export function runningFor(createdAt: string, now: number) {
const minutes = Math.max(
diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.go
index 81327411..25c4d89f 100644
--- a/contracts/generated/go/teamhubpublic/openapi.gen.go
+++ b/contracts/generated/go/teamhubpublic/openapi.gen.go
@@ -2414,6 +2414,24 @@ func (e ReferenceSegmentTargetType) Valid() bool {
}
}
+// Defines values for RoomBackgroundTaskCancelResultStatus.
+const (
+ RoomBackgroundTaskCancelResultStatusCanceled RoomBackgroundTaskCancelResultStatus = "canceled"
+ RoomBackgroundTaskCancelResultStatusNotRunning RoomBackgroundTaskCancelResultStatus = "not_running"
+)
+
+// Valid indicates whether the value is a known member of the RoomBackgroundTaskCancelResultStatus enum.
+func (e RoomBackgroundTaskCancelResultStatus) Valid() bool {
+ switch e {
+ case RoomBackgroundTaskCancelResultStatusCanceled:
+ return true
+ case RoomBackgroundTaskCancelResultStatusNotRunning:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for RoomDocumentChangedPayloadKind.
const (
RoomDocumentChangedPayloadKindDocumentCreated RoomDocumentChangedPayloadKind = "document.created"
@@ -2887,19 +2905,19 @@ func (e SlackConversationKind) Valid() bool {
// Defines values for TaskAttemptSummaryStatus.
const (
- Passed TaskAttemptSummaryStatus = "passed"
- Running TaskAttemptSummaryStatus = "running"
- Stopped TaskAttemptSummaryStatus = "stopped"
+ TaskAttemptSummaryStatusPassed TaskAttemptSummaryStatus = "passed"
+ TaskAttemptSummaryStatusRunning TaskAttemptSummaryStatus = "running"
+ TaskAttemptSummaryStatusStopped TaskAttemptSummaryStatus = "stopped"
)
// Valid indicates whether the value is a known member of the TaskAttemptSummaryStatus enum.
func (e TaskAttemptSummaryStatus) Valid() bool {
switch e {
- case Passed:
+ case TaskAttemptSummaryStatusPassed:
return true
- case Running:
+ case TaskAttemptSummaryStatusRunning:
return true
- case Stopped:
+ case TaskAttemptSummaryStatusStopped:
return true
default:
return false
@@ -6515,6 +6533,16 @@ type RoomBackgroundTask struct {
Title string `json:"title"`
}
+// RoomBackgroundTaskCancelResult defines model for RoomBackgroundTaskCancelResult.
+type RoomBackgroundTaskCancelResult struct {
+ // Status canceled when this request stopped the Task; not_running when it was no longer running, so nothing changed.
+ Status RoomBackgroundTaskCancelResultStatus `json:"status"`
+ TaskId string `json:"task_id"`
+}
+
+// RoomBackgroundTaskCancelResultStatus canceled when this request stopped the Task; not_running when it was no longer running, so nothing changed.
+type RoomBackgroundTaskCancelResultStatus string
+
// RoomBackgroundTaskList defines model for RoomBackgroundTaskList.
type RoomBackgroundTaskList struct {
// Items Oldest first. Waiting for an approval counts as running; a Task leaves the list once it is idle, failed or canceled.
diff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.ts
index 701c996e..aea4d77d 100644
--- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts
+++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts
@@ -739,6 +739,26 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/v0/rooms/{roomId}/background-tasks/{taskId}/cancel": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Cancel one background Task's current turn
+ * @description Stops the Task as its Meta's task stop does: the current turn ends and its approval cards expire, but its session and playground stay, so the Meta can resume it later. The Room's Meta is told who canceled it. Canceling a Task that is no longer running changes nothing.
+ */
+ post: operations["cancelRoomBackgroundTask"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/v0/rooms/{roomId}/runs/{runId}/cancel": {
parameters: {
query?: never;
@@ -5184,6 +5204,14 @@ export interface components {
/** @description Oldest first. Waiting for an approval counts as running; a Task leaves the list once it is idle, failed or canceled. */
items: components["schemas"]["RoomBackgroundTask"][];
};
+ RoomBackgroundTaskCancelResult: {
+ task_id: string;
+ /**
+ * @description canceled when this request stopped the Task; not_running when it was no longer running, so nothing changed.
+ * @enum {string}
+ */
+ status: "canceled" | "not_running";
+ };
RoomRunCancelRequest: {
request_id: components["schemas"]["IdempotencyKey"];
};
@@ -8924,6 +8952,32 @@ export interface operations {
404: components["responses"]["NotFound"];
};
};
+ cancelRoomBackgroundTask: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ roomId: string;
+ taskId: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The Task's state after the request. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["RoomBackgroundTaskCancelResult"];
+ };
+ };
+ 401: components["responses"]["Unauthenticated"];
+ 404: components["responses"]["NotFound"];
+ 409: components["responses"]["Conflict"];
+ };
+ };
cancelRoomRun: {
parameters: {
query?: never;
diff --git a/contracts/openapi/components/room-run-control.yaml b/contracts/openapi/components/room-run-control.yaml
index e451db77..26466dda 100644
--- a/contracts/openapi/components/room-run-control.yaml
+++ b/contracts/openapi/components/room-run-control.yaml
@@ -42,6 +42,17 @@ components:
description: Oldest first. Waiting for an approval counts as running; a Task leaves the list once it is idle, failed or canceled.
items:
$ref: "#/components/schemas/RoomBackgroundTask"
+ RoomBackgroundTaskCancelResult:
+ type: object
+ additionalProperties: false
+ required: [task_id, status]
+ properties:
+ task_id:
+ type: string
+ status:
+ type: string
+ description: canceled when this request stopped the Task; not_running when it was no longer running, so nothing changed.
+ enum: [canceled, not_running]
RoomRunCancelRequest:
type: object
additionalProperties: false
diff --git a/contracts/openapi/paths/room-run-control.yaml b/contracts/openapi/paths/room-run-control.yaml
index ece6e511..f6b3402d 100644
--- a/contracts/openapi/paths/room-run-control.yaml
+++ b/contracts/openapi/paths/room-run-control.yaml
@@ -40,6 +40,39 @@ backgroundTasks:
$ref: "../components/common.yaml#/components/responses/Unauthenticated"
"404":
$ref: "../components/common.yaml#/components/responses/NotFound"
+cancelBackgroundTask:
+ post:
+ operationId: cancelRoomBackgroundTask
+ summary: Cancel one background Task's current turn
+ description: >-
+ Stops the Task as its Meta's task stop does: the current turn ends and
+ its approval cards expire, but its session and playground stay, so the
+ Meta can resume it later. The Room's Meta is told who canceled it.
+ Canceling a Task that is no longer running changes nothing.
+ parameters:
+ - name: roomId
+ in: path
+ required: true
+ schema:
+ type: string
+ - name: taskId
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ "200":
+ description: The Task's state after the request.
+ content:
+ application/json:
+ schema:
+ $ref: "../components/room-run-control.yaml#/components/schemas/RoomBackgroundTaskCancelResult"
+ "401":
+ $ref: "../components/common.yaml#/components/responses/Unauthenticated"
+ "404":
+ $ref: "../components/common.yaml#/components/responses/NotFound"
+ "409":
+ $ref: "../components/common.yaml#/components/responses/Conflict"
cancelRun:
post:
operationId: cancelRoomRun
diff --git a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
index b90aea69..40fdf1f5 100644
--- a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
+++ b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
@@ -1224,6 +1224,8 @@ paths:
$ref: '../paths/room-run-control.yaml#/tenantRoomActivity'
/v0/rooms/{roomId}/background-tasks:
$ref: '../paths/room-run-control.yaml#/backgroundTasks'
+ /v0/rooms/{roomId}/background-tasks/{taskId}/cancel:
+ $ref: '../paths/room-run-control.yaml#/cancelBackgroundTask'
/v0/rooms/{roomId}/runs/{runId}/cancel:
$ref: '../paths/room-run-control.yaml#/cancelRun'
/v0/rooms/{roomId}/runs/{runId}/redeliver-unconfirmed-inputs:
diff --git a/docs/task-delegation.md b/docs/task-delegation.md
index b155a173..773f3e9e 100644
--- a/docs/task-delegation.md
+++ b/docs/task-delegation.md
@@ -11,18 +11,20 @@ conversation goes on.
![An animation of two Tasks running side by side: you ask Another Me to research Acme's rivals, then to draft a deck; its Meta starts a Task for each with task create, each AlterEgo's Task grows while it runs, a follow-up about the new logo joins the deck Task, and each result comes back into the chat as a card when its AlterEgo reports](../assets/feature-task-chat.gif)
-| Moment | Task state | Who wakes |
-| ------------------------------------------------------------ | -------------------------------------------- | ---------------------------------------- |
-| An AlterEgo finishes a turn | `idle` | The Meta, with that turn's last reply |
-| A turn ends while an approval card waits in your chat | `waiting_for_approval` | No one, until the card is answered |
-| You approve or deny the card, or it expires after 10 minutes | `running` | The AlterEgo |
-| A turn fails | `failed` | The Meta, with the error |
-| You add to the request, while it runs or after it is done | `running`, or queued behind the current turn | The AlterEgo |
-| You ask how it is going | Unchanged | No one; the Meta reads the Task's status |
-| You ask to stop it | `canceled`, with its files and session kept | No one |
-
-<sub>An AlterEgo never asks you anything; a question goes into its report, and
-the Meta decides whether to ask.</sub>
+| Moment | Task state | Who wakes |
+| -------------------------------------------------------------- | -------------------------------------------- | ---------------------------------------- |
+| An AlterEgo finishes a turn | `idle` | The Meta, with that turn's last reply |
+| A turn ends while an approval card waits in your chat | `waiting_for_approval` | No one, until the card is answered |
+| You approve or deny the card, or it expires after 10 minutes | `running` | The AlterEgo |
+| A turn fails | `failed` | The Meta, with the error |
+| You add to the request, while it runs or after it is done | `running`, or queued behind the current turn | The AlterEgo |
+| You ask how it is going | Unchanged | No one; the Meta reads the Task's status |
+| You ask to stop it | `canceled`, with its files and session kept | No one |
+| You press Cancel on it under _tasks running in the background_ | `canceled`, with its files and session kept | The Meta, told that you canceled it |
+
+<sub>A canceled Task is paused, not closed: the Meta can resume it with your
+next request or do something else. An AlterEgo never asks you anything; a
+question goes into its report, and the Meta decides whether to ask.</sub>
## On the computer