From ec2f044d8c3f76c140378c5b044a782a4673e43f Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 31 May 2026 10:32:56 +0800 Subject: [PATCH] =?UTF-8?q?docs(webui):=20=E5=88=B6=E5=AE=9A=E5=A4=A7?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E6=8B=86=E5=88=86=E8=AE=A1=E5=88=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../2026-05-31-split-webui-large-files.md | 982 ++++++++++++++++++ 1 file changed, 982 insertions(+) create mode 100644 docs/superpowers/plans/2026-05-31-split-webui-large-files.md diff --git a/docs/superpowers/plans/2026-05-31-split-webui-large-files.md b/docs/superpowers/plans/2026-05-31-split-webui-large-files.md new file mode 100644 index 0000000..9068f95 --- /dev/null +++ b/docs/superpowers/plans/2026-05-31-split-webui-large-files.md @@ -0,0 +1,982 @@ +# Split WebUI Large Files Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Continue the large-file split after `gui/gui_app.py` by modularizing the WebUI frontend and, only after the frontend is stable, splitting the Web GUI Python server. + +**Architecture:** Keep the current static WebUI behavior intact while moving code into focused `webui/js/*` and `webui/css/*` files. Each task changes one responsibility, preserves global names needed by `DOMContentLoaded`, runs focused tests, commits, and pushes before the next task. + +**Tech Stack:** Plain HTML/CSS/JavaScript, Python `http.server`, pytest, browser smoke test for UI changes. + +--- + +## Current Evidence + +From the current worktree on 2026-05-31: + +| File | Lines | Role | +|---|---:|---| +| `webui/styles.css` | 3745 | WebUI visual system, layout, panels, logs, responsive rules | +| `webui/app.js` | 2512 | WebUI constants, state, API calls, rendering, polling, event wiring | +| `gui/web_gui.py` | 1663 | local HTTP server, runner, API routes, static file serving | +| `webui/index.html` | 1232 | WebUI DOM structure and config bindings | + +`gui/gui_app.py` is already down to about 130 lines and should not be the next split target. The next target is the WebUI bundle. + +## Stop Conditions + +Stop this plan and write an outcome note when any one is true: + +1. `webui/app.js` is below 700 lines and `webui/styles.css` is below 1400 lines. +2. The next split would require changing more than 3 of the large files in one task. +3. Browser smoke finds a visual or runtime regression that cannot be fixed inside the current task boundary. +4. Tests fail and the fix would require behavior changes outside the current responsibility. + +## Verification Commands + +Run these after every JavaScript or HTML task: + +```powershell +python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1 +pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1 +``` + +Expected: + +```text +py_compile: exit code 0 +pytest: all selected tests PASS +``` + +Run these after every CSS or visual task: + +```powershell +python -m py_compile gui/web_gui.py > logs\webui_split_py_compile.log 2>&1 +pytest tests/test_webgui.py -q > logs\pytest_webui_split.log 2>&1 +``` + +Expected: + +```text +py_compile: exit code 0 +pytest: all selected tests PASS +``` + +For frontend visual changes, also start the Web GUI and inspect it in a browser: + +```powershell +python gui\web_gui.py +``` + +Expected browser checks: + +- `/` loads without a blank page. +- Console has no module load errors, syntax errors, or missing function errors. +- Header buttons, tabs, logs panel, reservations panel, high-value panel, screenshot preview, and footer remain visible without overlap at desktop width. +- At mobile width, command buttons wrap and panels remain readable. + +## Static Loading Decision + +The current page loads: + +```html + + +``` + +Use classic scripts for the first JavaScript split instead of ES modules. This avoids a broad initialization rewrite and keeps inline event expectations simple. New scripts must be loaded before `app.js` if `app.js` depends on them. + +For CSS, use multiple `` tags. Keep `styles.css` as the compatibility shell until the end of the CSS split. + +--- + +## Task 1: Add WebUI Static Asset Structure + +**Files:** +- Create: `webui/js/README.md` +- Create: `webui/css/README.md` +- Modify: `webui/index.html` + +- [ ] **Step 1: Create asset directory docs** + +Create `webui/js/README.md`: + +```markdown +# WebUI JavaScript modules + +Classic browser scripts loaded by `webui/index.html`. + +Load order matters: + +1. `constants.js` +2. `dom.js` +3. `api.js` +4. focused feature scripts +5. `app.js` + +Keep behavior-preserving splits small. Do not introduce a build step unless a later plan explicitly replaces this static layout. +``` + +Create `webui/css/README.md`: + +```markdown +# WebUI CSS modules + +Plain CSS files loaded by `webui/index.html`. + +Recommended order: + +1. `tokens.css` +2. `base.css` +3. `layout.css` +4. `components.css` +5. focused panel or feature CSS +6. `styles.css` compatibility remainder + +Keep selectors stable so existing HTML and JavaScript continue to work. +``` + +- [ ] **Step 2: Add no-op load anchors to `index.html`** + +Insert comments around the existing assets: + +```html + + +``` + +```html + + +``` + +- [ ] **Step 3: Verify** + +Run: + +```powershell +pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1 +``` + +Expected: selected tests PASS. + +- [ ] **Step 4: Commit and push** + +```powershell +git add webui/index.html webui/js/README.md webui/css/README.md +git commit -m "refactor(webui): add static module split structure" +git push +``` + +--- + +## Task 2: Extract JavaScript Constants and Copy + +**Files:** +- Create: `webui/js/constants.js` +- Modify: `webui/app.js` +- Modify: `webui/index.html` + +- [ ] **Step 1: Create `constants.js`** + +Move these top-level constants from `app.js` into `webui/js/constants.js` unchanged: + +```javascript +const UI_LIMITS = Object.freeze({ + runLogMaxLines: 50000, + runLogMaxChars: 200000, + actionsLogMaxLines: 5000, + scrollBottomThresholdPx: 5, + screenshotPollMs: 1500, + logPollMs: 800, + statsPollMs: 1200, +}); + +const UI_CLASS = Object.freeze({ + busy: "isBusy", + clickable: "isClickable", + collapsed: "isCollapsed", + listCollapsed: "isListCollapsed", + reservationHeader: "reservationHeader", + reservationBody: "reservationBody", + reservationsList: "reservationsList", + shotEmpty: "isShotEmpty", + statusRunning: "statusRunning", + statusIdle: "statusIdle", + statusError: "statusError", +}); + +const RUN_TONE = Object.freeze({ + running: "running", + idle: "idle", + error: "error", +}); +``` + +Also move `UI_COPY`, `TIMELINE_SERIES_KEYS`, `TIMELINE_LAYOUT`, `TIMELINE_STROKES`, and `DEFAULTS` unchanged. + +- [ ] **Step 2: Remove moved constants from `app.js`** + +Delete only the moved constant declarations from `webui/app.js`. Keep state variables such as `logIdx`, `pollTimer`, `runLogBuffer`, and `deviceOverviewState` in `app.js` for now. + +- [ ] **Step 3: Load `constants.js` before `app.js`** + +Change the bottom of `webui/index.html` to: + +```html + + + +``` + +- [ ] **Step 4: Verify** + +Run: + +```powershell +python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1 +pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1 +``` + +Expected: both PASS. + +- [ ] **Step 5: Browser smoke** + +Start: + +```powershell +python gui\web_gui.py +``` + +Open `http://127.0.0.1:8765/` or the printed local URL. Confirm console has no `UI_LIMITS is not defined`, `DEFAULTS is not defined`, or `fmtDuration is not defined` errors. + +- [ ] **Step 6: Commit and push** + +```powershell +git add webui/index.html webui/app.js webui/js/constants.js +git commit -m "refactor(webui): extract frontend constants" +git push +``` + +--- + +## Task 3: Extract DOM and Formatting Helpers + +**Files:** +- Create: `webui/js/dom_utils.js` +- Modify: `webui/app.js` +- Modify: `webui/index.html` + +- [ ] **Step 1: Create `dom_utils.js`** + +Move these functions from `app.js` into `webui/js/dom_utils.js` unchanged: + +```javascript +function $(id) +function setTextIfExists(id, text) +function clearEl(el) +function escapeHtml(s) +function fmtTime(ts) +function fmtNum(v) +function fmtDuration(seconds) +``` + +When implementing, copy the exact current function declarations and bodies from `webui/app.js`. + +- [ ] **Step 2: Remove moved functions from `app.js`** + +Delete the moved function declarations only. Do not move UI initialization functions yet. + +- [ ] **Step 3: Load `dom_utils.js` after `constants.js`** + +```html + + + +``` + +- [ ] **Step 4: Verify and smoke** + +Run the standard JavaScript verification commands. In browser console, confirm no `$ is not defined`, `fmtDuration is not defined`, or `escapeHtml is not defined` errors. + +- [ ] **Step 5: Commit and push** + +```powershell +git add webui/index.html webui/app.js webui/js/dom_utils.js +git commit -m "refactor(webui): extract DOM and format helpers" +git push +``` + +--- + +## Task 4: Extract API Client Helpers + +**Files:** +- Create: `webui/js/api_client.js` +- Modify: `webui/app.js` +- Modify: `webui/index.html` + +- [ ] **Step 1: Create `api_client.js`** + +Move these functions and state from `app.js` into `webui/js/api_client.js` unchanged: + +```javascript +let _apiFailStreak = 0; +const _apiFailThreshold = 2; +let _csrfToken = null; + +function setConnState(state) +function notifyApiOk() +function notifyApiFail() +async function apiGet(path) +async function getCsrfToken() +async function apiPost(path, body) +``` + +When implementing, copy the exact current function declarations and bodies from `webui/app.js`. + +- [ ] **Step 2: Remove moved declarations from `app.js`** + +Delete only the moved declarations. Keep feature-level functions such as `refreshDevices`, `startRun`, `pollLogs`, and `pollStats` in `app.js`. + +- [ ] **Step 3: Load `api_client.js` after `dom_utils.js`** + +```html + + + + +``` + +- [ ] **Step 4: Verify and smoke** + +Run the standard JavaScript verification commands. In browser, click refresh devices and load config. Confirm API state footer updates and no `apiGet is not defined` or CSRF errors appear. + +- [ ] **Step 5: Commit and push** + +```powershell +git add webui/index.html webui/app.js webui/js/api_client.js +git commit -m "refactor(webui): extract API client helpers" +git push +``` + +--- + +## Task 5: Extract Log View Behavior + +**Files:** +- Create: `webui/js/log_views.js` +- Modify: `webui/app.js` +- Modify: `webui/index.html` + +- [ ] **Step 1: Create `log_views.js`** + +Move the log rendering and search functions from `app.js` into `webui/js/log_views.js`: + +```javascript +function classifyLogLine(line) +function renderLogLineNode(line) +function appendLog(lines) +function renderRunLog() +function appendRunLogLines(lines) +async function fetchActionsLog() +function renderActionsLog() +``` + +Keep these shared state variables in `app.js` for this task: + +```javascript +let runLogBuffer = []; +let runLogFilter = ""; +let runLogMode = "filter"; +let runSearchResultsBuffer = []; +let runSearchActive = false; +let actionsLogBuffer = []; +let actionsLogFilter = ""; +``` + +Because classic scripts share global scope, `log_views.js` can keep using these names. + +- [ ] **Step 2: Remove moved functions from `app.js`** + +Delete only the moved function declarations. + +- [ ] **Step 3: Load `log_views.js` before `app.js`** + +```html + + + + + +``` + +- [ ] **Step 4: Verify and smoke** + +Run the standard JavaScript verification commands. In browser, check the run log filter/search and action log refresh. + +- [ ] **Step 5: Commit and push** + +```powershell +git add webui/index.html webui/app.js webui/js/log_views.js +git commit -m "refactor(webui): extract log view behavior" +git push +``` + +--- + +## Task 6: Extract Dashboard Renderers + +**Files:** +- Create: `webui/js/dashboard_renderers.js` +- Modify: `webui/app.js` +- Modify: `webui/index.html` + +- [ ] **Step 1: Create `dashboard_renderers.js`** + +Move these renderer functions from `app.js` into `webui/js/dashboard_renderers.js`: + +```javascript +function renderBars(containerId, dataMap, labelMap) +function renderTopContent(containerId, items) +function renderWinsTable(containerId, wins) +function renderTimeline(containerId, timeline) +function renderOverviewSparkline(svgId, timeline) +``` + +- [ ] **Step 2: Remove moved functions from `app.js`** + +Delete only the moved renderer declarations. + +- [ ] **Step 3: Load `dashboard_renderers.js` before `app.js`** + +```html + + +``` + +Keep all earlier module script tags before `dashboard_renderers.js`. + +- [ ] **Step 4: Verify and smoke** + +Run standard JavaScript verification. In browser, confirm stats charts, timeline tooltip, top content table, and wins table still render. + +- [ ] **Step 5: Commit and push** + +```powershell +git add webui/index.html webui/app.js webui/js/dashboard_renderers.js +git commit -m "refactor(webui): extract dashboard renderers" +git push +``` + +--- + +## Task 7: Extract Config Form Binding + +**Files:** +- Create: `webui/js/config_form.js` +- Modify: `webui/app.js` +- Modify: `webui/index.html` + +- [ ] **Step 1: Create `config_form.js`** + +Move these config-related functions from `app.js` into `webui/js/config_form.js`: + +```javascript +function getConfigBoundElements() +function syncMirrorFields() +function getConfigValue(cfg, key) +function coerceValue(type, raw, isCheckbox) +function applyConfigToUI(cfg) +function collectConfigFromUI() +async function loadConfig() +async function saveConfig() +``` + +- [ ] **Step 2: Remove moved functions from `app.js`** + +Delete only the moved config declarations. + +- [ ] **Step 3: Load `config_form.js` before `app.js`** + +```html + + +``` + +Keep all earlier module script tags before `config_form.js`. + +- [ ] **Step 4: Verify and smoke** + +Run standard JavaScript verification and `pytest tests/test_gui_webui_sync.py -q`. In browser, load config, change one harmless UI field, save, reload, and confirm no config-binding error appears. + +- [ ] **Step 5: Commit and push** + +```powershell +git add webui/index.html webui/app.js webui/js/config_form.js +git commit -m "refactor(webui): extract config form bindings" +git push +``` + +--- + +## Task 8: Extract Polling and Device Actions + +**Files:** +- Create: `webui/js/runtime_actions.js` +- Modify: `webui/app.js` +- Modify: `webui/index.html` + +- [ ] **Step 1: Create `runtime_actions.js`** + +Move these functions from `app.js` into `webui/js/runtime_actions.js`: + +```javascript +async function refreshDevices() +function decorateDeviceSelect() +function selectedDeviceId() +async function postDeviceAction(path, body, successPrefix) +async function forceStopRun() +async function sendBackKey() +async function wifiEnable() +async function wifiConnect() +async function wifiDisconnect() +async function tryAutoReconnectLastWifi() +async function wifiScan() +async function startRun() +async function testYanghao() +async function testComment() +async function stopRun() +async function pollLogs() +async function pollReservations() +async function pollHighValueRooms() +async function pollStats() +function startPolling() +function startStatsPolling() +``` + +Keep `DOMContentLoaded` event wiring in `app.js`. + +- [ ] **Step 2: Remove moved functions from `app.js`** + +Delete only the moved runtime declarations. + +- [ ] **Step 3: Load `runtime_actions.js` before `app.js`** + +```html + + +``` + +Keep all earlier module script tags before `runtime_actions.js`. + +- [ ] **Step 4: Verify and smoke** + +Run standard JavaScript verification. In browser, click refresh devices, load config, start/stop if safe, refresh action log, and switch through all panels. + +- [ ] **Step 5: Commit and push** + +```powershell +git add webui/index.html webui/app.js webui/js/runtime_actions.js +git commit -m "refactor(webui): extract runtime actions and polling" +git push +``` + +--- + +## Task 9: Reduce `app.js` to Initialization Glue + +**Files:** +- Create: `webui/js/ui_init.js` +- Modify: `webui/app.js` +- Modify: `webui/index.html` + +- [ ] **Step 1: Move UI initialization helpers** + +Move these functions into `webui/js/ui_init.js`: + +```javascript +function initTheme() +function ensureToastContainer() +function toast(message, kind = "info", { duration = 3500 } = {}) +function initConfigSearch() +function initFooter() +function attachCopyButtons() +function initKeyboardShortcuts() +function initHeaderScroll() +function initShotFullscreen() +function applyKbdHints() +function initStickySectionShadow() +function initShortcutsHelp() +function updateTabBadge(target, count) +function startReservationsCountdownTick() +function initTabs() +function attachNumberSteppers() +function pollShot() +function startShotPolling() +function setButtonBusy(id, busy) +function setRunOverview(state, meta, tone) +function updateDeviceOverview() +``` + +- [ ] **Step 2: Keep `app.js` as bootstrapping only** + +After this task, `app.js` should contain: + +```javascript +window.addEventListener("DOMContentLoaded", async () => { + initTheme(); + initTabs(); + initConfigSearch(); + initFooter(); + attachCopyButtons(); + initShotFullscreen(); + initHeaderScroll(); + initKeyboardShortcuts(); + initShortcutsHelp(); + initStickySectionShadow(); + attachNumberSteppers(); + applyKbdHints(); + syncMirrorFields(); + await refreshDevices(); + await loadConfig(); + startPolling(); + startStatsPolling(); + startShotPolling(); + startReservationsCountdownTick(); + pollLogs(); + pollStats(); + pollShot(); + pollReservations(); + pollHighValueRooms(); +}); +``` + +During implementation, preserve the existing event listener bindings from the current `DOMContentLoaded` body. If the current body wires buttons or inputs, keep those bindings in `app.js` or move them into a clearly named `bindAppEvents()` function in `ui_init.js`. + +- [ ] **Step 3: Verify and smoke** + +Run standard JavaScript verification. Browser smoke must cover initial load, tabs, theme, footer, shortcuts overlay, screenshot preview, logs, and config load/save. + +- [ ] **Step 4: Commit and push** + +```powershell +git add webui/index.html webui/app.js webui/js/ui_init.js +git commit -m "refactor(webui): reduce app script to initialization glue" +git push +``` + +--- + +## Task 10: Split CSS Tokens and Base Rules + +**Files:** +- Create: `webui/css/tokens.css` +- Create: `webui/css/base.css` +- Modify: `webui/styles.css` +- Modify: `webui/index.html` + +- [ ] **Step 1: Extract theme tokens** + +Move these ranges from `styles.css` into `webui/css/tokens.css`: + +- `:root { ... }` light theme token block +- `:root[data-theme="dark"] { ... }` dark theme token block +- reduced-motion token or global animation defaults that are pure variables + +Do not rename variables. + +- [ ] **Step 2: Extract base element rules** + +Move base reset and generic element rules into `webui/css/base.css`: + +- `*`, `html`, `body` +- `button`, `input`, `select`, `textarea` +- generic focus-visible rules +- global scrollbar rules +- generic utility classes that are not tied to one panel + +- [ ] **Step 3: Load extracted CSS before `styles.css`** + +```html + + + + +``` + +- [ ] **Step 4: Verify and smoke** + +Run CSS verification commands. Browser smoke must compare light and dark theme basics, header, buttons, forms, and scrollbars. + +- [ ] **Step 5: Commit and push** + +```powershell +git add webui/index.html webui/styles.css webui/css/tokens.css webui/css/base.css +git commit -m "refactor(webui): extract CSS tokens and base rules" +git push +``` + +--- + +## Task 11: Split CSS Layout and Shared Components + +**Files:** +- Create: `webui/css/layout.css` +- Create: `webui/css/components.css` +- Modify: `webui/styles.css` +- Modify: `webui/index.html` + +- [ ] **Step 1: Extract layout rules** + +Move app shell, header, workspace, panel grid, and footer layout rules into `layout.css`. Include responsive `@media` rules that only affect those layout selectors. + +- [ ] **Step 2: Extract shared component rules** + +Move shared button, card, tab, field, table, tooltip, toast, skeleton, and shortcut overlay rules into `components.css`. Include related `@media` and `prefers-reduced-motion` blocks when they directly belong to those selectors. + +- [ ] **Step 3: Load CSS in stable order** + +```html + + + + + +``` + +- [ ] **Step 4: Verify and smoke** + +Run CSS verification. Browser smoke must check desktop and mobile layout, tabs, cards, buttons, toast, tooltip, and shortcuts overlay. + +- [ ] **Step 5: Commit and push** + +```powershell +git add webui/index.html webui/styles.css webui/css/layout.css webui/css/components.css +git commit -m "refactor(webui): extract CSS layout and shared components" +git push +``` + +--- + +## Task 12: Split CSS Feature Panels + +**Files:** +- Create: `webui/css/panels.css` +- Create: `webui/css/logs.css` +- Create: `webui/css/charts.css` +- Modify: `webui/styles.css` +- Modify: `webui/index.html` + +- [ ] **Step 1: Extract panel-specific styles** + +Move screenshot preview, reservations, high-value room, realtime status, and panel-specific content rules into `panels.css`. + +- [ ] **Step 2: Extract log styles** + +Move run log, action log, log line classification, log search, and log scrollbar rules into `logs.css`. + +- [ ] **Step 3: Extract chart/table styles** + +Move chart blocks, timeline tooltip, bar rows, top content table, wins table, and related table rows into `charts.css`. + +- [ ] **Step 4: Load CSS in stable order** + +```html + + + + + + + + +``` + +- [ ] **Step 5: Verify and smoke** + +Run CSS verification. Browser smoke must check screenshot preview, reservations, high-value room list, log panels, charts, and mobile wrapping. + +- [ ] **Step 6: Commit and push** + +```powershell +git add webui/index.html webui/styles.css webui/css/panels.css webui/css/logs.css webui/css/charts.css +git commit -m "refactor(webui): extract CSS feature panels" +git push +``` + +--- + +## Task 13: Decide Whether to Split `index.html` + +**Files:** +- Modify: `webui/index.html` +- Optional create: `webui/partials/README.md` + +- [ ] **Step 1: Recount file sizes** + +Run: + +```powershell +rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize +``` + +- [ ] **Step 2: Keep `index.html` intact unless it is still above 1000 lines** + +If `index.html` is at or below 1000 lines, do not split it in this plan. HTML partial loading would require server or build changes and is not needed yet. + +If `index.html` remains above 1000 lines and the team wants smaller HTML files, write a separate spec before changing runtime behavior. That spec must choose one of: + +- server-side partial injection in `gui/web_gui.py` +- client-side fetch of static partials +- build-time HTML generation + +- [ ] **Step 3: Commit only if docs are added** + +If `webui/partials/README.md` is created: + +```powershell +git add webui/partials/README.md +git commit -m "docs(webui): record HTML partial split decision" +git push +``` + +--- + +## Task 14: Split `gui/web_gui.py` Only After Frontend Is Stable + +**Files:** +- Create: `gui/web_gui_pkg/static_handler.py` +- Create: `gui/web_gui_pkg/request_parsing.py` +- Create: `gui/web_gui_pkg/routes.py` +- Modify: `gui/web_gui.py` +- Test: `tests/test_webgui.py` + +- [ ] **Step 1: Extract request parsing helpers** + +Move `_send_json` and `_read_json` behavior into functions that still receive the `Handler` instance: + +```python +def send_json(handler: BaseHTTPRequestHandler, obj: object, status: int = 200) -> None: + data = json.dumps(obj, ensure_ascii=False).encode("utf-8") + handler.send_response(status) + handler.send_header("Content-Type", "application/json; charset=utf-8") + handler.send_header("Cache-Control", "no-store") + handler.send_header("Content-Length", str(len(data))) + handler.end_headers() + handler.wfile.write(data) +``` + +```python +def read_json(handler: BaseHTTPRequestHandler) -> dict: + n = int(handler.headers.get("Content-Length") or 0) + raw = handler.rfile.read(n) if n > 0 else b"{}" + try: + value = json.loads(raw.decode("utf-8")) + except Exception: + return {} + return value if isinstance(value, dict) else {} +``` + +Keep `Handler._send_json` and `Handler._read_json` as thin wrappers at first. + +- [ ] **Step 2: Extract static file serving** + +Move `_serve_static` into `gui/web_gui_pkg/static_handler.py`: + +```python +def serve_static( + handler: BaseHTTPRequestHandler, + *, + webui_dir: str, + rel_path: str, + log_error: Callable[[str], None], +) -> None: + # paste current Handler._serve_static body and replace: + # self -> handler + # WEBUI_DIR -> webui_dir + # _wg_log(...) -> log_error(...) +``` + +Keep `Handler._serve_static` as: + +```python +def _serve_static(self, rel_path: str) -> None: + serve_static( + self, + webui_dir=WEBUI_DIR, + rel_path=rel_path, + log_error=lambda msg: _wg_log(msg, level="ERROR"), + ) +``` + +- [ ] **Step 3: Verify** + +Run: + +```powershell +python -m py_compile gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py > logs\web_gui_split_py_compile.log 2>&1 +pytest tests/test_webgui.py -q > logs\pytest_web_gui_split.log 2>&1 +``` + +Expected: PASS. + +- [ ] **Step 4: Commit and push** + +```powershell +git add gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py tests/test_webgui.py +git commit -m "refactor(webgui): extract request and static helpers" +git push +``` + +--- + +## Task 15: Final Outcome Note + +**Files:** +- Modify: this plan file + +- [ ] **Step 1: Record final sizes** + +Run: + +```powershell +rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize +``` + +- [ ] **Step 2: Append outcome** + +Append: + +```markdown +## Outcome + +- `webui/app.js`: 2512 -> actual final line count +- `webui/styles.css`: 3745 -> actual final line count +- `webui/index.html`: 1232 -> actual final line count +- `gui/web_gui.py`: 1663 -> actual final line count +- Extracted JS modules: actual module filenames +- Extracted CSS modules: actual module filenames +- Verification: exact pytest log path and browser smoke result +- Remaining large files: actual top remaining files from the final size command +``` + +- [ ] **Step 3: Commit and push** + +```powershell +git add docs/superpowers/plans/2026-05-31-split-webui-large-files.md +git commit -m "docs(webui): record large-file split outcome" +git push +``` + +--- + +## Execution Notes + +- Do not batch tasks. Each task must pass verification, commit, and push before starting the next one. +- Keep query-string versions in `index.html` synchronized across all WebUI assets touched in a task. +- Do not introduce a frontend build step in this plan. +- Do not convert to ES modules until the classic-script split is complete and browser smoke is clean. +- For JavaScript moves, copy exact function bodies first, verify, then optionally do tiny cleanup in a separate commit. +- For CSS moves, preserve selector order unless the moved file load order proves an equivalent cascade. +- Project rule: only stage files changed by the current task.