Jelajahi Sumber

Merge pull request #1606 from LGG686/dev-tool

Dev tool
huangrunheng 5 bulan lalu
induk
melakukan
e87fb7e87d
27 mengubah file dengan 7997 tambahan dan 37 penghapusan
  1. 11 5
      dev_tools/assets_extract.py
  2. 118 2
      dev_tools/assets_test.py
  3. 5 4
      module/config/utils.py
  4. 239 0
      module/server/annotator_rule_schema.py
  5. 9 1
      module/server/app.py
  6. 8 4
      module/server/script_router.py
  7. 53 21
      module/server/script_websocket.py
  8. 1451 0
      module/server/tool.py
  9. 416 0
      module/server/tool_router.py
  10. 26 0
      module/server/web/annotator/index.html
  11. 1186 0
      module/server/web/annotator/static/css/base.css
  12. 298 0
      module/server/web/annotator/static/css/center-panel.css
  13. 97 0
      module/server/web/annotator/static/css/left-window.css
  14. 266 0
      module/server/web/annotator/static/css/right-window.css
  15. 60 0
      module/server/web/annotator/static/css/topbar.css
  16. 2855 0
      module/server/web/annotator/static/js/app.js
  17. 8 0
      module/server/web/annotator/static/js/center-panel.js
  18. 591 0
      module/server/web/annotator/static/js/layout-ui.js
  19. 8 0
      module/server/web/annotator/static/js/left-window.js
  20. 83 0
      module/server/web/annotator/static/js/main.js
  21. 8 0
      module/server/web/annotator/static/js/right-window.js
  22. 8 0
      module/server/web/annotator/static/js/topbar.js
  23. 40 0
      module/server/web/annotator/static/widget/center-panel.html
  24. 21 0
      module/server/web/annotator/static/widget/component-manifest.md
  25. 60 0
      module/server/web/annotator/static/widget/left-window.html
  26. 60 0
      module/server/web/annotator/static/widget/right-window.html
  27. 12 0
      module/server/web/annotator/static/widget/topbar.html

+ 11 - 5
dev_tools/assets_extract.py

@@ -204,12 +204,14 @@ class ListExtractor:
         """
         self.file = str(Path(file).resolve().relative_to((Path.cwd()).resolve()).as_posix())
         self.image_path = Path(self.file).parent.as_posix()
-        self._result = '\n\n\t# List Rule Assets\n'
+        self._result = ''
 
         if not isinstance(data, dict):
             raise TypeError("data must be dict")
 
-        self._result += self.extract(data)
+        extracted = self.extract(data)
+        if extracted:
+            self._result = '\n\n\t# List Rule Assets\n' + extracted
 
     @property
     def result(self) -> str:
@@ -221,15 +223,19 @@ class ListExtractor:
         :param data:
         :return:
         """
+        items = data.get("list", [])
+        if not items:
+            return ""
+
         width, height = 0, 0
         array: list = []
-        for item in data["list"]:
+        for item in items:
             roi_front = item["roiFront"].split(",")
             width += int(roi_front[2])
             height += int(roi_front[3])
             array.append(f'"{item["itemName"]}"')
-        width = int(width / len(data["list"]))
-        height = int(height / len(data["list"]))
+        width = int(width / len(items))
+        height = int(height / len(items))
         array = ', '.join(array)
 
         description: str = f'\t# {data["description"]} \n'

+ 118 - 2
dev_tools/assets_test.py

@@ -9,13 +9,13 @@ from module.atom.image import RuleImage
 from module.atom.ocr import RuleOcr
 
 
-def load_image(file: str):
+def load_image(file: str, strict_size: bool = True):
     file = Path(file)
     img = cv2.imdecode(fromfile(file, dtype=uint8), -1)
     img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
 
     height, width, channels = img.shape
-    if height != 720 or width != 1280:
+    if strict_size and (height != 720 or width != 1280):
         logger.error(f'Image size is {height}x{width}, not 720x1280')
         return None
     return img
@@ -33,6 +33,122 @@ def detect_ocr(file: str, target: RuleOcr):
     return target.ocr(img)
 
 
+def _roi_to_text(roi: list | tuple) -> str:
+    x, y, w, h = roi
+    return f"{int(round(x))},{int(round(y))},{int(round(w))},{int(round(h))}"
+
+
+def detect_image_detail(file: str, target: RuleImage) -> dict:
+    img = load_image(file, strict_size=False)
+    if img is None:
+        return {
+            "matched": False,
+            "similarity": 0.0,
+            "roiFront": _roi_to_text(target.roi_front),
+            "roiBack": _roi_to_text(target.roi_back),
+            "message": "image_load_failed",
+        }
+
+    similarity = 0.0
+    matched = False
+    message = "not_match"
+
+    if target.is_template_match:
+        source = target.corp(img)
+        mat = target.image
+        if source.shape[0] < mat.shape[0] or source.shape[1] < mat.shape[1]:
+            return {
+                "matched": False,
+                "similarity": 0.0,
+                "roiFront": _roi_to_text(target.roi_front),
+                "roiBack": _roi_to_text(target.roi_back),
+                "message": "roi_back_too_small",
+            }
+        res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
+        _, max_val, _, max_loc = cv2.minMaxLoc(res)
+        similarity = float(max_val)
+        matched = similarity >= target.threshold
+        target.roi_front[0] = int(max_loc[0] + target.roi_back[0])
+        target.roi_front[1] = int(max_loc[1] + target.roi_back[1])
+        target.roi_front[2] = int(mat.shape[1])
+        target.roi_front[3] = int(mat.shape[0])
+        message = "match" if matched else "not_match"
+    else:
+        try:
+            matched = bool(target.test_match(img))
+            similarity = 1.0 if matched else 0.0
+            message = "match" if matched else "not_match"
+        except Exception as e:
+            message = f"sift_error:{e}"
+
+    return {
+        "matched": matched,
+        "similarity": round(similarity, 4),
+        "roiFront": _roi_to_text(target.roi_front),
+        "roiBack": _roi_to_text(target.roi_back),
+        "message": message,
+    }
+
+
+def detect_ocr_detail(file: str, target: RuleOcr) -> dict:
+    img = load_image(file, strict_size=False)
+    if img is None:
+        return {
+            "matched": False,
+            "similarity": 0.0,
+            "text": "",
+            "roiFront": _roi_to_text(target.roi),
+            "roiBack": _roi_to_text(target.area),
+            "message": "image_load_failed",
+        }
+
+    boxed = target.detect_and_ocr(img, logDisplay=False)
+    selected = None
+
+    if boxed:
+        if target.keyword:
+            for item in boxed:
+                text = str(item.ocr_text or "")
+                if target.keyword in text or text == target.keyword:
+                    selected = item
+                    break
+        if selected is None:
+            selected = max(boxed, key=lambda x: float(x.score))
+
+    if selected is None:
+        return {
+            "matched": False,
+            "similarity": 0.0,
+            "text": "",
+            "roiFront": _roi_to_text(target.roi),
+            "roiBack": _roi_to_text(target.area),
+            "message": "not_match",
+        }
+
+    box = selected.box
+    x0 = int(np.min(box[:, 0])) + int(target.roi[0])
+    y0 = int(np.min(box[:, 1])) + int(target.roi[1])
+    x1 = int(np.max(box[:, 0])) + int(target.roi[0])
+    y1 = int(np.max(box[:, 1])) + int(target.roi[1])
+    w = max(1, x1 - x0)
+    h = max(1, y1 - y0)
+
+    target.roi = [x0, y0, w, h]
+    target.area = [x0, y0, w, h]
+
+    text = str(selected.ocr_text or "")
+    matched = target.match(text, included=True) if target.keyword else bool(text)
+
+    return {
+        "matched": matched,
+        "similarity": round(float(selected.score), 4),
+        "text": text,
+        "roiFront": _roi_to_text(target.roi),
+        "roiBack": _roi_to_text(target.area),
+        "message": "match" if matched else "not_match",
+    }
+
+
 # 图片文件路径 可以是相对路径
 IMAGE_FILE = r"C:\Users\Ryland\Desktop\ScreenShot_2026-05-30_141821_235.png"
 if __name__ == '__main__':

+ 5 - 4
module/config/utils.py

@@ -9,6 +9,7 @@ from filelock import FileLock
 from datetime import datetime, timedelta, timezone, time
 
 from module.config.atomicwrites import atomic_write
+from module.logger import logger
 
 DEFAULT_TIME = datetime(2023, 1, 1, 0, 0)
 
@@ -50,7 +51,7 @@ def read_file(file: str):
     _, ext = os.path.splitext(file)
     lock = FileLock(f"{file}.lock")
     with lock:
-        print(f'read: {file}')
+        logger.debug(f'read: {file}')
         if ext == '.yaml':
             with open(file, mode='r', encoding='utf-8') as f:
                 s = f.read()
@@ -65,7 +66,7 @@ def read_file(file: str):
                 s = f.read()
                 return json.loads(s)
         else:
-            print(f'Unsupported config file extension: {ext}')
+            logger.warning(f'Unsupported config file extension: {ext}')
             return {}
 
 def write_file(file: str, data):
@@ -83,7 +84,7 @@ def write_file(file: str, data):
     _, ext = os.path.splitext(file)
     lock = FileLock(f"{file}.lock")
     with lock:
-        print(f'write: {file}')
+        logger.debug(f'write: {file}')
         if ext == '.yaml':
             with atomic_write(file, overwrite=True, encoding='utf-8', newline='') as f:
                 if isinstance(data, list):
@@ -97,7 +98,7 @@ def write_file(file: str, data):
                 s = json.dumps(data, indent=2, ensure_ascii=False, sort_keys=False, default=str)
                 f.write(s)
         else:
-            print(f'Unsupported config file extension: {ext}')
+            logger.warning(f'Unsupported config file extension: {ext}')
 
 
 def deep_iter(data, depth=0, current_depth=1):

+ 239 - 0
module/server/annotator_rule_schema.py

@@ -0,0 +1,239 @@
+from __future__ import annotations
+
+from collections import OrderedDict
+from copy import deepcopy
+from typing import Any
+
+RULE_TYPE_SCHEMAS: OrderedDict[str, dict[str, Any]] = OrderedDict(
+    {
+        "image": {
+            "type": "image",
+            "label": "RuleImage",
+            "capabilities": {
+                "supports_test": True,
+                "supports_crop": True,
+                "supports_image_preview": True,
+                "shared_roi_back": False,
+            },
+            "fields": [
+                {"key": "itemName", "label": "itemName", "control": "text", "default": "new"},
+                {
+                    "key": "imageName",
+                    "label": "imageName",
+                    "control": "text",
+                    "default": "",
+                    "auto_from_item_name": True,
+                },
+                {
+                    "key": "method",
+                    "label": "method",
+                    "control": "select",
+                    "default": "Template matching",
+                    "options": ["Template matching", "Sift Flann"],
+                },
+                {
+                    "key": "threshold",
+                    "label": "threshold",
+                    "control": "number",
+                    "default": 0.8,
+                    "step": 0.01,
+                    "min": 0,
+                    "max": 1,
+                    "integer": False,
+                },
+                {"key": "description", "label": "description", "control": "textarea", "default": "", "full": True},
+            ],
+        },
+        "ocr": {
+            "type": "ocr",
+            "label": "RuleOcr",
+            "capabilities": {
+                "supports_test": True,
+                "supports_crop": False,
+                "supports_image_preview": False,
+                "shared_roi_back": False,
+            },
+            "fields": [
+                {"key": "itemName", "label": "itemName", "control": "text", "default": "new"},
+                {
+                    "key": "mode",
+                    "label": "mode",
+                    "control": "select",
+                    "default": "Single",
+                    "options": ["Single", "Full", "Digit", "DigitCounter", "Duration", "Quantity"],
+                },
+                {"key": "method", "label": "method", "control": "text", "default": "Default"},
+                {"key": "keyword", "label": "keyword", "control": "text", "default": ""},
+                {"key": "description", "label": "description", "control": "textarea", "default": "", "full": True},
+            ],
+        },
+        "click": {
+            "type": "click",
+            "label": "RuleClick",
+            "capabilities": {
+                "supports_test": False,
+                "supports_crop": False,
+                "supports_image_preview": False,
+                "shared_roi_back": False,
+            },
+            "fields": [
+                {"key": "itemName", "label": "itemName", "control": "text", "default": "new"},
+                {"key": "description", "label": "description", "control": "textarea", "default": "", "full": True},
+            ],
+        },
+        "swipe": {
+            "type": "swipe",
+            "label": "RuleSwipe",
+            "capabilities": {
+                "supports_test": False,
+                "supports_crop": False,
+                "supports_image_preview": False,
+                "shared_roi_back": False,
+            },
+            "fields": [
+                {"key": "itemName", "label": "itemName", "control": "text", "default": "new"},
+                {
+                    "key": "mode",
+                    "label": "mode",
+                    "control": "select",
+                    "default": "default",
+                    "options": ["default", "vector"],
+                },
+                {"key": "description", "label": "description", "control": "textarea", "default": "", "full": True},
+            ],
+        },
+        "long_click": {
+            "type": "long_click",
+            "label": "RuleLongClick",
+            "capabilities": {
+                "supports_test": False,
+                "supports_crop": False,
+                "supports_image_preview": False,
+                "shared_roi_back": False,
+            },
+            "fields": [
+                {"key": "itemName", "label": "itemName", "control": "text", "default": "new"},
+                {
+                    "key": "duration",
+                    "label": "duration(ms)",
+                    "control": "number",
+                    "default": 1000,
+                    "min": 1,
+                    "step": 1,
+                    "integer": True,
+                },
+                {"key": "description", "label": "description", "control": "textarea", "default": "", "full": True},
+            ],
+        },
+        "list": {
+            "type": "list",
+            "label": "RuleList",
+            "capabilities": {
+                "supports_test": True,
+                "supports_crop": True,
+                "supports_image_preview": True,
+                "shared_roi_back": True,
+            },
+            "fields": [
+                {"key": "itemName", "label": "itemName", "control": "text", "default": "new"},
+            ],
+            "meta_fields": [
+                {"key": "name", "label": "list.name", "control": "text", "default": "list_name"},
+                {
+                    "key": "direction",
+                    "label": "list.direction",
+                    "control": "select",
+                    "default": "vertical",
+                    "options": ["vertical", "horizontal"],
+                },
+                {
+                    "key": "type",
+                    "label": "list.type",
+                    "control": "select",
+                    "default": "image",
+                    "options": ["image", "ocr"],
+                },
+                {"key": "description", "label": "list.description", "control": "text", "default": ""},
+            ],
+        },
+    }
+)
+
+
+ROI_DEFAULT = "0,0,100,100"
+
+
+def get_rule_types() -> list[str]:
+    return list(RULE_TYPE_SCHEMAS.keys())
+
+
+def get_rule_schema(rule_type: str) -> dict[str, Any]:
+    schema = RULE_TYPE_SCHEMAS.get(str(rule_type or "").strip())
+    if not schema:
+        schema = RULE_TYPE_SCHEMAS["image"]
+    return deepcopy(schema)
+
+
+def get_rule_schemas() -> list[dict[str, Any]]:
+    return [get_rule_schema(rule_type) for rule_type in get_rule_types()]
+
+
+def get_schema_payload() -> dict[str, Any]:
+    return {
+        "rule_types": get_rule_types(),
+        "schemas": {rule_type: get_rule_schema(rule_type) for rule_type in get_rule_types()},
+    }
+
+
+def _field_defaults(fields: list[dict[str, Any]]) -> dict[str, Any]:
+    return {field["key"]: deepcopy(field.get("default")) for field in fields}
+
+
+def default_rule(rule_type: str) -> dict[str, Any]:
+    schema = get_rule_schema(rule_type)
+    rule = _field_defaults(schema.get("fields", []))
+    rule["roiFront"] = ROI_DEFAULT
+    if rule_type != "list":
+        rule["roiBack"] = ROI_DEFAULT
+    return rule
+
+
+def default_list_meta() -> dict[str, Any]:
+    schema = get_rule_schema("list")
+    meta = _field_defaults(schema.get("meta_fields", []))
+    meta["roiBack"] = ROI_DEFAULT
+    return meta
+
+
+def merge_rule_with_defaults(rule_type: str, rule: dict[str, Any] | None) -> dict[str, Any]:
+    merged = default_rule(rule_type)
+    if isinstance(rule, dict):
+        merged.update(rule)
+    if rule_type == "list":
+        merged.pop("description", None)
+    return merged
+
+
+def merge_list_meta_with_defaults(meta: dict[str, Any] | None) -> dict[str, Any]:
+    merged = default_list_meta()
+    if isinstance(meta, dict):
+        merged.update(meta)
+    return merged
+
+
+def field_default(rule_type: str, key: str, fallback: Any = None) -> Any:
+    schema = get_rule_schema(rule_type)
+    fields = list(schema.get("fields", [])) + list(schema.get("meta_fields", []))
+    for field in fields:
+        if field.get("key") == key:
+            return deepcopy(field.get("default"))
+    return fallback
+
+
+def field_options(rule_type: str, key: str) -> list[str]:
+    schema = get_rule_schema(rule_type)
+    fields = list(schema.get("fields", [])) + list(schema.get("meta_fields", []))
+    for field in fields:
+        if field.get("key") == key:
+            return list(field.get("options", []))
+    return []

+ 9 - 1
module/server/app.py

@@ -1,6 +1,8 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
+from pathlib import Path
+
 from contextlib import asynccontextmanager
 
 import argparse
@@ -12,9 +14,10 @@ from fastapi.middleware.cors import CORSMiddleware
 from module.logger import logger
 from module.server.home_router import home_app
 from module.server.script_router import script_app
+from module.server.tool_router import tool_app
 from module.server.setting import State
 from module.server.main_manager import mm
-
+from starlette.staticfiles import StaticFiles
 
 
 @asynccontextmanager
