Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Delete closed threads: judge closed state per thread and on the server
AdityaUmale725b56141e8e
diff --git a/server/bulk-delete-tasks.e2e.test.ts b/server/bulk-delete-tasks.e2e.test.tsindex d073324dbf..a66380b348 100644--- a/server/bulk-delete-tasks.e2e.test.ts+++ b/server/bulk-delete-tasks.e2e.test.ts@@ -138,6 +138,20 @@ posixOnly("bulk delete tasks e2e", () => {await waitUntil(async () => (await getBot(bot.id))?.busy === false, 15_000, "turn never finished");});+ it("a closed-only delete keeps a thread that is not closed when the request arrives", async () => {+ const bot = await newBot("Bulk Closed");+ const open = await newTask(bot.id);++ const res = await api("POST", `/api/bots/${bot.id}/tasks/delete`, { threadIds: [open], scope: "closed" });++ expect(res.status, JSON.stringify(res.body)).toBe(200);+ expect(res.body.deleted).toEqual([]);+ expect(res.body.refused).toEqual([{ threadId: open, reason: "not-closed" }]);+ expect(await taskIds(bot.id)).toContain(open);+ expect((await api("POST", `/api/bots/${bot.id}/tasks/delete`, { threadIds: [open], scope: "open" })).status).toBe(400);+ expect(await taskIds(bot.id)).toContain(open);+ });+it("rejects malformed bodies and unknown bots", async () => {const bot = await newBot("Bulk D");const url = `/api/bots/${bot.id}/tasks/delete`;@@ -203,6 +217,19 @@ posixOnly("bulk delete tasks e2e", () => {await waitUntil(async () => (await api("GET", "/api/bots")).body.groups.find((g: any) => g.id === room.id)?.working === false, 15_000, "room turn never finished");});+ it("a closed-only channel delete keeps a thread that is not closed", async () => {+ const bot = await newBot("Bulk Closed Room");+ const room = await newRoom("Bulk room closed", bot);+ const second = (await api("POST", `/api/groups/${room.id}/tasks`, {})).body.task.threadId;++ const res = await api("POST", `/api/groups/${room.id}/tasks/delete`, { threadIds: [second], scope: "closed" });++ expect(res.status, JSON.stringify(res.body)).toBe(200);+ expect(res.body.deleted).toEqual([]);+ expect(res.body.refused).toEqual([{ threadId: second, reason: "not-closed" }]);+ expect((await roomTaskIds(room.id)).sort()).toEqual([room.threadId, second].sort());+ });+it("rejects malformed channel bodies, unknown channels and bot-to-bot channels", async () => {const bot = await newBot("Bulk H");const room = await newRoom("Bulk room 3", bot);diff --git a/server/routes/bulk-delete.test.ts b/server/routes/bulk-delete.test.tsnew file mode 100644index 0000000000..f04f879f40--- /dev/null+++ b/server/routes/bulk-delete.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from "vitest";+import { bulkDeleteThreadIds, outsideClosedScope } from "./bulk-delete.ts";++describe("bulkDeleteThreadIds scope", () => {+ it("defaults to every listed thread and accepts a closed-only scope", () => {+ expect(bulkDeleteThreadIds({ threadIds: ["a", "a", "b"] })).toEqual({ ok: true, threadIds: ["a", "b"], scope: "all" });+ expect(bulkDeleteThreadIds({ threadIds: ["a"], scope: "closed" })).toEqual({ ok: true, threadIds: ["a"], scope: "closed" });+ });++ it("refuses an unknown scope", () => {+ expect(bulkDeleteThreadIds({ threadIds: ["a"], scope: "open" })).toMatchObject({ ok: false });+ expect(bulkDeleteThreadIds({ threadIds: ["a"], scope: 1 })).toMatchObject({ ok: false });+ });+});++describe("outsideClosedScope", () => {+ const closedBy = { botId: "helper", name: "Helper", at: 1 };+ it("lets only a closed, unpinned thread through", () => {+ expect(outsideClosedScope({ closedBy })).toBe(false);+ expect(outsideClosedScope({ closedBy, pinned: true })).toBe(true);+ expect(outsideClosedScope({})).toBe(true);+ expect(outsideClosedScope(null)).toBe(true);+ expect(outsideClosedScope(undefined)).toBe(true);+ });+});diff --git a/server/routes/bulk-delete.ts b/server/routes/bulk-delete.tsindex 509699e3c8..9450bb3c7f 100644--- a/server/routes/bulk-delete.ts+++ b/server/routes/bulk-delete.ts@@ -1,14 +1,20 @@export const MAX_BULK_DELETE_THREADS = 500;-export type BulkDeleteRefusal = { threadId: string; reason: "not-found" | "busy" };+export type BulkDeleteRefusal = { threadId: string; reason: "not-found" | "busy" | "not-closed" };+export type BulkDeleteScope = "all" | "closed";-/** The distinct thread ids of a bulk delete body, or the 400 error to answer with. */-export function bulkDeleteThreadIds(body: unknown): { ok: true; threadIds: string[] } | { ok: false; error: string } {+/** A "closed" delete takes a thread only while it is still closed and not pinned, judged when the request arrives. */+export const outsideClosedScope = (task: { closedBy?: unknown; pinned?: boolean } | null | undefined): boolean => !task?.closedBy || task.pinned === true;++/** The distinct thread ids and scope of a bulk delete body, or the 400 error to answer with. */+export function bulkDeleteThreadIds(body: unknown): { ok: true; threadIds: string[]; scope: BulkDeleteScope } | { ok: false; error: string } {if (!body || typeof body !== "object" || Array.isArray(body)) return { ok: false, error: "body must be a JSON object" };const ids = (body as { threadIds?: unknown }).threadIds;if (!Array.isArray(ids) || ids.length === 0 || ids.length > MAX_BULK_DELETE_THREADS|| ids.some((id) => typeof id !== "string" || id === "")) {return { ok: false, error: `threadIds must be 1-${MAX_BULK_DELETE_THREADS} thread ids` };}- return { ok: true, threadIds: [...new Set(ids as string[])] };+ const scope = (body as { scope?: unknown }).scope ?? "all";+ if (scope !== "all" && scope !== "closed") return { ok: false, error: "scope must be \"all\" or \"closed\"" };+ return { ok: true, threadIds: [...new Set(ids as string[])], scope };}diff --git a/server/routes/channels.ts b/server/routes/channels.tsindex 99ad98cf86..8590ab6c14 100644--- a/server/routes/channels.ts+++ b/server/routes/channels.ts@@ -38,7 +38,7 @@ import type { UsageTrigger } from "../usage-ledger.ts";import { parseMentionPicks } from "../../shared/room-mentions.ts";import { sameNameRefusal, sameNameRefusalForBots } from "../same-name-mentions.ts";import { conversationLanguage } from "../server-lines.ts";-import { bulkDeleteThreadIds, type BulkDeleteRefusal } from "./bulk-delete.ts";+import { bulkDeleteThreadIds, outsideClosedScope, type BulkDeleteRefusal } from "./bulk-delete.ts";import { FORK_BUSY, FORK_NO_TEXT, parseForkRequest } from "./fork-request.ts";import { PASS, type RouteHandler } from "./table.ts";import { sawThread } from "../thread-presence.ts";@@ -217,8 +217,9 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {const refused: BulkDeleteRefusal[] = [];for (const threadId of parsed.threadIds) {const refusal = deleteRefusal(auth, group.id, threadId);- if (!refusal) allowed.push(threadId);- else refused.push({ threadId, reason: refusal.status === 409 ? "busy" : "not-found" });+ if (refusal) refused.push({ threadId, reason: refusal.status === 409 ? "busy" : "not-found" });+ else if (parsed.scope === "closed" && outsideClosedScope(store.groupTaskByThread(group.id, threadId))) refused.push({ threadId, reason: "not-closed" });+ else allowed.push(threadId);}if (allowed.length >= (group.tasks?.length ?? 1)) return json(res, 400, { error: "a channel keeps at least one task" });const result = deleteGroupTasks(group.id, allowed);diff --git a/server/routes/tasks.ts b/server/routes/tasks.tsindex 5703b4f30e..b5771c332d 100644--- a/server/routes/tasks.ts+++ b/server/routes/tasks.ts@@ -15,7 +15,7 @@ import { parseSurface } from "../surface.ts";import type { ThreadStarters } from "../thread-starters.ts";import { titleConversationExcerpt, type ThreadTitleSource } from "../thread-title.ts";import type { MessagePage } from "./channels.ts";-import { bulkDeleteThreadIds, type BulkDeleteRefusal } from "./bulk-delete.ts";+import { bulkDeleteThreadIds, outsideClosedScope, type BulkDeleteRefusal } from "./bulk-delete.ts";import { FORK_BUSY, FORK_NO_TEXT, parseForkRequest } from "./fork-request.ts";import { PASS, type RouteHandler } from "./table.ts";import { madeThread, sawThread } from "../thread-presence.ts";@@ -230,8 +230,9 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTaconst refused: BulkDeleteRefusal[] = [];for (const threadId of parsed.threadIds) {const refusal = deleteRefusal(auth, bot.id, threadId);- if (!refusal) allowed.push(threadId);- else refused.push({ threadId, reason: refusal.status === 409 ? "busy" : "not-found" });+ if (refusal) refused.push({ threadId, reason: refusal.status === 409 ? "busy" : "not-found" });+ else if (parsed.scope === "closed" && outsideClosedScope(store.taskByThread(bot.id, threadId))) refused.push({ threadId, reason: "not-closed" });+ else allowed.push(threadId);}const result = deleteTasks(bot.id, allowed);if (!result) return json(res, 404, { error: "no such bot" });diff --git a/src/components/BotMenuDelete.test.ts b/src/components/BotMenuDelete.test.tsindex 3466017178..4c79c1e8a8 100644--- a/src/components/BotMenuDelete.test.ts+++ b/src/components/BotMenuDelete.test.ts@@ -76,7 +76,27 @@ describe("delete closed threads", () => {await deleteAllThreads(closedBot, dispatch, "closed");- expect(post).toHaveBeenLastCalledWith("/api/bots/maus/tasks/delete", { method: "POST", body: JSON.stringify({ threadIds: ["done", "old"] }) });+ expect(post).toHaveBeenLastCalledWith("/api/bots/maus/tasks/delete", { method: "POST", body: JSON.stringify({ threadIds: ["done", "old"], scope: "closed" }) });expect(dispatch).toHaveBeenLastCalledWith({ type: "notice", notice: { kind: "note", botName: null, text: "Deleted: 2." } });});++ it("keeps an idle closed thread selectable while the bot works in another thread", () => {+ const working = { ...closedBot, busy: true, activity: "working" as const };+ expect(closedThreadRows(allThreadRows(working)).map((row) => row.threadId)).toEqual(["done", "old"]);+ });++ it("still leaves out a closed thread that is itself running", () => {+ const tasks = closedBot.tasks!.map((task) => (task.threadId === "done" ? { ...task, activity: "working" as const } : task));+ expect(closedThreadRows(allThreadRows({ ...closedBot, tasks })).map((row) => row.threadId)).toEqual(["old"]);+ });++ it("says how many were kept because they were reopened or pinned meanwhile", async () => {+ const post = vi.mocked(api);+ post.mockResolvedValueOnce({ deleted: ["old"], refused: [{ threadId: "done", reason: "not-closed" }], bot: { id: "maus" } });+ const dispatch = vi.fn();++ await deleteAllThreads(closedBot, dispatch, "closed");++ expect(dispatch).toHaveBeenLastCalledWith({ type: "notice", notice: { kind: "note", botName: null, text: "Deleted: 1. Kept because they were reopened or pinned: 1." } });+ });});diff --git a/src/components/BotMenuDelete.tsx b/src/components/BotMenuDelete.tsxindex e7f28f3e59..9af3efb4b5 100644--- a/src/components/BotMenuDelete.tsx+++ b/src/components/BotMenuDelete.tsx@@ -29,6 +29,8 @@ export function BotDeleteMenuItem({ deleting, onClick, className = "flex w-fullexport function allThreadRows(bot: Bot) {return (bot.tasks ?? []).filter((task) => !task.routineRunId).map((task) => {+ // A closed thread keeps its own state: the bot working in another thread must not make it look running.+ if (task.closedBy) return { ...task, busy: task.busy ?? (task.activity === "working" || task.activity === "waiting-on-you"), activity: task.activity };const thread = currentTaskBot(bot, task.threadId);return { ...task, busy: thread.busy, activity: thread.activity };});@@ -44,7 +46,7 @@ export const closedThreadRows = (rows: ThreadRows): ThreadRows =>const scopedRows = (rows: ThreadRows, scope: DeleteScope): ThreadRows => (scope === "closed" ? closedThreadRows(rows) : rows);export async function deleteAllThreads(bot: Bot, dispatch: Dispatch, scope: DeleteScope = "all"): Promise<void> {- const outcome = await deleteThreadsInBulk({ botId: bot.id }, scopedRows(allThreadRows(bot), scope).map((row) => row.threadId), dispatch);+ const outcome = await deleteThreadsInBulk({ botId: bot.id }, scopedRows(allThreadRows(bot), scope).map((row) => row.threadId), dispatch, scope);dispatch({ type: "notice", notice: { kind: "note", botName: null, text: bulkDeleteOutcome(outcome) } });}diff --git a/src/components/BulkSelectBar.tsx b/src/components/BulkSelectBar.tsxindex 9ef9a12b13..891d5be380 100644--- a/src/components/BulkSelectBar.tsx+++ b/src/components/BulkSelectBar.tsx@@ -8,12 +8,12 @@ export type BulkDeleteResult = { responses: DeleteResponse[]; error?: string };type Selection = ReadonlySet<string>;/** One request per chunk, in order; a failed chunk stops the rest, and earlier chunks stay deleted. */-export async function deleteThreadsInBulk(owner: { botId: string } | { groupId: string }, threadIds: string[], dispatch: (action: Action) => void): Promise<BulkDeleteResult> {+export async function deleteThreadsInBulk(owner: { botId: string } | { groupId: string }, threadIds: string[], dispatch: (action: Action) => void, scope: "all" | "closed" = "all"): Promise<BulkDeleteResult> {const url = "botId" in owner ? `/api/bots/${owner.botId}/tasks/delete` : `/api/groups/${owner.groupId}/tasks/delete`;const responses: DeleteResponse[] = [];try {for (const part of chunkIds(threadIds)) {- const response = await api<DeleteResponse & { bot?: BotAnnouncement; group?: Partial<Group> & { id: string } }>(url, { method: "POST", body: JSON.stringify({ threadIds: part }) });+ const response = await api<DeleteResponse & { bot?: BotAnnouncement; group?: Partial<Group> & { id: string } }>(url, { method: "POST", body: JSON.stringify(scope === "closed" ? { threadIds: part, scope } : { threadIds: part }) });responses.push(response);if (response.bot) dispatch({ type: "botPatched", bot: response.bot });if (response.group) dispatch({ type: "groupPatched", group: response.group });@@ -66,6 +66,7 @@ export function bulkDeleteOutcome(outcome: BulkDeleteResult): string {t("task.bulk.result", { count: done.deleted }),done.busy > 0 ? t("task.bulk.resultBusy", { count: done.busy }) : null,done.missing > 0 ? t("task.bulk.resultMissing", { count: done.missing }) : null,+ done.notClosed > 0 ? t("task.bulk.resultNotClosed", { count: done.notClosed }) : null,outcome.error ? t("task.bulk.resultError", { message: outcome.error }) : null,].filter(Boolean).join(" ");}diff --git a/src/lib/bulk-select.test.ts b/src/lib/bulk-select.test.tsindex 8952cb9b41..83c46747bb 100644--- a/src/lib/bulk-select.test.ts+++ b/src/lib/bulk-select.test.ts@@ -103,7 +103,10 @@ describe("summarizeDelete", () => {{ deleted: ["a", "b"], refused: [{ threadId: "c", reason: "busy" }] },{ deleted: ["d"], refused: [{ threadId: "e", reason: "not-found" }, { threadId: "f", reason: "busy" }] },]);- expect(summary).toEqual({ deleted: 3, busy: 2, missing: 1 });+ expect(summary).toEqual({ deleted: 3, busy: 2, missing: 1, notClosed: 0 });+ });+ it("counts threads a closed-only delete kept because they were no longer closed", () => {+ expect(summarizeDelete([{ deleted: ["a"], refused: [{ threadId: "b", reason: "not-closed" }] }])).toEqual({ deleted: 1, busy: 0, missing: 0, notClosed: 1 });});});diff --git a/src/lib/bulk-select.ts b/src/lib/bulk-select.tsindex 7adc63f89a..b1f1fca7c6 100644--- a/src/lib/bulk-select.ts+++ b/src/lib/bulk-select.ts@@ -8,7 +8,7 @@ export type SelectableRow = {createdAt?: number;};-export type DeleteRefusal = { threadId: string; reason: "not-found" | "busy" };+export type DeleteRefusal = { threadId: string; reason: "not-found" | "busy" | "not-closed" };export type DeleteResponse = { deleted: string[]; refused: DeleteRefusal[] };export const BULK_DELETE_CHUNK = 200;@@ -75,12 +75,12 @@ export function chunkIds(ids: readonly string[], size = BULK_DELETE_CHUNK): strireturn chunks;}-export function summarizeDelete(responses: readonly DeleteResponse[]): { deleted: number; busy: number; missing: number } {- const summary = { deleted: 0, busy: 0, missing: 0 };+export function summarizeDelete(responses: readonly DeleteResponse[]): { deleted: number; busy: number; missing: number; notClosed: number } {+ const summary = { deleted: 0, busy: 0, missing: 0, notClosed: 0 };for (const response of responses) {summary.deleted += response.deleted.length;for (const refusal of response.refused) {- if (refusal.reason === "busy") summary.busy++; else summary.missing++;+ if (refusal.reason === "busy") summary.busy++; else if (refusal.reason === "not-closed") summary.notClosed++; else summary.missing++;}}return summary;diff --git a/src/locales/en.json b/src/locales/en.jsonindex 408b9ae643..1752a79082 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -3425,6 +3425,7 @@"task.bulk.result": "Deleted: {count}.","task.bulk.resultBusy": "Kept because they are running: {count}.","task.bulk.resultMissing": "Already gone: {count}.",+ "task.bulk.resultNotClosed": "Kept because they were reopened or pinned: {count}.","task.bulk.resultError": "Stopped early: {message}","task.bulk.retitle": "Name by content","task.bulk.retitling": "Naming…",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex ff21d52d1f..c390166ec0 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -3212,6 +3212,7 @@"task.bulk.result": "Excluídas: {count}.","task.bulk.resultBusy": "Mantidas por estarem em andamento: {count}.","task.bulk.resultMissing": "Conversas que já não existiam: {count}.",+ "task.bulk.resultNotClosed": "Mantidas por terem sido reabertas ou fixadas: {count}.","task.bulk.resultError": "Parou antes do fim: {message}","task.bulk.retitle": "Nomear pelo conteúdo","task.bulk.retitling": "Nomeando…",