Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

fix: preserve local styles and improve issue diagnostics (#6408)

Oleg Isonen60c549c46f92
diff --git a/apps/builder/app/services/github-issue-report.server.test.ts b/apps/builder/app/services/github-issue-report.server.test.ts
index 64d6d73568..c3780111eb 100644
--- a/apps/builder/app/services/github-issue-report.server.test.ts
+++ b/apps/builder/app/services/github-issue-report.server.test.ts
@@ -30,6 +30,8 @@ const report: IssueReportInput = {
recentFailure: {
tool: "preview.start",
code: "PROJECT_BUNDLE_INVALID",
+ httpStatus: 504,
+ elapsedMs: 17_000,
issues: [
{
path: ["assets", "0", "type"],
@@ -38,6 +40,16 @@ const report: IssueReportInput = {
},
],
},
+ session: {
+ staleNamespaces: ["styles"],
+ missingNamespaces: ["instances"],
+ invalidatedNamespaces: [],
+ },
+ preview: {
+ stale: true,
+ hasRenderedVersion: true,
+ renderedVersionMatchesSession: false,
+ },
},
report: {
userStory:
@@ -71,6 +83,10 @@ describe("GitHub issue reports", () => {
expect(body).toContain("## Captured failure diagnostics");
expect(body).toContain("- Tool: `preview.start`");
expect(body).toContain("- Error code: `PROJECT_BUNDLE_INVALID`");
+ expect(body).toContain("- HTTP status: `504`");
+ expect(body).toContain("- Duration: `17000ms`");
+ expect(body).toContain("stale=styles");
+ expect(body).toContain("version matches session=false");
expect(body).toContain(
'- `assets.0.type`: `invalid_value` (one of "font"|"image"|"video"|"file")'
);
diff --git a/apps/builder/app/services/github-issue-report.server.ts b/apps/builder/app/services/github-issue-report.server.ts
index 1744433444..ccd2c90946 100644
--- a/apps/builder/app/services/github-issue-report.server.ts
+++ b/apps/builder/app/services/github-issue-report.server.ts
@@ -37,6 +37,16 @@ const formatRuntime = (runtime: IssueReportInput["runtime"]) =>
`- API contract: ${runtime.apiContractVersion}`,
`- Bundle contract: ${runtime.bundleVersion ?? "unknown"}`,
]),
+ ...(runtime?.session === undefined
+ ? []
+ : [
+ `- Session namespace issues: stale=${runtime.session.staleNamespaces.join(",") || "none"}; missing=${runtime.session.missingNamespaces.join(",") || "none"}; invalidated=${runtime.session.invalidatedNamespaces.join(",") || "none"}`,
+ ]),
+ ...(runtime?.preview === undefined
+ ? []
+ : [
+ `- Preview: stale=${runtime.preview.stale}; rendered=${runtime.preview.hasRenderedVersion}; version matches session=${runtime.preview.renderedVersionMatchesSession ?? "unknown"}`,
+ ]),
].join("\n");
const formatFailureDiagnostics = (runtime: IssueReportInput["runtime"]) => {
@@ -50,6 +60,12 @@ const formatFailureDiagnostics = (runtime: IssueReportInput["runtime"]) => {
"",
`- Tool: \`${failure.tool}\``,
`- Error code: \`${failure.code}\``,
+ ...(failure.httpStatus === undefined
+ ? []
+ : [`- HTTP status: \`${failure.httpStatus}\``]),
+ ...(failure.elapsedMs === undefined
+ ? []
+ : [`- Duration: \`${failure.elapsedMs}ms\``]),
...(issues.length === 0
? []
: [
diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.ts
index 52ceaff935..4bf4e4d873 100644
--- a/packages/cli/src/commands/mcp.ts
+++ b/packages/cli/src/commands/mcp.ts
@@ -19,6 +19,10 @@ import {
getProjectBasicAuthCredentials,
type BuilderNamespace,
} from "@webstudio-is/project-build/contracts";
+import {
+ getBuilderStateNamespacesByStatus,
+ type BuilderStateNamespaceStatus,
+} from "@webstudio-is/project-build/state";
import { diffPngFiles } from "@webstudio-is/vision/diff";
import {
publicApiOperationRequiresServerSupport,
@@ -1860,7 +1864,37 @@ const createCliMcpHost = async ({
connection: apiConnection,
projectRoot,
sessionProjectId: projectId,
- issueReportRuntime: () => createIssueReportRuntime(recentFailure),
+ issueReportRuntime: () => {
+ const snapshot = session.snapshot;
+ const previewStatus = previewFreshness.status();
+ const renderedProjectVersion = previewStatus.renderedProjectVersion;
+ const namespacesByStatus =
+ snapshot === undefined
+ ? undefined
+ : (status: BuilderStateNamespaceStatus) =>
+ getBuilderStateNamespacesByStatus(snapshot.freshness, status);
+ return createIssueReportRuntime(recentFailure, {
+ ...(namespacesByStatus === undefined
+ ? {}
+ : {
+ session: {
+ staleNamespaces: namespacesByStatus("stale"),
+ missingNamespaces: namespacesByStatus("missing"),
+ invalidatedNamespaces: namespacesByStatus("invalidated"),
+ },
+ }),
+ preview: {
+ stale: previewStatus.stale,
+ hasRenderedVersion: renderedProjectVersion !== undefined,
+ ...(renderedProjectVersion === undefined || snapshot === undefined
+ ? {}
+ : {
+ renderedVersionMatchesSession:
+ renderedProjectVersion === snapshot.version,
+ }),
+ },
+ });
+ },
});
const restorePointStorage = createCliProjectRestorePointStorage(
getCliProjectRestorePointsFile(projectRoot, projectId)
@@ -2147,8 +2181,23 @@ const createCliMcpHost = async ({
host,
apiContract,
toolCount: operations.length,
- recordToolFailure(canonicalTool: string, error: unknown) {
- recentFailure = createIssueReportFailure(canonicalTool, error);
+ recordToolFailure(
+ canonicalTool: string,
+ error: unknown,
+ elapsedMs: number
+ ) {
+ if (canonicalTool !== "report-issue") {
+ recentFailure = createIssueReportFailure(
+ canonicalTool,
+ error,
+ elapsedMs
+ );
+ }
+ },
+ recordToolSuccess(canonicalTool: string) {
+ if (canonicalTool !== "report-issue") {
+ recentFailure = undefined;
+ }
},
reportLog(message: string) {
if (message.startsWith("ready with ")) {
@@ -2732,6 +2781,7 @@ export const mcp = async (
toolCount,
reportLog,
recordToolFailure,
+ recordToolSuccess,
apiContract,
dispose,
} = await createCliMcpHost({
@@ -2750,6 +2800,7 @@ export const mcp = async (
toolNameFormat: options.toolNameFormat,
getErrorCode: getStableErrorCode,
onToolFailure: recordToolFailure,
+ onToolSuccess: recordToolSuccess,
reportLog: (_level, message) => {
reportLog(message);
},
diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.ts
index 462b1b6121..f89ac4c7f6 100644
--- a/packages/cli/src/project-session.test.ts
+++ b/packages/cli/src/project-session.test.ts
@@ -45,11 +45,11 @@ test("adds anonymous local runtime metadata only to issue reports", () => {
},
};
- expect(addIssueReportRuntime("report-issue", report, runtime)).toEqual({
+ expect(addIssueReportRuntime("report-issue", report, () => runtime)).toEqual({
...report,
runtime,
});
- expect(addIssueReportRuntime("audit", report, runtime)).toBe(report);
+ expect(addIssueReportRuntime("audit", report, () => runtime)).toBe(report);
});
test("keeps only anonymous structured fields from the latest tool failure", () => {
@@ -71,7 +71,7 @@ test("keeps only anonymous structured fields from the latest tool failure", () =
code: "PROJECT_BUNDLE_INVALID",
issues: [
{
- path: [],
+ path: ["assets", "0"],
code: "invalid_value",
constraint: "one of supported asset types",
},
@@ -106,13 +106,27 @@ test("keeps only anonymous structured fields from the latest tool failure", () =
code: "INVALID_INPUT",
issues: [
{
- path: [],
+ path: ["fragment"],
code: "invalid_webstudio_jsx",
constraint: "valid_webstudio_jsx_syntax",
},
],
});
+ expect(
+ createIssueReportFailure("select-instance", {
+ code: "INVALID_INPUT",
+ issues: [
+ {
+ path: ["instanceId"],
+ code: "invalid_type",
+ message: "Expected string",
+ constraint: "type:string",
+ },
+ ],
+ }).issues?.[0].path
+ ).toEqual(["instanceId"]);
+
const sensitiveKey = "customer-secret-key";
const serialized = JSON.stringify(
createIssueReportFailure("update-styles", {
@@ -128,7 +142,48 @@ test("keeps only anonymous structured fields from the latest tool failure", () =
})
);
expect(serialized).not.toContain(sensitiveKey);
- expect(JSON.parse(serialized).issues[0].path).toEqual([]);
+ expect(JSON.parse(serialized).issues[0].path).toEqual(["updates", "0"]);
+
+ const rootSecret = JSON.stringify(
+ createIssueReportFailure("update-styles", {
+ code: "INVALID_INPUT",
+ issues: [
+ { path: [sensitiveKey], code: "unrecognized", constraint: "known key" },
+ ],
+ })
+ );
+ expect(rootSecret).not.toContain(sensitiveKey);
+
+ expect(
+ createIssueReportFailure("update-styles", {
+ code: "INVALID_INPUT",
+ issues: [
+ {
+ path: [sensitiveKey, "0"],
+ code: "invalid_type",
+ message: "Expected string",
+ constraint: "type:string",
+ },
+ ],
+ }).issues?.[0].path
+ ).toEqual([]);
+});
+
+test("captures failure timing and HTTP status", () => {
+ expect(
+ createIssueReportFailure(
+ "preview-asset-query",
+ new Error("Request failed", {
+ cause: Object.assign(new Error("Gateway timeout"), { status: 504 }),
+ }),
+ 17_000
+ )
+ ).toEqual({
+ tool: "preview-asset-query",
+ code: "MCP_TOOL_FAILED",
+ httpStatus: 504,
+ elapsedMs: 17_000,
+ });
});
test("scopes project session files for explicitly selected projects", () => {
@@ -982,6 +1037,9 @@ describe("cli project session transport", () => {
test("keeps configured project id for default server operation transport", async () => {
let requestBody = "";
let requestUrl = "";
+ const issueReportRuntime = vi.fn(() => {
+ throw new Error("issue report runtime should be lazy");
+ });
const fetch = vi.fn(async (request: URL | RequestInfo) => {
if (request instanceof Request) {
requestUrl = request.url;
@@ -1011,6 +1069,7 @@ describe("cli project session transport", () => {
origin: "https://example.com",
authToken: "token",
},
+ issueReportRuntime,
});
await transport.executeServerOperation?.({
@@ -1021,6 +1080,7 @@ describe("cli project session transport", () => {
const requestText = `${requestUrl}\n${requestBody}`;
expect(requestText).toContain("project-1");
expect(requestText).not.toContain("other-project");
+ expect(issueReportRuntime).not.toHaveBeenCalled();
});
test("adds anonymous runtime metadata to issue report requests", async () => {
diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.ts
index 1f7a2abb35..03e930e315 100644
--- a/packages/cli/src/project-session.ts
+++ b/packages/cli/src/project-session.ts
@@ -187,6 +187,11 @@ export const getCliProjectRestorePointsFile = (
"restore-points.json"
);
const compatibilityVersion = "cli-project-session-v1";
+const issueReportPathRoots = new Set([
+ ...builderNamespaces,
+ ...publicApiOperations.flatMap((operation) => operation.inputFields),
+ "input",
+]);
const createCliProjectSessionCompatibility = (
connection: ApiConnection
@@ -243,7 +248,8 @@ const publicOperationById = new Map(
);
export const createIssueReportRuntime = (
- recentFailure?: IssueReportRecentFailure
+ recentFailure?: IssueReportRecentFailure,
+ diagnostics?: Pick<IssueReportRuntime, "session" | "preview">
): IssueReportRuntime => ({
cliVersion: packageJson.version,
nodeVersion: process.versions.node,
@@ -254,26 +260,44 @@ export const createIssueReportRuntime = (
apiContractVersion: publicApiContractVersion,
bundleVersion,
recentFailure,
+ ...diagnostics,
});
export const createIssueReportFailure = (
canonicalTool: string,
- error: unknown
+ error: unknown,
+ elapsedMs?: number
): IssueReportRecentFailure => {
const errorCode = getStableErrorCode(error);
+ const httpStatus = httpClient.getErrorStatus(error);
const issues =
errorCode === undefined
? undefined
: getValidationIssues(error)
?.slice(0, 30)
.map((issue) => ({
- path: [],
+ // Keep only a known namespace/input field and array index. Leaf
+ // keys may contain project data, while this prefix is enough to
+ // locate the failing input shape (for example `updates[0]`).
+ path: issueReportPathRoots.has(issue.path[0] ?? "")
+ ? [
+ issue.path[0],
+ ...(/^\d+$/.test(issue.path[1] ?? "") ? [issue.path[1]] : []),
+ ]
+ : [],
code: issue.code,
constraint: issue.constraint,
}));
return {
tool: canonicalTool,
code: errorCode ?? "MCP_TOOL_FAILED",
+ ...(typeof httpStatus === "number" &&
+ Number.isInteger(httpStatus) &&
+ httpStatus >= 100 &&
+ httpStatus <= 599
+ ? { httpStatus }
+ : {}),
+ ...(elapsedMs === undefined ? {} : { elapsedMs }),
...(issues === undefined || issues.length === 0 ? {} : { issues }),
};
};
@@ -281,12 +305,12 @@ export const createIssueReportFailure = (
export const addIssueReportRuntime = (
command: PublicApiCommand,
input: unknown,
- runtime: IssueReportRuntime = createIssueReportRuntime()
+ getRuntime: () => IssueReportRuntime = createIssueReportRuntime
) => {
if (command !== "report-issue" || isPlainRecord(input) === false) {
return input;
}
- return { ...input, runtime };
+ return { ...input, runtime: getRuntime() };
};
const executePublicServerOperation = async ({
@@ -317,7 +341,7 @@ const executePublicServerOperation = async ({
...(addIssueReportRuntime(
operation.command,
input,
- issueReportRuntime?.() ?? createIssueReportRuntime()
+ issueReportRuntime
) as Record<string, unknown>),
projectId: connection.projectId,
});
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index 6bafd5572a..c164552750 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -53,6 +53,7 @@ import {
getPublishJob,
getApiCompatibilityMessage,
getApiErrorCode,
+ getErrorStatus,
getBuildSnapshot,
getPage,
getPageByPath,
@@ -198,17 +199,7 @@ test("reports non-json api responses", async () => {
});
} catch (error) {
message = error instanceof Error ? error.message : String(error);
- status =
- typeof error === "object" && error !== null && "status" in error
- ? error.status
- : typeof error === "object" &&
- error !== null &&
- "cause" in error &&
- typeof error.cause === "object" &&
- error.cause !== null &&
- "status" in error.cause
- ? error.cause.status
- : undefined;
+ status = getErrorStatus(error);
}
expect(status).toBe(413);
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index d7b74063f4..0abbdf2d9b 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -386,13 +386,27 @@ const encodeAssetDescriptionHeader = (value: string) =>
const formatError = (error: unknown) =>
error instanceof Error ? error.message : String(error);
-const getErrorStatus = (error: unknown) =>
- typeof error === "object" &&
- error !== null &&
- "status" in error &&
- typeof error.status === "number"
- ? error.status
- : undefined;
+export const getErrorStatus = (error: unknown) => {
+ const visited = new Set<unknown>();
+ let current = error;
+ while (
+ typeof current === "object" &&
+ current !== null &&
+ visited.has(current) === false
+ ) {
+ visited.add(current);
+ const record = current as Record<string, unknown>;
+ const data =
+ typeof record.data === "object" && record.data !== null
+ ? (record.data as Record<string, unknown>)
+ : undefined;
+ const status = record.status ?? data?.status;
+ if (typeof status === "number") {
+ return status;
+ }
+ current = record.cause ?? data?.cause;
+ }
+};
const retryOnce = async <Result>(task: () => Promise<Result>, delayMs = 0) => {
try {
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index f6b895450f..8229615243 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -8366,6 +8366,7 @@ describe("project session mcp adapter", () => {
});
test("sends sparse protocol-native tool lifecycle logging", async () => {
+ const onToolSuccess = vi.fn();
const server = await createProjectSessionMcpServer({
operations: publicMcpOperations,
createProjectSession: createSessionFactory(),
@@ -8375,6 +8376,7 @@ describe("project session mcp adapter", () => {
result: [{ id: "home" }],
})
),
+ onToolSuccess,
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
@@ -8411,6 +8413,7 @@ describe("project session mcp adapter", () => {
},
])
);
+ expect(onToolSuccess).toHaveBeenCalledWith("list-pages");
} finally {
await client.close();
await server.close();
@@ -8830,7 +8833,11 @@ describe("project session mcp adapter", () => {
},
})
);
- expect(onToolFailure).toHaveBeenCalledWith("list-pages", error);
+ expect(onToolFailure).toHaveBeenCalledWith(
+ "list-pages",
+ error,
+ expect.any(Number)
+ );
await client.callTool({
name: "customer/project",
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 5cd575b16e..5bd7267558 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -9214,13 +9214,19 @@ export const createProjectSessionMcpServer = async <
toolNameFormat = "canonical",
toolHeartbeatIntervalMs = 10_000,
onToolFailure,
+ onToolSuccess,
}: Omit<ProjectSessionMcpCoreOptions<Command>, "reportToolProgress"> & {
getErrorCode?: McpErrorCodeResolver;
reportLog?: (level: McpLogLevel, message: string) => void;
onInitialized?: (clientName: string | undefined) => void;
toolNameFormat?: "canonical" | "underscores";
toolHeartbeatIntervalMs?: number;
- onToolFailure?: (canonicalTool: string, error: unknown) => void;
+ onToolFailure?: (
+ canonicalTool: string,
+ error: unknown,
+ elapsedMs: number
+ ) => void;
+ onToolSuccess?: (canonicalTool: string) => void;
}) => {
const server = new Server(
{ name: "webstudio", version: "0.0.0" },
@@ -9357,13 +9363,16 @@ export const createProjectSessionMcpServer = async <
dryRun,
signal: extra.signal,
});
- sendLog("info", `tool ${name} succeeded in ${Date.now() - startedAt}ms`);
+ const elapsedMs = Date.now() - startedAt;
+ onToolSuccess?.(canonicalName ?? "unknown");
+ sendLog("info", `tool ${name} succeeded in ${elapsedMs}ms`);
return result;
} catch (error) {
- onToolFailure?.(canonicalName ?? "unknown", error);
+ const elapsedMs = Date.now() - startedAt;
+ onToolFailure?.(canonicalName ?? "unknown", error, elapsedMs);
sendLog(
"error",
- `tool ${name} failed in ${Date.now() - startedAt}ms: ${
+ `tool ${name} failed in ${elapsedMs}ms: ${
error instanceof Error ? error.message : String(error)
}`
);
diff --git a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
index 40551f8215..41c4240e73 100644
--- a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
+++ b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts
@@ -206,6 +206,16 @@ export const serverOnlyRouterOperationMetadata = {
minLength: 1,
maxLength: 160,
},
+ httpStatus: {
+ type: "integer",
+ minimum: 100,
+ maximum: 599,
+ },
+ elapsedMs: {
+ type: "integer",
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
issues: {
maxItems: 30,
type: "array",
@@ -239,6 +249,57 @@ export const serverOnlyRouterOperationMetadata = {
required: ["tool", "code"],
additionalProperties: false,
},
+ session: {
+ type: "object",
+ properties: {
+ staleNamespaces: {
+ maxItems: 50,
+ type: "array",
+ items: {
+ type: "string",
+ maxLength: 100,
+ },
+ },
+ missingNamespaces: {
+ maxItems: 50,
+ type: "array",
+ items: {
+ type: "string",
+ maxLength: 100,
+ },
+ },
+ invalidatedNamespaces: {
+ maxItems: 50,
+ type: "array",
+ items: {
+ type: "string",
+ maxLength: 100,
+ },
+ },
+ },
+ required: [
+ "staleNamespaces",
+ "missingNamespaces",
+ "invalidatedNamespaces",
+ ],
+ additionalProperties: false,
+ },
+ preview: {
+ type: "object",
+ properties: {
+ stale: {
+ type: "boolean",
+ },
+ hasRenderedVersion: {
+ type: "boolean",
+ },
+ renderedVersionMatchesSession: {
+ type: "boolean",
+ },
+ },
+ required: ["stale", "hasRenderedVersion"],
+ additionalProperties: false,
+ },
},
required: [
"cliVersion",
diff --git a/packages/protocol/src/issue-report.ts b/packages/protocol/src/issue-report.ts
index 305e0c5a60..76446f999b 100644
--- a/packages/protocol/src/issue-report.ts
+++ b/packages/protocol/src/issue-report.ts
@@ -50,10 +50,28 @@ const issueReportRecentFailure = z
.object({
tool: z.string().trim().min(1).max(160),
code: z.string().trim().min(1).max(160),
+ httpStatus: z.number().int().min(100).max(599).optional(),
+ elapsedMs: z.number().int().nonnegative().optional(),
issues: z.array(issueReportFailureIssue).max(30).optional(),
})
.strict();
+const issueReportSession = z
+ .object({
+ staleNamespaces: z.array(z.string().max(100)).max(50),
+ missingNamespaces: z.array(z.string().max(100)).max(50),
+ invalidatedNamespaces: z.array(z.string().max(100)).max(50),
+ })
+ .strict();
+
+const issueReportPreview = z
+ .object({
+ stale: z.boolean(),
+ hasRenderedVersion: z.boolean(),
+ renderedVersionMatchesSession: z.boolean().optional(),
+ })
+ .strict();
+
const issueReportRuntime = z
.object({
cliVersion: z.string().trim().min(1).max(100),
@@ -65,6 +83,8 @@ const issueReportRuntime = z
apiContractVersion: z.string().trim().min(1).max(100),
bundleVersion: z.string().trim().min(1).max(100).optional(),
recentFailure: issueReportRecentFailure.optional(),
+ session: issueReportSession.optional(),
+ preview: issueReportPreview.optional(),
})
.strict()
.describe(
diff --git a/packages/template/src/jsx.test.tsx b/packages/template/src/jsx.test.tsx
index faebe0d929..7987c512b4 100644
--- a/packages/template/src/jsx.test.tsx
+++ b/packages/template/src/jsx.test.tsx
@@ -768,9 +768,9 @@ test("combine local styles with tokens", () => {
{ id: "body:ws:style", type: "local" },
{ id: "0", type: "token", name: "primary" },
]);
- // Selection should have both local style source and token
+ // Tokens provide defaults and local styles override them.
expect(styleSourceSelections).toEqual([
- { instanceId: "body", values: ["body:ws:style", "0"] },
+ { instanceId: "body", values: ["0", "body:ws:style"] },
]);
expect(styles).toHaveLength(2);
});
diff --git a/packages/template/src/jsx.ts b/packages/template/src/jsx.ts
index 5356e4bce4..2ace34bc76 100644
--- a/packages/template/src/jsx.ts
+++ b/packages/template/src/jsx.ts
@@ -885,7 +885,8 @@ export const renderTemplate = (
(sel) => sel.instanceId === instanceId
);
if (existingSelection) {
- existingSelection.values.push(...tokenIds);
+ // Tokens provide defaults; instance-local styles must win in the cascade.
+ existingSelection.values.unshift(...tokenIds);
} else {
styleSourceSelections.push({
instanceId,