DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
test(web): cover code block appearance preferences
Dryice Liu9cf8829f3b5b
diff --git a/web/scripts/register-node-test-aliases.cjs b/web/scripts/register-node-test-aliases.cjsnew file mode 100644index 000000000..465b428c5--- /dev/null+++ b/web/scripts/register-node-test-aliases.cjs@@ -0,0 +1,19 @@+const Module = require("node:module");+const path = require("node:path");++const distRoot = path.join(process.cwd(), "dist", "node-tests");+const originalResolveFilename = Module._resolveFilename;++Module._resolveFilename = function (request, parent, isMain, options) {+ if (typeof request === "string" && request.startsWith("@/")) {+ return originalResolveFilename.call(+ this,+ path.join(distRoot, request.slice(2)),+ parent,+ isMain,+ options,+ );+ }++ return originalResolveFilename.call(this, request, parent, isMain, options);+};diff --git a/web/scripts/run-node-tests.mjs b/web/scripts/run-node-tests.mjsindex d553fd36f..a23c80b3f 100644--- a/web/scripts/run-node-tests.mjs+++ b/web/scripts/run-node-tests.mjs@@ -51,4 +51,9 @@ if (testFiles.length === 0) {process.exit(1);}-run(process.execPath, ["--test", ...testFiles]);+run(process.execPath, [+ "-r",+ "./scripts/register-node-test-aliases.cjs",+ "--test",+ ...testFiles,+]);diff --git a/web/tests/app-shell-storage-code-block.test.ts b/web/tests/app-shell-storage-code-block.test.tsnew file mode 100644index 000000000..3433b58cc--- /dev/null+++ b/web/tests/app-shell-storage-code-block.test.ts@@ -0,0 +1,158 @@+import test from "node:test";+import assert from "node:assert/strict";++// Mock window localStorage for node test environment+let mockLocalStorage: Record<string, string> = {};+let mockSessionStorage: Record<string, string> = {};++function mockWindow() {+ global.window = {+ localStorage: {+ getItem: (key: string) => mockLocalStorage[key] ?? null,+ setItem: (key: string, value: string) => {+ mockLocalStorage[key] = value;+ },+ removeItem: (key: string) => {+ delete mockLocalStorage[key];+ },+ },+ sessionStorage: {+ getItem: (key: string) => mockSessionStorage[key] ?? null,+ setItem: (key: string, value: string) => {+ mockSessionStorage[key] = value;+ },+ removeItem: (key: string) => {+ delete mockSessionStorage[key];+ },+ },+ dispatchEvent: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ } as any;+}++mockWindow();++// Import after mocking window+import {+ CODE_BLOCK_THEME_STORAGE_KEY,+ DEFAULT_CODE_BLOCK_THEME,+ readStoredCodeBlockTheme,+ CODE_BLOCK_SHOW_LINE_NUMBERS_STORAGE_KEY,+ DEFAULT_CODE_BLOCK_SHOW_LINE_NUMBERS,+ readStoredCodeBlockShowLineNumbers,+ writeStoredCodeBlockTheme,+ writeStoredCodeBlockShowLineNumbers,+ CODE_BLOCK_WRAP_LONG_LINES_STORAGE_KEY,+ DEFAULT_CODE_BLOCK_WRAP_LONG_LINES,+ readStoredCodeBlockWrapLongLines,+ writeStoredCodeBlockWrapLongLines,+ CODE_BLOCK_SETTINGS_EVENT,+} from "../context/app-shell-storage";++test("app-shell-storage: code block theme defaults to oneDark", () => {+ assert.equal(DEFAULT_CODE_BLOCK_THEME, "oneDark");+ assert.equal(CODE_BLOCK_THEME_STORAGE_KEY, "deeptutor.code-block-theme");++ // When no value is stored, read returns default+ mockLocalStorage = {}; // Clear+ const theme = readStoredCodeBlockTheme();+ assert.equal(theme, "oneDark");+});++test("app-shell-storage: code block show line numbers defaults to false", () => {+ assert.equal(DEFAULT_CODE_BLOCK_SHOW_LINE_NUMBERS, false);+ assert.equal(+ CODE_BLOCK_SHOW_LINE_NUMBERS_STORAGE_KEY,+ "deeptutor.code-block-show-line-numbers",+ );++ // When no value is stored, read returns default+ mockLocalStorage = {}; // Clear+ const showLineNumbers = readStoredCodeBlockShowLineNumbers();+ assert.equal(showLineNumbers, false);+});++test("app-shell-storage: code block wrap long lines defaults to false", () => {+ assert.equal(DEFAULT_CODE_BLOCK_WRAP_LONG_LINES, false);+ assert.equal(+ CODE_BLOCK_WRAP_LONG_LINES_STORAGE_KEY,+ "deeptutor.code-block-wrap-long-lines",+ );++ // When no value is stored, read returns default+ mockLocalStorage = {}; // Clear+ const wrapLongLines = readStoredCodeBlockWrapLongLines();+ assert.equal(wrapLongLines, false);+});++test("app-shell-storage: write and read code block theme", () => {+ // Clear first+ mockLocalStorage = {};++ // Write a theme+ writeStoredCodeBlockTheme("dracula");+ assert.equal(readStoredCodeBlockTheme(), "dracula");++ // Write another theme+ writeStoredCodeBlockTheme("oneLight");+ assert.equal(readStoredCodeBlockTheme(), "oneLight");+});++test("app-shell-storage: write and read code block show line numbers", () => {+ // Clear first+ mockLocalStorage = {};++ // Write true+ writeStoredCodeBlockShowLineNumbers(true);+ assert.equal(readStoredCodeBlockShowLineNumbers(), true);++ // Write false+ writeStoredCodeBlockShowLineNumbers(false);+ assert.equal(readStoredCodeBlockShowLineNumbers(), false);+});++test("app-shell-storage: write and read code block wrap long lines", () => {+ // Clear first+ mockLocalStorage = {};++ // Write true+ writeStoredCodeBlockWrapLongLines(true);+ assert.equal(readStoredCodeBlockWrapLongLines(), true);++ // Write false+ writeStoredCodeBlockWrapLongLines(false);+ assert.equal(readStoredCodeBlockWrapLongLines(), false);+});++test("app-shell-storage: CODE_BLOCK_SETTINGS_EVENT constant exists", () => {+ assert.equal(CODE_BLOCK_SETTINGS_EVENT, "deeptutor:code-block-settings");+});++test("app-shell-storage: write dispatches CODE_BLOCK_SETTINGS_EVENT", () => {+ let dispatchedEvents: Array<{ type: string; detail: any }> = [];++ (global.window as any).dispatchEvent = (event: any) => {+ dispatchedEvents.push({ type: event.type, detail: event.detail });+ };++ // Clear and write+ mockLocalStorage = {};+ dispatchedEvents = [];++ writeStoredCodeBlockTheme("dracula");+ assert.equal(dispatchedEvents.length, 1);+ assert.equal(dispatchedEvents[0].type, CODE_BLOCK_SETTINGS_EVENT);+ assert.equal(dispatchedEvents[0].detail.codeBlockTheme, "dracula");++ // Write another setting+ writeStoredCodeBlockShowLineNumbers(true);+ assert.equal(dispatchedEvents.length, 2);+ assert.equal(dispatchedEvents[1].type, CODE_BLOCK_SETTINGS_EVENT);+ assert.equal(dispatchedEvents[1].detail.codeBlockShowLineNumbers, true);++ writeStoredCodeBlockWrapLongLines(false);+ assert.equal(dispatchedEvents.length, 3);+ assert.equal(dispatchedEvents[2].type, CODE_BLOCK_SETTINGS_EVENT);+ assert.equal(dispatchedEvents[2].detail.codeBlockWrapLongLines, false);+});\ No newline at end of filediff --git a/web/tests/appearance-settings-page.test.ts b/web/tests/appearance-settings-page.test.tsnew file mode 100644index 000000000..ab23b6464--- /dev/null+++ b/web/tests/appearance-settings-page.test.ts@@ -0,0 +1,73 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";++import { CODE_BLOCK_THEME_OPTIONS } from "../components/common/code-block-themes";++const appearancePagePath = path.join(+ process.cwd(),+ "app",+ "(utility)",+ "settings",+ "appearance",+ "page.tsx",+);++function readAppearancePage() {+ return fs.readFileSync(appearancePagePath, "utf8");+}++test("appearance settings page: adds the code blocks section after the theme section", () => {+ const source = readAppearancePage();++ const themeIndex = source.indexOf('title={t("Theme")}');+ const codeBlocksIndex = source.indexOf('title={t("Code blocks")}');++ assert.notEqual(themeIndex, -1, "Theme section should exist");+ assert.notEqual(codeBlocksIndex, -1, "Code blocks section should exist");+ assert.ok(+ codeBlocksIndex > themeIndex,+ "Code blocks section should come after Theme",+ );+});++test("appearance settings page: wires syntax theme select and toggle controls to settings context", () => {+ const source = readAppearancePage();++ assert.match(source, /codeBlockTheme/);+ assert.match(source, /updateCodeBlockTheme/);+ assert.match(source, /codeBlockShowLineNumbers/);+ assert.match(source, /updateCodeBlockShowLineNumbers/);+ assert.match(source, /codeBlockWrapLongLines/);+ assert.match(source, /updateCodeBlockWrapLongLines/);+ assert.match(source, /CODE_BLOCK_THEME_OPTIONS/);+ assert.match(source, /<Toggle/);+});++test("appearance settings page: renders code-block switch checked state from app-shell storage", () => {+ const source = readAppearancePage();++ assert.match(+ source,+ /readStoredCodeBlockShowLineNumbers/,+ "Code-block switches must hydrate from app-shell storage so reloaded localStorage true values render checked.",+ );+ assert.match(+ source,+ /checked=\{showLineNumbersChecked\}/,+ "Show line numbers switch should render from page-local storage-hydrated state, not the SettingsContext default false initializer.",+ );+ assert.match(+ source,+ /checked=\{wrapLongLinesChecked\}/,+ "Wrap long lines switch should render from page-local storage-hydrated state, not the SettingsContext default false initializer.",+ );+});++test("appearance settings page: exposes every registered code block theme option in the select", () => {+ const source = readAppearancePage();++ assert.ok(CODE_BLOCK_THEME_OPTIONS.length > 0);+ assert.match(source, /CODE_BLOCK_THEME_OPTIONS\.map/);+});diff --git a/web/tests/code-block-themes.test.ts b/web/tests/code-block-themes.test.tsnew file mode 100644index 000000000..6c1270a1e--- /dev/null+++ b/web/tests/code-block-themes.test.ts@@ -0,0 +1,181 @@+import { test } from "node:test";+import { strict as assert } from "node:assert";+import { readFileSync } from "node:fs";+import path from "node:path";+import {+ CODE_BLOCK_THEME_OPTIONS,+ DEFAULT_CODE_BLOCK_THEME_ID,+ getCodeBlockTheme,+ getCodeBlockThemeBackground,+} from "../components/common/code-block-themes";++test("code-block-themes: registry has exactly 46 options", () => {+ assert.equal(CODE_BLOCK_THEME_OPTIONS.length, 46);+});++test("code-block-themes: every option has a non-null style object", () => {+ for (const option of CODE_BLOCK_THEME_OPTIONS) {+ assert.ok(option.style, `Theme ${option.id} has a null style object`);+ assert.ok(+ typeof option.style === "object",+ `Theme ${option.id} style is not an object`,+ );+ }+});++test("code-block-themes: default theme ID is oneDark", () => {+ assert.equal(DEFAULT_CODE_BLOCK_THEME_ID, "oneDark");+});++test("code-block-themes: every option ID is unique", () => {+ const ids = CODE_BLOCK_THEME_OPTIONS.map((opt) => opt.id);+ const uniqueIds = new Set(ids);+ assert.equal(uniqueIds.size, ids.length, "All theme IDs should be unique");+});++test("code-block-themes: every option has a non-empty label", () => {+ for (const option of CODE_BLOCK_THEME_OPTIONS) {+ assert.ok(+ option.label && option.label.trim().length > 0,+ `Theme ${option.id} has an empty label`,+ );+ }+});++test("code-block-themes: getCodeBlockTheme returns the correct style for valid IDs", () => {+ const oneDarkOption = CODE_BLOCK_THEME_OPTIONS.find((opt) => opt.id === "oneDark");+ assert.ok(oneDarkOption, "oneDark option should exist");++ const style = getCodeBlockTheme("oneDark");+ assert.strictEqual(style, oneDarkOption?.style);++ // Test a few more themes+ const draculaStyle = getCodeBlockTheme("dracula");+ assert.ok(draculaStyle, "dracula style should be non-null");++ const vscDarkPlusStyle = getCodeBlockTheme("vscDarkPlus");+ assert.ok(vscDarkPlusStyle, "vscDarkPlus style should be non-null");+});++test("code-block-themes: getCodeBlockTheme falls back to oneDark for invalid IDs", () => {+ const oneDarkStyle = CODE_BLOCK_THEME_OPTIONS.find((opt) => opt.id === "oneDark")?.style;+ assert.ok(oneDarkStyle, "oneDark style should exist");++ const invalidStyle = getCodeBlockTheme("non-existent-theme");+ assert.strictEqual(invalidStyle, oneDarkStyle);++ const emptyStyle = getCodeBlockTheme("");+ assert.strictEqual(emptyStyle, oneDarkStyle);++ const undefinedStyle = getCodeBlockTheme(undefined as any);+ assert.strictEqual(undefinedStyle, oneDarkStyle);+});++test("code-block-themes: getCodeBlockThemeBackground extracts background color", () => {+ const oneDarkOption = CODE_BLOCK_THEME_OPTIONS.find((opt) => opt.id === "oneDark");+ assert.ok(oneDarkOption, "oneDark option should exist");++ const background = getCodeBlockThemeBackground(oneDarkOption.style);+ // oneDark should have a background color+ assert.ok(background, "oneDark theme should have a background color");+ assert.ok(typeof background === "string", "background should be a string");+});++test("code-block-themes: getCodeBlockThemeBackground returns undefined when no background", () => {+ const minimalStyle = {} as any;+ const background = getCodeBlockThemeBackground(minimalStyle);+ assert.strictEqual(background, undefined);+});++test("code-block-themes: getCodeBlockThemeBackground handles backgroundColor-only themes", () => {+ const backgroundColorOnlyStyle = {+ 'pre[class*="language-"]': {+ backgroundColor: "#fdf6e3",+ },+ } as any;++ const background = getCodeBlockThemeBackground(backgroundColorOnlyStyle);+ assert.strictEqual(background, "#fdf6e3", "backgroundColor-only themes should return their backgroundColor");+});++test("code-block-themes: getCodeBlockThemeBackground prefers backgroundColor over background", () => {+ const bothPropertiesStyle = {+ 'pre[class*="language-"]': {+ backgroundColor: "#fdf6e3",+ background: "#1f2937",+ },+ } as any;++ const background = getCodeBlockThemeBackground(bothPropertiesStyle);+ assert.strictEqual(background, "#fdf6e3", "backgroundColor should take precedence over background");+});++test("code-block-themes: all 46 theme IDs are from the installed Prism files", () => {+ const expectedIds = [+ "a11yDark",+ "a11yOneLight",+ "atomDark",+ "base16AteliersulphurpoolLight",+ "cb",+ "coldarkCold",+ "coldarkDark",+ "coyWithoutShadows",+ "coy",+ "darcula",+ "dark",+ "dracula",+ "duotoneDark",+ "duotoneEarth",+ "duotoneForest",+ "duotoneLight",+ "duotoneSea",+ "duotoneSpace",+ "funky",+ "ghcolors",+ "gruvboxDark",+ "gruvboxLight",+ "holiTheme",+ "hopscotch",+ "lucario",+ "materialDark",+ "materialLight",+ "materialOceanic",+ "nightOwl",+ "nord",+ "okaidia",+ "oneDark",+ "oneLight",+ "pojoaque",+ "prism",+ "shadesOfPurple",+ "solarizedDarkAtom",+ "solarizedlight",+ "synthwave84",+ "tomorrow",+ "twilight",+ "vsDark",+ "vs",+ "vscDarkPlus",+ "xonokai",+ "zTouch",+ ];++ const actualIds = CODE_BLOCK_THEME_OPTIONS.map((opt) => opt.id).sort();+ assert.deepStrictEqual(actualIds, expectedIds.sort(), "Theme IDs should match expected list");+});++test("code-block-themes: every theme in expected list has a style", () => {+ for (const id of CODE_BLOCK_THEME_OPTIONS.map((opt) => opt.id)) {+ const style = getCodeBlockTheme(id);+ assert.ok(style, `Theme ${id} should resolve to a style object`);+ }+});++test("app-shell-context: theme change subscription is registered exactly once", () => {+ const source = readFileSync(+ path.join(process.cwd(), "context", "AppShellContext.tsx"),+ "utf8",+ );+ const matches = source.match(/subscribeToThemeChanges\s*\(/g) ?? [];+ assert.equal(matches.length, 1);+});diff --git a/web/tests/markdown-renderer-code-fallback.test.ts b/web/tests/markdown-renderer-code-fallback.test.tsnew file mode 100644index 000000000..9cd647723--- /dev/null+++ b/web/tests/markdown-renderer-code-fallback.test.ts@@ -0,0 +1,49 @@+import test from "node:test";+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import path from "node:path";++const richRendererSource = readFileSync(+ path.join(process.cwd(), "components/common/RichMarkdownRenderer.tsx"),+ "utf8",+);+const simpleRendererSource = readFileSync(+ path.join(process.cwd(), "components/common/SimpleMarkdownRenderer.tsx"),+ "utf8",+);++test("rich-markdown-renderer: non-rich multiline fallback documents settings boundary", () => {+ assert.match(+ richRendererSource,+ /code-block appearance settings apply only when rich code rendering is enabled/i,+ );+});++test("simple-markdown-renderer: compatibility fallback documents settings boundary", () => {+ assert.match(+ simpleRendererSource,+ /compatibility fallback/i,+ );+ assert.match(+ simpleRendererSource,+ /does not consume the[\s\S]*code-block theme registry/i,+ );+});++test("rich-markdown-renderer: enableCode=false keeps multiline code as static readable fallback", () => {+ assert.match(richRendererSource, /if \(isMultiline && enableCode\)/);+ assert.match(richRendererSource, /if \(isMultiline\)/);+ assert.match(richRendererSource, /bg-\[\#1f2937\]/);+ assert.match(richRendererSource, /text-\[\#e5e7eb\]/);+ assert.doesNotMatch(richRendererSource, /showLineNumbers=/);+ assert.doesNotMatch(richRendererSource, /wrapLongLines=/);+});++test("simple-markdown-renderer: multiline code remains a static compatibility block", () => {+ assert.match(simpleRendererSource, /raw\.includes\("\\n"\)/);+ assert.match(simpleRendererSource, /bg-\[\#1f2937\]/);+ assert.match(simpleRendererSource, /text-\[\#e5e7eb\]/);+ assert.doesNotMatch(simpleRendererSource, /code-block-themes/);+ assert.doesNotMatch(simpleRendererSource, /showLineNumbers=/);+ assert.doesNotMatch(simpleRendererSource, /wrapLongLines=/);+});diff --git a/web/tests/rich-code-block.test.ts b/web/tests/rich-code-block.test.tsnew file mode 100644index 000000000..2f9b48d96--- /dev/null+++ b/web/tests/rich-code-block.test.ts@@ -0,0 +1,212 @@+import test from "node:test";+import assert from "node:assert/strict";+import React from "react";+import { renderToStaticMarkup } from "react-dom/server";+import RichCodeBlock from "../components/common/RichCodeBlock";+import { AppShellProvider } from "../context/AppShellContext";+import {+ getCodeBlockTheme,+ getCodeBlockThemeBackground,+} from "../components/common/code-block-themes";+import {+ CODE_BLOCK_SHOW_LINE_NUMBERS_STORAGE_KEY,+ CODE_BLOCK_THEME_STORAGE_KEY,+ CODE_BLOCK_WRAP_LONG_LINES_STORAGE_KEY,+} from "../context/app-shell-storage";++let mockLocalStorage: Record<string, string> = {};+let mockSessionStorage: Record<string, string> = {};++function installMockWindow() {+ const localStorage = {+ getItem: (key: string) => mockLocalStorage[key] ?? null,+ setItem: (key: string, value: string) => {+ mockLocalStorage[key] = value;+ },+ removeItem: (key: string) => {+ delete mockLocalStorage[key];+ },+ };++ const sessionStorage = {+ getItem: (key: string) => mockSessionStorage[key] ?? null,+ setItem: (key: string, value: string) => {+ mockSessionStorage[key] = value;+ },+ removeItem: (key: string) => {+ delete mockSessionStorage[key];+ },+ };++ global.window = {+ localStorage,+ sessionStorage,+ dispatchEvent: () => true,+ addEventListener: () => {},+ removeEventListener: () => {},+ matchMedia: () => ({+ matches: false,+ media: "(prefers-color-scheme: dark)",+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => true,+ }),+ } as any;++ global.localStorage = localStorage as any;+ global.sessionStorage = sessionStorage as any;+}++installMockWindow();++function renderCodeBlock(raw: string, lang: string) {+ return renderToStaticMarkup(+ React.createElement(+ AppShellProvider,+ null,+ React.createElement(RichCodeBlock, { raw, lang }),+ ),+ );+}++test("rich-code-block: highlighted blocks use selected theme background instead of hardcoded dark styling", () => {+ mockLocalStorage = {+ [CODE_BLOCK_THEME_STORAGE_KEY]: "oneLight",+ [CODE_BLOCK_SHOW_LINE_NUMBERS_STORAGE_KEY]: "false",+ [CODE_BLOCK_WRAP_LONG_LINES_STORAGE_KEY]: "false",+ };+ mockSessionStorage = {};++ const html = renderCodeBlock("const value = 1;", "js");+ const oneLightBackground = getCodeBlockThemeBackground(getCodeBlockTheme("oneLight"));++ assert.ok(oneLightBackground, "oneLight should expose a background color");+ assert.match(+ html,+ new RegExp(`background(?:-color)?:${oneLightBackground.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`),+ );+ assert.doesNotMatch(html, /background:#1f2937/);+});++test("rich-code-block: highlighted blocks honor line-number and wrap preferences", () => {+ mockLocalStorage = {+ [CODE_BLOCK_THEME_STORAGE_KEY]: "dracula",+ [CODE_BLOCK_SHOW_LINE_NUMBERS_STORAGE_KEY]: "true",+ [CODE_BLOCK_WRAP_LONG_LINES_STORAGE_KEY]: "true",+ };+ mockSessionStorage = {};++ const html = renderCodeBlock("print('hello')\nprint('world')", "python");++ assert.match(html, /react-syntax-highlighter-line-number/);+ // The outer <pre> must itself wrap; matching pre-wrap only on the inner+ // <code> gave false confidence while long lines were clipped at runtime.+ assert.match(html, /<pre[^>]*style="[^"]*white-space:pre-wrap[^"]*"/);+});++test("rich-code-block: plain text blocks honor line-number and wrap preferences", () => {+ mockLocalStorage = {+ [CODE_BLOCK_THEME_STORAGE_KEY]: "oneDark",+ [CODE_BLOCK_SHOW_LINE_NUMBERS_STORAGE_KEY]: "true",+ [CODE_BLOCK_WRAP_LONG_LINES_STORAGE_KEY]: "true",+ };+ mockSessionStorage = {};++ const html = renderCodeBlock("plain text line\nanother line", "text");++ assert.match(html, /react-syntax-highlighter-line-number/);+ assert.match(html, /<pre[^>]*style="[^"]*white-space:pre-wrap[^"]*"/);+ assert.doesNotMatch(html, /unknown language/i);+});++test("rich-code-block: wrap disabled keeps the outer <pre> unwrapped and horizontally scrollable", () => {+ mockLocalStorage = {+ [CODE_BLOCK_THEME_STORAGE_KEY]: "dracula",+ [CODE_BLOCK_SHOW_LINE_NUMBERS_STORAGE_KEY]: "false",+ [CODE_BLOCK_WRAP_LONG_LINES_STORAGE_KEY]: "false",+ };+ mockSessionStorage = {};++ const html = renderCodeBlock(+ "const veryLongLine = 'this should stay on one line and scroll instead of wrapping';",+ "javascript",+ );++ // When wrap is off, the outer <pre> must NOT receive pre-wrap (otherwise+ // wrapping would be forced even with the setting disabled) and must keep+ // horizontal scroll available so long lines are reachable, not clipped.+ assert.doesNotMatch(html, /<pre[^>]*style="[^"]*white-space:pre-wrap[^"]*"/);+ assert.match(html, /<pre[^>]*style="[^"]*overflow-x:auto[^"]*"/);+});++test("rich-code-block: wrap mode breaks long unbroken tokens instead of clipping them", () => {+ mockLocalStorage = {+ [CODE_BLOCK_THEME_STORAGE_KEY]: "oneLight",+ [CODE_BLOCK_SHOW_LINE_NUMBERS_STORAGE_KEY]: "false",+ [CODE_BLOCK_WRAP_LONG_LINES_STORAGE_KEY]: "true",+ };+ mockSessionStorage = {};++ // F3 browser-proven case: a 200-char unbroken token (no whitespace) still+ // overflowed with only white-space:pre-wrap on the outer <pre>, because+ // pre-wrap breaks only at whitespace and a long identifier/string/URL has+ // no break opportunity. The renderer must additionally emit+ // overflow-wrap:break-word so the browser is permitted to split the token+ // mid-word when it would otherwise overflow. Asserting on BOTH the outer+ // <pre> and the inner <code> because the line layout uses per-line flex+ // rows and inheritance must reach the token spans from both levels.+ const longUnbrokenToken = "a".repeat(200);+ const html = renderCodeBlock(longUnbrokenToken, "javascript");++ assert.match(html, /<pre[^>]*style="[^"]*overflow-wrap:break-word[^"]*"/);+ assert.match(html, /<code[^>]*style="[^"]*overflow-wrap:break-word[^"]*"/);+});++test("rich-code-block: wrap + line-numbers does not let per-line flex wrappers defeat overflow-wrap", () => {+ mockLocalStorage = {+ [CODE_BLOCK_THEME_STORAGE_KEY]: "oneLight",+ [CODE_BLOCK_SHOW_LINE_NUMBERS_STORAGE_KEY]: "true",+ [CODE_BLOCK_WRAP_LONG_LINES_STORAGE_KEY]: "true",+ };+ mockSessionStorage = {};++ // F3 rerun-2 browser-proven case: with wrap AND line-numbers both on,+ // react-syntax-highlighter's highlight.js (lines 99-103) forces each+ // per-line span wrapper to display:flex so the line-number gutter can+ // align in a column. That flex layout makes each token span a flex item+ // with the default min-width:auto, which CANNOT shrink below content+ // size — so a long unbreakable token overflows the line wrapper (F3+ // measured the nested flex line wrapper at clientWidth 536 /+ // scrollWidth 4326 for the short-token case, and 536 / 2319 for the+ // 240-char unbroken-token case). overflow-wrap:break-word was already+ // correctly set on <pre> and <code> but could not propagate its break+ // behavior into unshrinkable flex items, so the visible result was a+ // horizontal clip. The outer-<pre> and overflow-wrap regressions above+ // guard the previously fixed layers; this regression guards the+ // remaining flex-line-wrapper cause specifically.+ const longUnbrokenToken = "a".repeat(200);+ const html = renderCodeBlock(`${longUnbrokenToken} tail`, "javascript");++ // Line numbers must still be emitted so we know we are exercising the+ // wrap+line-numbers code path that triggers the library's display:flex.+ assert.match(html, /react-syntax-highlighter-line-number/);++ const codeMatch = html.match(/<code[^>]*>([\s\S]*?)<\/code>/);+ assert.ok(codeMatch, "<code> element should exist in rendered output");+ const codeInner = codeMatch[1];++ // No span inside <code> may carry display:flex when wrap is enabled:+ // that style is the proximate cause of the F3 live-browser clip. The+ // per-line wrapper must lay out as a normal block instead so that+ // overflow-wrap:break-word (inherited from <pre>/<code>) can break+ // long unbreakable tokens instead of being defeated by flex items+ // whose min-width:auto refuses to shrink.+ assert.doesNotMatch(+ codeInner,+ /<span[^>]*style="[^"]*display:\s*flex[^"]*"/,+ "per-line span wrapper inside <code> must not be display:flex when wrap is enabled",+ );+});diff --git a/web/tests/settings-context-boolean-hydration.test.ts b/web/tests/settings-context-boolean-hydration.test.tsnew file mode 100644index 000000000..899d924c1--- /dev/null+++ b/web/tests/settings-context-boolean-hydration.test.ts@@ -0,0 +1,80 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";++import { readStoredCodeBlockShowLineNumbers, readStoredCodeBlockWrapLongLines, writeStoredCodeBlockShowLineNumbers, writeStoredCodeBlockWrapLongLines } from "@/context/app-shell-storage";++const settingsContextPath = path.join(+ process.cwd(),+ "components",+ "settings",+ "SettingsContext.tsx",+);++function readSettingsContextSource() {+ return fs.readFileSync(settingsContextPath, "utf8");+}++function mockWindow() {+ global.window = {+ localStorage: {+ getItem: (key: string) => (global.window as any).localStorage._storage[key] ?? null,+ setItem: (key: string, value: string) => {+ (global.window as any).localStorage._storage[key] = value;+ },+ removeItem: (key: string) => {+ delete (global.window as any).localStorage._storage[key];+ },+ },+ dispatchEvent: () => true,+ } as any;+ (global.window as any).localStorage._storage = {};+}++test("readStoredCodeBlockShowLineNumbers returns true when localStorage has string 'true'", () => {+ mockWindow();+ writeStoredCodeBlockShowLineNumbers(true);+ assert.equal(readStoredCodeBlockShowLineNumbers(), true);+});++test("readStoredCodeBlockWrapLongLines returns true when localStorage has string 'true'", () => {+ mockWindow();+ writeStoredCodeBlockWrapLongLines(true);+ assert.equal(readStoredCodeBlockWrapLongLines(), true);+});++test("readStoredCodeBlockShowLineNumbers returns false when localStorage is undefined (SSR)", () => {+ (global.window as any) = undefined as any;+ assert.equal(readStoredCodeBlockShowLineNumbers(), false, "Should return default false when window is undefined");+});++test("readStoredCodeBlockWrapLongLines returns false when localStorage is undefined (SSR)", () => {+ (global.window as any) = undefined as any;+ assert.equal(readStoredCodeBlockWrapLongLines(), false, "Should return default false when window is undefined");+});++test("settings-context: code-block boolean switches hydrate after first render", () => {+ const source = readSettingsContextSource();++ assert.doesNotMatch(+ source,+ /useState<\s*UiSettings\["code_block_show_line_numbers"\]\s*>\(\(\) =>\s*readStoredCodeBlockShowLineNumbers\(\)\s*\)/,+ "Show line numbers must not read localStorage during the first render, or React can keep the server-rendered aria-checked=false DOM after reload.",+ );+ assert.doesNotMatch(+ source,+ /useState<\s*UiSettings\["code_block_wrap_long_lines"\]\s*>\(\(\) =>\s*readStoredCodeBlockWrapLongLines\(\)\s*\)/,+ "Wrap long lines must not read localStorage during the first render, or React can keep the server-rendered aria-checked=false DOM after reload.",+ );+ assert.match(+ source,+ /setCodeBlockShowLineNumbers\(\s*readStoredCodeBlockShowLineNumbers\(\)\s*\)/,+ "Show line numbers should re-read localStorage after mount so persisted true forces a DOM update.",+ );+ assert.match(+ source,+ /setCodeBlockWrapLongLines\(\s*readStoredCodeBlockWrapLongLines\(\)\s*\)/,+ "Wrap long lines should re-read localStorage after mount so persisted true forces a DOM update.",+ );+});diff --git a/web/tests/settings-context-ui-sync.test.ts b/web/tests/settings-context-ui-sync.test.tsnew file mode 100644index 000000000..2643184b0--- /dev/null+++ b/web/tests/settings-context-ui-sync.test.ts@@ -0,0 +1,231 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";++let mockLocalStorage: Record<string, string> = {};+let mockSessionStorage: Record<string, string> = {};+let dispatchedEvents: Array<{ type: string; detail: any }> = [];++function mockWindow() {+ global.window = {+ localStorage: {+ getItem: (key: string) => mockLocalStorage[key] ?? null,+ setItem: (key: string, value: string) => {+ mockLocalStorage[key] = value;+ },+ removeItem: (key: string) => {+ delete mockLocalStorage[key];+ },+ },+ sessionStorage: {+ getItem: (key: string) => mockSessionStorage[key] ?? null,+ setItem: (key: string, value: string) => {+ mockSessionStorage[key] = value;+ },+ removeItem: (key: string) => {+ delete mockSessionStorage[key];+ },+ },+ dispatchEvent: (event: any) => {+ dispatchedEvents.push({ type: event.type, detail: event.detail });+ return true;+ },+ addEventListener: () => {},+ removeEventListener: () => {},+ } as any;+}++mockWindow();++import * as settingsContext from "../components/settings/SettingsContext";+import {+ CODE_BLOCK_SETTINGS_EVENT,+ readStoredCodeBlockShowLineNumbers,+ readStoredCodeBlockTheme,+ readStoredCodeBlockWrapLongLines,+} from "../context/app-shell-storage";++const settingsContextPath = path.join(+ process.cwd(),+ "components",+ "settings",+ "SettingsContext.tsx",+);++function readSettingsContextSource() {+ return fs.readFileSync(settingsContextPath, "utf8");+}++test("settings-context: syncLoadedCodeBlockSettingsToAppShell writes backend-loaded values into app-shell storage", () => {+ const sync = (settingsContext as any).syncLoadedCodeBlockSettingsToAppShell;++ assert.equal(typeof sync, "function");++ mockLocalStorage = {};+ dispatchedEvents = [];++ const normalized = sync({+ code_block_theme: "dracula",+ code_block_show_line_numbers: true,+ code_block_wrap_long_lines: true,+ });++ assert.equal(readStoredCodeBlockTheme(), "dracula");+ assert.equal(readStoredCodeBlockShowLineNumbers(), true);+ assert.equal(readStoredCodeBlockWrapLongLines(), true);+ assert.deepEqual(normalized, {+ code_block_theme: "dracula",+ code_block_show_line_numbers: true,+ code_block_wrap_long_lines: true,+ });+ assert.equal(+ dispatchedEvents.filter((event) => event.type === CODE_BLOCK_SETTINGS_EVENT)+ .length,+ 3,+ );+});++test("settings-context: persistUiSettingsPatch sends only the changed code-block field", async () => {+ const persist = (settingsContext as any).persistUiSettingsPatch;++ assert.equal(typeof persist, "function");++ let capturedInput: unknown;+ let capturedInit: RequestInit | undefined;++ await persist(+ {+ code_block_theme: "dracula",+ },+ async (input: RequestInfo | URL, init?: RequestInit) => {+ capturedInput = input;+ capturedInit = init;+ return { ok: true } as Response;+ },+ );++ assert.match(String(capturedInput), /\/api\/v1\/settings\/ui$/);+ assert.equal(capturedInit?.method, "PUT");+ assert.deepEqual(JSON.parse(String(capturedInit?.body)), {+ code_block_theme: "dracula",+ });+});++test("settings-context: persistUiSettingsPatch can save theme without sending code-block fields", async () => {+ const persist = (settingsContext as any).persistUiSettingsPatch;++ assert.equal(typeof persist, "function");++ let capturedInit: RequestInit | undefined;++ await persist(+ {+ theme: "dark",+ },+ async (_input: RequestInfo | URL, init?: RequestInit) => {+ capturedInit = init;+ return { ok: true } as Response;+ },+ );++ assert.deepEqual(JSON.parse(String(capturedInit?.body)), {+ theme: "dark",+ });+});++test("settings-context: boolean values survive reload cycle from localStorage", () => {+ const sync = (settingsContext as any).syncLoadedCodeBlockSettingsToAppShell;++ mockLocalStorage = {};+ sync({+ code_block_theme: "dracula",+ code_block_show_line_numbers: true,+ code_block_wrap_long_lines: true,+ });++ assert.equal(readStoredCodeBlockTheme(), "dracula");+ assert.equal(readStoredCodeBlockShowLineNumbers(), true);+ assert.equal(readStoredCodeBlockWrapLongLines(), true);++ assert.equal(readStoredCodeBlockTheme(), "dracula", "Theme should persist across reload");+ assert.equal(readStoredCodeBlockShowLineNumbers(), true, "Show line numbers should persist across reload");+ assert.equal(readStoredCodeBlockWrapLongLines(), true, "Wrap long lines should persist across reload");++ const secondSync = sync({+ code_block_theme: "dracula",+ code_block_show_line_numbers: true,+ code_block_wrap_long_lines: true,+ });++ assert.equal(secondSync.code_block_show_line_numbers, true, "Show line numbers should remain true after backend sync");+ assert.equal(secondSync.code_block_wrap_long_lines, true, "Wrap long lines should remain true after backend sync");+});++test("settings-context: syncLoadedCodeBlockSettingsToAppShell handles string boolean representations from backend", () => {+ const sync = (settingsContext as any).syncLoadedCodeBlockSettingsToAppShell;++ mockLocalStorage = {};++ const result = sync({+ code_block_theme: "dracula",+ code_block_show_line_numbers: "True",+ code_block_wrap_long_lines: "true",+ });++ assert.equal(result.code_block_show_line_numbers, true, "String 'True' should be normalized to boolean true");+ assert.equal(result.code_block_wrap_long_lines, true, "String 'true' should be normalized to boolean true");+ assert.equal(readStoredCodeBlockShowLineNumbers(), true, "Line numbers should be stored as true");+ assert.equal(readStoredCodeBlockWrapLongLines(), true, "Wrap long lines should be stored as true");+});++test("settings-context: backend values override localStorage values during sync", () => {+ const sync = (settingsContext as any).syncLoadedCodeBlockSettingsToAppShell;++ // Simulate localStorage having different (old/stale) values+ mockLocalStorage = {+ "deeptutor.codeBlockShowLineNumbers": "false",+ "deeptutor.codeBlockWrapLongLines": "false",+ "deeptutor.codeBlockTheme": "oneDark",+ };++ // Backend returns true values+ const result = sync({+ code_block_theme: "dracula",+ code_block_show_line_numbers: true,+ code_block_wrap_long_lines: true,+ });++ // Verify backend values win+ assert.equal(result.code_block_show_line_numbers, true, "Backend true should override localStorage false");+ assert.equal(result.code_block_wrap_long_lines, true, "Backend true should override localStorage false");+ assert.equal(result.code_block_theme, "dracula", "Backend theme should override localStorage theme");++ // Verify localStorage is updated to backend values+ assert.equal(readStoredCodeBlockShowLineNumbers(), true, "localStorage should be updated to backend true");+ assert.equal(readStoredCodeBlockWrapLongLines(), true, "localStorage should be updated to backend true");+ assert.equal(readStoredCodeBlockTheme(), "dracula", "localStorage theme should be updated to backend value");++ // This test would fail if a post-mount effect re-read from localStorage,+ // as it would overwrite the backend-loaded true values with the old false values.+});++test("settings-context: backend code-block sync updates AppShell state directly", () => {+ const source = readSettingsContextSource();++ assert.match(+ source,+ /useAppShell/,+ "SettingsContext must not rely only on localStorage events; AppShell can miss those during effect ordering on reload.",+ );+ assert.match(+ source,+ /setAppShellCodeBlockShowLineNumbers\(\s*syncedCodeBlockSettings\.code_block_show_line_numbers,?\s*\)/,+ "Backend-loaded show-line-number values should update AppShell state directly.",+ );+ assert.match(+ source,+ /setAppShellCodeBlockWrapLongLines\(\s*syncedCodeBlockSettings\.code_block_wrap_long_lines,?\s*\)/,+ "Backend-loaded wrap-long-lines values should update AppShell state directly.",+ );+});diff --git a/web/tsconfig.node-tests.json b/web/tsconfig.node-tests.jsonindex aeb01cddd..fb5b38045 100644--- a/web/tsconfig.node-tests.json+++ b/web/tsconfig.node-tests.json@@ -4,10 +4,13 @@"noEmit": false,"outDir": "./dist/node-tests","rootDir": ".",+ "baseUrl": ".","module": "commonjs","moduleResolution": "node","incremental": false,- "paths": {}+ "paths": {+ "@/*": ["./*"]+ }},"include": ["tests/**/*.ts"]}