@@ -40,6 +43,11 @@ app.add_middleware(
 
 app.include_router(home_app)
 app.include_router(script_app)
+app.include_router(tool_app)
+
+annotator_static_dir = Path(__file__).resolve().parent / "web" / "annotator" / "static"
+if annotator_static_dir.exists():
+    app.mount("/tool/annotator/static", StaticFiles(directory=str(annotator_static_dir)), name="annotator_static")
 
 
 async def on_startup():

+ 8 - 4
module/server/script_router.py

@@ -207,12 +207,13 @@ async def websocket_endpoint(websocket: WebSocket, script_name: str):
         mm.script_process[script_name] = ScriptProcess(script_name)
     script_process = mm.script_process[script_name]
     await script_process.connect(websocket)
-    await script_process.broadcast_state({"state": script_process.state})
-    config = mm.config_cache(script_name)
-    config.get_next()
-    await script_process.broadcast_state({"schedule": config.get_schedule_data()})
 
     try:
+        await script_process.send_json(websocket, {"state": script_process.state})
+        config = mm.config_cache(script_name)
+        config.get_next()
+        await script_process.send_json(websocket, {"schedule": config.get_schedule_data()})
+
         while True:
             # 初次进入,广播state schedule
             data = await websocket.receive_text()
@@ -230,3 +231,6 @@ async def websocket_endpoint(websocket: WebSocket, script_name: str):
     except WebSocketDisconnect:
         logger.warning(f'[{script_name}] websocket disconnect')
         await script_process.disconnect(websocket)
+    except Exception as e:
+        logger.exception(f'[{script_name}] websocket error: {e}')
+        await script_process.disconnect(websocket)

+ 53 - 21
module/server/script_websocket.py

@@ -1,7 +1,11 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
-from fastapi import FastAPI, WebSocket, WebSocketDisconnect
+from typing import Iterable
+
+from fastapi import WebSocket, WebSocketDisconnect
+from starlette.websockets import WebSocketState
+
 
 class ScriptWSManager:
 
@@ -11,41 +15,69 @@ class ScriptWSManager:
     async def connect(self, ws: WebSocket):
         # 等待连接
         await ws.accept()
-        self.active_connections.append(ws)
+        if ws not in self.active_connections:
+            self.active_connections.append(ws)
 
     async def disconnect(self, ws: WebSocket):
-        # 关闭时 移除ws对象
-        self.active_connections.remove(ws)
+        # 关闭时移除 ws 对象,重复调用也应安全
+        if ws in self.active_connections:
+            self.active_connections.remove(ws)
+        if ws.client_state == WebSocketState.DISCONNECTED:
+            return
         try:
             # 给前端发送最后一次关闭信号
             await ws.close()
-        except RuntimeError as e:
-            print(e)
+        except (RuntimeError, WebSocketDisconnect):
+            return
+        except Exception:
+            return
+
+    async def send_text(self, ws: WebSocket, message: str) -> bool:
+        return await self._send(ws, ws.send_text, message)
+
+    async def send_json(self, ws: WebSocket, data: dict) -> bool:
+        return await self._send(ws, ws.send_json, data)
 
     async def broadcast(self, message: str):
         # 广播消息
-        for connection in self.active_connections:
-            try:
-                await connection.send_text(message)
-            except RuntimeError:
-                await self.disconnect(connection)
+        await self._broadcast(self.active_connections, lambda connection: connection.send_text(message))
 
     async def broadcast_state(self, data: dict):
         # 广播自身的状态
-        for connection in self.active_connections:
-            try:
-                await connection.send_json(data)
-            except RuntimeError:
-                await self.disconnect(connection)
+        await self._broadcast(self.active_connections, lambda connection: connection.send_json(data))
 
     async def broadcast_log(self, log: str):
         # 广播日志
-        for connection in self.active_connections:
-            try:
-                await connection.send_text(log)
-            except RuntimeError:
-                await self.disconnect(connection)
+        await self._broadcast(self.active_connections, lambda connection: connection.send_text(log))
 
+    async def _send(self, ws: WebSocket, sender, payload) -> bool:
+        if ws.client_state == WebSocketState.DISCONNECTED:
+            await self.disconnect(ws)
+            return False
+        try:
+            await sender(payload)
+            return True
+        except (RuntimeError, WebSocketDisconnect):
+            await self.disconnect(ws)
+            return False
+        except Exception:
+            await self.disconnect(ws)
+            return False
+
+    async def _broadcast(self, connections: Iterable[WebSocket], sender_factory) -> None:
+        dead_connections: list[WebSocket] = []
+        for connection in list(connections):
+            if connection.client_state == WebSocketState.DISCONNECTED:
+                dead_connections.append(connection)
+                continue
+            try:
+                await sender_factory(connection)
+            except (RuntimeError, WebSocketDisconnect):
+                dead_connections.append(connection)
+            except Exception:
+                dead_connections.append(connection)
+        for connection in dead_connections:
+            await self.disconnect(connection)
 
 
 

+ 1451 - 0
module/server/tool.py

@@ -0,0 +1,1451 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import json
+import re
+import shutil
+import threading
+import time
+import uuid
+import base64
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import cv2
+import numpy as np
+from filelock import FileLock
+
+from dev_tools.assets_extract import AssetsExtractor
+from dev_tools.assets_test import detect_image_detail, detect_ocr_detail
+from module.config.atomicwrites import atomic_write
+from module.config.config import Config
+from module.device.device import Device
+from module.logger import logger
+from module.server.config_manager import ConfigManager
+from module.server.annotator_rule_schema import (
+    default_list_meta,
+    field_default,
+    field_options,
+    get_rule_types,
+    get_schema_payload,
+    merge_list_meta_with_defaults,
+    merge_rule_with_defaults,
+)
+
+PROJECT_ROOT = Path.cwd().resolve()
+TASKS_ROOT = (PROJECT_ROOT / "tasks").resolve()
+ANNOTATOR_ROOT = (PROJECT_ROOT / "log" / "annotator").resolve()
+
+ALLOWED_IMAGE_EXT = {".png", ".jpg", ".jpeg", ".bmp", ".webp"}
+ALLOWED_RULE_TYPE = set(get_rule_types())
+ALLOWED_OCR_MODE = set(field_options("ocr", "mode"))
+ALLOWED_LIST_DIRECTION = set(field_options("list", "direction"))
+ALLOWED_LIST_MODE = set(field_options("list", "type"))
+ALLOWED_SWIPE_MODE = set(field_options("swipe", "mode"))
+
+SESSION_IDLE_TIMEOUT_SECONDS = 10 * 60
+SESSION_SWEEP_INTERVAL_SECONDS = 30
+EMULATOR_CAPTURE_MAX_RETRIES = 3
+EMULATOR_CAPTURE_RETRY_BACKOFF_SECONDS = 1.0
+
+
+class AnnotatorError(Exception):
+    def __init__(self, code: str, message: str, status_code: int = 400) -> None:
+        super().__init__(message)
+        self.code = code
+        self.message = message
+        self.status_code = status_code
+
+
+@dataclass
+class SessionImage:
+    image_id: str
+    path: Path
+    source: str
+    original_name: str
+    created_at: float
+
+    def to_dict(self, session_id: str) -> dict[str, Any]:
+        url = f"/tool/annotator/api/images/{session_id}/{self.image_id}"
+        return {
+            "id": self.image_id,
+            "name": self.original_name,
+            "source": self.source,
+            "created_at": self.created_at,
+            "url": url,
+            "thumb_url": url,
+        }
+
+
+class EmulatorCaptureSession:
+    def __init__(self, session_id: str) -> None:
+        self.session_id = session_id
+        self.state = "stopped"
+        self.config_name = ""
+        self.frame_rate = 2
+        self.error = ""
+        self._thread: threading.Thread | None = None
+        self._stop_event = threading.Event()
+        self._frame_lock = threading.Lock()
+        self._latest_frame = None
+        self._latest_jpeg: bytes | None = None
+        self._updated_at = 0.0
+        self._retry_count = 0
+        self._max_retries = EMULATOR_CAPTURE_MAX_RETRIES
+        self._last_error_at = 0.0
+
+    def status(self) -> dict[str, Any]:
+        with self._frame_lock:
+            return {
+                "state": self.state,
+                "config_name": self.config_name,
+                "frame_rate": self.frame_rate,
+                "error": self.error,
+                "updated_at": self._updated_at,
+                "last_frame_at": self._updated_at,
+                "retry_count": self._retry_count,
+                "max_retries": self._max_retries,
+                "last_error_at": self._last_error_at,
+            }
+
+    def start(self, config_name: str, frame_rate: int) -> int:
+        self.stop(clear_error=True)
+        with self._frame_lock:
+            self.config_name = config_name
+            self.frame_rate = max(1, min(int(frame_rate), 10))
+            self.state = "starting"
+            self.error = ""
+            self._updated_at = 0.0
+            self._retry_count = 0
+            self._last_error_at = 0.0
+            self._latest_frame = None
+            self._latest_jpeg = None
+        self._stop_event.clear()
+        self._thread = threading.Thread(target=self._run, daemon=True, name=f"annotator_capture_{self.session_id}")
+        self._thread.start()
+        return self.frame_rate
+
+    def stop(self, clear_error: bool = False) -> None:
+        self._stop_event.set()
+        thread = self._thread
+        if thread and thread.is_alive():
+            thread.join(timeout=2.5)
+        self._thread = None
+        with self._frame_lock:
+            self.state = "stopped"
+            self._retry_count = 0
+            if clear_error:
+                self.error = ""
+                self._last_error_at = 0.0
+
+    def _build_device(self, config: Config, interval: float) -> Device:
+        device = Device(config=config)
+        device.disable_stuck_detection()
+        device.screenshot_interval_set(interval)
+        logger.info(
+            f"[annotator] emulator device ready, session={self.session_id}, "
+            f"config={self.config_name}, interval={interval:.3f}"
+        )
+        return device
+
+    @staticmethod
+    def _release_device(device: Device | None) -> None:
+        if device is None:
+            return
+        try:
+            device.release_during_wait()
+        except Exception:
+            pass
+
+    @staticmethod
+    def _format_error_message(error: Exception) -> str:
+        text = str(error).strip()
+        if text:
+            return text
+        return error.__class__.__name__
+
+    def _mark_capture_failure(self, stage: str, error: Exception) -> tuple[bool, int, str]:
+        message = self._format_error_message(error)
+        with self._frame_lock:
+            self.error = message
+            self._last_error_at = time.time()
+            self._retry_count += 1
+            attempt = self._retry_count
+            should_retry = attempt <= self._max_retries and not self._stop_event.is_set()
+            self.state = "starting" if should_retry else "error"
+        if should_retry:
+            logger.warning(
+                f"[annotator] emulator capture retry, session={self.session_id}, config={self.config_name}, "
+                f"stage={stage}, attempt={attempt}/{self._max_retries}, error={message}"
+            )
+        else:
+            logger.error(
+                f"[annotator] emulator capture failed, session={self.session_id}, config={self.config_name}, "
+                f"stage={stage}, attempt={attempt}/{self._max_retries}, error={message}"
+            )
+        return should_retry, attempt, message
+
+    def _run(self) -> None:
+        device: Device | None = None
+        interval = max(0.1, 1.0 / float(self.frame_rate))
+        try:
+            config = Config(config_name=self.config_name)
+            while not self._stop_event.is_set():
+                if device is None:
+                    try:
+                        device = self._build_device(config, interval)
+                        with self._frame_lock:
+                            self.state = "running"
+                    except Exception as e:
+                        should_retry, attempt, _ = self._mark_capture_failure("connect", e)
+                        if not should_retry:
+                            break
+                        if self._stop_event.wait(EMULATOR_CAPTURE_RETRY_BACKOFF_SECONDS * attempt):
+                            break
+                        continue
+
+                try:
+                    frame = device.screenshot()
+                except Exception as e:
+                    self._release_device(device)
+                    device = None
+                    should_retry, attempt, _ = self._mark_capture_failure("capture", e)
+                    if not should_retry:
+                        break
+                    if self._stop_event.wait(EMULATOR_CAPTURE_RETRY_BACKOFF_SECONDS * attempt):
+                        break
+                    continue
+
+                frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
+                ok, buf = cv2.imencode(".jpg", frame_bgr)
+                if ok:
+                    with self._frame_lock:
+                        self._latest_frame = frame_bgr.copy()
+                        self._latest_jpeg = buf.tobytes()
+                        self._updated_at = time.time()
+                        self._retry_count = 0
+                        self.error = ""
+                        self.state = "running"
+
+                if self._stop_event.wait(interval):
+                    break
+        except Exception:
+            with self._frame_lock:
+                self.state = "error"
+                self._last_error_at = time.time()
+                if not self.error:
+                    self.error = "模拟器采集线程异常退出"
+            logger.error(f"[annotator] emulator capture loop crashed, session={self.session_id}, config={self.config_name}")
+        finally:
+            self._release_device(device)
+            if self.state != "error":
+                with self._frame_lock:
+                    self.state = "stopped"
+
+    def latest_jpeg(self) -> bytes | None:
+        with self._frame_lock:
+            if self.state != "running" or self._latest_jpeg is None:
+                return None
+            return bytes(self._latest_jpeg)
+
+    def capture_latest_frame(self, output_file: Path) -> None:
+        with self._frame_lock:
+            state = self.state
+            error = self.error
+            frame = None if self._latest_frame is None else self._latest_frame.copy()
+
+        if state != "running":
+            if state == "error":
+                raise AnnotatorError("emulator_error", f"模拟器画面不可用: {error or 'unknown'}", 409)
+            if state == "starting":
+                raise AnnotatorError("emulator_starting", "模拟器画面尚未就绪,请稍后重试", 409)
+            raise AnnotatorError("emulator_not_running", "模拟器画面未启动", 409)
+
+        if frame is None:
+            raise AnnotatorError("no_frame", "当前没有可用帧,无法截图", 400)
+
+        ok = cv2.imwrite(str(output_file), frame)
+        if not ok:
+            raise AnnotatorError("capture_failed", "保存截图失败", 500)
+
+
+class AnnotatorSession:
+    def __init__(self, session_id: str) -> None:
+        self.session_id = session_id
+        self.root = ANNOTATOR_ROOT / session_id
+        self.upload_dir = self.root / "uploads"
+        self.capture_dir = self.root / "captures"
+        self.root.mkdir(parents=True, exist_ok=True)
+        self.upload_dir.mkdir(parents=True, exist_ok=True)
+        self.capture_dir.mkdir(parents=True, exist_ok=True)
+        self.images: dict[str, SessionImage] = {}
+        self.image_order: list[str] = []
+        self.current_image_id: str | None = None
+        self.lock = threading.Lock()
+        self.capture_session = EmulatorCaptureSession(session_id)
+        self.last_active_at = time.time()
+
+    def touch(self) -> float:
+        now = time.time()
+        with self.lock:
+            self.last_active_at = now
+        return now
+
+    def get_last_active_at(self) -> float:
+        with self.lock:
+            return self.last_active_at
+
+    def shutdown(self) -> None:
+        self.capture_session.stop(clear_error=True)
+
+    def add_image(self, image_file: Path, source: str, original_name: str) -> SessionImage:
+        image_id = uuid.uuid4().hex
+        image = SessionImage(
+            image_id=image_id,
+            path=image_file,
+            source=source,
+            original_name=original_name,
+            created_at=time.time(),
+        )
+        with self.lock:
+            self.images[image_id] = image
+            self.image_order.append(image_id)
+            self.current_image_id = image_id
+            self.last_active_at = time.time()
+        return image
+
+    def remove_image(self, image_id: str) -> bool:
+        with self.lock:
+            image = self.images.pop(image_id, None)
+            if image is None:
+                return False
+            self.image_order = [x for x in self.image_order if x != image_id]
+            if self.current_image_id == image_id:
+                self.current_image_id = self.image_order[-1] if self.image_order else None
+            self.last_active_at = time.time()
+        try:
+            if image.path.exists():
+                image.path.unlink()
+        except Exception:
+            logger.warning(f"[annotator] remove image file failed: {image.path}")
+        return True
+
+    def remove_images(self, image_ids: list[str]) -> int:
+        removed = 0
+        for image_id in image_ids:
+            if self.remove_image(image_id):
+                removed += 1
+        return removed
+
+    def clear_images(self) -> int:
+        with self.lock:
+            image_ids = list(self.image_order)
+        return self.remove_images(image_ids)
+
+    def snapshot(self) -> dict[str, Any]:
+        with self.lock:
+            images = [self.images[i].to_dict(self.session_id) for i in self.image_order if i in self.images]
+            return {
+                "session_id": self.session_id,
+                "current_image_id": self.current_image_id,
+                "updated_at": self.last_active_at,
+                "images": images,
+                "emulator": self.capture_session.status(),
+            }
+
+
+class AnnotatorManager:
+    def __init__(self) -> None:
+        self._sessions: dict[str, AnnotatorSession] = {}
+        self._lock = threading.Lock()
+        self._cleanup_lock = threading.Lock()
+        self._last_cleanup_at = 0.0
+        self._session_idle_timeout = SESSION_IDLE_TIMEOUT_SECONDS
+        self._session_sweep_interval = SESSION_SWEEP_INTERVAL_SECONDS
+        self._cleanup_stop = threading.Event()
+        self._cleanup_thread = threading.Thread(
+            target=self._session_cleanup_loop,
+            daemon=True,
+            name="annotator_session_cleanup",
+        )
+        ANNOTATOR_ROOT.mkdir(parents=True, exist_ok=True)
+        self._cleanup_thread.start()
+
+    def _session_cleanup_loop(self) -> None:
+        while not self._cleanup_stop.wait(self._session_sweep_interval):
+            try:
+                self._cleanup_expired_sessions(force=True)
+            except Exception:
+                logger.exception("[annotator] cleanup loop failed")
+
+    def _cleanup_expired_sessions(self, force: bool = False) -> None:
+        now = time.time()
+        if not force and now - self._last_cleanup_at < self._session_sweep_interval:
+            return
+
+        with self._cleanup_lock:
+            now = time.time()
+            if not force and now - self._last_cleanup_at < self._session_sweep_interval:
+                return
+            self._last_cleanup_at = now
+
+            expired: list[str] = []
+            with self._lock:
+                for session_id, session in self._sessions.items():
+                    idle_seconds = now - session.get_last_active_at()
+                    if idle_seconds >= self._session_idle_timeout:
+                        expired.append(session_id)
+
+        for session_id in expired:
+            self.close_session(session_id, reason="timeout")
+
+    @staticmethod
+    def index_file() -> Path:
+        return Path(__file__).resolve().parent / "web" / "annotator" / "index.html"
+
+    @staticmethod
+    def static_dir() -> Path:
+        return Path(__file__).resolve().parent / "web" / "annotator"
+
+    def _cleanup_session_dir_path(self, session_id: str, target: Path, reason: str) -> bool:
+        target = target.resolve()
+        self._ensure_within_root(target, ANNOTATOR_ROOT)
+        if target == ANNOTATOR_ROOT:
+            raise AnnotatorError("invalid_path", "会话目录无效", 500)
+
+        if not target.exists():
+            return False
+
+        if not target.is_dir():
+            logger.warning(
+                f"[annotator] skip non-dir session cleanup, session={session_id}, reason={reason}, target={target}"
+            )
+            return False
+
+        shutil.rmtree(target)
+        logger.info(f"[annotator] session dir removed, session={session_id}, reason={reason}, dir={target}")
+        return True
+
+    def _cleanup_session_dir(self, session: AnnotatorSession, reason: str) -> bool:
+        return self._cleanup_session_dir_path(session.session_id, session.root, reason)
+
+    def _cleanup_foreign_session_dirs(self, keep_session_id: str, reason: str) -> int:
+        removed = 0
+        if not ANNOTATOR_ROOT.exists():
+            return removed
+
+        for target in ANNOTATOR_ROOT.iterdir():
+            if target.name == keep_session_id:
+                continue
+            try:
+                if self._cleanup_session_dir_path(target.name, target, reason):
+                    removed += 1
+            except Exception:
+                logger.exception(
+                    f"[annotator] foreign session dir cleanup failed, session={target.name}, reason={reason}"
+                )
+        return removed
+
+    def _replace_active_sessions(self, session: AnnotatorSession, reason: str) -> int:
+        with self._lock:
+            replaced_sessions = [
+                (session_id, existing)
+                for session_id, existing in self._sessions.items()
+                if session_id != session.session_id
+            ]
+            self._sessions = {session.session_id: session}
+
+        for session_id, existing in replaced_sessions:
+            try:
+                existing.shutdown()
+            except Exception:
+                logger.exception(
+                    f"[annotator] old session shutdown failed, session={session_id}, reason={reason}"
+                )
+            try:
+                self._cleanup_session_dir(existing, reason)
+            except Exception:
+                logger.exception(
+                    f"[annotator] old session dir cleanup failed, session={session_id}, reason={reason}"
+                )
+        return len(replaced_sessions)
+
+    def close_session(self, session_id: str, reason: str = "manual", raise_if_missing: bool = False) -> dict[str, Any]:
+        with self._lock:
+            session = self._sessions.pop(session_id, None)
+
+        if session is None:
+            if raise_if_missing:
+                raise AnnotatorError("invalid_session", f"会话不存在: {session_id}", 404)
+            return {
+                "session_id": session_id,
+                "closed": False,
+                "reason": reason,
+                "dir_removed": False,
+            }
+
+        session.shutdown()
+
+        dir_removed = False
+        try:
+            dir_removed = self._cleanup_session_dir(session, reason)
+        except Exception:
+            logger.exception(f"[annotator] session dir cleanup failed, session={session_id}, reason={reason}")
+
+        logger.info(
+            f"[annotator] session closed, session={session_id}, reason={reason}, dir_removed={dir_removed}"
+        )
+        return {
+            "session_id": session_id,
+            "closed": True,
+            "reason": reason,
+            "dir_removed": dir_removed,
+        }
+
+    def create_session(self) -> dict[str, Any]:
+        self._cleanup_expired_sessions()
+        with self._cleanup_lock:
+            session_id = uuid.uuid4().hex
+            session = AnnotatorSession(session_id)
+            replace_reason = f"replaced_by:{session_id}"
+            replaced_count = self._replace_active_sessions(session, replace_reason)
+            orphan_removed = self._cleanup_foreign_session_dirs(
+                keep_session_id=session_id,
+                reason=f"create_session:{session_id}",
+            )
+        logger.info(
+            f"[annotator] session created, session={session_id}, "
+            f"replaced_sessions={replaced_count}, removed_other_dirs={orphan_removed}"
+        )
+        return session.snapshot()
+
+    def _get_session(self, session_id: str) -> AnnotatorSession:
+        self._cleanup_expired_sessions()
+        with self._lock:
+            session = self._sessions.get(session_id)
+        if session is None:
+            raise AnnotatorError("invalid_session", f"会话不存在: {session_id}", 404)
+        session.touch()
+        return session
+
+    def get_session_snapshot(self, session_id: str) -> dict[str, Any]:
+        return self._get_session(session_id).snapshot()
+
+    @staticmethod
+    def _safe_stem(filename: str) -> str:
+        stem = Path(filename).stem.strip()
+        stem = re.sub(r"[^a-zA-Z0-9_\-]", "_", stem)
+        return stem or "image"
+
+    def save_uploaded_images_base64(self, session_id: str, images_payload: list[dict[str, Any]]) -> list[dict[str, Any]]:
+        session = self._get_session(session_id)
+        results: list[dict[str, Any]] = []
+        for payload in images_payload:
+            filename = str(payload.get("name", "")).strip()
+            content_base64 = str(payload.get("content_base64", "")).strip()
+            if not filename:
+                continue
+            if not content_base64:
+                continue
+            suffix = Path(filename).suffix.lower()
+            if not suffix:
+                suffix = ".png"
+            if suffix not in ALLOWED_IMAGE_EXT:
+                raise AnnotatorError("invalid_image_ext", f"不支持的图片类型: {suffix}", 400)
+            image_name = f"{uuid.uuid4().hex}_{self._safe_stem(filename)}{suffix}"
+            target = session.upload_dir / image_name
+            if "," in content_base64:
+                content_base64 = content_base64.split(",", 1)[1]
+            try:
+                content = base64.b64decode(content_base64)
+            except Exception as e:
+                raise AnnotatorError("invalid_image_data", f"图片编码解析失败: {filename}", 400) from e
+            target.write_bytes(content)
+            image = session.add_image(target, "upload", filename)
+            results.append(image.to_dict(session_id))
+        if not results:
+            raise AnnotatorError("empty_upload", "未上传有效图片", 400)
+        logger.info(f"[annotator] upload images, session={session_id}, count={len(results)}")
+        return results
+
+    def list_images(self, session_id: str) -> list[dict[str, Any]]:
+        session = self._get_session(session_id)
+        return session.snapshot()["images"]
+
+    def get_image_file(self, session_id: str, image_id: str) -> Path:
+        session = self._get_session(session_id)
+        image = session.images.get(image_id)
+        if image is None:
+            raise AnnotatorError("image_not_found", f"图片不存在: {image_id}", 404)
+        return image.path
+
+    def delete_image(self, session_id: str, image_id: str) -> dict[str, Any]:
+        session = self._get_session(session_id)
+        removed = session.remove_image(image_id)
+        if not removed:
+            raise AnnotatorError("image_not_found", f"图片不存在: {image_id}", 404)
+        logger.info(f"[annotator] image removed, session={session_id}, image={image_id}")
+        return session.snapshot()
+
+    def delete_images(self, session_id: str, image_ids: list[str]) -> dict[str, Any]:
+        if not image_ids:
+            raise AnnotatorError("empty_image_ids", "image_ids 不能为空", 400)
+        session = self._get_session(session_id)
+        removed = session.remove_images(image_ids)
+        logger.info(f"[annotator] images removed, session={session_id}, removed={removed}")
+        return {"removed_count": removed, "session": session.snapshot()}
+
+    def clear_images(self, session_id: str) -> dict[str, Any]:
+        session = self._get_session(session_id)
+        removed = session.clear_images()
+        logger.info(f"[annotator] images cleared, session={session_id}, removed={removed}")
+        return {"removed_count": removed, "session": session.snapshot()}
+
+    @staticmethod
+    def list_task_names() -> list[str]:
+        tasks = []
+        for d in TASKS_ROOT.iterdir():
+            if not d.is_dir():
+                continue
+            if d.name.startswith("__"):
+                continue
+            tasks.append(d.name)
+        return sorted(tasks)
+
+    def list_configs(self) -> list[str]:
+        return ConfigManager.all_script_files()
+
+    @staticmethod
+    def rule_schema() -> dict[str, Any]:
+        return get_schema_payload()
+
+    def start_emulator(self, session_id: str, config_name: str, frame_rate: int) -> dict[str, Any]:
+        session = self._get_session(session_id)
+        if config_name not in self.list_configs():
+            raise AnnotatorError("invalid_config", f"配置不存在: {config_name}", 400)
+        applied_rate = session.capture_session.start(config_name, frame_rate)
+        logger.info(
+            f"[annotator] emulator start, session={session_id}, config={config_name}, frame_rate={applied_rate}"
+        )
+        return session.capture_session.status()
+
+    def stop_emulator(self, session_id: str) -> dict[str, Any]:
+        session = self._get_session(session_id)
+        session.capture_session.stop(clear_error=True)
+        logger.info(f"[annotator] emulator stop, session={session_id}")
+        return session.capture_session.status()
+
+    def emulator_status(self, session_id: str) -> dict[str, Any]:
+        session = self._get_session(session_id)
+        return session.capture_session.status()
+
+    def latest_emulator_frame(self, session_id: str) -> bytes | None:
+        session = self._get_session(session_id)
+        return session.capture_session.latest_jpeg()
+
+    def capture_from_emulator(self, session_id: str) -> dict[str, Any]:
+        session = self._get_session(session_id)
+        target = session.capture_dir / f"capture_{int(time.time() * 1000)}.png"
+        session.capture_session.capture_latest_frame(target)
+        image = session.add_image(target, "capture", target.name)
+        logger.info(f"[annotator] capture frame, session={session_id}, target={target}")
+        return image.to_dict(session_id)
+
+    @staticmethod
+    def _format_roi_number(value: float) -> str:
+        rounded = round(value)
+        if abs(value - rounded) < 1e-6:
+            return str(int(rounded))
+        text = f"{value:.4f}".rstrip("0").rstrip(".")
+        return text or "0"
+
+    @staticmethod
+    def _parse_roi(value: str) -> str:
+        if not isinstance(value, str):
+            raise AnnotatorError("invalid_roi", "ROI 必须是字符串", 400)
+        parts = [p.strip() for p in value.split(",")]
+        if len(parts) != 4:
+            raise AnnotatorError("invalid_roi", "ROI 必须是 x,y,w,h", 400)
+        try:
+            x, y, w, h = [float(p) for p in parts]
+        except ValueError as e:
+            raise AnnotatorError("invalid_roi", "ROI 必须是数字", 400) from e
+        if w <= 0 or h <= 0:
+            raise AnnotatorError("invalid_roi", "ROI 的宽高必须大于 0", 400)
+        return ",".join(
+            [
+                AnnotatorManager._format_roi_number(x),
+                AnnotatorManager._format_roi_number(y),
+                AnnotatorManager._format_roi_number(w),
+                AnnotatorManager._format_roi_number(h),
+            ]
+        )
+
+    def _normalize_image_rules(self, rules: list[dict[str, Any]]) -> list[dict[str, Any]]:
+        normalized: list[dict[str, Any]] = []
+        for index, rule in enumerate(rules):
+            item_name = str(rule.get("itemName", "")).strip()
+            if not item_name:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条规则缺少 itemName", 400)
+            image_name = str(rule.get("imageName", "")).strip() or f"{item_name}.png"
+            threshold_value = rule.get("threshold", 0.8)
+            try:
+                threshold = float(threshold_value)
+            except (TypeError, ValueError) as e:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条规则 threshold 非法", 400) from e
+            if threshold < 0 or threshold > 1:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条规则 threshold 必须在 0-1", 400)
+            normalized.append(
+                {
+                    "itemName": item_name,
+                    "imageName": image_name,
+                    "roiFront": self._parse_roi(str(rule.get("roiFront", ""))),
+                    "roiBack": self._parse_roi(str(rule.get("roiBack", ""))),
+                    "method": str(rule.get("method", field_default("image", "method", "Template matching"))).strip() or field_default("image", "method", "Template matching"),
+                    "threshold": threshold,
+                    "description": str(rule.get("description", "")).strip(),
+                }
+            )
+        return normalized
+
+    def _normalize_ocr_rules(self, rules: list[dict[str, Any]]) -> list[dict[str, Any]]:
+        normalized: list[dict[str, Any]] = []
+        for index, rule in enumerate(rules):
+            item_name = str(rule.get("itemName", "")).strip()
+            if not item_name:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条规则缺少 itemName", 400)
+            mode = str(rule.get("mode", field_default("ocr", "mode", "Single"))).strip() or field_default("ocr", "mode", "Single")
+            if mode not in ALLOWED_OCR_MODE:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条规则 mode 不支持: {mode}", 400)
+            normalized.append(
+                {
+                    "itemName": item_name,
+                    "roiFront": self._parse_roi(str(rule.get("roiFront", ""))),
+                    "roiBack": self._parse_roi(str(rule.get("roiBack", ""))),
+                    "mode": mode,
+                    "method": str(rule.get("method", field_default("ocr", "method", "Default"))).strip() or field_default("ocr", "method", "Default"),
+                    "keyword": str(rule.get("keyword", "")).strip(),
+                    "description": str(rule.get("description", "")).strip(),
+                }
+            )
+        return normalized
+
+    def _normalize_click_rules(self, rules: list[dict[str, Any]]) -> list[dict[str, Any]]:
+        normalized: list[dict[str, Any]] = []
+        for index, rule in enumerate(rules):
+            item_name = str(rule.get("itemName", "")).strip()
+            if not item_name:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条点击规则缺少 itemName", 400)
+            normalized.append(
+                {
+                    "itemName": item_name,
+                    "roiFront": self._parse_roi(str(rule.get("roiFront", ""))),
+                    "roiBack": self._parse_roi(str(rule.get("roiBack", ""))),
+                    "description": str(rule.get("description", "")).strip(),
+                }
+            )
+        return normalized
+
+    def _normalize_swipe_rules(self, rules: list[dict[str, Any]]) -> list[dict[str, Any]]:
+        normalized: list[dict[str, Any]] = []
+        for index, rule in enumerate(rules):
+            item_name = str(rule.get("itemName", "")).strip()
+            if not item_name:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条滑动规则缺少 itemName", 400)
+            mode = str(rule.get("mode", field_default("swipe", "mode", "default"))).strip() or field_default("swipe", "mode", "default")
+            if mode not in ALLOWED_SWIPE_MODE:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条滑动规则 mode 不支持: {mode}", 400)
+            normalized.append(
+                {
+                    "itemName": item_name,
+                    "roiFront": self._parse_roi(str(rule.get("roiFront", ""))),
+                    "roiBack": self._parse_roi(str(rule.get("roiBack", ""))),
+                    "mode": mode,
+                    "description": str(rule.get("description", "")).strip(),
+                }
+            )
+        return normalized
+
+    def _normalize_long_click_rules(self, rules: list[dict[str, Any]]) -> list[dict[str, Any]]:
+        normalized: list[dict[str, Any]] = []
+        for index, rule in enumerate(rules):
+            item_name = str(rule.get("itemName", "")).strip()
+            if not item_name:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条长按规则缺少 itemName", 400)
+            try:
+                duration = int(rule.get("duration", field_default("long_click", "duration", 1000)))
+            except (TypeError, ValueError) as e:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条长按规则 duration 非法", 400) from e
+            if duration <= 0:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条长按规则 duration 必须大于 0", 400)
+            normalized.append(
+                {
+                    "itemName": item_name,
+                    "roiFront": self._parse_roi(str(rule.get("roiFront", ""))),
+                    "roiBack": self._parse_roi(str(rule.get("roiBack", ""))),
+                    "duration": duration,
+                    "description": str(rule.get("description", "")).strip(),
+                }
+            )
+        return normalized
+
+    def _normalize_list_rules(self, rules: list[dict[str, Any]], list_meta: dict[str, Any] | None) -> dict[str, Any]:
+        if not list_meta:
+            raise AnnotatorError("invalid_rule", "list 规则缺少 list_meta", 400)
+
+        list_name = str(list_meta.get("name", "")).strip()
+        if not list_name:
+            raise AnnotatorError("invalid_rule", "list_meta.name 不能为空", 400)
+
+        direction = str(list_meta.get("direction", field_default("list", "direction", "vertical"))).strip() or field_default("list", "direction", "vertical")
+        if direction not in ALLOWED_LIST_DIRECTION:
+            raise AnnotatorError("invalid_rule", f"list_meta.direction 不支持: {direction}", 400)
+
+        list_type = str(list_meta.get("type", field_default("list", "type", "image"))).strip() or field_default("list", "type", "image")
+        if list_type not in ALLOWED_LIST_MODE:
+            raise AnnotatorError("invalid_rule", f"list_meta.type 不支持: {list_type}", 400)
+
+        roi_back = self._parse_roi(str(list_meta.get("roiBack", "")))
+
+        normalized_items = []
+        for index, item in enumerate(rules):
+            item_name = str(item.get("itemName", "")).strip()
+            if not item_name:
+                raise AnnotatorError("invalid_rule", f"第 {index + 1} 条 list 项缺少 itemName", 400)
+            normalized_items.append(
+                {
+                    "itemName": item_name,
+                    "roiFront": self._parse_roi(str(item.get("roiFront", ""))),
+                }
+            )
+
+        return {
+            "name": list_name,
+            "direction": direction,
+            "type": list_type,
+            "roiBack": roi_back,
+            "description": str(list_meta.get("description", "")).strip(),
+            "list": normalized_items,
+        }
+
+    @staticmethod
+    def _ensure_within_root(path: Path, root: Path) -> None:
+        try:
+            path.relative_to(root)
+        except ValueError as e:
+            raise AnnotatorError("invalid_path", "目标路径不在允许目录内", 400) from e
+
+    @staticmethod
+    def _resolve_task_root(task_name: str) -> Path:
+        task_root = (TASKS_ROOT / task_name).resolve()
+        AnnotatorManager._ensure_within_root(task_root, TASKS_ROOT)
+        if not task_root.exists() or not task_root.is_dir():
+            raise AnnotatorError("invalid_task", f"任务目录不存在: {task_name}", 404)
+        return task_root
+
+    @staticmethod
+    def _resolve_tasks_subdir(rel_dir: str) -> Path:
+        rel = Path(str(rel_dir or "").strip().replace("\\", "/"))
+        if rel.is_absolute():
+            raise AnnotatorError("invalid_path", "目录路径必须是相对路径", 400)
+        base = (TASKS_ROOT / rel).resolve()
+        AnnotatorManager._ensure_within_root(base, TASKS_ROOT)
+        if not base.exists() or not base.is_dir():
+            raise AnnotatorError("invalid_path", f"目录不存在: {rel.as_posix()}", 404)
+        return base
+
+    @staticmethod
+    def _resolve_json_path(task_name: str, json_relpath: str) -> tuple[Path, Path]:
+        task_root = AnnotatorManager._resolve_task_root(task_name)
+        rel = Path(json_relpath)
+        if rel.is_absolute():
+            raise AnnotatorError("invalid_path", "json_relpath 必须是相对路径", 400)
+        target_json = (task_root / rel).resolve()
+        AnnotatorManager._ensure_within_root(target_json, task_root)
+        if target_json.suffix.lower() != ".json":
+            raise AnnotatorError("invalid_path", "目标文件必须是 .json", 400)
+        return task_root, target_json
+
+    @staticmethod
+    def _resolve_assets_extract_target(task_root: Path, target_json: Path) -> tuple[Path, Path]:
+        task_root = task_root.resolve()
+        target_json = target_json.resolve()
+        AnnotatorManager._ensure_within_root(target_json, task_root)
+
+        if task_root.name != "Component":
+            return task_root, task_root / "assets.py"
+
+        rel_parts = target_json.relative_to(task_root).parts
+        if len(rel_parts) < 2:
+            raise AnnotatorError(
+                "invalid_component_task",
+                "Component 目录下的规则文件必须位于具体组件子任务目录中",
+                400,
+            )
+
+        component_name = rel_parts[0]
+        extract_root = (task_root / component_name).resolve()
+        AnnotatorManager._ensure_within_root(extract_root, task_root)
+        if not extract_root.exists() or not extract_root.is_dir():
+            raise AnnotatorError(
+                "invalid_component_task",
+                f"Component 子任务目录不存在: {component_name}",
+                404,
+            )
+        return extract_root, extract_root / "assets.py"
+
+    @staticmethod
+    def list_task_json_files(task_name: str) -> list[str]:
+        task_root = AnnotatorManager._resolve_task_root(task_name)
+        result = []
+        for p in task_root.rglob("*.json"):
+            if p.is_file():
+                result.append(str(p.relative_to(task_root).as_posix()))
+        return sorted(result)
+
+    @staticmethod
+    def list_rule_source(rel_dir: str = "") -> dict[str, Any]:
+        base = AnnotatorManager._resolve_tasks_subdir(rel_dir)
+        directories: list[str] = []
+        json_files: list[str] = []
+        for item in sorted(base.iterdir(), key=lambda x: x.name.lower()):
+            if item.is_dir():
+                if item.name.startswith("__"):
+                    continue
+                directories.append(item.name)
+            elif item.is_file() and item.suffix.lower() == ".json":
+                json_files.append(item.name)
+
+        base_rel = ""
+        if base != TASKS_ROOT:
+            base_rel = str(base.relative_to(TASKS_ROOT).as_posix())
+
+        return {
+            "base_dir": base_rel,
+            "directories": directories,
+            "json_files": json_files,
+        }
+
+    @staticmethod
+    def create_rule_json(rel_dir: str, file_name: str) -> dict[str, Any]:
+        base = AnnotatorManager._resolve_tasks_subdir(rel_dir)
+        name = str(file_name or "").strip()
+        if not name:
+            raise AnnotatorError("invalid_name", "文件名不能为空", 400)
+        if "/" in name or "\\" in name:
+            raise AnnotatorError("invalid_name", "文件名不能包含路径分隔符", 400)
+        if not name.lower().endswith(".json"):
+            name = f"{name}.json"
+        target = (base / name).resolve()
+        AnnotatorManager._ensure_within_root(target, TASKS_ROOT)
+        if target.exists():
+            raise AnnotatorError("file_exists", f"文件已存在: {name}", 409)
+        target.parent.mkdir(parents=True, exist_ok=True)
+        with atomic_write(target, overwrite=True, encoding="utf-8") as f:
+            json.dump([], f, ensure_ascii=False, indent=2)
+        return {"file": str(target.relative_to(TASKS_ROOT).as_posix())}
+
+    @staticmethod
+    def delete_rule_json(rel_dir: str, file_name: str) -> dict[str, Any]:
+        base = AnnotatorManager._resolve_tasks_subdir(rel_dir)
+        name = str(file_name or "").strip()
+        if not name:
+            raise AnnotatorError("invalid_name", "文件名不能为空", 400)
+        if "/" in name or "\\" in name:
+            raise AnnotatorError("invalid_name", "文件名不能包含路径分隔符", 400)
+        target = (base / name).resolve()
+        AnnotatorManager._ensure_within_root(target, TASKS_ROOT)
+        if target.suffix.lower() != ".json":
+            raise AnnotatorError("invalid_name", "仅支持删除 .json 文件", 400)
+        if not target.exists():
+            raise AnnotatorError("json_not_found", f"JSON 文件不存在: {name}", 404)
+        target.unlink()
+        return {"file": str(target.relative_to(TASKS_ROOT).as_posix())}
+
+    @staticmethod
+    def _detect_rule_type(data: Any) -> str:
+        if isinstance(data, dict) and "list" in data and "name" in data:
+            return "list"
+        if isinstance(data, list) and data:
+            item = data[0]
+            if not isinstance(item, dict):
+                return "unknown"
+            if "imageName" in item:
+                return "image"
+            if "keyword" in item:
+                return "ocr"
+            if "duration" in item:
+                return "long_click"
+            if "mode" in item:
+                return "swipe"
+            return "click"
+        return "unknown"
+
+    @staticmethod
+    def load_rule_file(task_name: str, json_relpath: str) -> dict[str, Any]:
+        task_root, target_json = AnnotatorManager._resolve_json_path(task_name, json_relpath)
+        if not target_json.exists():
+            raise AnnotatorError("json_not_found", f"JSON 文件不存在: {json_relpath}", 404)
+
+        with open(target_json, "r", encoding="utf-8") as f:
+            data = json.load(f)
+
+        rule_type = AnnotatorManager._detect_rule_type(data)
+
+        list_meta = None
+        rules: list[dict[str, Any]] = []
+
+        if rule_type == "list":
+            list_meta = {
+                "name": str(data.get("name", field_default("list", "name", "list_name"))),
+                "direction": str(data.get("direction", field_default("list", "direction", "vertical"))),
+                "type": str(data.get("type", field_default("list", "type", "image"))),
+                "roiBack": str(data.get("roiBack", default_list_meta().get("roiBack", "0,0,100,100"))),
+                "description": str(data.get("description", field_default("list", "description", ""))),
+            }
+            for item in data.get("list", []):
+                if not isinstance(item, dict):
+                    continue
+                rules.append(
+                    {
+                        "itemName": str(item.get("itemName", "")),
+                        "roiFront": str(item.get("roiFront", "0,0,100,100")),
+                    }
+                )
+        elif isinstance(data, list):
+            for item in data:
+                if not isinstance(item, dict):
+                    continue
+                if rule_type == "image":
+                    rules.append(
+                        {
+                            "itemName": str(item.get("itemName", "")),
+                            "imageName": str(item.get("imageName", "")),
+                            "roiFront": str(item.get("roiFront", "0,0,100,100")),
+                            "roiBack": str(item.get("roiBack", "0,0,100,100")),
+                            "method": str(item.get("method", "Template matching")),
+                            "threshold": float(item.get("threshold", 0.8)),
+                            "description": str(item.get("description", "")),
+                        }
+                    )
+                elif rule_type == "ocr":
+                    rules.append(
+                        {
+                            "itemName": str(item.get("itemName", "")),
+                            "roiFront": str(item.get("roiFront", "0,0,100,100")),
+                            "roiBack": str(item.get("roiBack", "0,0,100,100")),
+                            "mode": str(item.get("mode", "Single")),
+                            "method": str(item.get("method", "Default")),
+                            "keyword": str(item.get("keyword", "")),
+                            "description": str(item.get("description", "")),
+                        }
+                    )
+                elif rule_type == "click":
+                    rules.append(
+                        {
+                            "itemName": str(item.get("itemName", "")),
+                            "roiFront": str(item.get("roiFront", "0,0,100,100")),
+                            "roiBack": str(item.get("roiBack", "0,0,100,100")),
+                            "description": str(item.get("description", "")),
+                        }
+                    )
+                elif rule_type == "swipe":
+                    rules.append(
+                        {
+                            "itemName": str(item.get("itemName", "")),
+                            "roiFront": str(item.get("roiFront", "0,0,100,100")),
+                            "roiBack": str(item.get("roiBack", "0,0,100,100")),
+                            "mode": str(item.get("mode", "default")),
+                            "description": str(item.get("description", "")),
+                        }
+                    )
+                elif rule_type == "long_click":
+                    rules.append(
+                        {
+                            "itemName": str(item.get("itemName", "")),
+                            "roiFront": str(item.get("roiFront", "0,0,100,100")),
+                            "roiBack": str(item.get("roiBack", "0,0,100,100")),
+                            "duration": int(item.get("duration", 1000)),
+                            "description": str(item.get("description", "")),
+                        }
+                    )
+
+        if rule_type == "list":
+            list_meta = merge_list_meta_with_defaults(list_meta)
+        rules = [merge_rule_with_defaults(rule_type, item) for item in rules]
+
+        rule_type_locked = rule_type in ALLOWED_RULE_TYPE and len(rules) > 0
+
+        return {
+            "task_name": task_name,
+            "json_relpath": str(target_json.relative_to(task_root).as_posix()),
+            "rule_type": rule_type,
+            "rule_type_locked": rule_type_locked,
+            "rules": rules,
+            "list_meta": list_meta,
+        }
+
+    @staticmethod
+    def _resolve_rule_image_path(task_root: Path, target_json: Path, image_name: str) -> tuple[Path, str]:
+        image_rel = str(image_name or "").strip()
+        if not image_rel:
+            raise AnnotatorError("invalid_path", "image_name 不能为空", 400)
+        rel = Path(image_rel)
+        if rel.is_absolute():
+            raise AnnotatorError("invalid_path", "image_name 必须是相对路径", 400)
+        target = (target_json.parent / rel).resolve()
+        AnnotatorManager._ensure_within_root(target, task_root)
+        if target.suffix.lower() not in ALLOWED_IMAGE_EXT:
+            raise AnnotatorError("invalid_image_ext", "目标图片后缀不受支持", 400)
+        return target, image_rel
+
+    @staticmethod
+    def get_rule_image_file(task_name: str, json_relpath: str, image_name: str) -> Path:
+        task_root, target_json = AnnotatorManager._resolve_json_path(task_name, json_relpath)
+        target, image_rel = AnnotatorManager._resolve_rule_image_path(task_root, target_json, image_name)
+        if not target.exists() or not target.is_file():
+            raise AnnotatorError("image_not_found", f"图片不存在: {image_rel}", 404)
+        return target
+
+    def delete_rule_image(self, task_name: str, json_relpath: str, image_name: str) -> dict[str, Any]:
+        task_root, target_json = self._resolve_json_path(task_name, json_relpath)
+        target, image_rel = self._resolve_rule_image_path(task_root, target_json, image_name)
+
+        if target.exists() and not target.is_file():
+            raise AnnotatorError("invalid_path", f"目标图片不是文件: {image_rel}", 400)
+
+        removed = False
+        if target.exists():
+            try:
+                target.unlink()
+            except OSError as e:
+                raise AnnotatorError("delete_image_failed", f"删除图片失败: {image_rel}", 500) from e
+            removed = True
+
+        logger.info(
+            f"[annotator] delete rule image, task={task_name}, target={target}, removed={removed}"
+        )
+
+        return {
+            "removed": removed,
+            "image_name": image_rel,
+            "target_image": str(target.relative_to(PROJECT_ROOT).as_posix()),
+            "target_json": str(target_json.relative_to(task_root).as_posix()),
+        }
+
+    @staticmethod
+    def _list_item_image_name(item_name: str) -> str:
+        name = str(item_name or "").strip()
+        if not name:
+            raise AnnotatorError("invalid_rule", "list 项缺少 itemName", 400)
+        return f"{name}.png"
+
+    @classmethod
+    def get_list_item_image_file(cls, task_name: str, json_relpath: str, item_name: str) -> Path:
+        return cls.get_rule_image_file(task_name, json_relpath, cls._list_item_image_name(item_name))
+
+    @staticmethod
+    def _parse_roi_tuple(value: str) -> tuple[int, int, int, int]:
+        roi = AnnotatorManager._parse_roi(value)
+        x, y, w, h = [float(v) for v in roi.split(",")]
+        return int(round(x)), int(round(y)), int(round(w)), int(round(h))
+
+    @staticmethod
+    def _load_session_bgr_image(session: AnnotatorSession, image_id: str) -> tuple[np.ndarray, Path]:
+        image = session.images.get(image_id)
+        if image is None:
+            raise AnnotatorError("image_not_found", f"图片不存在: {image_id}", 404)
+        if not image.path.exists():
+            raise AnnotatorError("image_not_found", "源图片文件不存在", 404)
+        raw = cv2.imread(str(image.path), cv2.IMREAD_COLOR)
+        if raw is None:
+            raise AnnotatorError("invalid_image_data", "源图片读取失败", 400)
+        return raw, image.path
+
+    def test_rule(
+        self,
+        session_id: str,
+        image_id: str,
+        task_name: str,
+        json_relpath: str,
+        rule_type: str,
+        rule: dict[str, Any],
+        list_meta: dict[str, Any] | None = None,
+    ) -> dict[str, Any]:
+        session = self._get_session(session_id)
+        _, source_path = self._load_session_bgr_image(session, image_id)
+
+        if rule_type == "image":
+            item_name = str(rule.get("itemName", "")).strip() or "unnamed"
+            image_name = str(rule.get("imageName", "")).strip()
+            if not image_name:
+                raise AnnotatorError("invalid_rule", "image 规则缺少 imageName", 400)
+            method = str(rule.get("method", field_default("image", "method", "Template matching"))).strip() or field_default("image", "method", "Template matching")
+            try:
+                threshold = float(rule.get("threshold", 0.8))
+            except (TypeError, ValueError) as e:
+                raise AnnotatorError("invalid_rule", "threshold 非法", 400) from e
+            roi_back = self._parse_roi_tuple(str(rule.get("roiBack", "")))
+            task_root, target_json = self._resolve_json_path(task_name, json_relpath)
+            template = self.get_rule_image_file(task_name, json_relpath, image_name)
+            from module.atom.image import RuleImage
+
+            target = RuleImage(
+                roi_front=self._parse_roi_tuple(str(rule.get("roiFront", "0,0,100,100"))),
+                roi_back=roi_back,
+                method=method,
+                threshold=threshold,
+                file=str(template),
+            )
+            detail = detect_image_detail(str(source_path), target)
+            return {
+                "rule_type": "image",
+                "item_name": item_name,
+                "image_name": image_name,
+                "matched": bool(detail.get("matched", False)),
+                "similarity": float(detail.get("similarity", 0.0)),
+                "roiFront": self._parse_roi(str(detail.get("roiFront", rule.get("roiFront", "0,0,100,100")))),
+                "roiBack": self._parse_roi(str(detail.get("roiBack", rule.get("roiBack", "0,0,100,100")))),
+                "threshold": threshold,
+                "message": str(detail.get("message", "not_match")),
+                "target_json": str(target_json.relative_to(task_root).as_posix()),
+            }
+
+        if rule_type == "ocr":
+            item_name = str(rule.get("itemName", "")).strip() or "unnamed"
+            mode = str(rule.get("mode", field_default("ocr", "mode", "Single"))).strip() or field_default("ocr", "mode", "Single")
+            method = str(rule.get("method", "Default")).strip() or "Default"
+            keyword = str(rule.get("keyword", "")).strip()
+            roi_front = self._parse_roi_tuple(str(rule.get("roiFront", "")))
+            roi_back = self._parse_roi_tuple(str(rule.get("roiBack", "")))
+            from module.atom.ocr import RuleOcr
+
+            target = RuleOcr(
+                name=item_name,
+                mode=mode,
+                method=method,
+                roi=roi_front,
+                area=roi_back,
+                keyword=keyword,
+            )
+            detail = detect_ocr_detail(str(source_path), target)
+            return {
+                "rule_type": "ocr",
+                "item_name": item_name,
+                "matched": bool(detail.get("matched", False)),
+                "similarity": float(detail.get("similarity", 0.0)),
+                "text": str(detail.get("text", "")),
+                "keyword": keyword,
+                "roiFront": self._parse_roi(str(detail.get("roiFront", rule.get("roiFront", "0,0,100,100")))),
+                "roiBack": self._parse_roi(str(detail.get("roiBack", rule.get("roiBack", "0,0,100,100")))),
+                "message": str(detail.get("message", "not_match")),
+            }
+
+        if rule_type == "list":
+            if not list_meta:
+                raise AnnotatorError("invalid_rule", "list 测试缺少 list_meta", 400)
+
+            item_name = str(rule.get("itemName", "")).strip()
+            if not item_name:
+                raise AnnotatorError("invalid_rule", "list 项缺少 itemName", 400)
+
+            list_type = str(list_meta.get("type", field_default("list", "type", "image"))).strip() or field_default("list", "type", "image")
+            if list_type not in ALLOWED_LIST_MODE:
+                raise AnnotatorError("invalid_rule", f"list_meta.type 不支持: {list_type}", 400)
+            list_roi_back = self._parse_roi_tuple(str(list_meta.get("roiBack", "")))
+
+            if list_type == "image":
+                template = self.get_list_item_image_file(task_name, json_relpath, item_name)
+                from module.atom.image import RuleImage
+
+                target = RuleImage(
+                    roi_front=list_roi_back,
+                    roi_back=list_roi_back,
+                    method="Template matching",
+                    threshold=0.8,
+                    file=str(template),
+                )
+                detail = detect_image_detail(str(source_path), target)
+                return {
+                    "rule_type": "list",
+                    "list_type": "image",
+                    "item_name": item_name,
+                    "image_name": self._list_item_image_name(item_name),
+                    "matched": bool(detail.get("matched", False)),
+                    "similarity": float(detail.get("similarity", 0.0)),
+                    "roiFront": self._parse_roi(str(detail.get("roiFront", self._parse_roi(str(list_meta.get("roiBack", "0,0,100,100")))))),
+                    "roiBack": self._parse_roi(str(detail.get("roiBack", self._parse_roi(str(list_meta.get("roiBack", "0,0,100,100")))))),
+                    "threshold": 0.8,
+                    "message": str(detail.get("message", "not_match")),
+                }
+
+            from module.atom.ocr import RuleOcr
+
+            target = RuleOcr(
+                name=item_name,
+                mode="Full",
+                method="Default",
+                roi=list_roi_back,
+                area=(0, 0, 10, 10),
+                keyword=item_name,
+            )
+            detail = detect_ocr_detail(str(source_path), target)
+            return {
+                "rule_type": "list",
+                "list_type": "ocr",
+                "item_name": item_name,
+                "matched": bool(detail.get("matched", False)),
+                "similarity": float(detail.get("similarity", 0.0)),
+                "text": str(detail.get("text", "")),
+                "keyword": item_name,
+                "roiFront": self._parse_roi(str(detail.get("roiFront", self._parse_roi(str(list_meta.get("roiBack", "0,0,100,100")))))),
+                "roiBack": self._parse_roi(str(detail.get("roiBack", self._parse_roi(str(list_meta.get("roiBack", "0,0,100,100")))))),
+                "message": str(detail.get("message", "not_match")),
+            }
+
+        raise AnnotatorError("invalid_rule_type", f"不支持测试的 rule_type: {rule_type}", 400)
+
+    def save_rules_and_generate(
+        self,
+        session_id: str,
+        task_name: str,
+        json_relpath: str,
+        rule_type: str,
+        rules: list[dict[str, Any]],
+        list_meta: dict[str, Any] | None = None,
+    ) -> dict[str, Any]:
+        _ = self._get_session(session_id)
+        if not isinstance(rules, list):
+            raise AnnotatorError("invalid_rule", "rules 必须是数组", 400)
+
+        task_root, target_json = self._resolve_json_path(task_name, json_relpath)
+
+        if rule_type == "image":
+            payload = self._normalize_image_rules(rules) if rules else []
+        elif rule_type == "ocr":
+            payload = self._normalize_ocr_rules(rules) if rules else []
+        elif rule_type == "click":
+            payload = self._normalize_click_rules(rules) if rules else []
+        elif rule_type == "swipe":
+            payload = self._normalize_swipe_rules(rules) if rules else []
+        elif rule_type == "long_click":
+            payload = self._normalize_long_click_rules(rules) if rules else []
+        elif rule_type == "list":
+            payload = self._normalize_list_rules(rules, list_meta)
+        else:
+            raise AnnotatorError("invalid_rule_type", f"不支持的 rule_type: {rule_type}", 400)
+
+        target_json.parent.mkdir(parents=True, exist_ok=True)
+
+        lock = FileLock(f"{target_json}.lock")
+        with lock:
+            with atomic_write(target_json, overwrite=True, encoding="utf-8") as f:
+                json.dump(payload, f, ensure_ascii=False, indent=2)
+
+        save_status = "success"
+        generate_status = "success"
+        generate_error = ""
+        assets_file = ""
+        extract_root = None
+        try:
+            extract_root, assets_path = self._resolve_assets_extract_target(task_root, target_json)
+            assets_file = str(assets_path.relative_to(PROJECT_ROOT).as_posix())
+            AssetsExtractor(str(extract_root)).extract()
+        except Exception as e:
+            generate_status = "failed"
+            generate_error = str(e)
+            logger.exception(
+                f"[annotator] assets generate failed, session={session_id}, task={task_name}, "
+                f"target={target_json}, extract_root={extract_root}"
+            )
+
+        logger.info(
+            f"[annotator] save rules, session={session_id}, task={task_name}, target={target_json}, "
+            f"rule_type={rule_type}, save_status={save_status}, generate_status={generate_status}, "
+            f"assets_file={assets_file or 'n/a'}"
+        )
+
+        rule_count = len(payload.get("list", [])) if isinstance(payload, dict) and "list" in payload else len(payload)
+
+        return {
+            "save_status": save_status,
+            "generate_status": generate_status,
+            "error": generate_error,
+            "target_json": str(target_json.relative_to(PROJECT_ROOT).as_posix()),
+            "assets_file": assets_file,
+            "rule_count": rule_count,
+        }
+
+    def save_cropped_image(
+        self,
+        session_id: str,
+        image_id: str,
+        task_name: str,
+        json_relpath: str,
+        image_name: str,
+        roi: str,
+    ) -> dict[str, Any]:
+        session = self._get_session(session_id)
+        image = session.images.get(image_id)
+        if image is None:
+            raise AnnotatorError("image_not_found", f"图片不存在: {image_id}", 404)
+
+        if not image.path.exists():
+            raise AnnotatorError("image_not_found", "源图片文件不存在", 404)
+
+        task_root, target_json = self._resolve_json_path(task_name, json_relpath)
+        image_rel = Path(image_name)
+        if image_rel.is_absolute():
+            raise AnnotatorError("invalid_path", "image_name 必须是相对路径", 400)
+
+        target_image = (target_json.parent / image_rel).resolve()
+        self._ensure_within_root(target_image, task_root)
+        if target_image.suffix.lower() not in ALLOWED_IMAGE_EXT:
+            raise AnnotatorError("invalid_image_ext", "目标图片后缀不受支持", 400)
+
+        raw = cv2.imread(str(image.path), cv2.IMREAD_COLOR)
+        if raw is None:
+            raise AnnotatorError("invalid_image_data", "源图片读取失败", 400)
+
+        roi_text = self._parse_roi(roi)
+        x_f, y_f, w_f, h_f = [float(v) for v in roi_text.split(",")]
+        x = int(round(x_f))
+        y = int(round(y_f))
+        w = int(round(w_f))
+        h = int(round(h_f))
+
+        ih, iw = raw.shape[:2]
+        x = max(0, min(x, iw - 1))
+        y = max(0, min(y, ih - 1))
+        w = max(1, min(w, iw - x))
+        h = max(1, min(h, ih - y))
+        crop = raw[y:y + h, x:x + w]
+
+        target_image.parent.mkdir(parents=True, exist_ok=True)
+        ok = cv2.imwrite(str(target_image), crop)
+        if not ok:
+            raise AnnotatorError("save_image_failed", "保存裁剪图片失败", 500)
+
+        logger.info(
+            f"[annotator] save crop image, session={session_id}, image={image_id}, target={target_image}, roi={roi_text}"
+        )
+
+        return {
+            "save_status": "success",
+            "target_image": str(target_image.relative_to(PROJECT_ROOT).as_posix()),
+            "roi": roi_text,
+        }
+
+
+annotator_manager = AnnotatorManager()
+
+
+
+
+
+
+
+
+
+

+ 416 - 0
module/server/tool_router.py

@@ -0,0 +1,416 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import asyncio
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
+from fastapi.responses import FileResponse
+from pydantic import BaseModel
+
+from module.logger import logger
+from module.server.tool import AnnotatorError, annotator_manager
+
+tool_app = APIRouter(
+    prefix="/tool",
+    tags=["tool"],
+)
+
+
+class EmulatorStartBody(BaseModel):
+    session_id: str
+    config_name: str
+    frame_rate: int = 2
+
+
+class SessionBody(BaseModel):
+    session_id: str
+
+
+class RuleSaveBody(BaseModel):
+    session_id: str
+    task_name: str
+    json_relpath: str
+    rule_type: str
+    rules: list[dict[str, Any]]
+    list_meta: dict[str, Any] | None = None
+
+
+class UploadImageItem(BaseModel):
+    name: str
+    content_base64: str
+
+
+class UploadImagesBody(BaseModel):
+    session_id: str
+    images: list[UploadImageItem]
+
+
+class BatchDeleteImagesBody(BaseModel):
+    session_id: str
+    image_ids: list[str]
+
+
+class CropSaveBody(BaseModel):
+    session_id: str
+    image_id: str
+    task_name: str
+    json_relpath: str
+    image_name: str
+    roi: str
+
+
+class RuleImageDeleteBody(BaseModel):
+    task_name: str
+    json_relpath: str
+    image_name: str
+
+
+class RuleFileCreateBody(BaseModel):
+    dir_path: str
+    file_name: str
+
+
+class RuleFileDeleteBody(BaseModel):
+    dir_path: str
+    file_name: str
+
+
+class RuleTestBody(BaseModel):
+    session_id: str
+    image_id: str
+    task_name: str
+    json_relpath: str
+    rule_type: str
+    rule: dict[str, Any]
+    list_meta: dict[str, Any] | None = None
+
+def _raise_annotator_error(e: AnnotatorError) -> None:
+    raise HTTPException(
+        status_code=e.status_code,
+        detail={"code": e.code, "message": e.message},
+    )
+
+
+def _close_session_safely(session_id: str, reason: str) -> dict[str, Any]:
+    return annotator_manager.close_session(session_id, reason=reason, raise_if_missing=False)
+
+
+@tool_app.get('/annotator')
+async def tool_annotator_page():
+    page = annotator_manager.index_file()
+    if not page.exists():
+        raise HTTPException(status_code=404, detail={"code": "page_not_found", "message": "标注页面不存在"})
+    return FileResponse(page)
+
+
+@tool_app.post('/annotator/api/session')
+async def annotator_create_session():
+    session = annotator_manager.create_session()
+    return {"code": "ok", "session": session}
+
+
+@tool_app.get('/annotator/api/session/{session_id}')
+async def annotator_get_session(session_id: str):
+    try:
+        session = annotator_manager.get_session_snapshot(session_id)
+        return {"code": "ok", "session": session}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+
+
+@tool_app.delete('/annotator/api/session/{session_id}')
+async def annotator_close_session(session_id: str, reason: str = "client_close"):
+    try:
+        result = _close_session_safely(session_id, f"api:{reason}")
+        return {"code": "ok", **result}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/session/{session_id}/close')
+async def annotator_close_session_beacon(session_id: str, reason: str = "pagehide"):
+    try:
+        result = _close_session_safely(session_id, f"beacon:{reason}")
+        return {"code": "ok", **result}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+@tool_app.post('/annotator/api/images/upload')
+async def annotator_upload_images(data: UploadImagesBody):
+    try:
+        images = annotator_manager.save_uploaded_images_base64(
+            data.session_id,
+            [item.dict() for item in data.images],
+        )
+        return {"code": "ok", "images": images}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.get('/annotator/api/images')
+async def annotator_list_images(session_id: str):
+    try:
+        images = annotator_manager.list_images(session_id)
+        return {"code": "ok", "images": images}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.get('/annotator/api/images/{session_id}/{image_id}')
+async def annotator_image_file(session_id: str, image_id: str):
+    try:
+        image = annotator_manager.get_image_file(session_id, image_id)
+        return FileResponse(image)
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.delete('/annotator/api/images/{session_id}/{image_id}')
+async def annotator_delete_image(session_id: str, image_id: str):
+    try:
+        session = annotator_manager.delete_image(session_id, image_id)
+        return {"code": "ok", "session": session}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/images/delete-batch')
+async def annotator_delete_batch_images(data: BatchDeleteImagesBody):
+    try:
+        result = annotator_manager.delete_images(data.session_id, data.image_ids)
+        return {"code": "ok", **result}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/images/clear')
+async def annotator_clear_images(data: SessionBody):
+    try:
+        result = annotator_manager.clear_images(data.session_id)
+        return {"code": "ok", **result}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.get('/annotator/api/configs')
+async def annotator_configs():
+    configs = annotator_manager.list_configs()
+    return {"code": "ok", "configs": configs}
+
+
+@tool_app.get('/annotator/api/tasks')
+async def annotator_tasks():
+    tasks = annotator_manager.list_task_names()
+    return {"code": "ok", "tasks": tasks}
+
+
+@tool_app.get('/annotator/api/tasks/{task_name}/json')
+async def annotator_task_json_files(task_name: str):
+    try:
+        files = annotator_manager.list_task_json_files(task_name)
+        return {"code": "ok", "json_files": files}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.get('/annotator/api/rules/schema')
+async def annotator_rule_schema():
+    try:
+        data = annotator_manager.rule_schema()
+        return {"code": "ok", **data}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.get('/annotator/api/rules/load')
+async def annotator_load_rules(task_name: str, json_relpath: str):
+    try:
+        data = annotator_manager.load_rule_file(task_name, json_relpath)
+        return {"code": "ok", **data}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.get('/annotator/api/rules/source')
+async def annotator_rule_source(dir_path: str = ""):
+    try:
+        data = annotator_manager.list_rule_source(dir_path)
+        return {"code": "ok", **data}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/rules/source/create')
+async def annotator_rule_source_create(data: RuleFileCreateBody):
+    try:
+        result = annotator_manager.create_rule_json(data.dir_path, data.file_name)
+        return {"code": "ok", **result}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/rules/source/delete')
+async def annotator_rule_source_delete(data: RuleFileDeleteBody):
+    try:
+        result = annotator_manager.delete_rule_json(data.dir_path, data.file_name)
+        return {"code": "ok", **result}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.get('/annotator/api/rules/image-preview')
+async def annotator_rule_image_preview(task_name: str, json_relpath: str, image_name: str):
+    try:
+        image = annotator_manager.get_rule_image_file(task_name, json_relpath, image_name)
+        return FileResponse(image)
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/rules/image/delete')
+async def annotator_rule_image_delete(data: RuleImageDeleteBody):
+    try:
+        result = annotator_manager.delete_rule_image(data.task_name, data.json_relpath, data.image_name)
+        return {"code": "ok", **result}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/emulator/start')
+async def annotator_start_emulator(data: EmulatorStartBody):
+    try:
+        status = annotator_manager.start_emulator(data.session_id, data.config_name, data.frame_rate)
+        return {"code": "ok", "emulator": status}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/emulator/stop')
+async def annotator_stop_emulator(data: SessionBody):
+    try:
+        status = annotator_manager.stop_emulator(data.session_id)
+        return {"code": "ok", "emulator": status}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.get('/annotator/api/emulator/status')
+async def annotator_emulator_status(session_id: str):
+    try:
+        status = annotator_manager.emulator_status(session_id)
+        return {"code": "ok", "emulator": status}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/emulator/capture')
+async def annotator_capture_frame(data: SessionBody):
+    try:
+        image = annotator_manager.capture_from_emulator(data.session_id)
+        return {"code": "ok", "image": image}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/rules/test')
+async def annotator_test_rule(data: RuleTestBody):
+    try:
+        result = annotator_manager.test_rule(
+            session_id=data.session_id,
+            image_id=data.image_id,
+            task_name=data.task_name,
+            json_relpath=data.json_relpath,
+            rule_type=data.rule_type,
+            rule=data.rule,
+            list_meta=data.list_meta,
+        )
+        return {"code": "ok", "result": result}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/rules/save')
+async def annotator_save_rules(data: RuleSaveBody):
+    try:
+        result = annotator_manager.save_rules_and_generate(
+            session_id=data.session_id,
+            task_name=data.task_name,
+            json_relpath=data.json_relpath,
+            rule_type=data.rule_type,
+            rules=data.rules,
+            list_meta=data.list_meta,
+        )
+        code = "ok" if result.get("generate_status") == "success" else "partial_success"
+        return {"code": code, **result}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.post('/annotator/api/images/crop-save')
+async def annotator_crop_save(data: CropSaveBody):
+    try:
+        result = annotator_manager.save_cropped_image(
+            session_id=data.session_id,
+            image_id=data.image_id,
+            task_name=data.task_name,
+            json_relpath=data.json_relpath,
+            image_name=data.image_name,
+            roi=data.roi,
+        )
+        return {"code": "ok", **result}
+    except AnnotatorError as e:
+        _raise_annotator_error(e)
+
+
+@tool_app.websocket('/annotator/ws/{session_id}')
+async def annotator_frame_ws(websocket: WebSocket, session_id: str):
+    await websocket.accept()
+    try:
+        annotator_manager.get_session_snapshot(session_id)
+        while True:
+            frame = annotator_manager.latest_emulator_frame(session_id)
+            if frame:
+                await websocket.send_bytes(frame)
+                continue
+
+            status = annotator_manager.emulator_status(session_id)
+            if status.get("state") == "error":
+                await websocket.send_json(
+                    {
+                        "event": "error",
+                        "code": "emulator_error",
+                        "message": status.get("error", "unknown"),
+                    }
+                )
+                await websocket.close(code=1011)
+                break
+
+            await asyncio.sleep(0.1)
+    except WebSocketDisconnect:
+        logger.info(f"[annotator] ws disconnect, session={session_id}")
+    except AnnotatorError as e:
+        if e.code != "invalid_session":
+            logger.warning(f"[annotator] ws annotator error, session={session_id}, code={e.code}")
+        try:
+            await websocket.send_json({"event": "error", "code": e.code, "message": e.message})
+        except Exception:
+            pass
+        try:
+            await websocket.close(code=1008)
+        except Exception:
+            pass
+    except Exception as e:
+        message = str(e).strip().lower()
+        if e.__class__.__name__ == "ClientDisconnected" or "disconnected" in message:
+            logger.info(f"[annotator] ws client disconnected during send, session={session_id}")
+        else:
+            logger.exception(f"[annotator] ws failed, session={session_id}")
+        try:
+            await websocket.close(code=1011)
+        except Exception:
+            pass
+
+

+ 26 - 0
module/server/web/annotator/index.html

@@ -0,0 +1,26 @@
+<!doctype html>
+<html lang="zh-CN">
+<head>
+  <meta charset="utf-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1">
+  <title>OAS Web 标注工具</title>
+  <link rel="stylesheet" href="/tool/annotator/static/css/base.css">
+  <link rel="stylesheet" href="/tool/annotator/static/css/topbar.css">
+  <link rel="stylesheet" href="/tool/annotator/static/css/left-window.css">
+  <link rel="stylesheet" href="/tool/annotator/static/css/center-panel.css">
+  <link rel="stylesheet" href="/tool/annotator/static/css/right-window.css">
+</head>
+<body>
+  <div class="app" id="appRoot">
+    <div id="topbarMount"></div>
+
+    <main class="layout" id="ideLayout">
+      <div id="leftWindowMount"></div>
+      <div id="centerPanelMount"></div>
+      <div id="rightWindowMount"></div>
+    </main>
+  </div>
+
+  <script src="/tool/annotator/static/js/main.js"></script>
+</body>
+</html>

+ 1186 - 0
module/server/web/annotator/static/css/base.css

@@ -0,0 +1,1186 @@
+:root {
+  color-scheme: dark;
+
+  --bg-page: #1e1f22;
+  --bg-page-overlay-1: #2d3138;
+  --bg-page-overlay-2: #2b2f37;
+
+  --bg-topbar-1: #31353b;
+  --bg-topbar-2: #2a2d32;
+
+  --bg-panel-1: #2f3237;
+  --bg-panel-2: #2a2d31;
+  --bg-subpanel: #1f2227;
+  --bg-input: #1f2124;
+  --bg-button-1: #3c4148;
+  --bg-button-2: #33373e;
+  --bg-button-hover-1: #454b54;
+  --bg-button-hover-2: #373b43;
+
+  --bg-rail-1: #2f3339;
+  --bg-rail-2: #282b31;
+  --bg-rail-btn-1: #3e434c;
+  --bg-rail-btn-2: #363a42;
+  --bg-rail-btn-active-1: #335782;
+  --bg-rail-btn-active-2: #2d4c73;
+
+  --bg-stage: #1a1c20;
+  --bg-stage-inner: #111317;
+  --bg-output: #181a1e;
+
+  --text-main: #d6d8dc;
+  --text-secondary: #a9b1bd;
+  --text-muted: #99a1ad;
+  --text-title: #e6e8eb;
+  --text-code: #d5e7ff;
+
+  --line-main: #43464d;
+  --line-soft: #383b42;
+  --line-input: #4a4e56;
+
+  --accent: #4d94ff;
+  --accent-soft: rgba(77, 148, 255, 0.2);
+  --danger: #ff7575;
+  --ok: #70d080;
+
+  --danger-border: rgba(255, 117, 117, 0.45);
+  --ok-border: rgba(112, 208, 128, 0.45);
+  --fail-border: rgba(255, 117, 117, 0.45);
+  --selected-bg: rgba(77, 148, 255, 0.15);
+  --tip-bg: rgba(214, 167, 92, 0.12);
+  --tip-border: rgba(214, 167, 92, 0.4);
+  --grid-line: rgba(148, 164, 186, 0.16);
+
+  --shadow-panel: 0 4px 14px rgba(0, 0, 0, 0.24);
+  --shadow-stage: 0 12px 24px rgba(0, 0, 0, 0.36);
+
+  --rail-width: 44px;
+  --bottom-dock-space: 0px;
+  --bottom-dock-gap: 4px;
+}
+
+html[data-theme="light"] {
+  color-scheme: light;
+
+  --bg-page: #f5f6f8;
+  --bg-page-overlay-1: #dfe4ee;
+  --bg-page-overlay-2: #e8edf6;
+
+  --bg-topbar-1: #f7f9fd;
+  --bg-topbar-2: #edf2fa;
+
+  --bg-panel-1: #ffffff;
+  --bg-panel-2: #f8fbff;
+  --bg-subpanel: #f7f9fc;
+  --bg-input: #ffffff;
+  --bg-button-1: #f5f9ff;
+  --bg-button-2: #e7effb;
+  --bg-button-hover-1: #f0f6ff;
+  --bg-button-hover-2: #dfe8f7;
+
+  --bg-rail-1: #eef2f8;
+  --bg-rail-2: #e6ebf3;
+  --bg-rail-btn-1: #f8fbff;
+  --bg-rail-btn-2: #e6eef8;
+  --bg-rail-btn-active-1: #cce1ff;
+  --bg-rail-btn-active-2: #b9d5ff;
+
+  --bg-stage: #f0f4fa;
+  --bg-stage-inner: #e9edf5;
+  --bg-output: #f9fbff;
+
+  --text-main: #1f2733;
+  --text-secondary: #415063;
+  --text-muted: #5b687a;
+  --text-title: #111827;
+  --text-code: #11407e;
+
+  --line-main: #c7d2e0;
+  --line-soft: #d5deea;
+  --line-input: #b7c5d8;
+
+  --accent: #2f6dcf;
+  --accent-soft: rgba(47, 109, 207, 0.18);
+  --danger: #c0392b;
+  --ok: #2e7d32;
+
+  --danger-border: rgba(192, 57, 43, 0.45);
+  --ok-border: rgba(46, 125, 50, 0.45);
+  --fail-border: rgba(192, 57, 43, 0.45);
+  --selected-bg: rgba(47, 109, 207, 0.14);
+  --tip-bg: rgba(214, 167, 92, 0.14);
+  --tip-border: rgba(214, 167, 92, 0.45);
+  --grid-line: rgba(109, 129, 158, 0.18);
+
+  --shadow-panel: 0 4px 12px rgba(25, 45, 85, 0.08);
+  --shadow-stage: 0 10px 20px rgba(32, 49, 79, 0.16);
+}
+
+* {
+  box-sizing: border-box;
+}
+
+html,
+body {
+  margin: 0;
+  width: 100%;
+  height: 100%;
+}
+
+body {
+  font-family: "JetBrains Mono", "Cascadia Code", "Consolas", "Microsoft YaHei UI", sans-serif;
+  color: var(--text-main);
+  background:
+    radial-gradient(circle at 0 0, var(--bg-page-overlay-1) 0, transparent 42%),
+    radial-gradient(circle at 100% 100%, var(--bg-page-overlay-2) 0, transparent 34%),
+    var(--bg-page);
+}
+
+code {
+  color: var(--text-code);
+  font-size: 12px;
+}
+
+.app {
+  position: relative;
+  height: 100vh;
+  display: flex;
+  flex-direction: column;
+  overflow: hidden;
+}
+
+.topbar {
+  height: 44px;
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  padding: 8px 14px;
+  border-bottom: 1px solid var(--line-main);
+  background: linear-gradient(180deg, var(--bg-topbar-1) 0%, var(--bg-topbar-2) 100%);
+}
+
+.topbar h1 {
+  margin: 0;
+  font-size: 14px;
+  font-weight: 600;
+  letter-spacing: 0.03em;
+  color: var(--text-title);
+}
+
+.topbar-actions {
+  display: flex;
+  align-items: center;
+  gap: 12px;
+}
+
+.theme-switch {
+  display: flex;
+  align-items: center;
+  gap: 6px;
+  margin: 0;
+  font-size: 12px;
+  color: var(--text-muted);
+}
+
+.theme-switch select {
+  height: 28px;
+  min-width: 90px;
+}
+
+.session-meta {
+  font-size: 12px;
+  color: var(--text-muted);
+}
+
+.layout {
+  flex: 1;
+  min-height: 0;
+  display: flex;
+  gap: 0;
+  padding: 8px;
+  overflow: auto;
+}
+
+.tool-window {
+  min-height: 0;
+  display: flex;
+  align-items: stretch;
+  flex: 0 0 auto;
+}
+
+.icon-rail {
+  width: var(--rail-width);
+  background: linear-gradient(180deg, var(--bg-rail-1), var(--bg-rail-2));
+  border: 1px solid var(--line-soft);
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  gap: 6px;
+  padding: 8px 6px;
+  overflow-y: auto;
+  overflow-x: hidden;
+}
+
+.icon-rail-left {
+  border-radius: 8px 0 0 8px;
+  border-right: 0;
+}
+
+.icon-rail-right {
+  border-radius: 0 8px 8px 0;
+  border-left: 0;
+}
+
+.rail-btn {
+  width: 30px;
+  min-height: 60px;
+  border: 1px solid var(--line-input);
+  border-radius: 6px;
+  padding: 6px 3px;
+  font-size: 11px;
+  line-height: 1.2;
+  letter-spacing: 0.03em;
+  background: linear-gradient(180deg, var(--bg-rail-btn-1), var(--bg-rail-btn-2));
+  color: var(--text-main);
+  writing-mode: vertical-rl;
+  text-orientation: mixed;
+  cursor: pointer;
+  user-select: none;
+}
+
+.rail-btn:hover {
+  border-color: var(--accent);
+}
+
+.rail-btn.active {
+  border-color: var(--accent);
+  background: linear-gradient(180deg, var(--bg-rail-btn-active-1), var(--bg-rail-btn-active-2));
+  box-shadow: inset 0 0 0 1px var(--accent);
+}
+
+
+.rail-btn-output {
+  margin-top: auto;
+}
+
+.tool-content {
+  min-width: 0;
+  min-height: 0;
+  overflow: hidden;
+  transition: opacity 0.12s ease;
+}
+
+.tool-content-left,
+.tool-content-right {
+  border: 1px solid var(--line-soft);
+  padding: 8px;
+  background: linear-gradient(180deg, var(--bg-panel-1) 0%, var(--bg-panel-2) 100%);
+}
+
+.tool-content-left {
+  border-left: 0;
+  border-radius: 0 8px 8px 0;
+}
+
+.tool-content-right {
+  border-right: 0;
+  border-radius: 8px 0 0 8px;
+}
+
+.tool-window.collapsed .tool-content {
+  width: 0 !important;
+  padding: 0;
+  border-width: 0;
+  opacity: 0;
+  pointer-events: none;
+}
+
+.edge-splitter {
+  width: 8px;
+  min-width: 8px;
+  cursor: col-resize;
+  position: relative;
+  flex: 0 0 auto;
+}
+
+.edge-splitter::before {
+  content: "";
+  position: absolute;
+  top: 12px;
+  bottom: 12px;
+  left: 2px;
+  width: 4px;
+  border-radius: 4px;
+  background: linear-gradient(180deg, transparent 0%, var(--line-main) 18%, var(--line-main) 82%, transparent 100%);
+  opacity: 0.75;
+}
+
+.edge-splitter:hover::before {
+  background: linear-gradient(180deg, transparent 0%, var(--accent) 20%, var(--accent) 80%, transparent 100%);
+}
+
+.edge-splitter.disabled {
+  width: 0;
+  min-width: 0;
+  pointer-events: none;
+}
+
+.edge-splitter.disabled::before {
+  display: none;
+}
+
+.stack {
+  min-height: 0;
+  height: 100%;
+  display: flex;
+  flex-direction: column;
+  gap: 8px;
+}
+
+.stack.stack-icon-mode .panel-slot-active {
+  flex: 1 1 0;
+}
+
+.stack .panel-slot-hidden {
+  display: none !important;
+}
+
+.stack.stack-two-open {
+  gap: 0;
+}
+
+.stack.stack-two-open .panel-slot-active {
+  flex: 0 0 auto;
+  min-height: 0;
+}
+
+.panel-height-splitter {
+  display: none;
+  flex: 0 0 10px;
+  position: relative;
+  cursor: row-resize;
+}
+
+.panel-height-splitter::before {
+  content: "";
+  position: absolute;
+  left: 12px;
+  right: 12px;
+  top: 3px;
+  height: 4px;
+  border-radius: 4px;
+  background: linear-gradient(90deg, transparent, var(--line-main), transparent);
+  opacity: 0.75;
+}
+
+.panel-height-splitter:hover::before {
+  background: linear-gradient(90deg, transparent, var(--accent), transparent);
+}
+
+.stack.stack-two-open .panel-height-splitter {
+  display: block;
+}
+
+.panel-height-splitter.disabled {
+  display: none !important;
+}
+
+.panel {
+  background: linear-gradient(180deg, var(--bg-panel-1) 0%, var(--bg-panel-2) 100%);
+  border: 1px solid var(--line-soft);
+  border-radius: 8px;
+  padding: 10px;
+  min-height: 0;
+  display: flex;
+  flex-direction: column;
+  box-shadow: var(--shadow-panel);
+}
+
+.panel-top,
+.panel-fill {
+  max-height: none;
+  overflow: hidden;
+}
+
+.panel-fill {
+  min-height: 200px;
+}
+
+.panel-scroll-box {
+  display: flex;
+  flex-direction: column;
+}
+
+.panel-scroll-body {
+  min-height: 0;
+  overflow: auto;
+  padding-right: 2px;
+}
+
+.panel-lock-scroll {
+  overflow: hidden;
+}
+
+.center-panel {
+  flex: 1 1 auto;
+  min-width: 620px;
+  margin: 0 4px;
+  display: flex;
+  flex-direction: column;
+  min-height: 0;
+  overflow: auto;
+}
+
+.app.dock-open #leftContent,
+.app.dock-open #rightContent,
+.app.dock-open .center-panel {
+  margin-bottom: calc(var(--bottom-dock-space) + var(--bottom-dock-gap));
+}
+
+.app.dock-open .center-panel {
+  overflow: auto;
+}
+
+h2 {
+  margin: 2px 0 10px;
+  font-size: 13px;
+  line-height: 1.3;
+  letter-spacing: 0.04em;
+  text-transform: uppercase;
+  color: var(--text-secondary);
+  flex-shrink: 0;
+}
+
+h3 {
+  margin: 0;
+  font-size: 12px;
+  font-weight: 600;
+  letter-spacing: 0.03em;
+  color: var(--text-secondary);
+}
+
+label {
+  display: flex;
+  flex-direction: column;
+  gap: 5px;
+  margin: 8px 0;
+  font-size: 12px;
+  color: var(--text-secondary);
+}
+
+input,
+select,
+textarea,
+button {
+  font-family: inherit;
+  font-size: 12px;
+}
+
+input,
+select,
+textarea {
+  border: 1px solid var(--line-input);
+  border-radius: 5px;
+  padding: 7px 8px;
+  background: var(--bg-input);
+  color: var(--text-main);
+  transition: border-color 0.12s ease, box-shadow 0.12s ease;
+}
+
+input:focus,
+select:focus,
+textarea:focus {
+  border-color: var(--accent);
+  outline: none;
+  box-shadow: 0 0 0 2px var(--accent-soft);
+}
+
+textarea {
+  min-height: 78px;
+  resize: vertical;
+}
+
+button {
+  border: 1px solid var(--line-input);
+  border-radius: 5px;
+  padding: 7px 10px;
+  background: linear-gradient(180deg, var(--bg-button-1), var(--bg-button-2));
+  color: var(--text-main);
+  cursor: pointer;
+  transition: border-color 0.14s ease, background 0.14s ease, box-shadow 0.14s ease;
+}
+
+button:hover {
+  border-color: var(--accent);
+  background: linear-gradient(180deg, var(--bg-button-hover-1), var(--bg-button-hover-2));
+}
+
+button:active {
+  filter: brightness(0.97);
+}
+
+button:focus-visible {
+  outline: none;
+  box-shadow: 0 0 0 2px var(--accent-soft);
+}
+
+button:disabled {
+  opacity: 0.58;
+  cursor: not-allowed;
+}
+
+.btn-loading {
+  position: relative;
+  padding-left: 26px;
+}
+
+.btn-loading::before {
+  content: "";
+  position: absolute;
+  left: 10px;
+  top: 50%;
+  width: 10px;
+  height: 10px;
+  margin-top: -5px;
+  border: 2px solid currentColor;
+  border-right-color: transparent;
+  border-radius: 50%;
+  animation: btn-spin 0.75s linear infinite;
+}
+
+.danger-btn {
+  border-color: var(--danger-border);
+  color: var(--danger);
+}
+
+.row {
+  display: flex;
+  gap: 8px;
+  margin: 8px 0;
+  flex-wrap: wrap;
+  align-items: center;
+}
+
+.row > input,
+.row > select {
+  flex: 1 1 180px;
+  min-width: 120px;
+}
+
+.row > button {
+  flex: 0 0 auto;
+}
+
+.block {
+  padding: 8px;
+  border: 1px dashed var(--line-main);
+  border-radius: 6px;
+  margin: 8px 0;
+  background: var(--bg-subpanel);
+}
+
+.hidden {
+  display: none !important;
+}
+
+.small-output {
+  margin: 8px 0 0;
+  padding: 8px;
+  border-radius: 6px;
+  background: var(--bg-subpanel);
+  border: 1px solid var(--line-main);
+  color: var(--text-secondary);
+  white-space: pre-wrap;
+  word-break: break-word;
+  min-height: 48px;
+}
+
+.preview-card {
+  border: 1px solid var(--line-main);
+  border-radius: 6px;
+  min-height: 140px;
+  background: var(--bg-subpanel);
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  overflow: auto;
+}
+
+#emulatorPreview {
+  width: 100%;
+  height: auto;
+  max-height: 190px;
+  object-fit: contain;
+}
+
+.selected-info {
+  font-size: 12px;
+  color: var(--text-muted);
+  margin-bottom: 6px;
+  flex-shrink: 0;
+}
+
+#sessionImagesPanel .row {
+  flex-shrink: 0;
+}
+
+.image-list {
+  display: flex;
+  flex-direction: column;
+  gap: 6px;
+  border: 1px solid var(--line-main);
+  border-radius: 8px;
+  padding: 6px;
+  background: var(--bg-subpanel);
+  overflow: auto;
+  min-height: 0;
+  flex: 1;
+}
+
+.image-item {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+  border: 1px solid var(--line-input);
+  border-radius: 6px;
+  padding: 5px;
+  background: linear-gradient(180deg, var(--bg-panel-1), var(--bg-panel-2));
+  cursor: pointer;
+  min-width: 0;
+}
+
+.image-item.active {
+  border-color: var(--accent);
+  box-shadow: inset 0 0 0 1px var(--accent);
+}
+
+.image-item.selected {
+  background: var(--selected-bg);
+}
+
+.image-item .selector {
+  display: flex;
+  align-items: center;
+}
+
+.image-item img {
+  width: 52px;
+  height: 36px;
+  object-fit: cover;
+  border-radius: 4px;
+  background: var(--bg-subpanel);
+  border: 1px solid var(--line-main);
+  flex-shrink: 0;
+}
+
+.image-item .image-name {
+  flex: 1;
+  min-width: 0;
+  font-size: 12px;
+  color: var(--text-main);
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+
+.stage-wrap {
+  flex: 0 0 auto;
+  min-height: 300px;
+  height: min(68vh, 760px);
+  max-height: min(68vh, 760px);
+  display: block;
+  overflow: auto;
+  border: 1px solid var(--line-main);
+  border-radius: 8px;
+  background:
+    linear-gradient(90deg, var(--grid-line) 1px, transparent 1px) 0 0 / 24px 24px,
+    linear-gradient(var(--grid-line) 1px, transparent 1px) 0 0 / 24px 24px,
+    var(--bg-stage);
+  padding: 12px;
+}
+
+.stage-canvas-holder {
+  min-width: 100%;
+  width: max-content;
+  text-align: center;
+}
+
+.image-stage {
+  position: relative;
+  display: inline-block;
+  width: auto !important;
+  height: auto !important;
+  min-width: 320px;
+  min-height: 180px;
+  border: 1px solid var(--line-main);
+  border-radius: 6px;
+  overflow: hidden;
+  background: var(--bg-stage-inner);
+  vertical-align: top;
+  line-height: 0;
+  box-shadow: var(--shadow-stage);
+}
+
+#mainImage {
+  position: relative;
+  display: block;
+  width: auto;
+  height: auto;
+  max-width: none;
+  max-height: none;
+  object-fit: fill;
+  user-select: none;
+  pointer-events: none;
+}
+
+#mainImage:not([src]),
+#mainImage[src=""] {
+  display: none;
+}
+
+.no-image {
+  position: absolute;
+  inset: 0;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  color: var(--text-muted);
+  font-size: 12px;
+  pointer-events: none;
+}
+
+.roi {
+  position: absolute;
+  border-style: solid;
+  cursor: move;
+  user-select: none;
+  z-index: 3;
+}
+
+.roi .tag {
+  position: absolute;
+  left: 0;
+  top: -19px;
+  font-size: 10px;
+  padding: 2px 5px;
+  border-radius: 4px;
+  background: rgba(10, 12, 14, 0.86);
+  color: #f3f8ff;
+}
+
+html[data-theme="light"] .roi .tag {
+  background: rgba(24, 33, 49, 0.82);
+}
+
+.roi .resize-handle {
+  position: absolute;
+  width: 10px;
+  height: 10px;
+  right: -5px;
+  bottom: -5px;
+  background: #fff;
+  border: 1px solid currentColor;
+  border-radius: 2px;
+  cursor: nwse-resize;
+}
+
+.roi-front {
+  border-width: 2px;
+  border-color: #ff6b6b;
+  color: #ff6b6b;
+}
+
+.roi-back {
+  border-width: 2px;
+  border-color: #7fd67f;
+  color: #7fd67f;
+}
+
+.roi-test-front {
+  border-width: 2px;
+  border-color: #7fa7ff;
+  color: #7fa7ff;
+  border-style: dashed;
+  pointer-events: none;
+}
+
+.roi-test-back {
+  border-width: 2px;
+  border-color: #58c7c7;
+  color: #58c7c7;
+  border-style: dashed;
+  pointer-events: none;
+}
+
+.roi-values {
+  display: grid;
+  grid-template-columns: 1fr 1fr;
+  gap: 8px;
+  margin-top: 8px;
+  flex-shrink: 0;
+}
+
+
+.output-panel {
+  margin-top: 8px;
+  border: 1px solid var(--line-main);
+  border-radius: 8px;
+  background: var(--bg-subpanel);
+  display: flex;
+  flex-direction: column;
+  min-height: 200px;
+  max-height: 360px;
+  flex: 1 1 auto;
+  overflow: hidden;
+}
+
+.center-output-panel {
+  flex: 0 0 auto;
+  height: clamp(180px, 24vh, 300px);
+  min-height: 180px;
+  max-height: 320px;
+}
+
+.output-header {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  border-bottom: 1px solid var(--line-main);
+  padding: 8px 10px;
+}
+
+.output-log {
+  margin: 0;
+  padding: 8px 10px;
+  font-size: 12px;
+  line-height: 1.5;
+  white-space: pre-wrap;
+  word-break: break-word;
+  overflow: auto;
+  flex: 1;
+  color: var(--text-main);
+  background: var(--bg-output);
+}
+
+.dir-selectors {
+  display: flex;
+  align-items: center;
+  flex-wrap: wrap;
+  gap: 6px;
+  padding: 8px;
+  border: 1px solid var(--line-main);
+  border-radius: 6px;
+  background: var(--bg-subpanel);
+}
+
+.breadcrumb-root-prefix {
+  color: var(--text-muted);
+  font-weight: 700;
+  line-height: 1;
+  padding: 0 2px;
+}
+
+.breadcrumb-sep {
+  color: var(--text-muted);
+  font-weight: 600;
+}
+
+.breadcrumb-select {
+  min-width: 130px;
+  max-width: 230px;
+  height: 30px;
+  padding: 4px 8px;
+}
+
+.current-dir {
+  font-size: 12px;
+  color: var(--text-muted);
+  margin: 8px 0 6px;
+}
+
+.tip {
+  font-size: 12px;
+  color: #d6a75c;
+  background: var(--tip-bg);
+  border: 1px solid var(--tip-border);
+  padding: 6px;
+  border-radius: 6px;
+  margin-bottom: 6px;
+}
+
+.rule-editor-panel {
+  min-width: 0;
+  overflow: hidden;
+}
+
+.rule-editor-scroll {
+  display: flex;
+  flex: 1 1 auto;
+  flex-direction: column;
+  min-height: 0;
+  min-width: 0;
+  overflow: hidden;
+}
+
+.rule-list {
+  border: 1px solid var(--line-main);
+  border-radius: 8px;
+  background: var(--bg-subpanel);
+  min-height: 220px;
+  max-height: none;
+  flex: 2 1 0;
+  overflow-y: auto;
+  overflow-x: hidden;
+  padding: 6px;
+  display: flex;
+  flex-direction: column;
+  gap: 6px;
+}
+
+.rule-detail-scroll {
+  min-height: 0;
+  flex: 1 1 0;
+  overflow-y: auto;
+  overflow-x: hidden;
+  padding-right: 2px;
+}
+
+.rule-item {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+  border: 1px solid var(--line-input);
+  border-radius: 6px;
+  background: linear-gradient(180deg, var(--bg-panel-1), var(--bg-panel-2));
+  padding: 5px;
+  cursor: pointer;
+}
+
+.rule-item.active {
+  border-color: var(--accent);
+  box-shadow: inset 0 0 0 1px var(--accent);
+}
+
+.rule-thumb-wrap {
+  position: relative;
+  width: 44px;
+  height: 30px;
+  border-radius: 4px;
+  background: var(--bg-subpanel);
+  border: 1px solid var(--line-main);
+  flex-shrink: 0;
+  overflow: hidden;
+}
+
+.rule-thumb {
+  display: block;
+  width: 100%;
+  height: 100%;
+  object-fit: cover;
+}
+
+.rule-thumb:not([src]),
+.rule-thumb[src=""] {
+  display: none;
+}
+
+.rule-thumb-empty {
+  position: absolute;
+  inset: 0;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  font-size: 11px;
+  color: var(--text-muted);
+  pointer-events: none;
+}
+
+.rule-thumb-wrap.has-image .rule-thumb-empty {
+  display: none;
+}
+
+.rule-item-text {
+  flex: 1;
+  min-width: 0;
+  font-size: 12px;
+  color: var(--text-main);
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+
+.rule-editor-panel.rule-editor-compact .form-grid {
+  grid-template-columns: 1fr;
+}
+
+
+.form-grid {
+  display: grid;
+  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+  gap: 8px;
+  min-width: 0;
+}
+
+.form-grid label {
+  min-width: 0;
+}
+
+.form-grid input,
+.form-grid select,
+.form-grid textarea {
+  width: 100%;
+  min-width: 0;
+}
+
+.form-grid .full {
+  grid-column: 1 / -1;
+}
+
+.action-row {
+  align-items: center;
+}
+
+#saveRulesBtn.save-ok {
+  border-color: var(--ok-border);
+  color: var(--ok);
+  box-shadow: inset 0 0 0 1px var(--ok-border);
+}
+
+#saveRulesBtn.save-fail {
+  border-color: var(--fail-border);
+  color: var(--danger);
+  box-shadow: inset 0 0 0 1px var(--fail-border);
+}
+
+
+.stack.stack-icon-mode .panel-scroll-body,
+.stack.stack-icon-mode .image-list,
+.stack.stack-icon-mode .rule-detail-scroll {
+  min-height: 0;
+  overflow-y: auto;
+  overflow-x: hidden;
+}
+
+.layout-resizing {
+  cursor: col-resize !important;
+  user-select: none;
+}
+
+.layout-resizing * {
+  transition: none !important;
+}
+
+@media (max-width: 1800px) {
+  .center-panel {
+    min-width: 520px;
+  }
+}
+
+@media (max-width: 720px) {
+  .layout {
+    padding: 6px;
+    gap: 6px;
+  }
+
+  .topbar {
+    padding: 8px 10px;
+  }
+
+  .topbar h1 {
+    font-size: 13px;
+  }
+
+  .topbar-actions {
+    gap: 8px;
+  }
+
+  .theme-switch {
+    font-size: 11px;
+  }
+
+  .row {
+    gap: 6px;
+  }
+
+  .form-grid {
+    grid-template-columns: 1fr;
+  }
+
+  .form-grid .full {
+    grid-column: span 1;
+  }
+
+  .roi-values {
+    grid-template-columns: 1fr;
+  }
+}
+
+
+
+@keyframes btn-spin {
+  to {
+    transform: rotate(360deg);
+  }
+}
+
+
+
+
+
+
+
+
+
+
+
+.bottom-output-dock {
+  position: absolute;
+  left: calc(8px + var(--rail-width) + 6px);
+  right: calc(8px + var(--rail-width) + 6px);
+  bottom: 8px;
+  height: 220px;
+  z-index: 20;
+  display: flex;
+  flex-direction: column;
+  min-height: 0;
+  pointer-events: none;
+}
+
+.bottom-output-resize {
+  height: 10px;
+  cursor: row-resize;
+  pointer-events: auto;
+  position: relative;
+}
+
+.bottom-output-resize::before {
+  content: "";
+  position: absolute;
+  left: 16px;
+  right: 16px;
+  top: 3px;
+  height: 4px;
+  border-radius: 4px;
+  background: linear-gradient(90deg, transparent, var(--line-main), transparent);
+}
+
+.bottom-output-resize:hover::before {
+  background: linear-gradient(90deg, transparent, var(--accent), transparent);
+}
+
+.output-dock-panel {
+  margin-top: 0;
+  max-height: none;
+  flex: 1 1 auto;
+  min-height: 0;
+  pointer-events: auto;
+}
+
+.output-dock-panel .output-log {
+  min-height: 0;
+}
+.bottom-dock-resizing {
+  cursor: row-resize !important;
+  user-select: none;
+}
+

