From fde375ecf2d62109eeca42ee00f952b38438da0f Mon Sep 17 00:00:00 2001 From: Aden Linday Date: Sun, 30 Aug 2026 21:17:24 +0930 Subject: [PATCH] feat: add AI Mod Creator with OpenRouter generation and safe mod runtime Introduce a dev-only floating creator for generating and managing local page mods, including background key handling, recipe validation, and sidebar navigation fixes. Co-authored-by: Cursor --- package.json | 1 + src/background.ts | 12 + src/background/aiModCreator.test.ts | 292 ++++ src/background/aiModCreator.ts | 738 ++++++++++ src/background/aiModUserScripts.test.ts | 33 + src/background/aiModUserScripts.ts | 290 ++++ src/css/injected.scss | 5 + src/manifests/manifest.json | 2 +- .../aiModCreator/CreatorTabNav.svelte | 104 ++ .../aiModCreator/FloatingModCreator.svelte | 1263 +++++++++++++++++ .../aiModCreator/GeneratingView.svelte | 326 +++++ .../aiModCreator/LoadingSkinFrame.svelte | 42 + .../aiModCreator/LoadingSpinnerMini.svelte | 74 + .../aiModCreator/ModCreatorIcon.svelte | 32 + .../aiModCreator/advancedModRuntime.test.ts | 81 ++ .../aiModCreator/advancedModRuntime.ts | 210 +++ src/plugins/built-in/aiModCreator/index.ts | 173 +++ src/plugins/built-in/aiModCreator/logger.ts | 34 + .../built-in/aiModCreator/modRuntime.test.ts | 200 +++ .../built-in/aiModCreator/modRuntime.ts | 228 +++ .../built-in/aiModCreator/modStyle.test.ts | 23 + src/plugins/built-in/aiModCreator/modStyle.ts | 37 + src/plugins/built-in/aiModCreator/models.ts | 61 + .../built-in/aiModCreator/pageContext.test.ts | 234 +++ .../built-in/aiModCreator/pageContext.ts | 291 ++++ src/plugins/built-in/aiModCreator/prompt.ts | 175 +++ .../aiModCreator/recipeSchema.test.ts | 267 ++++ .../built-in/aiModCreator/recipeSchema.ts | 666 +++++++++ .../aiModCreator/scriptSafety.test.ts | 43 + .../built-in/aiModCreator/scriptSafety.ts | 100 ++ .../built-in/aiModCreator/selection.test.ts | 69 + .../built-in/aiModCreator/selection.ts | 185 +++ src/plugins/built-in/aiModCreator/services.ts | 181 +++ .../built-in/aiModCreator/storage.test.ts | 69 + src/plugins/built-in/aiModCreator/storage.ts | 68 + src/plugins/built-in/aiModCreator/types.ts | 246 ++++ src/plugins/index.ts | 2 + src/seqta/ui/sidebar/mountCustomSidebar.ts | 5 +- src/seqta/ui/sidebar/sidebarState.svelte.ts | 12 +- 39 files changed, 6870 insertions(+), 4 deletions(-) create mode 100644 src/background/aiModCreator.test.ts create mode 100644 src/background/aiModCreator.ts create mode 100644 src/background/aiModUserScripts.test.ts create mode 100644 src/background/aiModUserScripts.ts create mode 100644 src/plugins/built-in/aiModCreator/CreatorTabNav.svelte create mode 100644 src/plugins/built-in/aiModCreator/FloatingModCreator.svelte create mode 100644 src/plugins/built-in/aiModCreator/GeneratingView.svelte create mode 100644 src/plugins/built-in/aiModCreator/LoadingSkinFrame.svelte create mode 100644 src/plugins/built-in/aiModCreator/LoadingSpinnerMini.svelte create mode 100644 src/plugins/built-in/aiModCreator/ModCreatorIcon.svelte create mode 100644 src/plugins/built-in/aiModCreator/advancedModRuntime.test.ts create mode 100644 src/plugins/built-in/aiModCreator/advancedModRuntime.ts create mode 100644 src/plugins/built-in/aiModCreator/index.ts create mode 100644 src/plugins/built-in/aiModCreator/logger.ts create mode 100644 src/plugins/built-in/aiModCreator/modRuntime.test.ts create mode 100644 src/plugins/built-in/aiModCreator/modRuntime.ts create mode 100644 src/plugins/built-in/aiModCreator/modStyle.test.ts create mode 100644 src/plugins/built-in/aiModCreator/modStyle.ts create mode 100644 src/plugins/built-in/aiModCreator/models.ts create mode 100644 src/plugins/built-in/aiModCreator/pageContext.test.ts create mode 100644 src/plugins/built-in/aiModCreator/pageContext.ts create mode 100644 src/plugins/built-in/aiModCreator/prompt.ts create mode 100644 src/plugins/built-in/aiModCreator/recipeSchema.test.ts create mode 100644 src/plugins/built-in/aiModCreator/recipeSchema.ts create mode 100644 src/plugins/built-in/aiModCreator/scriptSafety.test.ts create mode 100644 src/plugins/built-in/aiModCreator/scriptSafety.ts create mode 100644 src/plugins/built-in/aiModCreator/selection.test.ts create mode 100644 src/plugins/built-in/aiModCreator/selection.ts create mode 100644 src/plugins/built-in/aiModCreator/services.ts create mode 100644 src/plugins/built-in/aiModCreator/storage.test.ts create mode 100644 src/plugins/built-in/aiModCreator/storage.ts create mode 100644 src/plugins/built-in/aiModCreator/types.ts diff --git a/package.json b/package.json index 4bf8cc04..cdce99ab 100644 --- a/package.json +++ b/package.json @@ -108,6 +108,7 @@ "semver": "^7.7.1", "sortablejs": "^1.15.6", "svelte": "^5.46.4", + "svelte-hero-icons": "^5.2.0", "webextension-polyfill": "^0.12.0" }, "overrides": { diff --git a/src/background.ts b/src/background.ts index e4110da5..10db3aad 100644 --- a/src/background.ts +++ b/src/background.ts @@ -19,6 +19,10 @@ import { registerGoogleCalendarMessageHandlers, registerOutlookCalendarMessageHandlers, } from "./background/calendarBackground"; +import { + handleAiModCreatorMessage, + registerAiModCreatorStreaming, +} from "./background/aiModCreator"; /** * Session-only dev-mode override of the content API base. @@ -525,6 +529,13 @@ const MESSAGE_HANDLERS: Record = { cloudFavorite: handleCloudFavorite, cloudSettingsUpload: handleCloudSettingsUpload, cloudSettingsDownload: handleCloudSettingsDownload, + aiModCreator: (request, sendResponse, sender) => + handleAiModCreatorMessage( + request, + sender ?? {}, + sendResponse, + isTrustedSender, + ), cloudSettingsPoll: () => { void runCloudSettingsPoll(); return false; @@ -573,6 +584,7 @@ const MESSAGE_HANDLERS: Record = { registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender); registerOutlookCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender); +registerAiModCreatorStreaming(isTrustedSender); initCalendarBackground(); browser.runtime.onMessage.addListener( diff --git a/src/background/aiModCreator.test.ts b/src/background/aiModCreator.test.ts new file mode 100644 index 00000000..40287120 --- /dev/null +++ b/src/background/aiModCreator.test.ts @@ -0,0 +1,292 @@ +import browser from "webextension-polyfill"; +import { + AI_MOD_CREATOR_MESSAGE_TYPE, + createAiModCreatorService, + formatOpenRouterError, + handleAiModCreatorMessage, +} from "./aiModCreator"; +import type { SelectedElementContext } from "@/plugins/built-in/aiModCreator/types"; + +const context: SelectedElementContext = { + route: "assessments", + rootSelector: "#selected", + request: "Round this card", + userContext: "Assessment summary", + selectedHtml: '
Assessment
', + domCatalog: [ + { + selector: ":scope", + tag: "section", + classes: [], + parentSelector: null, + siblingIndex: 0, + siblingCount: 1, + layout: { display: "block" }, + }, + ], + tagName: "section", + dimensions: { width: 400, height: 200 }, + computedStyle: { color: "rgb(0, 0, 0)" }, +}; + +describe("AI mod OpenRouter background service", () => { + it("stores the key locally and reports only whether it exists", async () => { + const service = createAiModCreatorService({ + fetchImpl: jest.fn(), + now: () => 1_000, + }); + + await service.saveKey(" sk-or-v1-test-key-123456 "); + await expect(service.getKeyStatus()).resolves.toEqual({ configured: true }); + expect(await browser.storage.local.get("aiModCreator.openRouterApiKey")).toEqual({ + "aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456", + }); + + await service.clearKey(); + await expect(service.getKeyStatus()).resolves.toEqual({ configured: false }); + }); + + it("calls the free model with json_object output and provider fallbacks", async () => { + await browser.storage.local.set({ + "aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456", + }); + const fetchImpl = jest.fn(async (_url: string, init?: RequestInit) => { + const body = JSON.parse(String(init?.body)); + expect(body).toMatchObject({ + model: "minimax/minimax-m2.7:free", + provider: { allow_fallbacks: true }, + response_format: { type: "json_object" }, + }); + expect(init?.headers).toMatchObject({ + Authorization: "Bearer sk-or-v1-test-key-123456", + }); + return new Response( + JSON.stringify({ + choices: [ + { + message: { + content: JSON.stringify({ + name: "Rounded card", + description: "Rounds the selected card.", + operations: [ + { + type: "setStyle", + selector: ":scope", + property: "border-radius", + value: "12px", + }, + ], + }), + }, + }, + ], + }), + { status: 200 }, + ); + }); + const service = createAiModCreatorService({ + fetchImpl, + now: () => 10_000, + }); + + await expect(service.generate(context)).resolves.toMatchObject({ + name: "Rounded card", + operations: [{ type: "setStyle", property: "border-radius" }], + }); + expect(fetchImpl).toHaveBeenCalledWith( + "https://openrouter.ai/api/v1/chat/completions", + expect.objectContaining({ method: "POST" }), + ); + }); + + it("retries without structured output when OpenRouter routing fails", async () => { + await browser.storage.local.set({ + "aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456", + }); + const fetchImpl = jest + .fn() + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + error: { + message: + "No endpoints found that can handle the requested parameters.", + }, + }), + { status: 404 }, + ), + ) + .mockResolvedValueOnce( + new Response( + JSON.stringify({ + choices: [ + { + message: { + content: JSON.stringify({ + name: "Fallback mod", + description: "Generated without structured output.", + operations: [{ type: "hide", selector: ":scope .meta" }], + }), + }, + }, + ], + }), + { status: 200 }, + ), + ); + const service = createAiModCreatorService({ + fetchImpl, + now: () => 10_000, + }); + + await expect(service.generate(context)).resolves.toMatchObject({ + name: "Fallback mod", + }); + expect(fetchImpl).toHaveBeenCalledTimes(2); + const firstBody = JSON.parse(String(fetchImpl.mock.calls[0][1]?.body)); + const secondBody = JSON.parse(String(fetchImpl.mock.calls[1][1]?.body)); + expect(firstBody.response_format).toEqual({ type: "json_object" }); + expect(secondBody.response_format).toBeUndefined(); + }); + + it("streams partial recipe content and token usage", async () => { + await browser.storage.local.set({ + "aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456", + }); + const json = JSON.stringify({ + name: "Streamed mod", + description: "Generated incrementally", + operations: [{ type: "hide", selector: ":scope .metadata" }], + }); + const first = json.slice(0, 35); + const second = json.slice(35); + const streamBody = [ + `data: ${JSON.stringify({ choices: [{ delta: { reasoning_details: [{}] } }] })}\n\n`, + `data: ${JSON.stringify({ choices: [{ delta: { content: first } }] })}\n\n`, + `data: ${JSON.stringify({ choices: [{ delta: { content: second } }], usage: { prompt_tokens: 20, completion_tokens: 30 } })}\n\n`, + "data: [DONE]\n\n", + ].join(""); + const service = createAiModCreatorService({ + fetchImpl: jest.fn(async () => + new Response(streamBody, { + status: 200, + headers: { "Content-Type": "text/event-stream" }, + }), + ), + now: () => 20_000, + }); + const progress: unknown[] = []; + + await expect( + service.streamGenerate(context, (update) => progress.push(update)), + ).resolves.toMatchObject({ name: "Streamed mod" }); + expect(progress).toEqual( + expect.arrayContaining([ + { type: "status", text: "Connecting to MiniMax M2.7 (free)…" }, + { type: "status", text: "Model is reasoning…" }, + { type: "content", text: first }, + { + type: "usage", + promptTokens: 20, + completionTokens: 30, + }, + ]), + ); + }); + + it("surfaces stream rate-limit errors with actionable guidance", async () => { + await browser.storage.local.set({ + "aiModCreator.openRouterApiKey": "sk-or-v1-test-key-123456", + }); + const streamBody = [ + ": OPENROUTER PROCESSING\n\n", + `data: ${JSON.stringify({ + error: { + code: 429, + message: "Provider returned error", + metadata: { error_type: "rate_limit_exceeded" }, + }, + })}\n\n`, + ].join(""); + const service = createAiModCreatorService({ + fetchImpl: jest.fn(async () => + new Response(streamBody, { + status: 200, + headers: { "Content-Type": "text/event-stream" }, + }), + ), + now: () => 20_000, + }); + + await expect(service.streamGenerate(context, () => {})).rejects.toThrow( + /Rate limit reached for MiniMax M2\.7 \(free\)/, + ); + }); + + it("formats free-tier rate-limit guidance", () => { + expect( + formatOpenRouterError( + { + code: 429, + message: "Provider returned error", + metadata: { error_type: "rate_limit_exceeded" }, + }, + "minimax/minimax-m2.7:free", + ), + ).toMatch(/switch model/i); + }); + + it("rejects missing keys, oversized input, throttling, and provider errors", async () => { + const service = createAiModCreatorService({ + fetchImpl: jest.fn(), + now: () => 1_000, + }); + await expect(service.generate(context)).rejects.toThrow("API key"); + + await service.saveKey("sk-or-v1-test-key-123456"); + await expect( + service.generate({ ...context, request: "x".repeat(2_001) }), + ).rejects.toThrow("too long"); + + const failingService = createAiModCreatorService({ + fetchImpl: jest.fn(async () => + new Response( + JSON.stringify({ + error: { + message: "Free model rate limit reached", + code: 429, + metadata: { error_type: "rate_limit_exceeded" }, + }, + }), + { status: 429 }, + ), + ), + now: () => 10_000, + }); + await expect(failingService.generate(context)).rejects.toThrow( + /Rate limit reached for MiniMax M2\.7 \(free\)/, + ); + await expect(failingService.generate(context)).rejects.toThrow( + /Please wait \d+s/, + ); + }); + + it("rejects untrusted runtime message senders", () => { + const sendResponse = jest.fn(); + const handled = handleAiModCreatorMessage( + { + type: AI_MOD_CREATOR_MESSAGE_TYPE, + action: "status", + }, + { id: "another-extension" } as browser.Runtime.MessageSender, + sendResponse, + () => false, + ); + + expect(handled).toBe(false); + expect(sendResponse).toHaveBeenCalledWith({ + success: false, + error: "Unauthorized sender", + }); + }); +}); diff --git a/src/background/aiModCreator.ts b/src/background/aiModCreator.ts new file mode 100644 index 00000000..da9007a4 --- /dev/null +++ b/src/background/aiModCreator.ts @@ -0,0 +1,738 @@ +import browser from "webextension-polyfill"; +import { + buildAiModMessages, +} from "@/plugins/built-in/aiModCreator/prompt"; +import { + formatRecipeValidationError, + parseGeneratedModDraft, +} from "@/plugins/built-in/aiModCreator/recipeSchema"; +import { aiModLog } from "@/plugins/built-in/aiModCreator/logger"; +import { + DEFAULT_OPENROUTER_MODEL_ID, + getModelOption, + validateModelId, +} from "@/plugins/built-in/aiModCreator/models"; +import { + OPENROUTER_API_KEY_STORAGE_KEY, + OPENROUTER_MODEL_STORAGE_KEY, +} from "@/plugins/built-in/aiModCreator/storage"; +import { + executeAdvancedMod, + getAdvancedScriptSupport, + stopAdvancedMod, +} from "./aiModUserScripts"; +import type { + GenerationProgress, + GeneratedModDraft, + KeyStatus, + SelectedElementContext, + StoredModRecipe, +} from "@/plugins/built-in/aiModCreator/types"; + +export const AI_MOD_CREATOR_MESSAGE_TYPE = "aiModCreator"; +export const OPENROUTER_MODEL_ID = DEFAULT_OPENROUTER_MODEL_ID; +const OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"; +const MIN_GENERATION_INTERVAL_MS = 5_000; +const ROUTING_ERROR_PATTERN = + /no endpoints found|can handle the requested parameters/i; + +type ResponseFormatMode = "json_object" | "none"; + +type StorageArea = Pick< + browser.Storage.StorageArea, + "get" | "set" | "remove" +>; +type FetchLike = (input: string, init?: RequestInit) => Promise; +type SendResponse = (response: unknown) => void; +type TrustCheck = (sender?: browser.Runtime.MessageSender) => boolean; + +function validateApiKey(value: unknown): string { + if (typeof value !== "string") throw new Error("API key is required"); + const key = value.trim(); + if (key.length < 16 || key.length > 512) { + throw new Error("API key must be between 16 and 512 characters"); + } + return key; +} + +function validateContext(value: unknown): SelectedElementContext { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error("Selected element context is required"); + } + const context = value as SelectedElementContext; + const limits: Array<[keyof SelectedElementContext, number]> = [ + ["route", 256], + ["rootSelector", 1_000], + ["request", 2_000], + ["userContext", 4_000], + ["selectedHtml", 24_000], + ["ancestorHtml", 6_000], + ["tagName", 80], + ]; + for (const [key, limit] of limits) { + const field = context[key]; + if (field === undefined) continue; + if (typeof field !== "string") throw new Error(`${key} must be text`); + if (field.length > limit) throw new Error(`${key} is too long`); + } + if (!Array.isArray(context.domCatalog)) { + throw new Error("domCatalog is required"); + } + if (context.domCatalog.length > 100) { + throw new Error("domCatalog must contain at most 100 entries"); + } + for (const entry of context.domCatalog) { + if (!entry || typeof entry !== "object") { + throw new Error("domCatalog entries must be objects"); + } + if (typeof entry.selector !== "string" || entry.selector.length > 500) { + throw new Error("domCatalog selector is invalid"); + } + if (typeof entry.tag !== "string" || entry.tag.length > 80) { + throw new Error("domCatalog tag is invalid"); + } + if ( + entry.layout && + (typeof entry.layout !== "object" || + Array.isArray(entry.layout) || + Object.keys(entry.layout).length > 24) + ) { + throw new Error("domCatalog layout summary is invalid"); + } + for (const countKey of ["rowCount", "columnCount", "itemCount"] as const) { + const count = entry[countKey]; + if (count === undefined) continue; + if (!Number.isFinite(count) || count < 0 || count > 10_000) { + throw new Error(`domCatalog ${countKey} is invalid`); + } + } + } + if (context.parentChain !== undefined) { + if (!Array.isArray(context.parentChain)) { + throw new Error("parentChain must be an array"); + } + if (context.parentChain.length > 3) { + throw new Error("parentChain must contain at most 3 entries"); + } + for (const entry of context.parentChain) { + if (!entry || typeof entry !== "object") { + throw new Error("parentChain entries must be objects"); + } + if (typeof entry.tag !== "string" || entry.tag.length > 80) { + throw new Error("parentChain tag is invalid"); + } + if (!Array.isArray(entry.classes) || entry.classes.length > 8) { + throw new Error("parentChain classes are invalid"); + } + for (const className of entry.classes) { + if (typeof className !== "string" || className.length > 80) { + throw new Error("parentChain class name is invalid"); + } + } + if ( + !entry.layout || + typeof entry.layout !== "object" || + Array.isArray(entry.layout) || + Object.keys(entry.layout).length > 24 + ) { + throw new Error("parentChain layout summary is invalid"); + } + } + } + if (context.structuralHints !== undefined) { + const hints = context.structuralHints; + if (!hints || typeof hints !== "object" || Array.isArray(hints)) { + throw new Error("structuralHints must be an object"); + } + if (typeof hints.hasTable !== "boolean" || typeof hints.hasList !== "boolean") { + throw new Error("structuralHints flags are invalid"); + } + if (!Array.isArray(hints.primaryClasses) || hints.primaryClasses.length > 8) { + throw new Error("structuralHints primaryClasses are invalid"); + } + for (const className of hints.primaryClasses) { + if (typeof className !== "string" || className.length > 80) { + throw new Error("structuralHints class name is invalid"); + } + } + for (const countKey of ["rowCount", "columnCount", "itemCount"] as const) { + const count = hints[countKey]; + if (count === undefined) continue; + if (!Number.isFinite(count) || count < 0 || count > 10_000) { + throw new Error(`structuralHints ${countKey} is invalid`); + } + } + } + if (!context.request.trim()) throw new Error("Change request is required"); + if ( + !context.dimensions || + !Number.isFinite(context.dimensions.width) || + !Number.isFinite(context.dimensions.height) + ) { + throw new Error("Element dimensions are invalid"); + } + if ( + !context.computedStyle || + typeof context.computedStyle !== "object" || + Array.isArray(context.computedStyle) || + Object.keys(context.computedStyle).length > 20 + ) { + throw new Error("Computed style summary is invalid"); + } + return { + ...context, + dimensions: { ...context.dimensions }, + computedStyle: { ...context.computedStyle }, + domCatalog: context.domCatalog.map((entry) => ({ + ...entry, + classes: [...entry.classes], + layout: { ...entry.layout }, + })), + ...(context.parentChain + ? { + parentChain: context.parentChain.map((entry) => ({ + ...entry, + classes: [...entry.classes], + layout: { ...entry.layout }, + })), + } + : {}), + ...(context.structuralHints + ? { + structuralHints: { + ...context.structuralHints, + primaryClasses: [...context.structuralHints.primaryClasses], + }, + } + : {}), + }; +} + +function responseContent(payload: unknown): string { + if (!payload || typeof payload !== "object") { + throw new Error("OpenRouter returned an invalid response"); + } + const choices = (payload as { choices?: unknown }).choices; + if (!Array.isArray(choices) || choices.length === 0) { + throw new Error("OpenRouter returned no choices"); + } + const content = ( + choices[0] as { message?: { content?: unknown } } + ).message?.content; + if (typeof content === "string") return content; + if (Array.isArray(content)) { + const combined = content + .map((part) => + part && + typeof part === "object" && + "text" in part && + typeof part.text === "string" + ? part.text + : "", + ) + .join(""); + if (combined) return combined; + } + throw new Error("OpenRouter returned no generated recipe"); +} + +async function providerError( + response: Response, + modelId: string, +): Promise { + const fallback = `OpenRouter request failed (${response.status})`; + try { + const payload = (await response.json()) as { + error?: { message?: unknown; code?: number; metadata?: { error_type?: string } } | string; + }; + if (typeof payload.error === "string") { + return formatOpenRouterError({ message: payload.error }, modelId); + } + if (payload.error && typeof payload.error === "object") { + return formatOpenRouterError(payload.error, modelId); + } + } catch { + // Use the status-only fallback without exposing response content. + } + if (response.status === 429) { + return formatOpenRouterError({ code: 429 }, modelId); + } + return fallback; +} + +type OpenRouterErrorShape = { + code?: number; + message?: string; + metadata?: { error_type?: string }; +}; + +export function formatOpenRouterError( + error: OpenRouterErrorShape | undefined, + modelId: string, +): string { + if (!error) return "OpenRouter request failed"; + + const errorType = error.metadata?.error_type; + const message = typeof error.message === "string" ? error.message : ""; + const isRateLimit = + error.code === 429 || + errorType === "rate_limit_exceeded" || + /rate limit/i.test(message); + + if (isRateLimit) { + const model = getModelOption(modelId); + const tierHint = + model?.tier === "free" + ? "Free models share strict provider limits — wait 1–2 minutes or switch model in the creator panel." + : "Wait a minute and try again."; + return `Rate limit reached for ${model?.label ?? modelId}. ${tierHint}`; + } + + return message || "OpenRouter request failed"; +} + +function openRouterRequestBody( + context: SelectedElementContext, + stream: boolean, + formatMode: ResponseFormatMode, + modelId: string, +): Record { + const body: Record = { + model: modelId, + messages: buildAiModMessages(context), + temperature: 0.2, + max_tokens: 8_000, + stream, + provider: { + allow_fallbacks: true, + }, + }; + + if (formatMode === "json_object") { + body.response_format = { type: "json_object" }; + } + + return body; +} + +function openRouterRequestInit( + apiKey: string, + context: SelectedElementContext, + stream: boolean, + formatMode: ResponseFormatMode, + modelId: string, +): RequestInit { + return { + method: "POST", + headers: { + Authorization: `Bearer ${apiKey}`, + "Content-Type": "application/json", + "HTTP-Referer": "https://betterseqta.org", + "X-Title": "BetterSEQTA+ AI Mod Creator", + }, + body: JSON.stringify( + openRouterRequestBody(context, stream, formatMode, modelId), + ), + }; +} + +function isRoutingError(message: string): boolean { + return ROUTING_ERROR_PATTERN.test(message); +} + +function parseValidatedDraft( + content: string | GeneratedModDraft, +): GeneratedModDraft { + try { + return parseGeneratedModDraft(content); + } catch (error) { + throw new Error(formatRecipeValidationError(error)); + } +} + +async function requestGeneratedDraft( + fetchImpl: FetchLike, + apiKey: string, + context: SelectedElementContext, + stream: boolean, + modelId: string, + onProgress?: (progress: GenerationProgress) => void, +): Promise { + const modes: ResponseFormatMode[] = ["json_object", "none"]; + let lastError = "OpenRouter request failed"; + const modelLabel = getModelOption(modelId)?.label ?? modelId; + + for (const [index, mode] of modes.entries()) { + if (index > 0) { + aiModLog.warn("background", "Retrying OpenRouter request", { mode, lastError }); + onProgress?.({ + type: "status", + text: "Retrying with a simpler OpenRouter request…", + }); + } else if (stream) { + onProgress?.({ type: "status", text: `Connecting to ${modelLabel}…` }); + } + + aiModLog.info("background", "Sending OpenRouter request", { + mode, + stream, + model: modelId, + route: context.route, + rootSelector: context.rootSelector, + }); + + const response = await fetchImpl( + OPENROUTER_URL, + openRouterRequestInit(apiKey, context, stream, mode, modelId), + ); + if (response.ok) { + aiModLog.info("background", "OpenRouter request succeeded", { + mode, + stream, + status: response.status, + }); + if (stream) { + return consumeOpenRouterStream( + response, + modelId, + onProgress ?? (() => {}), + ); + } + const payload = await response.json(); + const content = responseContent(payload); + aiModLog.debug("background", "OpenRouter non-stream content", content); + return parseValidatedDraft(content); + } + + lastError = await providerError(response, modelId); + aiModLog.warn("background", "OpenRouter request failed", { + mode, + stream, + status: response.status, + error: lastError, + }); + if (!isRoutingError(lastError)) break; + } + + throw new Error(lastError); +} + +async function consumeOpenRouterStream( + response: Response, + modelId: string, + onProgress: (progress: GenerationProgress) => void, +): Promise { + if (!response.body) throw new Error("OpenRouter returned an empty stream"); + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + let generatedContent = ""; + let reasoningStarted = false; + + const processEvent = (event: string) => { + const data = event + .split(/\r?\n/) + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice(5).trim()) + .join(""); + if (!data || data === "[DONE]") return; + + const chunk = JSON.parse(data) as { + error?: OpenRouterErrorShape; + choices?: Array<{ + delta?: { + content?: string | null; + reasoning_details?: unknown[]; + }; + error?: OpenRouterErrorShape; + }>; + usage?: { + prompt_tokens?: number; + completion_tokens?: number; + }; + }; + const streamError = chunk.error ?? chunk.choices?.[0]?.error; + if (streamError) { + aiModLog.warn("background", "OpenRouter stream error chunk", streamError); + throw new Error(formatOpenRouterError(streamError, modelId)); + } + + const delta = chunk.choices?.[0]?.delta; + if (Array.isArray(delta?.reasoning_details) && !reasoningStarted) { + reasoningStarted = true; + onProgress({ type: "status", text: "Model is reasoning…" }); + } + if (typeof delta?.content === "string" && delta.content) { + generatedContent += delta.content; + onProgress({ type: "content", text: delta.content }); + } + if (chunk.usage) { + onProgress({ + type: "usage", + promptTokens: chunk.usage.prompt_tokens, + completionTokens: chunk.usage.completion_tokens, + }); + } + }; + + while (true) { + const { value, done } = await reader.read(); + buffer += decoder.decode(value, { stream: !done }); + const events = buffer.split(/\r?\n\r?\n/); + buffer = events.pop() ?? ""; + for (const event of events) processEvent(event); + if (done) break; + } + if (buffer.trim()) processEvent(buffer); + aiModLog.debug("background", "Completed OpenRouter stream", { + contentLength: generatedContent.length, + preview: generatedContent.slice(0, 500), + }); + return parseValidatedDraft(generatedContent); +} + +export function createAiModCreatorService( + dependencies: { + storage?: StorageArea; + fetchImpl?: FetchLike; + now?: () => number; + } = {}, +) { + const storage = dependencies.storage ?? browser.storage.local; + const fetchImpl = dependencies.fetchImpl ?? fetch; + const now = dependencies.now ?? Date.now; + let inFlight = false; + let lastGenerationAt = Number.NEGATIVE_INFINITY; + + const getStoredKey = async (): Promise => { + const result = await storage.get(OPENROUTER_API_KEY_STORAGE_KEY); + const value = result[OPENROUTER_API_KEY_STORAGE_KEY]; + return typeof value === "string" && value.length > 0 ? value : null; + }; + + const getStoredModelId = async (): Promise => { + const result = await storage.get(OPENROUTER_MODEL_STORAGE_KEY); + const value = result[OPENROUTER_MODEL_STORAGE_KEY]; + if (typeof value === "string" && value.length > 0) { + try { + return validateModelId(value); + } catch { + aiModLog.warn("background", "Ignoring invalid stored model id", value); + } + } + return DEFAULT_OPENROUTER_MODEL_ID; + }; + + const beginGeneration = () => { + const currentTime = now(); + if (inFlight) { + throw new Error("A generation is already in progress"); + } + if (currentTime - lastGenerationAt < MIN_GENERATION_INTERVAL_MS) { + const waitSeconds = Math.ceil( + (MIN_GENERATION_INTERVAL_MS - (currentTime - lastGenerationAt)) / 1000, + ); + throw new Error( + `Please wait ${waitSeconds}s before generating another mod`, + ); + } + inFlight = true; + lastGenerationAt = currentTime; + }; + + return { + async saveKey(apiKey: unknown): Promise { + await storage.set({ + [OPENROUTER_API_KEY_STORAGE_KEY]: validateApiKey(apiKey), + }); + }, + + async clearKey(): Promise { + await storage.remove(OPENROUTER_API_KEY_STORAGE_KEY); + }, + + async getKeyStatus(): Promise { + return { configured: (await getStoredKey()) !== null }; + }, + + async getModelSettings() { + return { modelId: await getStoredModelId() }; + }, + + async saveModel(modelId: unknown): Promise { + await storage.set({ + [OPENROUTER_MODEL_STORAGE_KEY]: validateModelId(modelId), + }); + aiModLog.info("background", "Saved OpenRouter model", modelId); + }, + + async generate(input: unknown): Promise { + const context = validateContext(input); + const apiKey = await getStoredKey(); + if (!apiKey) throw new Error("OpenRouter API key is not configured"); + const modelId = await getStoredModelId(); + beginGeneration(); + + try { + return await requestGeneratedDraft( + fetchImpl, + apiKey, + context, + false, + modelId, + ); + } finally { + inFlight = false; + } + }, + + async streamGenerate( + input: unknown, + onProgress: (progress: GenerationProgress) => void, + ): Promise { + const context = validateContext(input); + const apiKey = await getStoredKey(); + if (!apiKey) throw new Error("OpenRouter API key is not configured"); + const modelId = await getStoredModelId(); + beginGeneration(); + + try { + return await requestGeneratedDraft( + fetchImpl, + apiKey, + context, + true, + modelId, + onProgress, + ); + } finally { + inFlight = false; + } + }, + }; +} + +const defaultService = createAiModCreatorService(); + +export function handleAiModCreatorMessage( + request: { + type?: string; + action?: string; + apiKey?: unknown; + context?: unknown; + recipe?: unknown; + id?: unknown; + modelId?: unknown; + }, + sender: browser.Runtime.MessageSender, + sendResponse: SendResponse, + isTrustedSender: TrustCheck, +): boolean { + if (!isTrustedSender(sender)) { + sendResponse({ success: false, error: "Unauthorized sender" }); + return false; + } + + const action = request.action; + aiModLog.debug("background", "Handling message", { + action, + tabId: sender.tab?.id, + senderId: sender.id, + }); + void (async () => { + try { + let data: unknown; + if (action === "saveKey") { + await defaultService.saveKey(request.apiKey); + } else if (action === "clearKey") { + await defaultService.clearKey(); + } else if (action === "status") { + data = await defaultService.getKeyStatus(); + } else if (action === "getModel") { + data = await defaultService.getModelSettings(); + } else if (action === "saveModel") { + await defaultService.saveModel(request.modelId); + } else if (action === "advancedSupport") { + data = getAdvancedScriptSupport(); + } else if (action === "generate") { + data = await defaultService.generate(request.context); + } else if (action === "executeAdvanced") { + if (sender.tab?.id === undefined) { + throw new Error("Advanced scripts require a SEQTA browser tab"); + } + const { devMode } = await browser.storage.local.get("devMode"); + if (devMode !== true) { + throw new Error("Advanced scripts are available only in developer mode"); + } + await executeAdvancedMod( + request.recipe as StoredModRecipe, + sender.tab.id, + ); + } else if (action === "stopAdvanced") { + if (sender.tab?.id === undefined || typeof request.id !== "string") { + throw new Error("Advanced script id or tab is missing"); + } + await stopAdvancedMod(request.id, sender.tab.id); + } else { + throw new Error("Unsupported AI Mod Creator action"); + } + sendResponse({ success: true, data }); + aiModLog.debug("background", "Message handled", { action }); + } catch (error) { + const message = + error instanceof Error ? error.message : "AI request failed"; + aiModLog.error("background", "Message failed", { action, error: message }); + sendResponse({ + success: false, + error: message, + }); + } + })(); + return true; +} + +export function registerAiModCreatorStreaming( + isTrustedSender: TrustCheck, +): void { + browser.runtime.onConnect.addListener((port) => { + if (port.name !== "aiModCreator.stream") return; + if (!isTrustedSender(port.sender)) { + port.postMessage({ type: "error", error: "Unauthorized sender" }); + port.disconnect(); + return; + } + + let started = false; + port.onMessage.addListener((message: unknown) => { + if (started) return; + started = true; + const context = + message && typeof message === "object" && "context" in message + ? (message as { context?: unknown }).context + : undefined; + aiModLog.info("background", "Starting streamed generation"); + void defaultService + .streamGenerate(context, (progress) => { + port.postMessage({ type: "progress", progress }); + }) + .then((draft) => { + aiModLog.info("background", "Streamed generation complete", { + name: draft.name, + operationCount: draft.operations.length, + }); + port.postMessage({ type: "done", draft }); + port.disconnect(); + }) + .catch((error) => { + const message = + error instanceof Error ? error.message : "AI streaming failed"; + aiModLog.error("background", "Streamed generation failed", message); + port.postMessage({ + type: "error", + error: message, + }); + port.disconnect(); + }); + }); + }); +} diff --git a/src/background/aiModUserScripts.test.ts b/src/background/aiModUserScripts.test.ts new file mode 100644 index 00000000..d278becc --- /dev/null +++ b/src/background/aiModUserScripts.test.ts @@ -0,0 +1,33 @@ +import { buildExecutionSource } from "./aiModUserScripts"; +import type { StoredModRecipe } from "@/plugins/built-in/aiModCreator/types"; + +const baseRecipe: StoredModRecipe = { + schemaVersion: 1, + id: "mod-test", + enabled: true, + route: "welcome", + rootSelector: "#titlebar", + name: "Test mod", + description: "Test", + operations: [], + advancedScript: ` + const house = select('.userInfohouse'); + if (!house) throw new Error('Missing .userInfohouse inside selected root'); + return () => {}; + `, + createdAt: 1, + updatedAt: 1, +}; + +describe("advanced user script injection source", () => { + it("does not declare select twice in the generated runtime", () => { + const source = buildExecutionSource(baseRecipe); + expect(source.match(/\bconst select\b/g)?.length).toBe(1); + expect(source.match(/\bconst selectAll\b/g)?.length).toBe(1); + }); + + it("throws when the selected root is missing", () => { + const source = buildExecutionSource(baseRecipe); + expect(source).toContain("AI mod root not found on this page"); + }); +}); diff --git a/src/background/aiModUserScripts.ts b/src/background/aiModUserScripts.ts new file mode 100644 index 00000000..1ab5b0b3 --- /dev/null +++ b/src/background/aiModUserScripts.ts @@ -0,0 +1,290 @@ +import { + SAFE_ATTRIBUTE_NAMES, + SAFE_INSERT_TAGS, + SAFE_STYLE_PROPERTIES, + validateStoredRecipes, +} from "@/plugins/built-in/aiModCreator/recipeSchema"; +import { assertAdvancedScriptSafe } from "@/plugins/built-in/aiModCreator/scriptSafety"; +import type { StoredModRecipe } from "@/plugins/built-in/aiModCreator/types"; + +interface UserScriptsApi { + configureWorld(details: { + worldId: string; + csp: string; + messaging: boolean; + }): Promise; + execute(details: { + target: { tabId: number; allFrames: boolean }; + worldId: string; + world: "USER_SCRIPT"; + injectImmediately: boolean; + js: Array<{ code: string }>; + }): Promise; +} + +const USER_SCRIPT_CSP = [ + "default-src 'none'", + "script-src 'self' 'unsafe-inline'", + "connect-src 'none'", + "img-src 'none'", + "media-src 'none'", + "font-src 'none'", + "object-src 'none'", + "frame-src 'none'", + "child-src 'none'", + "form-action 'none'", + "base-uri 'none'", +].join("; "); + +function getUserScriptsApi(): UserScriptsApi { + const globalApis = globalThis as unknown as { + chrome?: { userScripts?: UserScriptsApi }; + browser?: { userScripts?: UserScriptsApi }; + }; + const api = + globalApis.chrome?.userScripts ?? globalApis.browser?.userScripts; + if (!api?.execute || !api.configureWorld) { + throw new Error( + "Advanced scripts require Chrome User Scripts support.", + ); + } + return api; +} + +export const ADVANCED_SCRIPT_SETUP_INSTRUCTIONS = [ + "Open chrome://extensions", + "Find BetterSEQTA+ and open Details", + 'Enable "Allow User Scripts"', + "Reload this SEQTA tab, then enable the mod again", +].join("\n"); + +export function getAdvancedScriptSupport(): { + supported: boolean; + reason?: string; + instructions?: string; +} { + try { + getUserScriptsApi(); + return { supported: true }; + } catch (error) { + return { + supported: false, + reason: + error instanceof Error + ? error.message + : "Advanced scripts are unavailable in this browser", + instructions: ADVANCED_SCRIPT_SETUP_INSTRUCTIONS, + }; + } +} + +function worldId(id: string): string { + return `bsplus-${id}`.slice(0, 256); +} + +export function buildExecutionSource(recipe: StoredModRecipe): string { + const script = assertAdvancedScriptSafe(recipe.advancedScript); + const config = JSON.stringify({ + id: recipe.id, + route: recipe.route, + rootSelector: recipe.rootSelector, + allowedAttributes: SAFE_ATTRIBUTE_NAMES, + allowedStyles: SAFE_STYLE_PROPERTIES, + allowedTags: SAFE_INSERT_TAGS, + }); + + return `(() => { + "use strict"; + const config = ${config}; + const registryKey = Symbol.for("betterseqta.aiModRuntime"); + const registry = globalThis[registryKey] ?? (globalThis[registryKey] = new Map()); + const previousCleanup = registry.get(config.id); + if (typeof previousCleanup === "function") previousCleanup(); + + const route = (location.hash.split("?page=/")[1] ?? "").split(/[/?#]/)[0]; + if (config.route && route !== config.route) { + throw new Error("AI mod route mismatch: expected " + config.route + " but page is " + route); + } + const root = document.querySelector(config.rootSelector); + if (!(root instanceof HTMLElement)) { + throw new Error("AI mod root not found on this page: " + config.rootSelector); + } + + const cleanups = []; + const remember = (cleanup) => { + if (typeof cleanup === "function") cleanups.push(cleanup); + return cleanup; + }; + const insideRoot = (element) => + element instanceof Element && (element === root || root.contains(element)); + const requireInsideRoot = (element) => { + if (!insideRoot(element)) throw new Error("AI mod attempted to leave its selected root"); + return element; + }; + const query = (selector = ":scope") => + selector === ":scope" ? root : root.querySelector(selector); + const queryAll = (selector = ":scope") => + selector === ":scope" ? [root] : Array.from(root.querySelectorAll(selector)); + + const bsplus = Object.freeze({ + root, + select: query, + selectAll: queryAll, + onCleanup: remember, + setText(element, text) { + requireInsideRoot(element); + const previous = element.textContent; + element.textContent = String(text); + remember(() => { element.textContent = previous; }); + return element; + }, + setStyle(element, property, value) { + requireInsideRoot(element); + if (!config.allowedStyles.includes(property)) throw new Error("Unsupported style property"); + const previous = element.style.getPropertyValue(property); + const priority = element.style.getPropertyPriority(property); + element.style.setProperty(property, String(value).replace(/\\s*!important\\s*$/i, "").trim(), "important"); + remember(() => previous + ? element.style.setProperty(property, previous, priority) + : element.style.removeProperty(property)); + return element; + }, + setAttribute(element, name, value) { + requireInsideRoot(element); + if (!config.allowedAttributes.includes(name)) throw new Error("Unsupported attribute"); + const hadAttribute = element.hasAttribute(name); + const previous = element.getAttribute(name); + element.setAttribute(name, String(value)); + remember(() => hadAttribute + ? element.setAttribute(name, previous ?? "") + : element.removeAttribute(name)); + return element; + }, + create(tag, text, parent = root) { + requireInsideRoot(parent); + if (!config.allowedTags.includes(tag)) throw new Error("Unsupported element tag"); + const element = document.createElement(tag); + element.textContent = String(text); + parent.append(element); + remember(() => element.remove()); + return element; + }, + on(element, event, handler, options) { + requireInsideRoot(element); + element.addEventListener(event, handler, options); + remember(() => element.removeEventListener(event, handler, options)); + }, + observe(element, callback, options = { childList: true, subtree: true }) { + requireInsideRoot(element); + const observer = new MutationObserver(callback); + observer.observe(element, options); + remember(() => observer.disconnect()); + return observer; + }, + }); + + const select = bsplus.select; + const selectAll = bsplus.selectAll; + + let disposed = false; + const cleanup = () => { + if (disposed) return; + disposed = true; + for (const callback of cleanups.reverse()) { + try { callback(); } catch (error) { console.warn("[BetterSEQTA+ AI Mod] Cleanup failed", error); } + } + registry.delete(config.id); + }; + + try { + const userCleanup = (() => { +${script} + })(); + remember(userCleanup); + registry.set(config.id, cleanup); + return { ok: true }; + } catch (error) { + cleanup(); + throw error; + } + })();`; +} + +function buildStopSource(id: string): string { + return `(() => { + const registry = globalThis[Symbol.for("betterseqta.aiModRuntime")]; + const cleanup = registry?.get(${JSON.stringify(id)}); + if (typeof cleanup === "function") cleanup(); + })();`; +} + +async function configureWorld(api: UserScriptsApi, id: string): Promise { + try { + await api.configureWorld({ + worldId: worldId(id), + csp: USER_SCRIPT_CSP, + messaging: false, + }); + } catch (error) { + throw new Error( + `Could not configure the isolated script world: ${ + error instanceof Error ? error.message : "browser rejected it" + }`, + ); + } +} + +async function executeSource( + api: UserScriptsApi, + id: string, + tabId: number, + source: string, +): Promise { + await configureWorld(api, id); + const results = (await api.execute({ + target: { tabId, allFrames: false }, + world: "USER_SCRIPT", + worldId: worldId(id), + injectImmediately: true, + js: [{ code: source }], + })) as Array<{ result?: unknown; error?: unknown }> | undefined; + + const injectionError = results?.find((entry) => entry.error)?.error; + if (injectionError) { + throw new Error( + injectionError instanceof Error + ? injectionError.message + : String(injectionError), + ); + } +} + +export async function executeAdvancedMod( + input: StoredModRecipe, + tabId: number, +): Promise { + const support = getAdvancedScriptSupport(); + if (!support.supported) { + throw new Error( + `${support.reason ?? "Advanced scripts are unavailable"}\n\n${support.instructions ?? ADVANCED_SCRIPT_SETUP_INSTRUCTIONS}`, + ); + } + const [recipe] = validateStoredRecipes([input]); + if (!recipe.advancedScript) return; + await executeSource( + getUserScriptsApi(), + recipe.id, + tabId, + buildExecutionSource(recipe), + ); +} + +export async function stopAdvancedMod( + id: string, + tabId: number, +): Promise { + const support = getAdvancedScriptSupport(); + if (!support.supported) return; + if (!/^[A-Za-z0-9_-]{1,160}$/.test(id)) throw new Error("Invalid mod id"); + await executeSource(getUserScriptsApi(), id, tabId, buildStopSource(id)); +} diff --git a/src/css/injected.scss b/src/css/injected.scss index fbc90533..f827fbc2 100644 --- a/src/css/injected.scss +++ b/src/css/injected.scss @@ -772,6 +772,11 @@ html.bsplus-custom-title-pending #title > :not(#bsplus-title-root), background-image: none !important; } + > #bsplus-sidebar-root.drilling .sub ul .bsplus-sidebar-item, + > #bsplus-sidebar-root.drilling .sub ul .bsplus-sidebar-item * { + pointer-events: auto !important; + } + > #bsplus-sidebar-root > li.hasChildren.bsplus-active > label, > #bsplus-sidebar-root.drilling > li.hasChildren > label { pointer-events: none !important; diff --git a/src/manifests/manifest.json b/src/manifests/manifest.json index 095e37fb..e3fc7ec2 100644 --- a/src/manifests/manifest.json +++ b/src/manifests/manifest.json @@ -15,7 +15,7 @@ "64": "resources/icons/icon-64.png" } }, - "permissions": ["tabs", "notifications", "storage", "identity", "alarms"], + "permissions": ["tabs", "notifications", "storage", "identity", "alarms", "userScripts"], "host_permissions": [ "https://newsapi.org/", "https://betterseqta.org/", diff --git a/src/plugins/built-in/aiModCreator/CreatorTabNav.svelte b/src/plugins/built-in/aiModCreator/CreatorTabNav.svelte new file mode 100644 index 00000000..fbba19c5 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/CreatorTabNav.svelte @@ -0,0 +1,104 @@ + + +
+
+ + {#each tabs as tab (tab.id)} + + {/each} +
+
+ + diff --git a/src/plugins/built-in/aiModCreator/FloatingModCreator.svelte b/src/plugins/built-in/aiModCreator/FloatingModCreator.svelte new file mode 100644 index 00000000..b0cc53c7 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/FloatingModCreator.svelte @@ -0,0 +1,1263 @@ + + + + +
+ {#if isOpen} + + + {/if} + + +
+ +{#if showPayload && payload} + +{/if} + +{#if showImport} + +{/if} + + diff --git a/src/plugins/built-in/aiModCreator/GeneratingView.svelte b/src/plugins/built-in/aiModCreator/GeneratingView.svelte new file mode 100644 index 00000000..a76ac363 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/GeneratingView.svelte @@ -0,0 +1,326 @@ + + +
+ {#if error} + + {:else} +
+ +
+

Generating mod recipe

+ {#key status} +

+ {status || "Connecting to model…"} +

+ {/key} +
+
+ +
+ + Streaming response + {#if tokenUsage} + + {tokenUsage} + + {/if} +
+ +
+ {#if streamChunks.length === 0} +
+ + + +
+ {:else} +
+          {#each streamChunks as chunk, index (index)}
+            
+              {chunk}
+            
+          {/each}
+          
+        
+ {/if} +
+ {/if} +
+ + diff --git a/src/plugins/built-in/aiModCreator/LoadingSkinFrame.svelte b/src/plugins/built-in/aiModCreator/LoadingSkinFrame.svelte new file mode 100644 index 00000000..b8b2682b --- /dev/null +++ b/src/plugins/built-in/aiModCreator/LoadingSkinFrame.svelte @@ -0,0 +1,42 @@ + + +
+ +
+ {@render children()} +
+
+ + diff --git a/src/plugins/built-in/aiModCreator/LoadingSpinnerMini.svelte b/src/plugins/built-in/aiModCreator/LoadingSpinnerMini.svelte new file mode 100644 index 00000000..962d7706 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/LoadingSpinnerMini.svelte @@ -0,0 +1,74 @@ + + + + + diff --git a/src/plugins/built-in/aiModCreator/ModCreatorIcon.svelte b/src/plugins/built-in/aiModCreator/ModCreatorIcon.svelte new file mode 100644 index 00000000..772e9a0b --- /dev/null +++ b/src/plugins/built-in/aiModCreator/ModCreatorIcon.svelte @@ -0,0 +1,32 @@ + + + + + diff --git a/src/plugins/built-in/aiModCreator/advancedModRuntime.test.ts b/src/plugins/built-in/aiModCreator/advancedModRuntime.test.ts new file mode 100644 index 00000000..fdc32223 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/advancedModRuntime.test.ts @@ -0,0 +1,81 @@ +/** @jest-environment jsdom */ +/** + * Unit-test runtime only. Production advanced mods run through the background + * User Scripts API because page/content CSP blocks eval/new Function. + */ +import { runAdvancedMod, stopAdvancedMod } from "./advancedModRuntime"; +import type { StoredModRecipe } from "./types"; + +describe("advanced mod runtime", () => { + beforeEach(() => { + document.body.innerHTML = ""; + stopAdvancedMod("test-mod"); + }); + + it("runs an advanced script scoped to the selected root", () => { + document.body.innerHTML = ` +
+

House

+

ID

+
+ `; + const root = document.getElementById("root")!; + const label = root.querySelector(".label")!; + const target = root.querySelector(".target")!; + + const recipe: StoredModRecipe = { + schemaVersion: 1, + id: "test-mod", + enabled: true, + route: "", + rootSelector: "#root", + name: "Move label", + description: "Moves label next to target", + operations: [], + advancedScript: ` + const label = select('.label'); + const target = select('.target'); + target.parentNode.insertBefore(label, target); + return () => { + root.prepend(label); + }; + `, + createdAt: 1, + updatedAt: 1, + }; + + runAdvancedMod(recipe); + expect(target.previousElementSibling).toBe(label); + + stopAdvancedMod("test-mod"); + expect(root.firstElementChild).toBe(label); + }); + + it("stops a previously started mod before restarting it", () => { + document.body.innerHTML = `
Y11HA
`; + const recipe: StoredModRecipe = { + schemaVersion: 1, + id: "test-mod", + enabled: true, + route: "", + rootSelector: "#root", + name: "Hide badge", + description: "Hides badge", + operations: [], + advancedScript: ` + const badge = select('.badge'); + badge.hidden = true; + return () => { badge.hidden = false; }; + `, + createdAt: 1, + updatedAt: 1, + }; + + runAdvancedMod(recipe); + expect(document.querySelector(".badge")).toHaveProperty("hidden", true); + runAdvancedMod(recipe); + expect(document.querySelector(".badge")).toHaveProperty("hidden", true); + stopAdvancedMod("test-mod"); + expect(document.querySelector(".badge")).toHaveProperty("hidden", false); + }); +}); diff --git a/src/plugins/built-in/aiModCreator/advancedModRuntime.ts b/src/plugins/built-in/aiModCreator/advancedModRuntime.ts new file mode 100644 index 00000000..4a74c8f4 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/advancedModRuntime.ts @@ -0,0 +1,210 @@ +import { + SAFE_ATTRIBUTE_NAMES, + SAFE_INSERT_TAGS, + SAFE_STYLE_PROPERTIES, + normalizeStyleProperty, +} from "./recipeSchema"; +import { assertAdvancedScriptSafe } from "./scriptSafety"; +import { applyModStyleProperty, restoreModStyleProperty } from "./modStyle"; +import { aiModLog } from "./logger"; +import type { StoredModRecipe } from "./types"; + +/** + * Test-only runtime. Production uses background User Scripts injection because + * SEQTA's CSP blocks eval/new Function inside content scripts. + */ + +const REGISTRY_KEY = Symbol.for("betterseqta.aiModRuntime"); +type Cleanup = () => void; + +function getRegistry(): Map { + const globalScope = globalThis as typeof globalThis & { + [key: symbol]: Map | undefined; + }; + if (!globalScope[REGISTRY_KEY]) { + globalScope[REGISTRY_KEY] = new Map(); + } + return globalScope[REGISTRY_KEY]!; +} + +function currentRoute(): string { + return (window.location.hash.split("?page=/")[1] ?? "").split(/[/?#]/)[0]; +} + +function createBsplus(root: HTMLElement, cleanups: Cleanup[]) { + const remember = (cleanup: unknown) => { + if (typeof cleanup === "function") cleanups.push(cleanup as Cleanup); + return cleanup; + }; + const insideRoot = (element: Element) => + element === root || root.contains(element); + const requireInsideRoot = (element: Element) => { + if (!insideRoot(element)) { + throw new Error("AI mod attempted to leave its selected root"); + } + return element; + }; + const select = (selector = ":scope") => + selector === ":scope" + ? root + : root.querySelector(selector); + const selectAll = (selector = ":scope") => + selector === ":scope" + ? [root] + : Array.from(root.querySelectorAll(selector)); + + return Object.freeze({ + root, + select, + selectAll, + onCleanup: remember, + setText(element: HTMLElement, text: string) { + requireInsideRoot(element); + const previous = element.textContent; + element.textContent = String(text); + remember(() => { + element.textContent = previous; + }); + return element; + }, + setStyle(element: HTMLElement, property: string, value: string) { + requireInsideRoot(element); + const normalizedProperty = normalizeStyleProperty(property); + if (!SAFE_STYLE_PROPERTIES.includes(normalizedProperty as never)) { + throw new Error("Unsupported style property"); + } + const snapshot = applyModStyleProperty( + element, + normalizedProperty, + String(value), + true, + ); + remember(() => + restoreModStyleProperty(element, normalizedProperty, snapshot), + ); + return element; + }, + setAttribute(element: HTMLElement, name: string, value: string) { + requireInsideRoot(element); + if (!SAFE_ATTRIBUTE_NAMES.includes(name as never)) { + throw new Error("Unsupported attribute"); + } + const hadAttribute = element.hasAttribute(name); + const previous = element.getAttribute(name); + element.setAttribute(name, String(value)); + remember(() => + hadAttribute + ? element.setAttribute(name, previous ?? "") + : element.removeAttribute(name), + ); + return element; + }, + create(tag: string, text: string, parent: HTMLElement = root) { + requireInsideRoot(parent); + if (!SAFE_INSERT_TAGS.includes(tag as never)) { + throw new Error("Unsupported element tag"); + } + const element = document.createElement(tag); + element.textContent = String(text); + parent.append(element); + remember(() => element.remove()); + return element; + }, + on( + element: HTMLElement, + event: string, + handler: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ) { + requireInsideRoot(element); + element.addEventListener(event, handler, options); + remember(() => element.removeEventListener(event, handler, options)); + }, + observe( + element: HTMLElement, + callback: MutationCallback, + options: MutationObserverInit = { childList: true, subtree: true }, + ) { + requireInsideRoot(element); + const observer = new MutationObserver(callback); + observer.observe(element, options); + remember(() => observer.disconnect()); + return observer; + }, + }); +} + +export function runAdvancedMod(recipe: StoredModRecipe): void { + if (!recipe.advancedScript) return; + + stopAdvancedMod(recipe.id); + const script = assertAdvancedScriptSafe(recipe.advancedScript); + + if (recipe.route && currentRoute() !== recipe.route) { + aiModLog.debug("runtime", `Skipped mod ${recipe.id} on route ${currentRoute()}`); + return; + } + + const root = document.querySelector(recipe.rootSelector); + if (!(root instanceof HTMLElement)) { + throw new Error( + `Selected root not found on this page: ${recipe.rootSelector}`, + ); + } + + const cleanups: Cleanup[] = []; + const bsplus = createBsplus(root, cleanups); + const select = bsplus.select; + const selectAll = bsplus.selectAll; + let disposed = false; + + const cleanup = () => { + if (disposed) return; + disposed = true; + for (const callback of cleanups.reverse()) { + try { + callback(); + } catch (error) { + aiModLog.warn("runtime", `Cleanup failed for mod ${recipe.id}`, error); + } + } + getRegistry().delete(recipe.id); + }; + + try { + const runner = new Function( + "root", + "bsplus", + "select", + "selectAll", + `"use strict"; return (() => { ${script} })();`, + ) as ( + root: HTMLElement, + bsplus: ReturnType, + select: typeof bsplus.select, + selectAll: typeof bsplus.selectAll, + ) => unknown; + + const userCleanup = runner(root, bsplus, select, selectAll); + if (typeof userCleanup === "function") { + cleanups.push(userCleanup as Cleanup); + } + getRegistry().set(recipe.id, cleanup); + aiModLog.info("runtime", `Started advanced mod ${recipe.id}`, recipe.name); + } catch (error) { + cleanup(); + throw error; + } +} + +export function stopAdvancedMod(id: string): void { + const cleanup = getRegistry().get(id); + if (typeof cleanup === "function") { + cleanup(); + aiModLog.info("runtime", `Stopped advanced mod ${id}`); + } +} + +export function isAdvancedModRuntimeAvailable(): boolean { + return typeof document !== "undefined" && typeof Function !== "undefined"; +} diff --git a/src/plugins/built-in/aiModCreator/index.ts b/src/plugins/built-in/aiModCreator/index.ts new file mode 100644 index 00000000..ff24762f --- /dev/null +++ b/src/plugins/built-in/aiModCreator/index.ts @@ -0,0 +1,173 @@ +import browser from "webextension-polyfill"; +import { unmount } from "svelte"; +import type { Plugin } from "@/plugins/core/types"; +import renderSvelte from "@/interface/main"; +import { syncPageThemeToElement } from "@/interface/utils/syncPageTheme"; +import { settingsState } from "@/seqta/utils/listeners/SettingsState"; +import FloatingModCreator from "./FloatingModCreator.svelte"; +import { ModRuntime } from "./modRuntime"; +import { createCreatorServices } from "./services"; +import { AI_MODS_STORAGE_KEY, loadStoredMods } from "./storage"; +import { aiModLog } from "./logger"; + +const HOST_ATTRIBUTE = "data-bsplus-ai-mod-creator-host"; + +async function mountCreator(): Promise<() => void> { + document.querySelector(`[${HOST_ATTRIBUTE}]`)?.remove(); + + const host = document.createElement("div"); + host.setAttribute(HOST_ATTRIBUTE, ""); + Object.assign(host.style, { + position: "fixed", + right: "0", + bottom: "0", + width: "0", + height: "0", + zIndex: "2147483647", + }); + document.body.appendChild(host); + syncPageThemeToElement(host); + + const shadow = host.attachShadow({ mode: "open" }); + const services = createCreatorServices(); + const app = renderSvelte( + FloatingModCreator, + shadow, + { services }, + "content", + ); + + const runtime = new ModRuntime(); + runtime.start(); + let activeAdvancedScripts = new Map(); + + const currentRoute = () => { + const path = window.location.hash.split("?page=/")[1] ?? ""; + return path.split(/[/?#]/)[0]; + }; + + const syncMods = async () => { + const mods = await loadStoredMods(); + aiModLog.debug("plugin", "Syncing stored mods", { + count: mods.length, + route: currentRoute(), + }); + runtime.setRecipes(mods); + const route = currentRoute(); + const nextAdvanced = mods.filter( + (mod) => + mod.enabled && + Boolean(mod.advancedScript) && + (!mod.route || mod.route === route), + ); + const nextIds = new Set(nextAdvanced.map((mod) => mod.id)); + + await Promise.all( + [...activeAdvancedScripts.keys()] + .filter((id) => !nextIds.has(id)) + .map((id) => + services.stopAdvancedScript(id).catch((error) => { + aiModLog.warn("plugin", `Failed to stop AI mod ${id}`, error); + }), + ), + ); + + for (const mod of nextAdvanced) { + if (activeAdvancedScripts.get(mod.id) === mod.updatedAt) continue; + try { + await services.executeAdvancedScript(mod); + aiModLog.info("plugin", `Started advanced mod ${mod.id}`); + } catch (error) { + aiModLog.warn("plugin", `Failed to execute advanced AI mod ${mod.id}`, error); + } + } + activeAdvancedScripts = new Map( + nextAdvanced.map((mod) => [mod.id, mod.updatedAt]), + ); + }; + + await syncMods(); + + const onStorageChanged = ( + changes: Record, + areaName: string, + ) => { + if (areaName !== "local" || !changes[AI_MODS_STORAGE_KEY]) return; + void syncMods(); + }; + browser.storage.onChanged.addListener(onStorageChanged); + window.addEventListener("hashchange", syncMods); + + const themeObserver = new MutationObserver(() => syncPageThemeToElement(host)); + themeObserver.observe(document.documentElement, { + attributes: true, + attributeFilter: ["class", "style"], + }); + + const syncTheme = () => syncPageThemeToElement(host); + settingsState.register("DarkMode", syncTheme); + settingsState.register("selectedColor", syncTheme); + + return () => { + settingsState.unregister("DarkMode", syncTheme); + settingsState.unregister("selectedColor", syncTheme); + themeObserver.disconnect(); + browser.storage.onChanged.removeListener(onStorageChanged); + window.removeEventListener("hashchange", syncMods); + for (const id of activeAdvancedScripts.keys()) { + void services.stopAdvancedScript(id).catch((error) => { + console.warn(`[BetterSEQTA+] Failed to stop AI mod ${id}:`, error); + }); + } + activeAdvancedScripts = new Map(); + runtime.stop(); + unmount(app); + host.remove(); + }; +} + +const aiModCreatorPlugin: Plugin = { + id: "ai-mod-creator", + name: "AI Mod Creator", + description: + "Developer-only local creator for safe, declarative BetterSEQTA+ page mods.", + version: "0.1.0", + settings: {}, + beta: true, + run: async () => { + let cleanup: (() => void) | null = null; + let generation = 0; + + const syncEnabledState = async () => { + const currentGeneration = ++generation; + if (!settingsState.devMode) { + cleanup?.(); + cleanup = null; + return; + } + if (cleanup) return; + const nextCleanup = await mountCreator(); + if ( + currentGeneration !== generation || + !settingsState.devMode + ) { + nextCleanup(); + return; + } + cleanup = nextCleanup; + }; + + const onDevModeChanged = () => void syncEnabledState(); + settingsState.register("devMode", onDevModeChanged); + await syncEnabledState(); + + return () => { + generation += 1; + settingsState.unregister("devMode", onDevModeChanged); + cleanup?.(); + cleanup = null; + }; + }, +}; + +export default aiModCreatorPlugin; diff --git a/src/plugins/built-in/aiModCreator/logger.ts b/src/plugins/built-in/aiModCreator/logger.ts new file mode 100644 index 00000000..560fef2d --- /dev/null +++ b/src/plugins/built-in/aiModCreator/logger.ts @@ -0,0 +1,34 @@ +const PREFIX = "[BetterSEQTA+ AI Mod Creator]"; + +function serialize(value: unknown): unknown { + if (value instanceof Error) { + return { name: value.name, message: value.message, stack: value.stack }; + } + if (typeof value === "string" && value.length > 4_000) { + return `${value.slice(0, 4_000)}… (${value.length} chars)`; + } + return value; +} + +export const aiModLog = { + debug(scope: string, ...details: unknown[]) { + console.debug(PREFIX, scope, ...details.map(serialize)); + }, + info(scope: string, ...details: unknown[]) { + console.info(PREFIX, scope, ...details.map(serialize)); + }, + warn(scope: string, ...details: unknown[]) { + console.warn(PREFIX, scope, ...details.map(serialize)); + }, + error(scope: string, ...details: unknown[]) { + console.error(PREFIX, scope, ...details.map(serialize)); + }, + group(scope: string, label: string, fn: () => void) { + console.groupCollapsed(`${PREFIX} ${scope} · ${label}`); + try { + fn(); + } finally { + console.groupEnd(); + } + }, +}; diff --git a/src/plugins/built-in/aiModCreator/modRuntime.test.ts b/src/plugins/built-in/aiModCreator/modRuntime.test.ts new file mode 100644 index 00000000..072f3b35 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/modRuntime.test.ts @@ -0,0 +1,200 @@ +/** @jest-environment jsdom */ + +import { applyModRecipe, ModRuntime } from "./modRuntime"; +import type { StoredModRecipe } from "./types"; + +function recipe( + operations: StoredModRecipe["operations"], + overrides: Partial = {}, +): StoredModRecipe { + return { + schemaVersion: 1, + id: "mod-1", + name: "Test mod", + description: "Test", + enabled: true, + route: "assessments", + rootSelector: "#selected", + operations, + createdAt: 1, + updatedAt: 1, + ...overrides, + }; +} + +describe("safe AI mod runtime", () => { + beforeEach(() => { + window.location.hash = "#?page=/assessments"; + document.body.innerHTML = ` +
+

Old title

+

One old old

+
+

Outside

+ `; + }); + + it("applies the supported standard-library operations", () => { + const cleanup = applyModRecipe( + recipe([ + { + type: "setText", + selector: ":scope .title", + text: "New title", + }, + { + type: "replaceText", + selector: ":scope .description", + search: "old", + replacement: "new", + all: true, + }, + { + type: "setAttribute", + selector: ":scope", + name: "aria-label", + value: "New label", + }, + { + type: "setStyle", + selector: ":scope", + property: "border-radius", + value: "12px", + }, + { + type: "addClass", + selector: ":scope", + className: "custom-card", + }, + { + type: "hide", + selector: ":scope .description", + }, + { + type: "insertText", + selector: ":scope", + position: "append", + tag: "span", + text: "Generated note", + className: "note", + }, + ]), + document, + ); + + const selected = document.querySelector("#selected")!; + expect(selected.querySelector(".title")?.textContent).toBe("New title"); + expect(selected.querySelector(".description")?.textContent).toBe( + "One new new", + ); + expect(selected.querySelector(".description")?.style.display).toBe( + "none", + ); + expect( + selected.querySelector(".description")?.style.getPropertyPriority( + "display", + ), + ).toBe("important"); + expect(selected.getAttribute("aria-label")).toBe("New label"); + expect(selected.style.borderRadius).toBe("12px"); + expect(selected.style.getPropertyPriority("border-radius")).toBe("important"); + expect(selected.classList.contains("custom-card")).toBe(true); + expect(selected.querySelector(".note")?.textContent).toBe("Generated note"); + + cleanup(); + expect(selected.querySelector(".title")?.textContent).toBe("Old title"); + expect(selected.querySelector(".description")?.textContent).toBe( + "One old old", + ); + expect(selected.querySelector(".description")?.style.display).toBe( + "", + ); + expect(selected.getAttribute("aria-label")).toBe("Old label"); + expect(selected.style.borderRadius).toBe(""); + expect(selected.classList.contains("custom-card")).toBe(false); + expect(selected.querySelector(".note")).toBeNull(); + }); + + it("never changes nodes outside the captured root", () => { + const cleanup = applyModRecipe( + recipe([{ type: "setText", selector: ":scope #outside", text: "Changed" }]), + document, + ); + + expect(document.querySelector("#outside")?.textContent).toBe("Outside"); + cleanup(); + }); + + it("applies setStyle with important priority to beat page CSS caps", () => { + window.location.hash = "#?page=/news"; + document.body.innerHTML = ` +
+
News
+
+ `; + + const cleanup = applyModRecipe( + recipe( + [ + { + type: "setStyle", + selector: ":scope > div.home-container", + property: "max-width", + value: "100%", + }, + { + type: "setStyle", + selector: ":scope > div.home-container", + property: "width", + value: "100%", + }, + ], + { route: "news" }, + ), + document, + ); + + const container = document.querySelector(".home-container")!; + expect(container.style.getPropertyValue("max-width")).toBe("100%"); + expect(container.style.getPropertyPriority("max-width")).toBe("important"); + expect(container.style.getPropertyValue("width")).toBe("100%"); + expect(container.style.getPropertyPriority("width")).toBe("important"); + + cleanup(); + }); + + it("reconciles enabled recipes after a SPA remount and restores on stop", async () => { + jest.useFakeTimers(); + const runtime = new ModRuntime(document, () => "assessments"); + runtime.start(); + runtime.setRecipes( + recipe([{ type: "setText", selector: ":scope .title", text: "Changed" }]), + ); + expect(document.querySelector(".title")?.textContent).toBe("Changed"); + + document.querySelector("#selected")!.outerHTML = + '

Remounted

'; + await Promise.resolve(); + jest.runOnlyPendingTimers(); + expect(document.querySelector(".title")?.textContent).toBe("Changed"); + + runtime.stop(); + expect(document.querySelector(".title")?.textContent).toBe("Remounted"); + jest.useRealTimers(); + }); + + it("applies only enabled recipes matching the current route", () => { + const runtime = new ModRuntime(document, () => "courses"); + runtime.start(); + runtime.setRecipes([ + recipe([{ type: "setText", selector: ":scope .title", text: "Wrong" }]), + recipe( + [{ type: "setText", selector: ":scope .title", text: "Disabled" }], + { id: "mod-2", route: "courses", enabled: false }, + ), + ]); + + expect(document.querySelector(".title")?.textContent).toBe("Old title"); + runtime.stop(); + }); +}); diff --git a/src/plugins/built-in/aiModCreator/modRuntime.ts b/src/plugins/built-in/aiModCreator/modRuntime.ts new file mode 100644 index 00000000..59aca7d5 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/modRuntime.ts @@ -0,0 +1,228 @@ +import { validateStoredRecipes } from "./recipeSchema"; +import { + applyModStyleProperty, + restoreModStyleProperty, +} from "./modStyle"; +import type { ModOperation, StoredModRecipe } from "./types"; +type Cleanup = () => void; + +function targetsFor( + root: HTMLElement, + selector: string, +): HTMLElement[] { + if (selector === ":scope") return [root]; + try { + return [...root.querySelectorAll(selector)]; + } catch { + return []; + } +} + +function applyOperation( + root: HTMLElement, + operation: ModOperation, + modId: string, +): Cleanup[] { + const cleanups: Cleanup[] = []; + for (const element of targetsFor(root, operation.selector)) { + switch (operation.type) { + case "setText": + case "replaceText": { + const previous = element.textContent; + if (operation.type === "setText") { + element.textContent = operation.text; + } else if (operation.all) { + element.textContent = (previous ?? "").split(operation.search).join( + operation.replacement, + ); + } else { + element.textContent = (previous ?? "").replace( + operation.search, + operation.replacement, + ); + } + cleanups.push(() => { + element.textContent = previous; + }); + break; + } + case "setAttribute": { + const hadAttribute = element.hasAttribute(operation.name); + const previous = element.getAttribute(operation.name); + element.setAttribute(operation.name, operation.value); + cleanups.push(() => { + if (hadAttribute && previous !== null) { + element.setAttribute(operation.name, previous); + } else { + element.removeAttribute(operation.name); + } + }); + break; + } + case "setStyle": { + const important = operation.important !== false; + const snapshot = applyModStyleProperty( + element, + operation.property, + operation.value, + important, + ); + cleanups.push(() => { + restoreModStyleProperty(element, operation.property, snapshot); + }); + break; + } + case "addClass": + case "removeClass": { + const hadClass = element.classList.contains(operation.className); + element.classList.toggle( + operation.className, + operation.type === "addClass", + ); + cleanups.push(() => { + element.classList.toggle(operation.className, hadClass); + }); + break; + } + case "hide": + case "show": { + const previous = element.style.getPropertyValue("display"); + const priority = element.style.getPropertyPriority("display"); + if (operation.type === "hide") { + element.style.setProperty("display", "none", "important"); + } else { + element.style.removeProperty("display"); + } + cleanups.push(() => { + if (previous) { + element.style.setProperty("display", previous, priority); + } else { + element.style.removeProperty("display"); + } + }); + break; + } + case "insertText": { + if ( + element === root && + (operation.position === "before" || operation.position === "after") + ) { + break; + } + const inserted = document.createElement(operation.tag); + inserted.textContent = operation.text; + inserted.dataset.bsplusAiMod = modId; + if (operation.className) inserted.classList.add(operation.className); + if (operation.position === "before") { + element.before(inserted); + } else if (operation.position === "after") { + element.after(inserted); + } else if (operation.position === "prepend") { + element.prepend(inserted); + } else { + element.append(inserted); + } + cleanups.push(() => inserted.remove()); + break; + } + } + } + return cleanups; +} + +export function applyModRecipe( + input: StoredModRecipe, + documentRef: Document = document, +): Cleanup { + const [recipe] = validateStoredRecipes([input]); + let root: HTMLElement | null = null; + try { + root = documentRef.querySelector(recipe.rootSelector); + } catch { + return () => {}; + } + if (!root) return () => {}; + + const cleanups = recipe.operations.flatMap((operation) => + applyOperation(root!, operation, recipe.id), + ); + return () => { + for (const cleanup of [...cleanups].reverse()) cleanup(); + }; +} + +export class ModRuntime { + private recipes: StoredModRecipe[] = []; + private cleanups: Cleanup[] = []; + private observer: MutationObserver | null = null; + private reconcileTimer: ReturnType | null = null; + private running = false; + + constructor( + private readonly documentRef: Document = document, + private readonly getRoute: () => string = () => { + const route = window.location.hash.split("?page=/")[1] ?? ""; + return route.split(/[/?#]/)[0]; + }, + ) {} + + start(): void { + if (this.running) return; + this.running = true; + this.observer = new MutationObserver(() => this.scheduleReconcile()); + this.observe(); + window.addEventListener("hashchange", this.handleRouteChange); + this.reconcile(); + } + + setRecipes(input: StoredModRecipe | StoredModRecipe[]): void { + this.recipes = validateStoredRecipes( + Array.isArray(input) ? input : [input], + ); + if (this.running) this.reconcile(); + } + + stop(): void { + this.running = false; + if (this.reconcileTimer) clearTimeout(this.reconcileTimer); + this.reconcileTimer = null; + this.observer?.disconnect(); + this.observer = null; + window.removeEventListener("hashchange", this.handleRouteChange); + this.clearAppliedMods(); + } + + private readonly handleRouteChange = () => this.scheduleReconcile(); + + private observe(): void { + if (!this.observer || !this.documentRef.body) return; + this.observer.observe(this.documentRef.body, { + childList: true, + subtree: true, + }); + } + + private scheduleReconcile(): void { + if (!this.running || this.reconcileTimer) return; + this.reconcileTimer = setTimeout(() => { + this.reconcileTimer = null; + this.reconcile(); + }, 40); + } + + private clearAppliedMods(): void { + for (const cleanup of [...this.cleanups].reverse()) cleanup(); + this.cleanups = []; + } + + private reconcile(): void { + if (!this.running) return; + this.observer?.disconnect(); + this.clearAppliedMods(); + const route = this.getRoute(); + this.cleanups = this.recipes + .filter((recipe) => recipe.enabled && recipe.route === route) + .map((recipe) => applyModRecipe(recipe, this.documentRef)); + this.observe(); + } +} diff --git a/src/plugins/built-in/aiModCreator/modStyle.test.ts b/src/plugins/built-in/aiModCreator/modStyle.test.ts new file mode 100644 index 00000000..d974cb06 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/modStyle.test.ts @@ -0,0 +1,23 @@ +/** @jest-environment jsdom */ + +import { + applyModStyleProperty, + restoreModStyleProperty, + stripStyleImportantSuffix, +} from "./modStyle"; + +describe("modStyle", () => { + it("strips trailing !important from values", () => { + expect(stripStyleImportantSuffix("100% !important")).toBe("100%"); + expect(stripStyleImportantSuffix("100% !IMPORTANT")).toBe("100%"); + }); + + it("applies styles with important priority by default", () => { + const element = document.createElement("div"); + const snapshot = applyModStyleProperty(element, "max-width", "100%"); + expect(element.style.getPropertyValue("max-width")).toBe("100%"); + expect(element.style.getPropertyPriority("max-width")).toBe("important"); + restoreModStyleProperty(element, "max-width", snapshot); + expect(element.style.getPropertyValue("max-width")).toBe(""); + }); +}); diff --git a/src/plugins/built-in/aiModCreator/modStyle.ts b/src/plugins/built-in/aiModCreator/modStyle.ts new file mode 100644 index 00000000..7720fb88 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/modStyle.ts @@ -0,0 +1,37 @@ +/** Apply mod styles with priority over BetterSEQTA page CSS. */ +export function stripStyleImportantSuffix(value: string): string { + return value.replace(/\s*!important\s*$/i, "").trim(); +} + +export interface ModStyleSnapshot { + previous: string; + priority: string; +} + +export function applyModStyleProperty( + element: HTMLElement, + property: string, + value: string, + important = true, +): ModStyleSnapshot { + const previous = element.style.getPropertyValue(property); + const priority = element.style.getPropertyPriority(property); + element.style.setProperty( + property, + stripStyleImportantSuffix(value), + important ? "important" : "", + ); + return { previous, priority }; +} + +export function restoreModStyleProperty( + element: HTMLElement, + property: string, + snapshot: ModStyleSnapshot, +): void { + if (snapshot.previous) { + element.style.setProperty(property, snapshot.previous, snapshot.priority); + } else { + element.style.removeProperty(property); + } +} diff --git a/src/plugins/built-in/aiModCreator/models.ts b/src/plugins/built-in/aiModCreator/models.ts new file mode 100644 index 00000000..c3deb407 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/models.ts @@ -0,0 +1,61 @@ +export const DEFAULT_OPENROUTER_MODEL_ID = "minimax/minimax-m2.7:free"; + +export interface AiModModelOption { + id: string; + label: string; + description: string; + tier: "free" | "paid"; +} + +export const AI_MOD_MODEL_OPTIONS: readonly AiModModelOption[] = [ + { + id: "minimax/minimax-m2.7:free", + label: "MiniMax M2.7 (free)", + description: + "Best free option for agentic DOM mods. Separate provider rate limits apply.", + tier: "free", + }, + { + id: "minimax/minimax-m3:free", + label: "MiniMax M3 (free)", + description: "Alternate free MiniMax with GMICloud rate limits.", + tier: "free", + }, + { + id: "google/gemma-3-27b-it:free", + label: "Gemma 3 27B (free)", + description: "Free Google model; useful when MiniMax free tiers are busy.", + tier: "free", + }, + { + id: "meta-llama/llama-3.3-70b-instruct:free", + label: "Llama 3.3 70B (free)", + description: "Free Meta model with broader availability.", + tier: "free", + }, + { + id: "minimax/minimax-m3", + label: "MiniMax M3 (paid)", + description: "Paid tier with much higher rate limits.", + tier: "paid", + }, +] as const; + +export const ALLOWED_OPENROUTER_MODEL_IDS = new Set( + AI_MOD_MODEL_OPTIONS.map((option) => option.id), +); + +export function validateModelId(value: unknown): string { + if (typeof value !== "string") { + throw new Error("Model id is required"); + } + const modelId = value.trim(); + if (!ALLOWED_OPENROUTER_MODEL_IDS.has(modelId)) { + throw new Error("Unsupported OpenRouter model"); + } + return modelId; +} + +export function getModelOption(modelId: string): AiModModelOption | undefined { + return AI_MOD_MODEL_OPTIONS.find((option) => option.id === modelId); +} diff --git a/src/plugins/built-in/aiModCreator/pageContext.test.ts b/src/plugins/built-in/aiModCreator/pageContext.test.ts new file mode 100644 index 00000000..b523cc89 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/pageContext.test.ts @@ -0,0 +1,234 @@ +/** @jest-environment jsdom */ + +import { buildSelectedElementContext } from "./pageContext"; + +describe("selected element context", () => { + it("sends only the selected subtree and redacts active content and values", () => { + document.body.innerHTML = ` +
Never include me
+
+ + Assessment details + +

Selected text

+
+ `; + const selected = document.querySelector("#selected")!; + + const context = buildSelectedElementContext(selected, { + route: "assessments", + rootSelector: "#selected", + request: "Make this clearer", + userContext: "This is an assessment card.", + }); + + expect(context.selectedHtml).toContain("Selected text"); + expect(context.selectedHtml).not.toContain("Never include me"); + expect(context.selectedHtml).not.toContain("student@example.test"); + expect(context.selectedHtml).not.toContain("onclick"); + expect(context.selectedHtml).not.toContain("data-session"); + expect(context.selectedHtml).not.toContain(" { + document.body.innerHTML = ` +
+
+
+
+

Y11HA

+

Jaxon Lewis-Wilson

+
+

15845 // 33804833

+
+
+
+ `; + const selected = document.querySelector(".userInfoText")!; + + const context = buildSelectedElementContext(selected, { + route: "welcome", + rootSelector: ".userInfoText", + request: "Move house next to ID", + userContext: "", + }); + + expect(context.ancestorHtml).toContain("userInfo"); + expect(context.selectedHtml).toContain('display: flex'); + expect(context.domCatalog).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + tag: "p", + classes: ["userInfoCode"], + directText: "15845 // 33804833", + }), + expect.objectContaining({ + tag: "p", + classes: expect.arrayContaining(["userInfohouse", "userInfoCode"]), + directText: "Y11HA", + }), + ]), + ); + expect( + context.domCatalog.find((entry) => entry.selector === ":scope")?.layout, + ).toMatchObject({ + display: "flex", + flexDirection: "column", + alignItems: "flex-end", + }); + }); + + it("caps all user-controlled fields", () => { + const selected = document.createElement("div"); + selected.textContent = "x".repeat(30_000); + document.body.appendChild(selected); + + const context = buildSelectedElementContext(selected, { + route: "r".repeat(2_000), + rootSelector: "#selected", + request: "q".repeat(5_000), + userContext: "c".repeat(8_000), + }); + + expect(context.selectedHtml.length).toBeLessThanOrEqual(24_000); + expect(context.route.length).toBeLessThanOrEqual(256); + expect(context.request.length).toBeLessThanOrEqual(2_000); + expect(context.userContext.length).toBeLessThanOrEqual(4_000); + expect(context.domCatalog.length).toBeLessThanOrEqual(100); + }); + + it("captures only a small allowlisted computed-style summary", () => { + const selected = document.createElement("div"); + selected.style.color = "rgb(1, 2, 3)"; + selected.style.backgroundColor = "rgb(4, 5, 6)"; + selected.style.backgroundImage = "url(https://example.test/pixel)"; + document.body.appendChild(selected); + + const context = buildSelectedElementContext(selected, { + route: "", + rootSelector: "div", + request: "Restyle", + userContext: "", + }); + + expect(context.computedStyle).toMatchObject({ + color: "rgb(1, 2, 3)", + backgroundColor: "rgb(4, 5, 6)", + }); + expect(context.computedStyle).not.toHaveProperty("backgroundImage"); + }); + + it("includes parent chain summaries for placement context", () => { + document.body.innerHTML = ` +
+
+
+

15845

+
+
+
+ `; + const selected = document.querySelector(".userInfoText")!; + + const context = buildSelectedElementContext(selected, { + route: "welcome", + rootSelector: ".userInfoText", + request: "Reorder items", + userContext: "", + }); + + expect(context.parentChain).toEqual([ + expect.objectContaining({ + tag: "div", + classes: ["userInfo"], + layout: expect.objectContaining({ display: "flex" }), + }), + expect.objectContaining({ + tag: "div", + classes: ["titlebar"], + layout: expect.objectContaining({ + display: "flex", + alignItems: "center", + }), + }), + ]); + expect(context.structuralHints).toMatchObject({ + hasTable: false, + hasList: false, + primaryClasses: ["userInfoText"], + }); + }); + + it("includes table and list structure counts in root catalog and hints", () => { + document.body.innerHTML = ` + + + + +
NameGradeDue
EssayAMon
QuizBTue
+ `; + const table = document.querySelector(".assessmentTable")!; + + const tableContext = buildSelectedElementContext(table, { + route: "assessments", + rootSelector: ".assessmentTable", + request: "Highlight header row", + userContext: "", + }); + + expect( + tableContext.domCatalog.find((entry) => entry.selector === ":scope"), + ).toMatchObject({ + rowCount: 3, + columnCount: 3, + }); + expect(tableContext.structuralHints).toMatchObject({ + hasTable: true, + hasList: false, + rowCount: 3, + columnCount: 3, + primaryClasses: ["assessmentTable"], + }); + + document.body.innerHTML = ` +
    +
  • Task one
  • +
  • Task two
  • +
  • Task three
  • +
+ `; + const list = document.querySelector(".taskList")!; + + const listContext = buildSelectedElementContext(list, { + route: "tasks", + rootSelector: ".taskList", + request: "Bold first item", + userContext: "", + }); + + expect( + listContext.domCatalog.find((entry) => entry.selector === ":scope"), + ).toMatchObject({ + itemCount: 3, + }); + expect(listContext.structuralHints).toMatchObject({ + hasTable: false, + hasList: true, + itemCount: 3, + primaryClasses: ["taskList"], + }); + }); +}); diff --git a/src/plugins/built-in/aiModCreator/pageContext.ts b/src/plugins/built-in/aiModCreator/pageContext.ts new file mode 100644 index 00000000..94c6b945 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/pageContext.ts @@ -0,0 +1,291 @@ +import { buildScopeRelativeSelector } from "./selection"; +import type { + DomElementSummary, + ParentChainSummary, + SelectedElementContext, + StructuralHints, +} from "./types"; + +const HTML_LIMIT = 24_000; +const ANCESTOR_HTML_LIMIT = 6_000; +const REQUEST_LIMIT = 2_000; +const USER_CONTEXT_LIMIT = 4_000; +const ROUTE_LIMIT = 256; +const DOM_CATALOG_LIMIT = 100; +const DIRECT_TEXT_LIMIT = 120; +const PARENT_CHAIN_LIMIT = 3; +const CLASS_LIMIT = 8; + +const COMPUTED_STYLE_PROPERTIES = [ + ["color", "color"], + ["backgroundColor", "background-color"], + ["display", "display"], + ["flexDirection", "flex-direction"], + ["alignItems", "align-items"], + ["justifyContent", "justify-content"], + ["gap", "gap"], + ["flexWrap", "flex-wrap"], + ["fontSize", "font-size"], + ["fontWeight", "font-weight"], + ["padding", "padding"], + ["margin", "margin"], + ["border", "border"], + ["borderRadius", "border-radius"], + ["width", "width"], + ["height", "height"], + ["textAlign", "text-align"], + ["opacity", "opacity"], +] as const; + +const ALLOWED_INLINE_STYLE = + /^(display|flex|align-items|justify-content|gap|flex-direction|flex-wrap|text-align|padding|margin|border-radius|opacity|font-size|font-weight|width|height|background-color|color)$/i; + +function cap(value: string, maxLength: number): string { + return value.trim().slice(0, maxLength); +} + +function sanitizeInlineStyle(value: string): string { + return value + .split(";") + .map((part) => part.trim()) + .filter((part) => { + if (!part.includes(":")) return false; + const name = part.split(":")[0]?.trim() ?? ""; + return ( + ALLOWED_INLINE_STYLE.test(name) && + !/url\s*\(|expression\s*\(|javascript\s*:/i.test(part) + ); + }) + .join("; "); +} + +function sanitizeClone(element: HTMLElement): HTMLElement { + const clone = element.cloneNode(true) as HTMLElement; + clone + .querySelectorAll( + "script,style,noscript,iframe,object,embed,link,meta,template", + ) + .forEach((node) => node.remove()); + + const nodes = [clone, ...clone.querySelectorAll("*")]; + for (const node of nodes) { + for (const attribute of [...node.attributes]) { + const name = attribute.name.toLowerCase(); + if ( + name.startsWith("on") || + name.startsWith("data-") || + [ + "action", + "checked", + "formaction", + "href", + "selected", + "src", + "srcset", + "value", + ].includes(name) + ) { + node.removeAttribute(attribute.name); + continue; + } + if (name === "style") { + const sanitizedStyle = sanitizeInlineStyle(attribute.value); + if (sanitizedStyle) node.setAttribute("style", sanitizedStyle); + else node.removeAttribute("style"); + } + } + } + return clone; +} + +function computedStyleSummary(element: HTMLElement): Record { + const style = getComputedStyle(element); + return Object.fromEntries( + COMPUTED_STYLE_PROPERTIES.map(([outputName, cssName]) => [ + outputName, + style.getPropertyValue(cssName) || + (style as unknown as Record)[outputName] || + "", + ]).filter(([, value]) => value.length > 0), + ); +} + +function directText(element: HTMLElement): string | undefined { + const chunks: string[] = []; + for (const node of element.childNodes) { + if (node.nodeType === Node.TEXT_NODE) { + const text = node.textContent?.replace(/\s+/g, " ").trim() ?? ""; + if (text) chunks.push(text); + } + } + if (chunks.length === 0) return undefined; + return cap(chunks.join(" "), DIRECT_TEXT_LIMIT); +} + +function classSummary(element: HTMLElement): string[] { + return [...element.classList].slice(0, CLASS_LIMIT); +} + +function findTable(element: HTMLElement): HTMLTableElement | null { + if (element instanceof HTMLTableElement) return element; + return element.querySelector("table"); +} + +function findList(element: HTMLElement): HTMLUListElement | HTMLOListElement | null { + if (element instanceof HTMLUListElement || element instanceof HTMLOListElement) { + return element; + } + return element.querySelector("ul, ol"); +} + +function tableMetrics( + element: HTMLElement, +): { rowCount: number; columnCount: number } | null { + const table = findTable(element); + if (!table) return null; + + const rows = [...table.querySelectorAll("tr")]; + const columnCount = rows.reduce((max, row) => { + const cells = row.querySelectorAll("td, th").length; + return Math.max(max, cells); + }, 0); + + return { rowCount: rows.length, columnCount }; +} + +function listMetrics(element: HTMLElement): { itemCount: number } | null { + const list = findList(element); + if (!list) return null; + return { itemCount: list.querySelectorAll(":scope > li").length }; +} + +function buildStructuralHints(element: HTMLElement): StructuralHints { + const table = tableMetrics(element); + const list = listMetrics(element); + + return { + hasTable: table !== null, + hasList: list !== null, + ...(table ? table : {}), + ...(list ? list : {}), + primaryClasses: classSummary(element), + }; +} + +function buildParentChain(element: HTMLElement): ParentChainSummary[] { + const chain: ParentChainSummary[] = []; + let current = element.parentElement; + + while ( + current && + current !== document.body && + current !== document.documentElement && + chain.length < PARENT_CHAIN_LIMIT + ) { + chain.push({ + tag: current.tagName.toLowerCase(), + classes: classSummary(current), + layout: computedStyleSummary(current), + }); + current = current.parentElement; + } + + return chain; +} + +function rootStructureSummary( + root: HTMLElement, +): Pick { + const table = tableMetrics(root); + const list = listMetrics(root); + return { + ...(table ?? {}), + ...(list ?? {}), + }; +} + +function buildDomCatalog(root: HTMLElement): DomElementSummary[] { + const nodes = [root, ...root.querySelectorAll("*")].slice( + 0, + DOM_CATALOG_LIMIT, + ); + + return nodes.map((node) => { + const parent = node.parentElement; + const parentSelector = + parent && root.contains(parent) + ? buildScopeRelativeSelector(root, parent) + : node === root + ? null + : ":scope"; + const siblings = parent + ? [...parent.children].filter((child) => child instanceof HTMLElement) + : [root]; + + const summary: DomElementSummary = { + selector: buildScopeRelativeSelector(root, node), + tag: node.tagName.toLowerCase(), + classes: classSummary(node), + ...(directText(node) ? { directText: directText(node) } : {}), + parentSelector, + siblingIndex: siblings.indexOf(node), + siblingCount: siblings.length, + layout: computedStyleSummary(node), + }; + + if (node === root) { + Object.assign(summary, rootStructureSummary(root)); + } + + return summary; + }); +} + +function buildAncestorContext(root: HTMLElement): { ancestorHtml?: string } { + const parent = root.parentElement; + if ( + !parent || + parent === document.body || + parent === document.documentElement + ) { + return {}; + } + + return { + ancestorHtml: sanitizeClone(parent).outerHTML.slice(0, ANCESTOR_HTML_LIMIT), + }; +} + +export function buildSelectedElementContext( + element: HTMLElement, + input: { + route: string; + rootSelector: string; + request: string; + userContext: string; + }, +): SelectedElementContext { + const rect = element.getBoundingClientRect(); + const sanitized = sanitizeClone(element); + const ancestor = buildAncestorContext(element); + const parentChain = buildParentChain(element); + const structuralHints = buildStructuralHints(element); + + return { + route: cap(input.route, ROUTE_LIMIT), + rootSelector: cap(input.rootSelector, 1_000), + request: cap(input.request, REQUEST_LIMIT), + userContext: cap(input.userContext, USER_CONTEXT_LIMIT), + selectedHtml: sanitized.outerHTML.slice(0, HTML_LIMIT), + domCatalog: buildDomCatalog(element), + ...(ancestor.ancestorHtml ? { ancestorHtml: ancestor.ancestorHtml } : {}), + ...(parentChain.length > 0 ? { parentChain } : {}), + structuralHints, + tagName: element.tagName.toLowerCase(), + dimensions: { + width: Math.round(rect.width), + height: Math.round(rect.height), + }, + computedStyle: computedStyleSummary(element), + }; +} diff --git a/src/plugins/built-in/aiModCreator/prompt.ts b/src/plugins/built-in/aiModCreator/prompt.ts new file mode 100644 index 00000000..e605b617 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/prompt.ts @@ -0,0 +1,175 @@ +import { + SAFE_ATTRIBUTE_NAMES, + SAFE_INSERT_POSITIONS, + SAFE_INSERT_TAGS, + SAFE_STYLE_PROPERTIES, +} from "./recipeSchema"; +import type { SelectedElementContext } from "./types"; + +const operationSchemas = [ + { + type: "object", + additionalProperties: false, + required: ["type", "selector", "text"], + properties: { + type: { const: "setText" }, + selector: { type: "string" }, + text: { type: "string" }, + }, + }, + { + type: "object", + additionalProperties: false, + required: ["type", "selector", "search", "replacement"], + properties: { + type: { const: "replaceText" }, + selector: { type: "string" }, + search: { type: "string" }, + replacement: { type: "string" }, + all: { type: "boolean" }, + }, + }, + { + type: "object", + additionalProperties: false, + required: ["type", "selector", "name", "value"], + properties: { + type: { const: "setAttribute" }, + selector: { type: "string" }, + name: { type: "string", enum: SAFE_ATTRIBUTE_NAMES }, + value: { type: "string" }, + }, + }, + { + type: "object", + additionalProperties: false, + required: ["type", "selector", "property", "value"], + properties: { + type: { const: "setStyle" }, + selector: { type: "string" }, + property: { type: "string", enum: SAFE_STYLE_PROPERTIES }, + value: { type: "string" }, + }, + }, + ...(["addClass", "removeClass"] as const).map((type) => ({ + type: "object", + additionalProperties: false, + required: ["type", "selector", "className"], + properties: { + type: { const: type }, + selector: { type: "string" }, + className: { type: "string" }, + }, + })), + ...(["hide", "show"] as const).map((type) => ({ + type: "object", + additionalProperties: false, + required: ["type", "selector"], + properties: { + type: { const: type }, + selector: { type: "string" }, + }, + })), + { + type: "object", + additionalProperties: false, + required: ["type", "selector", "position", "tag", "text"], + properties: { + type: { const: "insertText" }, + selector: { type: "string" }, + position: { type: "string", enum: SAFE_INSERT_POSITIONS }, + tag: { type: "string", enum: SAFE_INSERT_TAGS }, + text: { type: "string" }, + className: { type: "string" }, + }, + }, +]; + +export const AI_MOD_RESPONSE_JSON_SCHEMA = { + type: "object", + additionalProperties: false, + required: ["name", "description", "operations"], + properties: { + name: { type: "string", minLength: 1, maxLength: 120 }, + description: { type: "string", maxLength: 500 }, + operations: { + type: "array", + minItems: 0, + maxItems: 30, + items: { oneOf: operationSchemas }, + }, + advancedScript: { + type: "string", + minLength: 1, + maxLength: 20_000, + }, + }, +} as const; + +export function buildAiModMessages(context: SelectedElementContext) { + const allowedStyleProperties = SAFE_STYLE_PROPERTIES.join(", "); + + return [ + { + role: "system", + content: `You create advanced BetterSEQTA+ DOM mods. +Return only a valid JSON object with keys: name, description, operations, and optionally advancedScript. +Each operation must be an object with a string "type" field and a "selector" field. +Supported type values: setText, replaceText, setAttribute, setStyle, addClass, removeClass, hide, show, insertText. +operations may be an empty array when advancedScript alone implements the requested change. + +setStyle rules: +- Use kebab-case property names only (e.g. "flex-wrap", not "flexWrap"). +- Allowed properties: ${allowedStyleProperties} +- Do not use background-image, transform, animation, or any property not in the allowed list. +- setStyle operations automatically override BetterSEQTA page CSS (including rules with !important). Target constraining ancestors, not only leaf nodes — e.g. for full-width news cards set max-width, width, margin, and padding on :scope > div.home-container (BS+ caps it at 1050px), not only on .NewsArticle children. + +Example (full-width layout — override BS+ container cap): +{"name":"Full-width news","description":"Expands home container to viewport width","operations":[{"type":"setStyle","selector":":scope > div.home-container","property":"max-width","value":"100%"},{"type":"setStyle","selector":":scope > div.home-container","property":"width","value":"100%"},{"type":"setStyle","selector":":scope > div.home-container","property":"margin-left","value":"0"},{"type":"setStyle","selector":":scope > div.home-container","property":"margin-right","value":"0"}]} + +Example (simple style): +{"name":"Rounded card","description":"Adds rounded corners","operations":[{"type":"setStyle","selector":":scope","property":"border-radius","value":"12px"}]} + +Example (flex row layout): +{"name":"Flex toolbar","description":"Lays out children in a horizontal row","operations":[{"type":"setStyle","selector":":scope","property":"display","value":"flex"},{"type":"setStyle","selector":":scope","property":"align-items","value":"center"},{"type":"setStyle","selector":":scope","property":"gap","value":"8px"},{"type":"setStyle","selector":":scope","property":"flex-wrap","value":"wrap"}]} + +Example (CSS grid layout): +{"name":"Grid cards","description":"Displays children in a responsive grid","operations":[{"type":"setStyle","selector":":scope","property":"display","value":"grid"},{"type":"setStyle","selector":":scope","property":"grid-template-columns","value":"repeat(auto-fill, minmax(200px, 1fr))"},{"type":"setStyle","selector":":scope","property":"gap","value":"12px"}]} + +Example (table to grid — convert a table container to grid while keeping child cells): +{"name":"Table as grid","description":"Replaces table layout with CSS grid on the wrapper","operations":[{"type":"setStyle","selector":":scope","property":"display","value":"grid"},{"type":"setStyle","selector":":scope","property":"grid-template-columns","value":"repeat(3, 1fr)"},{"type":"setStyle","selector":":scope","property":"gap","value":"8px"},{"type":"setStyle","selector":":scope tr","property":"display","value":"contents"},{"type":"setStyle","selector":":scope td, :scope th","property":"display","value":"block"}]} +For table-to-grid mods, target the table or tbody with display:grid and use display:contents on tr rows so td/th become direct grid items. Use advancedScript when row/column reordering or cell merging is required. + +Advanced-only example: +{"name":"Reorder header","description":"Moves child nodes","operations":[],"advancedScript":"return () => {};"} +Every selector must be ":scope" or begin with ":scope " / ":scope>" so it stays inside the user's selected root. +Use domCatalog for exact relative selectors, sibling order, and computed layout on each node. +Use parentChain to understand how the selected root is nested inside parent containers. +Use structuralHints (hasTable, rowCount, columnCount, hasList, itemCount, primaryClasses) for table/list/grid transforms. +Use ancestorHtml to see how the selected root sits inside its parent container. +Use selectedHtml for full subtree markup including preserved inline layout styles. +Select the smallest page area that actually contains the elements you need to change. Do not select BetterSEQTA+ overlay UI; select the underlying SEQTA content instead. +When moving elements, preserve BetterSEQTA+ styling: prefer flex rows with align-items:center, gap, inline-block badges, var(--text-primary), var(--auto-background), and transparent/theme borders over solid black boxes. +If required elements are missing inside root, throw an Error explaining which selector failed. +Use operations for simple reversible changes and advancedScript for richer JavaScript behavior. +advancedScript runs with root, bsplus, and shorthand helpers select(selector) / selectAll(selector) in scope. +The helper library provides select(selector), selectAll(selector), setText(element,text), setStyle(element,property,value), setAttribute(element,name,value), create(tag,text,parent), on(element,event,handler), observe(element,callback,options), and onCleanup(callback). +You may call select() directly or use bsplus.select(). +The advancedScript body must return a cleanup function and should use bsplus helpers so disabling the mod restores the page. +Never use network APIs, extension APIs, browser storage, cookies, navigation, raw HTML markup, eval, dynamic imports, workers, programmatic clicks/submits, src/href assignments, or unbounded loops. +You may clear a container with element.innerHTML = '' before moving existing nodes, but never assign HTML strings or use outerHTML/insertAdjacentHTML. +Prefer appendChild, insertBefore, replaceChildren, cloneNode, remove, and textContent for DOM changes. +Direct DOM APIs are allowed for advanced layout and interaction work, but keep every change within root and register cleanup. +Prefer the smallest set of reversible operations. Do not invent page content that is not requested. +For insertText, "before" and "after" may only target descendants, not :scope itself.`, + }, + { + role: "user", + content: `Create a mod for this explicitly selected page area:\n${JSON.stringify( + context, + null, + 2, + )}`, + }, + ] as const; +} diff --git a/src/plugins/built-in/aiModCreator/recipeSchema.test.ts b/src/plugins/built-in/aiModCreator/recipeSchema.test.ts new file mode 100644 index 00000000..2e68c1b4 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/recipeSchema.test.ts @@ -0,0 +1,267 @@ +import { + createStoredRecipe, + extractJsonFromModelText, + normalizeStyleProperty, + parseGeneratedModDraft, + parseStoredRecipes, +} from "./recipeSchema"; + +describe("AI mod recipe validation", () => { + const validDraft = { + name: "Calmer assessment card", + description: "Makes the selected card easier to scan.", + operations: [ + { + type: "setStyle", + selector: ":scope", + property: "border-radius", + value: "16px", + }, + { + type: "setText", + selector: ":scope .title", + text: "Upcoming assessment", + }, + ], + }; + + it("accepts a safe generated draft and creates a stored recipe", () => { + const draft = parseGeneratedModDraft(JSON.stringify(validDraft)); + const recipe = createStoredRecipe(draft, { + rootSelector: "#assessment-42", + route: "assessments", + now: 1_700_000_000_000, + id: "mod-1", + }); + + expect(recipe).toMatchObject({ + schemaVersion: 1, + id: "mod-1", + enabled: false, + rootSelector: "#assessment-42", + route: "assessments", + name: validDraft.name, + createdAt: 1_700_000_000_000, + }); + }); + + it.each([ + { + label: "script-like attribute", + operation: { + type: "setAttribute", + selector: ":scope", + name: "onclick", + value: "alert(1)", + }, + }, + { + label: "network-capable CSS", + operation: { + type: "setStyle", + selector: ":scope", + property: "background-image", + value: "url(https://attacker.invalid/pixel)", + }, + }, + { + label: "selector escaping the selected root", + operation: { + type: "hide", + selector: "body", + }, + }, + { + label: "raw executable operation", + operation: { + type: "javascript", + code: "document.cookie", + }, + }, + ])("rejects $label", ({ operation }) => { + expect(() => + parseGeneratedModDraft( + JSON.stringify({ + ...validDraft, + operations: [operation], + }), + ), + ).toThrow(); + }); + + it("extracts JSON from fenced model output", () => { + const json = JSON.stringify(validDraft); + expect(parseGeneratedModDraft(`\`\`\`json\n${json}\n\`\`\``)).toMatchObject({ + name: validDraft.name, + }); + expect(extractJsonFromModelText(`Here is the mod:\n${json}`)).toBe(json); + }); + + it("normalizes common model operation shapes", () => { + expect( + parseGeneratedModDraft( + JSON.stringify({ + name: "Aliased mod", + description: "Uses alternate field names", + operations: [ + { + setStyle: { + target: ":scope", + styleProperty: "border-radius", + styleValue: "12px", + }, + }, + { + action: "hide", + element: ":scope .meta", + }, + ], + }), + ), + ).toMatchObject({ + name: "Aliased mod", + operations: [ + { + type: "setStyle", + selector: ":scope", + property: "border-radius", + value: "12px", + }, + { type: "hide", selector: ":scope .meta" }, + ], + }); + }); + + it.each([ + ["flexWrap", "flex-wrap"], + ["alignItems", "align-items"], + ["gridTemplateColumns", "grid-template-columns"], + ["flexDirection", "flex-direction"], + ["overflowX", "overflow-x"], + ["zIndex", "z-index"], + ["whiteSpace", "white-space"], + ["border-radius", "border-radius"], + ])("normalizes style property %s to %s", (input, expected) => { + expect(normalizeStyleProperty(input)).toBe(expected); + }); + + it("accepts camelCase style properties from the model", () => { + expect( + parseGeneratedModDraft( + JSON.stringify({ + name: "Flex layout", + description: "Uses camelCase property names", + operations: [ + { + type: "setStyle", + selector: ":scope", + property: "flexWrap", + value: "wrap", + }, + { + type: "setStyle", + selector: ":scope", + property: "alignItems", + value: "center", + }, + ], + }), + ), + ).toMatchObject({ + operations: [ + { type: "setStyle", property: "flex-wrap", value: "wrap" }, + { type: "setStyle", property: "align-items", value: "center" }, + ], + }); + }); + + it("accepts newly allowed layout style properties", () => { + expect( + parseGeneratedModDraft( + JSON.stringify({ + name: "Grid layout", + description: "CSS grid on selected root", + operations: [ + { + type: "setStyle", + selector: ":scope", + property: "display", + value: "grid", + }, + { + type: "setStyle", + selector: ":scope", + property: "grid-template-columns", + value: "repeat(3, 1fr)", + }, + ], + }), + ).operations, + ).toHaveLength(2); + }); + + it("accepts advancedScript-only mods with no declarative operations", () => { + const draft = parseGeneratedModDraft( + JSON.stringify({ + name: "House next to ID", + description: "Moves house info beside the user ID", + operations: [], + advancedScript: + "const house = bsplus.select(':scope .userInfohouse'); return () => {};", + }), + ); + + expect(draft.operations).toEqual([]); + expect(draft.advancedScript).toContain("bsplus.select"); + }); + + it("rejects mods with neither operations nor advancedScript", () => { + expect(() => + parseGeneratedModDraft( + JSON.stringify({ + name: "Empty mod", + description: "Does nothing", + operations: [], + }), + ), + ).toThrow("at least one operation or an advancedScript"); + }); + + it("rejects oversized or non-JSON model output", () => { + expect(() => parseGeneratedModDraft("not json")).toThrow(); + expect(() => + parseGeneratedModDraft( + JSON.stringify({ + ...validDraft, + name: "x".repeat(121), + }), + ), + ).toThrow(); + }); + + it("validates every imported recipe before returning any", () => { + const recipe = createStoredRecipe( + parseGeneratedModDraft(JSON.stringify(validDraft)), + { + rootSelector: "#assessment-42", + route: "assessments", + now: 1, + id: "mod-1", + }, + ); + + expect(parseStoredRecipes(JSON.stringify([recipe]))).toEqual([recipe]); + expect(() => + parseStoredRecipes( + JSON.stringify([ + recipe, + { + ...recipe, + id: "bad", + operations: [{ type: "hide", selector: "html" }], + }, + ]), + ), + ).toThrow(); + }); +}); diff --git a/src/plugins/built-in/aiModCreator/recipeSchema.ts b/src/plugins/built-in/aiModCreator/recipeSchema.ts new file mode 100644 index 00000000..e12f3f14 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/recipeSchema.ts @@ -0,0 +1,666 @@ +import { + AI_MOD_SCHEMA_VERSION, + type GeneratedModDraft, + type ModOperation, + type SafeAttributeName, + type SafeStyleProperty, + type StoredModRecipe, +} from "./types"; +import { assertAdvancedScriptSafe } from "./scriptSafety"; +import { aiModLog } from "./logger"; +import { stripStyleImportantSuffix } from "./modStyle"; + +export const SAFE_STYLE_PROPERTIES: readonly SafeStyleProperty[] = [ + "align-items", + "align-self", + "aspect-ratio", + "background", + "background-color", + "border", + "border-color", + "border-radius", + "border-style", + "border-width", + "bottom", + "box-shadow", + "color", + "cursor", + "display", + "flex", + "flex-direction", + "flex-grow", + "flex-shrink", + "flex-wrap", + "font-size", + "font-weight", + "gap", + "grid-template-columns", + "height", + "justify-content", + "left", + "letter-spacing", + "line-height", + "margin", + "margin-bottom", + "margin-left", + "margin-right", + "margin-top", + "max-height", + "max-width", + "min-height", + "min-width", + "object-fit", + "opacity", + "order", + "overflow", + "overflow-x", + "overflow-y", + "padding", + "padding-bottom", + "padding-left", + "padding-right", + "padding-top", + "position", + "right", + "text-align", + "text-decoration", + "top", + "vertical-align", + "white-space", + "width", + "z-index", +] as const; + +const SAFE_STYLE_PROPERTY_SET = new Set(SAFE_STYLE_PROPERTIES); + +/** Converts camelCase CSS property names to kebab-case (e.g. flexWrap -> flex-wrap). */ +export function normalizeStyleProperty(value: string): string { + const trimmed = value.trim(); + if (!trimmed.includes("-") && /[A-Z]/.test(trimmed)) { + return trimmed + .replace(/([a-z0-9])([A-Z])/g, "$1-$2") + .replace(/([A-Z])([A-Z][a-z])/g, "$1-$2") + .toLowerCase(); + } + return trimmed.toLowerCase(); +} + +export const SAFE_ATTRIBUTE_NAMES: readonly SafeAttributeName[] = [ + "aria-label", + "aria-description", + "aria-hidden", + "placeholder", + "role", + "title", +] as const; + +export const SAFE_INSERT_TAGS = [ + "div", + "span", + "p", + "button", + "label", +] as const; +export const SAFE_INSERT_POSITIONS = [ + "before", + "after", + "prepend", + "append", +] as const; + +const OPERATION_TYPES = new Set([ + "setText", + "replaceText", + "setAttribute", + "setStyle", + "addClass", + "removeClass", + "hide", + "show", + "insertText", +]); +const CLASS_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/; +const UNSAFE_STYLE_VALUE = + /(?:url\s*\(|expression\s*\(|javascript\s*:|@import|[{};]|<\/?style)/i; + +const TYPE_ALIASES: Record = { + settext: "setText", + set_text: "setText", + replacetext: "replaceText", + replace_text: "replaceText", + setattribute: "setAttribute", + set_attribute: "setAttribute", + setstyle: "setStyle", + set_style: "setStyle", + style: "setStyle", + addclass: "addClass", + add_class: "addClass", + removeclass: "removeClass", + remove_class: "removeClass", + inserttext: "insertText", + insert_text: "insertText", + hidden: "hide", + visible: "show", +}; + +function describeValue(value: unknown): string { + if (value === null) return "null"; + if (value === undefined) return "undefined"; + if (Array.isArray(value)) return `array(${value.length})`; + if (typeof value === "object") { + const preview = JSON.stringify(value); + return `object ${preview.length > 160 ? `${preview.slice(0, 160)}…` : preview}`; + } + return `${typeof value}: ${String(value).slice(0, 120)}`; +} + +function coerceString(value: unknown): string | null { + if (typeof value === "string") { + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; + } + if (typeof value === "number" || typeof value === "boolean") { + return String(value); + } + return null; +} + +function normalizeOperationType(value: unknown): string | null { + const direct = coerceString(value); + if (direct) { + if (OPERATION_TYPES.has(direct)) return direct; + const compact = direct.replace(/[\s_-]+/g, "").toLowerCase(); + const alias = TYPE_ALIASES[compact] ?? TYPE_ALIASES[direct.toLowerCase()]; + if (alias) return alias; + } + if (value && typeof value === "object" && !Array.isArray(value)) { + const record = value as Record; + return normalizeOperationType( + record.type ?? record.name ?? record.action ?? record.op, + ); + } + return null; +} + +function unwrapKeyedOperation( + operation: Record, +): Record { + if (operation.type || operation.action || operation.op) return operation; + + const keys = Object.keys(operation).filter((key) => { + const normalized = normalizeOperationType(key); + return normalized !== null; + }); + if (keys.length !== 1) return operation; + + const type = normalizeOperationType(keys[0]); + const payload = operation[keys[0]]; + if (!type || !payload || typeof payload !== "object" || Array.isArray(payload)) { + return operation; + } + + return { + type, + ...(payload as Record), + }; +} + +function normalizeOperationRecord( + value: unknown, + index: number, +): Record { + if (typeof value === "string") { + throw new Error( + `Operation #${index + 1} must be an object, received string: ${value.slice(0, 120)}`, + ); + } + + const operation = asRecord(value, `Operation #${index + 1}`); + const unwrapped = unwrapKeyedOperation(operation); + const type = normalizeOperationType( + unwrapped.type ?? unwrapped.action ?? unwrapped.op ?? unwrapped.operation, + ); + if (!type) { + throw new Error( + `Operation #${index + 1} has an invalid type (received ${describeValue( + unwrapped.type ?? unwrapped.action ?? unwrapped.op, + )}). Expected one of: ${[...OPERATION_TYPES].join(", ")}`, + ); + } + + const selector = + unwrapped.selector ?? + unwrapped.target ?? + unwrapped.element ?? + unwrapped.query ?? + ":scope"; + + return { + ...unwrapped, + type, + selector, + ...(unwrapped.className === undefined && unwrapped.class !== undefined + ? { className: unwrapped.class } + : {}), + ...(unwrapped.property === undefined && + (unwrapped.styleProperty !== undefined || unwrapped.cssProperty !== undefined) + ? { + property: unwrapped.styleProperty ?? unwrapped.cssProperty, + } + : {}), + ...(unwrapped.text === undefined && unwrapped.content !== undefined + ? { text: unwrapped.content } + : {}), + ...(unwrapped.value === undefined && unwrapped.styleValue !== undefined + ? { value: unwrapped.styleValue } + : {}), + }; +} + +function normalizeDraftShape(value: unknown): unknown { + const draft = asRecord(value, "Generated mod"); + let operations = draft.operations; + + if (operations && typeof operations === "object" && !Array.isArray(operations)) { + operations = Object.values(operations as Record); + aiModLog.warn( + "recipeSchema", + "Normalized operations object into an array", + operations, + ); + } + + if (!Array.isArray(operations)) { + throw new Error("Generated mod operations must be a list"); + } + + return { + ...draft, + operations: operations.map(normalizeOperationRecord), + }; +} + +function asRecord(value: unknown, label: string): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error(`${label} must be an object`); + } + return value as Record; +} + +function boundedString( + value: unknown, + label: string, + maxLength: number, + allowEmpty = false, +): string { + if (typeof value !== "string") { + throw new Error(`${label} must be text (received ${describeValue(value)})`); + } + const result = value.trim(); + if (!allowEmpty && result.length === 0) throw new Error(`${label} is required`); + if (result.length > maxLength) { + throw new Error(`${label} is too long (maximum ${maxLength} characters)`); + } + return result; +} + +function validateRelativeSelector(value: unknown): string { + const selector = boundedString(value, "Operation selector", 500); + if ( + selector !== ":scope" && + !selector.startsWith(":scope ") && + !selector.startsWith(":scope>") + ) { + throw new Error("Operation selectors must stay inside :scope"); + } + if (selector.includes(",") || /(?:^|\s)(?:html|body|:root)(?:\s|$)/i.test(selector)) { + throw new Error("Operation selector may not escape the selected root"); + } + return selector; +} + +function validateClassName(value: unknown): string { + const className = boundedString(value, "Class name", 64); + if (!CLASS_NAME_PATTERN.test(className)) { + throw new Error("Class name contains unsupported characters"); + } + return className; +} + +function validateOperation(value: unknown): ModOperation { + const operation = asRecord(value, "Operation"); + const type = boundedString(operation.type, "Operation type", 40); + if (!OPERATION_TYPES.has(type)) { + throw new Error(`Unsupported operation type: ${type}`); + } + const selector = validateRelativeSelector(operation.selector); + + switch (type) { + case "setText": + return { + type, + selector, + text: boundedString(operation.text, "Text", 2_000, true), + }; + case "replaceText": + return { + type, + selector, + search: boundedString(operation.search, "Search text", 500), + replacement: boundedString( + operation.replacement, + "Replacement text", + 2_000, + true, + ), + ...(operation.all === true ? { all: true } : {}), + }; + case "setAttribute": { + const name = boundedString(operation.name, "Attribute name", 40); + if (!SAFE_ATTRIBUTE_NAMES.includes(name as SafeAttributeName)) { + throw new Error(`Unsafe attribute: ${name}`); + } + return { + type, + selector, + name: name as SafeAttributeName, + value: boundedString(operation.value, "Attribute value", 1_000, true), + }; + } + case "setStyle": { + const rawProperty = boundedString(operation.property, "Style property", 60); + const property = normalizeStyleProperty(rawProperty); + if (!SAFE_STYLE_PROPERTY_SET.has(property)) { + throw new Error(`Unsafe style property: ${rawProperty}`); + } + const styleValue = stripStyleImportantSuffix( + boundedString(operation.value, "Style value", 200, true), + ); + if (UNSAFE_STYLE_VALUE.test(styleValue)) { + throw new Error("Style value contains unsafe content"); + } + const important = + operation.important === undefined + ? undefined + : operation.important === true; + return { + type, + selector, + property: property as SafeStyleProperty, + value: styleValue, + ...(important === undefined ? {} : { important }), + }; + } + case "addClass": + case "removeClass": + return { + type, + selector, + className: validateClassName(operation.className), + }; + case "hide": + case "show": + return { type, selector }; + case "insertText": { + const position = boundedString(operation.position, "Insert position", 20); + const tag = boundedString(operation.tag, "Insert tag", 20); + if (!SAFE_INSERT_POSITIONS.includes(position as never)) { + throw new Error(`Unsafe insert position: ${position}`); + } + if (!SAFE_INSERT_TAGS.includes(tag as never)) { + throw new Error(`Unsafe insert tag: ${tag}`); + } + return { + type, + selector, + position: position as "before" | "after" | "prepend" | "append", + tag: tag as "div" | "span" | "p" | "button" | "label", + text: boundedString(operation.text, "Inserted text", 2_000, true), + ...(operation.className === undefined + ? {} + : { className: validateClassName(operation.className) }), + }; + } + } + + throw new Error("Unsupported operation"); +} + +function describeOperationPreview(value: unknown): string { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return "unknown operation"; + } + const operation = value as Record; + const type = + operation.type ?? + operation.action ?? + operation.op ?? + Object.keys(operation).find((key) => normalizeOperationType(key) !== null) ?? + "unknown"; + const selector = + operation.selector ?? + operation.target ?? + operation.element ?? + operation.query ?? + ":scope"; + return `${String(type)} → ${String(selector).slice(0, 80)}`; +} + +export function formatRecipeValidationError(error: unknown): string { + const base = + error instanceof Error ? error.message : "Recipe validation failed"; + if (base.startsWith("Recipe validation failed:")) { + return base; + } + + const suggestions: string[] = []; + const unsafeStyle = base.match(/Unsafe style property:\s*(.+)/i); + if (unsafeStyle) { + const property = unsafeStyle[1].trim(); + suggestions.push( + `"${property}" is not allowed. Supported style properties include ${SAFE_STYLE_PROPERTIES.slice(0, 10).join(", ")}, and more.`, + ); + suggestions.push( + "For layout changes, try display, flex-wrap, align-items, justify-content, gap, or grid-template-columns.", + ); + } + if (/Unsafe attribute:/i.test(base)) { + suggestions.push( + `Allowed attributes: ${SAFE_ATTRIBUTE_NAMES.join(", ")}.`, + ); + } + if (/selectors must stay inside :scope/i.test(base)) { + suggestions.push( + 'Selectors must start with :scope (for example ":scope" or ":scope .child").', + ); + } + if (/invalid JSON/i.test(base)) { + suggestions.push("Try regenerating the mod or switching to a different model."); + } + if (/at least one operation/i.test(base)) { + suggestions.push( + "Describe a concrete DOM change such as hiding an element, changing color, or rounding corners.", + ); + } + if (/Unsupported operation type:/i.test(base)) { + suggestions.push( + "Supported operations: setText, replaceText, setAttribute, setStyle, addClass, removeClass, hide, show, insertText.", + ); + } + + if (suggestions.length === 0) { + return `Recipe validation failed: ${base}`; + } + + return `Recipe validation failed: ${base} — ${suggestions.join(" ")}`; +} + +function validateDraft(value: unknown): GeneratedModDraft { + const normalized = normalizeDraftShape(value); + const draft = asRecord(normalized, "Generated mod"); + if (!Array.isArray(draft.operations)) { + throw new Error("Generated mod operations must be a list"); + } + if (draft.operations.length > 30) { + throw new Error("Generated mod may contain at most 30 operations"); + } + + const operations = draft.operations.map((operation, index) => { + try { + return validateOperation(operation); + } catch (cause) { + const detail = + cause instanceof Error ? cause.message : "Invalid operation"; + throw new Error( + `Operation #${index + 1} (${describeOperationPreview(operation)}): ${detail}`, + ); + } + }); + const advancedScript = + draft.advancedScript === undefined || + (typeof draft.advancedScript === "string" && + draft.advancedScript.trim().length === 0) + ? undefined + : assertAdvancedScriptSafe(draft.advancedScript); + + if (operations.length === 0 && !advancedScript) { + throw new Error( + "Generated mod must include at least one operation or an advancedScript", + ); + } + + return { + name: boundedString(draft.name, "Mod name", 120), + description: boundedString( + draft.description, + "Mod description", + 500, + true, + ), + operations, + ...(advancedScript === undefined ? {} : { advancedScript }), + }; +} + +export function extractJsonFromModelText(text: string): string { + const trimmed = text.trim(); + if (trimmed.startsWith("{")) return trimmed; + const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i); + if (fenced?.[1]) return fenced[1].trim(); + const start = trimmed.indexOf("{"); + const end = trimmed.lastIndexOf("}"); + if (start >= 0 && end > start) return trimmed.slice(start, end + 1); + return trimmed; +} + +export function parseGeneratedModDraft( + input: string | GeneratedModDraft, +): GeneratedModDraft { + let parsed: unknown; + if (typeof input === "string") { + const normalized = extractJsonFromModelText(input); + if (normalized.length > 50_000) { + throw new Error("Generated response is too large"); + } + try { + parsed = JSON.parse(normalized); + } catch { + aiModLog.error("recipeSchema", "Model returned invalid JSON", normalized); + throw new Error("The model returned invalid JSON"); + } + } else { + parsed = input; + } + + try { + const draft = validateDraft(parsed); + aiModLog.info("recipeSchema", "Validated generated mod draft", { + name: draft.name, + operationCount: draft.operations.length, + hasAdvancedScript: Boolean(draft.advancedScript), + }); + return draft; + } catch (error) { + aiModLog.error("recipeSchema", "Recipe validation failed", { + parsed, + error, + }); + throw error; + } +} + +export function createStoredRecipe( + draft: GeneratedModDraft, + input: { + rootSelector: string; + route: string; + now?: number; + id?: string; + }, +): StoredModRecipe { + const validated = validateDraft(draft); + const now = input.now ?? Date.now(); + const generatedId = + input.id ?? + globalThis.crypto?.randomUUID?.() ?? + `mod-${now}-${Math.random().toString(36).slice(2, 10)}`; + + return validateStoredRecipe({ + ...validated, + schemaVersion: AI_MOD_SCHEMA_VERSION, + id: generatedId, + enabled: false, + route: input.route, + rootSelector: input.rootSelector, + createdAt: now, + updatedAt: now, + }); +} + +function validateStoredRecipe(value: unknown): StoredModRecipe { + const recipe = asRecord(value, "Stored mod"); + if (recipe.schemaVersion !== AI_MOD_SCHEMA_VERSION) { + throw new Error("Unsupported mod schema version"); + } + const draft = validateDraft(recipe); + const id = boundedString(recipe.id, "Mod id", 160); + if (!/^[A-Za-z0-9_-]+$/.test(id)) { + throw new Error("Mod id contains unsupported characters"); + } + const rootSelector = boundedString(recipe.rootSelector, "Root selector", 1_000); + if (/^(?:html|body|:root|\*)$/i.test(rootSelector)) { + throw new Error("Root selector is too broad"); + } + const createdAt = Number(recipe.createdAt); + const updatedAt = Number(recipe.updatedAt); + if (!Number.isFinite(createdAt) || !Number.isFinite(updatedAt)) { + throw new Error("Mod timestamps are invalid"); + } + return { + ...draft, + schemaVersion: AI_MOD_SCHEMA_VERSION, + id, + enabled: recipe.enabled === true, + route: boundedString(recipe.route, "Route", 256, true), + rootSelector, + createdAt, + updatedAt, + }; +} + +export function parseStoredRecipes(json: string): StoredModRecipe[] { + if (json.length > 500_000) throw new Error("Import file is too large"); + let parsed: unknown; + try { + parsed = JSON.parse(json); + } catch { + throw new Error("Import file is not valid JSON"); + } + if (!Array.isArray(parsed)) throw new Error("Import must contain a mod list"); + if (parsed.length > 100) throw new Error("At most 100 mods can be imported"); + return parsed.map(validateStoredRecipe); +} + +export function validateStoredRecipes(value: unknown): StoredModRecipe[] { + return parseStoredRecipes(JSON.stringify(value)); +} diff --git a/src/plugins/built-in/aiModCreator/scriptSafety.test.ts b/src/plugins/built-in/aiModCreator/scriptSafety.test.ts new file mode 100644 index 00000000..8cfb85d7 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/scriptSafety.test.ts @@ -0,0 +1,43 @@ +import { assertAdvancedScriptSafe } from "./scriptSafety"; + +describe("advanced AI mod script safeguards", () => { + it("allows advanced DOM code with cleanup", () => { + expect(() => + assertAdvancedScriptSafe(` + const cards = bsplus.selectAll(":scope .card"); + for (const card of cards) { + bsplus.setStyle(card, "border-radius", "16px"); + bsplus.on(card, "click", () => card.classList.toggle("expanded")); + } + const observer = bsplus.observe(root, () => console.info("changed")); + return () => observer.disconnect(); + `), + ).not.toThrow(); + }); + + it("allows clearing containers with empty innerHTML during DOM moves", () => { + expect(() => + assertAdvancedScriptSafe(` + const wrapper = bsplus.select(".search-trigger-wrapper"); + wrapper.innerHTML = ''; + wrapper.appendChild(anchor); + return () => {}; + `), + ).not.toThrow(); + }); + + it.each([ + ["network requests", `fetch("https://attacker.invalid")`], + ["extension APIs", `chrome.storage.local.get(null)`], + ["page storage", `localStorage.getItem("token")`], + ["cookies", `document.cookie`], + ["dynamic evaluation", `eval("alert(1)")`], + ["script injection", `element.innerHTML = ""`], + ["non-empty innerHTML", `wrapper.innerHTML = "
"`], + ["innerHTML append", `wrapper.innerHTML += ""`], + ["navigation", `location.href = "https://attacker.invalid"`], + ["unbounded loops", `while (true) {}`], + ])("rejects %s", (_label, script) => { + expect(() => assertAdvancedScriptSafe(script)).toThrow(); + }); +}); diff --git a/src/plugins/built-in/aiModCreator/scriptSafety.ts b/src/plugins/built-in/aiModCreator/scriptSafety.ts new file mode 100644 index 00000000..61261ad6 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/scriptSafety.ts @@ -0,0 +1,100 @@ +const MAX_SCRIPT_LENGTH = 20_000; + +const BLOCKED_PATTERNS: ReadonlyArray<{ + pattern: RegExp; + reason: string; +}> = [ + { + pattern: + /\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|RTCPeerConnection|sendBeacon)\b/i, + reason: "network access", + }, + { + pattern: /\b(?:chrome|browser)\s*\./i, + reason: "extension API access", + }, + { + pattern: + /\b(?:localStorage|sessionStorage|indexedDB|caches|cookieStore)\b/i, + reason: "browser storage access", + }, + { pattern: /\bdocument\s*\.\s*cookie\b/i, reason: "cookie access" }, + { + pattern: + /\b(?:eval|Function|AsyncFunction|GeneratorFunction|importScripts|Worker|SharedWorker)\s*\(/i, + reason: "dynamic code execution", + }, + { pattern: /\bimport\s*\(/i, reason: "dynamic imports" }, + { + pattern: /\b(?:globalThis|top|parent|opener)\b/i, + reason: "cross-world access", + }, + { + pattern: /\b(?:location|history)\s*(?:\.|\[|=)/i, + reason: "navigation", + }, + { + pattern: /\bwindow\s*\.\s*(?:open|postMessage)\s*\(/i, + reason: "cross-window messaging", + }, + { + pattern: /\.(?:src|srcset|href|action|formAction)\s*=/i, + reason: "network-capable DOM properties", + }, + { + pattern: + /\.setAttribute\s*\(\s*["'`](?:src|srcset|href|action|formaction|style|on[^"'`]*)["'`]/i, + reason: "unsafe DOM attributes", + }, + { + pattern: /\.(?:outerHTML|insertAdjacentHTML)\b/i, + reason: "raw HTML injection", + }, + { + pattern: /<\s*(?:script|iframe|object|embed|link|meta|form)\b/i, + reason: "active HTML", + }, + { + pattern: /\.(?:submit|requestSubmit|click)\s*\(/i, + reason: "programmatic page actions", + }, + { + pattern: /\b(?:while\s*\(\s*true\s*\)|for\s*\(\s*;\s*;\s*\))/i, + reason: "unbounded loops", + }, + { + pattern: /(?:__proto__|prototype\s*\[|constructor\s*\.\s*constructor)/i, + reason: "prototype escape", + }, +]; + +const EMPTY_STRING_LITERAL = /^['"`]\s*['"`]$/; + +function assertNoUnsafeInnerHtml(script: string): void { + for (const match of script.matchAll(/\.innerHTML\s*=\s*([^;\n]+)/g)) { + if (!EMPTY_STRING_LITERAL.test(match[1].trim())) { + throw new Error("Advanced script blocked: raw HTML injection"); + } + } + if (/\.innerHTML\s*\+=/.test(script)) { + throw new Error("Advanced script blocked: raw HTML injection"); + } +} + +export function assertAdvancedScriptSafe(value: unknown): string { + if (typeof value !== "string") throw new Error("Advanced script must be text"); + const script = value.trim(); + if (!script) throw new Error("Advanced script is empty"); + if (script.length > MAX_SCRIPT_LENGTH) { + throw new Error( + `Advanced script is too long (maximum ${MAX_SCRIPT_LENGTH} characters)`, + ); + } + assertNoUnsafeInnerHtml(script); + for (const { pattern, reason } of BLOCKED_PATTERNS) { + if (pattern.test(script)) { + throw new Error(`Advanced script blocked: ${reason}`); + } + } + return script; +} diff --git a/src/plugins/built-in/aiModCreator/selection.test.ts b/src/plugins/built-in/aiModCreator/selection.test.ts new file mode 100644 index 00000000..e03aa0ea --- /dev/null +++ b/src/plugins/built-in/aiModCreator/selection.test.ts @@ -0,0 +1,69 @@ +/** @jest-environment jsdom */ + +import { + createStableSelector, + startElementSelection, +} from "./selection"; + +describe("AI mod element selection", () => { + beforeEach(() => { + document.body.innerHTML = ` +
+
+

First

+

Second

+
+
+ `; + }); + + it("prefers a unique id or test attribute", () => { + const target = document.querySelector("[data-testid=target]")!; + expect(createStableSelector(target)).toBe('[data-testid="target"]'); + + target.id = "assessment:42"; + expect(createStableSelector(target)).toBe("#assessment\\:42"); + }); + + it("falls back to a unique structural selector", () => { + const target = document.querySelectorAll("article")[1]; + target.removeAttribute("data-testid"); + + const selector = createStableSelector(target); + expect(document.querySelector(selector)).toBe(target); + expect(document.querySelectorAll(selector)).toHaveLength(1); + }); + + it("captures a clicked page element without activating it", () => { + const onSelect = jest.fn(); + const onCancel = jest.fn(); + const target = document.querySelector("[data-testid=target]")!; + const clickSpy = jest.fn(); + target.addEventListener("click", clickSpy); + + const stop = startElementSelection({ onSelect, onCancel }); + target.dispatchEvent( + new MouseEvent("click", { bubbles: true, cancelable: true }), + ); + + expect(onSelect).toHaveBeenCalledWith(target); + expect(clickSpy).not.toHaveBeenCalled(); + expect(onCancel).not.toHaveBeenCalled(); + expect(document.querySelector("[data-bsplus-ai-selection-overlay]")).toBeNull(); + stop(); + }); + + it("cancels with Escape and removes the overlay", () => { + const onCancel = jest.fn(); + const stop = startElementSelection({ + onSelect: jest.fn(), + onCancel, + }); + + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + + expect(onCancel).toHaveBeenCalledTimes(1); + expect(document.querySelector("[data-bsplus-ai-selection-overlay]")).toBeNull(); + stop(); + }); +}); diff --git a/src/plugins/built-in/aiModCreator/selection.ts b/src/plugins/built-in/aiModCreator/selection.ts new file mode 100644 index 00000000..10b5b599 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/selection.ts @@ -0,0 +1,185 @@ +const PREFERRED_ATTRIBUTES = ["data-testid", "data-id", "name"] as const; + +function isUnique(selector: string, documentRef: Document): boolean { + try { + return documentRef.querySelectorAll(selector).length === 1; + } catch { + return false; + } +} + +function escapeCss(value: string): string { + const escaped = value.replace(/([^\w-])/g, "\\$1"); + if (/^-?\d/.test(escaped)) { + const firstDigit = escaped.startsWith("-") ? escaped[1] : escaped[0]; + const prefixLength = escaped.startsWith("-") ? 2 : 1; + return `${escaped.startsWith("-") ? "-" : ""}\\3${firstDigit} ${escaped.slice(prefixLength)}`; + } + return escaped; +} + +function elementSegment(element: Element): string { + const tag = element.tagName.toLowerCase(); + const stableClasses = [...element.classList] + .filter((className) => /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/.test(className)) + .slice(0, 2); + let segment = `${tag}${stableClasses + .map((className) => `.${escapeCss(className)}`) + .join("")}`; + + const parent = element.parentElement; + if (parent) { + const sameTag = [...parent.children].filter( + (sibling) => sibling.tagName === element.tagName, + ); + if (sameTag.length > 1) { + segment += `:nth-of-type(${sameTag.indexOf(element) + 1})`; + } + } + return segment; +} + +export function createStableSelector( + element: Element, + documentRef: Document = document, +): string { + if (element.id) { + const byId = `#${escapeCss(element.id)}`; + if (isUnique(byId, documentRef)) return byId; + } + + for (const attribute of PREFERRED_ATTRIBUTES) { + const value = element.getAttribute(attribute); + if (!value || value.length > 160) continue; + const selector = `[${attribute}="${escapeCss(value)}"]`; + if (isUnique(selector, documentRef)) return selector; + } + + const segments: string[] = []; + let current: Element | null = element; + while (current && current !== documentRef.documentElement) { + segments.unshift(elementSegment(current)); + const selector = segments.join(" > "); + if (isUnique(selector, documentRef)) return selector; + current = current.parentElement; + } + + const selector = segments.join(" > "); + if (!selector || !isUnique(selector, documentRef)) { + throw new Error("Could not create a stable selector for this element"); + } + return selector; +} + +export function buildScopeRelativeSelector( + root: HTMLElement, + target: Element, +): string { + if (target === root) return ":scope"; + if (!root.contains(target)) { + throw new Error("Cannot build a selector outside the selected root"); + } + const segments: string[] = []; + let current: Element | null = target; + while (current && current !== root) { + segments.unshift(elementSegment(current)); + current = current.parentElement; + } + return segments.length > 0 ? `:scope > ${segments.join(" > ")}` : ":scope"; +} + +export interface ElementSelectionOptions { + onSelect: (element: HTMLElement) => void; + onCancel: () => void; + ignoredRoot?: Node | null; +} + +function eventElement(event: Event): HTMLElement | null { + for (const item of event.composedPath()) { + if (item instanceof HTMLElement) return item; + } + return event.target instanceof HTMLElement ? event.target : null; +} + +export function startElementSelection({ + onSelect, + onCancel, + ignoredRoot, +}: ElementSelectionOptions): () => void { + const overlay = document.createElement("div"); + overlay.dataset.bsplusAiSelectionOverlay = ""; + Object.assign(overlay.style, { + position: "fixed", + pointerEvents: "none", + zIndex: "2147483647", + border: "2px solid var(--better-main, #8b5cf6)", + borderRadius: "6px", + background: "color-mix(in srgb, var(--better-main, #8b5cf6) 14%, transparent)", + boxShadow: "0 0 0 1px rgba(255,255,255,.7)", + display: "none", + transition: "left 60ms, top 60ms, width 60ms, height 60ms", + }); + document.body.appendChild(overlay); + + let active = true; + const isIgnored = (element: HTMLElement) => + element === overlay || + ignoredRoot === element || + Boolean(ignoredRoot?.contains(element)) || + Boolean( + ignoredRoot instanceof HTMLElement && + ignoredRoot.shadowRoot?.contains(element), + ); + + const updateOverlay = (element: HTMLElement) => { + const rect = element.getBoundingClientRect(); + Object.assign(overlay.style, { + display: "block", + left: `${rect.left}px`, + top: `${rect.top}px`, + width: `${rect.width}px`, + height: `${rect.height}px`, + }); + }; + + const cleanup = () => { + if (!active) return; + active = false; + document.removeEventListener("pointermove", onPointerMove, true); + document.removeEventListener("click", onClick, true); + document.removeEventListener("keydown", onKeyDown, true); + overlay.remove(); + }; + + const onPointerMove = (event: PointerEvent) => { + const element = eventElement(event); + if (!element || isIgnored(element)) { + overlay.style.display = "none"; + return; + } + updateOverlay(element); + }; + + const onClick = (event: MouseEvent) => { + const element = eventElement(event); + if (!element || isIgnored(element)) return; + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + cleanup(); + onSelect(element); + }; + + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== "Escape") return; + event.preventDefault(); + event.stopPropagation(); + cleanup(); + onCancel(); + }; + + document.addEventListener("pointermove", onPointerMove, true); + document.addEventListener("click", onClick, true); + document.addEventListener("keydown", onKeyDown, true); + return cleanup; +} diff --git a/src/plugins/built-in/aiModCreator/services.ts b/src/plugins/built-in/aiModCreator/services.ts new file mode 100644 index 00000000..3cb7d532 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/services.ts @@ -0,0 +1,181 @@ +import browser from "webextension-polyfill"; +import { + formatRecipeValidationError, + parseGeneratedModDraft, +} from "./recipeSchema"; +import { aiModLog } from "./logger"; +import { + deleteStoredMod, + exportStoredMods, + importStoredMods, + loadStoredMods, + setStoredModEnabled, + upsertStoredMod, +} from "./storage"; +import type { + AdvancedScriptSupport, + CreatorServices, + GeneratedModDraft, + GenerationProgress, + KeyStatus, + ModelSettings, + SelectedElementContext, +} from "./types"; + +const AI_MOD_CREATOR_MESSAGE_TYPE = "aiModCreator"; + +interface MessageResponse { + success?: boolean; + data?: unknown; + error?: unknown; +} + +async function sendBackgroundMessage( + action: string, + payload: Record = {}, +): Promise { + aiModLog.debug("services", `Sending background message: ${action}`, payload); + const response = (await browser.runtime.sendMessage({ + type: AI_MOD_CREATOR_MESSAGE_TYPE, + action, + ...payload, + })) as MessageResponse | undefined; + if (!response?.success) { + const error = + typeof response?.error === "string" + ? response.error + : "AI Mod Creator background service is unavailable"; + aiModLog.error("services", `Background message failed: ${action}`, error); + throw new Error(error); + } + aiModLog.debug("services", `Background message succeeded: ${action}`, response.data); + return response.data; +} + +function streamGeneration( + context: SelectedElementContext, + onProgress?: (progress: GenerationProgress) => void, +) { + return new Promise>( + (resolve, reject) => { + aiModLog.info("services", "Opening streaming generation port", { + route: context.route, + rootSelector: context.rootSelector, + request: context.request, + }); + const port = browser.runtime.connect({ name: "aiModCreator.stream" }); + let settled = false; + port.onMessage.addListener( + (message: { + type?: string; + progress?: GenerationProgress; + draft?: unknown; + error?: unknown; + }) => { + if (message.type === "progress" && message.progress) { + aiModLog.debug("services", "Stream progress", message.progress); + onProgress?.(message.progress); + } else if (message.type === "done") { + settled = true; + aiModLog.info("services", "Stream completed", message.draft); + try { + resolve(parseGeneratedModDraft(message.draft as GeneratedModDraft)); + } catch (error) { + const formatted = formatRecipeValidationError(error); + aiModLog.error("services", "Failed to validate streamed draft", { + draft: message.draft, + error: formatted, + }); + reject(new Error(formatted)); + } + } else if (message.type === "error") { + settled = true; + const errorMessage = + typeof message.error === "string" + ? message.error + : "AI streaming failed"; + aiModLog.error("services", "Stream error from background", errorMessage); + reject(new Error(errorMessage)); + } + }, + ); + port.onDisconnect.addListener(() => { + if (!settled) { + aiModLog.error("services", "Streaming port disconnected early"); + reject(new Error("AI streaming connection closed")); + } + }); + port.postMessage({ context }); + }, + ); +} + +export function createCreatorServices(): CreatorServices { + return { + async getKeyStatus() { + const data = await sendBackgroundMessage("status"); + if ( + !data || + typeof data !== "object" || + typeof (data as KeyStatus).configured !== "boolean" + ) { + throw new Error("Invalid API key status response"); + } + return { configured: (data as KeyStatus).configured }; + }, + async getModelSettings() { + const data = await sendBackgroundMessage("getModel"); + if ( + !data || + typeof data !== "object" || + typeof (data as ModelSettings).modelId !== "string" + ) { + throw new Error("Invalid model settings response"); + } + return { modelId: (data as ModelSettings).modelId }; + }, + async saveModel(modelId) { + await sendBackgroundMessage("saveModel", { modelId }); + }, + async getAdvancedScriptSupport() { + const data = await sendBackgroundMessage("advancedSupport"); + if ( + !data || + typeof data !== "object" || + typeof (data as AdvancedScriptSupport).supported !== "boolean" + ) { + throw new Error("Invalid advanced script support response"); + } + return data as AdvancedScriptSupport; + }, + async openExtensionSettings() { + const extensionId = browser.runtime.id; + await browser.tabs.create({ + url: `chrome://extensions/?id=${extensionId}`, + }); + }, + async saveKey(apiKey) { + await sendBackgroundMessage("saveKey", { apiKey }); + }, + async clearKey() { + await sendBackgroundMessage("clearKey"); + }, + async generate(context, onProgress) { + return streamGeneration(context, onProgress); + }, + loadMods: loadStoredMods, + saveMod: upsertStoredMod, + setModEnabled: setStoredModEnabled, + deleteMod: deleteStoredMod, + importMods: importStoredMods, + exportMods: exportStoredMods, + async executeAdvancedScript(recipe) { + aiModLog.info("services", "Requesting advanced mod via background", recipe.id); + await sendBackgroundMessage("executeAdvanced", { recipe }); + }, + async stopAdvancedScript(id) { + aiModLog.info("services", "Stopping advanced mod via background", id); + await sendBackgroundMessage("stopAdvanced", { id }); + }, + }; +} diff --git a/src/plugins/built-in/aiModCreator/storage.test.ts b/src/plugins/built-in/aiModCreator/storage.test.ts new file mode 100644 index 00000000..30c84fd0 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/storage.test.ts @@ -0,0 +1,69 @@ +import browser from "webextension-polyfill"; +import { + deleteStoredMod, + exportStoredMods, + importStoredMods, + loadStoredMods, + setStoredModEnabled, + upsertStoredMod, +} from "./storage"; +import type { StoredModRecipe } from "./types"; + +const storedRecipe: StoredModRecipe = { + schemaVersion: 1, + id: "mod-1", + name: "Test", + description: "Test mod", + enabled: false, + route: "assessments", + rootSelector: "#selected", + operations: [{ type: "hide", selector: ":scope" }], + createdAt: 1, + updatedAt: 1, +}; + +describe("AI mod local storage", () => { + it("immutably inserts, updates, toggles, and deletes recipes", async () => { + await upsertStoredMod(storedRecipe); + expect(await loadStoredMods()).toEqual([storedRecipe]); + + await setStoredModEnabled("mod-1", true); + expect((await loadStoredMods())[0]).toMatchObject({ + id: "mod-1", + enabled: true, + }); + + await upsertStoredMod({ ...storedRecipe, name: "Updated" }); + expect((await loadStoredMods())[0].name).toBe("Updated"); + + await deleteStoredMod("mod-1"); + expect(await loadStoredMods()).toEqual([]); + }); + + it("round-trips validated import/export JSON", async () => { + await upsertStoredMod(storedRecipe); + const exported = await exportStoredMods(); + + await browser.storage.local.clear?.(); + const imported = await importStoredMods(exported); + + expect(imported).toEqual([storedRecipe]); + expect(await loadStoredMods()).toEqual([storedRecipe]); + }); + + it("does not overwrite storage when an import is invalid", async () => { + await upsertStoredMod(storedRecipe); + + await expect( + importStoredMods( + JSON.stringify([ + { + ...storedRecipe, + operations: [{ type: "javascript", code: "alert(1)" }], + }, + ]), + ), + ).rejects.toThrow(); + expect(await loadStoredMods()).toEqual([storedRecipe]); + }); +}); diff --git a/src/plugins/built-in/aiModCreator/storage.ts b/src/plugins/built-in/aiModCreator/storage.ts new file mode 100644 index 00000000..df9f72f0 --- /dev/null +++ b/src/plugins/built-in/aiModCreator/storage.ts @@ -0,0 +1,68 @@ +import browser from "webextension-polyfill"; +import { parseStoredRecipes, validateStoredRecipes } from "./recipeSchema"; +import type { StoredModRecipe } from "./types"; + +export const AI_MODS_STORAGE_KEY = "aiModCreator.mods"; +export const OPENROUTER_API_KEY_STORAGE_KEY = + "aiModCreator.openRouterApiKey"; +export const OPENROUTER_MODEL_STORAGE_KEY = "aiModCreator.openRouterModelId"; + +async function writeStoredMods( + recipes: StoredModRecipe[], +): Promise { + const validated = validateStoredRecipes(recipes); + await browser.storage.local.set({ [AI_MODS_STORAGE_KEY]: validated }); + return validated; +} + +export async function loadStoredMods(): Promise { + const result = await browser.storage.local.get(AI_MODS_STORAGE_KEY); + const stored = result[AI_MODS_STORAGE_KEY]; + if (stored === undefined) return []; + try { + return validateStoredRecipes(stored); + } catch (error) { + console.error("[BetterSEQTA+] Ignoring invalid locally stored AI mods:", error); + return []; + } +} + +export async function upsertStoredMod( + recipe: StoredModRecipe, +): Promise { + const [validated] = validateStoredRecipes([recipe]); + const existing = await loadStoredMods(); + const next = existing.some((item) => item.id === validated.id) + ? existing.map((item) => (item.id === validated.id ? validated : item)) + : [...existing, validated]; + return writeStoredMods(next); +} + +export async function setStoredModEnabled( + id: string, + enabled: boolean, +): Promise { + const existing = await loadStoredMods(); + const next = existing.map((item) => + item.id === id ? { ...item, enabled, updatedAt: Date.now() } : item, + ); + return writeStoredMods(next); +} + +export async function deleteStoredMod( + id: string, +): Promise { + const existing = await loadStoredMods(); + return writeStoredMods(existing.filter((item) => item.id !== id)); +} + +export async function exportStoredMods(): Promise { + return JSON.stringify(await loadStoredMods(), null, 2); +} + +export async function importStoredMods( + json: string, +): Promise { + const imported = parseStoredRecipes(json); + return writeStoredMods(imported); +} diff --git a/src/plugins/built-in/aiModCreator/types.ts b/src/plugins/built-in/aiModCreator/types.ts new file mode 100644 index 00000000..39f3da6d --- /dev/null +++ b/src/plugins/built-in/aiModCreator/types.ts @@ -0,0 +1,246 @@ +export const AI_MOD_SCHEMA_VERSION = 1 as const; + +export type SafeStyleProperty = + | "align-items" + | "align-self" + | "aspect-ratio" + | "background" + | "background-color" + | "border" + | "border-color" + | "border-radius" + | "border-style" + | "border-width" + | "bottom" + | "box-shadow" + | "color" + | "cursor" + | "display" + | "flex" + | "flex-direction" + | "flex-grow" + | "flex-shrink" + | "flex-wrap" + | "font-size" + | "font-weight" + | "gap" + | "grid-template-columns" + | "height" + | "justify-content" + | "left" + | "letter-spacing" + | "line-height" + | "margin" + | "margin-bottom" + | "margin-left" + | "margin-right" + | "margin-top" + | "max-height" + | "max-width" + | "min-height" + | "min-width" + | "object-fit" + | "opacity" + | "order" + | "overflow" + | "overflow-x" + | "overflow-y" + | "padding" + | "padding-bottom" + | "padding-left" + | "padding-right" + | "padding-top" + | "position" + | "right" + | "text-align" + | "text-decoration" + | "top" + | "vertical-align" + | "white-space" + | "width" + | "z-index"; + +export type SafeAttributeName = + | "aria-label" + | "aria-description" + | "aria-hidden" + | "placeholder" + | "role" + | "title"; + +interface OperationBase { + selector: string; +} + +export interface SetTextOperation extends OperationBase { + type: "setText"; + text: string; +} + +export interface ReplaceTextOperation extends OperationBase { + type: "replaceText"; + search: string; + replacement: string; + all?: boolean; +} + +export interface SetAttributeOperation extends OperationBase { + type: "setAttribute"; + name: SafeAttributeName; + value: string; +} + +export interface SetStyleOperation extends OperationBase { + type: "setStyle"; + property: SafeStyleProperty; + value: string; + /** When true (default), beats BetterSEQTA stylesheet rules including !important. */ + important?: boolean; +} + +export interface AddClassOperation extends OperationBase { + type: "addClass"; + className: string; +} + +export interface RemoveClassOperation extends OperationBase { + type: "removeClass"; + className: string; +} + +export interface HideOperation extends OperationBase { + type: "hide"; +} + +export interface ShowOperation extends OperationBase { + type: "show"; +} + +export interface InsertTextOperation extends OperationBase { + type: "insertText"; + position: "before" | "after" | "prepend" | "append"; + tag: "div" | "span" | "p" | "button" | "label"; + text: string; + className?: string; +} + +export type ModOperation = + | SetTextOperation + | ReplaceTextOperation + | SetAttributeOperation + | SetStyleOperation + | AddClassOperation + | RemoveClassOperation + | HideOperation + | ShowOperation + | InsertTextOperation; + +export interface GeneratedModDraft { + name: string; + description: string; + operations: ModOperation[]; + advancedScript?: string; +} + +export interface StoredModRecipe extends GeneratedModDraft { + schemaVersion: typeof AI_MOD_SCHEMA_VERSION; + id: string; + enabled: boolean; + route: string; + rootSelector: string; + createdAt: number; + updatedAt: number; +} + +export interface DomElementSummary { + selector: string; + tag: string; + classes: string[]; + directText?: string; + parentSelector: string | null; + siblingIndex: number; + siblingCount: number; + layout: Record; + rowCount?: number; + columnCount?: number; + itemCount?: number; +} + +export interface ParentChainSummary { + tag: string; + classes: string[]; + layout: Record; +} + +export interface StructuralHints { + hasTable: boolean; + hasList: boolean; + rowCount?: number; + columnCount?: number; + itemCount?: number; + primaryClasses: string[]; +} + +export interface SelectedElementContext { + route: string; + rootSelector: string; + request: string; + userContext: string; + selectedHtml: string; + domCatalog: DomElementSummary[]; + ancestorHtml?: string; + parentChain?: ParentChainSummary[]; + structuralHints?: StructuralHints; + tagName: string; + dimensions: { + width: number; + height: number; + }; + computedStyle: Record; +} + +export interface KeyStatus { + configured: boolean; +} + +export interface ModelSettings { + modelId: string; +} + +export interface AdvancedScriptSupport { + supported: boolean; + reason?: string; + instructions?: string; +} + +export interface GenerationProgress { + type: "status" | "content" | "usage"; + text?: string; + promptTokens?: number; + completionTokens?: number; +} + +export interface CreatorServices { + getKeyStatus: () => Promise; + getModelSettings: () => Promise; + saveModel: (modelId: string) => Promise; + getAdvancedScriptSupport: () => Promise; + openExtensionSettings: () => Promise; + saveKey: (apiKey: string) => Promise; + clearKey: () => Promise; + generate: ( + context: SelectedElementContext, + onProgress?: (progress: GenerationProgress) => void, + ) => Promise; + loadMods: () => Promise; + saveMod: (recipe: StoredModRecipe) => Promise; + setModEnabled: ( + id: string, + enabled: boolean, + ) => Promise; + deleteMod: (id: string) => Promise; + importMods: (json: string) => Promise; + exportMods: () => Promise; + executeAdvancedScript: (recipe: StoredModRecipe) => Promise; + stopAdvancedScript: (id: string) => Promise; +} diff --git a/src/plugins/index.ts b/src/plugins/index.ts index 191d03cb..91c75688 100644 --- a/src/plugins/index.ts +++ b/src/plugins/index.ts @@ -17,6 +17,7 @@ import enhancedNavigationPluginLazy from "./built-in/enhancedNavigation/lazy"; import globalSearchPluginLazy from "./built-in/globalSearch/lazy"; import gradeAnalyticsPluginLazy from "./built-in/gradeAnalytics/lazy"; import errorPageKittenPlugin from "./built-in/errorPageKitten"; +import aiModCreatorPlugin from "./built-in/aiModCreator"; // Initialize plugin manager const pluginManager = PluginManager.getInstance(); @@ -38,6 +39,7 @@ pluginManager.registerPlugin(enhancedNavigationPluginLazy); pluginManager.registerPlugin(globalSearchPluginLazy); pluginManager.registerPlugin(gradeAnalyticsPluginLazy); pluginManager.registerPlugin(errorPageKittenPlugin); +pluginManager.registerPlugin(aiModCreatorPlugin); export async function initializePlugins(): Promise { await pluginManager.startAllPlugins(); diff --git a/src/seqta/ui/sidebar/mountCustomSidebar.ts b/src/seqta/ui/sidebar/mountCustomSidebar.ts index 9d27fa31..728c7a37 100644 --- a/src/seqta/ui/sidebar/mountCustomSidebar.ts +++ b/src/seqta/ui/sidebar/mountCustomSidebar.ts @@ -120,10 +120,11 @@ function onCustomSidebarCaptureClick(event: MouseEvent) { const li = target.closest("li.item[data-key]"); if (!(li instanceof HTMLElement) || !root.contains(li)) return; - // Already-open folder chrome (renders its own `.sub`) — ignore; use Back. + // Open folder header row only — leaf clicks inside `.sub` must still navigate. if ( li.classList.contains("hasChildren") && - li.querySelector(":scope > .sub") + li.querySelector(":scope > .sub") && + !target.closest(".sub") ) { return; } diff --git a/src/seqta/ui/sidebar/sidebarState.svelte.ts b/src/seqta/ui/sidebar/sidebarState.svelte.ts index 984d0e8e..755c67d8 100644 --- a/src/seqta/ui/sidebar/sidebarState.svelte.ts +++ b/src/seqta/ui/sidebar/sidebarState.svelte.ts @@ -326,12 +326,22 @@ class SidebarState { // SEQTA rewrites `.active` on the route change. if (this.isDrilling) { this.enterFrameKey = null; - restoreCustomMenuActive(); + clearNativeDrillActive(menu); } const native = findNativeMenuEntry(menu, item); if (native) { native.click(); + // Inside a drill panel, SEQTA native rows may no-op if their folder is not + // `.active` — fall back to hash routing for standard (non-BS+) pages only. + if ( + this.isDrilling && + item.path && + !item.betterseqta && + getPagePathFromHash() !== item.path + ) { + location.hash = `?page=${item.path}`; + } return; }