diff --git a/AGENTS.md b/AGENTS.md index 5b60b81a..f81a8950 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -127,7 +127,7 @@ Server push only. `pushBotNotice` (`server:bot-message`, `server:bot-updated`), ### Chatrooms (`chatrooms`) -A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions; their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces//chatrooms[/]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one. Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`). +A worker reaches another worker **only through the coordinator**: `ask_crew` (every worker run except hook calls; never the coordinator) opens a room (`createChatroom`) for the run's user and place. Who can be asked is the app's call (`chatroomAskableBots`): in a workspace its members, else every worker the user reaches. Every bot in a room has a hidden session there (`bot_sessions.chatroom_id`, status `chatroom`) holding its messages and jobs; **every session query that lists or picks a conversation must exclude them** (`chatroom_id IS NULL`, and hook sessions the same way). The coordinator's turns are queued straight onto the queue (`enqueueChatroomTurn`, it works for a member there) and run by `runChatroomTurn` with only `ask_member`/`answer_requester`/`refuse_request`, the room fenced as data (`chatroomTurns`). A room job ending (`onChatroomJobEnded`, from complete/fail) wakes the coordinator; closing (`closeChatroom`, once) cancels what's open and posts the outcome into the asking bot's session as a user-side message with `from_chatroom_id` (fenced for the model, shown as from the coordinator) and wakes it, except when stopped. Caps: `AppData.ChatroomMaxCoordinatorTurns`, `ChatroomMaxDepth` (nested rooms, `parent_chatroom_id`; a bot waiting up the chain can't be asked), `ChatroomMaxOpenPerBot`. Room jobs never change faces or name sessions; their messages push as `server:chatroom-message`/`server:chatroom-updated`, never as notifications. Rooms are read-only records kept per place, like conversations: a workspace's open under it (`/admin/workspaces//chatrooms[/]`, listed in the workspace rail after its bots), the rest under `/admin/chatrooms` (after the workspaces in the main rail); links go through `chatroomHref` and a room opened at the wrong place redirects. The rail loads its section itself (`api/admin/chatrooms/list?workspace_id=`); `[room:ID]` chip. The user can only Stop one, or Try again once it's `failed` or `stopped` (`retryChatroom`: the same room reopened with its turn budget reset and a note as the asking bot's message, since the room's turns must end on a non-coordinator one; refused past the open cap or when a nested room's parent closed; a stopped room's outcome doesn't wake the bot, so `chatroomHoldsReply` keeps the thinking row away). Under the thread an open room shows where each bot stands (`chatroomBotStatuses`, from the summary's open `jobs` plus live `server:bot-job-update` steps), and so does the asking bot's conversation, linked to the room (`useConversationChatrooms`, `?requester_bot_id=` on the list, refetched on reconnect); bots' faces stay out of it. **Retention:** closed rooms go after the app setting `chatroom_keep_days` (daily `prune-chatrooms`) and past `chatroom_max_per_place` rooms per place (also pruned as each room closes), oldest first (`pruneChatroomsSql`; open rooms and rooms an open one was asked from are never pruned; deletion through `deleteChatroomRows`). ### Workspaces diff --git a/src/components/general/chatroom-retry-button.tsx b/src/components/general/chatroom-retry-button.tsx new file mode 100644 index 00000000..0f3d2424 --- /dev/null +++ b/src/components/general/chatroom-retry-button.tsx @@ -0,0 +1,58 @@ +import { useContext, useState } from "react"; +import { RotateCcw } from "lucide-react"; +import Button from "@moduletrace/twui/layout/Button"; +import HeaderIconButton from "@/src/components/general/header-icon-button"; +import retryChatroomRequest from "@/src/functions/frontend/retry-chatroom-request"; +import { AppContext } from "@/src/pages/__root"; +import type { ChatroomSummary } from "@/src/types"; +import canRetryChatroom from "@/src/utils/can-retry-chatroom"; +import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user"; + +type Props = { + chatroom: Pick; + /** + * Say it in words, for a button sitting in a message. + */ + labelled?: boolean; +}; + +/** + * Tries a failed or stopped request again after a confirm. Shows nothing + * for any other room, or for a user who can only read. + */ +export default function ChatroomRetryButton({ chatroom, labelled }: Props) { + const { pageProps } = useContext(AppContext); + const [loading, setLoading] = useState(false); + + if (!canRetryChatroom({ chatroom })) return null; + if (isReadOnlyUser({ user_types: pageProps?.user_types || [] })) return null; + + const retry = async () => { + if (!window.confirm(`Try this request again? The coordinator picks it up from what was already said.`)) return; + + setLoading(true); + const res = await retryChatroomRequest({ chatroom_id: Number(chatroom.id) }).catch(() => null); + setLoading(false); + + if (!res?.success) window.alert(res?.msg || `Couldn't try it again.`); + }; + + if (!labelled) { + return ; + } + + return ( + + ); +} diff --git a/src/dict/chatroom-dict.ts b/src/dict/chatroom-dict.ts index 1e7dfe9f..bd8942b7 100644 --- a/src/dict/chatroom-dict.ts +++ b/src/dict/chatroom-dict.ts @@ -27,6 +27,12 @@ export const ChatroomStatuses = [ export type ChatroomStatus = (typeof ChatroomStatuses)[number]["value"]; +/** + * Rooms that ended without an answer because something went wrong or the + * user stopped them, which the user can try again. A refusal is an answer. + */ +export const ChatroomRetryableStatuses: ChatroomStatus[] = ["failed", "stopped"]; + /** * The title of the coordinator's turns in a room, on its jobs. */ diff --git a/src/functions/backend/db/chatrooms/grab-user-chatrooms.ts b/src/functions/backend/db/chatrooms/grab-user-chatrooms.ts index c62a185f..b251a505 100644 --- a/src/functions/backend/db/chatrooms/grab-user-chatrooms.ts +++ b/src/functions/backend/db/chatrooms/grab-user-chatrooms.ts @@ -14,24 +14,37 @@ type Params = { * bots' own chats. Left out, every room. */ workspace_id?: number | null; + /** + * Only what this bot asked from its conversation, not from inside + * another room. + */ + requester_bot_id?: number | null; }; /** * The user's own chatrooms (all, or one place's): open ones first, then by * latest activity. */ -export default async function grabUserChatrooms({ user_id, limit = 200, workspace_id }: Params): Promise { +export default async function grabUserChatrooms({ + user_id, + limit = 200, + workspace_id, + requester_bot_id, +}: Params): Promise { const scoped = workspace_id !== undefined; const rooms = ( await BunSQLite.sql({ - sql: `SELECT * FROM chatrooms WHERE user_id = ?${scoped ? ` AND workspace_id IS ?` : ""} + sql: `SELECT * FROM chatrooms WHERE user_id = ?${scoped ? ` AND workspace_id IS ?` : ""}${ + requester_bot_id ? ` AND requester_bot_id = ? AND parent_chatroom_id IS NULL` : "" + } ORDER BY (status = 'open') DESC, COALESCE(last_activity_at, created_at) DESC, id DESC LIMIT ?`, values: [ user_id, ...(scoped ? [workspace_id ? Number(workspace_id) : null] : []), + ...(requester_bot_id ? [requester_bot_id] : []), Math.max(1, Math.floor(limit)), ], }) diff --git a/src/functions/backend/db/chatrooms/retry-chatroom.ts b/src/functions/backend/db/chatrooms/retry-chatroom.ts new file mode 100644 index 00000000..1fef1901 --- /dev/null +++ b/src/functions/backend/db/chatrooms/retry-chatroom.ts @@ -0,0 +1,109 @@ +import BunSQLite from "@moduletrace/bun-sqlite"; +import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db"; +import pushBotNotice from "@/src/bots-queue/push-bot-notice"; +import { AppData } from "@/src/data/app-data"; +import AppError from "@/src/utils/app-error"; +import canRetryChatroom from "@/src/utils/can-retry-chatroom"; +import chatroomRetryNote from "@/src/utils/chatroom-retry-note"; +import grabUserBot from "../bots/grab-user-bot"; +import insertBotMessage from "../bots/insert-bot-message"; +import closeChatroom from "./close-chatroom"; +import enqueueChatroomTurn from "./enqueue-chatroom-turn"; +import ensureChatroomSession from "./ensure-chatroom-session"; +import grabChatroom from "./grab-chatroom"; +import pushChatroomUpdated from "./push-chatroom-updated"; + +type Params = { + chatroom_id: number | string; + user_id: number | string; +}; + +/** + * The room's user tries a failed or stopped request again: the same room + * reopens with a fresh turn budget and the coordinator picks it up from + * what was said, so the answer goes back the way a first one would. The + * note goes in on the asking bot's side because the room's turns can't + * end on the coordinator's own. Refused past + * `AppData.ChatroomMaxOpenPerBot`, and for a room asked from inside + * another room that has closed, since nothing is waiting on it there. + * Returns false when it was reopened already. + */ +export default async function retryChatroom({ chatroom_id, user_id }: Params) { + const room = await grabChatroom({ chatroom_id, user_id }); + + if (!room?.id) { + throw new AppError(`Chatroom not found.`); + } + + if (room.status == "open") return false; + + if (!canRetryChatroom({ chatroom: room })) { + throw new AppError(`Only a request that failed or was stopped can be tried again.`); + } + + const requester = await grabUserBot({ bot_id: room.requester_bot_id || 0, user_id }); + + if (!requester?.id) { + throw new AppError(`The bot that asked is no longer one you work with.`); + } + + if (room.parent_chatroom_id) { + const parent = await grabChatroom({ chatroom_id: room.parent_chatroom_id }); + + if (parent?.status != "open") { + throw new AppError(`The request this one was part of has closed. Try that one again instead.`); + } + } + + const open = Number( + ( + await BunSQLite.sql<{ n: number }>({ + sql: `SELECT COUNT(*) AS n FROM chatrooms WHERE user_id = ? AND requester_bot_id = ? AND status = 'open'`, + values: [user_id, requester.id], + }) + ).payload?.[0]?.n, + ); + + if (open >= AppData.ChatroomMaxOpenPerBot) { + throw new AppError(`${requester.name} already has ${open} requests open. Wait for one to finish.`); + } + + const now = Date.now(); + + const reopened = ( + await BunSQLite.sql({ + sql: `UPDATE chatrooms SET status = 'open', outcome = NULL, closed_at = NULL, coordinator_turns = 0, last_activity_at = ?, updated_at = ? + WHERE id = ? AND status = ? + RETURNING *`, + values: [now, now, room.id, room.status!], + }) + ).payload?.[0]; + + if (!reopened?.id) return false; + + /** + * An open room with no turn queued would wait on nothing. + */ + try { + const session = await ensureChatroomSession({ chatroom: reopened, bot_id: requester.id }); + + await pushBotNotice({ + bot_id: requester.id, + message: await insertBotMessage({ + bot_id: requester.id, + session_id: Number(session.id), + workspace_id: reopened.workspace_id || null, + text: chatroomRetryNote({ chatroom: room }), + }), + }); + + await enqueueChatroomTurn({ chatroom: reopened }); + } catch (error) { + await closeChatroom({ chatroom_id: reopened.id, status: "failed", outcome: `The request couldn't be tried again.` }); + throw error; + } + + await pushChatroomUpdated({ chatroom_id: reopened.id }); + + return true; +} diff --git a/src/functions/frontend/retry-chatroom-request.ts b/src/functions/frontend/retry-chatroom-request.ts new file mode 100644 index 00000000..d465482f --- /dev/null +++ b/src/functions/frontend/retry-chatroom-request.ts @@ -0,0 +1,14 @@ +import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi"; +import type { APIResponseObject } from "@moduletrace/bunext/types"; +import type { ChatroomIdRequest } from "@/src/schemas/bot-schema"; + +/** + * Tries a failed or stopped chatroom again. Its new state arrives over the + * WebSocket. + */ +export default async function retryChatroomRequest({ chatroom_id }: ChatroomIdRequest) { + return await fetchApi(`/api/admin/chatrooms/retry`, { + method: "POST", + body: { chatroom_id }, + }); +} diff --git a/src/pages/admin/bots/[bot_id]/(data)/conversation-chatrooms-context.ts b/src/pages/admin/bots/[bot_id]/(data)/conversation-chatrooms-context.ts new file mode 100644 index 00000000..b9be9563 --- /dev/null +++ b/src/pages/admin/bots/[bot_id]/(data)/conversation-chatrooms-context.ts @@ -0,0 +1,8 @@ +import React from "react"; +import type { ChatroomSummary } from "@/src/types"; + +/** + * The requests the bot asked from this conversation, kept live, so the + * thread can show the open ones and its messages can offer a retry. + */ +export const ConversationChatroomsContext = React.createContext([]); diff --git a/src/pages/admin/bots/[bot_id]/(hooks)/use-conversation-chatrooms.ts b/src/pages/admin/bots/[bot_id]/(hooks)/use-conversation-chatrooms.ts new file mode 100644 index 00000000..1318dd65 --- /dev/null +++ b/src/pages/admin/bots/[bot_id]/(hooks)/use-conversation-chatrooms.ts @@ -0,0 +1,47 @@ +import fetchApi from "@moduletrace/twui/utils/fetch/fetchApi"; +import type { APIResponseObject } from "@moduletrace/bunext/types"; +import { useEffect, useState } from "react"; +import useConnectionEpoch from "@/src/hooks/use-connection-epoch"; +import useServerEvent from "@/src/hooks/use-server-event"; +import type { ChatroomSummary } from "@/src/types"; +import chatroomInConversation from "@/src/utils/chatroom-in-conversation"; +import mergeChatroom from "@/src/utils/merge-chatroom"; + +type Params = { + bot_id: number; + workspace_id: number | null; +}; + +/** + * The latest requests a bot asked from this conversation, open ones first: + * loaded here (no page carries them), kept current from + * `server:chatroom-updated`, and read again after the socket may have + * dropped, so a push missed meanwhile can't leave a finished one showing. + */ +export default function useConversationChatrooms({ bot_id, workspace_id }: Params) { + const [chatrooms, setChatrooms] = useState([]); + const epoch = useConnectionEpoch(); + + useEffect(() => { + if (!bot_id) return; + + const query = `requester_bot_id=${bot_id}${workspace_id ? `&workspace_id=${workspace_id}` : ""}`; + + fetchApi<{}, APIResponseObject>(`/api/admin/chatrooms/list?${query}`, { method: "GET" }) + .then((res) => { + if (res?.success) setChatrooms(res.payload || []); + }) + .catch(() => {}); + }, [bot_id, workspace_id, epoch]); + + useServerEvent({ + event: "server:chatroom-updated", + onData: (room: ChatroomSummary) => { + if (!chatroomInConversation({ chatroom: room, bot_id, workspace_id })) return; + + setChatrooms((prev) => mergeChatroom({ chatrooms: prev, chatroom: room })); + }, + }); + + return chatrooms; +} diff --git a/src/pages/admin/bots/[bot_id]/(partials)/conversation-chatroom-row.tsx b/src/pages/admin/bots/[bot_id]/(partials)/conversation-chatroom-row.tsx new file mode 100644 index 00000000..7fa2e5b3 --- /dev/null +++ b/src/pages/admin/bots/[bot_id]/(partials)/conversation-chatroom-row.tsx @@ -0,0 +1,28 @@ +import Link from "@moduletrace/twui/layout/Link"; +import Span from "@moduletrace/twui/layout/Span"; +import ChatroomStatus from "@/src/pages/admin/chatrooms/[chatroom_id]/(sections)/chatroom-status"; +import type { ChatroomSummary } from "@/src/types"; +import chatroomHref from "@/src/utils/chatroom-href"; + +type Props = { + room: ChatroomSummary; +}; + +/** + * One open request: what was asked and where each bot in it stands, the + * whole of it a link to the room. + */ +export default function ConversationChatroomRow({ room }: Props) { + return ( + + + {room.title || "A request"} + + + + ); +} diff --git a/src/pages/admin/bots/[bot_id]/(partials)/conversation-chatroom-status.tsx b/src/pages/admin/bots/[bot_id]/(partials)/conversation-chatroom-status.tsx new file mode 100644 index 00000000..3b8693af --- /dev/null +++ b/src/pages/admin/bots/[bot_id]/(partials)/conversation-chatroom-status.tsx @@ -0,0 +1,23 @@ +import { useContext } from "react"; +import Stack from "@moduletrace/twui/layout/Stack"; +import { ConversationChatroomsContext } from "../(data)/conversation-chatrooms-context"; +import ConversationChatroomRow from "./conversation-chatroom-row"; + +/** + * Under the thread: every request the bot has open with the crew, until + * it's done. + */ +export default function ConversationChatroomStatus() { + const chatrooms = useContext(ConversationChatroomsContext); + const open = chatrooms.filter((room) => room.status == "open"); + + if (!open.length) return null; + + return ( + + {open.map((room) => ( + + ))} + + ); +} diff --git a/src/pages/admin/bots/[bot_id]/(partials)/crew-message-line.tsx b/src/pages/admin/bots/[bot_id]/(partials)/crew-message-line.tsx index dd973959..6c69b9cf 100644 --- a/src/pages/admin/bots/[bot_id]/(partials)/crew-message-line.tsx +++ b/src/pages/admin/bots/[bot_id]/(partials)/crew-message-line.tsx @@ -1,9 +1,11 @@ -import { memo } from "react"; +import { memo, useContext } from "react"; import Markdown from "react-markdown"; import remarkGfm from "remark-gfm"; import Stack from "@moduletrace/twui/layout/Stack"; +import ChatroomRetryButton from "@/src/components/general/chatroom-retry-button"; import type { BotMessageWithAttachments } from "@/src/types"; import linkComputerRefs from "@/src/utils/link-computer-refs"; +import { ConversationChatroomsContext } from "../(data)/conversation-chatrooms-context"; import { MessageMarkdownComponents } from "../(data)/message-markdown-components"; /** @@ -18,14 +20,19 @@ type Props = { /** * One chatroom outcome in the asking bot's conversation, rendered like a - * bot's message (its room ref a chip that opens the room). + * bot's message (its room ref a chip that opens the room), with a way to + * try the request again while its room is failed or stopped. */ function CrewMessageLine({ message }: Props) { + const chatrooms = useContext(ConversationChatroomsContext); + const chatroom = chatrooms.find((room) => room.id == message.from_chatroom_id); + return ( {linkComputerRefs({ text: message.text || "" })} + {chatroom ? : null} ); } diff --git a/src/pages/admin/bots/[bot_id]/(partials)/message-thread.tsx b/src/pages/admin/bots/[bot_id]/(partials)/message-thread.tsx index 5ccd7033..246539e7 100644 --- a/src/pages/admin/bots/[bot_id]/(partials)/message-thread.tsx +++ b/src/pages/admin/bots/[bot_id]/(partials)/message-thread.tsx @@ -10,6 +10,7 @@ import useMessageSelection from "../(hooks)/use-message-selection"; import useThreadScroll from "../(hooks)/use-thread-scroll"; import groupMessages from "../(utils)/group-messages"; import BotThinkingRow from "./bot-thinking-row"; +import ConversationChatroomStatus from "./conversation-chatroom-status"; import MessageGroupBlock from "./message-group-block"; import OlderMessagesLoader from "./older-messages-loader"; import QuoteSelectionButton from "./quote-selection-button"; @@ -38,6 +39,11 @@ type Props = { * The conversation went on in another session: no reply is due here. */ moved_on?: boolean; + /** + * No reply is due, for another reason: the last word is a chatroom's + * that doesn't wake the bot. + */ + no_reply_due?: boolean; /** * Shown after the messages, or in the middle of an empty thread, e.g. * that the bot has no model to answer with. @@ -68,7 +74,8 @@ type Props = { * Bottom-anchored: the stack sits 24px above the composer rule and grows * upward. Empty space belongs at the top. New messages announce politely. * While the bot works on a reply or a task, a status row sits under the - * last one. Text selected in a message can be quoted in the composer. + * last one, and each request the bot has open with the crew shows where + * its bots stand until it's done. Text selected in a message can be quoted in the composer. * Older messages load as it scrolls to the top, and at the start of a * session that carries on from another, the earlier one can be opened * above it (shown only, never put in the bot's prompt); the reversed column keeps @@ -84,6 +91,7 @@ export default function MessageThread({ receiving, has_task, moved_on, + no_reply_due, notice, onQuote, older, @@ -132,12 +140,14 @@ export default function MessageThread({ /> ))} {notice} + {moved_on ? null : } + 0} has_task={Boolean(progress.task_id)} moved_on={Boolean(moved_to_session_id)} + no_reply_due={no_reply_due} notice={ !text_model && !history.loading ? ( @@ -487,6 +499,7 @@ export default function Conversation() { /> )} + diff --git a/src/pages/admin/bots/[bot_id]/(utils)/chatroom-holds-reply.ts b/src/pages/admin/bots/[bot_id]/(utils)/chatroom-holds-reply.ts new file mode 100644 index 00000000..5865cece --- /dev/null +++ b/src/pages/admin/bots/[bot_id]/(utils)/chatroom-holds-reply.ts @@ -0,0 +1,23 @@ +import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db"; +import type { ChatroomSummary } from "@/src/types"; + +type Params = { + /** + * The thread's last message. + */ + last_message?: Pick | null; + chatrooms: Pick[]; +}; + +/** + * Whether the thread's last word is a chatroom's that no reply follows, + * though it sits on the user's side: the room was stopped, which doesn't + * wake the bot, or it's running again and its answer is what comes next. + */ +export default function chatroomHoldsReply({ last_message, chatrooms }: Params) { + if (!last_message?.from_chatroom_id) return false; + + const status = chatrooms.find((room) => room.id == last_message.from_chatroom_id)?.status; + + return status == "stopped" || status == "open"; +} diff --git a/src/pages/admin/chatrooms/(partials)/chatroom-list-row.tsx b/src/pages/admin/chatrooms/(partials)/chatroom-list-row.tsx index 4907c829..2ff58ca4 100644 --- a/src/pages/admin/chatrooms/(partials)/chatroom-list-row.tsx +++ b/src/pages/admin/chatrooms/(partials)/chatroom-list-row.tsx @@ -1,3 +1,4 @@ +import ChatroomRetryButton from "@/src/components/general/chatroom-retry-button"; import ChatroomStones from "@/src/components/general/chatroom-stones"; import SettingsListRow from "@/src/pages/admin/settings/(partials)/settings-list-row"; import type { ChatroomSummary } from "@/src/types"; @@ -15,7 +16,8 @@ type Props = { /** * A chatroom in the list: the bots in it, the request, where it stands, - * the workspace it's in and when it last moved. + * the workspace it's in and when it last moved, and Try again once it + * failed or was stopped. */ export default function ChatroomListRow({ chatroom, show_workspace }: Props) { const at = Number(chatroom.last_activity_at || chatroom.created_at || 0); @@ -29,6 +31,8 @@ export default function ChatroomListRow({ chatroom, show_workspace }: Props) { subtitle={[chatroomStatusLine(chatroom), show_workspace && chatroom.workspace_name, at ? relativeTime({ at }) : ""] .filter(Boolean) .join(" ยท ")} - /> + > + + ); } diff --git a/src/pages/admin/chatrooms/[chatroom_id]/(sections)/chatroom-body.tsx b/src/pages/admin/chatrooms/[chatroom_id]/(sections)/chatroom-body.tsx index 5a2087ea..035035b2 100644 --- a/src/pages/admin/chatrooms/[chatroom_id]/(sections)/chatroom-body.tsx +++ b/src/pages/admin/chatrooms/[chatroom_id]/(sections)/chatroom-body.tsx @@ -3,6 +3,7 @@ import Row from "@moduletrace/twui/layout/Row"; import Stack from "@moduletrace/twui/layout/Stack"; import { AppContext } from "@/src/pages/__root"; import SettingsShell from "@/src/pages/admin/settings/(partials)/settings-shell"; +import ChatroomRetryButton from "@/src/components/general/chatroom-retry-button"; import { CrewBotsContext } from "@/src/pages/admin/bots/[bot_id]/(data)/crew-bots-context"; import type { BUN_SQLITE_COBBLE_BOT_MESSAGES } from "@/db/types/db"; import type { ChatroomSummary } from "@/src/types"; @@ -22,7 +23,8 @@ type Props = { /** * The open room, live: who is in it and their part, the thread and the - * outcome, where each bot stands while it's open, with Stop for anyone who can do more than read. + * outcome, where each bot stands while it's open, with Stop for anyone who + * can do more than read, and Try again once it failed or was stopped. */ export default function ChatroomBody({ chatroom, messages }: Props) { const { pageProps } = useContext(AppContext); @@ -36,7 +38,13 @@ export default function ChatroomBody({ chatroom, messages }: Props) { : undefined} + action={ + can_stop ? ( + + ) : ( + + ) + } no_trail={Boolean(room.workspace_id)} > diff --git a/src/pages/admin/help/(data)/help-topics.ts b/src/pages/admin/help/(data)/help-topics.ts index d2c8a843..4c8e0148 100644 --- a/src/pages/admin/help/(data)/help-topics.ts +++ b/src/pages/admin/help/(data)/help-topics.ts @@ -95,6 +95,8 @@ A task that hit the wall stops and reports instead of waiting, so after you hand - **Where:** with the conversation it came from. A request made in a workspace is listed under Chatrooms inside that workspace, after its bots; one made in a bot's own chat is listed under Chatrooms after the workspaces. The chip in the bot's message opens it too. - **Who can be asked:** in a workspace only the workspace's bots, otherwise any bot you work with. The work runs as you, with your access. - **Read-only:** nobody writes in a chatroom. To steer the coordinator, talk to it in its own chat (super admin only). You can **Stop** an open request from the room's header. +- **While it runs:** the asking bot's conversation shows where each bot in the request stands, linked to the room, until it's done. +- **Try again:** a request that failed or was stopped can be tried again, from the room's header, the Chatrooms list or the message in the conversation that says so. The same room carries on from what was already said, and the answer goes back to the bot that asked. - **What happens after:** the answer appears in the asking bot's conversation as a message from the coordinator, and the bot carries on from there.`, }, { diff --git a/src/pages/api/admin/chatrooms/list.ts b/src/pages/api/admin/chatrooms/list.ts index 34849ea8..b69d9892 100644 --- a/src/pages/api/admin/chatrooms/list.ts +++ b/src/pages/api/admin/chatrooms/list.ts @@ -8,8 +8,9 @@ import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bune /** * The user's latest chatrooms for the rail (open ones first) in one place: - * a workspace's (`?workspace_id=`), else those asked from bots' own chats. - * Loaded by the rail itself so no page carries them. + * a workspace's (`?workspace_id=`), else those asked from bots' own chats; + * with `?requester_bot_id=`, what that bot asked there, for its conversation. + * Loaded by the rail and the conversation themselves so no page carries them. */ export const handler: BunextAPIRouteHandler> = async ({ req, query }) => { try { @@ -29,6 +30,7 @@ export const handler: BunextAPIRouteHandler> user_id: user.id, limit: AppData.ChatroomRailLimit + 1, workspace_id: Number(query?.workspace_id) || null, + requester_bot_id: Number(query?.requester_bot_id) || null, }), }; } catch (error: unknown) { diff --git a/src/pages/api/admin/chatrooms/retry.ts b/src/pages/api/admin/chatrooms/retry.ts new file mode 100644 index 00000000..f37bbb08 --- /dev/null +++ b/src/pages/api/admin/chatrooms/retry.ts @@ -0,0 +1,39 @@ +import userAuth from "@/src/functions/backend/auth/user-auth"; +import retryChatroom from "@/src/functions/backend/db/chatrooms/retry-chatroom"; +import { ChatroomIdRequestSchema } from "@/src/schemas/bot-schema"; +import AppError from "@/src/utils/app-error"; +import parseWithSchema from "@/src/utils/parse-with-schema"; +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"; + +/** + * Tries one of the user's failed or stopped chatrooms again: the room + * reopens and the coordinator carries on from it. The room's new state + * goes out live. + */ +export const handler: BunextAPIRouteHandler = 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.`); + } + + const { chatroom_id } = parseWithSchema({ schema: ChatroomIdRequestSchema, data: body }); + + const retried = await retryChatroom({ chatroom_id, user_id: user.id }); + + return { success: true, msg: retried ? `Trying again.` : `It's already running.` }; + } catch (error: unknown) { + return { success: false, msg: safeErrorMessage({ error }) }; + } +}; diff --git a/src/utils/can-retry-chatroom.ts b/src/utils/can-retry-chatroom.ts new file mode 100644 index 00000000..03f27878 --- /dev/null +++ b/src/utils/can-retry-chatroom.ts @@ -0,0 +1,13 @@ +import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db"; +import { ChatroomRetryableStatuses, type ChatroomStatus } from "@/src/dict/chatroom-dict"; + +type Params = { + chatroom: Pick; +}; + +/** + * Whether a room ended in a way the user can try again. + */ +export default function canRetryChatroom({ chatroom }: Params) { + return ChatroomRetryableStatuses.includes(chatroom.status as ChatroomStatus); +} diff --git a/src/utils/chatroom-in-conversation.ts b/src/utils/chatroom-in-conversation.ts new file mode 100644 index 00000000..ee336f30 --- /dev/null +++ b/src/utils/chatroom-in-conversation.ts @@ -0,0 +1,20 @@ +import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db"; +import chatroomInPlace from "./chatroom-in-place"; + +type Params = { + chatroom: Pick; + bot_id: number; + workspace_id: number | null; +}; + +/** + * Whether a room was asked from a bot's conversation in a place, and not + * from inside another room. + */ +export default function chatroomInConversation({ chatroom, bot_id, workspace_id }: Params) { + return ( + chatroom.requester_bot_id == bot_id && + !chatroom.parent_chatroom_id && + chatroomInPlace({ chatroom, workspace_id }) + ); +} diff --git a/src/utils/chatroom-retry-note.ts b/src/utils/chatroom-retry-note.ts new file mode 100644 index 00000000..32d3dbb8 --- /dev/null +++ b/src/utils/chatroom-retry-note.ts @@ -0,0 +1,18 @@ +import type { BUN_SQLITE_COBBLE_CHATROOMS } from "@/db/types/db"; + +type Params = { + chatroom: Pick; +}; + +/** + * What a retried room says on the asking bot's side, so the coordinator + * knows why it's back and the thread keeps how the last try ended. + */ +export default function chatroomRetryNote({ chatroom }: Params) { + const heading = `**The user asked to try this again.**`; + const outcome = chatroom.outcome?.trim(); + + if (chatroom.status == "stopped") return `${heading} They stopped the last try.`; + + return outcome ? `${heading} The last try ended with: ${outcome}` : heading; +} diff --git a/src/utils/chatroom-retry.test.ts b/src/utils/chatroom-retry.test.ts new file mode 100644 index 00000000..9da1302e --- /dev/null +++ b/src/utils/chatroom-retry.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, test } from "bun:test"; +import chatroomHoldsReply from "@/src/pages/admin/bots/[bot_id]/(utils)/chatroom-holds-reply"; +import canRetryChatroom from "./can-retry-chatroom"; +import chatroomInConversation from "./chatroom-in-conversation"; +import chatroomRetryNote from "./chatroom-retry-note"; + +describe("canRetryChatroom", () => { + test("only failed and stopped rooms", () => { + expect(canRetryChatroom({ chatroom: { status: "failed" } })).toBe(true); + expect(canRetryChatroom({ chatroom: { status: "stopped" } })).toBe(true); + + for (const status of ["open", "answered", "refused"] as const) { + expect(canRetryChatroom({ chatroom: { status } })).toBe(false); + } + }); +}); + +describe("chatroomRetryNote", () => { + test("keeps how a failed try ended", () => { + expect(chatroomRetryNote({ chatroom: { status: "failed", outcome: "No model." } })).toContain("No model."); + }); + + test("says a stopped try was stopped", () => { + expect(chatroomRetryNote({ chatroom: { status: "stopped", outcome: "" } })).toContain("stopped"); + }); +}); + +describe("chatroomInConversation", () => { + const base = { requester_bot_id: 3, workspace_id: 7, parent_chatroom_id: undefined }; + + test("matches the asking bot in its place", () => { + expect(chatroomInConversation({ chatroom: base, bot_id: 3, workspace_id: 7 })).toBe(true); + }); + + test("leaves out other bots, other places and nested rooms", () => { + expect(chatroomInConversation({ chatroom: base, bot_id: 4, workspace_id: 7 })).toBe(false); + expect(chatroomInConversation({ chatroom: base, bot_id: 3, workspace_id: null })).toBe(false); + expect( + chatroomInConversation({ chatroom: { ...base, parent_chatroom_id: 1 }, bot_id: 3, workspace_id: 7 }), + ).toBe(false); + }); +}); + +describe("chatroomHoldsReply", () => { + const last_message = { from_chatroom_id: 5 }; + + test("a stopped room or one running again holds the reply", () => { + expect(chatroomHoldsReply({ last_message, chatrooms: [{ id: 5, status: "stopped" }] })).toBe(true); + expect(chatroomHoldsReply({ last_message, chatrooms: [{ id: 5, status: "open" }] })).toBe(true); + }); + + test("a failed room wakes the bot, and other messages don't count", () => { + expect(chatroomHoldsReply({ last_message, chatrooms: [{ id: 5, status: "failed" }] })).toBe(false); + expect(chatroomHoldsReply({ last_message: {}, chatrooms: [{ id: 5, status: "stopped" }] })).toBe(false); + }); +});