+ 298 - 0
module/server/web/annotator/static/css/center-panel.css

@@ -0,0 +1,298 @@
+.layout {
+  flex: 1;
+  min-height: 0;
+  display: flex;
+  gap: 0;
+  padding: 8px;
+  align-items: stretch;
+  overflow: hidden;
+}
+
+#leftWindowMount,
+#centerPanelMount,
+#rightWindowMount {
+  display: flex;
+  min-height: 0;
+}
+
+#leftWindowMount,
+#rightWindowMount {
+  flex: 0 0 auto;
+}
+
+#centerPanelMount {
+  flex: 1 1 auto;
+  min-width: 0;
+}
+
+#leftWindowMount > .tool-window,
+#rightWindowMount > .tool-window {
+  height: 100%;
+}
+
+#centerPanelMount > .center-panel {
+  height: 100%;
+}
+
+.tool-window {
+  min-height: 0;
+  height: 100%;
+  display: flex;
+  align-items: stretch;
+  flex: 0 0 auto;
+}
+
+.icon-rail,
+.tool-content {
+  height: 100%;
+}
+
+.center-panel {
+  flex: 1 1 auto;
+  min-width: 620px;
+  margin: 0 4px;
+  display: flex;
+  flex-direction: column;
+  min-height: 0;
+  overflow: hidden;
+}
+
+.app.dock-open #leftContent,
+.app.dock-open #rightContent,
+.app.dock-open .center-panel {
+  margin-bottom: calc(var(--bottom-dock-space) + var(--bottom-dock-gap));
+}
+
+.app.dock-open .center-panel {
+  overflow: hidden;
+}
+
+.stage-wrap {
+  flex: 1 1 auto;
+  min-height: 180px;
+  height: auto;
+  max-height: none;
+  display: block;
+  overflow: auto;
+  border: 1px solid var(--line-main);
+  border-radius: 8px;
+  background:
+    linear-gradient(90deg, var(--grid-line) 1px, transparent 1px) 0 0 / 24px 24px,
+    linear-gradient(var(--grid-line) 1px, transparent 1px) 0 0 / 24px 24px,
+    var(--bg-stage);
+  padding: 12px;
+}
+
+.stage-canvas-holder {
+  min-width: 100%;
+  width: max-content;
+  text-align: center;
+}
+
+.image-stage {
+  position: relative;
+  display: inline-block;
+  width: auto !important;
+  height: auto !important;
+  min-width: 320px;
+  min-height: 180px;
+  border: 1px solid var(--line-main);
+  border-radius: 6px;
+  overflow: hidden;
+  background: var(--bg-stage-inner);
+  vertical-align: top;
+  line-height: 0;
+  box-shadow: var(--shadow-stage);
+}
+
+#mainImage {
+  position: relative;
+  display: block;
+  width: auto;
+  height: auto;
+  max-width: none;
+  max-height: none;
+  object-fit: fill;
+  user-select: none;
+  pointer-events: none;
+}
+
+#mainImage:not([src]),
+#mainImage[src=""] {
+  display: none;
+}
+
+.no-image {
+  position: absolute;
+  inset: 0;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  color: var(--text-muted);
+  font-size: 12px;
+  pointer-events: none;
+}
+
+.roi {
+  position: absolute;
+  border-style: solid;
+  cursor: move;
+  user-select: none;
+  z-index: 3;
+}
+
+.roi .tag {
+  position: absolute;
+  left: 0;
+  top: -19px;
+  font-size: 10px;
+  padding: 2px 5px;
+  border-radius: 4px;
+  background: rgba(10, 12, 14, 0.86);
+  color: #f3f8ff;
+}
+
+html[data-theme="light"] .roi .tag {
+  background: rgba(24, 33, 49, 0.82);
+}
+
+.roi .resize-handle {
+  position: absolute;
+  width: 10px;
+  height: 10px;
+  background: #fff;
+  border: 1px solid currentColor;
+  border-radius: 2px;
+  z-index: 1;
+}
+
+.roi .resize-handle-nw {
+  left: -5px;
+  top: -5px;
+  cursor: nwse-resize;
+}
+
+.roi .resize-handle-ne {
+  right: -5px;
+  top: -5px;
+  cursor: nesw-resize;
+}
+
+.roi .resize-handle-sw {
+  left: -5px;
+  bottom: -5px;
+  cursor: nesw-resize;
+}
+
+.roi .resize-handle-se {
+  right: -5px;
+  bottom: -5px;
+  cursor: nwse-resize;
+}
+
+.roi-front {
+  border-width: 2px;
+  border-color: #ff6b6b;
+  color: #ff6b6b;
+}
+
+.roi-back {
+  border-width: 2px;
+  border-color: #7fd67f;
+  color: #7fd67f;
+}
+
+.roi-test-front {
+  border-width: 2px;
+  border-color: #7fa7ff;
+  color: #7fa7ff;
+  border-style: dashed;
+  pointer-events: none;
+}
+
+.roi-test-back {
+  border-width: 2px;
+  border-color: #58c7c7;
+  color: #58c7c7;
+  border-style: dashed;
+  pointer-events: none;
+}
+
+.roi-values {
+  display: grid;
+  grid-template-columns: 1fr 1fr;
+  gap: 8px;
+  margin-top: 8px;
+  flex-shrink: 0;
+}
+
+.output-panel {
+  margin-top: 8px;
+  border: 1px solid var(--line-main);
+  border-radius: 8px;
+  background: var(--bg-subpanel);
+  display: flex;
+  flex-direction: column;
+  min-height: 120px;
+  max-height: 240px;
+  flex: 0 0 auto;
+  overflow: hidden;
+}
+
+.center-output-panel {
+  flex: 0 0 auto;
+  height: clamp(130px, 18vh, 220px);
+  min-height: 120px;
+  max-height: 240px;
+}
+
+.output-header {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  border-bottom: 1px solid var(--line-main);
+  padding: 8px 10px;
+}
+
+.output-log {
+  margin: 0;
+  padding: 8px 10px;
+  font-size: 12px;
+  line-height: 1.5;
+  white-space: pre-wrap;
+  word-break: break-word;
+  overflow: auto;
+  flex: 1;
+  color: var(--text-main);
+  background: var(--bg-output);
+}
+
+@media (max-width: 1800px) {
+  .center-panel {
+    min-width: 520px;
+  }
+}
+
+@media (max-height: 900px) {
+  .stage-wrap {
+    min-height: 150px;
+  }
+
+  .center-output-panel {
+    height: clamp(110px, 16vh, 180px);
+    min-height: 110px;
+    max-height: 180px;
+  }
+}
+
+@media (max-width: 720px) {
+  .layout {
+    padding: 6px;
+    gap: 6px;
+  }
+
+  .roi-values {
+    grid-template-columns: 1fr;
+  }
+}
+

