Compare commits

...
2 Commits
Author SHA1 Message Date
tbenandClaude Opus 5.5 f1f48d842b Release v0.11.3
Release image / image (release) Canceled after 0s
CI / check (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 11:52:41 +01:00
tbenandClaude Opus 5.5 51b5fb28b1 List rail workspaces and bots by each user's last visit
The rail remembered one workspace in a cookie, so opening another sent the
previous one back to its old place, sometimes behind "See all". Record
visits per user in workspace_user_visits and bot_user_visits instead, so
the order follows the user across devices and survives sign-out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-01 11:52:08 +01:00
30 changed files with 295 additions and 176 deletions
+1 -1
View File
@@ -90,7 +90,7 @@ Enables SQLite foreign keys (`enableForeignKeys`), `bunextInit()`, `ensureDocker
- **Tables:** `bots` (`kind`, `color` `#rrggbb`, `stone`, `role`, `system_prompt`; `hue` is a legacy fallback), `bot_user_faces`, `bot_sessions`, `bot_messages`, `bot_tasks`, `bot_task_steps` (unused yet). Enums in `src/dict/bot-dict.ts`.
- **Sessions:** one thread per user per bot in its own chat plus one per workspace; split into `bot_sessions` (rollover at the app setting `bot_session_max_messages`, default `AppData.BotSessionMaxMessages`, via `grabBotSessionMaxMessages`; titled and summarised by `name-bot-session.ts` from the session's opening after a reply or a task (a session with no user message, work handed to the bot, is named from the bot's own messages; `grabSessionOpening`; `grabBotMessages` reads the latest), summary carried into the next session only when they're linked by `previous_session_id`, which only a carry-over sets; older implicit links are cleared at boot by `clearImplicitSessionLinks`). New session (`startBotSession`) and a conversation with no active session always start fresh. The rollover carries over like the bot does (`rollOverBotSession` -> `continueBotSession`, falling back to the stored summary; kept for the next message while a job is open in the full session or there's nothing to carry), inside send-message, so the user's message lands under the summary. Helpers in `src/functions/backend/db/bot-sessions/`. Job results land in the job's own session, even after it closes, except a reply that called `continue_in_new_session` (`carryOverBotSession`; the menu's and sessions modal's Continue in new session does the same through `continueBotSession`, the model writing title and summary, refused while a job is open in the session): its summary is kept on the closed session and opens the new one as a bot message (`carried_from_session_id`), the job's `session_id` moves so the answer follows, the new session is titled by the bot then (it has no first exchange to be named from), and the old one can never be reopened (`reopenBotSession` refuses; a thread showing it swaps its composer for a link to the new one). Session lists (rail, sessions modal) reopen a session on click, as before; a carried-over one can't be, so it opens to read (`?session_id=`, `conversationHref`). The page tells them which session it shows (`announceShownSession` -> `useShownSession`): they reload, mark it Current (greyed out; without `?session_id=` the active one is), list it even when it's older than the rail's latest, and the active row then leads back. From half the session length the reply prompt suggests moving on (`longSessionNote`). Earlier sessions never enter the prompt (only the last one's summary): the thread can open them above a session (`useOlderMessages.loadPrevious`, a divider per session, quote and reply as usual), and replies get `search_past_sessions`/`read_past_session` (scoped to that user, bot and place, never the current session) when the conversation has any.
- **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 (cookie `cobble_last_visited_bot_id`, never a workspace conversation) if still reachable, else coordinator (super admin) / latest bot / first workspace / empty. The workspace pages set `cobble_last_visited_workspace_id`, read in the root (`last_visited_workspace_id`), and the rail lists that workspace first (`orderRailWorkspaces`); it never decides the landing. `/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.
- **Routes:** `/admin/bots` reopens the last visited bot (cookie `cobble_last_visited_bot_id`, never a workspace conversation) 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`); it never decides the landing. `/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). While a reply is due (read with the live face, never the page's) the page polls `session-messages` (`use-reply-catch-up`, also at once when the page comes back into view or online) in case a push was missed, replaying the messages and the bot's face and task as their pushes.
- **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.
+98
View File
@@ -2016,6 +2016,104 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
},
],
},
{
tableName: "bot_user_visits",
tableDescription: `When each user last opened a conversation with a bot, in its own chat or a workspace, so their rail lists bots by it. Per user, since a bot belongs to the install`,
fields: [
{
fieldName: "bot_id",
dataType: "INTEGER",
foreignKey: {
cascadeDelete: true,
destinationTableName: "bots",
destinationTableColumnName: "id",
destinationTableColumnType: "INTEGER",
foreignKeyName: "bot_user_visit_bot_fk",
},
},
{
fieldName: "user_id",
dataType: "INTEGER",
foreignKey: {
cascadeDelete: true,
destinationTableName: "users",
destinationTableColumnName: "id",
destinationTableColumnType: "INTEGER",
foreignKeyName: "bot_user_visit_user_fk",
},
},
{
fieldName: "visited_at",
fieldDescription: `Unix milliseconds of the user's last visit`,
dataType: "INTEGER",
},
],
uniqueConstraints: [
{
alias: "one_visit_per_bot_user",
constraintName: "A user has one last visit per bot",
constraintTableFields: [
{ value: "bot_id" },
{ value: "user_id" },
],
},
],
indexes: [
{
indexName: "idx_bot_user_visits_user_id",
indexTableFields: ["user_id"],
},
],
},
{
tableName: "workspace_user_visits",
tableDescription: `When each user last opened a workspace, so their rail lists workspaces by it. Per user, since a workspace belongs to the install`,
fields: [
{
fieldName: "workspace_id",
dataType: "INTEGER",
foreignKey: {
cascadeDelete: true,
destinationTableName: "workspaces",
destinationTableColumnName: "id",
destinationTableColumnType: "INTEGER",
foreignKeyName: "workspace_user_visit_workspace_fk",
},
},
{
fieldName: "user_id",
dataType: "INTEGER",
foreignKey: {
cascadeDelete: true,
destinationTableName: "users",
destinationTableColumnName: "id",
destinationTableColumnType: "INTEGER",
foreignKeyName: "workspace_user_visit_user_fk",
},
},
{
fieldName: "visited_at",
fieldDescription: `Unix milliseconds of the user's last visit`,
dataType: "INTEGER",
},
],
uniqueConstraints: [
{
alias: "one_visit_per_workspace_user",
constraintName: "A user has one last visit per workspace",
constraintTableFields: [
{ value: "workspace_id" },
{ value: "user_id" },
],
},
],
indexes: [
{
indexName: "idx_workspace_user_visits_user_id",
indexTableFields: ["user_id"],
},
],
},
{
tableName: "bot_user_memories",
tableDescription: `What a bot remembers about one user (markdown). Only that user's runs see it, the way a workspace's memory stays in the workspace`,
+45 -1
View File
@@ -29,6 +29,8 @@ export const BunSQLiteTables = [
"bot_types",
"workspace_users",
"bot_users",
"bot_user_visits",
"workspace_user_visits",
"bot_user_memories",
"bot_user_faces",
"bot_message_media",
@@ -1266,6 +1268,48 @@ export type BUN_SQLITE_COBBLE_BOT_USERS = {
user_id?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_USER_VISITS = {
/**
* The unique identifier of the record.
*/
id?: number | "";
/**
* The time when the record was created. (Unix Timestamp)
*/
created_at?: number | "";
/**
* The time when the record was updated. (Unix Timestamp)
*/
updated_at?: number | "";
bot_id?: number | "";
user_id?: number | "";
/**
* Unix milliseconds of the user's last visit
*/
visited_at?: number | "";
}
export type BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS = {
/**
* The unique identifier of the record.
*/
id?: number | "";
/**
* The time when the record was created. (Unix Timestamp)
*/
created_at?: number | "";
/**
* The time when the record was updated. (Unix Timestamp)
*/
updated_at?: number | "";
workspace_id?: number | "";
user_id?: number | "";
/**
* Unix milliseconds of the user's last visit
*/
visited_at?: number | "";
}
export type BUN_SQLITE_COBBLE_BOT_USER_MEMORIES = {
/**
* The unique identifier of the record.
@@ -2520,4 +2564,4 @@ export type BUN_SQLITE_COBBLE_APP_SETTINGS = {
value?: string;
}
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
export type BUN_SQLITE_COBBLE_ALL_TYPEDEFS = BUN_SQLITE_COBBLE_USERS & BUN_SQLITE_COBBLE_USER_TYPES & BUN_SQLITE_COBBLE_SSO_LOGIN_CODES & BUN_SQLITE_COBBLE_USER_PASSWORDS & BUN_SQLITE_COBBLE_MEDIA & BUN_SQLITE_COBBLE_MEDIA_PARADIGMS & BUN_SQLITE_COBBLE_BOTS & BUN_SQLITE_COBBLE_CHATROOMS & BUN_SQLITE_COBBLE_BOT_SESSIONS & BUN_SQLITE_COBBLE_BOT_MESSAGES & BUN_SQLITE_COBBLE_BOT_MESSAGE_REACTIONS & BUN_SQLITE_COBBLE_BOT_TASKS & BUN_SQLITE_COBBLE_BOT_TASK_STEPS & BUN_SQLITE_COBBLE_TASKS & BUN_SQLITE_COBBLE_TASK_MEDIA & BUN_SQLITE_COBBLE_TASK_NOTES & BUN_SQLITE_COBBLE_BOTS_QUEUE & BUN_SQLITE_COBBLE_BOTS_QUEUE_UPDATES & BUN_SQLITE_COBBLE_CRON_JOBS & BUN_SQLITE_COBBLE_BOT_HOOKS & BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS & BUN_SQLITE_COBBLE_HOOK_PROPOSALS & BUN_SQLITE_COBBLE_SECRET_REQUESTS & BUN_SQLITE_COBBLE_BOT_QUESTIONS & BUN_SQLITE_COBBLE_BOT_GRAPHICS & BUN_SQLITE_COBBLE_WORKSPACES & BUN_SQLITE_COBBLE_WORKSPACE_BOTS & BUN_SQLITE_COBBLE_BOT_TYPES & BUN_SQLITE_COBBLE_WORKSPACE_USERS & BUN_SQLITE_COBBLE_BOT_USERS & BUN_SQLITE_COBBLE_BOT_USER_VISITS & BUN_SQLITE_COBBLE_WORKSPACE_USER_VISITS & BUN_SQLITE_COBBLE_BOT_USER_MEMORIES & BUN_SQLITE_COBBLE_BOT_USER_FACES & BUN_SQLITE_COBBLE_BOT_MESSAGE_MEDIA & BUN_SQLITE_COBBLE_CONTAINERS & BUN_SQLITE_COBBLE_COMPUTERS & BUN_SQLITE_COBBLE_BOT_COMPUTERS & BUN_SQLITE_COBBLE_WORKSPACE_COMPUTERS & BUN_SQLITE_COBBLE_HARNESS_PROVIDERS & BUN_SQLITE_COBBLE_HARNESS_MODELS & BUN_SQLITE_COBBLE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_BOT_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_WORKSPACE_HARNESS_SETTINGS & BUN_SQLITE_COBBLE_MCP_SERVERS & BUN_SQLITE_COBBLE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_SKILLS & BUN_SQLITE_COBBLE_EXTENSION_PROPOSALS & BUN_SQLITE_COBBLE_BOT_MCP_SERVERS & BUN_SQLITE_COBBLE_WORKSPACE_MCP_SERVERS & BUN_SQLITE_COBBLE_BOT_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_WORKSPACE_CUSTOM_TOOLS & BUN_SQLITE_COBBLE_BOT_SKILLS & BUN_SQLITE_COBBLE_WORKSPACE_SKILLS & BUN_SQLITE_COBBLE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_CHUNKS & BUN_SQLITE_COBBLE_KNOWLEDGEBASE_VECTORS & BUN_SQLITE_COBBLE_BOT_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_WORKSPACE_KNOWLEDGEBASES & BUN_SQLITE_COBBLE_LOGS & BUN_SQLITE_COBBLE_USER_PRESENCE & BUN_SQLITE_COBBLE_PUSH_SUBSCRIPTIONS & BUN_SQLITE_COBBLE_ENVS & BUN_SQLITE_COBBLE_BOT_FILES & BUN_SQLITE_COBBLE_TOKEN_USAGES & BUN_SQLITE_COBBLE_FILE_INGEST_QUEUE & BUN_SQLITE_COBBLE_APP_SETTINGS
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.11.2",
"version": "0.11.3",
"module": "index.ts",
"type": "module",
"private": true,
+2 -7
View File
@@ -61,11 +61,6 @@ export const AppData = {
* reads it.
*/
LastVisitedBotCookieName: `${SiteData["SiteSlug"]}_last_visited_bot_id`,
/**
* The workspace this browser was last in: the rail lists it first. Never
* where `/admin/bots` lands. `HttpOnly`: only the server reads it.
*/
LastVisitedWorkspaceCookieName: `${SiteData["SiteSlug"]}_last_visited_workspace_id`,
LastVisitedCookieMaxAgeSeconds: 365 * 24 * 60 * 60,
AuthExpiryDays: 60,
APICrudBasePath: "/api/admin/crud",
@@ -533,12 +528,12 @@ export const AppData = {
PastSessionReadMessages: 20,
PastSessionReadMessageChars: 2000,
/**
* Worker bots the rail lists, most recently active first, before
* Worker bots the rail lists, most recently visited first, before
* "See all bots".
*/
RailRecentBots: 5,
/**
* Workspaces the rail lists, most recently active first, before
* Workspaces the rail lists, most recently visited first, before
* "See all workspaces".
*/
RailRecentWorkspaces: 5,
@@ -57,6 +57,7 @@ export default async function deleteBot({ user_id, bot_id }: Params) {
await BunSQLite.sql({ sql: `DELETE FROM secret_requests WHERE bot_id = ?`, values: [bot.id] });
await BunSQLite.sql({ sql: `DELETE FROM bot_questions WHERE bot_id = ?`, values: [bot.id] });
await BunSQLite.sql({ sql: `DELETE FROM bot_graphics WHERE bot_id = ?`, values: [bot.id] });
await BunSQLite.sql({ sql: `DELETE FROM bot_user_visits WHERE bot_id = ?`, values: [bot.id] });
const res = await BunSQLite.sql({ sql: `DELETE FROM bots WHERE id = ?`, values: [bot.id] });
+3 -2
View File
@@ -20,7 +20,7 @@ type Params = {
* (`chatBotsSql`) or in one workspace (`workspaceBotsSql`). The
* coordinator is pinned first, then workers by latest activity. Each row
* carries the user's own face (`botFaceSql`) and conversation there: its
* unread flag, latest activity and latest message, and in a workspace
* unread flag, latest activity and latest message, their last visit, and in a workspace
* whether it's that workspace's admin (`is_admin`).
*/
export default async function grabBots({
@@ -38,6 +38,7 @@ export default async function grabBots({
sql += `SELECT\n`;
sql += ` b.*,\n`;
sql += ` ${face.sql},\n`;
sql += ` (SELECT v.visited_at FROM bot_user_visits v WHERE v.bot_id = b.id AND v.user_id = ?) AS last_visited_at,\n`;
sql += ` COALESCE(t.unread, 0) AS unread,\n`;
sql += ` t.last_activity_at AS last_activity_at,\n`;
sql += ` lm.text AS last_message_text,\n`;
@@ -61,7 +62,7 @@ export default async function grabBots({
const res = await BunSQLite.sql<BotWithLastMessage>({
sql,
values: [...face.values, scope, scope, user_id, scope, user_id, ...access.values],
values: [...face.values, user_id, scope, scope, user_id, scope, user_id, ...access.values],
});
return (res.payload || []).map((bot) => ({ ...bot, is_admin: Boolean(bot.is_admin) }));
@@ -0,0 +1,22 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
bot_id: number | string;
};
/**
* Notes that the user opened a conversation with a bot, in its own chat or
* a workspace (`bot_user_visits`), so the rail lists it by when they were
* last there. Callers must have checked the user reaches it.
*/
export default async function recordBotVisit({ user_id, bot_id }: Params) {
const now = Date.now();
await BunSQLite.sql({
sql: `INSERT INTO bot_user_visits (created_at, updated_at, bot_id, user_id, visited_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(bot_id, user_id) DO UPDATE SET visited_at = excluded.visited_at, updated_at = excluded.updated_at`,
values: [now, now, bot_id, user_id, now],
});
}
@@ -78,6 +78,9 @@ export default async function deleteUser({ actor_user_id, actor_user_types, user
await BunSQLite.sql({ sql: `DELETE FROM ${table} WHERE user_id = ?`, values: [user.id] });
}
await BunSQLite.sql({ sql: `DELETE FROM workspace_user_visits WHERE user_id = ?`, values: [user.id] });
await BunSQLite.sql({ sql: `DELETE FROM bot_user_visits WHERE user_id = ?`, values: [user.id] });
/**
* Their personal secrets, explicitly: foreign keys are off outside the
* server process.
@@ -41,6 +41,7 @@ export default async function deleteWorkspace({ user_id, workspace_id }: Params)
* Explicitly, since foreign keys are off outside the server process.
*/
await BunSQLite.sql({ sql: `DELETE FROM bot_types WHERE workspace_id = ?`, values: [workspace.id] });
await BunSQLite.sql({ sql: `DELETE FROM workspace_user_visits WHERE workspace_id = ?`, values: [workspace.id] });
await deleteChatrooms({ workspace_id: workspace.id! });
const res = await BunSQLite.sql({
@@ -20,11 +20,12 @@ export default async function grabUserWorkspaces({
const res = await BunSQLite.sql<WorkspaceWithActivity>({
sql: `SELECT w.*,
COALESCE((SELECT MAX(s.unread) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND s.chatroom_id IS NULL AND s.hook_id IS NULL), 0) AS unread,
(SELECT MAX(s.last_activity_at) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND s.chatroom_id IS NULL AND s.hook_id IS NULL) AS last_activity_at
(SELECT MAX(s.last_activity_at) FROM bot_sessions s WHERE s.workspace_id = w.id AND s.user_id = ? AND s.chatroom_id IS NULL AND s.hook_id IS NULL) AS last_activity_at,
(SELECT v.visited_at FROM workspace_user_visits v WHERE v.workspace_id = w.id AND v.user_id = ?) AS last_visited_at
FROM workspaces w
WHERE w.archived = 0 AND ${access.sql}
ORDER BY w.id ASC`,
values: [user_id, user_id, ...access.values],
values: [user_id, user_id, user_id, ...access.values],
});
return res.payload || [];
@@ -0,0 +1,22 @@
import BunSQLite from "@moduletrace/bun-sqlite";
type Params = {
user_id: number | string;
workspace_id: number | string;
};
/**
* Notes that the user opened a workspace (`workspace_user_visits`), so the
* rail lists it by when they were last there. Callers must have checked
* the user reaches it.
*/
export default async function recordWorkspaceVisit({ user_id, workspace_id }: Params) {
const now = Date.now();
await BunSQLite.sql({
sql: `INSERT INTO workspace_user_visits (created_at, updated_at, workspace_id, user_id, visited_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(workspace_id, user_id) DO UPDATE SET visited_at = excluded.visited_at, updated_at = excluded.updated_at`,
values: [now, now, workspace_id, user_id, now],
});
}
@@ -1,28 +0,0 @@
import { setCookies } from "@/src/utils/cookies";
import isSecureRequest from "@/src/utils/is-secure-request";
import lastVisitedWorkspaceCookies from "@/src/utils/last-visited-workspace-cookies";
type Params = {
req: Request;
res: Response;
workspace_id: number | string;
};
/**
* The page's response with the last-visited workspace cookie set, so the
* rail lists this workspace first from the next page on. Called from the
* workspace pages' `res_transform`.
*/
export default function withLastVisitedWorkspaceCookies({ req, res, workspace_id }: Params): Response {
const new_res = res.clone();
setCookies(
new_res,
lastVisitedWorkspaceCookies({
workspace_id,
secure: isSecureRequest({ req }),
}),
);
return new_res;
}
@@ -1,6 +1,7 @@
import { useState, type ReactNode } from "react";
import Span from "@moduletrace/twui/layout/Span";
import { AppData } from "@/src/data/app-data";
import orderByLastVisit from "@/src/utils/order-by-last-visit";
import type { BotWithLastMessage } from "@/src/types";
import pickRailBots from "../(utils)/pick-rail-bots";
import AllBotsModal from "./all-bots-modal";
@@ -12,7 +13,8 @@ import RailSeeAllStone from "./rail-see-all-stone";
type Props = {
title: string;
/**
* The worker bots, latest activity first.
* The worker bots, latest activity first: the order of those the user
* hasn't visited yet.
*/
workers: BotWithLastMessage[];
selected_id?: number;
@@ -29,12 +31,13 @@ type Props = {
};
/**
* A section of bots in the rail: the latest `AppData.RailRecentBots` to be
* active (and any that want attention), then "See all bots" for the rest,
* A section of bots in the rail: the latest `AppData.RailRecentBots` visited
* (and any that want attention), then "See all bots" for the rest,
* which lists them all in a modal.
*/
export default function RailBotsSection({ title, workers, selected_id, workspace_id, hrefFor, empty, action }: Props) {
export default function RailBotsSection({ title, workers: listed, selected_id, workspace_id, hrefFor, empty, action }: Props) {
const [open, setOpen] = useState(false);
const workers = orderByLastVisit({ items: listed });
const { shown, hidden } = pickRailBots({ workers, selected_id, limit: AppData.RailRecentBots });
return (
@@ -1,8 +1,7 @@
import { useContext, useState } from "react";
import Span from "@moduletrace/twui/layout/Span";
import { AppData } from "@/src/data/app-data";
import { AppContext } from "@/src/pages/__root";
import orderRailWorkspaces from "@/src/utils/order-rail-workspaces";
import orderByLastVisit from "@/src/utils/order-by-last-visit";
import type { WorkspaceWithActivity } from "@/src/types";
import { AddFlowContext } from "../(data)/add-flow-context";
import AllWorkspacesModal from "./all-workspaces-modal";
@@ -18,17 +17,13 @@ type Props = {
};
/**
* The user's workspaces, with a "+" to create one: the last visited one
* first, then the rest up to `AppData.RailRecentWorkspaces`, then "See all
* The user's workspaces, with a "+" to create one: the latest visited
* first, then the rest, up to `AppData.RailRecentWorkspaces`, then "See all
* workspaces" for the others, which lists them all in a modal.
*/
export default function RailWorkspacesSection({ workspaces: listed, selected_id }: Props) {
const { openForm } = useContext(AddFlowContext);
const { pageProps } = useContext(AppContext);
const workspaces = orderRailWorkspaces({
workspaces: listed,
first_id: pageProps?.last_visited_workspace_id,
});
const workspaces = orderByLastVisit({ items: listed });
const [open, setOpen] = useState(false);
const shown = workspaces.slice(0, AppData.RailRecentWorkspaces);
const hidden = workspaces.slice(AppData.RailRecentWorkspaces);
+2 -2
View File
@@ -2,7 +2,7 @@ import type { BotWithLastMessage } from "@/src/types";
type Params = {
/**
* The worker bots, latest activity first.
* The worker bots, in the order the rail lists them.
*/
workers: BotWithLastMessage[];
/**
@@ -13,7 +13,7 @@ type Params = {
};
/**
* Which workers the rail lists: the `limit` most recently active, plus any
* Which workers the rail lists: the first `limit`, plus any
* older one that's open, unread or needs the user, so nothing that wants
* attention hides behind "See all bots". The rest go to `hidden`, in the
* same order.
-2
View File
@@ -8,7 +8,6 @@ import isUnknownSettingsPath from "../utils/is-unknown-settings-path";
import { SettingsDefaultPath } from "../dict/settings-pages-dict";
import grabInstallName from "../functions/backend/db/app-settings/grab-install-name";
import grabInstallIcon from "../functions/backend/db/app-settings/grab-install-icon";
import readLastVisitedWorkspace from "../utils/read-last-visited-workspace";
/**
* Routing for a local install. There are no public pages:
@@ -85,7 +84,6 @@ const server: BunextPageServerFn<PagePropsType> = async ({ req, url }) => {
user_types,
install_name: await grabInstallName().catch(() => ""),
install_icon: await grabInstallIcon().catch(() => null),
last_visited_workspace_id: readLastVisitedWorkspace({ req }),
},
};
};
@@ -1,5 +1,6 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabConversationProps from "@/src/functions/backend/db/bot-sessions/grab-conversation-props";
import recordBotVisit from "@/src/functions/backend/db/bots/record-bot-visit";
import withLastVisitedBotCookies from "@/src/functions/server/with-last-visited-bot-cookies";
import type { PagePropsType, PageQueryObject } from "@/src/types";
import type { BunextPageServerFn } from "@moduletrace/bunext/types";
@@ -35,6 +36,8 @@ export const server: BunextPageServerFn<PagePropsType> = async (params) => {
const bot_id = props.bot.id;
await recordBotVisit({ user_id: user.id, bot_id });
return {
props,
res_transform(res) {
@@ -1,7 +1,8 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabConversationProps from "@/src/functions/backend/db/bot-sessions/grab-conversation-props";
import recordBotVisit from "@/src/functions/backend/db/bots/record-bot-visit";
import recordWorkspaceVisit from "@/src/functions/backend/db/workspaces/record-workspace-visit";
import withLastVisitedBotCookies from "@/src/functions/server/with-last-visited-bot-cookies";
import withLastVisitedWorkspaceCookies from "@/src/functions/server/with-last-visited-workspace-cookies";
import type { PagePropsType, PageQueryObject } from "@/src/types";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import type { BunextPageServerFn } from "@moduletrace/bunext/types";
@@ -38,16 +39,17 @@ export const server: BunextPageServerFn<PagePropsType> = async (params) => {
}
const bot_id = props.bot.id;
const workspace_id = props.workspace?.id;
await recordBotVisit({ user_id: user.id, bot_id });
if (props.workspace?.id) {
await recordWorkspaceVisit({ user_id: user.id, workspace_id: props.workspace.id });
}
return {
props,
res_transform(res) {
const with_bot = withLastVisitedBotCookies({ req: params.req, res, bot_id });
return workspace_id
? withLastVisitedWorkspaceCookies({ req: params.req, res: with_bot, workspace_id })
: with_bot;
return withLastVisitedBotCookies({ req: params.req, res, bot_id });
},
};
};
@@ -1,8 +1,8 @@
import withLastVisitedWorkspaceCookies from "@/src/functions/server/with-last-visited-workspace-cookies";
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabChatroomMessages from "@/src/functions/backend/db/chatrooms/grab-chatroom-messages";
import grabUserChatroom from "@/src/functions/backend/db/chatrooms/grab-user-chatroom";
import markChatroomRead from "@/src/functions/backend/db/chatrooms/mark-chatroom-read";
import recordWorkspaceVisit from "@/src/functions/backend/db/workspaces/record-workspace-visit";
import grabWorkspaceRailProps from "@/src/functions/backend/db/workspaces/grab-workspace-rail-props";
import type { PagePropsType, PageQueryObject } from "@/src/types";
import chatroomHref from "@/src/utils/chatroom-href";
@@ -38,6 +38,7 @@ export const server: BunextPageServerFn<PagePropsType> = async (params) => {
}
await markChatroomRead({ chatroom_id: chatroom.id, user_id: user.id });
await recordWorkspaceVisit({ user_id: user.id, workspace_id: rail.workspace.id! });
return {
props: {
@@ -45,8 +46,5 @@ export const server: BunextPageServerFn<PagePropsType> = async (params) => {
chatroom: { ...chatroom, unread: 0 },
chatroom_messages: await grabChatroomMessages({ chatroom_id: chatroom.id }),
},
res_transform(res) {
return withLastVisitedWorkspaceCookies({ req: params.req, res, workspace_id: Number(rail.workspace.id) });
},
};
};
@@ -1,6 +1,6 @@
import withLastVisitedWorkspaceCookies from "@/src/functions/server/with-last-visited-workspace-cookies";
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabUserChatrooms from "@/src/functions/backend/db/chatrooms/grab-user-chatrooms";
import recordWorkspaceVisit from "@/src/functions/backend/db/workspaces/record-workspace-visit";
import grabWorkspaceRailProps from "@/src/functions/backend/db/workspaces/grab-workspace-rail-props";
import { AdminHomePath } from "@/src/dict/admin-sections-dict";
import type { PagePropsType, PageQueryObject } from "@/src/types";
@@ -23,12 +23,11 @@ export const server: BunextPageServerFn<PagePropsType> = async (params) => {
return { redirect: { destination: AdminHomePath } };
}
await recordWorkspaceVisit({ user_id: user.id, workspace_id: rail.workspace.id! });
const chatrooms = await grabUserChatrooms({ user_id: user.id, workspace_id: Number(rail.workspace.id) });
return {
props: { ...rail, chatrooms },
res_transform(res) {
return withLastVisitedWorkspaceCookies({ req: params.req, res, workspace_id: Number(rail.workspace.id) });
},
};
};
@@ -1,9 +1,9 @@
import withLastVisitedWorkspaceCookies from "@/src/functions/server/with-last-visited-workspace-cookies";
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabUserWorkspaces from "@/src/functions/backend/db/workspaces/grab-user-workspaces";
import grabWorkspaceActivity from "@/src/functions/backend/db/workspaces/grab-workspace-activity";
import grabWorkspaceBots from "@/src/functions/backend/db/workspaces/grab-workspace-bots";
import grabWorkspaceComputers from "@/src/functions/backend/db/workspaces/grab-workspace-computers";
import recordWorkspaceVisit from "@/src/functions/backend/db/workspaces/record-workspace-visit";
import grabTasks from "@/src/functions/backend/db/tasks/grab-tasks";
import { AdminHomePath } from "@/src/dict/admin-sections-dict";
import type { PagePropsType, PageQueryObject } from "@/src/types";
@@ -35,6 +35,8 @@ export const server: BunextPageServerFn<PagePropsType> = async (params) => {
const workspace_id = Number(workspace.id);
await recordWorkspaceVisit({ user_id: user.id, workspace_id });
const [workspace_bots, workspace_computers, workspace_activity, workspace_tasks] =
await Promise.all([
grabWorkspaceBots({ user_id: user.id, workspace_id }),
@@ -55,8 +57,5 @@ export const server: BunextPageServerFn<PagePropsType> = async (params) => {
workspace_activity,
workspace_tasks,
},
res_transform(res) {
return withLastVisitedWorkspaceCookies({ req: params.req, res, workspace_id });
},
};
};
-4
View File
@@ -36,10 +36,6 @@ export const server: BunextPageServerFn = async ({ req }) => {
name: AppData["LastVisitedBotCookieName"],
httpOnly: true,
},
{
name: AppData["LastVisitedWorkspaceCookieName"],
httpOnly: true,
},
]);
return new_res;
},
+8 -5
View File
@@ -88,6 +88,10 @@ export type BotWithLastMessage = BotWithFace & {
last_activity_at?: number | null;
last_message_text?: string | null;
last_message_at?: number | null;
/**
* When this user last opened a conversation with it (`bot_user_visits`).
*/
last_visited_at?: number | null;
};
/**
@@ -260,6 +264,10 @@ export type BotSessionListItem = BUN_SQLITE_COBBLE_BOT_SESSIONS & {
export type WorkspaceWithActivity = BUN_SQLITE_COBBLE_WORKSPACES & {
unread: number;
last_activity_at?: number | null;
/**
* When this user last opened it (`workspace_user_visits`).
*/
last_visited_at?: number | null;
};
/**
@@ -1990,11 +1998,6 @@ export type PagePropsType = {
* General, and the root's icon links).
*/
install_icon?: PwaInstallIcon | null;
/**
* The workspace this browser was last in (a cookie read in the root):
* the rail lists it first.
*/
last_visited_workspace_id?: number | null;
/**
* The release the server is running, for the General settings page.
*/
@@ -1,27 +0,0 @@
import { AppData } from "@/src/data/app-data";
import type { CookieOptions } from "./cookies";
type Params = {
workspace_id: number | string;
/**
* From `isSecureRequest`, so plain HTTP over a VPN still keeps it.
*/
secure: boolean;
};
/**
* The cookie that remembers the workspace this browser was last in, for
* `setCookies`: read back by `readLastVisitedWorkspace` in the root, so the
* rail lists that workspace first. It never decides where `/admin/bots`
* lands. `HttpOnly`, since only the server reads it.
*/
export default function lastVisitedWorkspaceCookies({ workspace_id, secure }: Params): CookieOptions[] {
return [
{
name: AppData["LastVisitedWorkspaceCookieName"],
value: String(workspace_id),
secure,
maxAge: AppData["LastVisitedCookieMaxAgeSeconds"],
},
];
}
+37
View File
@@ -0,0 +1,37 @@
import { describe, expect, test } from "bun:test";
import orderByLastVisit from "./order-by-last-visit";
type Item = { id: number; last_visited_at?: number | null };
function ids(items: Item[]) {
return orderByLastVisit({ items }).map((item) => item.id);
}
describe("orderByLastVisit", () => {
test("visited items lead, latest first, the rest keep their order", () => {
expect(
ids([
{ id: 1 },
{ id: 2, last_visited_at: 100 },
{ id: 3 },
{ id: 4, last_visited_at: 300 },
{ id: 5, last_visited_at: 200 },
]),
).toEqual([4, 5, 2, 1, 3]);
});
test("unchanged when none were visited", () => {
expect(ids([{ id: 2 }, { id: 1, last_visited_at: null }])).toEqual([2, 1]);
});
test("leaves the list it was given alone", () => {
const items = [
{ id: 1, last_visited_at: 1 },
{ id: 2, last_visited_at: 2 },
];
orderByLastVisit({ items });
expect(items.map((item) => item.id)).toEqual([1, 2]);
});
});
+15
View File
@@ -0,0 +1,15 @@
type Params<T> = {
items: T[];
};
/**
* A rail list (workspaces, bots): what the user has visited first, latest
* first, then the rest in their order.
*/
export default function orderByLastVisit<T extends { last_visited_at?: number | null }>({ items }: Params<T>): T[] {
const visited = items
.filter((item) => item.last_visited_at)
.sort((a, b) => Number(b.last_visited_at) - Number(a.last_visited_at));
return [...visited, ...items.filter((item) => !item.last_visited_at)];
}
-21
View File
@@ -1,21 +0,0 @@
import { describe, expect, test } from "bun:test";
import type { WorkspaceWithActivity } from "@/src/types";
import orderRailWorkspaces from "./order-rail-workspaces";
const workspaces = [1, 2, 3, 4].map((id) => ({ id, name: `W${id}` }) as WorkspaceWithActivity);
function ids(list: WorkspaceWithActivity[]) {
return list.map((workspace) => workspace.id);
}
describe("orderRailWorkspaces", () => {
test("the last visited workspace leads, the rest keep their order", () => {
expect(ids(orderRailWorkspaces({ workspaces, first_id: 3 }))).toEqual([3, 1, 2, 4]);
});
test("unchanged without one, or when it isn't listed", () => {
expect(ids(orderRailWorkspaces({ workspaces }))).toEqual([1, 2, 3, 4]);
expect(ids(orderRailWorkspaces({ workspaces, first_id: null }))).toEqual([1, 2, 3, 4]);
expect(ids(orderRailWorkspaces({ workspaces, first_id: 9 }))).toEqual([1, 2, 3, 4]);
});
});
-23
View File
@@ -1,23 +0,0 @@
import type { WorkspaceWithActivity } from "@/src/types";
type Params = {
workspaces: WorkspaceWithActivity[];
/**
* The workspace this browser was last in (`readLastVisitedWorkspace`).
*/
first_id?: number | null;
};
/**
* The rail's workspaces with the last visited one first, the rest in
* their order. Unchanged when it isn't among them.
*/
export default function orderRailWorkspaces({ workspaces, first_id }: Params): WorkspaceWithActivity[] {
if (!first_id) return workspaces;
const first = workspaces.find((workspace) => Number(workspace.id) === Number(first_id));
if (!first) return workspaces;
return [first, ...workspaces.filter((workspace) => workspace !== first)];
}
-18
View File
@@ -1,18 +0,0 @@
import { AppData } from "@/src/data/app-data";
import { getCookie } from "./cookies";
import parsePositiveId from "./parse-positive-id";
type Params = {
req: Request;
};
/**
* The workspace this browser was last in, from the last-visited cookie
* (see `lastVisitedWorkspaceCookies`), or null. Only orders the rail, so a
* workspace the user no longer reaches just isn't in the list.
*/
export default function readLastVisitedWorkspace({ req }: Params): number | null {
return parsePositiveId({
value: getCookie(req, AppData["LastVisitedWorkspaceCookieName"]),
});
}