refactor: trim v2 hardening scaffolding
This commit is contained in:
1 parent
ecfb9d59e0
commit
2eb0baf17e
75 files changed
+334
-2067
No files matched your search
@@ -29,13 +29,12 @@
|
||||
"generate:components": "pnpm generate:catalog",
|
||||
"generate": "pnpm generate:catalog",
|
||||
"evaluate:ai": "bun ./scripts/evaluate-ai-authoring.ts",
|
||||
"evaluate:mcp": "tsx ./scripts/evaluate-mcp-agent.ts",
|
||||
"test:ai": "bun ./scripts/evaluate-ai-authoring.ts --ci",
|
||||
"test:reference-apis": "tsx ./scripts/verify-reference-apis.ts",
|
||||
"format": "oxfmt .",
|
||||
"lint": "oxlint",
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.scripts.json"
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "catalog:",
|
||||
@@ -62,14 +61,10 @@
|
||||
"zod": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ai-sdk/mcp": "catalog:",
|
||||
"@ai-sdk/provider": "catalog:",
|
||||
"@homarr/tsconfig": "workspace:^0.1.0",
|
||||
"@openrouter/ai-sdk-provider": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/react": "catalog:",
|
||||
"@types/react-dom": "catalog:",
|
||||
"ai": "catalog:",
|
||||
"jsdom": "catalog:",
|
||||
"react-dom": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import { createMCPClient } from "@ai-sdk/mcp";
|
||||
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
|
||||
|
||||
import { CUSTOM_WIDGET_AI_EVALUATION_CASES } from "./ai-evaluation-cases";
|
||||
import { DEFAULT_GENERATOR_MODEL } from "./ai-evaluation";
|
||||
import {
|
||||
buildCustomWidgetMcpAgentPrompt,
|
||||
createCustomWidgetMcpAgent,
|
||||
getCustomWidgetMcpToolExecutions,
|
||||
getCustomWidgetMcpWorkflowIssues,
|
||||
} from "./mcp-agent";
|
||||
|
||||
const openRouterApiKey = process.env.OPENROUTER_API_KEY;
|
||||
const mcpUrl = process.env.HOMARR_MCP_URL;
|
||||
const mcpApiKey = process.env.HOMARR_MCP_API_KEY;
|
||||
if (!openRouterApiKey) throw new Error("OPENROUTER_API_KEY is required");
|
||||
if (!mcpUrl) throw new Error("HOMARR_MCP_URL is required");
|
||||
if (!mcpApiKey) throw new Error("HOMARR_MCP_API_KEY is required");
|
||||
|
||||
const requestedCase = process.argv.find((value) => value.startsWith("--case="))?.slice("--case=".length) ?? "pokedex";
|
||||
const definitionId = process.argv.find((value) => value.startsWith("--definition="))?.slice("--definition=".length);
|
||||
const persist = process.argv.includes("--persist");
|
||||
const testCase = CUSTOM_WIDGET_AI_EVALUATION_CASES.find(({ id }) => id === requestedCase);
|
||||
if (!testCase) throw new Error(`Unknown MCP evaluation case '${requestedCase}'`);
|
||||
|
||||
const client = await createMCPClient({
|
||||
transport: { type: "http", url: mcpUrl, headers: { ApiKey: mcpApiKey } },
|
||||
});
|
||||
|
||||
try {
|
||||
const tools = await client.tools();
|
||||
const openrouter = createOpenRouter({
|
||||
apiKey: openRouterApiKey,
|
||||
appName: "Homarr Custom Widget MCP Evaluation",
|
||||
appUrl: "https://homarr.dev",
|
||||
});
|
||||
const agent = createCustomWidgetMcpAgent({
|
||||
model: openrouter(process.env.OPENROUTER_GENERATOR_MODEL ?? DEFAULT_GENERATOR_MODEL, {
|
||||
structuredOutputs: { strict: true },
|
||||
provider: { require_parameters: true, data_collection: "deny" },
|
||||
}),
|
||||
tools,
|
||||
});
|
||||
const result = await agent.generate({
|
||||
prompt: buildCustomWidgetMcpAgentPrompt({ testCase, persist, definitionId }),
|
||||
timeout: 300_000,
|
||||
});
|
||||
const toolExecutions = getCustomWidgetMcpToolExecutions(result.steps);
|
||||
const toolsUsed = toolExecutions.map(({ tool }) => tool);
|
||||
const issues = getCustomWidgetMcpWorkflowIssues({
|
||||
output: result.output,
|
||||
toolExecutions,
|
||||
persist,
|
||||
definitionId,
|
||||
requiredQueryCount: testCase.acceptance.requestRules.filter(({ kind }) => kind !== "action").length,
|
||||
requiredActionCount: testCase.acceptance.requestRules.filter(({ kind }) => kind === "action").length,
|
||||
});
|
||||
const summary = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
model: process.env.OPENROUTER_GENERATOR_MODEL ?? DEFAULT_GENERATOR_MODEL,
|
||||
caseId: testCase.id,
|
||||
persist,
|
||||
definitionId: definitionId ?? null,
|
||||
toolsUsed,
|
||||
failedTools: toolExecutions.filter(({ succeeded }) => !succeeded).map(({ tool }) => tool),
|
||||
output: result.output,
|
||||
workflowIssues: issues,
|
||||
};
|
||||
const outputDirectory = path.resolve(process.cwd(), ".ai-evaluations", "mcp");
|
||||
await mkdir(outputDirectory, { recursive: true });
|
||||
const outputFile = path.join(outputDirectory, `${testCase.id}-${Date.now()}.json`);
|
||||
await writeFile(outputFile, JSON.stringify(summary, null, 2), "utf8");
|
||||
process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
|
||||
if (result.output.status === "fail" || issues.length > 0) process.exitCode = 1;
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
@@ -1,322 +0,0 @@
|
||||
import type { LanguageModel, ToolSet } from "ai";
|
||||
import { Output, stepCountIs, ToolLoopAgent } from "ai";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import type { CustomWidgetAiEvaluationCase } from "./ai-evaluation-cases";
|
||||
|
||||
export const CUSTOM_WIDGET_MCP_AGENT_TOOLS = [
|
||||
"customWidget_get",
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
"customWidget_validate",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_previewQuery",
|
||||
"customWidget_previewAction",
|
||||
"customWidget_previewJournal",
|
||||
"customWidget_create",
|
||||
"customWidget_update",
|
||||
"customWidget_configurationRequestUser",
|
||||
] as const;
|
||||
|
||||
export const customWidgetMcpAgentResultSchema = z.strictObject({
|
||||
status: z.enum(["pass", "needs-user-configuration", "fail"]),
|
||||
summary: z.string().min(1).max(1_000),
|
||||
definitionId: z.string().min(1).nullable(),
|
||||
previewUrl: z.url().nullable(),
|
||||
iterations: z.number().int().min(1).max(20),
|
||||
evidence: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
tool: z.string().min(1).max(128),
|
||||
outcome: z.enum(["passed", "repaired", "pending", "failed"]),
|
||||
detail: z.string().min(1).max(500),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(30),
|
||||
remainingIssues: z.array(z.string().min(1).max(500)).max(10),
|
||||
});
|
||||
|
||||
export type CustomWidgetMcpAgentResult = z.infer<typeof customWidgetMcpAgentResultSchema>;
|
||||
|
||||
export interface CustomWidgetMcpToolExecution {
|
||||
tool: string;
|
||||
succeeded: boolean;
|
||||
requestId?: string;
|
||||
configurationStatus?: "pending" | "completed";
|
||||
}
|
||||
|
||||
interface AgentToolStep {
|
||||
toolCalls: ReadonlyArray<{ toolCallId: string; toolName: string; input: unknown }>;
|
||||
toolResults: ReadonlyArray<{ toolCallId: string; toolName: string; output: unknown }>;
|
||||
}
|
||||
|
||||
const AGENT_INSTRUCTIONS = `You are the Homarr Custom Widget release evaluator. Use only the supplied Custom Widget MCP tools.
|
||||
|
||||
Read the live authoring prompt, skill, and schema before authoring. Never invent a tool, API route, validation result, preview result, or credential. Validate every revision. Create a preview, execute every load query that can run, simulate actions instead of causing side effects, and inspect the preview journal. Repair validation, request, runtime, and template problems and repeat the failed checks.
|
||||
|
||||
Never put plaintext credentials in a widget, response, summary, or tool argument. For an authenticated source without existing credentials, create a user configuration request with customWidget_configurationRequestUser. If the user completes it while the workflow is active, check the same request until it reports completed and then resume the preview checks. Otherwise report needs-user-configuration. Never repeat its URL or request token in the structured result. Do not call secret-writing tools.
|
||||
|
||||
Revise unsaved definitions in your working context; do not mutate a stored template while debugging. Persist only when the user prompt explicitly says persistence is allowed and all runnable checks pass. For edits, read the current definition first and update the same definition. Return the required structured result with evidence tied to successful tool calls. A pass must have no remaining issues.`;
|
||||
|
||||
export function selectCustomWidgetMcpTools(tools: Readonly<Record<string, unknown>>): ToolSet {
|
||||
return Object.fromEntries(
|
||||
CUSTOM_WIDGET_MCP_AGENT_TOOLS.flatMap((name) => (tools[name] ? [[name, tools[name]]] : [])),
|
||||
) as ToolSet;
|
||||
}
|
||||
|
||||
export function createCustomWidgetMcpAgent(args: { model: LanguageModel; tools: Readonly<Record<string, unknown>> }) {
|
||||
return new ToolLoopAgent({
|
||||
model: args.model,
|
||||
tools: selectCustomWidgetMcpTools(args.tools),
|
||||
instructions: AGENT_INSTRUCTIONS,
|
||||
stopWhen: stepCountIs(20),
|
||||
temperature: 0,
|
||||
output: Output.object({ schema: customWidgetMcpAgentResultSchema }),
|
||||
});
|
||||
}
|
||||
|
||||
export function buildCustomWidgetMcpAgentPrompt(args: {
|
||||
testCase: CustomWidgetAiEvaluationCase;
|
||||
persist: boolean;
|
||||
definitionId?: string;
|
||||
}) {
|
||||
const task = args.definitionId
|
||||
? `Edit and debug Custom Widget definition ${args.definitionId}.`
|
||||
: "Create and debug a new Custom Widget.";
|
||||
return `${task}
|
||||
|
||||
User request:
|
||||
${args.testCase.request}
|
||||
|
||||
Verified API notes:
|
||||
${args.testCase.apiNotes}
|
||||
|
||||
API documentation:
|
||||
${args.testCase.documentationUrl}
|
||||
|
||||
Persistence is ${args.persist ? "allowed after every runnable check passes" : "not allowed; stop after the validated preview"}.`;
|
||||
}
|
||||
|
||||
export function getCustomWidgetMcpToolExecutions(steps: readonly AgentToolStep[]): CustomWidgetMcpToolExecution[] {
|
||||
const results = new Map(
|
||||
steps.flatMap(({ toolResults }) => toolResults).map((result) => [result.toolCallId, result] as const),
|
||||
);
|
||||
return steps.flatMap(({ toolCalls }) =>
|
||||
toolCalls.map((call) => {
|
||||
const requestId = asRecord(call.input)?.requestId;
|
||||
const output = results.get(call.toolCallId)?.output;
|
||||
const status = asRecord(getMcpToolPayload(output))?.status;
|
||||
return {
|
||||
tool: call.toolName,
|
||||
succeeded: isSuccessfulMcpToolOutput(call.toolName, output),
|
||||
...(typeof requestId === "string" ? { requestId } : {}),
|
||||
...(call.toolName === "customWidget_configurationRequestUser" &&
|
||||
(status === "pending" || status === "completed")
|
||||
? { configurationStatus: status }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function getCustomWidgetMcpWorkflowIssues(args: {
|
||||
output: CustomWidgetMcpAgentResult;
|
||||
toolExecutions: readonly CustomWidgetMcpToolExecution[];
|
||||
persist: boolean;
|
||||
definitionId?: string;
|
||||
requiredQueryCount?: number;
|
||||
requiredActionCount?: number;
|
||||
}) {
|
||||
const issues: string[] = [];
|
||||
const firstIndex = (tool: string) => args.toolExecutions.findIndex((entry) => entry.tool === tool);
|
||||
const firstSuccessfulIndex = (tool: string) =>
|
||||
args.toolExecutions.findIndex((entry) => entry.tool === tool && entry.succeeded);
|
||||
const lastSuccessfulIndex = (tool: string) =>
|
||||
args.toolExecutions.findLastIndex((entry) => entry.tool === tool && entry.succeeded);
|
||||
const hasTool = (tool: string) => firstIndex(tool) >= 0;
|
||||
const hasSuccessfulTool = (tool: string) => firstSuccessfulIndex(tool) >= 0;
|
||||
const required = [
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
"customWidget_validate",
|
||||
];
|
||||
if (args.definitionId) required.unshift("customWidget_get");
|
||||
if (args.output.status === "pass") {
|
||||
required.push("customWidget_previewCreate", "customWidget_previewQuery", "customWidget_previewJournal");
|
||||
if ((args.requiredActionCount ?? 0) > 0) required.push("customWidget_previewAction");
|
||||
if (args.persist) required.push(args.definitionId ? "customWidget_update" : "customWidget_create");
|
||||
}
|
||||
if (args.output.status === "needs-user-configuration") {
|
||||
required.push("customWidget_configurationRequestUser");
|
||||
if (!args.persist && !args.definitionId) required.push("customWidget_previewCreate");
|
||||
if (args.persist && !args.definitionId) required.push("customWidget_create");
|
||||
}
|
||||
if (hasTool("customWidget_configurationRequestUser") && !required.includes("customWidget_configurationRequestUser")) {
|
||||
required.push("customWidget_configurationRequestUser");
|
||||
}
|
||||
for (const tool of required) {
|
||||
if (!hasTool(tool)) issues.push(`Required tool was not used: ${tool}`);
|
||||
else if (!hasSuccessfulTool(tool)) issues.push(`Required tool did not complete successfully: ${tool}`);
|
||||
}
|
||||
|
||||
const firstValidation = firstSuccessfulIndex("customWidget_validate");
|
||||
const finalValidation = lastSuccessfulIndex("customWidget_validate");
|
||||
for (const tool of ["customWidget_getAuthoringPrompt", "customWidget_getSkill", "customWidget_schema"]) {
|
||||
if (hasSuccessfulTool(tool) && firstValidation >= 0 && firstSuccessfulIndex(tool) > firstValidation) {
|
||||
issues.push(`${tool} must run before the first validation`);
|
||||
}
|
||||
}
|
||||
if (
|
||||
args.definitionId &&
|
||||
hasSuccessfulTool("customWidget_get") &&
|
||||
firstValidation >= 0 &&
|
||||
firstSuccessfulIndex("customWidget_get") > firstValidation
|
||||
) {
|
||||
issues.push("customWidget_get must run before validating an edit");
|
||||
}
|
||||
const previewCreate = firstSuccessfulIndex("customWidget_previewCreate");
|
||||
const finalPreviewCreate = lastSuccessfulIndex("customWidget_previewCreate");
|
||||
if (finalValidation >= 0 && finalPreviewCreate >= 0 && finalValidation > finalPreviewCreate) {
|
||||
issues.push("The final validation must run before customWidget_previewCreate");
|
||||
}
|
||||
const previewChecks = [
|
||||
"customWidget_previewQuery",
|
||||
...((args.requiredActionCount ?? 0) > 0 ? ["customWidget_previewAction"] : []),
|
||||
"customWidget_previewJournal",
|
||||
];
|
||||
for (const tool of previewChecks) {
|
||||
if (hasSuccessfulTool(tool) && previewCreate >= 0 && firstSuccessfulIndex(tool) < previewCreate) {
|
||||
issues.push(`${tool} must run after customWidget_previewCreate`);
|
||||
}
|
||||
}
|
||||
if (args.output.status === "pass") {
|
||||
const completedConfiguration = args.toolExecutions.findLastIndex(
|
||||
(entry) =>
|
||||
entry.tool === "customWidget_configurationRequestUser" &&
|
||||
entry.succeeded &&
|
||||
entry.configurationStatus === "completed",
|
||||
);
|
||||
if (hasTool("customWidget_configurationRequestUser") && completedConfiguration < 0) {
|
||||
issues.push("A passing result requires the user configuration request to report completed");
|
||||
}
|
||||
const verifiedExecutions =
|
||||
completedConfiguration >= 0 ? args.toolExecutions.slice(completedConfiguration + 1) : args.toolExecutions;
|
||||
for (const [tool, requiredCount] of [
|
||||
["customWidget_previewQuery", args.requiredQueryCount ?? 1],
|
||||
["customWidget_previewAction", args.requiredActionCount ?? 0],
|
||||
] as const) {
|
||||
const completed = verifiedExecutions.filter((entry) => entry.tool === tool && entry.succeeded);
|
||||
const distinctRequestIds = new Set(completed.flatMap(({ requestId }) => (requestId ? [requestId] : [])));
|
||||
const completedCount = distinctRequestIds.size > 0 ? distinctRequestIds.size : completed.length;
|
||||
if (completedCount < requiredCount) {
|
||||
issues.push(`${tool} completed ${completedCount} time(s); expected at least ${requiredCount}`);
|
||||
}
|
||||
}
|
||||
const finalJournal = lastSuccessfulIndex("customWidget_previewJournal");
|
||||
if (finalJournal >= 0) {
|
||||
for (const tool of ["customWidget_previewQuery", "customWidget_previewAction"]) {
|
||||
if (lastSuccessfulIndex(tool) > finalJournal) {
|
||||
issues.push("customWidget_previewJournal must run after all preview requests");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const persistenceTool = args.definitionId ? "customWidget_update" : "customWidget_create";
|
||||
if (args.persist && args.output.status === "pass" && hasSuccessfulTool(persistenceTool)) {
|
||||
const lastPreviewCheck = Math.max(...previewChecks.map(lastSuccessfulIndex));
|
||||
if (lastSuccessfulIndex(persistenceTool) < lastPreviewCheck) {
|
||||
issues.push(`${persistenceTool} must run after all required preview checks`);
|
||||
}
|
||||
}
|
||||
if (!args.persist) {
|
||||
for (const tool of ["customWidget_create", "customWidget_update"]) {
|
||||
if (hasTool(tool)) issues.push(`${tool} was used even though persistence was not allowed`);
|
||||
}
|
||||
}
|
||||
|
||||
const evidenceTools = new Set(args.output.evidence.map(({ tool }) => tool));
|
||||
for (const evidence of args.output.evidence) {
|
||||
const tool = evidence.tool;
|
||||
if (!hasTool(tool)) issues.push(`Structured evidence names a tool that was not used: ${tool}`);
|
||||
else if (evidence.outcome !== "failed" && !hasSuccessfulTool(tool)) {
|
||||
issues.push(`Structured evidence claims a successful outcome for a failed tool: ${tool}`);
|
||||
}
|
||||
}
|
||||
for (const tool of required) {
|
||||
if (hasSuccessfulTool(tool) && !evidenceTools.has(tool)) {
|
||||
issues.push(`Structured evidence is missing the required tool: ${tool}`);
|
||||
}
|
||||
}
|
||||
if (args.output.status === "pass" && args.output.remainingIssues.length > 0) {
|
||||
issues.push("A passing result cannot contain remaining issues");
|
||||
}
|
||||
if (args.output.status === "pass" && args.output.previewUrl === null) {
|
||||
issues.push("A passing result must include the tested preview URL");
|
||||
}
|
||||
if (args.persist && args.output.definitionId === null) {
|
||||
issues.push("A persisted result must include the definition ID");
|
||||
}
|
||||
if (args.output.status === "needs-user-configuration") {
|
||||
if (!hasSuccessfulTool("customWidget_configurationRequestUser")) {
|
||||
issues.push("User configuration status requires customWidget_configurationRequestUser");
|
||||
} else if (!evidenceTools.has("customWidget_configurationRequestUser")) {
|
||||
issues.push("Structured evidence is missing customWidget_configurationRequestUser");
|
||||
}
|
||||
const finalConfiguration = args.toolExecutions.findLast(
|
||||
(entry) => entry.tool === "customWidget_configurationRequestUser" && entry.succeeded,
|
||||
);
|
||||
if (finalConfiguration?.configurationStatus !== "pending") {
|
||||
issues.push("User configuration status requires a pending configuration request");
|
||||
}
|
||||
const configurationRequest = firstSuccessfulIndex("customWidget_configurationRequestUser");
|
||||
const targetCreation = args.persist ? lastSuccessfulIndex(persistenceTool) : previewCreate;
|
||||
if (!args.definitionId && targetCreation >= 0 && configurationRequest < targetCreation) {
|
||||
issues.push("customWidget_configurationRequestUser must run after its definition or preview target exists");
|
||||
}
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
function isSuccessfulMcpToolOutput(tool: string, output: unknown) {
|
||||
const record = asRecord(output);
|
||||
if (!record || record.isError === true) return false;
|
||||
const payload = getMcpToolPayload(output);
|
||||
if (tool === "customWidget_validate") return asRecord(payload)?.valid === true;
|
||||
if (tool === "customWidget_previewCreate") return asRecord(payload)?.success === true;
|
||||
if (tool === "customWidget_previewQuery" || tool === "customWidget_previewAction") {
|
||||
return asRecord(payload)?.ok === true;
|
||||
}
|
||||
return output !== undefined;
|
||||
}
|
||||
|
||||
function getMcpToolPayload(output: unknown) {
|
||||
const record = asRecord(output);
|
||||
return record ? (decodeMcpTextPayload(record) ?? record) : undefined;
|
||||
}
|
||||
|
||||
function decodeMcpTextPayload(output: Record<string, unknown>) {
|
||||
if (!Array.isArray(output.content)) return undefined;
|
||||
const text = output.content
|
||||
.flatMap((part) => {
|
||||
const record = asRecord(part);
|
||||
return record?.type === "text" && typeof record.text === "string" ? [record.text] : [];
|
||||
})
|
||||
.join("");
|
||||
if (!text) return undefined;
|
||||
try {
|
||||
return JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
@@ -1,519 +0,0 @@
|
||||
import type { LanguageModelV3GenerateResult } from "@ai-sdk/provider";
|
||||
import { tool } from "ai";
|
||||
import { MockLanguageModelV3 } from "ai/test";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import {
|
||||
createCustomWidgetMcpAgent,
|
||||
getCustomWidgetMcpToolExecutions,
|
||||
getCustomWidgetMcpWorkflowIssues,
|
||||
} from "../../scripts/mcp-agent";
|
||||
|
||||
const usage = {
|
||||
inputTokens: { total: 10, noCache: 10, cacheRead: undefined, cacheWrite: undefined },
|
||||
outputTokens: { total: 10, text: 10, reasoning: undefined },
|
||||
};
|
||||
|
||||
const toolCall = (
|
||||
toolName: string,
|
||||
index: number,
|
||||
input: Record<string, unknown> = {},
|
||||
): LanguageModelV3GenerateResult => ({
|
||||
content: [{ type: "tool-call", toolCallId: `call-${index}`, toolName, input: JSON.stringify(input) }],
|
||||
finishReason: { unified: "tool-calls", raw: undefined },
|
||||
usage,
|
||||
warnings: [],
|
||||
});
|
||||
|
||||
const finalResult = (value: unknown): LanguageModelV3GenerateResult => ({
|
||||
content: [{ type: "text", text: JSON.stringify(value) }],
|
||||
finishReason: { unified: "stop", raw: undefined },
|
||||
usage,
|
||||
warnings: [],
|
||||
});
|
||||
|
||||
const successfulExecutions = (tools: readonly string[]) =>
|
||||
tools.map((toolName) => ({ tool: toolName, succeeded: true }));
|
||||
const mcpOutput = (value: unknown) => ({ content: [{ type: "text" as const, text: JSON.stringify(value) }] });
|
||||
|
||||
describe("Custom Widget MCP agent", () => {
|
||||
it("runs a repair, preview, and persistence workflow before structured success", async () => {
|
||||
const calls: string[] = [];
|
||||
let validationCount = 0;
|
||||
const makeTool = (name: string) =>
|
||||
tool({
|
||||
description: name,
|
||||
inputSchema: z.object({ requestId: z.string().optional() }),
|
||||
execute: vi.fn(() => {
|
||||
calls.push(name);
|
||||
if (name === "customWidget_validate") {
|
||||
validationCount += 1;
|
||||
return mcpOutput({ valid: validationCount > 1 });
|
||||
}
|
||||
if (name === "customWidget_previewCreate") return mcpOutput({ success: true });
|
||||
if (name === "customWidget_previewQuery" || name === "customWidget_previewAction") {
|
||||
return mcpOutput({ ok: true });
|
||||
}
|
||||
return mcpOutput({});
|
||||
}),
|
||||
});
|
||||
const sequence = [
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
"customWidget_validate",
|
||||
"customWidget_validate",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_previewQuery",
|
||||
"customWidget_previewQuery",
|
||||
"customWidget_previewAction",
|
||||
"customWidget_previewJournal",
|
||||
"customWidget_create",
|
||||
];
|
||||
const output = {
|
||||
status: "pass" as const,
|
||||
summary: "The repaired widget passed validation and preview checks and was persisted.",
|
||||
definitionId: "widget-1",
|
||||
previewUrl: "http://localhost:3000/manage/custom-widgets/preview/session-1",
|
||||
iterations: 2,
|
||||
evidence: [...new Set(sequence)].map((name) => ({
|
||||
tool: name,
|
||||
outcome: name === "customWidget_validate" ? ("repaired" as const) : ("passed" as const),
|
||||
detail: `${name} completed.`,
|
||||
})),
|
||||
remainingIssues: [],
|
||||
};
|
||||
let queryIndex = 0;
|
||||
const responses = [
|
||||
...sequence.map((toolName, index) => {
|
||||
if (toolName === "customWidget_previewQuery") {
|
||||
queryIndex += 1;
|
||||
return toolCall(toolName, index, { requestId: `query-${queryIndex}` });
|
||||
}
|
||||
if (toolName === "customWidget_previewAction") return toolCall(toolName, index, { requestId: "action-1" });
|
||||
return toolCall(toolName, index);
|
||||
}),
|
||||
finalResult(output),
|
||||
];
|
||||
let responseIndex = 0;
|
||||
const model = new MockLanguageModelV3({
|
||||
doGenerate: async () => responses[responseIndex++] ?? finalResult(output),
|
||||
});
|
||||
const tools = Object.fromEntries(sequence.map((name) => [name, makeTool(name)]));
|
||||
|
||||
const result = await createCustomWidgetMcpAgent({ model, tools }).generate({ prompt: "Build a widget" });
|
||||
expect(result.output).toEqual(output);
|
||||
expect(calls).toEqual(sequence);
|
||||
expect(model.doGenerateCalls.at(-1)?.responseFormat).toMatchObject({ type: "json" });
|
||||
const toolExecutions = getCustomWidgetMcpToolExecutions(result.steps);
|
||||
expect(toolExecutions.filter(({ tool: toolName }) => toolName === "customWidget_validate")).toEqual([
|
||||
{ tool: "customWidget_validate", succeeded: false },
|
||||
{ tool: "customWidget_validate", succeeded: true },
|
||||
]);
|
||||
expect(
|
||||
toolExecutions
|
||||
.filter(({ tool: toolName }) => toolName === "customWidget_previewQuery")
|
||||
.map(({ requestId }) => requestId),
|
||||
).toEqual(["query-1", "query-2"]);
|
||||
expect(
|
||||
getCustomWidgetMcpWorkflowIssues({
|
||||
output: result.output,
|
||||
toolExecutions,
|
||||
persist: true,
|
||||
requiredQueryCount: 2,
|
||||
requiredActionCount: 1,
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses the current definition and updates it in the edit workflow", async () => {
|
||||
const calls: string[] = [];
|
||||
const sequence = [
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
"customWidget_get",
|
||||
"customWidget_validate",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_previewQuery",
|
||||
"customWidget_previewJournal",
|
||||
"customWidget_update",
|
||||
];
|
||||
const output = {
|
||||
status: "pass" as const,
|
||||
summary: "The existing widget passed its edited preview and was updated.",
|
||||
definitionId: "widget-1",
|
||||
previewUrl: "http://localhost:3000/manage/custom-widgets/preview/session-2",
|
||||
iterations: 1,
|
||||
evidence: sequence.map((name) => ({ tool: name, outcome: "passed" as const, detail: `${name} completed.` })),
|
||||
remainingIssues: [],
|
||||
};
|
||||
const responses = [
|
||||
...sequence.map((toolName, index) =>
|
||||
toolCall(toolName, index, toolName === "customWidget_previewQuery" ? { requestId: "query-1" } : {}),
|
||||
),
|
||||
finalResult(output),
|
||||
];
|
||||
let responseIndex = 0;
|
||||
const model = new MockLanguageModelV3({
|
||||
doGenerate: async () => responses[responseIndex++] ?? finalResult(output),
|
||||
});
|
||||
const tools = Object.fromEntries(
|
||||
sequence.map((name) => [
|
||||
name,
|
||||
tool({
|
||||
description: name,
|
||||
inputSchema: z.object({ requestId: z.string().optional() }),
|
||||
execute: () => {
|
||||
calls.push(name);
|
||||
if (name === "customWidget_validate") return mcpOutput({ valid: true });
|
||||
if (name === "customWidget_previewCreate") return mcpOutput({ success: true });
|
||||
if (name === "customWidget_previewQuery") return mcpOutput({ ok: true });
|
||||
return mcpOutput({});
|
||||
},
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await createCustomWidgetMcpAgent({ model, tools }).generate({ prompt: "Edit widget-1" });
|
||||
expect(result.output).toEqual(output);
|
||||
expect(
|
||||
getCustomWidgetMcpWorkflowIssues({
|
||||
output: result.output,
|
||||
toolExecutions: getCustomWidgetMcpToolExecutions(result.steps),
|
||||
persist: true,
|
||||
definitionId: "widget-1",
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects a passing summary that skipped real MCP checks", () => {
|
||||
expect(
|
||||
getCustomWidgetMcpWorkflowIssues({
|
||||
output: {
|
||||
status: "pass",
|
||||
summary: "Looks good.",
|
||||
definitionId: null,
|
||||
previewUrl: null,
|
||||
iterations: 1,
|
||||
evidence: [{ tool: "customWidget_validate", outcome: "passed", detail: "Valid." }],
|
||||
remainingIssues: ["Preview was not tested."],
|
||||
},
|
||||
toolExecutions: successfulExecutions(["customWidget_validate"]),
|
||||
persist: false,
|
||||
}),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining("customWidget_previewCreate"),
|
||||
"A passing result cannot contain remaining issues",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects fabricated evidence and persistence before the final preview checks", () => {
|
||||
const toolsUsed = [
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
"customWidget_validate",
|
||||
"customWidget_create",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_previewQuery",
|
||||
"customWidget_previewJournal",
|
||||
];
|
||||
|
||||
expect(
|
||||
getCustomWidgetMcpWorkflowIssues({
|
||||
output: {
|
||||
status: "pass",
|
||||
summary: "The widget was tested.",
|
||||
definitionId: "widget-1",
|
||||
previewUrl: "http://localhost:3000/manage/custom-widgets/preview/session-3",
|
||||
iterations: 1,
|
||||
evidence: [
|
||||
...toolsUsed.map((name) => ({ tool: name, outcome: "passed" as const, detail: `${name} completed.` })),
|
||||
{ tool: "customWidget_previewAction", outcome: "passed", detail: "The model claimed an action passed." },
|
||||
],
|
||||
remainingIssues: [],
|
||||
},
|
||||
toolExecutions: successfulExecutions(toolsUsed),
|
||||
persist: true,
|
||||
}),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
"customWidget_create must run after all required preview checks",
|
||||
"Structured evidence names a tool that was not used: customWidget_previewAction",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts a repaired preview followed by final validation and a fresh preview", () => {
|
||||
const toolsUsed = [
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
"customWidget_validate",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_validate",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_previewQuery",
|
||||
"customWidget_previewJournal",
|
||||
];
|
||||
|
||||
expect(
|
||||
getCustomWidgetMcpWorkflowIssues({
|
||||
output: {
|
||||
status: "pass",
|
||||
summary: "The repaired widget passed a fresh preview.",
|
||||
definitionId: null,
|
||||
previewUrl: "http://localhost:3000/manage/custom-widgets/preview/session-repaired",
|
||||
iterations: 2,
|
||||
evidence: [...new Set(toolsUsed)].map((name) => ({
|
||||
tool: name,
|
||||
outcome: name === "customWidget_validate" ? ("repaired" as const) : ("passed" as const),
|
||||
detail: `${name} completed.`,
|
||||
})),
|
||||
remainingIssues: [],
|
||||
},
|
||||
toolExecutions: successfulExecutions(toolsUsed),
|
||||
persist: false,
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not report journal ordering when the journal was never run", () => {
|
||||
const toolsUsed = [
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
"customWidget_validate",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_previewQuery",
|
||||
];
|
||||
|
||||
const issues = getCustomWidgetMcpWorkflowIssues({
|
||||
output: {
|
||||
status: "pass",
|
||||
summary: "The agent incorrectly skipped the journal.",
|
||||
definitionId: null,
|
||||
previewUrl: "http://localhost:3000/manage/custom-widgets/preview/session-no-journal",
|
||||
iterations: 1,
|
||||
evidence: toolsUsed.map((name) => ({
|
||||
tool: name,
|
||||
outcome: "passed" as const,
|
||||
detail: `${name} completed.`,
|
||||
})),
|
||||
remainingIssues: [],
|
||||
},
|
||||
toolExecutions: successfulExecutions(toolsUsed),
|
||||
persist: false,
|
||||
});
|
||||
|
||||
expect(issues).toContain("Required tool was not used: customWidget_previewJournal");
|
||||
expect(issues).not.toContain("customWidget_previewJournal must run after all preview requests");
|
||||
});
|
||||
|
||||
it("allows secure preview configuration to pause before authenticated requests can run", () => {
|
||||
const toolsUsed = [
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
"customWidget_validate",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_configurationRequestUser",
|
||||
];
|
||||
|
||||
expect(
|
||||
getCustomWidgetMcpWorkflowIssues({
|
||||
output: {
|
||||
status: "needs-user-configuration",
|
||||
summary: "The definition is valid and the authenticated preview is waiting for secure user input.",
|
||||
definitionId: null,
|
||||
previewUrl: "http://localhost:3000/manage/custom-widgets/preview/session-4",
|
||||
iterations: 1,
|
||||
evidence: [...new Set(toolsUsed)].map((name) => ({
|
||||
tool: name,
|
||||
outcome: "passed" as const,
|
||||
detail: `${name} completed.`,
|
||||
})),
|
||||
remainingIssues: [],
|
||||
},
|
||||
toolExecutions: successfulExecutions(toolsUsed).map((entry) =>
|
||||
entry.tool === "customWidget_configurationRequestUser"
|
||||
? { ...entry, configurationStatus: "pending" as const }
|
||||
: entry,
|
||||
),
|
||||
persist: false,
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("resumes preview checks after secure user configuration reports completion", async () => {
|
||||
let configurationCalls = 0;
|
||||
const sequence = [
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
"customWidget_validate",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_configurationRequestUser",
|
||||
"customWidget_configurationRequestUser",
|
||||
"customWidget_previewQuery",
|
||||
"customWidget_previewJournal",
|
||||
];
|
||||
const output = {
|
||||
status: "pass" as const,
|
||||
summary: "The user completed secure source configuration and the authenticated preview passed.",
|
||||
definitionId: null,
|
||||
previewUrl: "http://localhost:3000/manage/custom-widgets/preview/session-configured",
|
||||
iterations: 2,
|
||||
evidence: [...new Set(sequence)].map((name) => ({
|
||||
tool: name,
|
||||
outcome: "passed" as const,
|
||||
detail: `${name} completed.`,
|
||||
})),
|
||||
remainingIssues: [],
|
||||
};
|
||||
const responses = [
|
||||
...sequence.map((toolName, index) => {
|
||||
if (toolName === "customWidget_configurationRequestUser") {
|
||||
return toolCall(
|
||||
toolName,
|
||||
index,
|
||||
configurationCalls++ === 0
|
||||
? { previewSessionId: "preview-1", sourceId: "default" }
|
||||
: { requestId: "configuration-1" },
|
||||
);
|
||||
}
|
||||
return toolCall(toolName, index, toolName === "customWidget_previewQuery" ? { requestId: "query-1" } : {});
|
||||
}),
|
||||
finalResult(output),
|
||||
];
|
||||
let responseIndex = 0;
|
||||
let configurationResults = 0;
|
||||
const model = new MockLanguageModelV3({
|
||||
doGenerate: async () => responses[responseIndex++] ?? finalResult(output),
|
||||
});
|
||||
const tools = Object.fromEntries(
|
||||
sequence.map((name) => [
|
||||
name,
|
||||
tool({
|
||||
description: name,
|
||||
inputSchema: z.object({
|
||||
requestId: z.string().optional(),
|
||||
previewSessionId: z.string().optional(),
|
||||
sourceId: z.string().optional(),
|
||||
}),
|
||||
execute: () => {
|
||||
if (name === "customWidget_validate") return mcpOutput({ valid: true });
|
||||
if (name === "customWidget_previewCreate") return mcpOutput({ success: true });
|
||||
if (name === "customWidget_previewQuery") return mcpOutput({ ok: true });
|
||||
if (name === "customWidget_configurationRequestUser") {
|
||||
configurationResults += 1;
|
||||
return mcpOutput({
|
||||
requestId: "configuration-1",
|
||||
status: configurationResults === 1 ? "pending" : "completed",
|
||||
});
|
||||
}
|
||||
return mcpOutput({});
|
||||
},
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
const result = await createCustomWidgetMcpAgent({ model, tools }).generate({ prompt: "Build a Jellyfin widget" });
|
||||
const toolExecutions = getCustomWidgetMcpToolExecutions(result.steps);
|
||||
expect(
|
||||
toolExecutions
|
||||
.filter(({ tool: toolName }) => toolName === "customWidget_configurationRequestUser")
|
||||
.map(({ configurationStatus }) => configurationStatus),
|
||||
).toEqual(["pending", "completed"]);
|
||||
expect(
|
||||
getCustomWidgetMcpWorkflowIssues({
|
||||
output: result.output,
|
||||
toolExecutions,
|
||||
persist: false,
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects success while secure user configuration is still pending", () => {
|
||||
const toolsUsed = [
|
||||
"customWidget_getAuthoringPrompt",
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
"customWidget_validate",
|
||||
"customWidget_previewCreate",
|
||||
"customWidget_configurationRequestUser",
|
||||
"customWidget_previewQuery",
|
||||
"customWidget_previewJournal",
|
||||
];
|
||||
const toolExecutions = successfulExecutions(toolsUsed).map((entry) =>
|
||||
entry.tool === "customWidget_configurationRequestUser"
|
||||
? { ...entry, configurationStatus: "pending" as const }
|
||||
: entry,
|
||||
);
|
||||
|
||||
expect(
|
||||
getCustomWidgetMcpWorkflowIssues({
|
||||
output: {
|
||||
status: "pass",
|
||||
summary: "The agent claimed the authenticated preview passed before configuration completed.",
|
||||
definitionId: null,
|
||||
previewUrl: "http://localhost:3000/manage/custom-widgets/preview/session-pending",
|
||||
iterations: 1,
|
||||
evidence: toolsUsed.map((name) => ({
|
||||
tool: name,
|
||||
outcome: "passed" as const,
|
||||
detail: `${name} completed.`,
|
||||
})),
|
||||
remainingIssues: [],
|
||||
},
|
||||
toolExecutions,
|
||||
persist: false,
|
||||
}),
|
||||
).toContain("A passing result requires the user configuration request to report completed");
|
||||
});
|
||||
|
||||
it("never exposes a credential-writing tool to the model", async () => {
|
||||
const forbiddenTool = tool({
|
||||
description: "Write a plaintext secret",
|
||||
inputSchema: z.object({ secret: z.string() }),
|
||||
execute: vi.fn(),
|
||||
});
|
||||
const safeTool = tool({
|
||||
description: "Request secure user configuration",
|
||||
inputSchema: z.object({}),
|
||||
execute: vi.fn(),
|
||||
});
|
||||
const model = new MockLanguageModelV3({
|
||||
doGenerate: async () =>
|
||||
finalResult({
|
||||
status: "fail",
|
||||
summary: "No source values were supplied.",
|
||||
definitionId: null,
|
||||
previewUrl: null,
|
||||
iterations: 1,
|
||||
evidence: [
|
||||
{ tool: "customWidget_configurationRequestUser", outcome: "pending", detail: "User input needed." },
|
||||
],
|
||||
remainingIssues: ["Source configuration is required."],
|
||||
}),
|
||||
});
|
||||
|
||||
await createCustomWidgetMcpAgent({
|
||||
model,
|
||||
tools: {
|
||||
customWidget_sourceConfigure: forbiddenTool,
|
||||
customWidget_secretSet: forbiddenTool,
|
||||
customWidget_configurationRequestUser: safeTool,
|
||||
},
|
||||
}).generate({ prompt: "Create an authenticated widget" });
|
||||
|
||||
const exposedTools = model.doGenerateCalls[0]?.tools?.map(({ name }) => name);
|
||||
expect(exposedTools).toContain("customWidget_configurationRequestUser");
|
||||
expect(exposedTools).not.toContain("customWidget_sourceConfigure");
|
||||
expect(exposedTools).not.toContain("customWidget_secretSet");
|
||||
});
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"extends": "@homarr/tsconfig/base.json",
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "node_modules/.cache/scripts-tsbuildinfo.json"
|
||||
},
|
||||
"include": ["scripts/**/*.ts"],
|
||||
"exclude": ["node_modules", "scripts/verify-reference-apis.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user