+ 97 - 0
module/server/web/annotator/static/css/left-window.css

@@ -0,0 +1,97 @@
+.icon-rail-left {
+  border-radius: 8px 0 0 8px;
+  border-right: 0;
+}
+
+.tool-content-left {
+  border-left: 0;
+  border-radius: 0 8px 8px 0;
+}
+
+#sessionImagesPanel .row {
+  flex-shrink: 0;
+}
+
+.selected-info {
+  font-size: 12px;
+  color: var(--text-muted);
+  margin-bottom: 6px;
+  flex-shrink: 0;
+}
+
+.image-list {
+  display: flex;
+  flex-direction: column;
+  gap: 6px;
+  border: 1px solid var(--line-main);
+  border-radius: 8px;
+  padding: 6px;
+  background: var(--bg-subpanel);
+  overflow: auto;
+  min-height: 0;
+  flex: 1;
+}
+
+.image-item {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+  border: 1px solid var(--line-input);
+  border-radius: 6px;
+  padding: 5px;
+  background: linear-gradient(180deg, var(--bg-panel-1), var(--bg-panel-2));
+  cursor: pointer;
+  min-width: 0;
+}
+
+.image-item.active {
+  border-color: var(--accent);
+  box-shadow: inset 0 0 0 1px var(--accent);
+}
+
+.image-item.selected {
+  background: var(--selected-bg);
+}
+
+.image-item .selector {
+  display: flex;
+  align-items: center;
+}
+
+.image-item img {
+  width: 52px;
+  height: 36px;
+  object-fit: cover;
+  border-radius: 4px;
+  background: var(--bg-subpanel);
+  border: 1px solid var(--line-main);
+  flex-shrink: 0;
+}
+
+.image-item .image-name {
+  flex: 1;
+  min-width: 0;
+  font-size: 12px;
+  color: var(--text-main);
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+
+.preview-card {
+  border: 1px solid var(--line-main);
+  border-radius: 6px;
+  min-height: 140px;
+  background: var(--bg-subpanel);
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  overflow: auto;
+}
+
+#emulatorPreview {
+  width: 100%;
+  height: auto;
+  max-height: 190px;
+  object-fit: contain;
+}

+ 266 - 0
module/server/web/annotator/static/css/right-window.css

