Compare commits

...
2 Commits
Author SHA1 Message Date
tben 45556b3b7f Bump version to 0.19.2
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-13 13:31:34 +01:00
tben 956a6b9772 Restore a running reply's step after a reload
The thinking row's step only ever came from `server:bot-job-update`, so a
refreshed conversation sat on its label until the run's next step, and a
socket that dropped silently left it there.

The reply's step is read from the server now: with the history
(`grabSessionReplyStep` through `openSessionReplyStepSql`, the open reply
job's newest tool step) and by the catch-up (`session-messages`), which
replays it as the push it would have been. `use-reply-progress` takes it
as a seed and only ever moves forward in `bots_queue_updates` ids
(`isNewerStep`), so a read that lands just before a newer push cannot take
the row back a line, and a step from another session never shows.
2026-11-13 13:28:28 +01:00
14 changed files with 325 additions and 22 deletions
+1 -1
View File
@@ -92,7 +92,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Coordinator:** exactly one, the super admin's alone, created idempotently by `ensureCoordinatorBot`. Default prompt `src/data/coordinator-system-prompt.ts`, backfilled only when empty.
- **Routes:** `/admin/bots` reopens the last visited bot's own chat (cookie `cobble_last_visited_bot_id`, `<bot>` or `<bot>:<workspace>`; the landing uses only the bot) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. Workspace and conversation pages record the visit per user (`recordWorkspaceVisit`/`workspace_user_visits`, `recordBotVisit`/`bot_user_visits`) and the rail lists both latest visited first (`last_visited_at`, `orderByLastVisit`; a workspace nobody visited yet ranks by its creation, so a new one leads); it never decides the landing. Settings and the rail pages get the cookie's conversation, workspace included, as root prop `last_conversation` (`grabLastConversation`, access-checked, only on those paths: `isPagesRailPath`), shown above their rail list as the way back (`RailLastConversation`). `/admin/bots/[bot_id]` conversation (header, thread and composer at 760px, no right panel; `?session_id=` opens another of the user's sessions there: a closed one is reopened, except a carried-over one, which shows with `SessionMovedBar` instead of the composer, pointing where the conversation went on); `/admin/bots/[bot_id]/models`; `/admin/workspaces/[id]` dashboard; `/admin/workspaces/[id]/chatrooms` that workspace's chatrooms; `/admin/workspaces/[id]/bots/[bot_id]` same conversation scoped to the workspace.
- **No model:** while the bot has no text model there (`bot_text_model` null, kept live by the models modal), the thread shows `NoModelNotice` (centred when empty): super admins get Connect a provider / Guided setup, others are told the super admin sets it up.
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face and task (`session-messages`, `use-reply-catch-up`), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **Conversation loading:** pages render everything server-side (`grabConversationProps`) **except the history**, which the client loads (`api/admin/bots/conversation-history`, merged with what's already shown, refetched on bfcache restore) and pages older messages on scroll. Rail lists go through `railBots`/`railWorkspaces` (no prompts/memory, previews cut). Every return to the page (window focus, a hidden tab visible, back online: `use-refocus`, `AppData.RefocusGapMs`) reads the crew again (`use-live-crew-refresh` -> `api/admin/bots/live-crew` -> `cobble:live-crew-refreshed`, taken by `useLiveBots`/`useLiveWorkspaces`) and the session's latest messages plus its bot's face, task and the step its reply is on (`session-messages`, `use-reply-catch-up`; the history's own `step` seeds that row on load, `use-reply-progress`, and a row only ever moves forward in `bots_queue_updates` ids), and the page polls the same while a reply is due (read with the live face, never the page's): pushes missed while the phone slept left threads thinking and faces stale until a reload. On a phone, pulling the thread up past its bottom lifts the newest message off the edge, opening just enough room for a lone refresh icon (a ghost button, no label; no deeper, however far the drag goes), and letting go only reloads once that full room has been held for half a second, which lights the icon (`AppData.PullToRefreshHoldMs`: an exhausted thread reaches the limit by accident too easily) and then turns it into its spinner for at least a second (`AppData.PullToRefreshMinLoadingMs`) while the conversation and the rail are read again (`use-pull-to-refresh` writes that room straight onto the content as the finger moves, never through a render, and owns the gesture until release; `PullToRefreshIndicator`; dragged back down before the release, the icon hides at the travel that showed it).
- **Sending:** `api/admin/bots/send-message.ts` -> `enqueueBotReply` -> `wakeBotsQueue`. **Never import `src/bots-queue/index.ts` from a page or API route** (pulls the bunext runtime into page bundles). Optimistic bubble in `pending_messages` until the saved message replaces it. A message is capped at the app setting `bot_message_max_chars` (Settings > General, default `AppData.BotMessageMaxChars`, counted on the trimmed markdown), checked by the composer before it sends (the reason shows under the input) and again by the route.
- **Composer:** Tiptap editor reading/writing markdown, drafts in `localStorage`, `@` bots / `#` workspaces written as `[bot:ID]`/`[workspace:ID]`. Enter sends (Mod+Enter in lists/code). **Up/Down walk the user's own earlier messages** (`use-composer-history`, from `composerHistoryTexts` over the thread's user messages, never a crew message): Up recalls the newest from an empty input and older ones from there, Down comes forward again and back to what was being typed, a keystroke takes the input back, an open mention menu or a selection keeps the arrows. A clear button (X, disabled while the input is empty) empties the text without sending, keeping the quote and the picked files. Ordered lists are read back from digit markers only (`composer-ordered-list`): Tiptap also takes `a.`/`i.`, so a recalled "Ok. Do that." came back as item 401 with "Ok." eaten. `@tiptap/react` needs `use-sync-external-store`; the app ships an ESM stand-in in `packages/use-sync-external-store-esm` (file dependency + override; the Dockerfile copies `packages/` before `bun install`).
- **Rendering:** markdown via `react-markdown` + `remark-gfm`, raw HTML never rendered, component map in `[bot_id]/(data)/message-markdown-components.tsx`. Inline refs, all linked by `link-computer-refs.ts` and rendered by chips in `(partials)/`: `[bot:ID]`, `[workspace:ID]`, `[computer:ID]`, `[file:ID]` (a saved file), `[folder:<volume>:<owner>:<path>]` (opens `FolderPreviewModal`, the files browser's listing over the chat, files opening their own preview; a modified click or its Open in Files goes to `/admin/files`), `[take-over:ID:mode]`, `[proposal:ID]`, `[hook-proposal:ID]`, `[secret:ID]` (masked env, Reveal/Copy), `[secret-request:ID]` (masked input card), `[question:ID]` (a bot's questions), `[suggestion:ID]` (its suggested next steps, buttons that fill the composer), `[graphic:ID]` (a bot graphic, framed inline), `[room:ID]` (a chatroom), `[task:ID]` (a tracker task, opening `TaskDetailModal`), `[setting:<section>:<field>]` (`SettingRefChip`: the exact Settings > General page and field to change, from `src/dict/general-settings-dict.ts`; every group of that page also has its own page under `/admin/settings/general/<section>`, and its fields are anchors). Parsers in `src/utils/*-ref.ts`. Anywhere else that renders bot-written markdown with `MessageMarkdownComponents` (a workspace's context on its dashboard, a task's description and notes through `TaskMarkdown`) runs it through `linkComputerRefs` and provides `CrewBotsContext`/`CrewWorkspacesContext` too. A ref quoted alone in a code span still links; one inside longer code stays literal (`linkComputerRefs` splits out code first). A file chip opens a file from another bot's folder for a user who reaches that folder (`userReachesFileScope`, the same rule as its bytes), so answers passed on from chatrooms keep working.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.19.1",
"version": "0.19.2",
"module": "index.ts",
"type": "module",
"private": true,
@@ -2,6 +2,7 @@ import { AppData } from "@/src/data/app-data";
import type { ConversationHistory } from "@/src/types";
import grabActiveBotTask from "../bots/grab-active-bot-task";
import grabBotMessages from "../bots/grab-bot-messages";
import grabSessionReplyStep from "../bots-queue/grab-session-reply-step";
import ensureBotSession from "./ensure-bot-session";
import grabCarriedToSessionId from "./grab-carried-to-session-id";
import reopenBotSession from "./reopen-bot-session";
@@ -31,8 +32,9 @@ type Params = {
* one is reopened, unless it was carried over, which only shows, with
* where the conversation went on), its latest
* `AppData.ConversationFirstMessages` messages (the thread loads older
* ones as it scrolls) and the bot's active task in it. Everything else on
* the page comes with it from the server (`grabConversationProps`).
* ones as it scrolls), the bot's active task in it and the step its
* running reply is on. Everything else on the page comes with it from the
* server (`grabConversationProps`).
* Null when the user can't chat with the bot there.
*/
export default async function grabConversationHistory({
@@ -87,13 +89,14 @@ export default async function grabConversationHistory({
session.unread = 0;
}
const [messages, task] = await Promise.all([
const [messages, task, step] = await Promise.all([
grabBotMessages({
session_id: session.id!,
user_id,
limit: AppData.ConversationFirstMessages + 1,
}),
grabActiveBotTask({ bot_id: open_bot_id, session_id: session.id }),
grabSessionReplyStep({ session_id: session.id! }),
]);
const has_more = messages.length > AppData.ConversationFirstMessages;
@@ -103,6 +106,7 @@ export default async function grabConversationHistory({
messages: has_more ? messages.slice(1) : messages,
has_more,
task,
step,
moved_to_session_id: carried_to,
};
}
@@ -0,0 +1,23 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BotJobUpdateData } from "@/src/types";
import openSessionReplyStepSql from "./open-session-reply-step-sql";
type Params = {
session_id: number | string;
};
/**
* The step the reply running in a session is on, as `server:bot-job-update`
* carries it, or null when no reply runs there. Read with a conversation's
* history and by its catch-up, so a reload (or a push missed while the page
* stayed open) shows what the reply is doing instead of only its label.
*/
export default async function grabSessionReplyStep({
session_id,
}: Params): Promise<BotJobUpdateData | null> {
const { sql, values } = openSessionReplyStepSql({ session_id });
const res = await BunSQLite.sql<BotJobUpdateData>({ sql, values });
const step = (res.payload || [])[0];
return step ? { ...step, id: Number(step.id), task_id: null } : null;
}
@@ -0,0 +1,66 @@
import { Database } from "bun:sqlite";
import { describe, expect, test } from "bun:test";
import openSessionReplyStepSql from "./open-session-reply-step-sql";
/**
* A conversation that reloads mid-reply reads the step the run is on from
* the server. It must be the open reply job's newest tool step, never a
* task's (a task brings its own), never a finished job's, never a closing
* note (its text is the answer) and never another session's.
*/
function setup() {
const db = new Database(":memory:");
db.run(
`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, kind TEXT, status TEXT, session_id INTEGER, task_id INTEGER)`,
);
db.run(
`CREATE TABLE bots_queue_updates (id INTEGER PRIMARY KEY, bots_queue_id INTEGER, bot_id INTEGER, kind TEXT, text TEXT, metadata TEXT, created_at INTEGER)`,
);
db.run(`INSERT INTO bots_queue (id, kind, status, session_id, task_id) VALUES
(10, 'reply', 'processing', 1, NULL),
(11, 'task', 'processing', 1, 50),
(12, 'reply', 'completed', 1, NULL),
(13, 'reply', 'processing', 2, NULL)`);
db.run(`INSERT INTO bots_queue_updates (id, bots_queue_id, bot_id, kind, text, metadata, created_at) VALUES
(100, 10, 7, 'tool', 'Reading the invoice', NULL, 1000),
(101, 10, 7, 'note', 'Here is the invoice', NULL, 1001),
(102, 11, 7, 'tool', 'Using sandbox_execute_bash', NULL, 1002),
(103, 12, 7, 'tool', 'Read the finished job', NULL, 1003),
(104, 13, 7, 'tool', 'Reading another session', NULL, 1004)`);
return db;
}
describe("openSessionReplyStepSql", () => {
test("reads the open reply's newest tool step, with its job's task and session", () => {
const db = setup();
const { sql, values } = openSessionReplyStepSql({ session_id: 1 });
const step = db.query(sql).get(...values) as {
id: number;
bots_queue_id: number;
bot_id: number;
kind: string;
text: string;
task_id: number | null;
session_id: number;
} | null;
expect(step?.id).toBe(100);
expect(step?.text).toBe("Reading the invoice");
expect(step?.bot_id).toBe(7);
expect(step?.task_id).toBeNull();
expect(step?.session_id).toBe(1);
});
test("a session with no reply running has no step", () => {
const db = setup();
db.run(`UPDATE bots_queue SET status = 'completed' WHERE id = 10`);
const { sql, values } = openSessionReplyStepSql({ session_id: 1 });
expect(db.query(sql).get(...values)).toBeNull();
});
});
@@ -0,0 +1,26 @@
type Params = {
session_id: number | string;
};
/**
* The newest step of the reply job a session still runs, with the job's
* task and session beside it, so a conversation that reloaded (or missed
* the step's push) shows what the reply is doing instead of waiting for its
* next step. A reply's steps are never stored with the task they belong to
* the way a task's are (`grabBotJobUpdates`), so they are read here.
*
* Only an open job's, only a reply's, and only a tool step: a closing note's
* text is the answer, about to land as the message.
*/
export default function openSessionReplyStepSql({ session_id }: Params) {
return {
sql: `SELECT u.*, q.task_id AS task_id, q.session_id AS session_id
FROM bots_queue_updates u
JOIN bots_queue q ON q.id = u.bots_queue_id
WHERE q.session_id = ? AND q.kind = 'reply' AND q.status IN ('pending', 'processing')
AND u.kind = 'tool' AND u.text IS NOT NULL
ORDER BY u.id DESC
LIMIT 1`,
values: [Number(session_id)],
};
}
@@ -23,15 +23,17 @@ type Params = {
/**
* Keeps the thread from waiting on a push that never came: every return to
* the page (`useRefocus`) reads the session's latest messages and the
* bot's face, status line and active task, and while a reply is due it
* does so every `AppData.BotReplyCatchUpMs` too. A missed message is
* replayed as the `server:bot-message` it would have been, so the thread,
* the rail and the unread flag all take it the usual way. The bot's face,
* status line and active task are replayed as `server:bot-updated`, so a
* reply that ended without a final message (its face push missed) can't
* leave the bot thinking or a finished task on screen. Reading it even
* when no reply is due is what lets a row stuck on a stale face or task
* clear itself without a reload.
* bot's face, status line, active task and the step its reply is on, and
* while a reply is due it does so every `AppData.BotReplyCatchUpMs` too. A
* missed message is replayed as the `server:bot-message` it would have been,
* so the thread, the rail and the unread flag all take it the usual way. The
* bot's face, status line and active task are replayed as
* `server:bot-updated`, so a reply that ended without a final message (its
* face push missed) can't leave the bot thinking or a finished task on
* screen. The step is replayed as `server:bot-job-update`, so a run whose
* steps were pushed while the page slept still shows the one it's on.
* Reading it even when no reply is due is what lets a row stuck on a stale
* face or task clear itself without a reload.
*/
export default function useReplyCatchUp({ session_id, awaiting_reply, last_message_id }: Params) {
const last_message = useRef(Number(last_message_id) || 0);
@@ -66,6 +68,13 @@ export default function useReplyCatchUp({ session_id, awaiting_reply, last_messa
replay({ data: { event: "server:bot-message", data: message } });
}
/**
* The step the reply is on now, replayed as the push it would have
* been: a row shows the line of the last step it heard of, and a
* reload or a socket that dropped heard of none.
*/
if (res.step?.id) replay({ data: { event: "server:bot-job-update", data: res.step } });
/**
* After the messages, so a reply that ended silently (its last
* word an interim one) drops the row once its face moves on.
@@ -1,6 +1,7 @@
import { useRef, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import useServerEvent from "@/src/hooks/use-server-event";
import type { BotJobUpdateData } from "@/src/types";
import isNewerStep from "../(utils)/is-newer-step";
type Params = {
bot_id: number;
@@ -14,25 +15,55 @@ type Params = {
* it.
*/
last_message_id?: number | null;
/**
* The step the server still has for the open reply, read with the
* history: a page that just loaded shows what the run is doing at once
* rather than only the row's label, waiting for its next push (the
* catch-up replays the newer ones).
*/
seed?: BotJobUpdateData | null;
};
type Step = {
id: number;
text: string;
after_message_id: number | null;
/**
* The session it was read in: another one's step never shows here.
*/
session_id: number | null;
};
/**
* The latest step of the reply running in the open session (a
* `bots_queue_updates` row's text, from `server:bot-job-update` without a
* task), so a reply that works through tools shows what it's doing. Only
* tool steps: the closing note is the answer itself.
* tool steps: the closing note is the answer itself. The steps the server
* still holds (the history's, the catch-up's replay) are taken the same
* way, and never take the row back a line.
*/
export default function useReplyProgress({ bot_id, session_id, last_message_id }: Params) {
export default function useReplyProgress({
bot_id,
session_id,
last_message_id,
seed,
}: Params) {
const [step, setStep] = useState<Step | null>(null);
const last_message = useRef(last_message_id || null);
last_message.current = last_message_id || null;
const adopt = useCallback((update: BotJobUpdateData) => {
const taken: Step = {
id: Number(update.id),
text: update.text as string,
after_message_id: last_message.current,
session_id: Number(update.session_id) || null,
};
setStep((shown) => (isNewerStep({ shown, step: taken }) ? taken : shown));
}, []);
useServerEvent({
event: "server:bot-job-update",
onData: (update: BotJobUpdateData) => {
@@ -45,9 +76,23 @@ export default function useReplyProgress({ bot_id, session_id, last_message_id }
if (update.kind == "note") return;
if (!session_id || update.session_id != session_id) return;
setStep({ text: update.text, after_message_id: last_message.current });
adopt(update);
},
});
return step && step.after_message_id == (last_message_id || null) ? step.text : null;
}
/**
* Read again with the history, so it lands once the thread shows the
* messages it belongs after (it's keyed to the last one).
*/
useEffect(() => {
if (!seed?.id || !seed.text) return;
adopt(seed);
}, [seed, last_message_id, adopt]);
return step &&
step.session_id == (session_id || null) &&
step.after_message_id == (last_message_id || null)
? step.text
: null;
}
@@ -0,0 +1,51 @@
import { describe, expect, test } from "bun:test";
import { renderToString } from "react-dom/server";
import type { BotWithLastMessage } from "@/src/types";
import BotThinkingRow from "./bot-thinking-row";
function bot(overrides: Partial<BotWithLastMessage>): BotWithLastMessage {
return {
id: 1,
name: "Ember",
color: "#c2410c",
stone: "ember",
face: "working",
...overrides,
} as BotWithLastMessage;
}
/**
* The row under the thread: its label, and the step of the work it shows.
* The reply's step is the one a reload has to bring back, or the row sits
* on its label until the run's next push.
*/
describe("BotThinkingRow", () => {
test("a reply owed here shows the step it's on", () => {
const html = renderToString(
<BotThinkingRow bot={bot({})} awaiting_reply reply_progress="Reading the invoice" />,
);
expect(html).toContain("Ember is thinking");
expect(html).toContain("Reading the invoice");
});
test("a task shows the step it's on", () => {
const html = renderToString(
<BotThinkingRow
bot={bot({ status_line: "Working on a task" })}
has_task
progress="Using sandbox_execute_bash"
/>,
);
expect(html).toContain("Ember is working");
expect(html).toContain("Using sandbox_execute_bash");
});
test("no step yet shows the label alone", () => {
const html = renderToString(<BotThinkingRow bot={bot({})} awaiting_reply />);
expect(html).toContain("Ember is thinking");
expect(html).not.toContain("Reading the invoice");
});
});
@@ -4,6 +4,7 @@ import isAwaitingReply from "../(utils)/is-awaiting-reply";
import Stack from "@moduletrace/twui/layout/Stack";
import type { BotMessageReactionEmoji } from "@/src/dict/bot-dict";
import type {
BotJobUpdateData,
BotMessageReactionData,
BotMessageWithAttachments,
} from "@/src/types";
@@ -75,6 +76,12 @@ export default function Conversation() {
const [messages, setMessages] = useState<BotMessageWithAttachments[]>(
[],
);
/**
* The step the reply running when the history loaded is on, read with
* it so a refreshed thread shows the run's line straight away instead
* of only the thinking row's label until its next push.
*/
const [reply_step, setReplyStep] = useState<BotJobUpdateData | null>(null);
/**
* Messages sent here that the server hasn't confirmed yet, shown after
* the saved ones so a slow connection never hides what was typed. They
@@ -202,6 +209,7 @@ export default function Conversation() {
previous_session_id: Number(history.session.previous_session_id) || null,
});
progress.reset({ task: history.task });
setReplyStep(history.step || null);
},
});
@@ -228,6 +236,7 @@ export default function Conversation() {
bot_id: bot?.id || 0,
session_id,
last_message_id: last_saved_id,
seed: reply_step,
});
useReplyCatchUp({
@@ -0,0 +1,28 @@
import { describe, expect, test } from "bun:test";
import isNewerStep from "./is-newer-step";
/**
* A row that reloads mid-run reads the reply's step from the server while a
* live push may already show a later one: the line only moves forward.
*/
describe("isNewerStep", () => {
test("the first step is taken", () => {
expect(isNewerStep({ shown: null, step: { id: 7 } })).toBe(true);
});
test("a later step replaces the one shown", () => {
expect(isNewerStep({ shown: { id: 7 }, step: { id: 8 } })).toBe(true);
});
test("an older one read from the server leaves the newer push alone", () => {
expect(isNewerStep({ shown: { id: 8 }, step: { id: 7 } })).toBe(false);
});
test("the same step read again changes nothing", () => {
expect(isNewerStep({ shown: { id: 8 }, step: { id: 8 } })).toBe(false);
});
test("no step takes nothing", () => {
expect(isNewerStep({ shown: { id: 8 }, step: null })).toBe(false);
});
});
@@ -0,0 +1,27 @@
type Step = {
id: number | string;
};
type Params = {
/**
* The step the thinking row shows.
*/
shown: Step | null;
/**
* The step that arrived: pushed live, replayed by the catch-up, or
* read with the history.
*/
step: Step | null;
};
/**
* Whether a step replaces the one on screen. Steps arrive by push and are
* also read from the server (a reload's history, the catch-up's replay), so
* one read just before a newer push reached the page must not take the
* thinking row's line back: rows only ever move forward.
*/
export default function isNewerStep({ shown, step }: Params) {
if (!step) return false;
return !shown || Number(step.id) > Number(shown.id);
}
+5 -2
View File
@@ -3,6 +3,7 @@ import grabUserBotSession from "@/src/functions/backend/db/bot-sessions/grab-use
import grabBotMessages from "@/src/functions/backend/db/bots/grab-bot-messages";
import grabBotFace from "@/src/functions/backend/db/bots/grab-bot-face";
import grabActiveBotTask from "@/src/functions/backend/db/bots/grab-active-bot-task";
import grabSessionReplyStep from "@/src/functions/backend/db/bots-queue/grab-session-reply-step";
import { AppData } from "@/src/data/app-data";
import { BotSessionIdRequestSchema } from "@/src/schemas/bot-schema";
import type { SessionMessagesResponse } from "@/src/types";
@@ -14,8 +15,9 @@ import type { BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* The latest messages of one of the session user's own sessions, and the
* bot's face, status line and active task for that user (as
* `server:bot-updated` carries them), so the open conversation can catch
* up on a reply or a face change whose live push it missed.
* `server:bot-updated` carries them) plus the step its reply is on (as
* `server:bot-job-update` does), so the open conversation can catch up on a
* reply, a face change or a step whose live push it missed.
*/
export const handler: BunextAPIRouteHandler<SessionMessagesResponse> = async ({ req, body }) => {
try {
@@ -51,6 +53,7 @@ export const handler: BunextAPIRouteHandler<SessionMessagesResponse> = async ({
...(await grabBotFace({ bot_id, user_id: user.id })),
task: await grabActiveBotTask({ bot_id, user_id: user.id }),
},
step: await grabSessionReplyStep({ session_id: session.id }),
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
+12
View File
@@ -568,6 +568,12 @@ export type BotUpdatedData = {
*/
export type SessionMessagesResponse = APIResponseObject<BotMessageWithAttachments> & {
bot?: BotUpdatedData | null;
/**
* The step the reply running in that session is on, as
* `server:bot-job-update` carries it: a conversation that missed the
* step's push replays it and keeps its thinking row's line.
*/
step?: BotJobUpdateData | null;
};
/**
@@ -2104,6 +2110,12 @@ export type ConversationHistory = {
* far.
*/
task: BotTaskWithSteps | null;
/**
* The step the reply running in the session is on (a
* `server:bot-job-update`), so a page that just loaded shows what it's
* doing instead of only its label. Null when no reply runs there.
*/
step?: BotJobUpdateData | null;
/**
* When the session shown was carried over into a newer one (it stays
* closed, to read): that session. Null otherwise.