streamline AI import and Workshop errors

This commit is contained in:
ajnart committed 2026-07-30 08:00:47 +02:00
1 parent 7a2d6009f7
commit 944c674939
21 files changed
+149 -109

No files matched your search

@@ -11,7 +11,7 @@ export const CUSTOM_WIDGET_MANTINE_VERSION = customJsxAuthoringCatalog.mantineVe
const CUSTOM_WIDGET_AI_PROMPT_LIMIT = 12_000;
export const CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION =
"Return exactly one complete `json` fenced block followed by one complete `jsx` fenced block. Do not include prose outside those blocks.";
"Return exactly one complete `json` fenced block containing the entire widget. Put the complete JSX source directly in the `template` string and JSON-escape it correctly. Do not include prose or additional code blocks.";
const RECOMMENDED_COMPONENTS = [
"Stack",
@@ -81,14 +81,13 @@ const leanShape = `{
"category": { "label": "Category", "control": "text", "default": "all" },
"limit": { "label": "Result limit", "control": "number", "default": 20, "min": 1, "max": 100 }
},
"template": "__HOMARR_TEMPLATE__"
"template": "<Stack><Text>{data.items?.name}</Text></Stack>"
}`;
function compactExample(index: number) {
const example = customJsxExamples[index];
if (!example) return "";
const { template, ...manifest } = example.widget;
return `Example — ${example.title}:\n\n\`\`\`json\n${JSON.stringify({ ...manifest, template: "__HOMARR_TEMPLATE__" }, null, 2)}\n\`\`\`\n\n\`\`\`jsx\n${template}\n\`\`\``;
return `Example — ${example.title}:\n\n\`\`\`json\n${JSON.stringify(example.widget, null, 2)}\n\`\`\``;
}
const AUTHORING_PROMPT = `You are writing one safe Homarr Custom JSX v2 dashboard widget for Mantine ${CUSTOM_WIDGET_MANTINE_VERSION}.
@@ -122,7 +121,7 @@ ${compactExample(0)}
${compactExample(1)}
Output the manifest with template set exactly to "__HOMARR_TEMPLATE__", then put the complete template in the JSX block.`;
Output one complete JSON manifest. Put the complete JSX directly in its template string so the user can copy one code block and paste it into Homarr once.`;
export const CUSTOM_WIDGET_AUTHORING_PROMPT = AUTHORING_PROMPT;
+5 -35
View File
@@ -69,10 +69,6 @@ function removedStateIssues(value: Record<string, unknown>): CustomWidgetImportI
);
}
function isTemplatePlaceholder(value: unknown) {
return typeof value === "string" && value.replace(/[\\*_`\s]/gu, "").toUpperCase() === "HOMARRTEMPLATE";
}
type ParsedWidgetValue =
| { success: true; value: Record<string, unknown> }
| { success: false; issue: CustomWidgetImportIssue };
@@ -100,24 +96,10 @@ export function parseCustomWidgetClipboard(text: string): HomarrCustomWidgetV2 |
export function parseCustomWidgetClipboardDetailed(text: string): CustomWidgetParseResult {
const blocks = extractFencedBlocks(text);
const jsonBlock = blocks.find((block) => block.language === "json" || block.language === "");
const jsxBlock = blocks.find((block) => block.language === "jsx" || block.language === "tsx");
const source = jsonBlock?.content ?? text;
const parsedValue = parseWidgetValue(source);
if (!parsedValue.success) return { success: false, issues: [parsedValue.issue] };
const widget = { ...parsedValue.value };
if (jsonBlock && isTemplatePlaceholder(widget.template) && !jsxBlock) {
return {
success: false,
issues: [
{
code: "MISSING_JSX_BLOCK",
path: ["template"],
message: "The manifest uses a template placeholder but no fenced JSX block was provided.",
},
],
};
}
if (jsxBlock && isTemplatePlaceholder(widget.template)) widget.template = jsxBlock.content.trim();
const removedIssues = removedStateIssues(widget);
if (removedIssues.length > 0) return { success: false, issues: removedIssues };
const parsed = customWidgetImportSchema.safeParse(widget);
@@ -128,20 +110,17 @@ export function parseCustomWidgetClipboardDetailed(text: string): CustomWidgetPa
export function parseCustomWidgetAiResponse(text: string): CustomWidgetParseResult {
const blocks = extractFencedBlocks(text);
const jsonBlocks = blocks.filter((block) => block.language === "json" || block.language === "");
const jsxBlocks = blocks.filter((block) => block.language === "jsx" || block.language === "tsx");
const formatIssues: CustomWidgetImportIssue[] = [];
if (jsonBlocks.length !== 1)
formatIssues.push({ code: "AI_JSON_BLOCK_REQUIRED", message: "Expected exactly one fenced json block." });
if (jsxBlocks.length !== 1)
formatIssues.push({ code: "AI_JSX_BLOCK_REQUIRED", message: "Expected exactly one fenced jsx block." });
if (blocks.length !== jsonBlocks.length)
formatIssues.push({
code: "AI_SINGLE_JSON_BLOCK_REQUIRED",
message: "Expected one JSON block only. Put the complete JSX directly in its template field.",
});
const source = jsonBlocks[0]?.content ?? text;
const parsedValue = parseWidgetValue(source);
if (!parsedValue.success) {
if (/\\_/u.test(source))
formatIssues.push({
code: "INVALID_JSON_ESCAPE",
message: 'JSON does not allow \\_ escapes. The template placeholder must be "__HOMARR_TEMPLATE__".',
});
if (/"(?:stateSchema|defaultState)"\s*:/u.test(source))
formatIssues.push({
code: "REMOVED_LOCAL_STATE",
@@ -153,15 +132,6 @@ export function parseCustomWidgetAiResponse(text: string): CustomWidgetParseResu
const removedIssues = removedStateIssues(widget);
if (removedIssues.length > 0) formatIssues.push(...removedIssues);
const warnings: CustomWidgetImportIssue[] = [];
if (jsxBlocks[0]) {
if (isTemplatePlaceholder(widget.template) || !widget.template) widget.template = jsxBlocks[0].content.trim();
else if (widget.template !== jsxBlocks[0].content.trim())
formatIssues.push({
code: "AI_TEMPLATE_PLACEHOLDER_REQUIRED",
path: ["template"],
message: 'The manifest template must be "__HOMARR_TEMPLATE__" when a separate JSX block is returned.',
});
}
if (formatIssues.length > 0) return { success: false, issues: formatIssues.slice(0, MAX_IMPORT_ISSUES) };
const parsed = customWidgetImportSchema.safeParse(widget);
if (!parsed.success) return { success: false, issues: zodIssues(parsed.error) };
@@ -18,7 +18,9 @@ describe("AI prompt", () => {
expect(prompt).toContain("Example — Service dashboard");
expect(prompt).toContain("Example — Search and action");
expect(prompt).toContain("visual hierarchy");
expect(prompt).toContain('template set exactly to "__HOMARR_TEMPLATE__"');
expect(prompt).toContain("Put the complete JSX directly in its template string");
expect(prompt).toContain("copy one code block and paste it into Homarr once");
expect(prompt).not.toContain("fenced block followed by");
expect(prompt).toContain('trigger="manual"');
expect(prompt).toContain("never write `=> {` anywhere");
expect(prompt).toContain('"choicesFrom"');
@@ -7,12 +7,11 @@ import {
parseCustomWidgetClipboardDetailed,
} from "../core";
const response = (manifest: unknown, jsx = "<Text>Ready</Text>") =>
`\`\`\`json\n${JSON.stringify(manifest, null, 2)}\n\`\`\`\n\`\`\`jsx\n${jsx}\n\`\`\``;
const response = (manifest: unknown) => `\`\`\`json\n${JSON.stringify(manifest, null, 2)}\n\`\`\``;
describe("Custom Widget imports", () => {
it("accepts exactly one lean manifest and JSX block", () => {
const result = parseCustomWidgetAiResponse(response({ ...CUSTOM_WIDGET_STARTER, template: "__HOMARR_TEMPLATE__" }));
it("accepts one complete JSON block and loads its template", () => {
const result = parseCustomWidgetAiResponse(response({ ...CUSTOM_WIDGET_STARTER, template: "<Text>Ready</Text>" }));
expect(result.success).toBe(true);
if (result.success) expect(result.widget.template).toBe("<Text>Ready</Text>");
});
@@ -25,7 +24,7 @@ describe("Custom Widget imports", () => {
requests: [],
optionsSchema: {},
defaultOptions: {},
template: "__HOMARR_TEMPLATE__",
template: "<Text>Ready</Text>",
}),
);
expect(result.success).toBe(false);
@@ -34,12 +33,20 @@ describe("Custom Widget imports", () => {
it("reports missing fences and removed local state", () => {
expect(parseCustomWidgetAiResponse(JSON.stringify(CUSTOM_WIDGET_STARTER)).success).toBe(false);
const result = parseCustomWidgetAiResponse(
response({ ...CUSTOM_WIDGET_STARTER, stateSchema: {}, template: "__HOMARR_TEMPLATE__" }),
response({ ...CUSTOM_WIDGET_STARTER, stateSchema: {}, template: "<Text>Ready</Text>" }),
);
expect(result.success).toBe(false);
if (!result.success) expect(result.issues.some(({ code }) => code === "REMOVED_LOCAL_STATE")).toBe(true);
});
it("rejects additional code blocks", () => {
const result = parseCustomWidgetAiResponse(
`${response({ ...CUSTOM_WIDGET_STARTER, template: "<Text>Ready</Text>" })}\n\`\`\`jsx\n<Text>Old format</Text>\n\`\`\``,
);
expect(result.success).toBe(false);
if (!result.success) expect(result.issues.some(({ code }) => code === "AI_SINGLE_JSON_BLOCK_REQUIRED")).toBe(true);
});
it("returns a capability review from keyed records", () => {
const review = getImportReview(CUSTOM_WIDGET_STARTER);
expect(review).toMatchObject({ origins: ["https://example.com"], authTypes: ["none"], hasActions: false });
@@ -13,15 +13,12 @@ describe("reference widget capabilities", () => {
expect(parsed.requests.detail?.trigger).toBe("manual");
});
it("round-trips the full Pokédex through the exact two-block AI paste format", () => {
it("round-trips the full Pokédex through the single-block AI paste format", () => {
const pokedex = BUNDLED_CUSTOM_WIDGETS.find(({ id }) => id === "seed-pokedex")?.widget;
if (!pokedex) throw new Error("Pokédex seed was not found");
const { template, ...manifest } = pokedex;
const parsed = parseCustomWidgetAiResponse(
`\`\`\`json\n${JSON.stringify({ ...manifest, template: "__HOMARR_TEMPLATE__" }, null, 2)}\n\`\`\`\n\n\`\`\`jsx\n${template}\n\`\`\``,
);
const parsed = parseCustomWidgetAiResponse(`\`\`\`json\n${JSON.stringify(pokedex, null, 2)}\n\`\`\``);
expect(parsed.success).toBe(true);
if (parsed.success) expect(parsed.widget.template).toBe(template);
if (parsed.success) expect(parsed.widget.template).toBe(pokedex.template);
});
it("validates a polished Portainer dashboard with start, stop, and restart actions", () => {
@@ -38,10 +35,10 @@ describe("reference widget capabilities", () => {
});
it("round-trips the Portainer dashboard through AI paste", () => {
const { template, ...manifest } = PORTAINER_REFERENCE_WIDGET;
const parsed = parseCustomWidgetAiResponse(
`\`\`\`json\n${JSON.stringify({ ...manifest, template: "__HOMARR_TEMPLATE__" }, null, 2)}\n\`\`\`\n\n\`\`\`jsx\n${template}\n\`\`\``,
`\`\`\`json\n${JSON.stringify(PORTAINER_REFERENCE_WIDGET, null, 2)}\n\`\`\``,
);
expect(parsed.success).toBe(true);
if (parsed.success) expect(parsed.widget.template).toBe(PORTAINER_REFERENCE_WIDGET.template);
});
});