@@ -0,0 +1,266 @@
+.icon-rail-right {
+  border-radius: 0 8px 8px 0;
+  border-left: 0;
+}
+
+.tool-content-right {
+  border-right: 0;
+  border-radius: 8px 0 0 8px;
+}
+
+.dir-selectors {
+  display: flex;
+  align-items: center;
+  flex-wrap: wrap;
+  gap: 6px;
+  padding: 8px;
+  border: 1px solid var(--line-main);
+  border-radius: 6px;
+  background: var(--bg-subpanel);
+}
+
+.breadcrumb-root-prefix {
+  color: var(--text-muted);
+  font-weight: 700;
+  line-height: 1;
+  padding: 0 2px;
+}
+
+.breadcrumb-sep {
+  color: var(--text-muted);
+  font-weight: 600;
+}
+
+.breadcrumb-select {
+  min-width: 130px;
+  max-width: 230px;
+  height: 30px;
+  padding: 4px 8px;
+}
+
+.rule-editor-panel {
+  min-width: 0;
+  overflow: hidden;
+}
+
+.rule-editor-scroll {
+  display: flex;
+  flex: 1 1 0;
+  flex-direction: column;
+  min-height: 0;
+  min-width: 0;
+  overflow-y: auto;
+  overflow-x: hidden;
+  padding-right: 2px;
+}
+
+.rule-search-box {
+  margin: 8px 0 6px;
+}
+
+.rule-search-box input {
+  width: 100%;
+}
+
+.rule-list {
+  border: 1px solid var(--line-main);
+  border-radius: 8px;
+  background: var(--bg-subpanel);
+  min-height: 220px;
+  height: 220px;
+  max-height: none;
+  flex: 0 0 auto;
+  overflow-y: auto;
+  overflow-x: hidden;
+  padding: 6px;
+  display: flex;
+  flex-direction: column;
+  gap: 6px;
+}
+
+.rule-list-splitter {
+  flex: 0 0 10px;
+  height: 10px;
+  position: relative;
+  cursor: row-resize;
+}
+
+.rule-list-splitter::before {
+  content: "";
+  position: absolute;
+  left: 12px;
+  right: 12px;
+  top: 3px;
+  height: 4px;
+  border-radius: 4px;
+  background: linear-gradient(90deg, transparent, var(--line-main), transparent);
+  opacity: 0.75;
+}
+
+.rule-list-splitter:hover::before {
+  background: linear-gradient(90deg, transparent, var(--accent), transparent);
+}
+
+.rule-detail-scroll {
+  min-height: 0;
+  flex: 0 0 auto;
+  overflow: visible;
+  padding-right: 0;
+}
+
+.rule-list-resizing {
+  cursor: row-resize !important;
+  user-select: none;
+}
+
+.rule-list-resizing * {
+  transition: none !important;
+}
+
+.rule-item {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+  border: 1px solid var(--line-input);
+  border-radius: 6px;
+  background: linear-gradient(180deg, var(--bg-panel-1), var(--bg-panel-2));
+  padding: 5px;
+  cursor: pointer;
+}
+
+.rule-item.active {
+  border-color: var(--accent);
+  box-shadow: inset 0 0 0 1px var(--accent);
+}
+
+.rule-thumb-wrap {
+  position: relative;
+  width: 44px;
+  height: 30px;
+  border-radius: 4px;
+  background: var(--bg-subpanel);
+  border: 1px solid var(--line-main);
+  flex-shrink: 0;
+  overflow: hidden;
+}
+
+.rule-thumb {
+  display: block;
+  width: 100%;
+  height: 100%;
+  object-fit: cover;
+}
+
+.rule-thumb:not([src]),
+.rule-thumb[src=""] {
+  display: none;
+}
+
+.rule-thumb-empty {
+  position: absolute;
+  inset: 0;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  font-size: 11px;
+  color: var(--text-muted);
+  pointer-events: none;
+}
+
+.rule-thumb-wrap.has-image .rule-thumb-empty {
+  display: none;
+}
+
+.rule-item-text {
+  flex: 1;
+  min-width: 0;
+  font-size: 12px;
+  color: var(--text-main);
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+
+.rule-list-empty {
+  min-height: 88px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  padding: 12px;
+  border: 1px dashed var(--line-input);
+  border-radius: 6px;
+  color: var(--text-muted);
+  font-size: 12px;
+  text-align: center;
+  background: rgba(255, 255, 255, 0.02);
+}
+
+.rule-editor-panel.rule-editor-compact .form-grid {
+  grid-template-columns: 1fr;
+}
+
+
+.form-grid {
+  display: grid;
+  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+  gap: 8px;
+  min-width: 0;
+}
+
+.form-grid label {
+  min-width: 0;
+}
+
+.form-grid input,
+.form-grid select,
+.form-grid textarea {
+  width: 100%;
+  min-width: 0;
+}
+
+.form-grid .full {
+  grid-column: 1 / -1;
+}
+
+.action-row {
+  align-items: center;
+}
+
+#saveRulesBtn.save-ok {
+  border-color: var(--ok-border);
+  color: var(--ok);
+  box-shadow: inset 0 0 0 1px var(--ok-border);
+}
+
+#saveRulesBtn.save-fail {
+  border-color: var(--fail-border);
+  color: var(--danger);
+  box-shadow: inset 0 0 0 1px var(--fail-border);
+}
+
+
+.current-dir {
+  font-size: 12px;
+  color: var(--text-muted);
+  margin: 8px 0 6px;
+}
+
+.tip {
+  font-size: 12px;
+  color: #d6a75c;
+  background: var(--tip-bg);
+  border: 1px solid var(--tip-border);
+  padding: 6px;
+  border-radius: 6px;
+  margin-bottom: 6px;
+}
+
+@media (max-width: 720px) {
+  .form-grid {
+    grid-template-columns: 1fr;
+  }
+
+  .form-grid .full {
+    grid-column: span 1;
+  }
+}

+ 60 - 0
module/server/web/annotator/static/css/topbar.css

@@ -0,0 +1,60 @@
+.topbar {
+  height: 44px;
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  padding: 8px 14px;
+  border-bottom: 1px solid var(--line-main);
+  background: linear-gradient(180deg, var(--bg-topbar-1) 0%, var(--bg-topbar-2) 100%);
+}
+
+.topbar h1 {
+  margin: 0;
+  font-size: 14px;
+  font-weight: 600;
+  letter-spacing: 0.03em;
+  color: var(--text-title);
+}
+
+.topbar-actions {
+  display: flex;
+  align-items: center;
+  gap: 12px;
+}
+
+.theme-switch {
+  display: flex;
+  align-items: center;
+  gap: 6px;
+  margin: 0;
+  font-size: 12px;
+  color: var(--text-muted);
+}
+
+.theme-switch select {
+  height: 28px;
+  min-width: 90px;
+}
+
+.session-meta {
+  font-size: 12px;
+  color: var(--text-muted);
+}
+
+@media (max-width: 720px) {
+  .topbar {
+    padding: 8px 10px;
+  }
+
+  .topbar h1 {
+    font-size: 13px;
+  }
+
+  .topbar-actions {
+    gap: 8px;
+  }
+
+  .theme-switch {
+    font-size: 11px;
+  }
+}

+ 2855 - 0
module/server/web/annotator/static/js/app.js

