Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01d6cffa8d | ||
|
|
8897f0b23f | ||
|
|
2dc6972de4 | ||
|
|
82fa223691 |
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.28.10",
|
||||
"version": "0.28.12",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -6,7 +6,7 @@ import wakeBotsQueue from "@/src/bots-queue/wake-bots-queue";
|
||||
import type { BotQuestionView } from "@/src/types";
|
||||
import botQuestionAnswersText from "@/src/utils/bot-question-answers-text";
|
||||
import planContinueAnswer from "@/src/utils/plan-continue-answer";
|
||||
import conversationLock from "../bot-sessions/conversation-lock";
|
||||
import conversationLock, { conversationLockKey } from "../bot-sessions/conversation-lock";
|
||||
import ensureBotSession from "../bot-sessions/ensure-bot-session";
|
||||
import grabUserBotSession from "../bot-sessions/grab-user-bot-session";
|
||||
import insertUserMessage from "../bots/insert-user-message";
|
||||
@@ -43,7 +43,7 @@ export default async function postBotQuestionAnswers({ view, user_id }: Params)
|
||||
const bot_id = Number(row.bot_id);
|
||||
|
||||
await conversationLock.run({
|
||||
key: `${user_id}:${bot_id}:${workspace_id || 0}`,
|
||||
key: conversationLockKey({ user_id, bot_id, workspace_id }),
|
||||
task: async () => {
|
||||
const session = await pickSession({ row, user_id });
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@ import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import AppError from "@/src/utils/app-error";
|
||||
import insertBotMessage from "../bots/insert-bot-message";
|
||||
import conversationLock, { conversationLockKey } from "./conversation-lock";
|
||||
import createBotSession from "./create-bot-session";
|
||||
import grabActiveBotSession from "./grab-active-bot-session";
|
||||
import grabUserBotSession from "./grab-user-bot-session";
|
||||
import unansweredMessageSql from "./unanswered-message-sql";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -57,8 +59,27 @@ type Params = {
|
||||
* session (`allow_inactive`, `next_status` closed), keeping the link to
|
||||
* the routine or hook and the conversation's active session untouched.
|
||||
* Returns that first message, for the caller to push.
|
||||
*
|
||||
* A reply's carry is refused while the user has written something that
|
||||
* reply hasn't answered: closing the session now leaves their message
|
||||
* behind in it while the answer goes to the new one.
|
||||
*/
|
||||
export default async function carryOverBotSession({
|
||||
export default async function carryOverBotSession(params: Params): Promise<BUN_SQLITE_COBBLE_BOT_MESSAGES> {
|
||||
/**
|
||||
* The reply writes to the conversation like a send does, so it waits
|
||||
* its turn: a message the user writes while it works lands in one
|
||||
* session or the other, never in one closed under it. A routine's or a
|
||||
* silent hook's own thread (`allow_inactive`, no job) moves on its own.
|
||||
*/
|
||||
if (!params.job_id) return await carryOverSession(params);
|
||||
|
||||
return await conversationLock.run({
|
||||
key: conversationLockKey(params),
|
||||
task: () => carryOverSession(params),
|
||||
});
|
||||
}
|
||||
|
||||
async function carryOverSession({
|
||||
session_id,
|
||||
user_id,
|
||||
bot_id,
|
||||
@@ -104,6 +125,23 @@ export default async function carryOverBotSession({
|
||||
throw new AppError(`This session has no messages yet: it's already fresh.`);
|
||||
}
|
||||
|
||||
if (job_id) {
|
||||
const unanswered = unansweredMessageSql({ session_id: active.id, job_id });
|
||||
|
||||
const waiting = (
|
||||
await BunSQLite.sql<{ unanswered: number }>({
|
||||
sql: `SELECT ${unanswered.sql} AS unanswered`,
|
||||
values: unanswered.values,
|
||||
})
|
||||
).payload?.[0]?.unanswered;
|
||||
|
||||
if (waiting) {
|
||||
throw new AppError(
|
||||
`The user wrote something this reply hasn't answered yet. Answer it in this session first, and carry the conversation over in a later reply.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
await BunSQLite.sql({
|
||||
|
||||
@@ -6,8 +6,18 @@ import createKeyLock from "@/src/utils/create-key-lock";
|
||||
* flight together (a double submit, a retry firing beside the first) both
|
||||
* read the same full session, one rolls the conversation over, and the
|
||||
* other writes into the session that was just closed, where the user never
|
||||
* sees it.
|
||||
* sees it. A reply carrying the conversation on is one of those writes.
|
||||
*/
|
||||
const conversationLock = createKeyLock();
|
||||
|
||||
type KeyParams = {
|
||||
user_id: number | string;
|
||||
bot_id: number;
|
||||
workspace_id?: number | null;
|
||||
};
|
||||
|
||||
export function conversationLockKey({ user_id, bot_id, workspace_id }: KeyParams) {
|
||||
return `${user_id}:${bot_id}:${workspace_id || 0}`;
|
||||
}
|
||||
|
||||
export default conversationLock;
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import unansweredMessageSql from "./unanswered-message-sql";
|
||||
|
||||
/**
|
||||
* A carry must notice the user's words it would leave behind: a message
|
||||
* written after the one the reply answers (or after a plan's step was
|
||||
* queued) is unanswered, and the session it is in is not safe to close.
|
||||
* Crew messages and the message the job answers are not the user's new
|
||||
* words.
|
||||
*/
|
||||
const db = new Database(":memory:");
|
||||
|
||||
db.run(
|
||||
`CREATE TABLE bot_messages (id INTEGER PRIMARY KEY, session_id INTEGER, author TEXT,
|
||||
from_ask_id INTEGER, from_install_request_id INTEGER, created_at INTEGER)`,
|
||||
);
|
||||
db.run(`CREATE TABLE bots_queue (id INTEGER PRIMARY KEY, message_id INTEGER, created_at INTEGER)`);
|
||||
|
||||
db.run(`INSERT INTO bots_queue VALUES (10, 100, 1000), (11, NULL, 2000)`);
|
||||
|
||||
db.run(`INSERT INTO bot_messages VALUES
|
||||
(100, 5, 'user', NULL, NULL, 900),
|
||||
(101, 5, 'user', NULL, NULL, 1100),
|
||||
(102, 5, 'user', 3, NULL, 1200),
|
||||
(103, 5, 'user', NULL, 4, 1300),
|
||||
(104, 5, 'bot', NULL, NULL, 1400),
|
||||
(200, 6, 'user', NULL, NULL, 2100),
|
||||
(201, 6, 'bot', NULL, NULL, 2200)`);
|
||||
|
||||
function unanswered({ session_id, job_id }: { session_id: number; job_id: number }) {
|
||||
const condition = unansweredMessageSql({ session_id, job_id });
|
||||
|
||||
return Boolean(
|
||||
(
|
||||
db.query(`SELECT ${condition.sql} AS unanswered`).get(...condition.values) as
|
||||
| { unanswered: number }
|
||||
| null
|
||||
)?.unanswered,
|
||||
);
|
||||
}
|
||||
|
||||
describe("unansweredMessageSql", () => {
|
||||
test("a message written after the one the job answers is unanswered", () => {
|
||||
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(true);
|
||||
});
|
||||
|
||||
test("the message the job answers is not", () => {
|
||||
db.run(`DELETE FROM bot_messages WHERE id IN (101, 102, 103)`);
|
||||
|
||||
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(false);
|
||||
|
||||
db.run(`INSERT INTO bot_messages VALUES
|
||||
(101, 5, 'user', NULL, NULL, 1100),
|
||||
(102, 5, 'user', 3, NULL, 1200),
|
||||
(103, 5, 'user', NULL, 4, 1300)`);
|
||||
});
|
||||
|
||||
test("a crew message is never the user's words", () => {
|
||||
db.run(`DELETE FROM bot_messages WHERE id = 101`);
|
||||
|
||||
expect(unanswered({ session_id: 5, job_id: 10 })).toBe(false);
|
||||
|
||||
db.run(`INSERT INTO bot_messages VALUES (101, 5, 'user', NULL, NULL, 1100)`);
|
||||
});
|
||||
|
||||
test("a step queued with no message counts what the user wrote after it", () => {
|
||||
expect(unanswered({ session_id: 6, job_id: 11 })).toBe(true);
|
||||
|
||||
db.run(`DELETE FROM bot_messages WHERE id = 200`);
|
||||
|
||||
expect(unanswered({ session_id: 6, job_id: 11 })).toBe(false);
|
||||
|
||||
db.run(`INSERT INTO bot_messages VALUES (200, 6, 'user', NULL, NULL, 2100)`);
|
||||
});
|
||||
|
||||
test("a job queued after the session's messages counts none of them", () => {
|
||||
expect(unanswered({ session_id: 5, job_id: 11 })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { SqlCondition } from "@/src/utils/crew-access/types";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
* The session the reply is answering in.
|
||||
*/
|
||||
session_id: number | string;
|
||||
/**
|
||||
* The reply's own job: the message it answers is `bots_queue.message_id`.
|
||||
*/
|
||||
job_id: number | string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The SQL for a user message the reply's job hasn't answered: one written
|
||||
* after the message the job answers, or, for a job queued with no message
|
||||
* (a plan's step), after the job was queued. Crew messages are left out:
|
||||
* they wake a bot, they aren't the user's own words. A run carrying the
|
||||
* conversation on while its answer is one of these leaves it behind in the
|
||||
* session it closes, unanswered.
|
||||
*/
|
||||
export default function unansweredMessageSql({ session_id, job_id }: Params): SqlCondition {
|
||||
return {
|
||||
sql: `EXISTS (SELECT 1 FROM bot_messages m JOIN bots_queue q ON q.id = ?
|
||||
WHERE m.session_id = ? AND m.author = 'user'
|
||||
AND m.from_ask_id IS NULL AND m.from_install_request_id IS NULL
|
||||
AND (m.id > q.message_id OR (q.message_id IS NULL AND m.created_at > q.created_at)))`,
|
||||
values: [Number(job_id), Number(session_id)],
|
||||
};
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ export default function continueInNewSessionTool({
|
||||
|
||||
return {
|
||||
name: "continue_in_new_session",
|
||||
description: `Move this conversation into a fresh session, carrying over a summary you write. Every reply re-reads the session's recent messages, so a long one costs more each time. Always use it when the user asks to carry on in a new, fresh or different session ("let's continue this in another session", "start a new chat for this"): don't just agree, move. Also use it when the session has grown long and the current topic is at a natural break (say so in your answer). The summary opens the new session, shown to the user and given to you from then on in place of these messages, so put in everything needed to carry on: what the user wants, decisions made, what's done, what's in progress or open, and every name, number, path, link and ref ([bot:ID], [file:ID], ...) exactly. Call it last: your answer then goes in the new session under the summary, so keep it to a line.`,
|
||||
description: `Move this conversation into a fresh session, carrying over a summary you write. Every reply re-reads the session's recent messages, so a long one costs more each time. Always use it when the user asks to carry on in a new, fresh or different session ("let's continue this in another session", "start a new chat for this"): don't just agree, move. Also use it when the session has grown long and the current topic is at a natural break (say so in your answer). The summary opens the new session, shown to the user and given to you from then on in place of these messages, so put in everything needed to carry on: what the user wants, decisions made, what's done, what's in progress or open, and every name, number, path, link and ref ([bot:ID], [file:ID], ...) exactly. Call it last: your answer then goes in the new session under the summary, so keep it to a line. If the user wrote something while you worked, answer that here first: the conversation only moves once everything they said is answered.`,
|
||||
schema: z.object({
|
||||
summary: z
|
||||
.string()
|
||||
|
||||
@@ -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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+91
-80
@@ -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}
|
||||
|
||||
@@ -3,7 +3,7 @@ import grabUserConversation from "@/src/functions/backend/db/bot-sessions/grab-u
|
||||
import grabUserBotSession from "@/src/functions/backend/db/bot-sessions/grab-user-bot-session";
|
||||
import reopenBotSession from "@/src/functions/backend/db/bot-sessions/reopen-bot-session";
|
||||
import ensureBotSession from "@/src/functions/backend/db/bot-sessions/ensure-bot-session";
|
||||
import conversationLock from "@/src/functions/backend/db/bot-sessions/conversation-lock";
|
||||
import conversationLock, { conversationLockKey } from "@/src/functions/backend/db/bot-sessions/conversation-lock";
|
||||
import insertUserMessage from "@/src/functions/backend/db/bots/insert-user-message";
|
||||
import grabUserBotMessage from "@/src/functions/backend/db/bots/grab-user-bot-message";
|
||||
import grabMessageIdByClientId from "@/src/functions/backend/db/bots/grab-message-id-by-client-id";
|
||||
@@ -151,7 +151,7 @@ export const handler: BunextAPIRouteHandler<APIResponseObject> = async ({
|
||||
* or its reply.
|
||||
*/
|
||||
const message = await conversationLock.run({
|
||||
key: `${user.id}:${bot.id}:${conversation.workspace_id || 0}`,
|
||||
key: conversationLockKey({ user_id: user.id, bot_id: bot.id, workspace_id: conversation.workspace_id }),
|
||||
task: async () => {
|
||||
/**
|
||||
* The thread on screen is where the message goes: a routine's
|
||||
|
||||
@@ -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 }) };
|
||||
|
||||
@@ -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 & {
|
||||
|
||||
Reference in New Issue
Block a user