fix custom widget review findings

This commit is contained in:
ajnart committed 2026-08-14 10:35:21 +02:00
1 parent 0482c040ec
commit afa54755fd
17 files changed
+207 -26

No files matched your search

@@ -8,12 +8,20 @@ import {
recordPreviewJournal,
resolvePreviewRequestParams,
} from "./preview-procedure-helpers";
import { executeCustomWidgetRequest } from "./request-executor";
import { executeCustomWidgetRequest, invalidateCustomWidgetResponseCache } from "./request-executor";
import { hashRuntimeParams, renderRequestBody, renderRequestTarget } from "./request-manifest";
import { acquireCustomWidgetRequestLimit } from "./request-limits";
import { getPreviewJournal, getPreviewSession, setPreviewSessionLiveActions } from "./preview-sessions";
export const previewQueryProcedures = {
previewRefresh: permissionRequiredProcedure
.requiresPermission("admin")
.input(z.object({ sessionId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
const session = await getPreviewSession(input.sessionId, ctx.session.user.id);
invalidateCustomWidgetResponseCache([`custom-jsx:preview:${session.id}:`]);
}),
previewQuery: permissionRequiredProcedure
.requiresPermission("admin")
.meta({
@@ -10,11 +10,12 @@ import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
const mocks = vi.hoisted(() => ({
executeRequest: vi.fn(async () => ({ ok: true, status: 200, statusText: "OK", data: { value: 42 } })),
invalidateResponseCache: vi.fn(),
}));
vi.mock("../../custom-widget/request-executor", () => ({
executeCustomWidgetRequest: mocks.executeRequest,
invalidateCustomWidgetResponseCache: vi.fn(),
invalidateCustomWidgetResponseCache: mocks.invalidateResponseCache,
}));
vi.mock("../../custom-widget/request-limits", () => ({
@@ -111,7 +112,21 @@ async function setup(
}
describe("Custom JSX v2 board router", () => {
beforeEach(() => mocks.executeRequest.mockClear());
beforeEach(() => {
mocks.executeRequest.mockClear();
mocks.invalidateResponseCache.mockClear();
});
test("refreshes the server response cache for a placed widget", async () => {
const { db, itemId } = await setup();
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
await caller.refresh({ itemId });
expect(mocks.invalidateResponseCache).toHaveBeenCalledWith([
expect.stringMatching(new RegExp(`^custom-jsx:${itemId}:\\d+:$`, "u")),
]);
});
test("loads placed widgets and public queries for anonymous visitors on public boards", async () => {
const { db, itemId } = await setup();
@@ -195,6 +195,13 @@ const executeRequest = async (
};
export const customApiRouter = createTRPCRouter({
refresh: publicProcedure.input(itemInputSchema).mutation(async ({ ctx, input }) => {
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
invalidateCustomWidgetResponseCache([
`custom-jsx:${resolved.item.id}:${getCustomWidgetCacheVersion(resolved.stored)}:`,
]);
}),
getData: publicProcedure.input(itemInputSchema).query(async ({ ctx, input }) => {
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
const loadRequests = Object.entries(resolved.definition.requests).filter(
@@ -53,8 +53,10 @@ export function SubFetch(props: SubFetchProps) {
(props.trigger !== "manual" || manualRun),
);
const refreshMs = normalizeRefreshInterval(props.refreshInterval);
const scope = itemId ? "item" : "preview";
const scopeId = itemId ?? previewSessionId;
const query = useQuery({
queryKey: ["custom-widget", itemId ?? previewSessionId, props.requestId, paramsKey],
queryKey: ["custom-widget", scope, scopeId, props.requestId, paramsKey],
queryFn: ({ signal }) =>
port.query({ itemId, previewSessionId, requestId: props.requestId ?? "", params: params ?? {} }, signal),
enabled,
@@ -10,8 +10,28 @@ describe("Workshop navigation translations", () => {
const messages = JSON.parse(await readFile(resolve(languageDirectory, "en.json"), "utf8")) as {
management?: { navbar?: { items?: { workshop?: unknown } } };
navigationStructure?: { manage?: { workshop?: { label?: unknown } } };
workshop?: Record<string, unknown>;
};
expect(messages.management?.navbar?.items?.workshop).toBe("Workshop");
expect(messages.navigationStructure?.manage?.workshop?.label).toBe("Workshop");
expect(messages.workshop).toMatchObject({
communityMember: "Community member",
outdated: "Outdated",
reportCount: expect.any(String),
reportWarning: expect.any(String),
reportVisibility: expect.any(String),
screenshotAlt: expect.any(String),
upvote: expect.any(String),
downvote: expect.any(String),
reportCategory: expect.objectContaining({
outdated: expect.any(String),
malicious: expect.any(String),
spam: expect.any(String),
copyright: expect.any(String),
inappropriate: expect.any(String),
other: expect.any(String),
}),
publish: expect.objectContaining({ invalidScreenshot: expect.any(String) }),
});
});
});
+18
View File
@@ -1151,6 +1151,15 @@
"emptyCss": "No CSS themes match this search.",
"noDescription": "No description",
"author": "by {name}",
"communityMember": "Community member",
"outdated": "Outdated",
"outdatedWarning": "The author marked this submission as outdated. Review it carefully before importing.",
"reportCount": "{count, plural, one {# report} other {# reports}}",
"reportWarning": "{count, plural, one {This submission has # open community report.} other {This submission has # open community reports.}} It remains installable, but you should review its content first.",
"reportVisibility": "Report details are visible only to this submission's author and Workshop admins.",
"screenshotAlt": "{title} screenshot {count, number}",
"upvote": "Upvote, {count, plural, one {# vote} other {# votes}}",
"downvote": "Downvote, {count, plural, one {# vote} other {# votes}}",
"inspectCss": "Inspect CSS",
"sourceCode": "Workshop entry",
"loadError": "This submission could not be loaded.",
@@ -1172,6 +1181,14 @@
"reportSend": "Send report",
"reportSent": "Report sent",
"reportSentDescription": "Workshop moderators can now review this submission.",
"reportCategory": {
"outdated": "Outdated or no longer working",
"malicious": "Malicious",
"spam": "Spam",
"copyright": "Copyright",
"inappropriate": "Inappropriate",
"other": "Other"
},
"voteError": "The vote could not be saved.",
"publish": {
"title": "Publish to Workshop",
@@ -1181,6 +1198,7 @@
"descriptionField": "Description",
"screenshots": "Screenshots",
"screenshotsDescription": "Up to five PNG, JPEG, or WebP images",
"invalidScreenshot": "Use PNG, JPEG, or WebP images no larger than 5 MB each.",
"privateSourceWarning": "This widget contains private source URLs for: {sources}. Replace personal hosts or IP addresses with safe service placeholders before publishing.",
"privateSourceConfirmation": "I reviewed these source URLs and they do not expose private infrastructure details",
"action": "Publish now",
@@ -107,26 +107,42 @@ export function WidgetDefinitionProvider(props: WidgetDefinitionProviderProps) {
confirmed: input.confirmed,
}),
invalidate: async ({ itemId, previewSessionId, targets }) => {
const invalidateAll = targets.includes("*");
if (previewSessionId) {
if (invalidateAll) {
await fetchApi.customWidget.previewRefresh.mutate({ sessionId: previewSessionId });
}
await queryClient.invalidateQueries({
predicate: (query) => {
const key = query.queryKey;
return key[0] === "custom-widget" && key[1] === previewSessionId && targets.includes(String(key[2]));
return (
key[0] === "custom-widget" &&
key[1] === "preview" &&
key[2] === previewSessionId &&
(invalidateAll || targets.includes(String(key[3])))
);
},
});
return;
}
if (!itemId) return;
if (targets.length === 0) return;
if (invalidateAll) await fetchApi.widget.customApi.refresh.mutate({ itemId });
const tasks: Promise<unknown>[] = [
queryClient.invalidateQueries({
predicate: (query) => {
const key = query.queryKey;
return key[0] === "custom-widget" && key[1] === itemId && targets.includes(String(key[2]));
return (
key[0] === "custom-widget" &&
key[1] === "item" &&
key[2] === itemId &&
(invalidateAll || targets.includes(String(key[3])))
);
},
}),
];
if (
invalidateAll ||
(props.requestCapabilities ?? []).some((request) => request.trigger === "load" && targets.includes(request.id))
) {
tasks.push(utils.widget.customApi.getData.invalidate({ itemId }));