@@ -0,0 +1,2855 @@
+(function () {
+  const API_PREFIX = "/tool/annotator";
+  const AllowedRuleTypes = new Set();
+
+  const state = {
+    sessionId: "",
+    sourceMode: "local",
+
+    images: [],
+    imageMap: new Map(),
+    imageElementMap: new Map(),
+    currentImageId: "",
+    selectedImageIds: new Set(),
+    roiViewport: {
+      left: 0,
+      top: 0,
+      width: 1,
+      height: 1,
+      naturalWidth: 1280,
+      naturalHeight: 720,
+    },
+
+    sourceDirs: [],
+    sourceLeafHasDirs: false,
+    sourceLeafJsonFiles: [],
+    currentDirPath: "",
+    jsonFileName: "",
+    taskName: "",
+    jsonRelPath: "",
+
+    ruleType: "image",
+    ruleTypeLocked: false,
+    ruleSchemas: [],
+    ruleSchemaMap: new Map(),
+    rules: [],
+    activeRuleIndex: -1,
+    ruleSearchKeyword: "",
+    listMeta: {
+      name: "list_name",
+      direction: "vertical",
+      type: "image",
+      roiBack: "0,0,100,100",
+      description: "",
+    },
+
+    dirty: false,
+
+    testOverlayActive: false,
+    testRoiFront: "",
+    testRoiBack: "",
+
+    imagePreviewCache: new Map(),
+    activeRuleImageExists: false,
+    imageCheckToken: 0,
+
+    ws: null,
+    wsImageUrl: "",
+    wsCloseExpected: false,
+    emulatorStatus: { state: "stopped" },
+    statusTimer: null,
+    sessionRecovering: false,
+    sessionClosing: false,
+  };
+
+  const el = {
+    sessionId: document.getElementById("sessionId"),
+    message: document.getElementById("globalMessage"),
+
+    sourceMode: document.getElementById("sourceMode"),
+    localControls: document.getElementById("localControls"),
+    emulatorControls: document.getElementById("emulatorControls"),
+
+    imageUpload: document.getElementById("imageUpload"),
+    uploadBtn: document.getElementById("uploadBtn"),
+    refreshImagesBtn: document.getElementById("refreshImagesBtn"),
+    removeImagesBtn: document.getElementById("removeImagesBtn"),
+    clearImagesBtn: document.getElementById("clearImagesBtn"),
+    imageList: document.getElementById("imageList"),
+    selectedImageCount: document.getElementById("selectedImageCount"),
+
+    configName: document.getElementById("configName"),
+    frameRate: document.getElementById("frameRate"),
+    startEmulatorBtn: document.getElementById("startEmulatorBtn"),
+    stopEmulatorBtn: document.getElementById("stopEmulatorBtn"),
+    captureBtn: document.getElementById("captureBtn"),
+    emulatorPreview: document.getElementById("emulatorPreview"),
+    emulatorStatus: document.getElementById("emulatorStatus"),
+
+    stageWrap: document.getElementById("stageWrap"),
+    imageStage: document.getElementById("imageStage"),
+    mainImage: document.getElementById("mainImage"),
+    noImagePlaceholder: document.getElementById("noImagePlaceholder"),
+    roiFront: document.getElementById("roiFront"),
+    roiBack: document.getElementById("roiBack"),
+    roiFrontValue: document.getElementById("roiFrontValue"),
+    roiBackValue: document.getElementById("roiBackValue"),
+    testRoiFront: document.getElementById("testRoiFront"),
+    testRoiBack: document.getElementById("testRoiBack"),
+    outputLog: document.getElementById("outputLog"),
+    clearOutputBtn: document.getElementById("clearOutputBtn"),
+
+    dirSelectors: document.getElementById("dirSelectors"),
+    currentDir: document.getElementById("currentDir"),
+    newJsonName: document.getElementById("newJsonName"),
+    createJsonBtn: document.getElementById("createJsonBtn"),
+    deleteJsonBtn: document.getElementById("deleteJsonBtn"),
+
+    ruleType: document.getElementById("ruleType"),
+    ruleTypeLockTip: document.getElementById("ruleTypeLockTip"),
+
+    listMetaBox: document.getElementById("listMetaBox"),
+    listMetaFields: document.getElementById("listMetaFields"),
+    listName: null,
+    listDirection: null,
+    listType: null,
+    listDescription: null,
+
+    ruleSearchBox: document.getElementById("ruleSearchBox"),
+    ruleSearchInput: document.getElementById("ruleSearchInput"),
+    ruleList: document.getElementById("ruleList"),
+    addRuleBtn: document.getElementById("addRuleBtn"),
+    deleteRuleBtn: document.getElementById("deleteRuleBtn"),
+    refreshRulesBtn: document.getElementById("refreshRulesBtn"),
+
+    ruleFields: document.getElementById("ruleFields"),
+    itemName: null,
+    imageNameWrap: null,
+    imageName: null,
+    methodWrap: null,
+    method: null,
+    thresholdWrap: null,
+    threshold: null,
+    modeWrap: null,
+    mode: null,
+    keywordWrap: null,
+    keyword: null,
+    durationWrap: null,
+    duration: null,
+    descriptionWrap: null,
+    description: null,
+
+    testRuleBtn: document.getElementById("testRuleBtn"),
+    saveImageBtn: document.getElementById("saveImageBtn"),
+    saveRulesBtn: document.getElementById("saveRulesBtn"),
+  };
+
+  function getRuleSchema(type = state.ruleType) {
+    return state.ruleSchemaMap.get(type) || null;
+  }
+
+  function getRuleFields(type = state.ruleType) {
+    const schema = getRuleSchema(type);
+    return schema && Array.isArray(schema.fields) ? schema.fields : [];
+  }
+
+  function getListMetaFields() {
+    const schema = getRuleSchema("list");
+    return schema && Array.isArray(schema.meta_fields) ? schema.meta_fields : [];
+  }
+
+  function getFieldDefault(type, key, fallback = "") {
+    const fields = type === "list"
+      ? [...getRuleFields(type), ...getListMetaFields()]
+      : getRuleFields(type);
+    const field = fields.find((item) => item.key === key);
+    if (!field) {
+      return fallback;
+    }
+    return field.default ?? fallback;
+  }
+
+  function getListMetaDefaults() {
+    const defaults = {
+      name: "list_name",
+      direction: "vertical",
+      type: "image",
+      roiBack: "0,0,100,100",
+      description: "",
+    };
+    for (const field of getListMetaFields()) {
+      defaults[field.key] = field.default ?? defaults[field.key] ?? "";
+    }
+    return defaults;
+  }
+
+  function getRuleFieldDomId(key) {
+    return key;
+  }
+
+  function getRuleFieldWrapId(key) {
+    return `${key}Wrap`;
+  }
+
+  function getListMetaFieldDomId(key) {
+    if (key === "name") {
+      return "listName";
+    }
+    if (key === "direction") {
+      return "listDirection";
+    }
+    if (key === "type") {
+      return "listType";
+    }
+    if (key === "description") {
+      return "listDescription";
+    }
+    return `list${key}`;
+  }
+
+  function createFieldControl(field, domId, wrapId = "") {
+    const label = document.createElement("label");
+    if (wrapId) {
+      label.id = wrapId;
+    }
+    if (field.full) {
+      label.classList.add("full");
+    }
+    label.append(document.createTextNode(field.label));
+
+    let control = null;
+    if (field.control === "textarea") {
+      control = document.createElement("textarea");
+    } else if (field.control === "select") {
+      control = document.createElement("select");
+      for (const optionValue of field.options || []) {
+        createOption(control, optionValue, optionValue);
+      }
+    } else {
+      control = document.createElement("input");
+      control.type = field.control === "number" ? "number" : "text";
+    }
+
+    control.id = domId;
+    if (field.step !== undefined && "step" in control) {
+      control.step = String(field.step);
+    }
+    if (field.min !== undefined && "min" in control) {
+      control.min = String(field.min);
+    }
+    if (field.max !== undefined && "max" in control) {
+      control.max = String(field.max);
+    }
+    label.appendChild(control);
+    return label;
+  }
+
+  function renderFieldGroup(container, fields, domIdResolver, wrapIdResolver = null) {
+    if (!container) {
+      return;
+    }
+    container.innerHTML = "";
+    for (const field of fields) {
+      const domId = domIdResolver(field.key);
+      const wrapId = wrapIdResolver ? wrapIdResolver(field.key) : "";
+      container.appendChild(createFieldControl(field, domId, wrapId));
+    }
+  }
+
+  function refreshDynamicFieldRefs() {
+    el.itemName = document.getElementById("itemName");
+    el.imageNameWrap = document.getElementById("imageNameWrap");
+    el.imageName = document.getElementById("imageName");
+    el.methodWrap = document.getElementById("methodWrap");
+    el.method = document.getElementById("method");
+    el.thresholdWrap = document.getElementById("thresholdWrap");
+    el.threshold = document.getElementById("threshold");
+    el.modeWrap = document.getElementById("modeWrap");
+    el.mode = document.getElementById("mode");
+    el.keywordWrap = document.getElementById("keywordWrap");
+    el.keyword = document.getElementById("keyword");
+    el.durationWrap = document.getElementById("durationWrap");
+    el.duration = document.getElementById("duration");
+    el.descriptionWrap = document.getElementById("descriptionWrap");
+    el.description = document.getElementById("description");
+
+    el.listName = document.getElementById("listName");
+    el.listDirection = document.getElementById("listDirection");
+    el.listType = document.getElementById("listType");
+    el.listDescription = document.getElementById("listDescription");
+  }
+
+  function bindRuleFieldChange(element, fieldKey) {
+    if (!element) {
+      return;
+    }
+    const eventName = element.tagName === "SELECT" ? "change" : "input";
+    element.addEventListener(eventName, () => updateRuleFromForm(fieldKey));
+  }
+
+  function bindDynamicFieldEvents() {
+    bindRuleFieldChange(el.itemName, "itemName");
+    bindRuleFieldChange(el.imageName, "imageName");
+    bindRuleFieldChange(el.method, "method");
+    bindRuleFieldChange(el.threshold, "threshold");
+    bindRuleFieldChange(el.mode, "mode");
+    bindRuleFieldChange(el.keyword, "keyword");
+    bindRuleFieldChange(el.duration, "duration");
+    bindRuleFieldChange(el.description, "description");
+
+    if (el.listName) {
+      el.listName.addEventListener("input", () => {
+        updateListMetaFromForm();
+        markDirty();
+      });
+    }
+    if (el.listDirection) {
+      el.listDirection.addEventListener("change", () => {
+        updateListMetaFromForm();
+        markDirty();
+        updateFieldVisibility();
+      });
+    }
+    if (el.listType) {
+      el.listType.addEventListener("change", () => {
+        updateListMetaFromForm();
+        clearTestOverlay();
+        renderRuleList();
+        markDirty();
+        updateFieldVisibility();
+      });
+    }
+    if (el.listDescription) {
+      el.listDescription.addEventListener("input", () => {
+        updateListMetaFromForm();
+        markDirty();
+      });
+    }
+  }
+
+  function renderDynamicFieldGroups() {
+    renderFieldGroup(el.ruleFields, getRuleFields(), getRuleFieldDomId, getRuleFieldWrapId);
+    renderFieldGroup(el.listMetaFields, getListMetaFields(), getListMetaFieldDomId);
+    refreshDynamicFieldRefs();
+    bindDynamicFieldEvents();
+  }
+
+  function populateRuleTypeOptions() {
+    el.ruleType.innerHTML = "";
+    for (const schema of state.ruleSchemas) {
+      createOption(el.ruleType, schema.type, schema.label || schema.type);
+    }
+  }
+
+  async function loadRuleSchemas() {
+    const res = await api(`${API_PREFIX}/api/rules/schema`);
+    const schemas = res.schemas || {};
+    const ruleTypes = Array.isArray(res.rule_types) ? res.rule_types : Object.keys(schemas);
+    state.ruleSchemas = ruleTypes.map((type) => schemas[type]).filter(Boolean);
+    state.ruleSchemaMap = new Map(state.ruleSchemas.map((schema) => [schema.type, schema]));
+    AllowedRuleTypes.clear();
+    for (const schema of state.ruleSchemas) {
+      AllowedRuleTypes.add(schema.type);
+    }
+    populateRuleTypeOptions();
+    if (!AllowedRuleTypes.has(state.ruleType)) {
+      state.ruleType = state.ruleSchemas[0] ? state.ruleSchemas[0].type : "image";
+    }
+    renderDynamicFieldGroups();
+  }
+
+  function setElementValue(element, value) {
+    if (!element) {
+      return;
+    }
+    element.value = value ?? "";
+  }
+
+  function readFieldValue(field, element) {
+    if (!element) {
+      return field.default ?? "";
+    }
+    if (field.control === "number") {
+      const raw = String(element.value || "").trim();
+      if (field.integer) {
+        const parsed = Number.parseInt(raw, 10);
+        return Number.isFinite(parsed) ? parsed : (field.default ?? 0);
+      }
+      const parsed = Number.parseFloat(raw);
+      return Number.isFinite(parsed) ? parsed : (field.default ?? 0);
+    }
+    const value = String(element.value || "").trim();
+    if (!value && field.default !== undefined) {
+      return field.default;
+    }
+    return value;
+  }
+
+  function showMessage(text, type = "") {
+    const message = String(text || "").trim();
+    if (!message) {
+      if (el.message) {
+        el.message.textContent = "";
+        el.message.classList.remove("error", "ok");
+      }
+      return;
+    }
+
+    if (el.message) {
+      el.message.textContent = message;
+      el.message.classList.remove("error", "ok");
+      if (type) {
+        el.message.classList.add(type);
+      }
+      return;
+    }
+
+    return;
+  }
+
+  function formatTime() {
+    const now = new Date();
+    return now.toLocaleTimeString("zh-CN", { hour12: false });
+  }
+
+  function appendOutput(title, payload) {
+    const lines = [];
+    lines.push(`[${formatTime()}] ${title}`);
+    if (payload !== undefined) {
+      if (typeof payload === "string") {
+        lines.push(payload);
+      } else {
+        lines.push(JSON.stringify(payload, null, 2));
+      }
+    }
+    const entry = `${lines.join("\n")}\n\n`;
+    el.outputLog.textContent = `${entry}${el.outputLog.textContent || ""}`;
+  }
+
+  function clearOutput() {
+    el.outputLog.textContent = "";
+  }
+
+  function clearSaveStatus() {
+    el.saveRulesBtn.classList.remove("save-ok", "save-fail");
+  }
+
+  function setSaveStatus(ok) {
+    el.saveRulesBtn.classList.remove("save-ok", "save-fail");
+    if (ok) {
+      el.saveRulesBtn.classList.add("save-ok");
+    } else {
+      el.saveRulesBtn.classList.add("save-fail");
+    }
+  }
+
+  function setUploadButtonLoading(loading) {
+    if (!el.uploadBtn) {
+      return;
+    }
+    el.uploadBtn.disabled = Boolean(loading);
+    el.uploadBtn.classList.toggle("btn-loading", Boolean(loading));
+    el.uploadBtn.textContent = loading ? "上传中..." : "上传";
+  }
+
+  function isInvalidSessionError(error) {
+    return Boolean(error && error.code === "invalid_session");
+  }
+
+  async function recoverSessionAfterInvalid() {
+    if (state.sessionRecovering) {
+      return true;
+    }
+
+    state.sessionRecovering = true;
+    try {
+      closeFrameSocket();
+      state.images = [];
+      state.currentImageId = "";
+      state.selectedImageIds.clear();
+      state.imageMap = new Map();
+      state.imageElementMap = new Map();
+      renderImageList();
+      clearTestOverlay();
+      setMainImage("");
+      updateTestButtonVisibility();
+      updateEmulatorStatusView({ state: "stopped", message: "session_invalid" });
+      showMessage("会话已失效,正在重建会话...", "error");
+
+      await createSession();
+      await refreshImages();
+      if (state.sourceMode === "emulator") {
+        await refreshEmulatorStatus();
+      }
+
+      showMessage("会话已重新创建,请重试刚才的操作", "ok");
+      return true;
+    } catch (recoverError) {
+      console.error(recoverError);
+      showMessage("会话失效且自动重建失败,请刷新页面后重试", "error");
+      return false;
+    } finally {
+      state.sessionRecovering = false;
+    }
+  }
+
+  function withError(fn) {
+    return async (...args) => {
+      try {
+        await fn(...args);
+      } catch (error) {
+        console.error(error);
+        if (isInvalidSessionError(error)) {
+          const recovered = await recoverSessionAfterInvalid();
+          if (recovered) {
+            return;
+          }
+        }
+        showMessage(error.message || String(error), "error");
+      }
+    };
+  }
+
+  async function api(path, options = {}) {
+    const request = { ...options };
+    request.headers = { ...(options.headers || {}) };
+
+    if (request.body !== undefined && !(request.body instanceof FormData) && !request.headers["Content-Type"]) {
+      request.headers["Content-Type"] = "application/json";
+    }
+
+    const response = await fetch(path, request);
+    const contentType = response.headers.get("content-type") || "";
+    const rawText = await response.text();
+    let payload = rawText;
+
+    if (contentType.includes("application/json")) {
+      payload = rawText ? JSON.parse(rawText) : {};
+    }
+
+    if (!response.ok) {
+      let message = "请求失败";
+      let code = "";
+      if (payload && payload.detail) {
+        if (typeof payload.detail === "string") {
+          message = payload.detail;
+        } else {
+          code = String(payload.detail.code || "");
+          message = payload.detail.message || payload.detail.code || JSON.stringify(payload.detail);
+        }
+      }
+      const error = new Error(message);
+      error.code = code;
+      error.status = response.status;
+      throw error;
+    }
+
+    return payload;
+  }
+
+  async function closeSession(reason = "client_close", useUnloadTransport = false) {
+    if (!state.sessionId || state.sessionClosing) {
+      return;
+    }
+
+    const sessionId = encodeURIComponent(state.sessionId);
+    const reasonQuery = `reason=${encodeURIComponent(reason)}`;
+    const closeUrl = `${API_PREFIX}/api/session/${sessionId}?${reasonQuery}`;
+
+    if (useUnloadTransport) {
+      state.sessionClosing = true;
+      const beaconUrl = `${API_PREFIX}/api/session/${sessionId}/close?${reasonQuery}`;
+      if (navigator.sendBeacon) {
+        navigator.sendBeacon(beaconUrl, "");
+        return;
+      }
+      fetch(closeUrl, {
+        method: "DELETE",
+        keepalive: true,
+      }).catch(() => {
+        // 页面卸载场景忽略错误
+      });
+      return;
+    }
+
+    state.sessionClosing = true;
+    try {
+      await api(closeUrl, { method: "DELETE" });
+    } finally {
+      state.sessionClosing = false;
+    }
+  }
+
+  function createOption(select, value, label) {
+    const option = document.createElement("option");
+    option.value = value;
+    option.textContent = label;
+    select.appendChild(option);
+  }
+
+  function fillSelect(select, values, placeholder) {
+    select.innerHTML = "";
+    createOption(select, "", placeholder);
+    for (const value of values) {
+      createOption(select, value, value);
+    }
+  }
+
+  function splitPath(pathText) {
+    return String(pathText || "")
+      .split("/")
+      .map((x) => x.trim())
+      .filter(Boolean);
+  }
+
+  function joinPath(parts) {
+    return parts.filter(Boolean).join("/");
+  }
+
+  function sanitizeImageNameBase(text) {
+    const value = String(text || "").trim();
+    const safe = value.replace(/[^\w\-\u4e00-\u9fa5]/g, "_");
+    return safe || "image";
+  }
+
+  function getRuleImageNamePrefix() {
+    const parts = splitPath(state.currentDirPath);
+    if (parts.length > 0) {
+      return sanitizeImageNameBase(parts[parts.length - 1]);
+    }
+    if (state.taskName) {
+      return sanitizeImageNameBase(state.taskName);
+    }
+    return "image";
+  }
+
+  function defaultImageNameForItem(itemName) {
+    const prefix = getRuleImageNamePrefix();
+    return `${prefix}_${sanitizeImageNameBase(itemName)}.png`;
+  }
+
+  function listImageNameForItem(itemName) {
+    const value = String(itemName || "").trim();
+    return value ? `${value}.png` : "";
+  }
+
+  function getRuleSubtype() {
+    if (state.ruleType === "list") {
+      return state.listMeta.type || "image";
+    }
+    return state.ruleType;
+  }
+
+  function isListImageRule() {
+    return state.ruleType === "list" && getRuleSubtype() === "image";
+  }
+
+  function isListOcrRule() {
+    return state.ruleType === "list" && getRuleSubtype() === "ocr";
+  }
+
+  function isImagePreviewRule() {
+    return state.ruleType === "image" || isListImageRule();
+  }
+
+  function parseRoi(text) {
+    const parts = String(text || "")
+      .split(",")
+      .map((item) => Number.parseFloat(item.trim()));
+    if (parts.length !== 4 || parts.some((x) => Number.isNaN(x))) {
+      return [0, 0, 100, 100];
+    }
+    const [x, y, w, h] = parts;
+    return [x, y, Math.max(1, w), Math.max(1, h)];
+  }
+
+  function parseRoiStrict(text) {
+    const parts = String(text || "")
+      .split(",")
+      .map((item) => Number.parseFloat(item.trim()));
+    if (parts.length !== 4 || parts.some((x) => !Number.isFinite(x))) {
+      return null;
+    }
+    const [x, y, w, h] = parts;
+    return formatRoiFromNumbers(x, y, w, h);
+  }
+
+  function getStageSize() {
+    return {
+      width: Math.max(1, el.imageStage.clientWidth || 1),
+      height: Math.max(1, el.imageStage.clientHeight || 1),
+    };
+  }
+
+  function computeRoiViewport() {
+    const stage = getStageSize();
+    const naturalWidth = Math.max(1, el.mainImage.naturalWidth || state.roiViewport.naturalWidth || 1280);
+    const naturalHeight = Math.max(1, el.mainImage.naturalHeight || state.roiViewport.naturalHeight || 720);
+
+    const scale = Math.min(stage.width / naturalWidth, stage.height / naturalHeight);
+    const width = Math.max(1, naturalWidth * scale);
+    const height = Math.max(1, naturalHeight * scale);
+
+    return {
+      left: (stage.width - width) / 2,
+      top: (stage.height - height) / 2,
+      width,
+      height,
+      naturalWidth,
+      naturalHeight,
+    };
+  }
+
+  function updateRoiViewport() {
+    state.roiViewport = computeRoiViewport();
+    return state.roiViewport;
+  }
+
+  function getRoiViewport() {
+    return updateRoiViewport();
+  }
+
+  function naturalToStageX(value, viewport) {
+    return viewport.left + (value * viewport.width) / viewport.naturalWidth;
+  }
+
+  function naturalToStageY(value, viewport) {
+    return viewport.top + (value * viewport.height) / viewport.naturalHeight;
+  }
+
+  function naturalToStageW(value, viewport) {
+    return (value * viewport.width) / viewport.naturalWidth;
+  }
+
+  function naturalToStageH(value, viewport) {
+    return (value * viewport.height) / viewport.naturalHeight;
+  }
+
+  function stageToNaturalX(value, viewport) {
+    return ((value - viewport.left) * viewport.naturalWidth) / viewport.width;
+  }
+
+  function stageToNaturalY(value, viewport) {
+    return ((value - viewport.top) * viewport.naturalHeight) / viewport.height;
+  }
+
+  function stageToNaturalW(value, viewport) {
+    return (value * viewport.naturalWidth) / viewport.width;
+  }
+
+  function stageToNaturalH(value, viewport) {
+    return (value * viewport.naturalHeight) / viewport.height;
+  }
+
+  function formatRoiFromNumbers(x, y, w, h) {
+    return `${Math.round(x)},${Math.round(y)},${Math.max(1, Math.round(w))},${Math.max(1, Math.round(h))}`;
+  }
+
+  function applyBoxFromRoi(box, roiText) {
+    const viewport = getRoiViewport();
+    const [x, y, w, h] = parseRoi(roiText);
+    box.style.left = `${Math.round(naturalToStageX(x, viewport))}px`;
+    box.style.top = `${Math.round(naturalToStageY(y, viewport))}px`;
+    box.style.width = `${Math.max(8, Math.round(naturalToStageW(w, viewport)))}px`;
+    box.style.height = `${Math.max(8, Math.round(naturalToStageH(h, viewport)))}px`;
+  }
+
+  function renderTestOverlay() {
+    if (!state.testOverlayActive || !state.testRoiFront || !state.testRoiBack) {
+      el.testRoiFront.classList.add("hidden");
+      el.testRoiBack.classList.add("hidden");
+      return;
+    }
+    applyBoxFromRoi(el.testRoiFront, state.testRoiFront);
+    applyBoxFromRoi(el.testRoiBack, state.testRoiBack);
+    el.testRoiFront.classList.remove("hidden");
+    el.testRoiBack.classList.remove("hidden");
+  }
+
+  function clearTestOverlay() {
+    state.testOverlayActive = false;
+    state.testRoiFront = "";
+    state.testRoiBack = "";
+    el.testRoiFront.classList.add("hidden");
+    el.testRoiBack.classList.add("hidden");
+    updateTestButtonVisibility();
+  }
+
+  function setTestOverlay(front, back) {
+    state.testRoiFront = String(front || "").trim();
+    state.testRoiBack = String(back || "").trim();
+    state.testOverlayActive = Boolean(state.testRoiFront && state.testRoiBack);
+    renderTestOverlay();
+    updateTestButtonVisibility();
+  }
+
+  function boxToRoi(box) {
+    const viewport = getRoiViewport();
+    const left = Number.parseFloat(box.style.left || "0");
+    const top = Number.parseFloat(box.style.top || "0");
+    const width = Number.parseFloat(box.style.width || "1");
+    const height = Number.parseFloat(box.style.height || "1");
+
+    return formatRoiFromNumbers(
+      stageToNaturalX(left, viewport),
+      stageToNaturalY(top, viewport),
+      stageToNaturalW(width, viewport),
+      stageToNaturalH(height, viewport),
+    );
+  }
+
+  function clampBox(box) {
+    const viewport = getRoiViewport();
+    const minSize = 8;
+    const maxWidth = Math.max(minSize, viewport.width);
+    const maxHeight = Math.max(minSize, viewport.height);
+    const maxLeft = viewport.left + maxWidth;
+    const maxTop = viewport.top + maxHeight;
+
+    let left = Number.parseFloat(box.style.left || "0");
+    let top = Number.parseFloat(box.style.top || "0");
+    let width = Number.parseFloat(box.style.width || "1");
+    let height = Number.parseFloat(box.style.height || "1");
+
+    width = Math.max(minSize, Math.min(width, maxWidth));
+    height = Math.max(minSize, Math.min(height, maxHeight));
+    left = Math.max(viewport.left, Math.min(left, maxLeft - width));
+    top = Math.max(viewport.top, Math.min(top, maxTop - height));
+
+    box.style.left = `${left}px`;
+    box.style.top = `${top}px`;
+    box.style.width = `${width}px`;
+    box.style.height = `${height}px`;
+  }
+
+  function setMainImage(url) {
+    if (!url) {
+      el.mainImage.removeAttribute("src");
+      el.noImagePlaceholder.classList.remove("hidden");
+      el.roiFront.classList.add("hidden");
+      el.roiBack.classList.add("hidden");
+      el.testRoiFront.classList.add("hidden");
+      el.testRoiBack.classList.add("hidden");
+      updateRoiViewport();
+      return;
+    }
+    el.mainImage.src = url;
+    el.noImagePlaceholder.classList.add("hidden");
+    el.roiFront.classList.remove("hidden");
+    el.roiBack.classList.remove("hidden");
+    renderTestOverlay();
+  }
+
+  function updateSelectedImageCount() {
+    el.selectedImageCount.textContent = String(state.selectedImageIds.size);
+    updateRemoveImagesButtonState();
+  }
+
+  function updateRemoveImagesButtonState() {
+    if (!el.removeImagesBtn) {
+      return;
+    }
+    el.removeImagesBtn.disabled = state.selectedImageIds.size === 0;
+  }
+
+  function markDirty() {
+    state.dirty = true;
+    clearSaveStatus();
+    updateTestButtonVisibility();
+  }
+
+  function clearDirty() {
+    state.dirty = false;
+    updateTestButtonVisibility();
+  }
+
+  function updateImageSelectionClass(imageId) {
+    const item = state.imageElementMap.get(imageId);
+    if (!item) {
+      return;
+    }
+    item.classList.toggle("selected", state.selectedImageIds.has(imageId));
+    const checkbox = item.querySelector("input[type='checkbox']");
+    if (checkbox) {
+      checkbox.checked = state.selectedImageIds.has(imageId);
+    }
+  }
+
+  function updateCurrentImageHighlight() {
+    for (const [imageId, item] of state.imageElementMap.entries()) {
+      item.classList.toggle("active", imageId === state.currentImageId);
+    }
+  }
+
+  function selectImage(imageId, showToast = true) {
+    const image = state.imageMap.get(imageId);
+    if (!image) {
+      return;
+    }
+    state.currentImageId = imageId;
+    clearTestOverlay();
+    setMainImage(`${image.url}?t=${Date.now()}`);
+    updateCurrentImageHighlight();
+    updateTestButtonVisibility();
+    if (showToast) {
+      showMessage(`当前图片: ${image.name}`, "ok");
+    }
+  }
+
+  function toggleImageSelected(imageId, checked) {
+    if (checked) {
+      state.selectedImageIds.add(imageId);
+    } else {
+      state.selectedImageIds.delete(imageId);
+    }
+    updateImageSelectionClass(imageId);
+    updateSelectedImageCount();
+  }
+
+  function normalizeImages(images) {
+    if (!Array.isArray(images)) {
+      return [];
+    }
+    return images.filter((image) => image && image.id);
+  }
+
+  function syncSelectedImageIds() {
+    const keepSelected = new Set();
+    for (const image of state.images) {
+      if (state.selectedImageIds.has(image.id)) {
+        keepSelected.add(image.id);
+      }
+    }
+    state.selectedImageIds = keepSelected;
+  }
+
+  function rebuildImageMap() {
+    state.imageMap = new Map(state.images.map((image) => [image.id, image]));
+  }
+
+  function ensureCurrentImageId() {
+    const hasCurrent = state.images.some((item) => item.id === state.currentImageId);
+    if (hasCurrent) {
+      return false;
+    }
+    state.currentImageId = state.images.length ? state.images[state.images.length - 1].id : "";
+    return true;
+  }
+
+  function clearImageListElements() {
+    state.imageElementMap.clear();
+    el.imageList.innerHTML = "";
+  }
+
+  function updateImageItemContent(image) {
+    const item = state.imageElementMap.get(image.id);
+    if (!item) {
+      return;
+    }
+
+    const thumb = item.querySelector("img");
+    if (thumb) {
+      thumb.alt = image.name;
+    }
+
+    const name = item.querySelector(".image-name");
+    if (name) {
+      name.textContent = `${image.name} (${image.source})`;
+    }
+  }
+
+  function applyEmptyImageListState() {
+    state.images = [];
+    state.currentImageId = "";
+    state.selectedImageIds.clear();
+    rebuildImageMap();
+    clearImageListElements();
+    clearTestOverlay();
+    setMainImage("");
+    updateSelectedImageCount();
+    updateTestButtonVisibility();
+  }
+
+  function buildImageItem(image) {
+    const item = document.createElement("div");
+    item.className = "image-item";
+    item.dataset.imageId = image.id;
+
+    const selector = document.createElement("label");
+    selector.className = "selector";
+    const checkbox = document.createElement("input");
+    checkbox.type = "checkbox";
+    checkbox.addEventListener("click", (event) => {
+      event.stopPropagation();
+      toggleImageSelected(image.id, checkbox.checked);
+    });
+    selector.appendChild(checkbox);
+
+    const thumb = document.createElement("img");
+    thumb.src = `${image.thumb_url}?t=${Date.now()}`;
+    thumb.alt = image.name;
+
+    const name = document.createElement("div");
+    name.className = "image-name";
+    name.textContent = `${image.name} (${image.source})`;
+
+    item.appendChild(selector);
+    item.appendChild(thumb);
+    item.appendChild(name);
+
+    item.addEventListener("click", () => selectImage(image.id));
+    return item;
+  }
+
+  function renderImageList() {
+    syncSelectedImageIds();
+    rebuildImageMap();
+    clearImageListElements();
+
+    for (const image of state.images) {
+      const item = buildImageItem(image);
+      state.imageElementMap.set(image.id, item);
+      el.imageList.appendChild(item);
+      updateImageSelectionClass(image.id);
+    }
+
+    updateCurrentImageHighlight();
+    updateSelectedImageCount();
+  }
+
+  function replaceImages(images) {
+    state.images = normalizeImages(images);
+
+    if (state.images.length === 0) {
+      applyEmptyImageListState();
+      return;
+    }
+
+    syncSelectedImageIds();
+    ensureCurrentImageId();
+    renderImageList();
+
+    const image = state.imageMap.get(state.currentImageId);
+    if (image) {
+      setMainImage(`${image.url}?t=${Date.now()}`);
+    }
+    updateTestButtonVisibility();
+  }
+
+  function appendImages(images) {
+    const incoming = normalizeImages(images);
+    if (!incoming.length) {
+      return;
+    }
+
+    const imageIndexMap = new Map(state.images.map((image, index) => [image.id, index]));
+    const appended = [];
+
+    for (const image of incoming) {
+      const existingIndex = imageIndexMap.get(image.id);
+      if (existingIndex !== undefined) {
+        state.images[existingIndex] = image;
+      } else {
+        imageIndexMap.set(image.id, state.images.length);
+        state.images.push(image);
+        appended.push(image);
+      }
+    }
+
+    syncSelectedImageIds();
+    rebuildImageMap();
+
+    for (const image of incoming) {
+      updateImageItemContent(image);
+    }
+
+    for (const image of appended) {
+      const item = buildImageItem(image);
+      state.imageElementMap.set(image.id, item);
+      el.imageList.appendChild(item);
+      updateImageSelectionClass(image.id);
+    }
+
+    const currentChanged = ensureCurrentImageId();
+    if (currentChanged) {
+      const image = state.imageMap.get(state.currentImageId);
+      if (image) {
+        setMainImage(`${image.url}?t=${Date.now()}`);
+      }
+    }
+
+    updateCurrentImageHighlight();
+    updateSelectedImageCount();
+    updateTestButtonVisibility();
+  }
+
+  async function refreshImages() {
+    if (!state.sessionId) {
+      return;
+    }
+
+    const res = await api(`${API_PREFIX}/api/images?session_id=${encodeURIComponent(state.sessionId)}`);
+    replaceImages(res.images);
+  }
+  async function uploadImages() {
+    if (!state.sessionId) {
+      return;
+    }
+
+    if (!el.imageUpload.files || el.imageUpload.files.length === 0) {
+      throw new Error("请选择至少一张图片");
+    }
+
+    setUploadButtonLoading(true);
+    try {
+      const files = Array.from(el.imageUpload.files);
+      const images = await Promise.all(
+        files.map(
+          (file) =>
+            new Promise((resolve, reject) => {
+              const reader = new FileReader();
+              reader.onload = () => resolve({ name: file.name, content_base64: reader.result });
+              reader.onerror = () => reject(new Error(`读取文件失败: ${file.name}`));
+              reader.readAsDataURL(file);
+            }),
+        ),
+      );
+
+      const payload = await api(`${API_PREFIX}/api/images/upload`, {
+        method: "POST",
+        body: JSON.stringify({ session_id: state.sessionId, images }),
+      });
+
+      el.imageUpload.value = "";
+      const appendedImages = normalizeImages(payload.images);
+      appendImages(appendedImages);
+      showMessage(`上传成功,共 ${appendedImages.length} 张`, "ok");
+    } finally {
+      setUploadButtonLoading(false);
+    }
+  }
+
+  async function removeSelectedImages() {
+    if (!state.sessionId || state.selectedImageIds.size === 0) {
+      throw new Error("请先勾选图片");
+    }
+
+    const ids = Array.from(state.selectedImageIds);
+    const res = await api(`${API_PREFIX}/api/images/delete-batch`, {
+      method: "POST",
+      body: JSON.stringify({ session_id: state.sessionId, image_ids: ids }),
+    });
+
+    await refreshImages();
+    showMessage(`已移除 ${res.removed_count || 0} 张图片`, "ok");
+  }
+
+  async function clearImages() {
+    if (!state.sessionId || state.images.length === 0) {
+      return;
+    }
+
+    const confirmed = window.confirm("确认清空当前会话的全部图片吗?");
+    if (!confirmed) {
+      return;
+    }
+
+    const res = await api(`${API_PREFIX}/api/images/clear`, {
+      method: "POST",
+      body: JSON.stringify({ session_id: state.sessionId }),
+    });
+
+    await refreshImages();
+    showMessage(`已清空图片,共 ${res.removed_count || 0} 张`, "ok");
+  }
+
+  function getCurrentRule() {
+    if (state.activeRuleIndex < 0 || state.activeRuleIndex >= state.rules.length) {
+      return null;
+    }
+    return state.rules[state.activeRuleIndex];
+  }
+
+  function syncRoiToRule() {
+    const rule = getCurrentRule();
+    if (!rule) {
+      return;
+    }
+
+    const front = boxToRoi(el.roiFront);
+    const back = boxToRoi(el.roiBack);
+
+    rule.roiFront = front;
+    if (state.ruleType === "list") {
+      state.listMeta.roiBack = back;
+    } else {
+      rule.roiBack = back;
+    }
+
+    el.roiFrontValue.value = front;
+    el.roiBackValue.value = back;
+    markDirty();
+  }
+
+  function captureCurrentCanvasRois() {
+    const rule = getCurrentRule();
+    if (!rule) {
+      return null;
+    }
+
+    clampBox(el.roiFront);
+    clampBox(el.roiBack);
+
+    return {
+      front: boxToRoi(el.roiFront),
+      back: boxToRoi(el.roiBack),
+    };
+  }
+
+  function createRuleFromCurrentCanvas(type) {
+    const rule = defaultRuleByType(type);
+    const roi = captureCurrentCanvasRois();
+    if (!roi) {
+      return rule;
+    }
+
+    rule.roiFront = roi.front;
+    if (type !== "list") {
+      rule.roiBack = roi.back;
+    } else {
+      state.listMeta.roiBack = roi.back;
+    }
+    return rule;
+  }
+
+  function applyRoiInputToRule(target) {
+    const rule = getCurrentRule();
+    if (!rule) {
+      return;
+    }
+
+    const isFront = target === "front";
+    const input = isFront ? el.roiFrontValue : el.roiBackValue;
+    const box = isFront ? el.roiFront : el.roiBack;
+    const parsed = parseRoiStrict(input.value);
+
+    if (!parsed) {
+      const fallback = isFront
+        ? (rule.roiFront || "0,0,100,100")
+        : (state.ruleType === "list" ? (state.listMeta.roiBack || "0,0,100,100") : (rule.roiBack || "0,0,100,100"));
+      input.value = fallback;
+      showMessage(`${isFront ? "roiFront" : "roiBack"} 格式无效,应为 x,y,w,h`, "error");
+      return;
+    }
+
+    applyBoxFromRoi(box, parsed);
+    clampBox(box);
+    const normalized = boxToRoi(box);
+    input.value = normalized;
+    if (normalized !== parsed) {
+      showMessage(`${isFront ? "roiFront" : "roiBack"} 超出图像显示范围,已自动规范化`, "ok");
+    }
+
+    if (isFront) {
+      rule.roiFront = normalized;
+    } else if (state.ruleType === "list") {
+      state.listMeta.roiBack = normalized;
+    } else {
+      rule.roiBack = normalized;
+    }
+
+    markDirty();
+  }
+
+  function refreshRoiLayoutFromRule() {
+    const rule = getCurrentRule();
+    updateRoiViewport();
+    if (!rule) {
+      applyBoxFromRoi(el.roiFront, "0,0,100,100");
+      applyBoxFromRoi(el.roiBack, "0,0,100,100");
+      clampBox(el.roiFront);
+      clampBox(el.roiBack);
+      renderTestOverlay();
+      return;
+    }
+    const front = rule.roiFront || "0,0,100,100";
+    const back = state.ruleType === "list" ? (state.listMeta.roiBack || "0,0,100,100") : (rule.roiBack || "0,0,100,100");
+    applyBoxFromRoi(el.roiFront, front);
+    applyBoxFromRoi(el.roiBack, back);
+    clampBox(el.roiFront);
+    clampBox(el.roiBack);
+    renderTestOverlay();
+  }
+
+  function setupRoiBox(box) {
+    const handles = Array.from(box.querySelectorAll(".resize-handle"));
+    let mode = "";
+    let resizeDir = "";
+    let startX = 0;
+    let startY = 0;
+    let origin = { left: 0, top: 0, width: 0, height: 0 };
+
+    const onMove = (event) => {
+      if (!mode) {
+        return;
+      }
+      const dx = event.clientX - startX;
+      const dy = event.clientY - startY;
+      if (mode === "drag") {
+        box.style.left = `${origin.left + dx}px`;
+        box.style.top = `${origin.top + dy}px`;
+      } else if (mode === "resize") {
+        const minSize = 8;
+        const right = origin.left + origin.width;
+        const bottom = origin.top + origin.height;
+        let left = origin.left;
+        let top = origin.top;
+        let width = origin.width;
+        let height = origin.height;
+
+        if (resizeDir.includes("w")) {
+          left = Math.min(origin.left + dx, right - minSize);
+          width = right - left;
+        } else {
+          width = Math.max(minSize, origin.width + dx);
+        }
+
+        if (resizeDir.includes("n")) {
+          top = Math.min(origin.top + dy, bottom - minSize);
+          height = bottom - top;
+        } else {
+          height = Math.max(minSize, origin.height + dy);
+        }
+
+        box.style.left = `${left}px`;
+        box.style.top = `${top}px`;
+        box.style.width = `${width}px`;
+        box.style.height = `${height}px`;
+      }
+      clampBox(box);
+      syncRoiToRule();
+    };
+
+    const onUp = () => {
+      mode = "";
+      resizeDir = "";
+      document.removeEventListener("mousemove", onMove);
+      document.removeEventListener("mouseup", onUp);
+    };
+
+    box.addEventListener("mousedown", (event) => {
+      if (event.target.closest(".resize-handle")) {
+        return;
+      }
+      event.preventDefault();
+      mode = "drag";
+      startX = event.clientX;
+      startY = event.clientY;
+      origin = {
+        left: Number.parseFloat(box.style.left || "0"),
+        top: Number.parseFloat(box.style.top || "0"),
+        width: Number.parseFloat(box.style.width || "1"),
+        height: Number.parseFloat(box.style.height || "1"),
+      };
+      document.addEventListener("mousemove", onMove);
+      document.addEventListener("mouseup", onUp);
+    });
+
+    for (const handle of handles) {
+      handle.addEventListener("mousedown", (event) => {
+        event.preventDefault();
+        event.stopPropagation();
+        mode = "resize";
+        resizeDir = handle.dataset.resizeDir || "se";
+        startX = event.clientX;
+        startY = event.clientY;
+        origin = {
+          left: Number.parseFloat(box.style.left || "0"),
+          top: Number.parseFloat(box.style.top || "0"),
+          width: Number.parseFloat(box.style.width || "1"),
+          height: Number.parseFloat(box.style.height || "1"),
+        };
+        document.addEventListener("mousemove", onMove);
+        document.addEventListener("mouseup", onUp);
+      });
+    }
+  }
+
+  function adjustStageByImage() {
+    const naturalW = el.mainImage.naturalWidth || 1280;
+    const naturalH = el.mainImage.naturalHeight || 720;
+
+    const containerW = el.stageWrap && el.stageWrap.parentElement
+      ? (el.stageWrap.parentElement.clientWidth - 28)
+      : 940;
+
+    const stageBaseH = window.innerWidth <= 1320
+      ? 520
+      : Math.min(window.innerHeight * 0.62, 640);
+
+    const maxW = Math.max(320, containerW);
+    const maxH = Math.max(240, stageBaseH - 20);
+    const scale = Math.min(maxW / naturalW, maxH / naturalH, 1);
+
+    const stageScale = scale || 1;
+    el.imageStage.style.width = `${Math.round(naturalW * stageScale)}px`;
+    el.imageStage.style.height = `${Math.round(naturalH * stageScale)}px`;
+
+    fillRuleForm();
+  }
+
+  function resetListMeta() {
+    state.listMeta = getListMetaDefaults();
+  }
+
+  function defaultRuleByType(type) {
+    const rule = {};
+    for (const field of getRuleFields(type)) {
+      rule[field.key] = field.default ?? "";
+    }
+    rule.itemName = String(rule.itemName || "new");
+    rule.roiFront = "0,0,100,100";
+    if (type !== "list") {
+      rule.roiBack = "0,0,100,100";
+    }
+    if (type === "image") {
+      rule.imageName = String(rule.imageName || "").trim() || defaultImageNameForItem(rule.itemName || "new");
+      rule.__autoImageName = true;
+    }
+    if (type === "list") {
+      delete rule.description;
+    }
+    return rule;
+  }
+
+  function normalizeLoadedRules(type, rules) {
+    const result = [];
+    for (const raw of rules || []) {
+      const item = { ...defaultRuleByType(type), ...(raw || {}) };
+      if (type === "image") {
+        const autoName = defaultImageNameForItem(item.itemName || "");
+        item.__autoImageName = !item.imageName || item.imageName === autoName;
+      }
+      if (type === "list") {
+        delete item.description;
+      }
+      result.push(item);
+    }
+    return result;
+  }
+
+  function cloneRules(rules) {
+    return (rules || []).map((rule) => ({ ...rule }));
+  }
+
+  function updateFieldVisibility() {
+    const type = state.ruleType;
+    el.listMetaBox.classList.toggle("hidden", type !== "list");
+
+    const showSaveImage = type === "image" || isListImageRule();
+    el.saveImageBtn.classList.toggle("hidden", !showSaveImage);
+
+    refreshActiveRuleImageExists().catch(() => {
+      // ignore
+    });
+  }
+
+  function getRulePreviewImageName(rule) {
+    if (!rule) {
+      return "";
+    }
+    if (state.ruleType === "image") {
+      return String(rule.imageName || "").trim();
+    }
+    if (isListImageRule()) {
+      return listImageNameForItem(rule.itemName);
+    }
+    return "";
+  }
+
+  function getRuleDeleteImageName(rule) {
+    if (!rule) {
+      return "";
+    }
+    if (state.ruleType === "image") {
+      const imageName = String(rule.imageName || "").trim();
+      return imageName || defaultImageNameForItem(rule.itemName || "image");
+    }
+    if (isListImageRule()) {
+      return listImageNameForItem(rule.itemName);
+    }
+    return "";
+  }
+
+  function canDeleteRuleLinkedImage(rule) {
+    if (!rule) {
+      return false;
+    }
+    return state.ruleType === "image" || isListImageRule();
+  }
+
+  function currentRulePreviewUrl(rule) {
+    if (!isImagePreviewRule()) {
+      return "";
+    }
+    const imageName = getRulePreviewImageName(rule);
+    if (!imageName || !state.taskName || !state.jsonRelPath) {
+      return "";
+    }
+    const query = new URLSearchParams({
+      task_name: state.taskName,
+      json_relpath: state.jsonRelPath,
+      image_name: imageName,
+    }).toString();
+    return `${API_PREFIX}/api/rules/image-preview?${query}`;
+  }
+
+  function getRuleImageCacheKeyFromImageName(imageName) {
+    const value = String(imageName || "").trim();
+    if (!value || !state.taskName || !state.jsonRelPath) {
+      return "";
+    }
+    return `${state.taskName}|${state.jsonRelPath}|${value}`;
+  }
+
+  function getRuleImageCacheKey(rule) {
+    return getRuleImageCacheKeyFromImageName(getRulePreviewImageName(rule));
+  }
+
+  async function checkRuleImageExists(rule) {
+    const key = getRuleImageCacheKey(rule);
+    if (!key) {
+      return false;
+    }
+    if (state.imagePreviewCache.has(key)) {
+      return Boolean(state.imagePreviewCache.get(key));
+    }
+    const url = currentRulePreviewUrl(rule);
+    if (!url) {
+      state.imagePreviewCache.set(key, false);
+      return false;
+    }
+    try {
+      const response = await fetch(`${url}&t=${Date.now()}`, { method: "GET", cache: "no-store" });
+      const exists = response.ok;
+      state.imagePreviewCache.set(key, exists);
+      return exists;
+    } catch (_error) {
+      state.imagePreviewCache.set(key, false);
+      return false;
+    }
+  }
+
+  function clearRuleImageCacheByImageName(imageName) {
+    const key = getRuleImageCacheKeyFromImageName(imageName);
+    if (key) {
+      state.imagePreviewCache.delete(key);
+    }
+  }
+
+  function clearRuleImageCache(rule) {
+    clearRuleImageCacheByImageName(getRulePreviewImageName(rule));
+  }
+
+  async function refreshActiveRuleImageExists() {
+    const token = ++state.imageCheckToken;
+    if (!isImagePreviewRule()) {
+      state.activeRuleImageExists = true;
+      updateTestButtonVisibility();
+      return;
+    }
+    const rule = getCurrentRule();
+    if (!rule) {
+      state.activeRuleImageExists = false;
+      updateTestButtonVisibility();
+      return;
+    }
+    const exists = await checkRuleImageExists(rule);
+    if (token !== state.imageCheckToken) {
+      return;
+    }
+    state.activeRuleImageExists = exists;
+    updateTestButtonVisibility();
+  }
+
+  function buildRuleItem(rule, index, displayIndex) {
+    const item = document.createElement("div");
+    item.className = "rule-item";
+    item.dataset.index = String(index);
+    item.dataset.displayIndex = String(displayIndex);
+
+    if (isImagePreviewRule()) {
+      const thumbWrap = document.createElement("div");
+      thumbWrap.className = "rule-thumb-wrap";
+
+      const thumb = document.createElement("img");
+      thumb.className = "rule-thumb";
+      thumb.alt = "";
+
+      const empty = document.createElement("span");
+      empty.className = "rule-thumb-empty";
+      empty.textContent = "空";
+
+      thumb.onload = () => {
+        thumbWrap.classList.add("has-image");
+      };
+
+      thumb.onerror = () => {
+        thumb.removeAttribute("src");
+        thumbWrap.classList.remove("has-image");
+      };
+
+      const url = currentRulePreviewUrl(rule);
+      if (url) {
+        thumb.src = `${url}&t=${Date.now()}`;
+      } else {
+        thumbWrap.classList.remove("has-image");
+      }
+
+      thumbWrap.appendChild(thumb);
+      thumbWrap.appendChild(empty);
+      item.appendChild(thumbWrap);
+    }
+
+    const text = document.createElement("div");
+    text.className = "rule-item-text";
+    text.textContent = `${displayIndex}. ${rule.itemName || "unnamed"}`;
+    item.appendChild(text);
+
+    item.addEventListener("click", () => {
+      state.activeRuleIndex = index;
+      updateRuleActiveHighlight();
+      fillRuleForm();
+      clearTestOverlay();
+      refreshActiveRuleImageExists().catch(() => {
+        // ignore
+      });
+    });
+
+    return item;
+  }
+
+  function buildRuleListEmptyState(message) {
+    const empty = document.createElement("div");
+    empty.className = "rule-list-empty";
+    empty.textContent = message;
+    return empty;
+  }
+
+  function getVisibleRuleEntries() {
+    const keyword = getNormalizedRuleSearchKeyword();
+    return state.rules
+      .map((rule, actualIndex) => ({ rule, actualIndex }))
+      .filter(({ rule }) => {
+        if (!keyword) {
+          return true;
+        }
+        return String(rule.itemName || "").toLowerCase().includes(keyword);
+      })
+      .map((entry, offset) => ({
+        ...entry,
+        displayIndex: offset + 1,
+      }));
+  }
+
+  function updateRuleActiveHighlight() {
+    const items = el.ruleList.querySelectorAll(".rule-item");
+    for (const item of items) {
+      const idx = Number.parseInt(item.dataset.index || "-1", 10);
+      item.classList.toggle("active", idx === state.activeRuleIndex);
+    }
+  }
+
+  function renderRuleList() {
+    el.ruleList.innerHTML = "";
+
+    if (state.rules.length === 0) {
+      state.activeRuleIndex = -1;
+      clearRuleForm();
+      fillListMetaForm();
+      return;
+    }
+
+    const visibleEntries = getVisibleRuleEntries();
+
+    if (visibleEntries.length === 0) {
+      state.activeRuleIndex = -1;
+      el.ruleList.appendChild(buildRuleListEmptyState("未找到匹配的规则项"));
+      clearRuleForm();
+      fillListMetaForm();
+      return;
+    }
+
+    if (state.activeRuleIndex < 0 || !visibleEntries.some((entry) => entry.actualIndex === state.activeRuleIndex)) {
+      state.activeRuleIndex = visibleEntries[0].actualIndex;
+    }
+
+    visibleEntries.forEach(({ rule, actualIndex, displayIndex }) => {
+      el.ruleList.appendChild(buildRuleItem(rule, actualIndex, displayIndex));
+    });
+
+    updateRuleActiveHighlight();
+    fillRuleForm();
+  }
+
+  function refreshActiveRuleItem() {
+    const active = el.ruleList.querySelector(`.rule-item[data-index="${state.activeRuleIndex}"]`);
+    if (!active) {
+      return;
+    }
+    const rule = getCurrentRule();
+    if (!rule) {
+      return;
+    }
+    const text = active.querySelector(".rule-item-text");
+    if (text) {
+      const displayIndex = Number.parseInt(active.dataset.displayIndex || "1", 10) || 1;
+      text.textContent = `${displayIndex}. ${rule.itemName || "unnamed"}`;
+    }
+    const thumbWrap = active.querySelector(".rule-thumb-wrap");
+    const thumb = active.querySelector(".rule-thumb");
+    if (thumb && isImagePreviewRule()) {
+      const url = currentRulePreviewUrl(rule);
+      if (url) {
+        if (thumbWrap) {
+          thumbWrap.classList.remove("has-image");
+        }
+        thumb.src = `${url}&t=${Date.now()}`;
+      } else {
+        thumb.removeAttribute("src");
+        if (thumbWrap) {
+          thumbWrap.classList.remove("has-image");
+        }
+      }
+    }
+  }
+
+  function clearRuleForm() {
+    for (const field of getRuleFields()) {
+      const element = document.getElementById(getRuleFieldDomId(field.key));
+      setElementValue(element, field.default ?? "");
+    }
+    el.roiFrontValue.value = "";
+    el.roiBackValue.value = "";
+    refreshRoiLayoutFromRule();
+    clearTestOverlay();
+    updateFieldVisibility();
+  }
+
+  function fillListMetaForm() {
+    const defaults = getListMetaDefaults();
+    for (const field of getListMetaFields()) {
+      const element = document.getElementById(getListMetaFieldDomId(field.key));
+      setElementValue(element, state.listMeta[field.key] ?? defaults[field.key] ?? "");
+    }
+  }
+
+  function updateListMetaFromForm() {
+    const defaults = getListMetaDefaults();
+    for (const field of getListMetaFields()) {
+      const element = document.getElementById(getListMetaFieldDomId(field.key));
+      state.listMeta[field.key] = readFieldValue(field, element) ?? defaults[field.key] ?? "";
+    }
+  }
+
+  function fillRuleForm() {
+    const rule = getCurrentRule();
+    if (!rule) {
+      clearRuleForm();
+      return;
+    }
+
+    for (const field of getRuleFields()) {
+      const element = document.getElementById(getRuleFieldDomId(field.key));
+      setElementValue(element, rule[field.key] ?? field.default ?? "");
+    }
+
+    const front = rule.roiFront || "0,0,100,100";
+    const back = state.ruleType === "list" ? (state.listMeta.roiBack || "0,0,100,100") : (rule.roiBack || "0,0,100,100");
+    el.roiFrontValue.value = front;
+    el.roiBackValue.value = back;
+
+    refreshRoiLayoutFromRule();
+
+    fillListMetaForm();
+    updateFieldVisibility();
+  }
+
+  function updateRuleFromForm(changedField = "") {
+    const rule = getCurrentRule();
+    if (!rule) {
+      return;
+    }
+
+    const oldPreviewImageName = getRulePreviewImageName(rule);
+    for (const field of getRuleFields()) {
+      if (state.ruleType === "image" && field.key === "imageName" && changedField === "itemName") {
+        continue;
+      }
+      const element = document.getElementById(getRuleFieldDomId(field.key));
+      rule[field.key] = readFieldValue(field, element);
+    }
+
+    const newItemName = String(rule.itemName || "").trim() || "unnamed";
+    rule.itemName = newItemName;
+
+    if (state.ruleType === "image") {
+      if (changedField === "itemName") {
+        rule.imageName = defaultImageNameForItem(newItemName);
+        rule.__autoImageName = true;
+        setElementValue(el.imageName, rule.imageName);
+      } else {
+        const imageNameInput = String(el.imageName && el.imageName.value || "").trim();
+        if (imageNameInput) {
+          rule.imageName = imageNameInput;
+          rule.__autoImageName = imageNameInput === defaultImageNameForItem(newItemName);
+        } else {
+          rule.imageName = defaultImageNameForItem(newItemName);
+          rule.__autoImageName = true;
+          setElementValue(el.imageName, rule.imageName);
+        }
+      }
+
+      const nextImageName = String(rule.imageName || "").trim();
+      if (oldPreviewImageName !== nextImageName || changedField === "itemName") {
+        clearRuleImageCacheByImageName(oldPreviewImageName);
+        clearRuleImageCache(rule);
+        state.activeRuleImageExists = false;
+      }
+    }
+
+    if (state.ruleType === "list") {
+      updateListMetaFromForm();
+      delete rule.description;
+      if (isListImageRule() && changedField === "itemName") {
+        clearRuleImageCacheByImageName(oldPreviewImageName);
+        clearRuleImageCache(rule);
+        state.activeRuleImageExists = false;
+      }
+    }
+
+    const searchKeyword = getNormalizedRuleSearchKeyword();
+    const activeStillVisible = !searchKeyword || String(rule.itemName || "").toLowerCase().includes(searchKeyword);
+    if (changedField === "itemName" && !activeStillVisible) {
+      renderRuleList();
+    } else {
+      refreshActiveRuleItem();
+    }
+    markDirty();
+    refreshActiveRuleImageExists().catch(() => {
+      // ignore
+    });
+  }
+
+  async function refreshRulesList() {
+    if (!state.jsonFileName) {
+      throw new Error("请先选择规则 JSON");
+    }
+    clearOutput();
+    clearSaveStatus();
+    clearTestOverlay();
+    await loadRulesFromSelectedFile();
+  }
+
+  function updateRuleTypeLockView() {
+    el.ruleType.disabled = state.ruleTypeLocked;
+    if (el.ruleTypeLockTip) {
+      el.ruleTypeLockTip.classList.toggle("hidden", !state.ruleTypeLocked);
+    }
+  }
+
+  function setRuleType(nextType) {
+    state.ruleType = AllowedRuleTypes.has(nextType) ? nextType : (state.ruleSchemas[0] ? state.ruleSchemas[0].type : "image");
+    el.ruleType.value = state.ruleType;
+    renderDynamicFieldGroups();
+    updateFieldVisibility();
+  }
+
+  function resolveTaskAndJson(dirPath, jsonName) {
+    const parts = splitPath(dirPath);
+    if (parts.length === 0) {
+      throw new Error("请先选择规则目录");
+    }
+    if (!jsonName) {
+      throw new Error("请先选择规则 JSON");
+    }
+    const taskName = parts[0];
+    const relParts = parts.slice(1);
+    relParts.push(jsonName);
+    return {
+      taskName,
+      jsonRelPath: joinPath(relParts),
+    };
+  }
+
+  async function fetchRuleSource(dirPath) {
+    const query = new URLSearchParams({ dir_path: dirPath || "" }).toString();
+    return api(`${API_PREFIX}/api/rules/source?${query}`);
+  }
+
+  function updateCurrentDirText() {
+    if (!el.currentDir) {
+      return;
+    }
+    const text = state.currentDirPath ? state.currentDirPath : "";
+    el.currentDir.textContent = text;
+  }
+
+  function hasLoadedRuleSource() {
+    return Boolean(state.taskName && state.jsonRelPath);
+  }
+
+  function getNormalizedRuleSearchKeyword() {
+    return String(state.ruleSearchKeyword || "").trim().toLowerCase();
+  }
+
+  function resetRuleSearch() {
+    state.ruleSearchKeyword = "";
+    if (el.ruleSearchInput) {
+      el.ruleSearchInput.value = "";
+    }
+  }
+
+  function updateRuleSearchVisibility() {
+    const visible = hasLoadedRuleSource();
+    if (el.ruleSearchBox) {
+      el.ruleSearchBox.classList.toggle("hidden", !visible);
+    }
+    if (el.ruleSearchInput) {
+      el.ruleSearchInput.disabled = !visible;
+      if (!visible) {
+        el.ruleSearchInput.value = "";
+      }
+    }
+  }
+
+  function clearRuleBinding() {
+    state.taskName = "";
+    state.jsonRelPath = "";
+    resetRuleSearch();
+    updateRuleSearchVisibility();
+  }
+
+  function updateRuleSourceActionVisibility() {
+    const canCreate = !state.sourceLeafHasDirs && !state.jsonFileName;
+    const canDelete = Boolean(state.jsonFileName);
+
+    el.newJsonName.classList.toggle("hidden", !canCreate);
+    el.createJsonBtn.classList.toggle("hidden", !canCreate);
+    el.deleteJsonBtn.classList.toggle("hidden", !canDelete);
+  }
+
+  function createBreadcrumbSelect(values, selected, placeholder) {
+    const select = document.createElement("select");
+    select.className = "breadcrumb-select";
+    createOption(select, "", placeholder);
+    for (const name of values) {
+      createOption(select, name, name);
+    }
+    if (selected && values.includes(selected)) {
+      select.value = selected;
+    }
+    return select;
+  }
+
+  async function rebuildDirSelectors(targetPath = "", targetJson = "", autoLoad = false) {
+    const preferredDirs = splitPath(targetPath);
+    const preferredJson = String(targetJson || "").trim();
+
+    state.sourceDirs = [];
+    state.sourceLeafHasDirs = false;
+    state.sourceLeafJsonFiles = [];
+    state.currentDirPath = "";
+    state.jsonFileName = "";
+
+    el.dirSelectors.innerHTML = "";
+
+    const rootPrefix = document.createElement("span");
+    rootPrefix.className = "breadcrumb-root-prefix";
+    rootPrefix.textContent = "/";
+    el.dirSelectors.appendChild(rootPrefix);
+
+    let currentPath = "";
+    let data = await fetchRuleSource(currentPath);
+    let depth = 0;
+
+    while (true) {
+      const dirs = Array.isArray(data.directories) ? data.directories : [];
+      const expected = preferredDirs[depth] || "";
+      const selectedDir = expected && dirs.includes(expected) ? expected : "";
+
+      if (dirs.length > 0) {
+        if (depth > 0) {
+          const sep = document.createElement("span");
+          sep.className = "breadcrumb-sep";
+          sep.textContent = "/";
+          el.dirSelectors.appendChild(sep);
+        }
+
+        const dirSelect = createBreadcrumbSelect(dirs, selectedDir, "选择目录");
+        dirSelect.dataset.depth = String(depth);
+        dirSelect.addEventListener(
+          "change",
+          withError(async () => {
+            const changeDepth = Number.parseInt(dirSelect.dataset.depth || "0", 10);
+            const nextDirs = state.sourceDirs.slice(0, changeDepth);
+            if (dirSelect.value) {
+              nextDirs.push(dirSelect.value);
+            }
+            clearRuleBinding();
+            await rebuildDirSelectors(joinPath(nextDirs), "", false);
+          }),
+        );
+        el.dirSelectors.appendChild(dirSelect);
+      }
+
+      if (dirs.length === 0 || !selectedDir) {
+        state.sourceDirs = preferredDirs.slice(0, depth);
+        state.currentDirPath = joinPath(state.sourceDirs);
+        state.sourceLeafHasDirs = dirs.length > 0 && !selectedDir;
+        state.sourceLeafJsonFiles = state.sourceLeafHasDirs ? [] : (Array.isArray(data.json_files) ? data.json_files : []);
+        break;
+      }
+
+      state.sourceDirs.push(selectedDir);
+      currentPath = joinPath(state.sourceDirs);
+      data = await fetchRuleSource(currentPath);
+      depth += 1;
+    }
+
+    if (!state.sourceLeafHasDirs) {
+      if (state.sourceDirs.length > 0) {
+        const sep = document.createElement("span");
+        sep.className = "breadcrumb-sep";
+        sep.textContent = "/";
+        el.dirSelectors.appendChild(sep);
+      }
+
+      const jsonSelect = createBreadcrumbSelect(state.sourceLeafJsonFiles, preferredJson, "选择 JSON");
+      if (preferredJson && state.sourceLeafJsonFiles.includes(preferredJson)) {
+        state.jsonFileName = preferredJson;
+        jsonSelect.value = preferredJson;
+      } else {
+        state.jsonFileName = "";
+      }
+
+      jsonSelect.addEventListener(
+        "change",
+        withError(async () => {
+          state.jsonFileName = jsonSelect.value || "";
+          if (!state.jsonFileName) {
+            clearRuleBinding();
+            updateRuleSourceActionVisibility();
+            updateTestButtonVisibility();
+            return;
+          }
+          await loadRulesFromSelectedFile();
+          updateRuleSourceActionVisibility();
+        }),
+      );
+      el.dirSelectors.appendChild(jsonSelect);
+    }
+
+    updateCurrentDirText();
+    updateRuleSourceActionVisibility();
+
+    if (autoLoad && state.jsonFileName) {
+      await loadRulesFromSelectedFile();
+    }
+  }
+
+  async function createJsonFile() {
+    const fileName = el.newJsonName.value.trim();
+    if (!fileName) {
+      throw new Error("请输入新 JSON 名称");
+    }
+    if (state.sourceLeafHasDirs) {
+      throw new Error("当前路径下还有子目录,请继续选择到最终目录");
+    }
+
+    const res = await api(`${API_PREFIX}/api/rules/source/create`, {
+      method: "POST",
+      body: JSON.stringify({
+        dir_path: state.currentDirPath,
+        file_name: fileName,
+      }),
+    });
+
+    const parts = splitPath(res.file || "");
+    if (parts.length === 0) {
+      throw new Error("新增 JSON 返回路径异常");
+    }
+    const created = parts.pop() || "";
+    const dirPath = joinPath(parts);
+
+    el.newJsonName.value = "";
+    await rebuildDirSelectors(dirPath, created, true);
+    showMessage(`已新增规则文件: ${created}`, "ok");
+  }
+
+  async function deleteJsonFile() {
+    const jsonName = state.jsonFileName;
+    if (!jsonName) {
+      throw new Error("请先选择要删除的 JSON 文件");
+    }
+
+    const confirmed = window.confirm(`确认删除 ${jsonName} ?`);
+    if (!confirmed) {
+      return;
+    }
+
+    await api(`${API_PREFIX}/api/rules/source/delete`, {
+      method: "POST",
+      body: JSON.stringify({
+        dir_path: state.currentDirPath,
+        file_name: jsonName,
+      }),
+    });
+
+    state.jsonFileName = "";
+    clearRuleBinding();
+    await rebuildDirSelectors(state.currentDirPath, "", false);
+    showMessage(`已删除规则文件: ${jsonName}`, "ok");
+  }
+
+  async function loadRulesFromSelectedFile() {
+    if (!state.jsonFileName) {
+      throw new Error("请先选择规则 JSON");
+    }
+
+    const pair = resolveTaskAndJson(state.currentDirPath, state.jsonFileName);
+    const previousTaskName = state.taskName;
+    const previousJsonRelPath = state.jsonRelPath;
+    state.taskName = pair.taskName;
+    state.jsonRelPath = pair.jsonRelPath;
+    if (state.taskName !== previousTaskName || state.jsonRelPath !== previousJsonRelPath) {
+      resetRuleSearch();
+    }
+    updateRuleSearchVisibility();
+
+    const query = new URLSearchParams({
+      task_name: state.taskName,
+      json_relpath: state.jsonRelPath,
+    }).toString();
+
+    const res = await api(`${API_PREFIX}/api/rules/load?${query}`);
+    const loadedType = res.rule_type;
+    const validType = AllowedRuleTypes.has(loadedType) ? loadedType : "image";
+
+    state.ruleTypeLocked = Boolean(res.rule_type_locked);
+    setRuleType(validType);
+    updateRuleTypeLockView();
+
+    if (state.ruleType === "list") {
+      resetListMeta();
+      state.listMeta = {
+        ...state.listMeta,
+        ...(res.list_meta || {}),
+      };
+      state.listMeta.roiBack = state.listMeta.roiBack || "0,0,100,100";
+    } else {
+      resetListMeta();
+    }
+
+    state.rules = normalizeLoadedRules(state.ruleType, res.rules || []);
+    if (state.rules.length === 0) {
+      state.ruleTypeLocked = false;
+      updateRuleTypeLockView();
+      state.rules = [defaultRuleByType(state.ruleType)];
+    }
+    state.activeRuleIndex = 0;
+
+    renderRuleList();
+    clearDirty();
+    clearTestOverlay();
+    clearSaveStatus();
+    showMessage(`已加载 ${state.taskName}/${state.jsonRelPath} (${state.ruleType})`, "ok");
+
+    await refreshActiveRuleImageExists();
+  }
+
+  function collectRulesPayload() {
+    if (!state.sessionId) {
+      throw new Error("会话不存在,请刷新页面重试");
+    }
+    if (!state.taskName || !state.jsonRelPath) {
+      throw new Error("请先选择规则 JSON");
+    }
+
+    syncRoiToRule();
+
+
+    const rules = state.rules.map((rule) => {
+      const cleaned = { ...rule };
+      delete cleaned.__autoImageName;
+      if (state.ruleType === "list") {
+        delete cleaned.description;
+      }
+      return cleaned;
+    });
+
+    const payload = {
+      session_id: state.sessionId,
+      task_name: state.taskName,
+      json_relpath: state.jsonRelPath,
+      rule_type: state.ruleType,
+      rules,
+    };
+
+    if (state.ruleType === "list") {
+      payload.list_meta = {
+        name: state.listMeta.name,
+        direction: state.listMeta.direction,
+        type: state.listMeta.type,
+        roiBack: state.listMeta.roiBack,
+        description: state.listMeta.description,
+      };
+    }
+
+    return payload;
+  }
+
+  async function persistRules() {
+    try {
+      const payload = collectRulesPayload();
+      const result = await api(`${API_PREFIX}/api/rules/save`, {
+        method: "POST",
+        body: JSON.stringify(payload),
+      });
+
+      const ok = result.generate_status === "success";
+      setSaveStatus(ok);
+      const outputTitle = ok
+        ? "保存成功"
+        : (result.save_status === "success" ? "规则已保存,生成失败" : "保存失败");
+      appendOutput(outputTitle, result);
+
+      clearDirty();
+      await rebuildDirSelectors(state.currentDirPath, state.jsonFileName, false);
+      await refreshActiveRuleImageExists();
+      return { ok, result };
+    } catch (error) {
+      setSaveStatus(false);
+      appendOutput("保存失败", error?.message || String(error));
+      throw error;
+    }
+  }
+
+  async function saveRules() {
+    const { ok, result } = await persistRules();
+    const assetsFile = String(result.assets_file || "").trim();
+    if (ok) {
+      const suffix = assetsFile ? `,已生成 ${assetsFile}` : "";
+      showMessage(`已保存规则,共 ${result.rule_count || 0} 条${suffix}`, "ok");
+      return;
+    }
+    const targetText = assetsFile ? `,目标文件: ${assetsFile}` : "";
+    showMessage(`规则已保存,但 assets.py 生成失败: ${result.error || "未知错误"}${targetText}`, "error");
+  }
+  async function saveImageCrop() {
+    const rule = getCurrentRule();
+    if (!rule) {
+      throw new Error("请先选择规则项");
+    }
+    if (!state.currentImageId) {
+      throw new Error("请先选择图片");
+    }
+    if (!state.taskName || !state.jsonRelPath) {
+      throw new Error("请先选择规则 JSON");
+    }
+
+    syncRoiToRule();
+
+    let imageName = "";
+    if (state.ruleType === "image") {
+      imageName = String(rule.imageName || "").trim();
+      if (!imageName) {
+        imageName = defaultImageNameForItem(rule.itemName || "image");
+        rule.imageName = imageName;
+      }
+    } else if (isListImageRule()) {
+      imageName = listImageNameForItem(rule.itemName || "");
+      if (!imageName) {
+        throw new Error("list 项缺少 itemName");
+      }
+    } else {
+      imageName = defaultImageNameForItem(rule.itemName || "image");
+    }
+
+    const result = await api(`${API_PREFIX}/api/images/crop-save`, {
+      method: "POST",
+      body: JSON.stringify({
+        session_id: state.sessionId,
+        image_id: state.currentImageId,
+        task_name: state.taskName,
+        json_relpath: state.jsonRelPath,
+        image_name: imageName,
+        roi: rule.roiFront,
+      }),
+    });
+
+    appendOutput("裁剪图片", result);
+    showMessage(`图片已保存: ${result.target_image}`, "ok");
+
+    if (isImagePreviewRule()) {
+      const key = getRuleImageCacheKey(rule);
+      if (key) {
+        state.imagePreviewCache.set(key, true);
+      }
+    }
+
+    refreshActiveRuleItem();
+    await refreshActiveRuleImageExists();
+  }
+
+  async function deleteRuleLinkedImage(imageName) {
+    return api(`${API_PREFIX}/api/rules/image/delete`, {
+      method: "POST",
+      body: JSON.stringify({
+        task_name: state.taskName,
+        json_relpath: state.jsonRelPath,
+        image_name: imageName,
+      }),
+    });
+  }
+
+  async function deleteCurrentRule() {
+    if (state.activeRuleIndex < 0) {
+      return;
+    }
+
+    const previousRules = cloneRules(state.rules);
+    const previousActiveRuleIndex = state.activeRuleIndex;
+    const previousDirty = state.dirty;
+
+    const removedIndex = previousActiveRuleIndex;
+    const removed = previousRules[removedIndex];
+    const itemName = String(removed?.itemName || "").trim() || `第 ${removedIndex + 1} 项`;
+    const imageRule = canDeleteRuleLinkedImage(removed);
+    const imageName = imageRule ? getRuleDeleteImageName(removed) : "";
+
+    let deleteLinkedImage = false;
+    if (imageRule) {
+      const message = [
+        "是否同时删除关联图像?",
+        "点击“确定”:删除规则配置和关联图像",
+        "点击“取消”:仅删除规则配置,保留关联图像",
+      ].join("\n");
+      deleteLinkedImage = window.confirm(message);
+    }
+
+    clearRuleImageCache(removed);
+    state.rules.splice(removedIndex, 1);
+    if (state.activeRuleIndex >= state.rules.length) {
+      state.activeRuleIndex = state.rules.length - 1;
+    }
+    clearTestOverlay();
+    renderRuleList();
+    markDirty();
+
+    let message = `已删除规则配置: ${itemName}`;
+    let messageType = "ok";
+
+    let saveResult = null;
+    try {
+      saveResult = await persistRules();
+    } catch (_error) {
+      state.rules = cloneRules(previousRules);
+      state.activeRuleIndex = previousActiveRuleIndex;
+      clearTestOverlay();
+      renderRuleList();
+      if (previousDirty) {
+        markDirty();
+      } else {
+        clearDirty();
+      }
+      setSaveStatus(false);
+      showMessage(`删除规则失败: ${itemName},规则配置未保存`, "error");
+      refreshActiveRuleImageExists().catch(() => {
+        // ignore
+      });
+      return;
+    }
+
+    if (!saveResult.ok) {
+      message = `已删除规则配置: ${itemName},但 assets.py 生成失败`;
+      if (deleteLinkedImage) {
+        message += ",未删除关联图像";
+      }
+      showMessage(message, "error");
+      return;
+    }
+
+    if (deleteLinkedImage) {
+      if (!imageName || !state.taskName || !state.jsonRelPath) {
+        const result = {
+          removed: false,
+          image_name: imageName,
+          message: "缺少关联图像路径,未删除模板图",
+        };
+        appendOutput("删除规则关联图像", result);
+        message = `已删除规则配置: ${itemName},但未删除关联图像`;
+        messageType = "error";
+      } else {
+        try {
+          const result = await deleteRuleLinkedImage(imageName);
+          clearRuleImageCacheByImageName(imageName);
+          appendOutput("删除规则关联图像", result);
+          if (result.removed) {
+            message = `已删除规则配置与关联图像: ${itemName}`;
+          } else {
+            message = `已删除规则配置: ${itemName},关联图像原本不存在`;
+          }
+        } catch (error) {
+          appendOutput("删除规则关联图像失败", {
+            image_name: imageName,
+            message: error?.message || String(error),
+          });
+          message = `已删除规则配置: ${itemName},但删除关联图像失败`;
+          messageType = "error";
+        }
+      }
+    } else if (imageRule) {
+      message = `已删除规则配置: ${itemName},保留关联图像`;
+    }
+
+    showMessage(message, messageType);
+    refreshActiveRuleImageExists().catch(() => {
+      // ignore
+    });
+  }
+  function updateTestButtonVisibility() {
+    const hasRule = Boolean(getCurrentRule());
+    const subtype = getRuleSubtype();
+    const canTestType = state.ruleType === "image"
+      || state.ruleType === "ocr"
+      || (state.ruleType === "list" && (subtype === "image" || subtype === "ocr"));
+    let canUse = canTestType && hasRule && !!state.currentImageId && !!state.taskName && !!state.jsonRelPath;
+
+    if (canUse && isImagePreviewRule()) {
+      canUse = state.activeRuleImageExists || state.testOverlayActive;
+    }
+
+    if (state.testOverlayActive) {
+      canUse = true;
+    }
+
+    el.testRuleBtn.classList.toggle("hidden", !canUse);
+    el.testRuleBtn.textContent = state.testOverlayActive ? "清除" : "测试";
+  }
+
+  async function testCurrentRule() {
+    if (state.testOverlayActive) {
+      clearTestOverlay();
+      appendOutput("清除测试框", "已清除 test_roi_front / test_roi_back");
+      return;
+    }
+
+    const rule = getCurrentRule();
+    if (!rule) {
+      throw new Error("请先选择规则项");
+    }
+    if (!state.currentImageId) {
+      throw new Error("请先选择图片");
+    }
+    if (!state.taskName || !state.jsonRelPath) {
+      throw new Error("请先选择规则 JSON");
+    }
+
+    const payloadRule = { ...rule };
+    delete payloadRule.__autoImageName;
+    delete payloadRule.description;
+
+    const payload = {
+      session_id: state.sessionId,
+      image_id: state.currentImageId,
+      task_name: state.taskName,
+      json_relpath: state.jsonRelPath,
+      rule_type: state.ruleType,
+      rule: payloadRule,
+    };
+    if (state.ruleType === "list") {
+      payload.list_meta = {
+        name: state.listMeta.name,
+        direction: state.listMeta.direction,
+        type: state.listMeta.type,
+        roiBack: state.listMeta.roiBack,
+        description: state.listMeta.description,
+      };
+    }
+
+    const res = await api(`${API_PREFIX}/api/rules/test`, {
+      method: "POST",
+      body: JSON.stringify(payload),
+    });
+
+    const result = res.result || {};
+    setTestOverlay(result.roiFront, result.roiBack);
+    appendOutput("测试结果", result);
+  }
+
+  function updateEmulatorStatusView(data) {
+    const status = data && typeof data === "object" ? { ...data } : {};
+    if (!status.state) {
+      status.state = "stopped";
+    }
+    state.emulatorStatus = status;
+    el.emulatorStatus.textContent = JSON.stringify(status, null, 2);
+  }
+
+  function setEmulatorErrorStatus(message, extra = {}) {
+    const text = String(message || extra.error || "模拟器预览出错").trim() || "模拟器预览出错";
+    const base = state.emulatorStatus && typeof state.emulatorStatus === "object" ? state.emulatorStatus : {};
+    updateEmulatorStatusView({
+      ...base,
+      ...extra,
+      state: extra.state || "error",
+      error: text,
+    });
+    return text;
+  }
+
+  async function syncEmulatorStatusAfterSocketIssue(message) {
+    const text = setEmulatorErrorStatus(message);
+    showMessage(text, "error");
+    try {
+      await refreshEmulatorStatus();
+    } catch (error) {
+      if (isInvalidSessionError(error)) {
+        const recovered = await recoverSessionAfterInvalid();
+        if (recovered) {
+          return;
+        }
+      }
+      const finalMessage = setEmulatorErrorStatus(error.message || String(error));
+      showMessage(finalMessage, "error");
+    }
+  }
+
+  function closeFrameSocket(markExpected = true) {
+    if (state.ws) {
+      state.wsCloseExpected = Boolean(markExpected);
+      state.ws.close();
+      state.ws = null;
+    } else {
+      state.wsCloseExpected = false;
+    }
+    if (state.wsImageUrl) {
+      URL.revokeObjectURL(state.wsImageUrl);
+      state.wsImageUrl = "";
+    }
+  }
+
+  function openFrameSocket() {
+    if (!state.sessionId) {
+      return;
+    }
+    if (state.ws && (state.ws.readyState === WebSocket.OPEN || state.ws.readyState === WebSocket.CONNECTING)) {
+      return;
+    }
+
+    state.wsCloseExpected = false;
+    const wsProtocol = window.location.protocol === "https:" ? "wss" : "ws";
+    const wsUrl = `${wsProtocol}://${window.location.host}${API_PREFIX}/ws/${encodeURIComponent(state.sessionId)}`;
+    const socket = new WebSocket(wsUrl);
+    socket.binaryType = "blob";
+
+    socket.onmessage = (event) => {
+      if (typeof event.data === "string") {
+        try {
+          const data = JSON.parse(event.data);
+          if (data.event === "error") {
+            closeFrameSocket();
+            syncEmulatorStatusAfterSocketIssue(data.message || "模拟器预览出错").catch((error) => {
+              console.error(error);
+            });
+          }
+        } catch (_e) {
+          // ignore
+        }
+        return;
+      }
+
+      const url = URL.createObjectURL(event.data);
+      if (state.wsImageUrl) {
+        URL.revokeObjectURL(state.wsImageUrl);
+      }
+      state.wsImageUrl = url;
+      el.emulatorPreview.src = url;
+    };
+
+    socket.onerror = () => {
+      closeFrameSocket();
+      syncEmulatorStatusAfterSocketIssue("模拟器预览连接异常").catch((error) => {
+        console.error(error);
+      });
+    };
+
+    socket.onclose = () => {
+      const expectedClose = state.wsCloseExpected;
+      if (state.ws === socket) {
+        state.ws = null;
+      }
+      state.wsCloseExpected = false;
+      if (expectedClose || state.sourceMode !== "emulator" || state.sessionClosing) {
+        return;
+      }
+      syncEmulatorStatusAfterSocketIssue("模拟器预览连接已断开").catch((error) => {
+        console.error(error);
+      });
+    };
+
+    state.ws = socket;
+  }
+  async function refreshEmulatorStatus() {
+    if (!state.sessionId) {
+      return;
+    }
+    const res = await api(`${API_PREFIX}/api/emulator/status?session_id=${encodeURIComponent(state.sessionId)}`);
+    const status = res.emulator || {};
+    updateEmulatorStatusView(status);
+
+    if (state.sourceMode === "emulator" && status.state === "running") {
+      openFrameSocket();
+    }
+
+    if (status.state !== "running" && status.state !== "starting") {
+      closeFrameSocket();
+    }
+  }
+
+  async function startEmulator() {
+    if (!state.sessionId) {
+      throw new Error("会话未初始化");
+    }
+    const configName = el.configName.value;
+    if (!configName) {
+      throw new Error("请先选择脚本配置");
+    }
+
+    const frameRate = Number.parseInt(el.frameRate.value, 10);
+    const body = {
+      session_id: state.sessionId,
+      config_name: configName,
+      frame_rate: Number.isFinite(frameRate) ? frameRate : 2,
+    };
+
+    const res = await api(`${API_PREFIX}/api/emulator/start`, {
+      method: "POST",
+      body: JSON.stringify(body),
+    });
+
+    updateEmulatorStatusView(res.emulator || {});
+    await refreshEmulatorStatus();
+    showMessage("模拟器会话已启动", "ok");
+  }
+
+  async function stopEmulator() {
+    if (!state.sessionId) {
+      return;
+    }
+    const res = await api(`${API_PREFIX}/api/emulator/stop`, {
+      method: "POST",
+      body: JSON.stringify({ session_id: state.sessionId }),
+    });
+    closeFrameSocket();
+    updateEmulatorStatusView(res.emulator || {});
+    showMessage("模拟器会话已停止", "ok");
+  }
+
+  async function captureEmulatorFrame() {
+    if (!state.sessionId) {
+      throw new Error("会话未初始化");
+    }
+    const result = await api(`${API_PREFIX}/api/emulator/capture`, {
+      method: "POST",
+      body: JSON.stringify({ session_id: state.sessionId }),
+    });
+    appendImages(result && result.image ? [result.image] : []);
+    showMessage("已将当前帧加入图片列表", "ok");
+  }
+
+  function setSourceMode(mode) {
+    state.sourceMode = mode;
+    el.sourceMode.value = mode;
+
+    const isLocal = mode === "local";
+    el.localControls.classList.toggle("hidden", !isLocal);
+    el.emulatorControls.classList.toggle("hidden", isLocal);
+
+    if (isLocal) {
+      closeFrameSocket();
+    } else {
+      refreshEmulatorStatus().catch(async (error) => {
+        if (isInvalidSessionError(error)) {
+          const recovered = await recoverSessionAfterInvalid();
+          if (recovered) {
+            return;
+          }
+        }
+        showMessage(error.message || String(error), "error");
+      });
+    }
+  }
+
+  async function createSession() {
+    const res = await api(`${API_PREFIX}/api/session`, { method: "POST" });
+    const session = res.session || {};
+    state.sessionId = session.session_id || "";
+    state.sessionClosing = false;
+    el.sessionId.textContent = state.sessionId || "-";
+  }
+
+  async function loadConfigs() {
+    const res = await api(`${API_PREFIX}/api/configs`);
+    fillSelect(el.configName, res.configs || [], "请选择脚本配置");
+  }
+
+  function bindEvents() {
+    el.sourceMode.addEventListener("change", () => setSourceMode(el.sourceMode.value));
+
+    el.uploadBtn.addEventListener("click", withError(uploadImages));
+    el.refreshImagesBtn.addEventListener("click", withError(refreshImages));
+    el.removeImagesBtn.addEventListener("click", withError(removeSelectedImages));
+    el.clearImagesBtn.addEventListener("click", withError(clearImages));
+    updateRemoveImagesButtonState();
+
+    el.startEmulatorBtn.addEventListener("click", withError(startEmulator));
+    el.stopEmulatorBtn.addEventListener("click", withError(stopEmulator));
+    el.captureBtn.addEventListener("click", withError(captureEmulatorFrame));
+
+    el.mainImage.addEventListener("load", adjustStageByImage);
+
+    const applyFrontInput = () => applyRoiInputToRule("front");
+    const applyBackInput = () => applyRoiInputToRule("back");
+
+    el.roiFrontValue.addEventListener("change", applyFrontInput);
+    el.roiFrontValue.addEventListener("blur", applyFrontInput);
+    el.roiFrontValue.addEventListener("keydown", (event) => {
+      if (event.key === "Enter") {
+        event.preventDefault();
+        applyFrontInput();
+      }
+    });
+
+    el.roiBackValue.addEventListener("change", applyBackInput);
+    el.roiBackValue.addEventListener("blur", applyBackInput);
+    el.roiBackValue.addEventListener("keydown", (event) => {
+      if (event.key === "Enter") {
+        event.preventDefault();
+        applyBackInput();
+      }
+    });
+
+    el.createJsonBtn.addEventListener("click", withError(createJsonFile));
+    el.deleteJsonBtn.addEventListener("click", withError(deleteJsonFile));
+    if (el.ruleSearchInput) {
+      el.ruleSearchInput.addEventListener("input", () => {
+        state.ruleSearchKeyword = el.ruleSearchInput.value || "";
+        clearTestOverlay();
+        renderRuleList();
+      });
+    }
+
+    el.ruleType.addEventListener("change", () => {
+      if (state.ruleTypeLocked) {
+        el.ruleType.value = state.ruleType;
+        return;
+      }
+      setRuleType(el.ruleType.value);
+      state.rules = [defaultRuleByType(state.ruleType)];
+      state.activeRuleIndex = 0;
+      clearTestOverlay();
+      renderRuleList();
+      markDirty();
+      showMessage(`已切换规则类型: ${state.ruleType}`, "ok");
+    });
+
+    el.addRuleBtn.addEventListener("click", () => {
+      const rule = createRuleFromCurrentCanvas(state.ruleType);
+      rule.itemName = `item_${state.rules.length + 1}`;
+      if (state.ruleType === "image") {
+        rule.imageName = defaultImageNameForItem(rule.itemName);
+      }
+      state.rules.push(rule);
+      state.activeRuleIndex = state.rules.length - 1;
+      clearTestOverlay();
+      renderRuleList();
+      markDirty();
+      refreshActiveRuleImageExists().catch(() => {
+        // ignore
+      });
+    });
+
+    el.deleteRuleBtn.addEventListener("click", withError(deleteCurrentRule));
+
+    if (el.refreshRulesBtn) {
+      el.refreshRulesBtn.addEventListener("click", withError(refreshRulesList));
+    }
+
+    el.testRuleBtn.addEventListener("click", withError(testCurrentRule));
+    el.saveImageBtn.addEventListener("click", withError(saveImageCrop));
+    el.saveRulesBtn.addEventListener("click", withError(saveRules));
+    el.clearOutputBtn.addEventListener("click", clearOutput);
+  }
+
+
+  window.addEventListener("resize", () => {
+    adjustStageByImage();
+  });
+
+  function cleanup(reason = "page_unload") {
+    if (state.statusTimer) {
+      clearInterval(state.statusTimer);
+      state.statusTimer = null;
+    }
+    closeFrameSocket();
+    closeSession(reason, true).catch(() => {
+      // 页面关闭阶段忽略网络错误
+    });
+  }
+
+  async function init() {
+    setupRoiBox(el.roiFront);
+    setupRoiBox(el.roiBack);
+    await loadRuleSchemas();
+    bindEvents();
+
+    resetListMeta();
+    state.rules = [defaultRuleByType(state.ruleType)];
+    state.activeRuleIndex = 0;
+    renderRuleList();
+
+    await createSession();
+    await Promise.all([loadConfigs(), rebuildDirSelectors("", "", false)]);
+    await refreshImages();
+
+    updateRuleTypeLockView();
+    updateFieldVisibility();
+    updateRuleSearchVisibility();
+    setSourceMode("local");
+    updateRuleSourceActionVisibility();
+    clearOutput();
+    clearSaveStatus();
+
+    state.statusTimer = window.setInterval(() => {
+      refreshEmulatorStatus().catch((error) => {
+        console.error(error);
+        if (isInvalidSessionError(error)) {
+          recoverSessionAfterInvalid().catch((recoverError) => {
+            console.error(recoverError);
+          });
+        }
+      });
+    }, 2500);
+
+    window.addEventListener("pagehide", () => cleanup("pagehide"));
+    window.addEventListener("beforeunload", () => cleanup("beforeunload"));
+    showMessage("标注会话已就绪", "ok");
+  }
+
+  init().catch((error) => {
+    console.error(error);
+    showMessage(error.message || String(error), "error");
+  });
+})();

