fix: harden assistant integration

This commit is contained in:
ajnart committed 2026-07-28 22:56:28 +02:00
1 parent 00e8790ec2
commit 36ae9f93ee
17 files changed
+321 -160

No files matched your search

+16 -9
View File
@@ -195,15 +195,22 @@ const ownedThreadAsync = async (db: Database, threadId: string, userId: string)
};
export const assistantRouter = createTRPCRouter({
getAvailability: protectedProcedure.query(async ({ ctx }) => {
const configuration = await getConfigurationAsync(ctx.db);
const requiresApiKey = configuration?.provider === "openrouter" || configuration?.provider === "openai";
return {
enabled: Boolean(
configuration?.enabled && configuration.modelId && (!requiresApiKey || configuration.encryptedApiKey),
),
};
}),
getAvailability: protectedProcedure
.meta({
mcp: {
enabled: true,
description: "Check whether Homarr Assistant is enabled and configured for the current user",
},
})
.query(async ({ ctx }) => {
const configuration = await getConfigurationAsync(ctx.db);
const requiresApiKey = configuration?.provider === "openrouter" || configuration?.provider === "openai";
return {
enabled: Boolean(
configuration?.enabled && configuration.modelId && (!requiresApiKey || configuration.encryptedApiKey),
),
};
}),
getAdminConfiguration: adminProcedure.query(async ({ ctx }) => {
const configuration = await getConfigurationAsync(ctx.db);
+17
View File
@@ -1,6 +1,9 @@
// @vitest-environment node
import { expect, test, vi } from "vitest";
import { extractToolsFromProcedures } from "trpc-to-mcp";
import { assistantRouter } from "../router/assistant";
import { appRouter } from "../router/app";
import { boardRouter } from "../router/board";
import { infoRouter } from "../router/info";
@@ -9,8 +12,21 @@ import { serverSettingsRouter } from "../router/serverSettings";
import { createTRPCRouter } from "../trpc";
vi.mock("@homarr/auth", () => ({}));
vi.mock("@homarr/common/server", () => ({
decryptSecret: vi.fn(),
encryptSecret: vi.fn(),
}));
vi.mock("@homarr/core/infrastructure/logs", () => ({
createLogger: () => ({
error: vi.fn(),
}),
}));
vi.mock("@homarr/core/infrastructure/db/env", () => ({
dbEnv: { DRIVER: "better-sqlite3" },
}));
const mcpTestRouter = createTRPCRouter({
assistant: assistantRouter,
app: appRouter,
board: boardRouter,
info: infoRouter,
@@ -29,6 +45,7 @@ test("MCP tools should contain expected procedures", () => {
const toolNames = tools.map((tool) => tool.name);
expect(tools.length).toBeGreaterThan(0);
expect(toolNames).toContain("assistant_getAvailability");
expect(toolNames).toContain("app_all");
expect(toolNames).toContain("app_byId");
expect(toolNames).toContain("app_create");
+4 -2
View File
@@ -6,6 +6,8 @@ import { dbEnv } from "@homarr/core/infrastructure/db/env";
import type { HomarrDatabase, HomarrDatabaseMysql, HomarrDatabasePostgresql } from "./driver";
import * as schema from "./schema";
const schemaTables = { ...schema };
type TableKey = {
[K in keyof typeof schema]: (typeof schema)[K] extends { _: { brand: "Table" } } ? K : never;
}[keyof typeof schema];
@@ -36,7 +38,7 @@ export const createDbInsertCollectionForTransaction = <TTableKey extends TableKe
for (const [key, values] of objectEntries(context)) {
if (values.length >= 1) {
transaction
.insert(schema[key])
.insert(schemaTables[key])
.values(values as never)
.run();
}
@@ -50,7 +52,7 @@ export const createDbInsertCollectionForTransaction = <TTableKey extends TableKe
for (const [key, values] of objectEntries(context)) {
if (values.length >= 1) {
// Below is actually the mysqlSchema when the driver is mysql
await transaction.insert(schema[key] as never).values(values as never);
await transaction.insert(schemaTables[key] as never).values(values as never);
}
}
});
@@ -23,9 +23,9 @@ CREATE TABLE `assistant_thread` (
);
--> statement-breakpoint
CREATE TABLE `assistant_message` (
`id` varchar(64) NOT NULL,
`id` varchar(128) NOT NULL,
`thread_id` varchar(64) NOT NULL,
`parent_id` varchar(64),
`parent_id` varchar(128),
`format` varchar(64) DEFAULT 'ai-sdk/v6' NOT NULL,
`content` text DEFAULT ('{"json": {}}') NOT NULL,
`created_at` timestamp DEFAULT (now()) NOT NULL,
@@ -35,3 +35,7 @@ CREATE TABLE `assistant_message` (
ALTER TABLE `assistant_thread` ADD CONSTRAINT `assistant_thread_user_id_user_id_fk` FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON DELETE cascade ON UPDATE no action;
--> statement-breakpoint
ALTER TABLE `assistant_message` ADD CONSTRAINT `assistant_message_thread_id_assistant_thread_id_fk` FOREIGN KEY (`thread_id`) REFERENCES `assistant_thread`(`id`) ON DELETE cascade ON UPDATE no action;
--> statement-breakpoint
CREATE INDEX `assistant_message__thread_id_created_at_idx` ON `assistant_message` (`thread_id`,`created_at`);
--> statement-breakpoint
CREATE INDEX `assistant_thread__user_id_updated_at_idx` ON `assistant_thread` (`user_id`,`updated_at`);
@@ -11,9 +11,9 @@ CREATE TABLE "assistant_configuration" (
);
--> statement-breakpoint
CREATE TABLE "assistant_message" (
"id" varchar(64) PRIMARY KEY NOT NULL,
"id" varchar(128) PRIMARY KEY NOT NULL,
"thread_id" varchar(64) NOT NULL,
"parent_id" varchar(64),
"parent_id" varchar(128),
"format" varchar(64) DEFAULT 'ai-sdk/v6' NOT NULL,
"content" text DEFAULT '{"json": {}}' NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL
@@ -30,4 +30,6 @@ CREATE TABLE "assistant_thread" (
);
--> statement-breakpoint
ALTER TABLE "assistant_message" ADD CONSTRAINT "assistant_message_thread_id_assistant_thread_id_fk" FOREIGN KEY ("thread_id") REFERENCES "public"."assistant_thread"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "assistant_thread" ADD CONSTRAINT "assistant_thread_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "assistant_thread" ADD CONSTRAINT "assistant_thread_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "assistant_message__thread_id_created_at_idx" ON "assistant_message" USING btree ("thread_id","created_at");--> statement-breakpoint
CREATE INDEX "assistant_thread__user_id_updated_at_idx" ON "assistant_thread" USING btree ("user_id","updated_at");
@@ -294,7 +294,7 @@
"columns": {
"id": {
"name": "id",
"type": "varchar(64)",
"type": "varchar(128)",
"primaryKey": true,
"notNull": true
},
@@ -306,7 +306,7 @@
},
"parent_id": {
"name": "parent_id",
"type": "varchar(64)",
"type": "varchar(128)",
"primaryKey": false,
"notNull": false
},
@@ -332,7 +332,29 @@
"default": "now()"
}
},
"indexes": {},
"indexes": {
"assistant_message__thread_id_created_at_idx": {
"name": "assistant_message__thread_id_created_at_idx",
"columns": [
{
"expression": "thread_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "created_at",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"assistant_message_thread_id_assistant_thread_id_fk": {
"name": "assistant_message_thread_id_assistant_thread_id_fk",
@@ -404,7 +426,29 @@
"default": "now()"
}
},
"indexes": {},
"indexes": {
"assistant_thread__user_id_updated_at_idx": {
"name": "assistant_thread__user_id_updated_at_idx",
"columns": [
{
"expression": "user_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "updated_at",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"assistant_thread_user_id_user_id_fk": {
"name": "assistant_thread_user_id_user_id_fk",
@@ -2687,4 +2731,4 @@
"schemas": {},
"tables": {}
}
}
}
@@ -30,3 +30,7 @@ CREATE TABLE `assistant_thread` (
`updated_at` integer DEFAULT (unixepoch()) NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `user`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE INDEX `assistant_message__thread_id_created_at_idx` ON `assistant_message` (`thread_id`,`created_at`);
--> statement-breakpoint
CREATE INDEX `assistant_thread__user_id_updated_at_idx` ON `assistant_thread` (`user_id`,`updated_at`);
@@ -346,7 +346,16 @@
"default": "(unixepoch())"
}
},
"indexes": {},
"indexes": {
"assistant_message__thread_id_created_at_idx": {
"name": "assistant_message__thread_id_created_at_idx",
"columns": [
"thread_id",
"created_at"
],
"isUnique": false
}
},
"foreignKeys": {
"assistant_message_thread_id_assistant_thread_id_fk": {
"name": "assistant_message_thread_id_assistant_thread_id_fk",
@@ -422,7 +431,16 @@
"default": "(unixepoch())"
}
},
"indexes": {},
"indexes": {
"assistant_thread__user_id_updated_at_idx": {
"name": "assistant_thread__user_id_updated_at_idx",
"columns": [
"user_id",
"updated_at"
],
"isUnique": false
}
},
"foreignKeys": {
"assistant_thread_user_id_user_id_fk": {
"name": "assistant_thread_user_id_user_id_fk",
@@ -2744,4 +2762,4 @@
"internal": {
"indexes": {}
}
}
}
+33 -21
View File
@@ -496,28 +496,40 @@ export const assistantConfigurations = mysqlTable("assistant_configuration", {
updatedAt: timestamp().notNull().defaultNow(),
});
export const assistantThreads = mysqlTable("assistant_thread", {
id: varchar({ length: 64 }).notNull().primaryKey(),
userId: varchar({ length: 64 })
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
title: varchar({ length: 256 }),
modelId: varchar({ length: 256 }),
status: varchar({ length: 16 }).$type<"regular" | "archived">().notNull().default("regular"),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp().notNull().defaultNow(),
});
export const assistantThreads = mysqlTable(
"assistant_thread",
{
id: varchar({ length: 64 }).notNull().primaryKey(),
userId: varchar({ length: 64 })
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
title: varchar({ length: 256 }),
modelId: varchar({ length: 256 }),
status: varchar({ length: 16 }).$type<"regular" | "archived">().notNull().default("regular"),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp().notNull().defaultNow(),
},
(thread) => ({
userUpdatedAtIdx: index("assistant_thread__user_id_updated_at_idx").on(thread.userId, thread.updatedAt),
}),
);
export const assistantMessages = mysqlTable("assistant_message", {
id: varchar({ length: 64 }).notNull().primaryKey(),
threadId: varchar({ length: 64 })
.notNull()
.references(() => assistantThreads.id, { onDelete: "cascade" }),
parentId: varchar({ length: 64 }),
format: varchar({ length: 64 }).notNull().default("ai-sdk/v6"),
content: text().default(emptySuperJSON).notNull(),
createdAt: timestamp().notNull().defaultNow(),
});
export const assistantMessages = mysqlTable(
"assistant_message",
{
id: varchar({ length: 128 }).notNull().primaryKey(),
threadId: varchar({ length: 64 })
.notNull()
.references(() => assistantThreads.id, { onDelete: "cascade" }),
parentId: varchar({ length: 128 }),
format: varchar({ length: 64 }).notNull().default("ai-sdk/v6"),
content: text().default(emptySuperJSON).notNull(),
createdAt: timestamp().notNull().defaultNow(),
},
(message) => ({
threadCreatedAtIdx: index("assistant_message__thread_id_created_at_idx").on(message.threadId, message.createdAt),
}),
);
export const apiKeyRelations = relations(apiKeys, ({ one }) => ({
user: one(users, {
+33 -21
View File
@@ -495,28 +495,40 @@ export const assistantConfigurations = pgTable("assistant_configuration", {
updatedAt: timestamp().notNull().defaultNow(),
});
export const assistantThreads = pgTable("assistant_thread", {
id: varchar({ length: 64 }).notNull().primaryKey(),
userId: varchar({ length: 64 })
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
title: varchar({ length: 256 }),
modelId: varchar({ length: 256 }),
status: varchar({ length: 16 }).$type<"regular" | "archived">().notNull().default("regular"),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp().notNull().defaultNow(),
});
export const assistantThreads = pgTable(
"assistant_thread",
{
id: varchar({ length: 64 }).notNull().primaryKey(),
userId: varchar({ length: 64 })
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
title: varchar({ length: 256 }),
modelId: varchar({ length: 256 }),
status: varchar({ length: 16 }).$type<"regular" | "archived">().notNull().default("regular"),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp().notNull().defaultNow(),
},
(thread) => ({
userUpdatedAtIdx: index("assistant_thread__user_id_updated_at_idx").on(thread.userId, thread.updatedAt),
}),
);
export const assistantMessages = pgTable("assistant_message", {
id: varchar({ length: 64 }).notNull().primaryKey(),
threadId: varchar({ length: 64 })
.notNull()
.references(() => assistantThreads.id, { onDelete: "cascade" }),
parentId: varchar({ length: 64 }),
format: varchar({ length: 64 }).notNull().default("ai-sdk/v6"),
content: text().default(emptySuperJSON).notNull(),
createdAt: timestamp().notNull().defaultNow(),
});
export const assistantMessages = pgTable(
"assistant_message",
{
id: varchar({ length: 128 }).notNull().primaryKey(),
threadId: varchar({ length: 64 })
.notNull()
.references(() => assistantThreads.id, { onDelete: "cascade" }),
parentId: varchar({ length: 128 }),
format: varchar({ length: 64 }).notNull().default("ai-sdk/v6"),
content: text().default(emptySuperJSON).notNull(),
createdAt: timestamp().notNull().defaultNow(),
},
(message) => ({
threadCreatedAtIdx: index("assistant_message__thread_id_created_at_idx").on(message.threadId, message.createdAt),
}),
);
export const apiKeyRelations = relations(apiKeys, ({ one }) => ({
user: one(users, {
+39 -27
View File
@@ -480,34 +480,46 @@ export const assistantConfigurations = sqliteTable("assistant_configuration", {
.default(sql`(unixepoch())`),
});
export const assistantThreads = sqliteTable("assistant_thread", {
id: text().notNull().primaryKey(),
userId: text()
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
title: text(),
modelId: text(),
status: text().$type<"regular" | "archived">().notNull().default("regular"),
createdAt: int({ mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`),
updatedAt: int({ mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`),
});
export const assistantThreads = sqliteTable(
"assistant_thread",
{
id: text().notNull().primaryKey(),
userId: text()
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
title: text(),
modelId: text(),
status: text().$type<"regular" | "archived">().notNull().default("regular"),
createdAt: int({ mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`),
updatedAt: int({ mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`),
},
(thread) => ({
userUpdatedAtIdx: index("assistant_thread__user_id_updated_at_idx").on(thread.userId, thread.updatedAt),
}),
);
export const assistantMessages = sqliteTable("assistant_message", {
id: text().notNull().primaryKey(),
threadId: text()
.notNull()
.references(() => assistantThreads.id, { onDelete: "cascade" }),
parentId: text(),
format: text().notNull().default("ai-sdk/v6"),
content: text().default(emptySuperJSON).notNull(),
createdAt: int({ mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`),
});
export const assistantMessages = sqliteTable(
"assistant_message",
{
id: text().notNull().primaryKey(),
threadId: text()
.notNull()
.references(() => assistantThreads.id, { onDelete: "cascade" }),
parentId: text(),
format: text().notNull().default("ai-sdk/v6"),
content: text().default(emptySuperJSON).notNull(),
createdAt: int({ mode: "timestamp" })
.notNull()
.default(sql`(unixepoch())`),
},
(message) => ({
threadCreatedAtIdx: index("assistant_message__thread_id_created_at_idx").on(message.threadId, message.createdAt),
}),
);
export const apiKeyRelations = relations(apiKeys, ({ one }) => ({
user: one(users, {
+6 -3
View File
@@ -11,6 +11,9 @@ import * as mysqlSchema from "../schema/mysql";
import * as postgresqlSchema from "../schema/postgresql";
import * as sqliteSchema from "../schema/sqlite";
const mysqlTables = { ...mysqlSchema };
const postgresqlTables = { ...postgresqlSchema };
// We need the following three types as there is currently no support for Buffer in mysql & pg and
// so we use a custom type which results in the config beeing different
type FixedMysqlConfig = {
@@ -63,7 +66,7 @@ test("schemas should match", () => {
if (!("uniqueName" in sqliteColumn)) return;
if (!("primary" in sqliteColumn)) return;
const mysqlTable = mysqlSchema[tableName];
const mysqlTable = mysqlTables[tableName];
const mysqlColumn = mysqlTable[columnName as keyof typeof mysqlTable] as object;
if (!("isUnique" in mysqlColumn)) return;
@@ -84,7 +87,7 @@ test("schemas should match", () => {
).toEqual(mysqlColumn.primary);
});
const mysqlTable = mysqlSchema[tableName];
const mysqlTable = mysqlTables[tableName];
const sqliteForeignKeys = sqliteTable[Symbol.for("drizzle:SQLiteInlineForeignKeys") as keyof typeof sqliteTable] as
| SqliteForeignKey[]
| undefined;
@@ -144,7 +147,7 @@ test("schemas should match for postgresql", () => {
objectEntries(sqliteSchema).forEach(([tableName, sqliteTable]) => {
// keys of sqliteSchema and postgresqlSchema are the same, so we can safely use tableName as key
// skipcq: JS-E1007
const postgresqlTable = postgresqlSchema[tableName];
const postgresqlTable = postgresqlTables[tableName];
Object.entries(sqliteTable).forEach(([columnName, sqliteColumn]: [string, object]) => {
if (!("isUnique" in sqliteColumn)) return;
if (!("uniqueName" in sqliteColumn)) return;