Compare commits

...
2 Commits
Author SHA1 Message Date
tben 01d6cffa8d Bump version to 0.28.12
CI / check (push) Canceled after 0s
Release image / image (release) Canceled after 0s
Release image / computer-image (release) Canceled after 0s
2026-11-26 06:04:31 +01:00
tben 8897f0b23f Let a knowledgebase document be read, and open its original
Clicking a document reads it over the list: written text as markdown, a file's extracted text as it is, cut at KnowledgebaseTextMaxChars and flagged when there is more. A file document's Open original loads its uploaded media row in the existing file preview, which crew managers now reach through grabKnowledgebaseDocumentMedia.

The bot composer's knowledgebase rows get the same documents list, read-only.
2026-11-26 06:04:26 +01:00
19 changed files with 457 additions and 172 deletions
+1 -1
View File
@@ -220,7 +220,7 @@ A user's access to an outside app (Gmail, Slack, ...) as themselves, reached thr
### Knowledgebases
A fourth extension kind (`ExtensionTables.knowledgebase`): `knowledgebases` given per bot (`bot_knowledgebases`), per workspace (`workspace_knowledgebases`) or every bot (`all_bots`), through the same add/remove/access/default paths as skills (`list_extensions` and `delete_extension` leave them out, and so do the proposal cards). Documents (`knowledgebase_documents`: an upload in private `media`, paradigm `knowledgebase-document`, or written `content`) are chunked into `knowledgebase_chunks` and embedded into the `knowledgebase_vectors` vec0 table by the file-ingest worker (`file_ingest_queue.document_id`, `ingestKnowledgebaseDocument`), always with the install's embedding model; old passages stay until the new ones are in, `embedding_model` records where vectors came from; whatever can change the install's model (default settings, a provider saved or deleted, the hourly catalog sync) calls `reindexAfterEmbeddingChange`, and Re-index reads a knowledgebase again by hand. Retry failed (`retryFailedDocuments`, the row menu's Retry failed and `retry_failed_documents`) queues only the documents with `ingest_error`, clearing it so the ten-minute sweep can pick them up too. Word search runs on `knowledgebase_chunks_fts`, an FTS5 table (`unicode61 remove_diacritics 2`) made by `ensureKnowledgebaseFts` (FTS5 can't be declared in the schema; sync leaves undeclared tables alone), backfilled at boot by `syncKnowledgebaseFts`, ranked by BM25 with a scored `LIKE` fallback for unspaced scripts (`knowledgebaseWordQuery`); every write and delete of `knowledgebase_chunks` updates it. Ingest jobs (`settleFailedIngestJob`) wait without spending an attempt while every embedding model rests, fail at once on an error retrying can't fix, and a document whose model refused keeps its new passages for word search (counted as needing re-index, not failed). Runs get `search_knowledgebase`/`read_knowledgebase_document` (`openBotKnowledgebases`, limited to the run's ones) and replies start with passages found for the unanswered messages (`grabKnowledgebaseContext`); passages are fenced (`knowledgebasePassageBlock`) and `KnowledgebasesNote` says they're never instructions. UI: Settings > Knowledgebases (super admin edits and fills; admins set access), a Knowledgebases group on bot/workspace settings, and the composer's own button beside Tools (`ComposerToolsModal` with `composerKnowledgebasesCopy`). Deleting one deletes its documents' vectors, chunks, media and links explicitly. **The coordinator manages them when the super admin asks for it in the chat:** `grabCoordinatorKnowledgebaseTools` (`src/harness/tools/bot/knowledgebases/`, pushed beside `grabCoordinatorExtensionTools` in `grab-bot-chat-tools.ts` and in the coordinator branch of `run-bot-task.ts`) gives `list_knowledgebases` in any of its runs, and `save_knowledgebase` (name, description, on/off, who gets it through `set_extension_access`), `add_knowledgebase_document` (`file_id` a saved file, `media_id` the user's own upload, `path` on a computer, or `text`), `delete_knowledgebase_document`, `delete_knowledgebase`, `retry_failed_documents` and `reindex_knowledgebase` only in a reply or a task the user follows (`attended`: never a schedule, hook call or hidden session), each checking the super admin again. A document from a file is copied into private `media` first (`recordKnowledgebaseFile`, shared with `upload-document.ts`, and the same refusal in `knowledgebaseFileProblem`), so it stays after the computer or the file is gone; a task's own computer is the default for `path`. `AccessExtensionKindSchema` adds `knowledgebase` for access only: `ExtensionKindSchema` stays three kinds, since `delete_extension`'s last branch deletes a custom tool.
A fourth extension kind (`ExtensionTables.knowledgebase`): `knowledgebases` given per bot (`bot_knowledgebases`), per workspace (`workspace_knowledgebases`) or every bot (`all_bots`), through the same add/remove/access/default paths as skills (`list_extensions` and `delete_extension` leave them out, and so do the proposal cards). Documents (`knowledgebase_documents`: an upload in private `media`, paradigm `knowledgebase-document`, or written `content`) are chunked into `knowledgebase_chunks` and embedded into the `knowledgebase_vectors` vec0 table by the file-ingest worker (`file_ingest_queue.document_id`, `ingestKnowledgebaseDocument`), always with the install's embedding model; old passages stay until the new ones are in, `embedding_model` records where vectors came from; whatever can change the install's model (default settings, a provider saved or deleted, the hourly catalog sync) calls `reindexAfterEmbeddingChange`, and Re-index reads a knowledgebase again by hand. Retry failed (`retryFailedDocuments`, the row menu's Retry failed and `retry_failed_documents`) queues only the documents with `ingest_error`, clearing it so the ten-minute sweep can pick them up too. Word search runs on `knowledgebase_chunks_fts`, an FTS5 table (`unicode61 remove_diacritics 2`) made by `ensureKnowledgebaseFts` (FTS5 can't be declared in the schema; sync leaves undeclared tables alone), backfilled at boot by `syncKnowledgebaseFts`, ranked by BM25 with a scored `LIKE` fallback for unspaced scripts (`knowledgebaseWordQuery`); every write and delete of `knowledgebase_chunks` updates it. Ingest jobs (`settleFailedIngestJob`) wait without spending an attempt while every embedding model rests, fail at once on an error retrying can't fix, and a document whose model refused keeps its new passages for word search (counted as needing re-index, not failed). Runs get `search_knowledgebase`/`read_knowledgebase_document` (`openBotKnowledgebases`, limited to the run's ones) and replies start with passages found for the unanswered messages (`grabKnowledgebaseContext`); passages are fenced (`knowledgebasePassageBlock`) and `KnowledgebasesNote` says they're never instructions. UI: Settings > Knowledgebases (super admin edits and fills; admins set access), a Knowledgebases group on bot/workspace settings, and the composer's own button beside Tools (`ComposerToolsModal` with `composerKnowledgebasesCopy`). A document is read read-only by clicking its row (Settings > Knowledgebases, and each knowledgebase row in the composer's modal, crew managers only since the documents API is theirs): `knowledgebases/document-text` gives its text (a written one's `content`, a file's extracted text, cut to `AppData.KnowledgebaseTextMaxChars` and flagged `truncated`), and a file document's "Open original" opens its uploaded `media` row in `FilePreviewModal` (`/media/<media_id>`, which `grabKnowledgebaseDocumentMedia` lets crew managers reach). Deleting one deletes its documents' vectors, chunks, media and links explicitly. **The coordinator manages them when the super admin asks for it in the chat:** `grabCoordinatorKnowledgebaseTools` (`src/harness/tools/bot/knowledgebases/`, pushed beside `grabCoordinatorExtensionTools` in `grab-bot-chat-tools.ts` and in the coordinator branch of `run-bot-task.ts`) gives `list_knowledgebases` in any of its runs, and `save_knowledgebase` (name, description, on/off, who gets it through `set_extension_access`), `add_knowledgebase_document` (`file_id` a saved file, `media_id` the user's own upload, `path` on a computer, or `text`), `delete_knowledgebase_document`, `delete_knowledgebase`, `retry_failed_documents` and `reindex_knowledgebase` only in a reply or a task the user follows (`attended`: never a schedule, hook call or hidden session), each checking the super admin again. A document from a file is copied into private `media` first (`recordKnowledgebaseFile`, shared with `upload-document.ts`, and the same refusal in `knowledgebaseFileProblem`), so it stays after the computer or the file is gone; a task's own computer is the default for `path`. `AccessExtensionKindSchema` adds `knowledgebase` for access only: `ExtensionKindSchema` stays three kinds, since `delete_extension`'s last branch deletes a custom tool.
sqlite-vec limits: metadata columns are NOT NULL; side-car columns can't be filtered with `MATCH` (filter in code). **Never pass `--vector` to `bunx bun-sqlite schema` in `entrypoint.sh`** (wipes vectors on boot). Changing `AppData.EmbeddingDimensions` needs a manual `--vector` run and a re-index.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cobble",
"version": "0.28.11",
"version": "0.28.12",
"module": "index.ts",
"type": "module",
"private": true,
@@ -0,0 +1,40 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type {
BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS,
BUN_SQLITE_COBBLE_MEDIA,
} from "@/db/types/db";
import canManageCrew from "@/src/utils/rbac/can-manage-crew";
import grabUserTypes from "../users/grab-user-types";
type Params = {
media_id: number | string;
user_id: number | string;
};
/**
* A knowledgebase document's own file (its private `media` row) for a crew
* manager, the same people Settings > Knowledgebases shows its documents
* to, so "Open original" loads it.
*/
export default async function grabKnowledgebaseDocumentMedia({
media_id,
user_id,
}: Params): Promise<BUN_SQLITE_COBBLE_MEDIA | null> {
const document = (
await BunSQLite.sql<Pick<BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS, "id">>({
sql: `SELECT id FROM knowledgebase_documents WHERE media_id = ? LIMIT 1`,
values: [Number(media_id)],
})
).payload?.[0];
if (!document?.id) return null;
if (!canManageCrew({ user_types: await grabUserTypes({ user_id }) })) return null;
const media = await BunSQLite.sql<BUN_SQLITE_COBBLE_MEDIA>({
sql: `SELECT * FROM media WHERE id = ? LIMIT 1`,
values: [Number(media_id)],
});
return media.payload?.[0] || null;
}
@@ -5,7 +5,7 @@ type Params = {
document: {
source?: string | null;
content?: string | null;
media_id?: number | null;
media_id?: number | string | null;
name?: string | null;
mime_type?: string | null;
};
@@ -18,11 +18,12 @@ type Params = {
export default async function grabKnowledgebaseDocumentText({ document }: Params) {
if (document.source == "text") return document.content || "";
if (!document.media_id) return "";
const media_id = Number(document.media_id) || 0;
if (!media_id) return "";
const media = await BunSQLite.sql<{ media_write_path?: string; text_content?: string }>({
sql: `SELECT media_write_path, text_content FROM media WHERE id = ? LIMIT 1`,
values: [document.media_id],
values: [media_id],
}).then((res) => res.payload?.[0]);
return (
@@ -1,6 +1,7 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS } from "@/db/types/db";
import type { KnowledgebaseDocumentsPayload } from "@/src/types";
import grabInstallEmbeddingModel from "./grab-install-embedding-model";
import grabKnowledgebase from "./grab-knowledgebase";
import { KnowledgebaseDocumentIndexingSql } from "./knowledgebase-document-indexing-sql";
import parseKnowledgebaseDocumentRow from "./parse-knowledgebase-document-row";
@@ -10,7 +11,8 @@ type Params = {
};
/**
* A knowledgebase's documents, newest first, without their text.
* A knowledgebase's documents, newest first, without their text, and the
* install's embedding model for their lines.
*/
export default async function listKnowledgebaseDocuments({
knowledgebase_id,
@@ -18,7 +20,7 @@ export default async function listKnowledgebaseDocuments({
const knowledgebase = await grabKnowledgebase({ knowledgebase_id });
const rows = await BunSQLite.sql<BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS & { indexing?: number }>({
sql: `SELECT id, knowledgebase_id, name, source, mime_type, size, chunk_count, embedding_model,
sql: `SELECT id, knowledgebase_id, name, source, media_id, mime_type, size, chunk_count, embedding_model,
ingested_at, ingest_error, created_at, ${KnowledgebaseDocumentIndexingSql} AS indexing
FROM knowledgebase_documents d WHERE knowledgebase_id = ? ORDER BY id DESC`,
values: [knowledgebase.id],
@@ -27,5 +29,6 @@ export default async function listKnowledgebaseDocuments({
return {
knowledgebase_id: knowledgebase.id,
documents: (rows.payload || []).map((row) => parseKnowledgebaseDocumentRow({ row })),
embedding_model: await grabInstallEmbeddingModel(),
};
}
@@ -0,0 +1,25 @@
import { describe, expect, test } from "bun:test";
import type { BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS } from "@/db/types/db";
import parseKnowledgebaseDocumentRow from "./parse-knowledgebase-document-row";
const parse = ({ media_id }: { media_id?: unknown }) =>
parseKnowledgebaseDocumentRow({
row: {
id: 1,
knowledgebase_id: 2,
name: "notes.md",
source: "file",
media_id,
} as BUN_SQLITE_COBBLE_KNOWLEDGEBASE_DOCUMENTS,
});
describe("parseKnowledgebaseDocumentRow", () => {
test("carries the file's media row, which Open original loads", () => {
expect(parse({ media_id: 12 }).media_id).toBe(12);
});
test("has no media row for a written document or a missing one", () => {
expect(parse({ media_id: undefined }).media_id).toBeNull();
expect(parse({ media_id: "" }).media_id).toBeNull();
});
});
@@ -18,6 +18,7 @@ export default function parseKnowledgebaseDocumentRow({ row }: Params): Knowledg
knowledgebase_id: Number(row.knowledgebase_id),
name: row.name || "",
source: row.source == "text" ? "text" : "file",
media_id: Number(row.media_id) || null,
mime_type: row.mime_type || "",
size: Number(row.size) || 0,
chunk_count: Number(row.chunk_count) || 0,
@@ -2,6 +2,7 @@ import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_MEDIA, BunSQLiteTables } from "@/db/types/db";
import grabSharedPictureMedia from "@/src/functions/backend/db/access/grab-shared-picture-media";
import grabBotFileMedia from "@/src/functions/backend/db/bot-files/grab-bot-file-media";
import grabKnowledgebaseDocumentMedia from "@/src/functions/backend/db/knowledgebases/grab-knowledgebase-document-media";
import grabTaskMediaFile from "@/src/functions/backend/db/tasks/grab-task-media-file";
type Params = {
@@ -20,7 +21,9 @@ type Params = {
* - a bot's or workspace's file, to whoever reaches the folder it lives in
* (`grabBotFileMedia`),
* - a file attached to a task, to whoever reaches the task
* (`grabTaskMediaFile`).
* (`grabTaskMediaFile`),
* - a knowledgebase document's file, to crew managers
* (`grabKnowledgebaseDocumentMedia`).
*
* Null when it is not theirs to see, so a request never turns into a path
* before this has passed.
@@ -51,6 +54,7 @@ export default async function grabUserMedia({
(await grabSharedPictureMedia({ media_id })) ||
(await grabBotFileMedia({ media_id, user_id })) ||
(await grabTaskMediaFile({ media_id, user_id })) ||
(await grabKnowledgebaseDocumentMedia({ media_id, user_id })) ||
undefined
);
}
@@ -22,6 +22,7 @@ const document: KnowledgebaseDocument = {
knowledgebase_id: 3,
name: "leave.md",
source: "file",
media_id: null,
mime_type: "md",
size: 2048,
chunk_count: 4,
@@ -31,6 +31,11 @@ type Props = {
add_hint: string;
add_noun: string;
onAdd: (params: { kind: BotExtensionKind; id: number }) => Promise<boolean>;
/**
* Reads a knowledgebase's documents. Only crew managers: the documents
* API is theirs.
*/
onOpenItem?: (item: BotExtension) => void;
onRemove: (params: {
kind: BotExtensionKind;
id: number;
@@ -55,6 +60,7 @@ export default function ComposerExtensionsList({
add_hint,
add_noun,
onAdd,
onOpenItem,
onRemove,
}: Props) {
return (
@@ -69,6 +75,11 @@ export default function ComposerExtensionsList({
key={`${item.kind}:${item.id}`}
item={item}
busy={busy == `${item.kind}:${item.id}`}
onOpen={
can_manage && item.kind == "knowledgebase" && onOpenItem
? () => onOpenItem(item)
: undefined
}
onRemove={
can_manage && item.source == "bot"
? () =>
@@ -2,14 +2,19 @@ import Button from "@moduletrace/twui/layout/Button";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { X } from "lucide-react";
import { FileText, X } from "lucide-react";
import extensionIcon from "@/src/components/general/extension-icon";
import RowIconButton from "@/src/components/general/row-icon-button";
import type { BotExtension } from "@/src/types";
import extensionStateNote from "@/src/utils/extension-state-note";
type Props = {
item: BotExtension;
busy?: boolean;
/**
* Reads a knowledgebase's documents; not given for anything else.
*/
onOpen?: () => void;
/**
* Takes it from the bot; not given for a workspace's own or when the
* user can't.
@@ -22,7 +27,7 @@ type Props = {
* the composer's modals. One that isn't working says so
* (`extensionStateNote`), one that's off is struck out.
*/
export default function ComposerToolRow({ item, busy, onRemove }: Props) {
export default function ComposerToolRow({ item, busy, onOpen, onRemove }: Props) {
const Icon = extensionIcon({ kind: item.kind });
const notes = [
item.detail,
@@ -50,6 +55,13 @@ export default function ComposerToolRow({ item, busy, onRemove }: Props) {
</Span>
) : null}
</Stack>
{onOpen ? (
<RowIconButton
icon={FileText}
title={`Open ${item.name}`}
onClick={onOpen}
/>
) : null}
{onRemove ? (
<Button
title={`Remove ${item.name}`}
@@ -13,6 +13,7 @@ import type {
BotExtensionsPayload,
ConnectorAppIcon,
} from "@/src/types";
import KnowledgebaseDocumentsModal from "@/src/pages/admin/settings/knowledgebases/(partials)/knowledgebase-documents-modal";
import ComposerConnectorsSection from "./composer-connectors-section";
import ComposerExtensionsList from "./composer-extensions-list";
import { twMerge } from "tailwind-merge";
@@ -108,6 +109,11 @@ export default function ComposerToolsModal({
onConnectorApps,
}: Props) {
const [open, setOpen] = useState(false);
/**
* The knowledgebase whose documents are read from its row; a read-only
* look at what the bot searches.
*/
const [viewing, setViewing] = useState<BotExtension>();
const count = attached.length;
const total = count + (connectors ? Number(connector_count || 0) : 0);
const has_problem = attached.some(
@@ -120,77 +126,87 @@ export default function ComposerToolsModal({
: copy.empty_label;
return (
<Modal
target={
<Button
title={copy.title}
type="button"
variant="ghost"
color="gray"
size="small"
beforeIcon={
<Row className="items-center gap-1! flex-nowrap">
{app_icons.map((app, index) => (
<Img
key={app.id}
src={app.logo}
alt={app.name}
title={app.name}
size={16}
circle
className={twMerge(
"shrink-0 border border-hairline bg-white object-contain relative",
index > 0 ? "-ml-1.5" : "",
)}
style={{ zIndex: index + 1 }}
/>
))}
<TriggerIcon size={12} aria-hidden />
</Row>
}
className={twMerge(
"shrink-0 gap-1! px-2! py-0.5! text-[12px] leading-4 text-ink-secondary",
)}
>
{label}
</Button>
}
targetWrapperProps={{ className: "shrink-0" }}
open={open}
setOpen={setOpen}
className="max-w-lg bg-paper p-6"
>
<Stack className="w-full gap-1! items-stretch">
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">
{copy.title}
</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{total ? copy.some : copy.none}
</Span>
</Stack>
<>
<Modal
target={
<Button
title={copy.title}
type="button"
variant="ghost"
color="gray"
size="small"
beforeIcon={
<Row className="items-center gap-1! flex-nowrap">
{app_icons.map((app, index) => (
<Img
key={app.id}
src={app.logo}
alt={app.name}
title={app.name}
size={16}
circle
className={twMerge(
"shrink-0 border border-hairline bg-white object-contain relative",
index > 0 ? "-ml-1.5" : "",
)}
style={{ zIndex: index + 1 }}
/>
))}
<TriggerIcon size={12} aria-hidden />
</Row>
}
className={twMerge(
"shrink-0 gap-1! px-2! py-0.5! text-[12px] leading-4 text-ink-secondary",
)}
>
{label}
</Button>
}
targetWrapperProps={{ className: "shrink-0" }}
open={open}
setOpen={setOpen}
className="max-w-lg bg-paper p-6"
>
<Stack className="w-full gap-1! items-stretch">
<H2 className="text-lg! leading-6! tracking-normal! font-bold text-ink">
{copy.title}
</H2>
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{total ? copy.some : copy.none}
</Span>
</Stack>
<ComposerExtensionsList
id={copy.id}
label={copy.title}
items={attached}
addable={addable}
can_manage={can_manage}
busy={busy}
add_hint={copy.add_hint}
add_noun={copy.add_noun}
onAdd={onAdd}
onRemove={onRemove}
/>
<ComposerExtensionsList
id={copy.id}
label={copy.title}
items={attached}
addable={addable}
can_manage={can_manage}
busy={busy}
add_hint={copy.add_hint}
add_noun={copy.add_noun}
onAdd={onAdd}
onOpenItem={setViewing}
onRemove={onRemove}
/>
{connectors ? (
<ComposerConnectorsSection
bot_id={connectors.bot_id}
workspace_id={connectors.workspace_id}
open={open}
onCount={onConnectorCount}
onApps={onConnectorApps}
{connectors ? (
<ComposerConnectorsSection
bot_id={connectors.bot_id}
workspace_id={connectors.workspace_id}
open={open}
onCount={onConnectorCount}
onApps={onConnectorApps}
/>
) : null}
</Modal>
{viewing ? (
<KnowledgebaseDocumentsModal
knowledgebase={{ id: viewing.id, name: viewing.name }}
can_edit={false}
onClose={() => setViewing(undefined)}
/>
) : null}
</Modal>
</>
);
}
@@ -21,6 +21,7 @@ const PollMs = 4000;
*/
export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params) {
const [documents, setDocuments] = useState<KnowledgebaseDocument[]>();
const [embedding_model, setEmbeddingModel] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState<Status>();
@@ -30,8 +31,10 @@ export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params)
body: { knowledgebase_id },
});
if (res.success && res.singleRes) setDocuments(res.singleRes.documents);
else setStatus({ error: true, msg: res.msg || "Couldn't load the documents." });
if (res.success && res.singleRes) {
setDocuments(res.singleRes.documents);
setEmbeddingModel(res.singleRes.embedding_model);
} else setStatus({ error: true, msg: res.msg || "Couldn't load the documents." });
};
useEffect(() => {
@@ -62,6 +65,7 @@ export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params)
}
setDocuments(res.singleRes.documents);
setEmbeddingModel(res.singleRes.embedding_model);
setStatus({ success: true, msg: res.msg || "Saved." });
return true;
};
@@ -116,5 +120,5 @@ export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params)
});
};
return { documents, busy, status, upload, saveText, remove, retry };
return { documents, embedding_model, busy, status, upload, saveText, remove, retry };
}
@@ -12,6 +12,11 @@ type Props = {
document: KnowledgebaseDocument;
embedding_model: string | null;
busy?: boolean;
/**
* Reads the document over the list: its text, and the original behind
* "Open original".
*/
onOpen?: () => void;
/**
* Opens a text document to edit; not given for a file or when the user
* can't edit.
@@ -28,11 +33,12 @@ type Props = {
* One document in a knowledgebase: what it is and how much of it bots can
* search, or why it couldn't be read.
*/
export default function KnowledgebaseDocumentRow({ document, embedding_model, busy, onEdit, onRetry, onDelete }: Props) {
export default function KnowledgebaseDocumentRow({ document, embedding_model, busy, onOpen, onEdit, onRetry, onDelete }: Props) {
return (
<SettingsListRow
avatar={<IconTile Icon={document.source == "text" ? NotebookPen : FileText} />}
title={document.name}
onOpen={onOpen}
title_icon={
<IndexStateMark
state={knowledgebaseIndexState({
@@ -0,0 +1,127 @@
import { useEffect, useState } from "react";
import Loading from "@moduletrace/twui/elements/Loading";
import Modal from "@moduletrace/twui/elements/Modal";
import Button from "@moduletrace/twui/layout/Button";
import H2 from "@moduletrace/twui/layout/H2";
import Row from "@moduletrace/twui/layout/Row";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import { FileText } from "lucide-react";
import FilePreviewCode from "@/src/components/general/file-preview-code";
import FilePreviewMarkdown from "@/src/components/general/file-preview-markdown";
import FilePreviewModal from "@/src/components/general/file-preview-modal";
import TopModalEscape from "@/src/components/general/top-modal-escape";
import { AppData } from "@/src/data/app-data";
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
import type { KnowledgebaseDocument } from "@/src/types";
import SettingsStatus from "../../(partials)/settings-status";
type Props = {
document: KnowledgebaseDocument;
onClose: () => void;
};
/**
* One document over its list, read-only: the text bots search, written in
* or read from its file (markdown rendered, extracted text as it is), with
* the original a click away.
*/
export default function KnowledgebaseDocumentView({ document, onClose }: Props) {
const [text, set_text] = useState<{ content: string; truncated: boolean }>();
const [error, set_error] = useState<string>();
const [original, set_original] = useState(false);
useEffect(() => {
let live = true;
postAdminApi<{ content: string; truncated: boolean }>({
path: "knowledgebases/document-text",
body: { document_id: document.id },
}).then((res) => {
if (!live) return;
if (res.success && res.singleRes) set_text({ content: res.singleRes.content, truncated: res.singleRes.truncated });
else set_error(res.msg || "Couldn't open the document.");
});
return () => {
live = false;
};
}, [document.id]);
return (
<>
<Modal
open
setOpen={(next) => {
if (!next) onClose();
}}
className="max-w-[860px]! w-[95vw] h-[85vh] p-0 bg-paper flex flex-col overflow-hidden"
>
<TopModalEscape onClose={onClose} />
<Stack className="w-full min-w-0 gap-1! items-stretch pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
<Row className="w-full gap-3! flex-wrap sm:flex-nowrap items-center">
<Stack className="grow min-w-0 gap-0! items-stretch">
<H2
title={document.name}
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate min-w-0"
>
{document.name}
</H2>
{text?.truncated ? (
<Span className="text-xs leading-4 text-ink-secondary">
Showing its first {AppData.KnowledgebaseTextMaxChars.toLocaleString()} characters. Open
the original to read the rest.
</Span>
) : null}
</Stack>
{document.media_id ? (
<Button
title={`Open the original of ${document.name}`}
type="button"
variant="ghost"
color="gray"
size="small"
onClick={() => set_original(true)}
beforeIcon={<FileText size={16} aria-hidden />}
className="shrink-0 gap-1!"
>
Open original
</Button>
) : null}
</Row>
</Stack>
{error ? (
<Stack className="w-full p-5 items-start">
<SettingsStatus status={{ error: true, msg: error }} />
</Stack>
) : !text ? (
<Stack className="w-full grow items-center justify-center">
<Loading />
</Stack>
) : !text.content.trim() ? (
<Stack className="w-full p-5 items-start">
<Span className="text-[13px] leading-[18px] text-ink-secondary">
{document.source == "text"
? "This document has no text yet."
: "No text could be read from its file. Open the original to read it."}
</Span>
</Stack>
) : document.source == "text" ? (
<FilePreviewMarkdown text={text.content} />
) : (
<FilePreviewCode text={text.content} />
)}
</Modal>
{original && document.media_id ? (
<FilePreviewModal
name={document.name}
url={`/media/${document.media_id}`}
media_type="document"
size={document.size}
onClose={() => set_original(false)}
/>
) : null}
</>
);
}
@@ -5,25 +5,24 @@ import Row from "@moduletrace/twui/layout/Row";
import { NotebookPen, Upload } from "lucide-react";
import { BotTextFileExtensions } from "@/src/dict/bot-file-dict";
import AddModalShell from "@/src/layouts/bots/(partials)/add-modal-shell";
import type { PublicKnowledgebase } from "@/src/types";
import type { KnowledgebaseDocument, PublicKnowledgebase } from "@/src/types";
import SettingsList from "../../(partials)/settings-list";
import SettingsStatus from "../../(partials)/settings-status";
import useKnowledgebaseDocuments from "../(hooks)/use-knowledgebase-documents";
import KnowledgebaseDocumentRow from "./knowledgebase-document-row";
import KnowledgebaseDocumentView from "./knowledgebase-document-view";
import KnowledgebaseTextForm from "./knowledgebase-text-form";
type Props = {
knowledgebase: PublicKnowledgebase;
/**
* Its id and name are all the list needs: the composer opens it too.
*/
knowledgebase: Pick<PublicKnowledgebase, "id" | "name">;
/**
* A super admin: adds, writes and deletes documents. Admins only read
* the list.
*/
can_edit: boolean;
/**
* The install's embedding model, to tell a document that needs
* re-indexing.
*/
embedding_model: string | null;
onClose: () => void;
};
@@ -31,16 +30,20 @@ type Props = {
* A knowledgebase's documents: each with how much of it is searchable,
* files to upload, and text to write straight in. A document is read
* (chunked and embedded) in the background; the list follows until it's
* done.
* done. Clicking one reads it over the list.
*/
export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, embedding_model, onClose }: Props) {
const { documents, busy, status, upload, saveText, remove, retry } = useKnowledgebaseDocuments({
export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, onClose }: Props) {
const { documents, embedding_model, busy, status, upload, saveText, remove, retry } = useKnowledgebaseDocuments({
knowledgebase_id: knowledgebase.id,
});
/**
* `new` writes a text document, a number edits that one.
*/
const [writing, setWriting] = useState<"new" | number>();
/**
* The document read over the list.
*/
const [viewing, set_viewing] = useState<KnowledgebaseDocument>();
const file_input = useRef<HTMLInputElement>(null);
if (writing) {
@@ -63,76 +66,84 @@ export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, e
}
return (
<AddModalShell
open
setOpen={(next) => !next && onClose()}
title={`Documents in ${knowledgebase.name}`}
description={`Upload ${BotTextFileExtensions.join(", ")} files, or write text straight in. Each is split into passages bots search.`}
>
{documents ? (
<SettingsList is_empty={!documents.length} empty="No documents yet.">
{documents.map((document) => (
<KnowledgebaseDocumentRow
key={document.id}
document={document}
embedding_model={embedding_model}
busy={busy}
onEdit={can_edit && document.source == "text" ? () => setWriting(document.id) : undefined}
onRetry={
can_edit && document.ingest_error && !document.indexing
? () => retry({ document })
: undefined
}
onDelete={can_edit ? () => remove({ document }) : undefined}
<>
<AddModalShell
open
setOpen={(next) => !next && onClose()}
title={`Documents in ${knowledgebase.name}`}
description={
can_edit
? `Upload ${BotTextFileExtensions.join(", ")} files, or write text straight in. Each is split into passages bots search. Click a document to read it.`
: "Each is split into passages bots search. Click a document to read it."
}
>
{documents ? (
<SettingsList is_empty={!documents.length} empty="No documents yet.">
{documents.map((document) => (
<KnowledgebaseDocumentRow
key={document.id}
document={document}
embedding_model={embedding_model}
busy={busy}
onOpen={() => set_viewing(document)}
onEdit={can_edit && document.source == "text" ? () => setWriting(document.id) : undefined}
onRetry={
can_edit && document.ingest_error && !document.indexing
? () => retry({ document })
: undefined
}
onDelete={can_edit ? () => remove({ document }) : undefined}
/>
))}
</SettingsList>
) : (
<Loading />
)}
{can_edit ? (
<Row className="gap-1!">
<input
ref={file_input}
type="file"
multiple
accept={BotTextFileExtensions.map((ext) => `.${ext}`).join(",")}
className="hidden"
onChange={(event) => {
const files = Array.from(event.target.files || []);
upload({ files }).catch(() => {});
event.target.value = "";
}}
/>
))}
</SettingsList>
) : (
<Loading />
)}
{can_edit ? (
<Row className="gap-1!">
<input
ref={file_input}
type="file"
multiple
accept={BotTextFileExtensions.map((ext) => `.${ext}`).join(",")}
className="hidden"
onChange={(event) => {
const files = Array.from(event.target.files || []);
upload({ files }).catch(() => {});
event.target.value = "";
}}
/>
<Button
title="Upload files"
type="button"
variant="ghost"
color="gray"
size="small"
loading={busy}
onClick={() => file_input.current?.click()}
beforeIcon={<Upload size={14} aria-hidden />}
className="gap-1!"
>
Upload files
</Button>
<Button
title="Write a document"
type="button"
variant="ghost"
color="gray"
size="small"
disabled={busy}
onClick={() => setWriting("new")}
beforeIcon={<NotebookPen size={14} aria-hidden />}
className="gap-1!"
>
Write a document
</Button>
</Row>
) : null}
<SettingsStatus status={status} />
</AddModalShell>
<Button
title="Upload files"
type="button"
variant="ghost"
color="gray"
size="small"
loading={busy}
onClick={() => file_input.current?.click()}
beforeIcon={<Upload size={14} aria-hidden />}
className="gap-1!"
>
Upload files
</Button>
<Button
title="Write a document"
type="button"
variant="ghost"
color="gray"
size="small"
disabled={busy}
onClick={() => setWriting("new")}
beforeIcon={<NotebookPen size={14} aria-hidden />}
className="gap-1!"
>
Write a document
</Button>
</Row>
) : null}
<SettingsStatus status={status} />
</AddModalShell>
{viewing ? <KnowledgebaseDocumentView document={viewing} onClose={() => set_viewing(undefined)} /> : null}
</>
);
}
@@ -22,7 +22,7 @@ type Props = {
knowledgebase: PublicKnowledgebase;
targets: ExtensionTargets;
/**
* The install's embedding model, for the documents' lines.
* The install's embedding model, for its index mark.
*/
embedding_model: string | null;
onChanged: (overview: KnowledgebasesOverviewPayload, msg: string) => void;
@@ -167,7 +167,6 @@ export default function KnowledgebaseRow({ selected, onSelected, knowledgebase,
<KnowledgebaseDocumentsModal
knowledgebase={knowledgebase}
can_edit={targets.can_edit}
embedding_model={embedding_model}
onClose={closeDocuments}
/>
) : null}
@@ -1,5 +1,7 @@
import { AppData } from "@/src/data/app-data";
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabKnowledgebaseDocumentRow from "@/src/functions/backend/db/knowledgebases/grab-knowledgebase-document-row";
import grabKnowledgebaseDocumentText from "@/src/functions/backend/db/knowledgebases/grab-knowledgebase-document-text";
import { KnowledgebaseDocumentIdRequestSchema } from "@/src/schemas/knowledgebase-schema";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
@@ -11,11 +13,19 @@ import type {
} from "@moduletrace/bunext/types";
/**
* Super admins and admins: a text document's title and content, loaded
* when it's opened to read or edit.
* Super admins and admins: a document's title and text, what was written in
* or what its file holds, loaded when it's opened to read or edit. Its
* first `AppData.KnowledgebaseTextMaxChars` characters, `truncated` when
* there are more.
*/
export const handler: BunextAPIRouteHandler<
APIResponseObject<{ document_id: number; name: string; content: string }>
APIResponseObject<{
document_id: number;
name: string;
source: "file" | "text";
content: string;
truncated: boolean;
}>
> = async ({ req, body }) => {
try {
if (req.method != "POST") {
@@ -34,14 +44,18 @@ export const handler: BunextAPIRouteHandler<
const { document_id } = parseWithSchema({ schema: KnowledgebaseDocumentIdRequestSchema, data: body });
const document = await grabKnowledgebaseDocumentRow({ document_id });
if (document.source != "text") {
throw new AppError(`Only a text document can be opened here.`);
}
const text = await grabKnowledgebaseDocumentText({ document });
const cap = AppData.KnowledgebaseTextMaxChars;
return {
success: true,
singleRes: { document_id: document.id, name: document.name || "", content: document.content || "" },
singleRes: {
document_id: document.id,
name: document.name || "",
source: document.source == "text" ? "text" : "file",
content: text.slice(0, cap),
truncated: text.length > cap,
},
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
+10
View File
@@ -2016,6 +2016,11 @@ export type KnowledgebaseDocument = {
knowledgebase_id: number;
name: string;
source: "file" | "text";
/**
* The uploaded file's private `media` row, for a file document: what
* "Open original" loads.
*/
media_id: number | null;
mime_type: string;
size: number;
chunk_count: number;
@@ -2036,6 +2041,11 @@ export type KnowledgebaseDocument = {
export type KnowledgebaseDocumentsPayload = {
knowledgebase_id: number;
documents: KnowledgebaseDocument[];
/**
* The install's embedding model, to tell a document it needs
* re-indexing.
*/
embedding_model: string | null;
};
export type KnowledgebasesOverviewPayload = ExtensionTargets & {