+ 8 - 0
module/server/web/annotator/static/js/center-panel.js

@@ -0,0 +1,8 @@
+(function () {
+  window.OASAnnotatorWidgets = window.OASAnnotatorWidgets || {};
+  window.OASAnnotatorWidgets["center-panel"] = {
+    mount: function () {
+      return true;
+    },
+  };
+})();

+ 591 - 0
module/server/web/annotator/static/js/layout-ui.js

@@ -0,0 +1,591 @@
+(function () {
+  const storageKey = "oas_annotator_layout_v3";
+  const themeKey = "oas_annotator_theme_v1";
+
+  const leftWindow = document.getElementById("leftWindow");
+  const rightWindow = document.getElementById("rightWindow");
+  const leftContent = document.getElementById("leftContent");
+  const rightContent = document.getElementById("rightContent");
+  const leftStack = document.getElementById("leftStack");
+  const rightStack = document.getElementById("rightStack");
+  const leftSplitter = document.getElementById("leftSplitter");
+  const rightSplitter = document.getElementById("rightSplitter");
+  const leftPanelSplitter = document.getElementById("leftPanelSplitter");
+  const rightPanelSplitter = document.getElementById("rightPanelSplitter");
+  const themeSelect = document.getElementById("themeSelect");
+  const appRoot = document.querySelector(".app");
+  const ruleEditorPanel = document.getElementById("ruleEditorPanel");
+  const ruleList = document.getElementById("ruleList");
+  const ruleListSplitter = document.getElementById("ruleListSplitter");
+
+  const outputDockToggle = document.getElementById("outputDockToggle");
+  const bottomOutputDock = document.getElementById("bottomOutputDock");
+  const bottomOutputResize = document.getElementById("bottomOutputResize");
+
+  if (
+    !leftWindow ||
+    !rightWindow ||
+    !leftContent ||
+    !rightContent ||
+    !leftStack ||
+    !rightStack ||
+    !leftSplitter ||
+    !rightSplitter ||
+    !leftPanelSplitter ||
+    !rightPanelSplitter
+  ) {
+    return;
+  }
+
+  const minLeftWidth = 280;
+  const maxLeftWidth = 760;
+  const minRightWidth = 320;
+  const maxRightWidth = 760;
+  const minPanelHeight = 140;
+  const minDockHeight = 140;
+  const minRuleListHeight = 220;
+
+  const leftButtons = Array.from(document.querySelectorAll(".rail-btn[data-window='left']"));
+  const rightButtons = Array.from(document.querySelectorAll(".rail-btn[data-window='right']"));
+
+  const leftOrder = leftButtons.map((btn) => btn.dataset.panelId).filter(Boolean);
+  const rightOrder = rightButtons.map((btn) => btn.dataset.panelId).filter(Boolean);
+
+  const defaultState = {
+    leftWidth: 360,
+    rightWidth: 460,
+    leftPanels: leftOrder.slice(),
+    rightPanels: rightOrder.slice(),
+    leftSplitRatio: 0.5,
+    rightSplitRatio: 0.5,
+    outputDockOpen: false,
+    outputDockHeight: 220,
+    ruleListHeight: minRuleListHeight,
+  };
+
+  const state = loadState();
+  normalizeState();
+
+  applyTheme(loadTheme());
+  applyWidths();
+  applySide("left");
+  applySide("right");
+  applyBottomDock();
+  updateRuleEditorCompactMode();
+  applyRuleListHeight();
+
+  if (ruleEditorPanel && typeof ResizeObserver !== "undefined") {
+    const observer = new ResizeObserver(() => {
+      updateRuleEditorCompactMode();
+    });
+    observer.observe(ruleEditorPanel);
+  }
+
+  leftButtons.forEach((button) => {
+    button.addEventListener("click", () => {
+      togglePanel("left", button.dataset.panelId || "");
+    });
+  });
+
+  rightButtons.forEach((button) => {
+    button.addEventListener("click", () => {
+      togglePanel("right", button.dataset.panelId || "");
+    });
+  });
+
+  leftSplitter.addEventListener("mousedown", (event) => {
+    if (!state.leftPanels.length) {
+      return;
+    }
+    startSideDrag("left", event);
+  });
+
+  rightSplitter.addEventListener("mousedown", (event) => {
+    if (!state.rightPanels.length) {
+      return;
+    }
+    startSideDrag("right", event);
+  });
+
+  leftPanelSplitter.addEventListener("mousedown", (event) => {
+    if (!leftStack.classList.contains("stack-two-open")) {
+      return;
+    }
+    startPanelDrag("left", event);
+  });
+
+  rightPanelSplitter.addEventListener("mousedown", (event) => {
+    if (!rightStack.classList.contains("stack-two-open")) {
+      return;
+    }
+    startPanelDrag("right", event);
+  });
+
+  if (ruleListSplitter && ruleList) {
+    ruleListSplitter.addEventListener("mousedown", (event) => {
+      startRuleListDrag(event);
+    });
+  }
+
+  if (outputDockToggle && bottomOutputDock) {
+    outputDockToggle.addEventListener("click", () => {
+      state.outputDockOpen = !state.outputDockOpen;
+      applyBottomDock();
+      saveState();
+      requestStageReflow();
+    });
+  }
+
+  if (bottomOutputResize && bottomOutputDock) {
+    bottomOutputResize.addEventListener("mousedown", (event) => {
+      if (!state.outputDockOpen) {
+        return;
+      }
+      startBottomDockDrag(event);
+    });
+  }
+
+  if (themeSelect) {
+    themeSelect.addEventListener("change", () => {
+      const theme = normalizeTheme(themeSelect.value);
+      applyTheme(theme);
+      saveTheme(theme);
+    });
+  }
+
+  window.addEventListener("resize", () => {
+    updatePanelHeights("left", false);
+    updatePanelHeights("right", false);
+    updateRuleEditorCompactMode();
+    applyRuleListHeight();
+    if (state.outputDockOpen) {
+      state.outputDockHeight = clamp(state.outputDockHeight, minDockHeight, getDockMaxHeight());
+      applyBottomDock();
+    }
+  });
+
+  function updateRuleEditorCompactMode() {
+    if (!ruleEditorPanel) {
+      return;
+    }
+    const compact = ruleEditorPanel.clientWidth > 0 && ruleEditorPanel.clientWidth < 430;
+    ruleEditorPanel.classList.toggle("rule-editor-compact", compact);
+  }
+
+  function clamp(value, min, max) {
+    return Math.max(min, Math.min(max, value));
+  }
+
+  function normalizeTheme(theme) {
+    return theme === "light" ? "light" : "dark";
+  }
+
+  function loadTheme() {
+    try {
+      const raw = window.localStorage.getItem(themeKey);
+      return normalizeTheme(raw || "dark");
+    } catch (_error) {
+      return "dark";
+    }
+  }
+
+  function saveTheme(theme) {
+    try {
+      window.localStorage.setItem(themeKey, normalizeTheme(theme));
+    } catch (_error) {
+      // ignore
+    }
+  }
+
+  function applyTheme(theme) {
+    const normalized = normalizeTheme(theme);
+    document.documentElement.setAttribute("data-theme", normalized);
+    if (themeSelect) {
+      themeSelect.value = normalized;
+    }
+  }
+
+  function loadState() {
+    try {
+      const raw = window.localStorage.getItem(storageKey);
+      if (!raw) {
+        return { ...defaultState };
+      }
+      const parsed = JSON.parse(raw);
+      return {
+        leftWidth: Number(parsed.leftWidth) || defaultState.leftWidth,
+        rightWidth: Number(parsed.rightWidth) || defaultState.rightWidth,
+        leftPanels: Array.isArray(parsed.leftPanels) ? parsed.leftPanels.slice() : defaultState.leftPanels.slice(),
+        rightPanels: Array.isArray(parsed.rightPanels) ? parsed.rightPanels.slice() : defaultState.rightPanels.slice(),
+        leftSplitRatio: Number(parsed.leftSplitRatio),
+        rightSplitRatio: Number(parsed.rightSplitRatio),
+        outputDockOpen: Boolean(parsed.outputDockOpen),
+        outputDockHeight: Number(parsed.outputDockHeight),
+        ruleListHeight: Number(parsed.ruleListHeight),
+      };
+    } catch (_error) {
+      return { ...defaultState };
+    }
+  }
+
+  function saveState() {
+    try {
+      window.localStorage.setItem(
+        storageKey,
+        JSON.stringify({
+          leftWidth: state.leftWidth,
+          rightWidth: state.rightWidth,
+          leftPanels: state.leftPanels,
+          rightPanels: state.rightPanels,
+          leftSplitRatio: state.leftSplitRatio,
+          rightSplitRatio: state.rightSplitRatio,
+          outputDockOpen: state.outputDockOpen,
+          outputDockHeight: state.outputDockHeight,
+          ruleListHeight: state.ruleListHeight,
+        }),
+      );
+    } catch (_error) {
+      // ignore
+    }
+  }
+
+  function normalizeState() {
+    state.leftWidth = clamp(state.leftWidth, minLeftWidth, maxLeftWidth);
+    state.rightWidth = clamp(state.rightWidth, minRightWidth, maxRightWidth);
+    state.leftPanels = leftOrder.filter((id) => state.leftPanels.includes(id));
+    state.rightPanels = rightOrder.filter((id) => state.rightPanels.includes(id));
+
+    if (state.leftPanels.length === 0) {
+      state.leftPanels = leftOrder.slice();
+    }
+    if (state.rightPanels.length === 0) {
+      state.rightPanels = rightOrder.slice();
+    }
+
+    state.leftSplitRatio = Number.isFinite(state.leftSplitRatio) ? clamp(state.leftSplitRatio, 0.2, 0.8) : 0.5;
+    state.rightSplitRatio = Number.isFinite(state.rightSplitRatio) ? clamp(state.rightSplitRatio, 0.2, 0.8) : 0.5;
+    state.outputDockHeight = Number.isFinite(state.outputDockHeight) ? clamp(state.outputDockHeight, minDockHeight, getDockMaxHeight()) : 220;
+    state.ruleListHeight = Number.isFinite(state.ruleListHeight) ? clamp(state.ruleListHeight, minRuleListHeight, getRuleListMaxHeight()) : minRuleListHeight;
+  }
+
+  function applyWidths() {
+    leftContent.style.width = `${state.leftWidth}px`;
+    rightContent.style.width = `${state.rightWidth}px`;
+  }
+
+  function getDockMaxHeight() {
+    return Math.max(minDockHeight, Math.floor(window.innerHeight * 0.72));
+  }
+
+  function getRuleListMaxHeight() {
+    if (!ruleEditorPanel) {
+      return 1200;
+    }
+    const panelHeight = Math.max(0, ruleEditorPanel.clientHeight || 0);
+    if (panelHeight <= 0) {
+      return 1200;
+    }
+    return Math.max(minRuleListHeight, Math.min(1200, Math.floor(panelHeight * 1.2)));
+  }
+
+  function applyRuleListHeight() {
+    if (!ruleList) {
+      return;
+    }
+    state.ruleListHeight = clamp(state.ruleListHeight, minRuleListHeight, getRuleListMaxHeight());
+    ruleList.style.height = `${Math.round(state.ruleListHeight)}px`;
+  }
+
+  function applyBottomDockInset(open) {
+    const dockOpen = Boolean(open);
+    const inset = dockOpen ? Math.max(minDockHeight, state.outputDockHeight) : 0;
+    document.documentElement.style.setProperty("--bottom-dock-space", `${inset}px`);
+    if (appRoot) {
+      appRoot.classList.toggle("dock-open", dockOpen);
+    }
+  }
+
+  function applyBottomDock() {
+    if (!bottomOutputDock || !outputDockToggle) {
+      return;
+    }
+
+    const open = Boolean(state.outputDockOpen);
+    outputDockToggle.classList.toggle("active", open);
+    bottomOutputDock.classList.toggle("hidden", !open);
+    applyBottomDockInset(open);
+
+    if (!open) {
+      return;
+    }
+
+    state.outputDockHeight = clamp(state.outputDockHeight, minDockHeight, getDockMaxHeight());
+    bottomOutputDock.style.height = `${state.outputDockHeight}px`;
+    applyBottomDockInset(true);
+  }
+
+  function togglePanel(side, panelId) {
+    if (!panelId) {
+      return;
+    }
+
+    const key = side === "left" ? "leftPanels" : "rightPanels";
+    const order = side === "left" ? leftOrder : rightOrder;
+    const values = state[key].slice();
+    const index = values.indexOf(panelId);
+
+    if (index >= 0) {
+      values.splice(index, 1);
+    } else {
+      values.push(panelId);
+    }
+
+    state[key] = order.filter((id) => values.includes(id));
+    applySide(side);
+    updateRuleEditorCompactMode();
+    requestStageReflow();
+    saveState();
+  }
+
+  function applySide(side) {
+    const stack = side === "left" ? leftStack : rightStack;
+    const windowEl = side === "left" ? leftWindow : rightWindow;
+    const splitter = side === "left" ? leftSplitter : rightSplitter;
+    const buttons = side === "left" ? leftButtons : rightButtons;
+    const panelSplitter = side === "left" ? leftPanelSplitter : rightPanelSplitter;
+    const key = side === "left" ? "leftPanels" : "rightPanels";
+
+    const activePanels = state[key];
+    const activeSet = new Set(activePanels);
+    const open = activePanels.length > 0;
+
+    windowEl.classList.toggle("collapsed", !open);
+    splitter.classList.toggle("disabled", !open);
+    stack.classList.toggle("stack-icon-mode", open);
+
+    buttons.forEach((button) => {
+      const id = button.dataset.panelId || "";
+      button.classList.toggle("active", activeSet.has(id));
+    });
+
+    const panelList = Array.from(stack.children).filter((node) => node.classList && node.classList.contains("panel"));
+    panelList.forEach((panel) => {
+      const isActive = activeSet.has(panel.id);
+      panel.classList.toggle("panel-slot-hidden", !isActive);
+      panel.classList.toggle("panel-slot-active", isActive);
+      panel.classList.remove("top-slot", "bottom-slot");
+      panel.style.removeProperty("height");
+      panel.style.removeProperty("order");
+    });
+
+    panelSplitter.classList.add("disabled");
+    panelSplitter.style.removeProperty("order");
+    stack.classList.remove("stack-two-open");
+
+    if (!open) {
+      requestStageReflow();
+      return;
+    }
+
+    if (activePanels.length === 1) {
+      const panel = document.getElementById(activePanels[0]);
+      if (panel) {
+        panel.style.order = "1";
+      }
+      return;
+    }
+
+    const topPanel = document.getElementById(activePanels[0]);
+    const bottomPanel = document.getElementById(activePanels[1]);
+
+    if (!topPanel || !bottomPanel) {
+      return;
+    }
+
+    stack.classList.add("stack-two-open");
+    panelSplitter.classList.remove("disabled");
+
+    topPanel.classList.add("top-slot");
+    bottomPanel.classList.add("bottom-slot");
+
+    topPanel.style.order = "1";
+    panelSplitter.style.order = "2";
+    bottomPanel.style.order = "3";
+
+    updatePanelHeights(side, false);
+  }
+
+  function updatePanelHeights(side, shouldReflow) {
+    const stack = side === "left" ? leftStack : rightStack;
+    const panelSplitter = side === "left" ? leftPanelSplitter : rightPanelSplitter;
+    const ratioKey = side === "left" ? "leftSplitRatio" : "rightSplitRatio";
+
+    if (!stack.classList.contains("stack-two-open")) {
+      return;
+    }
+
+    const topPanel = stack.querySelector(".panel-slot-active.top-slot");
+    const bottomPanel = stack.querySelector(".panel-slot-active.bottom-slot");
+    if (!topPanel || !bottomPanel) {
+      return;
+    }
+
+    const splitterHeight = panelSplitter.offsetHeight || 8;
+    const totalHeight = stack.clientHeight;
+    const available = Math.max(minPanelHeight * 2, totalHeight - splitterHeight);
+
+    let ratio = Number(state[ratioKey]);
+    ratio = Number.isFinite(ratio) ? clamp(ratio, 0.2, 0.8) : 0.5;
+
+    let topHeight = Math.round(available * ratio);
+    topHeight = clamp(topHeight, minPanelHeight, available - minPanelHeight);
+    const bottomHeight = available - topHeight;
+
+    state[ratioKey] = topHeight / available;
+
+    topPanel.style.height = `${topHeight}px`;
+    bottomPanel.style.height = `${bottomHeight}px`;
+
+    if (shouldReflow) {
+      requestStageReflow();
+    }
+  }
+
+  function startSideDrag(side, event) {
+    event.preventDefault();
+
+    const startX = event.clientX;
+    const startWidth = side === "left" ? state.leftWidth : state.rightWidth;
+
+    document.body.classList.add("layout-resizing");
+
+    const onMove = (moveEvent) => {
+      const delta = moveEvent.clientX - startX;
+      if (side === "left") {
+        state.leftWidth = clamp(startWidth + delta, minLeftWidth, maxLeftWidth);
+        leftContent.style.width = `${state.leftWidth}px`;
+      } else {
+        state.rightWidth = clamp(startWidth - delta, minRightWidth, maxRightWidth);
+        rightContent.style.width = `${state.rightWidth}px`;
+      }
+      updateRuleEditorCompactMode();
+    };
+
+    const onUp = () => {
+      document.body.classList.remove("layout-resizing");
+      document.removeEventListener("mousemove", onMove);
+      document.removeEventListener("mouseup", onUp);
+      saveState();
+      requestStageReflow();
+    };
+
+    document.addEventListener("mousemove", onMove);
+    document.addEventListener("mouseup", onUp);
+  }
+
+  function startPanelDrag(side, event) {
+    event.preventDefault();
+
+    const stack = side === "left" ? leftStack : rightStack;
+    const panelSplitter = side === "left" ? leftPanelSplitter : rightPanelSplitter;
+    const ratioKey = side === "left" ? "leftSplitRatio" : "rightSplitRatio";
+
+    document.body.classList.add("layout-resizing");
+
+    const onMove = (moveEvent) => {
+      const rect = stack.getBoundingClientRect();
+      const splitterHeight = panelSplitter.offsetHeight || 8;
+      const available = Math.max(minPanelHeight * 2, rect.height - splitterHeight);
+
+      const cursorY = clamp(moveEvent.clientY - rect.top, 0, rect.height);
+      const ratio = clamp(cursorY / Math.max(1, available), 0.2, 0.8);
+
+      state[ratioKey] = ratio;
+      updatePanelHeights(side, false);
+    };
+
+    const onUp = () => {
+      document.body.classList.remove("layout-resizing");
+      document.removeEventListener("mousemove", onMove);
+      document.removeEventListener("mouseup", onUp);
+      saveState();
+      requestStageReflow();
+    };
+
+    document.addEventListener("mousemove", onMove);
+    document.addEventListener("mouseup", onUp);
+  }
+
+  function startRuleListDrag(event) {
+    if (!ruleList) {
+      return;
+    }
+
+    event.preventDefault();
+
+    const startY = event.clientY;
+    const startHeight = ruleList.getBoundingClientRect().height || state.ruleListHeight || minRuleListHeight;
+
+    document.body.classList.add("rule-list-resizing");
+
+    const onMove = (moveEvent) => {
+      const delta = moveEvent.clientY - startY;
+      state.ruleListHeight = clamp(startHeight + delta, minRuleListHeight, getRuleListMaxHeight());
+      ruleList.style.height = `${Math.round(state.ruleListHeight)}px`;
+    };
+
+    const onUp = () => {
+      document.body.classList.remove("rule-list-resizing");
+      document.removeEventListener("mousemove", onMove);
+      document.removeEventListener("mouseup", onUp);
+      saveState();
+    };
+
+    document.addEventListener("mousemove", onMove);
+    document.addEventListener("mouseup", onUp);
+  }
+
+  function startBottomDockDrag(event) {
+    if (!bottomOutputDock) {
+      return;
+    }
+
+    event.preventDefault();
+
+    const startY = event.clientY;
+    const startHeight = state.outputDockHeight;
+
+    document.body.classList.add("bottom-dock-resizing");
+
+    const onMove = (moveEvent) => {
+      const delta = startY - moveEvent.clientY;
+      state.outputDockHeight = clamp(startHeight + delta, minDockHeight, getDockMaxHeight());
+      bottomOutputDock.style.height = `${state.outputDockHeight}px`;
+      applyBottomDockInset(true);
+    };
+
+    const onUp = () => {
+      document.body.classList.remove("bottom-dock-resizing");
+      document.removeEventListener("mousemove", onMove);
+      document.removeEventListener("mouseup", onUp);
+      saveState();
+      requestStageReflow();
+    };
+
+    document.addEventListener("mousemove", onMove);
+    document.addEventListener("mouseup", onUp);
+  }
+
+  function requestStageReflow() {
+    window.requestAnimationFrame(() => {
+      window.dispatchEvent(new Event("resize"));
+    });
+  }
+})();
+
+
+
+
+
+
+

