Retry failed knowledgebase documents, and tidy the settings rows

Failed documents can be read again on their own, from the row menu, a document, or retry_failed_documents. Knowledgebase and host directory actions move into a three-dot menu, and each mount shows whether it is a computer or a workspace.
This commit is contained in:
2026-11-19 16:28:01 +01:00
parent 6dc2859292
commit 52eab84f9a
22 changed files with 551 additions and 173 deletions
+1 -1
View File
@@ -212,7 +212,7 @@ A user's own running browser, reached over a browser MCP server they run beside
### 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. 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` 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`). 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.
@@ -22,6 +22,7 @@ type ComputerLinkRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS & {
type WorkspaceLinkRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & {
workspace_name?: string | null;
image_media_id?: number | null;
};
type CheckRow = BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS;
@@ -61,7 +62,8 @@ export default async function grabHostDirectories({
values: filtered ? [host_directory_id] : [],
}),
BunSQLite.sql<WorkspaceLinkRow>({
sql: `SELECT hdw.*, w.name AS workspace_name FROM host_directory_workspaces hdw
sql: `SELECT hdw.*, w.name AS workspace_name, w.image_media_id AS image_media_id
FROM host_directory_workspaces hdw
LEFT JOIN workspaces w ON w.id = hdw.workspace_id
${filtered ? "WHERE hdw.host_directory_id = ?" : ""}
ORDER BY hdw.id ASC`,
@@ -8,8 +8,9 @@ type Params = {
/**
* Reads every document of a knowledgebase again (after the install's
* embedding model changed, or one failed). Each keeps its old passages
* until its new ones are in. Returns how many were queued.
* embedding model changed). Each keeps its old passages until its new
* ones are in. Documents whose last read failed, and only those, are
* `retryFailedDocuments`. Returns how many were queued.
*/
export default async function reindexKnowledgebase({ knowledgebase_id }: Params) {
const knowledgebase = await grabKnowledgebase({ knowledgebase_id });
@@ -0,0 +1,44 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import enqueueDocumentIngest from "@/src/file-ingest/enqueue-document-ingest";
import grabKnowledgebase from "./grab-knowledgebase";
type Params = {
knowledgebase_id: number | string;
/**
* One document. Left out, every document of the knowledgebase whose
* last read failed.
*/
document_id?: number | string;
};
/**
* Queues the documents whose last read failed, and leaves the ones that
* already succeeded. Clearing `ingest_error` lets `ingest-pending-files`
* pick up one that was never read, if the queue write doesn't land.
* Returns how many were queued.
*/
export default async function retryFailedDocuments({ knowledgebase_id, document_id }: Params) {
const knowledgebase = await grabKnowledgebase({ knowledgebase_id });
const documents = await BunSQLite.sql<{ id: number }>({
sql: `SELECT id FROM knowledgebase_documents
WHERE knowledgebase_id = ? AND ingest_error IS NOT NULL AND (? IS NULL OR id = ?)`,
values: [knowledgebase.id, document_id ?? null, document_id ?? null],
});
const ids = (documents.payload || []).map((document) => document.id).filter(Boolean);
if (!ids.length) return 0;
await BunSQLite.sql({
sql: `UPDATE knowledgebase_documents SET ingest_error = NULL, updated_at = ?
WHERE knowledgebase_id = ? AND id IN (${ids.map(() => "?").join(", ")})`,
values: [Date.now(), knowledgebase.id, ...ids],
});
for (const id of ids) {
await enqueueDocumentIngest({ document_id: id });
}
return ids.length;
}
@@ -39,6 +39,7 @@ describe("describeKnowledgebase", () => {
expect(text).toContain("Handbook");
expect(text).toContain("[bot:7]");
expect(text).toContain("1 not read yet");
expect(text).not.toContain("retry_failed_documents");
expect(text).toContain("re-indexing fixes it");
});
@@ -48,6 +49,12 @@ describe("describeKnowledgebase", () => {
);
});
test("names the retry for ones that failed", () => {
const text = describeKnowledgebase({ knowledgebase: { ...knowledgebase, error_count: 2 } });
expect(text).toContain("2 failed (retry_failed_documents reads those again)");
});
test("lists documents and says one failed", () => {
const text = describeKnowledgebase({
knowledgebase,
@@ -27,7 +27,9 @@ export default function describeKnowledgebase({ knowledgebase, documents }: Para
lines.push(
`Documents: ${knowledgebase.document_count}` +
(knowledgebase.pending_count ? `, ${knowledgebase.pending_count} not read yet` : "") +
(knowledgebase.error_count ? `, ${knowledgebase.error_count} failed` : "") +
(knowledgebase.error_count
? `, ${knowledgebase.error_count} failed (retry_failed_documents reads those again)`
: "") +
(knowledgebase.warning_count ? `, ${knowledgebase.warning_count} with a warning` : "") +
(knowledgebase.stale_count
? `, ${knowledgebase.stale_count} searchable by words only or read by another embedding model (re-indexing fixes it)`
@@ -13,6 +13,7 @@ describe("grabCoordinatorKnowledgebaseTools", () => {
"add_knowledgebase_document",
"delete_knowledgebase_document",
"delete_knowledgebase",
"retry_failed_documents",
"reindex_knowledgebase",
]);
});
@@ -4,6 +4,7 @@ import deleteKnowledgebaseDocumentTool from "./delete-knowledgebase-document-too
import deleteKnowledgebaseTool from "./delete-knowledgebase-tool";
import listKnowledgebasesTool from "./list-knowledgebases-tool";
import reindexKnowledgebaseTool from "./reindex-knowledgebase-tool";
import retryFailedDocumentsTool from "./retry-failed-documents-tool";
import saveKnowledgebaseTool from "./save-knowledgebase-tool";
type Params = {
@@ -23,9 +24,9 @@ type Params = {
};
/**
* The coordinator's knowledgebase tools: list, fill, re-index, delete and
* share out. Every one but the listing is only in an attended run, and each
* checks the super admin itself.
* The coordinator's knowledgebase tools: list, fill, retry the ones that
* failed, re-index, delete and share out. Every one but the listing is only
* in an attended run, and each checks the super admin itself.
*/
export default function grabCoordinatorKnowledgebaseTools({
user_id,
@@ -44,6 +45,7 @@ export default function grabCoordinatorKnowledgebaseTools({
addKnowledgebaseDocumentTool({ user_id, bot_id, workspace_id, computer_id, attended }) as HarnessTool<unknown>,
deleteKnowledgebaseDocumentTool({ user_id, attended }) as HarnessTool<unknown>,
deleteKnowledgebaseTool({ user_id, attended }) as HarnessTool<unknown>,
retryFailedDocumentsTool({ user_id, attended }) as HarnessTool<unknown>,
reindexKnowledgebaseTool({ user_id, attended }) as HarnessTool<unknown>,
];
}
@@ -0,0 +1,59 @@
import { z } from "zod";
import grabKnowledgebase from "@/src/functions/backend/db/knowledgebases/grab-knowledgebase";
import retryFailedDocuments from "@/src/functions/backend/db/knowledgebases/retry-failed-documents";
import logEvent from "@/src/functions/backend/logger";
import type { HarnessTool } from "../../../types";
import assertSuperAdminRun from "../extensions/assert-super-admin-run";
type Params = {
user_id: number | string;
attended: boolean;
};
type Args = {
knowledgebase_id: number;
document_id?: number;
};
/**
* Reads again the documents whose last read failed. The ones that already
* succeeded are left as they are; reading every document again is
* `reindex_knowledgebase`.
*/
export default function retryFailedDocumentsTool({ user_id, attended }: Params): HarnessTool<Args> {
return {
name: "retry_failed_documents",
description: `Read again the documents of a knowledgebase whose last read failed (list_knowledgebases marks them failed). Documents that already succeeded are left as they are. With document_id, only that one, and only when it failed. Reading every document again, including the ones that succeeded, is reindex_knowledgebase.`,
schema: z.object({
knowledgebase_id: z.number().int().positive(),
document_id: z.number().int().positive().optional(),
}),
run: async ({ args }) => {
await assertSuperAdminRun({ user_id });
if (!attended) throw new Error(`Knowledgebases are only changed in a reply or a task the user follows.`);
const knowledgebase = await grabKnowledgebase({ knowledgebase_id: args.knowledgebase_id });
const count = await retryFailedDocuments({
knowledgebase_id: knowledgebase.id,
document_id: args.document_id,
});
await logEvent({
title: "Knowledgebase failed documents retried",
category: "system",
user_id: Number(user_id),
plain_text: `Queued ${count} failed documents of knowledgebase #${knowledgebase.id} (${knowledgebase.name}) to be read again.`,
metadata: { knowledgebase_id: knowledgebase.id, document_id: args.document_id, documents: count },
});
if (!count) {
return args.document_id
? `#${args.document_id} didn't fail, so it wasn't read again.`
: `#${knowledgebase.id} ${knowledgebase.name} has no failed documents.`;
}
return `Queued ${count} failed ${count == 1 ? "document" : "documents"} of #${knowledgebase.id} ${knowledgebase.name} to be read again. The ones that already succeeded were left as they are.`;
},
};
}
+2 -2
View File
@@ -161,9 +161,9 @@ Tell the bot your time zone once ("I'm in Lagos", "I'm on New York time") and it
If it's given and still misses:
- Open the knowledgebase's documents. A document still **being read** isn't searchable yet; one that **couldn't be read** names why (a scan with no text, a file too big). Write the text in instead, or upload a version with text in it.
- Open the knowledgebase's documents. A document still **being read** isn't searchable yet; one that **couldn't be read** names why (a scan with no text, a file too big). Write the text in instead, or upload a version with text in it. The retry icon on that document, or Retry failed in the knowledgebase's menu, reads the failed ones again and leaves the ones that succeeded.
- Bots search by meaning only with an embedding model, picked once for the whole install in **Settings, Models** under Embeddings. Without one they match words, which misses questions worded differently from the document. Picking or changing the model reads every document again on its own; a document shows **needs re-indexing** until it's done.
- If a document still says it needs re-indexing, use the refresh icon on its knowledgebase's row to read them all again.`,
- If a document still says it needs re-indexing, open the knowledgebase's menu and choose Re-index to read them all again.`,
},
{
id: "connect-browser",
@@ -0,0 +1,35 @@
import { useContext } from "react";
import type { LucideIcon } from "lucide-react";
import HeaderMenuItem from "@/src/pages/admin/bots/[bot_id]/(partials)/header-menu-item";
import { SettingsRowMenuClose } from "./settings-row-menu";
type Props = {
icon: LucideIcon;
title: string;
description?: string;
disabled?: boolean;
loading?: boolean;
onClick: () => void;
};
/**
* One action in a settings row's three-dot menu. It closes the menu, then
* runs, so a confirm dialog or a modal is the only thing left open.
*/
export default function SettingsRowMenuItem({ icon, title, description, disabled, loading, onClick }: Props) {
const close = useContext(SettingsRowMenuClose);
return (
<HeaderMenuItem
icon={icon}
title={title}
description={description}
disabled={disabled}
loading={loading}
onClick={() => {
close();
onClick();
}}
/>
);
}
@@ -0,0 +1,22 @@
import type { ReactNode } from "react";
import Paper from "@moduletrace/twui/elements/Paper";
import Stack from "@moduletrace/twui/layout/Stack";
type Props = {
children: ReactNode;
};
/**
* The panel a settings row's three-dot menu opens: the same surface as
* the conversation header's menu.
*/
export default function SettingsRowMenuPanel({ children }: Props) {
return (
<Paper
role="menu"
className="min-w-[220px] p-0! py-1 gap-0! items-stretch rounded-default bg-surface dark:bg-surface border-hairline dark:border-hairline shadow-popover! dark:shadow-popover!"
>
<Stack className="w-full gap-0! items-stretch">{children}</Stack>
</Paper>
);
}
@@ -0,0 +1,54 @@
import { createContext, useState, type ReactNode } from "react";
import Dropdown from "@moduletrace/twui/elements/Dropdown";
import Button from "@moduletrace/twui/layout/Button";
import { EllipsisVertical } from "lucide-react";
/**
* Closes the open menu. An item that then asks to confirm, or opens a
* modal, calls it first so the menu never sits over that.
*/
export const SettingsRowMenuClose = createContext<() => void>(() => {});
type Props = {
/**
* What the button is called, for the tooltip and screen readers.
*/
title: string;
disabled?: boolean;
children: ReactNode;
};
/**
* The three-dot menu on a settings row. One icon stands in for the row's
* actions, which open as a menu. An item closes it through
* `SettingsRowMenuClose` before it confirms or opens a modal.
*/
export default function SettingsRowMenu({ title, disabled, children }: Props) {
const [open, setOpen] = useState(false);
return (
<SettingsRowMenuClose.Provider value={() => setOpen(false)}>
<Dropdown
position="bottom-right"
externalOpen={open}
externalSetOpen={setOpen}
target={
<Button
title={title}
aria-label={title}
aria-haspopup="menu"
type="button"
variant="ghost"
color="text"
disabled={disabled}
className="shrink-0 p-2! text-ink-secondary dark:text-ink-secondary hover:text-ink hover:dark:text-ink hover:bg-sunken hover:dark:bg-sunken rounded-default transition-colors duration-[var(--m-fast)] focus-visible:ring-2 focus-visible:ring-ink"
>
<EllipsisVertical size={16} aria-hidden />
</Button>
}
>
{children}
</Dropdown>
</SettingsRowMenuClose.Provider>
);
}
@@ -24,6 +24,7 @@ function render({
}) {
return renderToString(
<HostDirectoryLinkRow
kind="computer"
name="Main computer"
href="/admin/settings/computers/1"
access={access}
@@ -51,10 +52,32 @@ describe("HostDirectoryLinkRow", () => {
expect(html).toContain("Main computer");
expect(html).toContain("/admin/settings/computers/1");
expect(html).toContain("Computer");
expect(html).toContain("Read and write");
expect(html).toContain("checked");
});
test("a workspace wears its own picture and says it is a workspace", () => {
const html = renderToString(
<HostDirectoryLinkRow
kind="workspace"
name="Moduletrace"
href="/admin/settings/workspaces/4"
image_media_id={12}
access="read-write"
state="unknown"
gate_deletes
onAccess={() => {}}
onDeletes={() => {}}
onRemove={() => {}}
/>,
);
expect(html).toContain("Workspace");
expect(html).toContain("/media/");
expect(html).toContain("12");
});
test("a folder the bots can't write in shows the command to run", () => {
const html = render({
state: "read-only",
@@ -70,7 +93,7 @@ describe("HostDirectoryLinkRow", () => {
expect(html).toContain("Read only");
expect(html).not.toContain("The bots can&#x27;t write there yet");
expect(html).toContain("Read and write");
expect(html).not.toContain("Give access");
});
test("a check that couldn't run says why", () => {
@@ -104,10 +127,11 @@ describe("HostDirectoryLinkRow", () => {
expect(html).not.toContain("setfacl");
});
test("a link whose bots can't write offers to give them access again", () => {
test("a link whose bots can't write keeps its check and its menu", () => {
const html = render({ state: "partial", onGrant: () => {} });
expect(html).toContain("Give access");
expect(html).toContain("Some bots can&#x27;t write");
expect(html).toContain("Main computer menu");
});
test("a read-only link never offers to give access", () => {
@@ -1,23 +1,37 @@
import { CircleAlert } from "lucide-react";
import Link from "@moduletrace/twui/layout/Link";
import Row from "@moduletrace/twui/layout/Row";
import type { ReactNode } from "react";
import { CircleAlert, KeyRound, Lock, RefreshCw, ShieldOff, Unlink } from "lucide-react";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import ComputerIconTile from "@/src/components/general/computer-icon-tile";
import WorkspaceAvatar from "@/src/components/general/workspace-avatar";
import {
HostDirectoryAccesses,
type HostDirectoryAccess,
type HostDirectoryCheckState,
} from "@/src/dict/host-directory-dict";
import SettingsRowAction from "../../(partials)/settings-row-action";
import HostDirectoryCheckTag from "../../(partials)/host-directory-check-tag";
import HostDirectoryCommandNote from "../../(partials)/host-directory-command-note";
import SettingsListRow from "../../(partials)/settings-list-row";
import SettingsRowMenu from "../../(partials)/settings-row-menu";
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
type Props = {
/**
* A computer, or a workspace. The picture is the workspace's own;
* a computer always wears the monitor.
*/
kind: "computer" | "workspace";
/**
* The computer or workspace it is mounted in.
*/
name: string;
href: string;
/**
* The workspace's picture. Left out for a computer, and for a
* workspace that has none.
*/
image_media_id?: number | null;
access: HostDirectoryAccess;
state: HostDirectoryCheckState;
checked_at?: number | null;
@@ -57,11 +71,13 @@ type Props = {
/**
* One place a host directory is mounted: a computer, or a workspace (on
* every computer it is on), what its bots can do there, and what the last
* check found.
* check found. The avatar says which kind it is.
*/
export default function HostDirectoryLinkRow({
kind,
name,
href,
image_media_id,
access,
state,
checked_at,
@@ -81,94 +97,101 @@ export default function HostDirectoryLinkRow({
const access_title =
HostDirectoryAccesses.find((item) => item.value == access)?.title ||
"Read and write";
const place = kind == "workspace" ? "Workspace" : "Computer";
const notes: ReactNode[] = [];
if (error) {
notes.push(
<Span key="error" role="alert" className="flex items-center gap-1.5 text-[12px] leading-4 text-ink">
<CircleAlert size={14} aria-hidden className="shrink-0" />
Couldn't check it: {error}
</Span>,
);
}
if (stale && !error) {
notes.push(
<Span key="stale" role="status" className="flex items-center gap-1.5 text-[12px] leading-4 text-ink-secondary">
<CircleAlert size={14} aria-hidden className="shrink-0" />
A bot was added since the last check, so its account hasn't been tested. Check again.
</Span>,
);
}
if (command) notes.push(<HostDirectoryCommandNote key="command" command={command} />);
return (
<Stack className="w-full gap-1! items-stretch border-t border-solid border-hairline py-1.5 first:border-t-0">
<Row className="w-full gap-x-2 gap-y-1! flex-wrap items-center">
<Link
href={href}
title={name}
className="min-w-0 truncate text-[13px] leading-[18px] text-ink hover:underline"
>
{name}
</Link>
<Span className="shrink-0 text-[12px] leading-4 text-ink-secondary">
{access_title}
</Span>
<Stack className="w-full gap-1! items-stretch border-t border-solid border-hairline py-1 first:border-t-0">
<SettingsListRow
avatar={
kind == "workspace" ? (
<WorkspaceAvatar image_media_id={image_media_id} />
) : (
<ComputerIconTile />
)
}
title={name}
href={href}
badge={place}
subtitle={access_title}
>
<HostDirectoryCheckTag state={state} checked_at={checked_at} />
<Row className="ml-auto shrink-0 gap-1! flex-nowrap">
{onGrant && access == "read-write" && (stale || state == "partial" || state == "read-only") ? (
<SettingsRowAction
title="Give every bot that sees this folder access to it"
label={granting ? "Giving access" : "Give access"}
disabled={busy || checking || granting}
onClick={onGrant}
/>
) : null}
{onCheck ? (
<SettingsRowAction
title="Check that the bots can read and write it now"
label={checking ? "Checking" : "Check"}
<SettingsRowMenu title={`${name} menu`} disabled={busy || checking}>
<SettingsRowMenuPanel>
{onGrant && access == "read-write" && (stale || state == "partial" || state == "read-only") ? (
<SettingsRowMenuItem
icon={KeyRound}
title={granting ? "Giving access" : "Give access"}
description="Give every bot that sees this folder access to it"
loading={granting}
disabled={busy || checking || granting}
onClick={onGrant}
/>
) : null}
{onCheck ? (
<SettingsRowMenuItem
icon={RefreshCw}
title={checking ? "Checking" : "Check"}
description="Check that the bots can read and write it now"
loading={checking}
disabled={busy || checking}
onClick={onCheck}
/>
) : null}
<SettingsRowMenuItem
icon={access == "read-write" ? Lock : KeyRound}
title={access == "read-write" ? "Read only" : "Read and write"}
description={
access == "read-write"
? "Mount it read only, so the bots can't change it"
: "Let the bots write there"
}
disabled={busy || checking}
onClick={onCheck}
onClick={onAccess}
/>
) : null}
<SettingsRowAction
title={
access == "read-write"
? "Mount it read only, so the bots can't change it"
: "Let the bots write there"
}
label={
access == "read-write"
? "Read only"
: "Read and write"
}
disabled={busy || checking}
onClick={onAccess}
/>
<SettingsRowAction
title={
gate_deletes
? "Stop asking: the bots can delete in it without your approval"
: "Ask you before a bot deletes anything in it"
}
label={
gate_deletes ? "Ask before deletes" : "Delete freely"
}
disabled={busy || checking}
onClick={onDeletes}
/>
<SettingsRowAction
title={`Unmount it from ${name}`}
label="Remove"
disabled={busy || checking}
onClick={onRemove}
/>
</Row>
</Row>
{error ? (
<Span
role="alert"
className="flex items-center gap-1.5 text-[12px] leading-4 text-ink"
>
<CircleAlert size={14} aria-hidden className="shrink-0" />
Couldn't check it: {error}
</Span>
) : null}
{stale && !error ? (
<Span
role="status"
className="flex items-center gap-1.5 text-[12px] leading-4 text-ink-secondary"
>
<CircleAlert size={14} aria-hidden className="shrink-0" />
A bot was added since the last check, so its account
hasn't been tested. Check again.
</Span>
) : null}
{command ? (
<HostDirectoryCommandNote command={command} />
) : null}
<SettingsRowMenuItem
icon={gate_deletes ? ShieldOff : Lock}
title={gate_deletes ? "Ask before deletes" : "Delete freely"}
description={
gate_deletes
? "Stop asking: the bots can delete in it without your approval"
: "Ask you before a bot deletes anything in it"
}
disabled={busy || checking}
onClick={onDeletes}
/>
<SettingsRowMenuItem
icon={Unlink}
title="Remove"
description={`Unmount it from ${name}`}
disabled={busy || checking}
onClick={onRemove}
/>
</SettingsRowMenuPanel>
</SettingsRowMenu>
</SettingsListRow>
{notes.length ? <Stack className="w-full gap-1! items-stretch px-3 pb-2">{notes}</Stack> : null}
</Stack>
);
}
}
@@ -1,5 +1,5 @@
import { useState } from "react";
import { FolderTree } from "lucide-react";
import { FolderTree, Pencil, Trash2 } from "lucide-react";
import Span from "@moduletrace/twui/layout/Span";
import Stack from "@moduletrace/twui/layout/Stack";
import IconTile from "@/src/components/general/icon-tile";
@@ -18,7 +18,9 @@ import hostDirectoryCheckStale from "@/src/utils/host-directory-check-stale";
import hostDirectoryPermissionCommand from "@/src/utils/host-directory-permission-command";
import InlineAddSelect from "@/src/components/general/inline-add-select";
import SettingsListRow from "../../(partials)/settings-list-row";
import SettingsRowAction from "../../(partials)/settings-row-action";
import SettingsRowMenu from "../../(partials)/settings-row-menu";
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
import HostDirectoryLinkRow from "./host-directory-link-row";
type Props = {
@@ -41,8 +43,10 @@ type Props = {
type LinkView = {
key: string;
kind: "computer" | "workspace";
name: string;
href: string;
image_media_id?: number | null;
access: HostDirectoryAccess;
state: HostDirectoryCheckState;
checked_at?: number | null;
@@ -177,6 +181,7 @@ export default function HostDirectoryRow({
return {
key: `computer-${link.id}`,
kind: "computer",
name: link.computer_name || `Computer ${link.computer_id}`,
href: `/admin/settings/computers/${link.computer_id}`,
access,
@@ -228,7 +233,9 @@ export default function HostDirectoryRow({
return {
key: `workspace-${link.id}`,
kind: "workspace",
name: link.workspace_name || `Workspace ${link.workspace_id}`,
image_media_id: link.image_media_id,
href: `/admin/settings/workspaces/${link.workspace_id}`,
access,
state,
@@ -314,26 +321,27 @@ export default function HostDirectoryRow({
title={name}
subtitle={source}
>
<SettingsRowAction
title={`Edit ${name}`}
label="Edit"
disabled={Boolean(busy)}
onClick={onEdit}
/>
<SettingsRowAction
title={`Remove ${name}`}
label="Remove"
disabled={Boolean(busy)}
onClick={remove}
/>
<SettingsRowMenu title={`${name} menu`} disabled={Boolean(busy)}>
<SettingsRowMenuPanel>
<SettingsRowMenuItem icon={Pencil} title="Edit" onClick={onEdit} />
<SettingsRowMenuItem
icon={Trash2}
title="Remove"
description="Its computers and workspaces stop seeing the folder. Nothing in the folder itself is deleted."
onClick={remove}
/>
</SettingsRowMenuPanel>
</SettingsRowMenu>
</SettingsListRow>
<Stack className="w-full gap-2! items-stretch px-3 pt-1 pb-3">
{links.length ? (
links.map((link) => (
<HostDirectoryLinkRow
key={link.key}
kind={link.kind}
name={link.name}
href={link.href}
image_media_id={link.image_media_id}
access={link.access}
state={link.state}
checked_at={link.checked_at}
@@ -107,5 +107,14 @@ export default function useKnowledgebaseDocuments({ knowledgebase_id }: Params)
await post({ path: "knowledgebases/delete-document", body: { document_id: document.id } });
};
return { documents, busy, status, upload, saveText, remove };
const retry = async ({ document }: { document: KnowledgebaseDocument }) => {
if (busy || !window.confirm(`Read ${document.name} again? Documents that already succeeded stay as they are.`)) return;
await post({
path: "knowledgebases/retry-failed-documents",
body: { knowledgebase_id, document_id: document.id },
});
};
return { documents, busy, status, upload, saveText, remove, retry };
}
@@ -1,4 +1,4 @@
import { FileText, NotebookPen, Pencil, Trash2 } from "lucide-react";
import { FileText, NotebookPen, Pencil, RotateCcw, Trash2 } from "lucide-react";
import Row from "@moduletrace/twui/layout/Row";
import IconTile from "@/src/components/general/icon-tile";
import RowIconButton from "@/src/components/general/row-icon-button";
@@ -17,6 +17,10 @@ type Props = {
* can't edit.
*/
onEdit?: () => void;
/**
* Reads this document again. Given only when its last read failed.
*/
onRetry?: () => void;
onDelete?: () => void;
};
@@ -24,7 +28,7 @@ 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, onDelete }: Props) {
export default function KnowledgebaseDocumentRow({ document, embedding_model, busy, onEdit, onRetry, onDelete }: Props) {
return (
<SettingsListRow
avatar={<IconTile Icon={document.source == "text" ? NotebookPen : FileText} />}
@@ -44,6 +48,9 @@ export default function KnowledgebaseDocumentRow({ document, embedding_model, bu
subtitle={knowledgebaseDocumentSummary({ document, embedding_model })}
>
<Row className="gap-0! flex-nowrap">
{onRetry ? (
<RowIconButton icon={RotateCcw} title={`Retry ${document.name}`} disabled={busy} onClick={onRetry} />
) : null}
{onEdit ? <RowIconButton icon={Pencil} title={`Edit ${document.name}`} disabled={busy} onClick={onEdit} /> : null}
{onDelete ? (
<RowIconButton icon={Trash2} title={`Delete ${document.name}`} disabled={busy} onClick={onDelete} />
@@ -34,7 +34,7 @@ type Props = {
* done.
*/
export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, embedding_model, onClose }: Props) {
const { documents, busy, status, upload, saveText, remove } = useKnowledgebaseDocuments({
const { documents, busy, status, upload, saveText, remove, retry } = useKnowledgebaseDocuments({
knowledgebase_id: knowledgebase.id,
});
/**
@@ -78,6 +78,11 @@ export default function KnowledgebaseDocumentsModal({ knowledgebase, can_edit, e
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}
/>
))}
@@ -1,13 +1,14 @@
import { useState } from "react";
import Row from "@moduletrace/twui/layout/Row";
import Stack from "@moduletrace/twui/layout/Stack";
import { FileText, Library, Pencil, RefreshCw, Trash2, Users } from "lucide-react";
import { FileText, Library, Pencil, RefreshCw, RotateCcw, Trash2, Users } from "lucide-react";
import IconTile from "@/src/components/general/icon-tile";
import RowIconButton from "@/src/components/general/row-icon-button";
import postAdminApi from "@/src/layouts/bots/(functions)/post-admin-api";
import type { ExtensionTargets, KnowledgebasesOverviewPayload, PublicKnowledgebase } from "@/src/types";
import ExtensionAccessModal from "../../(partials)/extension-access-modal";
import SettingsListRow from "../../(partials)/settings-list-row";
import SettingsRowMenu from "../../(partials)/settings-row-menu";
import SettingsRowMenuItem from "../../(partials)/settings-row-menu-item";
import SettingsRowMenuPanel from "../../(partials)/settings-row-menu-panel";
import extensionAccessLabel from "../../(utils)/extension-access-label";
import updatedAgo from "../../(utils)/updated-ago";
import knowledgebaseIndexState from "@/src/utils/knowledgebase-index-state";
@@ -29,8 +30,9 @@ type Props = {
/**
* One knowledgebase: how many documents it holds and how much of them is
* searchable, and who gets it. Documents, Edit and Access open in a modal;
* Re-index reads every document again with the install's embedding model.
* searchable, and who gets it. Its actions live in the three-dot menu:
* documents, who gets it, and for a super admin editing, retrying the
* ones that failed, reading every document again, and deleting it.
*/
export default function KnowledgebaseRow({ knowledgebase, targets, embedding_model, onChanged, onError }: Props) {
const [open, setOpen] = useState<"documents" | "edit" | "access">();
@@ -93,54 +95,54 @@ export default function KnowledgebaseRow({ knowledgebase, targets, embedding_mod
.filter(Boolean)
.join(" · ")}
>
<Row className="gap-0! flex-nowrap">
<RowIconButton
icon={FileText}
title={`Open the documents in ${knowledgebase.name}`}
disabled={busy}
onClick={() => setOpen("documents")}
/>
{targets.can_edit ? (
<RowIconButton
icon={Pencil}
title={`Edit ${knowledgebase.name}`}
disabled={busy}
onClick={() => setOpen("edit")}
/>
) : null}
<RowIconButton
icon={Users}
title={`Choose who gets ${knowledgebase.name}`}
disabled={busy}
onClick={() => setOpen("access")}
/>
{targets.can_edit && knowledgebase.document_count ? (
<RowIconButton
icon={RefreshCw}
title={`Re-index ${knowledgebase.name}: read every document again`}
disabled={busy}
onClick={() =>
post({
path: "knowledgebases/reindex-knowledgebase",
confirm: `Read every document in ${knowledgebase.name} again? Bots keep finding the old passages until the new ones are in.`,
})
}
/>
) : null}
{targets.can_edit ? (
<RowIconButton
icon={Trash2}
title={`Delete ${knowledgebase.name}`}
disabled={busy}
onClick={() =>
post({
path: "knowledgebases/delete-knowledgebase",
confirm: `Delete ${knowledgebase.name} and every document in it? Bots lose it at once.`,
})
}
/>
) : null}
</Row>
<SettingsRowMenu title={`${knowledgebase.name} menu`} disabled={busy}>
<SettingsRowMenuPanel>
<SettingsRowMenuItem icon={FileText} title="Documents" onClick={() => setOpen("documents")} />
{targets.can_edit ? (
<SettingsRowMenuItem icon={Pencil} title="Edit" onClick={() => setOpen("edit")} />
) : null}
<SettingsRowMenuItem icon={Users} title="Who gets it" onClick={() => setOpen("access")} />
{targets.can_edit && knowledgebase.warning_count ? (
<SettingsRowMenuItem
icon={RotateCcw}
title="Retry failed"
description={`Read again the ${knowledgebase.warning_count} ${knowledgebase.warning_count == 1 ? "document" : "documents"} that failed. The ones that already succeeded stay as they are.`}
onClick={() =>
post({
path: "knowledgebases/retry-failed-documents",
confirm: `Read again the ${knowledgebase.warning_count} ${knowledgebase.warning_count == 1 ? "document" : "documents"} in ${knowledgebase.name} that failed? The ones that already succeeded stay as they are.`,
})
}
/>
) : null}
{targets.can_edit && knowledgebase.document_count ? (
<SettingsRowMenuItem
icon={RefreshCw}
title="Re-index"
description="Read every document again. Bots keep finding the old passages until the new ones are in."
onClick={() =>
post({
path: "knowledgebases/reindex-knowledgebase",
confirm: `Read every document in ${knowledgebase.name} again? Bots keep finding the old passages until the new ones are in.`,
})
}
/>
) : null}
{targets.can_edit ? (
<SettingsRowMenuItem
icon={Trash2}
title="Delete"
description="Delete it and every document in it. Bots lose it at once."
onClick={() =>
post({
path: "knowledgebases/delete-knowledgebase",
confirm: `Delete ${knowledgebase.name} and every document in it? Bots lose it at once.`,
})
}
/>
) : null}
</SettingsRowMenuPanel>
</SettingsRowMenu>
</SettingsListRow>
{open == "documents" ? (
<KnowledgebaseDocumentsModal
@@ -0,0 +1,67 @@
import grabSuperAdminUser from "@/src/functions/backend/backups/grab-super-admin-user";
import grabKnowledgebasesOverview from "@/src/functions/backend/db/knowledgebases/grab-knowledgebases-overview";
import listKnowledgebaseDocuments from "@/src/functions/backend/db/knowledgebases/list-knowledgebase-documents";
import retryFailedDocuments from "@/src/functions/backend/db/knowledgebases/retry-failed-documents";
import logEvent, { grabRequestIP } from "@/src/functions/backend/logger";
import { KnowledgebaseIdRequestSchema } from "@/src/schemas/knowledgebase-schema";
import type { KnowledgebaseDocumentsPayload, KnowledgebasesOverviewPayload } from "@/src/types";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
import { z } from "zod";
const RequestSchema = KnowledgebaseIdRequestSchema.extend({
/**
* Set when the documents list retries one document; the answer is then
* that list. Left out, the knowledgebase's row retries every failed
* document and the answer is the overview.
*/
document_id: z.coerce.number().int().positive().optional(),
});
/**
* Super admin only: reads again the documents whose last read failed.
* Ones that already succeeded stay as they are.
*/
export const handler: BunextAPIRouteHandler<
APIResponseObject<KnowledgebasesOverviewPayload | KnowledgebaseDocumentsPayload>
> = async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const user = await grabSuperAdminUser({ req });
if (!user?.id) {
throw new AppError(`Only a super admin can do that.`);
}
const { knowledgebase_id, document_id } = parseWithSchema({ schema: RequestSchema, data: body });
const queued = await retryFailedDocuments({ knowledgebase_id, document_id });
await logEvent({
title: "Knowledgebase failed documents retried",
category: "system",
user_id: user.id,
plain_text: `User #${user.id} retried ${queued} failed ${queued == 1 ? "document" : "documents"} of the knowledgebase #${knowledgebase_id}.`,
metadata: { knowledgebase_id, document_id, queued },
ip_address: grabRequestIP(req),
});
const msg = queued
? `Reading ${queued} failed ${queued == 1 ? "document" : "documents"} again.`
: "Nothing failed to read.";
return {
success: true,
msg,
singleRes: document_id
? await listKnowledgebaseDocuments({ knowledgebase_id })
: await grabKnowledgebasesOverview({ user_id: user.id }),
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+4
View File
@@ -436,6 +436,10 @@ export type HostDirectoryComputerLink = BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTE
*/
export type HostDirectoryWorkspaceLink = BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES & {
workspace_name?: string | null;
/**
* The workspace's picture, for its row. Null means the workspace icon.
*/
image_media_id?: number | null;
/**
* The computers the workspace is on, where this folder is mounted.
*/