Compare commits

..
18 changed files with 499 additions and 141 deletions
+8 -3
View File
@@ -128,14 +128,19 @@ class DashboardService(
profile_supplier=self._resolved_llm_profile,
)
self.screener.ensure_builtin_strategies()
self._background_stop = threading.Event()
self._background_thread = self.jobs.start_scheduler(
def start_background_jobs(self) -> threading.Thread:
return self.jobs.start_scheduler(
self._background_refresh_tick,
self._background_stop,
interval_seconds=5,
initial_delay_seconds=3,
)
def stop_background_jobs(self, timeout_seconds: float = 5) -> bool:
scheduler_stopped = self.jobs.stop_scheduler(timeout_seconds)
workers_stopped = self.jobs.wait_for_idle(timeout_seconds)
return scheduler_stopped and workers_stopped
def _load_system_credentials(self, environment: dict[str, str]) -> dict[str, Any]:
encrypted = self.database.get_system_setting("credentials")
+4 -3
View File
@@ -16,12 +16,13 @@ def main(handler_class: type[Any] | None = None, service: Any | None = None) ->
parser.add_argument("--port", type=int, default=8765)
args = parser.parse_args()
server = ThreadingHTTPServer((args.host, args.port), handler_class)
print(f"Xiaobai Review Web is running at http://{args.host}:{args.port}")
print("Press Ctrl+C to stop.")
try:
service.start_background_jobs()
print(f"Xiaobai Review Web is running at http://{args.host}:{args.port}")
print("Press Ctrl+C to stop.")
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
service._background_stop.set()
service.stop_background_jobs()
server.server_close()
+1
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import copy
import json
import re
import secrets
from datetime import date, datetime, timedelta
from typing import Any
+37 -19
View File
@@ -18,6 +18,9 @@ class InProcessJobRunner:
self.repository = repository
self._locks: dict[str, threading.Lock] = {}
self._locks_guard = threading.Lock()
self._scheduler_guard = threading.Lock()
self._scheduler_stop = threading.Event()
self._scheduler_thread: threading.Thread | None = None
def submit(
self, job_id: str, idempotency_key: str, action: JobAction,
@@ -52,27 +55,42 @@ class InProcessJobRunner:
return True
def start_scheduler(
self, callback: Callable[[], None], stop_event: threading.Event,
interval_seconds: float, initial_delay_seconds: float = 0,
self, callback: Callable[[], None], interval_seconds: float,
initial_delay_seconds: float = 0,
) -> threading.Thread:
def schedule_loop() -> None:
if stop_event.wait(initial_delay_seconds):
return
while not stop_event.is_set():
try:
callback()
except Exception:
# Submitted jobs persist their own failures; the scheduler must stay alive.
pass
stop_event.wait(interval_seconds)
with self._scheduler_guard:
current = self._scheduler_thread
if current is not None and current.is_alive():
return current
self._scheduler_stop.clear()
thread = threading.Thread(
target=schedule_loop,
name="background-job-scheduler",
daemon=True,
)
thread.start()
return thread
def schedule_loop() -> None:
if self._scheduler_stop.wait(initial_delay_seconds):
return
while not self._scheduler_stop.is_set():
try:
callback()
except Exception:
# Submitted jobs persist failures; the scheduler must stay alive.
pass
self._scheduler_stop.wait(interval_seconds)
thread = threading.Thread(
target=schedule_loop,
name="background-job-scheduler",
daemon=True,
)
self._scheduler_thread = thread
thread.start()
return thread
def stop_scheduler(self, timeout_seconds: float = 5) -> bool:
with self._scheduler_guard:
thread = self._scheduler_thread
self._scheduler_stop.set()
if thread is not None and thread is not threading.current_thread():
thread.join(max(0, timeout_seconds))
return thread is None or not thread.is_alive()
def wait_for_idle(self, timeout_seconds: float = 5) -> bool:
deadline = time.monotonic() + max(0, timeout_seconds)
+1
View File
@@ -4,6 +4,7 @@ from datetime import datetime, timezone
from typing import Any
from urllib.parse import urlparse
from backend.bootstrap.config import validate_text
from backend.features.screener.compiler import LLMCompilerError, test_llm_connection
+10 -10
View File
@@ -309,13 +309,13 @@
"code_hotspots": [
{
"path": "frontend/styles/styles.css",
"bytes": 361776,
"lines": 15465
"bytes": 360238,
"lines": 15385
},
{
"path": "frontend/styles/redesign-v2.css",
"bytes": 263539,
"lines": 8570
"bytes": 262826,
"lines": 8554
},
{
"path": "frontend/index.html",
@@ -344,8 +344,8 @@
},
{
"path": "frontend/styles/renovation.css",
"bytes": 83949,
"lines": 1553
"bytes": 83812,
"lines": 1550
},
{
"path": "frontend/pages/heaven/page.css",
@@ -354,8 +354,8 @@
},
{
"path": "backend/features/heaven/service.py",
"bytes": 63123,
"lines": 1303
"bytes": 63138,
"lines": 1304
},
{
"path": "backend/features/market/insights.py",
@@ -374,8 +374,8 @@
},
{
"path": "backend/application.py",
"bytes": 47552,
"lines": 1087
"bytes": 47769,
"lines": 1092
},
{
"path": "frontend/styles/theme.css",
-16
View File
@@ -751,9 +751,6 @@ body.sidebar-collapsed .status-bar { left: 64px; }
min-height: 50px;
padding: 6px 8px;
}
.market-tape { display: none; }
.header-actions { width: 100%; }
.header-command-group { position: absolute; }
.module-nav,
body.sidebar-collapsed .module-nav {
inset: auto 0 0;
@@ -769,14 +766,6 @@ body.sidebar-collapsed .status-bar { left: 64px; }
border: 0;
border-top: 1px solid var(--r2-line);
}
.sidebar-brand,
.module-nav .nav-group-label,
.sidebar-collapse-button,
.module-nav .market-sub-tab { display: none; }
.module-nav .nav-group,
body.sidebar-collapsed .module-nav .nav-group { display: contents; }
.module-nav .module-tab,
body.sidebar-collapsed .module-nav .module-tab { display: none; }
.module-nav .module-tab.mobile-primary-tab,
body.sidebar-collapsed .module-nav .module-tab.mobile-primary-tab {
min-height: 54px;
@@ -789,12 +778,8 @@ body.sidebar-collapsed .status-bar { left: 64px; }
padding: 3px 2px;
font-size: 10px;
}
.module-nav .module-tab.mobile-primary-tab span { display: inline; }
.app-main { width: 100%; margin: 0; padding: 0 8px 16px; overflow: visible; }
.overview-strip { margin-inline: -8px; padding-inline: 8px; overflow-x: auto; }
.overview-strip .metric:nth-of-type(n + 4),
.overview-strip .metric-wide { display: none; }
.overview-toggle { display: none; }
.redesigned-page-head { align-items: flex-start; flex-wrap: wrap; margin-top: 12px; }
.redesigned-page-head .section-title-group { width: 100%; flex-wrap: wrap; }
.redesigned-page-head .toolbar-controls { width: 100%; margin-left: 0; justify-content: space-between; }
@@ -4318,7 +4303,6 @@ body.sidebar-collapsed .status-bar { left: 64px; }
#dragonView .dragon-operation-table .dragon-col-direction { width: 72px; }
#dragonView .dragon-operation-table .dragon-col-number { width: 82px; }
#dragonView .dragon-operation-table .dragon-col-seat { width: 190px; }
#dragonView .dragon-operation-table .dragon-col-reason { width: auto; }
#dragonView .dragon-operation-table :is(th, td).row-number { padding-inline: 8px; text-align: center; }
#dragonView .dragon-operation-table td.stock-code { font-variant-numeric: tabular-nums; }
#dragonView .dragon-operation-table thead th { position: sticky; top: 0; z-index: 2; background: #fafbfc; }
-3
View File
@@ -127,7 +127,6 @@ body.sidebar-collapsed .app-main { margin-left: 0; }
background: transparent;
}
.overview-strip .sentiment-block { padding-left: 0; }
.overview-strip .sentiment-gauge { width: 26px; height: 26px; flex: 0 0 26px; border-width: 2px; font-size: 10px; }
.overview-strip .sentiment-text { font-size: 12px; white-space: nowrap; }
.overview-strip .metric-label { color: var(--text-tertiary); font-size: 10.5px; white-space: nowrap; }
@@ -160,8 +159,6 @@ body.sidebar-collapsed .app-main { margin-left: 0; }
.overview-strip[data-overview-expanded="true"] .metric { min-height: 76px; align-items: flex-start; justify-content: center; flex-direction: column; gap: 4px; }
.overview-strip[data-overview-expanded="true"] .sentiment-block { flex-direction: row; justify-content: flex-start; align-items: center; }
.overview-strip[data-overview-expanded="true"] .sentiment-gauge { width: 48px; height: 48px; flex-basis: 48px; font-size: 13px; }
.overview-strip[data-overview-expanded="true"] .metric-value { font-size: 18px; }
/* Page frame and shared information architecture. */
.workspace-view,
body[data-active-view="screenerView"] .workspace-view,
-80
View File
@@ -666,10 +666,6 @@ time {
box-shadow: var(--shadow-soft);
}
.workspace-view.active-view {
display: block;
}
.workspace-view.active-view.view-entering {
animation: view-enter var(--motion-medium) var(--ease-out) both;
}
@@ -4745,10 +4741,6 @@ textarea {
outline-color: rgba(29, 101, 193, 0.48);
}
body.sidebar-collapsed {
grid-template-columns: 64px minmax(0, 1fr);
}
body.sidebar-collapsed .module-nav {
width: 64px;
padding-right: 7px;
@@ -4783,10 +4775,6 @@ body.sidebar-collapsed .sidebar-collapse-button .lucide {
}
@media (min-width: 721px) and (max-width: 1279px) {
.market-tape {
display: none;
}
.app-header {
grid-template-columns: 190px minmax(0, 1fr) auto;
}
@@ -4988,21 +4976,6 @@ body.sidebar-collapsed .sidebar-collapse-button .lucide {
box-shadow: 0 -4px 18px rgba(24, 34, 45, 0.07);
}
.module-nav .nav-brand,
.module-nav .nav-group-label,
.module-nav .market-sub-tab,
.module-nav .sidebar-collapse-button {
display: none;
}
.module-nav .nav-group,
body.sidebar-collapsed .module-nav .nav-group {
display: contents;
margin: 0;
padding: 0;
border: 0;
}
.module-nav .module-tab,
body.sidebar-collapsed .module-nav .module-tab {
min-height: 54px;
@@ -5017,11 +4990,6 @@ body.sidebar-collapsed .sidebar-collapse-button .lucide {
text-align: center;
}
.module-nav .module-tab.mobile-primary-tab,
body.sidebar-collapsed .module-nav .module-tab.mobile-primary-tab {
display: flex;
}
.module-nav .module-tab span,
body.sidebar-collapsed .module-nav .module-tab span {
display: block;
@@ -5369,8 +5337,6 @@ body.sidebar-collapsed .sidebar-collapse-button .lucide {
border-right: 1px solid var(--border);
transition: background-color var(--motion-medium) ease, opacity var(--motion-medium) ease;
}
.rotation-day:last-child { border-right: 0; }
.rotation-day header { display: grid; gap: 2px; margin-bottom: 8px; }
.rotation-day header time { font-size: 12px; font-weight: 700; }
.rotation-day header span { color: var(--text-secondary); font-size: 10px; }
@@ -7130,11 +7096,6 @@ body.sidebar-collapsed .sidebar-collapse-button .lucide {
box-shadow: 1px 0 0 var(--border);
}
#screenerView .probability-value strong,
#screenerView .probability-value small {
display: block;
}
#screenerView .probability-value small {
margin-top: 3px;
color: var(--text-secondary);
@@ -13032,10 +12993,6 @@ button.account-role-badge:focus-visible { outline: 2px solid var(--blue); outlin
}
@media (max-width: 720px) {
body.mentor-directory-open {
overflow: hidden;
}
.mentor-layout {
height: auto;
min-height: 580px;
@@ -14889,13 +14846,6 @@ dialog::backdrop {
width: 100%;
}
body,
body.sidebar-collapsed {
display: block;
min-height: 100dvh;
padding-bottom: calc(68px + env(safe-area-inset-bottom));
}
.app-header {
width: 100%;
height: 108px;
@@ -14908,10 +14858,6 @@ dialog::backdrop {
background: rgba(255, 255, 255, .98);
}
.brand-block {
height: 42px;
}
.brand-block .brand-mark,
.brand-block .brand-logo {
width: 34px;
@@ -14927,20 +14873,6 @@ dialog::backdrop {
font-size: 16px;
}
.header-actions {
position: absolute;
inset: 56px 10px auto;
display: flex;
justify-content: space-between;
gap: 6px;
}
.header-date-group {
height: 42px;
min-width: 0;
flex: 1;
}
.header-date-group .date-input {
width: 112px;
flex: 1;
@@ -14952,12 +14884,6 @@ dialog::backdrop {
min-width: 30px;
}
.header-actions > .icon-button {
width: 40px;
min-width: 40px;
min-height: 42px;
}
.header-menu-button {
display: grid;
}
@@ -15071,9 +14997,7 @@ dialog::backdrop {
font-size: 14px;
}
.overview-strip .metric:nth-of-type(1) { grid-column: 2; grid-row: 1; }
.overview-strip .metric:nth-of-type(2) { grid-column: 3; grid-row: 1; border-right: 0; }
.overview-strip .metric:nth-of-type(3) { grid-column: 2; grid-row: 2; }
.overview-strip .metric:nth-of-type(4) { grid-column: 3; grid-row: 2; border-right: 0; }
.overview-strip .metric:nth-of-type(5) { grid-column: 1 / 2; grid-row: 3; border-bottom: 0; }
.overview-strip .metric:nth-of-type(6) { grid-column: 2 / 4; grid-row: 3; border-right: 0; border-bottom: 0; }
@@ -15330,10 +15254,6 @@ dialog::backdrop {
overflow-y: auto;
}
.curated-strategy-list {
grid-template-columns: 1fr;
}
.quant-universe-grid {
grid-template-columns: 1fr 1fr;
}
+32
View File
@@ -1803,6 +1803,38 @@ test("heart breathing prepares once then contracts on each exhale", async ({ pag
await expect(page.locator(".heart-breath-ripple span").first()).toHaveCSS("transition-duration", "4s");
});
test("stylesheet layers do not repeat identical rules in the same cascade context", async ({ page }) => {
await mockApplication(page, session("admin", true));
await page.goto("/index.html");
const duplicates = await page.evaluate(() => {
const occurrences = new Map();
const visitRules = (rules, href, context = []) => {
for (const rule of Array.from(rules || [])) {
if (typeof rule.selectorText === "string" && rule.style) {
const key = `${context.join("\u0001")}\u0000${rule.selectorText}\u0000${rule.style.cssText}`;
const rows = occurrences.get(key) || [];
rows.push(href);
occurrences.set(key, rows);
continue;
}
if (!rule.cssRules) continue;
const condition = rule.conditionText || rule.media?.mediaText || rule.name || "";
visitRules(rule.cssRules, href, [...context, `${rule.type}:${condition}`]);
}
};
for (const sheet of Array.from(document.styleSheets)) {
const href = sheet.href ? new URL(sheet.href).pathname : "inline";
visitRules(sheet.cssRules, href);
}
return Array.from(occurrences.entries())
.filter(([, paths]) => new Set(paths).size > 1)
.map(([rule, paths]) => ({ rule, paths }));
});
expect(duplicates).toEqual([]);
});
test("mobile shell stays within the viewport", async ({ page }) => {
await page.setViewportSize({ width: 375, height: 812 });
await mockApplication(page, session("user", true));
+134
View File
@@ -29,6 +29,128 @@ RETIRED_FRONTEND_SOURCE_RANGES = (
)
AUDITED_FRONTEND_SOURCE_LINE_COUNT = 9283
# CR-12 and CR-13 remove only declarations repeated by a later stylesheet
# layer under the same cascade context. Entries are either an exact retired
# fragment or an exact (source, replacement) pair when surrounding context is
# needed to identify one nested occurrence. Every other byte remains part of
# the accepted CSS baseline.
AUDITED_CSS_RETIREMENTS = {
"styles.css": (
".workspace-view.active-view {\n display: block;\n}\n\n",
"body.sidebar-collapsed {\n grid-template-columns: 64px minmax(0, 1fr);\n}\n\n",
".rotation-day:last-child { border-right: 0; }\n\n",
(
"#screenerView .probability-value strong,\n"
"#screenerView .probability-value small {\n"
" display: block;\n"
"}\n\n"
),
(
(
"@media (min-width: 721px) and (max-width: 1279px) {\n"
" .market-tape {\n"
" display: none;\n"
" }\n\n"
" .app-header {"
),
(
"@media (min-width: 721px) and (max-width: 1279px) {\n"
" .app-header {"
),
),
(
" .module-nav .nav-brand,\n"
" .module-nav .nav-group-label,\n"
" .module-nav .market-sub-tab,\n"
" .module-nav .sidebar-collapse-button {\n"
" display: none;\n"
" }\n\n"
),
(
" .module-nav .nav-group,\n"
" body.sidebar-collapsed .module-nav .nav-group {\n"
" display: contents;\n"
" margin: 0;\n"
" padding: 0;\n"
" border: 0;\n"
" }\n\n"
),
(
" .module-nav .module-tab.mobile-primary-tab,\n"
" body.sidebar-collapsed .module-nav .module-tab.mobile-primary-tab {\n"
" display: flex;\n"
" }\n\n"
),
" body.mentor-directory-open {\n overflow: hidden;\n }\n\n",
(
" body,\n"
" body.sidebar-collapsed {\n"
" display: block;\n"
" min-height: 100dvh;\n"
" padding-bottom: calc(68px + env(safe-area-inset-bottom));\n"
" }\n\n"
),
" .brand-block {\n height: 42px;\n }\n\n",
(
" .header-actions {\n"
" position: absolute;\n"
" inset: 56px 10px auto;\n"
" display: flex;\n"
" justify-content: space-between;\n"
" gap: 6px;\n"
" }\n\n"
),
(
" .header-date-group {\n"
" height: 42px;\n"
" min-width: 0;\n"
" flex: 1;\n"
" }\n\n"
),
(
" .header-actions > .icon-button {\n"
" width: 40px;\n"
" min-width: 40px;\n"
" min-height: 42px;\n"
" }\n\n"
),
" .overview-strip .metric:nth-of-type(1) { grid-column: 2; grid-row: 1; }\n",
" .overview-strip .metric:nth-of-type(3) { grid-column: 2; grid-row: 2; }\n",
" .curated-strategy-list {\n grid-template-columns: 1fr;\n }\n\n",
),
"renovation.css": (
".overview-strip .sentiment-block { padding-left: 0; }\n",
(
'.overview-strip[data-overview-expanded="true"] .metric-value '
"{ font-size: 18px; }\n\n"
),
),
"redesign-v2.css": (
"#dragonView .dragon-operation-table .dragon-col-reason { width: auto; }\n",
(
" .market-tape { display: none; }\n"
" .header-actions { width: 100%; }\n"
" .header-command-group { position: absolute; }\n"
),
(
" .sidebar-brand,\n"
" .module-nav .nav-group-label,\n"
" .sidebar-collapse-button,\n"
" .module-nav .market-sub-tab { display: none; }\n"
" .module-nav .nav-group,\n"
" body.sidebar-collapsed .module-nav .nav-group { display: contents; }\n"
" .module-nav .module-tab,\n"
" body.sidebar-collapsed .module-nav .module-tab { display: none; }\n"
),
" .module-nav .module-tab.mobile-primary-tab span { display: inline; }\n",
(
" .overview-strip .metric:nth-of-type(n + 4),\n"
" .overview-strip .metric-wide { display: none; }\n"
" .overview-toggle { display: none; }\n"
),
),
}
def sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
@@ -123,6 +245,18 @@ def assert_moved_asset_matches(
frontend_relative: str | None = None,
) -> None:
target_relative = frontend_relative or original_relative
if original_relative in AUDITED_CSS_RETIREMENTS:
original = (ORIGINAL_STATIC / original_relative).read_text(encoding="utf-8")
for retired in AUDITED_CSS_RETIREMENTS[original_relative]:
source, replacement = retired if isinstance(retired, tuple) else (retired, "")
testcase.assertEqual(original.count(source), 1, source)
original = original.replace(source, replacement, 1)
testcase.assertEqual(
(FRONTEND_ROOT / target_relative).read_text(encoding="utf-8"),
original,
original_relative,
)
return
testcase.assertEqual(
sha256(FRONTEND_ROOT / target_relative),
sha256(ORIGINAL_STATIC / original_relative),
+65
View File
@@ -0,0 +1,65 @@
from __future__ import annotations
import ast
import sys
import unittest
from pathlib import Path
from unittest.mock import patch
from backend.bootstrap import runtime
class BackgroundLifecycleTests(unittest.TestCase):
def test_service_construction_does_not_start_the_scheduler(self) -> None:
source = (Path(__file__).parents[1] / "backend" / "application.py").read_text(
encoding="utf-8"
)
tree = ast.parse(source)
service_class = next(
node for node in tree.body
if isinstance(node, ast.ClassDef) and node.name == "DashboardService"
)
constructor = next(
node for node in service_class.body
if isinstance(node, ast.FunctionDef) and node.name == "__init__"
)
called_methods = {
node.func.attr for node in ast.walk(constructor)
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
}
self.assertNotIn("start_scheduler", called_methods)
def test_runtime_starts_jobs_after_bind_and_stops_before_close(self) -> None:
events: list[str] = []
class Service:
def start_background_jobs(self) -> None:
events.append("start-jobs")
def stop_background_jobs(self) -> None:
events.append("stop-jobs")
class Server:
def __init__(self, address: tuple[str, int], handler: object) -> None:
events.append("bind")
def serve_forever(self) -> None:
events.append("serve")
raise KeyboardInterrupt
def server_close(self) -> None:
events.append("close")
with (
patch.object(runtime, "ThreadingHTTPServer", Server),
patch.object(sys, "argv", ["server.py", "--port", "8797"]),
):
runtime.main(object, Service())
self.assertEqual(
events, ["bind", "start-jobs", "serve", "stop-jobs", "close"]
)
if __name__ == "__main__":
unittest.main()
+44
View File
@@ -124,6 +124,50 @@ class HeavenReadingTests(unittest.TestCase):
len(self.database.list_heaven_readings(self.owner["id"], "fortune")), 1
)
def test_trend_interpretation_saves_successful_agent_result(self):
service = DashboardService.__new__(DashboardService)
service.database = self.database
service._request_context = threading.local()
service._request_context.user_id = self.owner["id"]
setup = {
"trade_date": "20260723",
"chart": {
"available": True,
"sector": "银行",
"stock": {"code": "000001", "name": "平安银行"},
"hexagram": {
"name": "中孚",
"lines": [],
"transformed": {"name": "小畜"},
},
"movement": {},
},
}
with patch.object(service, "heaven_setup", return_value=setup), patch.object(
service,
"_call_heaven_agent",
return_value=(
{"answer": "完整的解势结果", "model": "test", "latency_ms": 1},
"primary",
),
):
result = service.heaven_interpret(
{
"mode": "trend",
"trade_date": "2026-07-23",
"stock_code": "000001",
}
)
self.assertFalse(result["reused"])
self.assertEqual(result["answer"], "完整的解势结果")
self.assertEqual(result["reading"]["subject"], "000001 平安银行")
self.assertEqual(
self.database.list_heaven_readings(self.owner["id"], "trend")[0]["answer"],
"完整的解势结果",
)
if __name__ == "__main__":
unittest.main()
+23
View File
@@ -68,6 +68,29 @@ class JobRunnerTests(unittest.TestCase):
)
self.assertEqual(self.repository.recent(1)[0]["status"], "failed")
def test_scheduler_start_is_idempotent_and_stop_waits_for_exit(self) -> None:
first = self.runner.start_scheduler(
lambda: None, interval_seconds=60, initial_delay_seconds=60
)
second = self.runner.start_scheduler(
lambda: None, interval_seconds=60, initial_delay_seconds=60
)
self.assertIs(first, second)
self.assertTrue(first.is_alive())
self.assertTrue(self.runner.stop_scheduler())
self.assertFalse(first.is_alive())
def test_scheduler_can_restart_after_an_orderly_stop(self) -> None:
first = self.runner.start_scheduler(
lambda: None, interval_seconds=60, initial_delay_seconds=60
)
self.assertTrue(self.runner.stop_scheduler())
second = self.runner.start_scheduler(
lambda: None, interval_seconds=60, initial_delay_seconds=60
)
self.assertIsNot(first, second)
self.assertTrue(self.runner.stop_scheduler())
if __name__ == "__main__":
unittest.main()
+27
View File
@@ -1,8 +1,10 @@
from __future__ import annotations
import unittest
from unittest.mock import patch
from backend.llm import LLMGateway, LLMGatewayError
from backend.llm.service import LLMServiceMixin
class ProviderFailure(RuntimeError):
@@ -113,6 +115,31 @@ class LLMGatewayTests(unittest.TestCase):
with self.assertRaisesRegex(LLMGatewayError, "额度已用完"):
gateway.call("mentor", "mentor-v1", lambda model: "unused", (ProviderFailure,))
def test_saved_system_model_can_reach_the_connection_probe(self) -> None:
service = LLMServiceMixin()
service._system_credentials = {
"llm_models": [
{
"id": "primary-model",
"name": "主模型",
"api_key": "secret",
"base_url": "https://model.example/v1",
"model": "model-name",
}
]
}
service.llm_gateway = self.gateway()
expected = {"ok": True, "reply": "OK"}
with patch(
"backend.llm.service.test_llm_connection", return_value=expected
) as connection_probe:
result = service.test_system_llm_profile("primary-model", {})
self.assertEqual(result, expected)
connection_probe.assert_called_once_with(
"secret", "https://model.example/v1", "model-name"
)
if __name__ == "__main__":
unittest.main()
@@ -44,7 +44,7 @@ class FrontendPreservationSliceTests(unittest.TestCase):
(ORIGINAL_STATIC / "index.html").read_text(encoding="utf-8"),
)
def test_complete_stylesheet_stack_is_byte_identical_after_relocation(self) -> None:
def test_stylesheet_stack_matches_baseline_after_audited_retirements(self) -> None:
for original, migrated in (
("shared/tokens.css", "shared/tokens.css"),
("styles.css", "styles/styles.css"),
+11 -6
View File
@@ -32,17 +32,22 @@ def main() -> None:
from server import RequestHandler, SERVICE
server = ThreadingHTTPServer(("127.0.0.1", args.port), RequestHandler)
print(
f"Preservation runtime is running at http://127.0.0.1:{args.port} "
f"with database {SERVICE.database.path}",
flush=True,
)
try:
if hasattr(SERVICE, "start_background_jobs"):
SERVICE.start_background_jobs()
print(
f"Preservation runtime is running at http://127.0.0.1:{args.port} "
f"with database {SERVICE.database.path}",
flush=True,
)
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
SERVICE._background_stop.set()
if hasattr(SERVICE, "stop_background_jobs"):
SERVICE.stop_background_jobs()
else:
SERVICE._background_stop.set()
server.server_close()
+101
View File
@@ -28,6 +28,8 @@
| CR-08 | NDJSON流式传输 | 问师与复盘助手重复维护响应头、事件写入、完成、断线及关闭流程 | HTTP共享层拥有唯一流式连接生命周期 | 已完成 |
| CR-09 | 应用服务门面 | 两个仅服务股池iFinD补全的方法仍错位在全局`DashboardService` | 原函数体机械归位到`PoolServiceMixin` | 已完成 |
| CR-10 | Repository所有权 | 五行行业阶段覆盖的三项持久化方法仍错位在根级数据库门面 | 原函数体机械归位到问天Repository,兼容数据继续保留 | 已完成 |
| CR-11 | 后台任务生命周期 | 导入应用即启动调度线程,启动早于端口绑定,停止只置位但不等待 | 运行时显式启停,每个Runner只拥有一个可等待的调度线程 | 已完成 |
| CR-12 | CSS跨层精确重复 | 七层样式保留多次视觉改造形成的重复顶层规则,前层声明被后层逐字覆盖 | 只删除能够由CSSOM证明完全重复的前层规则,并建立浏览器级重复门禁 | 已完成 |
## CR-01验收口径
@@ -247,6 +249,105 @@
本批基线为`xiaobai-reduction-09-service-facade-20260801`;检查点为
`xiaobai-reduction-10-repository-ownership-20260801`
## CR-11验收口径
- 导入`backend.application`或构造`DashboardService`不得启动后台调度;必须先成功绑定HTTP端口,
再由运行时显式启动。
- 同一`InProcessJobRunner`重复启动调度器必须返回同一活动线程,停止必须置位并在限定时间内等待退出,
有序停止后允许重新启动。
- 运行时关闭顺序固定为:停止调度、等待已提交任务、关闭HTTP服务器;迁移对比工具继续兼容原版入口。
- 三个任务的注册定义、5秒刷新频率、3秒初始延迟、幂等键、锁、重试、业务函数和结果不得改变。
- 声明的超时继续是目标与审计字段;Python线程不能安全强杀,本批不伪造硬取消能力。
## CR-11结果
- 删除`DashboardService`构造阶段的调度副作用,端口占用、模块导入和单元测试不再提前创建后台写线程;
`backend/bootstrap/runtime.py`成为正式启动与停止所有者。
- `InProcessJobRunner`集中持有调度停止事件和线程引用;重复启动幂等,停止可等待,原任务锁、持久化运行
状态、成功幂等、失败记录和后续重试逻辑保持不变。
- 新增语法树与运行顺序门禁,固定“构造不启动”“绑定后启动”“停止后关服”,并补齐重复启动与重启测试。
- 候选328项、纯`app/`导出265项和45项Playwright通过;24个JavaScript文件、API/架构注册表、
Git空白检查和SQLite完整性检查通过。
- 本批没有可安全删除的重复任务实现;为补齐原先缺失的生命周期,生产代码净增加24行。增加内容仅为
调度状态、幂等启停和运行时委托,不新增业务层、任务或兼容包装。
- 本批不修改页面、CSS、API、数据源、刷新计算、自动选股条件、数据库结构、权限或LLM。
本批基线为`xiaobai-reduction-10-repository-ownership-20260801`;检查点为
`xiaobai-reduction-11-background-jobs-20260801`
## CR-11人工验收修正
- 2026-08-02人工验收发现本地页面可访问,但行情与LLM同时无法连接。第一原因是验收服务由受限
自动化会话启动,子进程继承了禁止外部网络访问的权限;重新在主机正常网络权限下启动后恢复。
- 随后的主模型连接测试暴露`LLMServiceMixin`机械迁移时遗漏`validate_text`导入,导致请求在真正
访问模型前抛出`NameError`并关闭HTTP连接;恢复原依赖并增加保存模型连接探测的运行契约测试。
- 网站自身实测`000001`返回Tushare日K 60根、分时242点;主模型
`MiniMax-M2.7-highspeed`在2236毫秒内回复`OK`,证明服务进程的数据与LLM出网链路均已恢复。
- 修正后候选329项、纯`app/`导出266项通过;本次只恢复缺失导入和测试,不修改模型配置、额度、
提示词、回退策略、行情来源或计算逻辑。
- 继续验收观势时发现模型已经成功返回,但问天服务在保存解势记录前关闭了HTTP连接。原因是原版
`server.py`已有的`secrets`导入在机械拆分到问天服务时遗漏,生成非观气记录去重键时触发
`NameError`。迁移版恢复该标准库依赖,并增加“模型成功返回后保存观势结果”的完整服务回归测试。
- 使用`000001 平安银行`完成真实页面复测:六爻安全门6/6通过,解势结果正常返回并写入历史,
`8797`错误日志为空。该修正不改变提示词、模型选择、额度、卦象计算、记录结构或前端行为。
本修正基线为`xiaobai-reduction-11-background-jobs-20260801`;检查点为
`xiaobai-reduction-11-runtime-connectivity-fix-20260802`;后续解势修正检查点为
`xiaobai-reduction-11-heaven-interpret-fix-20260802`
## CR-12验收口径
- 本批只处理不同样式文件中、同为顶层、选择器与完整声明逐字等价的规则;媒体查询、伪状态、
动画、问天隔离样式以及仅外形相似的规则不进入删除范围。
- 删除的必须是较早加载的副本,较晚层继续提供完全相同的最终声明;样式加载顺序、变量、HTML、
JavaScript和主题切换逻辑均不改变。
- 迁移保真测试必须逐段登记允许退休的原始CSS文本,除登记片段外,其余源码继续与原版逐字符相等。
- 浏览器必须验证跨层顶层精确重复为零,并通过日间、夜间、桌面、390px移动端及全站交互回归。
## CR-12结果
- 通过浏览器CSSOM扫描七层运行样式,共发现57组完整重复规则;本批只批准其中7组跨文件顶层重复,
分别涉及工作区显示、折叠侧栏、板块轮动末列、选股概率值、摘要条两项声明及龙虎榜原因列。
其余50组位于同文件或嵌套媒体条件等更复杂环境,证据不足,继续保留。
- 删除7条较早加载的规则,三个生产CSS文件净减少19行、480字节;后层最终规则、选择器优先级与
加载顺序均未改变,没有新增兼容覆盖或第二套样式实现。
- 新增浏览器CSSOM门禁,任何两个样式层再次出现相同顶层选择器与完整声明都会失败;迁移保真门禁
只允许已登记的7个精确源码片段退休,其他CSS差异仍会失败。
- 真实`8797`页面复核情绪周期日间/夜间、龙虎榜和390×844移动端;三个受影响节点的计算样式
与删除前一致,移动端无横向溢出。候选330项、CSS/前端契约33项、迁移对照63项及46项
Playwright全部通过,24个JavaScript文件、API/架构注册表和SQLite完整性检查通过。
- 本批不修改页面布局、颜色、字体、间距、响应式规则、主题、动画、业务功能、API、数据库或部署。
本批基线为`xiaobai-reduction-11-heaven-interpret-fix-20260802`;检查点为
`xiaobai-reduction-12-css-exact-duplicates-20260802`
## CR-13验收口径
- 本批只处理不同样式文件中、处于浏览器规范化后完全相同媒体条件下、选择器与完整CSSOM声明完全
相同的规则;不同媒体上下文、同文件重复、近似声明、动画和问天隔离样式继续保留。
- 删除的必须是较早加载的副本,较晚样式层继续提供相同声明;媒体条件、规则顺序、选择器优先级、
变量、HTML、JavaScript和主题逻辑不得改变。
- 保真门禁必须逐段登记允许退休的原始源码;浏览器门禁必须递归遍历嵌套规则,并只将同一上下文内
跨文件的完整重复判为失败。
- 390×844明暗主题、1000×800中等宽度和1000×600低高度断点必须保持原计算样式与视觉结果。
## CR-13结果
- 浏览器CSSOM确认22组跨文件嵌套重复:1组位于721-1279px媒体条件,12组位于720px移动端条件,
9组位于720px或1023px低高度复合条件;全部删除较早层副本,后层规则原样保留。
- `styles.css`减少65行,`redesign-v2.css`减少15行,生产CSS合计净减少80行、约1.9 KB;没有新增
兼容覆盖、声明值、选择器或样式文件。
- Playwright门禁由顶层扫描扩展为递归上下文扫描,修改后同一嵌套上下文的跨文件完整重复为0;同文件
重复和不同上下文规则不在本批范围,未被误删。
- 1000×800和1000×600修改前后截图逐字节一致;390×844明暗主题的关键显示、定位、间距、网格、
溢出和导航状态一致,页面目视无差异。
- 候选330项、CSS/前端契约33项、迁移对照63项及46项Playwright全部通过;24个JavaScript文件、
API/架构注册表和SQLite完整性检查通过。
- 本批不修改页面布局、颜色、字体、间距、主题、动画、业务功能、API、数据库、数据源、LLM或部署。
本批基线为`xiaobai-reduction-12-css-exact-duplicates-20260802`;检查点为
`xiaobai-reduction-13-css-nested-duplicates-20260802`
## 人工验收记录
- 2026-08-01:用户检查CR-02与CR-03运行结果,确认未发现明显异常。本记录仅表示本轮可见功能与