+ 8 - 0
module/server/web/annotator/static/js/left-window.js

@@ -0,0 +1,8 @@
+(function () {
+  window.OASAnnotatorWidgets = window.OASAnnotatorWidgets || {};
+  window.OASAnnotatorWidgets["left-window"] = {
+    mount: function () {
+      return true;
+    },
+  };
+})();

+ 83 - 0
module/server/web/annotator/static/js/main.js

@@ -0,0 +1,83 @@
+(function () {
+  const STATIC_PREFIX = "/tool/annotator/static";
+
+  const widgets = [
+    { mountId: "topbarMount", name: "topbar", script: "topbar.js" },
+    { mountId: "leftWindowMount", name: "left-window", script: "left-window.js" },
+    { mountId: "centerPanelMount", name: "center-panel", script: "center-panel.js" },
+    { mountId: "rightWindowMount", name: "right-window", script: "right-window.js" },
+  ];
+
+  function ensureRegistry() {
+    if (!window.OASAnnotatorWidgets) {
+      window.OASAnnotatorWidgets = {};
+    }
+    return window.OASAnnotatorWidgets;
+  }
+
+  async function fetchWidget(name) {
+    const response = await fetch(`${STATIC_PREFIX}/widget/${name}.html`, { cache: "no-cache" });
+    if (!response.ok) {
+      throw new Error(`加载组件失败: ${name} (${response.status})`);
+    }
+    return response.text();
+  }
+
+  async function mountWidgets() {
+    for (const widget of widgets) {
+      const mount = document.getElementById(widget.mountId);
+      if (!mount) {
+        throw new Error(`缺少组件挂载点: ${widget.mountId}`);
+      }
+      mount.innerHTML = await fetchWidget(widget.name);
+    }
+  }
+
+  function loadScript(path) {
+    return new Promise((resolve, reject) => {
+      const script = document.createElement("script");
+      script.src = path;
+      script.async = false;
+      script.onload = () => resolve();
+      script.onerror = () => reject(new Error(`脚本加载失败: ${path}`));
+      document.body.appendChild(script);
+    });
+  }
+
+  async function loadComponentScripts() {
+    for (const widget of widgets) {
+      await loadScript(`${STATIC_PREFIX}/js/${widget.script}`);
+    }
+
+    const registry = ensureRegistry();
+    for (const widget of widgets) {
+      const component = registry[widget.name];
+      if (component && typeof component.mount === "function") {
+        component.mount();
+      }
+    }
+  }
+
+  async function loadRuntimeScripts() {
+    // 保持原有初始化顺序:先布局脚本,再业务脚本。
+    await loadScript(`${STATIC_PREFIX}/js/layout-ui.js`);
+    await loadScript(`${STATIC_PREFIX}/js/app.js`);
+  }
+
+  function showBootError(error) {
+    console.error(error);
+    const mount = document.createElement("pre");
+    mount.className = "small-output";
+    mount.textContent = `页面初始化失败: ${error.message || String(error)}`;
+    document.body.appendChild(mount);
+  }
+
+  async function bootstrap() {
+    ensureRegistry();
+    await mountWidgets();
+    await loadComponentScripts();
+    await loadRuntimeScripts();
+  }
+
+  bootstrap().catch(showBootError);
+})();

+ 8 - 0
module/server/web/annotator/static/js/right-window.js

@@ -0,0 +1,8 @@
+(function () {
+  window.OASAnnotatorWidgets = window.OASAnnotatorWidgets || {};
+  window.OASAnnotatorWidgets["right-window"] = {
+    mount: function () {
+      return true;
+    },
+  };
+})();

+ 8 - 0
module/server/web/annotator/static/js/topbar.js

@@ -0,0 +1,8 @@
+(function () {
+  window.OASAnnotatorWidgets = window.OASAnnotatorWidgets || {};
+  window.OASAnnotatorWidgets["topbar"] = {
+    mount: function () {
+      return true;
+    },
+  };
+})();

+ 40 - 0
module/server/web/annotator/static/widget/center-panel.html

@@ -0,0 +1,40 @@
+<section class="panel center-panel" id="centerPanel">
+  <h2>ROI 画布</h2>
+  <div id="stageWrap" class="stage-wrap">
+    <div class="stage-canvas-holder">
+      <div id="imageStage" class="image-stage">
+        <img id="mainImage" alt="标注图片" />
+        <div id="noImagePlaceholder" class="no-image">空</div>
+        <div id="roiBack" class="roi roi-back">
+          <span class="tag">Back</span>
+          <span class="resize-handle resize-handle-nw" data-resize-dir="nw"></span>
+          <span class="resize-handle resize-handle-ne" data-resize-dir="ne"></span>
+          <span class="resize-handle resize-handle-sw" data-resize-dir="sw"></span>
+          <span class="resize-handle resize-handle-se" data-resize-dir="se"></span>
+        </div>
+        <div id="roiFront" class="roi roi-front">
+          <span class="tag">Front</span>
+          <span class="resize-handle resize-handle-nw" data-resize-dir="nw"></span>
+          <span class="resize-handle resize-handle-ne" data-resize-dir="ne"></span>
+          <span class="resize-handle resize-handle-sw" data-resize-dir="sw"></span>
+          <span class="resize-handle resize-handle-se" data-resize-dir="se"></span>
+        </div>
+        <div id="testRoiBack" class="roi roi-test-back hidden"><span class="tag">TestBack</span></div>
+        <div id="testRoiFront" class="roi roi-test-front hidden"><span class="tag">TestFront</span></div>
+      </div>
+    </div>
+  </div>
+  <div class="roi-values">
+    <label>roiFront<input id="roiFrontValue" type="text"></label>
+    <label>roiBack<input id="roiBackValue" type="text"></label>
+  </div>
+
+  <section class="panel output-panel center-output-panel" id="centerOutputPanel">
+    <div class="output-header">
+      <h3>输出</h3>
+      <button id="clearOutputBtn" type="button">清空输出</button>
+    </div>
+    <pre id="outputLog" class="output-log"></pre>
+  </section>
+</section>
+

+ 21 - 0
module/server/web/annotator/static/widget/component-manifest.md

@@ -0,0 +1,21 @@
+# Annotator 组件清单
+
+## topbar
+- 原始 HTML 位置: `module/server/web/annotator/index.html` 顶部 `<header class="topbar">`
+- 原始 CSS 位置: `module/server/web/annotator/static/style.css` 中 `.topbar*` 规则
+- 原始 JS 位置: `module/server/web/annotator/static/layout-ui.js`(主题切换与头部控件)
+
+## left-window
+- 原始 HTML 位置: `module/server/web/annotator/index.html` 左侧工具栏 `<aside id="leftWindow">`
+- 原始 CSS 位置: `style.css` 中 `.tool-window-left`、`.image-list`、`.image-item`、左侧 stack 相关规则
+- 原始 JS 位置: `app.js`(图片上传/列表/模拟器来源)+ `layout-ui.js`(左侧布局拖拽)
+
+## center-panel
+- 原始 HTML 位置: `index.html` 中 `<section class="panel center-panel">`
+- 原始 CSS 位置: `style.css` 中 `.center-panel`、`.stage-wrap`、`.roi*`、`.output*` 规则
+- 原始 JS 位置: `app.js`(ROI、画布、输出面板)
+
+## right-window
+- 原始 HTML 位置: `index.html` 右侧工具栏 `<aside id="rightWindow">`
+- 原始 CSS 位置: `style.css` 中 `.tool-window-right`、`.dir-selectors`、`.rule-*`、`.form-grid` 规则
+- 原始 JS 位置: `app.js`(规则编辑与保存)+ `layout-ui.js`(右侧布局拖拽)

+ 60 - 0
module/server/web/annotator/static/widget/left-window.html

@@ -0,0 +1,60 @@
+<aside class="tool-window tool-window-left" id="leftWindow">
+  <div class="icon-rail icon-rail-left" id="leftRail">
+    <button type="button" class="rail-btn" data-window="left" data-panel-id="dataSourcePanel" title="数据来源">来源</button>
+    <button type="button" class="rail-btn" data-window="left" data-panel-id="sessionImagesPanel" title="图片">图片</button>
+  </div>
+  <div class="tool-content tool-content-left" id="leftContent">
+    <aside class="stack stack-left" id="leftStack">
+      <section class="panel panel-top panel-scroll-box" id="dataSourcePanel">
+        <h2>数据来源</h2>
+        <div class="panel-scroll-body">
+          <label>来源模式
+            <select id="sourceMode">
+              <option value="local" selected>本地图片</option>
+              <option value="emulator">模拟器画面</option>
+            </select>
+          </label>
+
+          <div id="localControls" class="block">
+            <label>上传图片(支持多选)
+              <input id="imageUpload" type="file" accept="image/*" multiple>
+            </label>
+            <button id="uploadBtn" type="button">上传</button>
+          </div>
+
+          <div id="emulatorControls" class="block hidden">
+            <label>脚本配置
+              <select id="configName"></select>
+            </label>
+            <label>帧率(1-10)
+              <input id="frameRate" type="number" min="1" max="10" value="2">
+            </label>
+            <div class="row">
+              <button id="startEmulatorBtn" type="button">连接模拟器</button>
+              <button id="stopEmulatorBtn" type="button">停止连接</button>
+            </div>
+            <div class="preview-card">
+              <img id="emulatorPreview" alt="模拟器预览" />
+            </div>
+            <button id="captureBtn" type="button">截取当前帧到图片列表</button>
+            <pre id="emulatorStatus" class="small-output"></pre>
+          </div>
+        </div>
+      </section>
+
+      <div class="panel-height-splitter" id="leftPanelSplitter" aria-hidden="true"></div>
+
+      <section class="panel panel-fill panel-lock-scroll" id="sessionImagesPanel">
+        <h2>图片</h2>
+        <div class="row">
+          <button id="refreshImagesBtn" type="button">刷新</button>
+          <button id="removeImagesBtn" type="button" class="danger-btn">移除</button>
+          <button id="clearImagesBtn" type="button" class="danger-btn">清空</button>
+        </div>
+        <div class="selected-info">已选中: <span id="selectedImageCount">0</span></div>
+        <div id="imageList" class="image-list"></div>
+      </section>
+    </aside>
+  </div>
+</aside>
+<div class="edge-splitter edge-splitter-left" id="leftSplitter" aria-hidden="true"></div>

+ 60 - 0
module/server/web/annotator/static/widget/right-window.html

@@ -0,0 +1,60 @@
+<div class="edge-splitter edge-splitter-right" id="rightSplitter" aria-hidden="true"></div>
+<aside class="tool-window tool-window-right" id="rightWindow">
+  <div class="tool-content tool-content-right" id="rightContent">
+    <aside class="stack stack-right" id="rightStack">
+      <section class="panel panel-top panel-scroll-box" id="ruleSourcePanel">
+        <h2>文件</h2>
+        <div class="panel-scroll-body">
+          <div id="dirSelectors" class="dir-selectors breadcrumb"></div>
+
+          <div class="row">
+            <input id="newJsonName" type="text" placeholder="输入新 JSON 名称" />
+            <button id="createJsonBtn" type="button">新增</button>
+            <button id="deleteJsonBtn" type="button" class="danger-btn">删除</button>
+          </div>
+        </div>
+      </section>
+
+      <div class="panel-height-splitter" id="rightPanelSplitter" aria-hidden="true"></div>
+
+      <section class="panel panel-fill rule-editor-panel" id="ruleEditorPanel">
+        <h2>规则</h2>
+        <div class="rule-editor-scroll">
+          <label>规则类型
+            <select id="ruleType"></select>
+          </label>
+
+          <div id="listMetaBox" class="block hidden">
+            <div id="listMetaFields" class="form-grid"></div>
+          </div>
+
+          <div class="row">
+            <button id="addRuleBtn" type="button">新增</button>
+            <button id="deleteRuleBtn" type="button">删除</button>
+            <button id="refreshRulesBtn" type="button">刷新</button>
+          </div>
+          <div id="ruleSearchBox" class="rule-search-box hidden">
+            <input id="ruleSearchInput" type="text" placeholder="按 itemName 搜索规则项" autocomplete="off" />
+          </div>
+          <div id="ruleList" class="rule-list"></div>
+
+          <div class="rule-list-splitter" id="ruleListSplitter" aria-hidden="true"></div>
+
+          <div class="rule-detail-scroll">
+            <div class="form-grid" id="ruleFields"></div>
+
+            <div class="row action-row">
+              <button id="saveImageBtn" type="button" class="hidden">裁剪</button>
+              <button id="saveRulesBtn" type="button">保存</button>
+              <button id="testRuleBtn" type="button" class="hidden">测试</button>
+            </div>
+          </div>
+        </div>
+      </section>
+    </aside>
+  </div>
+  <div class="icon-rail icon-rail-right" id="rightRail">
+    <button type="button" class="rail-btn" data-window="right" data-panel-id="ruleSourcePanel" title="文件">文件</button>
+    <button type="button" class="rail-btn" data-window="right" data-panel-id="ruleEditorPanel" title="规则">规则</button>
+  </div>
+</aside>

+ 12 - 0
module/server/web/annotator/static/widget/topbar.html

@@ -0,0 +1,12 @@
+<header class="topbar">
+  <h1>OAS Web 标注工具</h1>
+  <div class="topbar-actions">
+    <label class="theme-switch">
+      <select id="themeSelect">
+        <option value="dark">Dark</option>
+        <option value="light">Light</option>
+      </select>
+    </label>
+    <div class="session-meta"><span>Session:</span> <code id="sessionId">-</code></div>
+  </div>
+</header>