feat(assistant): optimize MCP and custom widget authoring (#6743)

* feat(assistant): optimize MCP and custom widget authoring

* fix(assistant): isolate server-safe JSX analyzer

* refactor(assistant): generate MCP tool staging

* fix(assistant): preserve widget placement follow-up

* fix(ci): allow fast gate to finish

* fix(custom-widgets): address review findings

* fix(custom-widgets): split preview evidence module

* style: format assistant custom widget files

* fix(custom-widgets): sync formatted skill schema
This commit is contained in:
Thomas authored and GitHub committed 2026-08-30 23:43:29 +02:00
1 parent 38f4b0e1f8
commit 5e23659d99
95 files changed
+6799 -1778

No files matched your search

@@ -17,6 +17,8 @@ interface AnalyzerJsxContext {
visitArrow(node: AstNode, depth: number, bindings: ReadonlySet<string>): void;
}
const componentsRequiringLiteralRequestId = new Set(["SubFetch", "ActionButton", "ToggleSwitch"]);
export function analyzeCustomJsxElement(
node: AstNode,
depth: number,
@@ -33,6 +35,17 @@ export function analyzeCustomJsxElement(
const resolvedName = name ? resolveCustomJsxComponentName(name) : null;
const descriptor = resolvedName ? customJsxComponentByName.get(resolvedName) : undefined;
const attributes = nodesOf(opening.attributes);
if (resolvedName && componentsRequiringLiteralRequestId.has(resolvedName)) {
const requestIdAttribute = attributes.find((attribute) => {
if (attribute.type !== "JSXAttribute") return false;
const attributeName = nodeOf(attribute.name);
return attributeName?.type === "JSXIdentifier" && attributeName.name === "requestId";
});
const requestIdValue = requestIdAttribute ? nodeOf(requestIdAttribute.value) : null;
if (requestIdValue?.type !== "Literal" || typeof requestIdValue.value !== "string" || !requestIdValue.value) {
context.add(requestIdAttribute ?? opening, `${resolvedName} must use a literal requestId`);
}
}
if (resolvedName === "TablerIcon") {
const attributeNames = new Set<string>();
for (const attribute of attributes) {
@@ -136,6 +149,10 @@ function analyzeAttributeValue(
const reason = getInvalidCustomJsxPropValueReason(componentName, attributeName, literalValue.value);
if (reason) context.add(attribute, `INVALID_PROP_VALUE: ${reason}`);
}
const expression = value?.type === "JSXExpressionContainer" ? nodeOf(value.expression) : null;
if (attributeName === "resetKey" && ["ArrayExpression", "ObjectExpression"].includes(expression?.type ?? "")) {
context.add(attribute, "INVALID_PROP_VALUE: resetKey must resolve to a finite number, string, boolean, or null");
}
if (
CUSTOM_JSX_URL_PROPS.has(attributeName) &&
value?.type === "Literal" &&
@@ -145,7 +162,6 @@ function analyzeAttributeValue(
context.add(attribute, `INVALID_PROP_VALUE: '${attributeName}' contains an unsafe URL`);
}
if (value?.type !== "JSXExpressionContainer") return;
const expression = nodeOf(value.expression);
if (expression && containsEscapingCallback(expression)) {
context.add(attribute, `BLOCKED_CAPABILITY: Callback prop '${attributeName}' is not allowed`);
} else if (expression && expression.type !== "JSXEmptyExpression") {
@@ -49,6 +49,7 @@ const callableRootMembers: Readonly<Record<string, ReadonlySet<string>>> = {
"now",
"toISOString",
"toLocaleDateString",
"toLocaleString",
"toLocaleTimeString",
]),
JSON: new Set(["stringify"]),
@@ -30,6 +30,16 @@ export type { CustomJsxTemplateDiagnostic } from "./analyzer-diagnostics";
const JsxParser = Parser.extend(jsx());
const requestStatusLabels = new Set(["loading", "success", "error"]);
export function addCustomJsxDiagnosticSourceExcerpts(
template: string,
diagnostics: readonly CustomJsxTemplateDiagnostic[],
) {
return diagnostics.map((diagnostic) => ({
...diagnostic,
sourceExcerpt: template.slice(Math.max(0, diagnostic.index - 100), diagnostic.index + 100),
}));
}
function directRequestStatusId(node: AstNode | null): string | null {
if (node?.type !== "MemberExpression") return null;
const object = nodeOf(node.object);
@@ -96,6 +96,12 @@ const safeMath = Object.freeze(
}),
);
const formatLocaleDateTime = (value: string | number, locale = "en-US", timeZone?: string) => {
const options: Intl.DateTimeFormatOptions = { dateStyle: "medium", timeStyle: "short" };
if (timeZone) options.timeZone = timeZone;
return new Intl.DateTimeFormat(locale, options).format(new Date(value));
};
const safeDate = Object.freeze(
Object.assign(Object.create(null) as Record<string, unknown>, {
now: createSafeCallable(() => Date.now()),
@@ -109,6 +115,7 @@ const safeDate = Object.freeze(
toLocaleTimeString: createSafeCallable((value: string | number, locale?: string) =>
new Date(value).toLocaleTimeString(locale ?? "en-US"),
),
toLocaleString: createSafeCallable(formatLocaleDateTime),
getTime: createSafeCallable((value: string | number) => new Date(value).getTime()),
getYear: createSafeCallable((value: string | number) => new Date(value).getFullYear()),
getMonth: createSafeCallable((value: string | number) => new Date(value).getMonth()),
@@ -0,0 +1,32 @@
import type { ReactNode } from "react";
import { useEffect, useRef, useState } from "react";
import { Button } from "@mantine/core";
export function createCopyButton(labels: { copy: string; copied: string }) {
return function SafeCopyButton({ value }: { value?: string; children?: ReactNode }) {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
const copy = async () => {
if (!value) return;
try {
await navigator.clipboard.writeText(value);
setCopied(true);
clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), 2_000);
} catch {
setCopied(false);
}
};
return (
<Button
size="xs"
variant={copied ? "filled" : "light"}
color={copied ? "teal" : "blue"}
onClick={() => void copy()}
>
{copied ? labels.copied : labels.copy}
</Button>
);
};
}
@@ -17,6 +17,11 @@ export function getScopedCustomJsxControlName(scopeId: string, name: string) {
}
export function getInvalidCustomJsxPropValueReason(componentName: string, propName: string, value: unknown) {
if (propName === "resetKey" && value !== null) {
const scalar =
typeof value === "string" || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value));
if (!scalar) return "resetKey supports only a finite number, string, boolean, or null";
}
if (
["DateTimePicker", "InlineDateTimePicker"].includes(componentName) &&
propName === "type" &&
@@ -1,5 +1,5 @@
import type { ComponentType, ReactNode } from "react";
import { createContext, createElement, useContext, useEffect, useId, useRef, useState } from "react";
import { createContext, createElement, useContext, useEffect, useId, useRef } from "react";
import * as Core from "@mantine/core";
import * as Charts from "@mantine/charts";
import * as Dates from "@mantine/dates";
@@ -14,6 +14,7 @@ import { ActionButton, ToggleSwitch } from "../runtime/actions";
import { SubData } from "../runtime/data";
import { RefreshButton } from "../runtime/refresh-button";
import { SubFetch } from "../runtime/sub-fetch";
import { createCopyButton } from "./copy-button";
import { Collapsible, PaginatedList, StatBar, TabPanel, TabsContainer, TypeBadge } from "./interactive-components";
import { getScopedCustomJsxControlName, isSafeCustomJsxUrl } from "./runtime-component-policy";
import { sanitizeCustomJsxProps } from "./safe-properties";
@@ -41,6 +42,7 @@ interface CustomJsxInputsContextValue {
inputTypes: Record<string, WidgetInputType>;
registerInput(name: string, type: WidgetInputType, initialValue: WidgetInputValue): () => void;
setInputValue(name: string, type: WidgetInputType, value: WidgetInputValue): void;
resetInput(name: string, type: WidgetInputType): void;
}
const CustomJsxInputsContext = createContext<CustomJsxInputsContextValue | null>(null);
@@ -52,9 +54,10 @@ export function CustomJsxInputsProvider({
inputTypes,
registerInput,
setInputValue,
resetInput,
}: CustomJsxInputsContextValue & { children: ReactNode }) {
return (
<CustomJsxInputsContext.Provider value={{ scopeId, inputs, inputTypes, registerInput, setInputValue }}>
<CustomJsxInputsContext.Provider value={{ scopeId, inputs, inputTypes, registerInput, setInputValue, resetInput }}>
{children}
</CustomJsxInputsContext.Provider>
);
@@ -97,11 +100,13 @@ function useBoundProps(componentName: string, props: Record<string, unknown>): R
const detachedScopeId = useId();
const binding = typeof props.bind === "string" ? props.bind : undefined;
const context = useContext(CustomJsxInputsContext);
const serializedResetKey = serializeResetKey(props.resetKey);
const sanitized = sanitizeCustomJsxProps(props, componentName);
if (namedRadioComponents.has(componentName) && typeof sanitized.name === "string") {
sanitized.name = getScopedCustomJsxControlName(context?.scopeId ?? detachedScopeId, sanitized.name);
}
delete sanitized.bind;
delete sanitized.resetKey;
const inputType = getCustomJsxBindingType(componentName, sanitized);
const initialValue = getInitialInputValue(inputType, sanitized);
const serializedInitialValue = JSON.stringify(initialValue);
@@ -111,6 +116,15 @@ function useBoundProps(componentName: string, props: Record<string, unknown>): R
if (!isBound || !binding || !registerInput || !inputType || serializedInitialValue === undefined) return;
return registerInput(binding, inputType, JSON.parse(serializedInitialValue) as WidgetInputValue);
}, [binding, inputType, isBound, registerInput, serializedInitialValue]);
const previousResetKey = useRef<{ initialized: boolean; value?: string }>({ initialized: false });
const resetInput = context?.resetInput;
useEffect(() => {
const previous = previousResetKey.current;
previousResetKey.current = { initialized: true, value: serializedResetKey };
if (!previous.initialized || previous.value === serializedResetKey || serializedResetKey === undefined) return;
if (!isBound || !binding || !inputType || !resetInput) return;
resetInput(binding, inputType);
}, [binding, inputType, isBound, resetInput, serializedResetKey]);
if (!isBound || !binding || !context || !inputType) return sanitized;
delete sanitized.defaultValue;
delete sanitized.defaultChecked;
@@ -140,6 +154,14 @@ function useBoundProps(componentName: string, props: Record<string, unknown>): R
return { ...sanitized, value: currentValue, onChange: update };
}
function serializeResetKey(value: unknown) {
if (value === null) return "null";
if (typeof value === "number") return Number.isFinite(value) ? `number:${value}` : undefined;
if (typeof value === "string") return `string:${value}`;
if (typeof value === "boolean") return `boolean:${value}`;
return undefined;
}
function getInitialInputValue(type: WidgetInputType | null, props: Record<string, unknown>): WidgetInputValue {
if (!type) return "";
const candidate = type === "boolean" ? props.defaultChecked : props.defaultValue;
@@ -197,35 +219,6 @@ function SafeLink({ component, props }: { component: ComponentType<never>; props
);
}
function createCopyButton(labels: { copy: string; copied: string }) {
return function SafeCopyButton({ value }: { value?: string; children?: ReactNode }) {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => () => clearTimeout(timer.current), []);
const copy = async () => {
if (!value) return;
try {
await navigator.clipboard.writeText(value);
setCopied(true);
clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), 2_000);
} catch {
setCopied(false);
}
};
return (
<Core.Button
size="xs"
variant={copied ? "filled" : "light"}
color={copied ? "teal" : "blue"}
onClick={() => void copy()}
>
{copied ? labels.copied : labels.copy}
</Core.Button>
);
};
}
export interface CustomJsxComponentAdapters {
TablerIcon: ComponentType<never>;
copyLabels: { copy: string; copied: string };