465 lines
15 KiB
Markdown
465 lines
15 KiB
Markdown
# Device Management Alignment and Server Logs Implementation Plan
|
|
|
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
|
|
**Goal:** Align the two device-management cards at their bottom edge and replace device business-event logs with real Python/Uvicorn server process logs.
|
|
|
|
**Architecture:** Extend `core/runlog.py` with a bounded server-log buffer and a custom `logging.Handler`. During FastAPI startup, attach the handler to application and Uvicorn loggers, enqueue captured records, and broadcast them through the existing `event.log` WebSocket channel. Keep the frontend protocol shape simple (`ts`, `level`, `logger`, `message`) and use CSS grid stretching for card alignment.
|
|
|
|
**Tech Stack:** Python 3, FastAPI, Uvicorn, asyncio, Python logging, vanilla HTML/CSS/JavaScript, pytest, pytest-asyncio, websockets.
|
|
|
|
**Repository note:** `E:/private/cp_agent` is not currently a Git repository, so commit steps cannot be executed. Each task still ends with an explicit verification checkpoint.
|
|
|
|
---
|
|
|
|
## File Structure
|
|
|
|
- Modify `server/core/runlog.py`: bounded server-log records and `ServerLogHandler`.
|
|
- Modify `server/main.py`: install/uninstall the handler, queue and broadcast log records, remove the old business-event `push_log` path.
|
|
- Modify `server/web/index.html`: equal-height desktop cards and level-based server-log rendering.
|
|
- Create `server/tests/test_server_logs.py`: unit and integration coverage for the log buffer, handler, list API, and WebSocket push.
|
|
- Create `server/tests/test_web_ui.py`: static regression checks for the required CSS and frontend log schema.
|
|
|
|
---
|
|
|
|
### Task 1: Server log buffer and logging handler
|
|
|
|
**Files:**
|
|
- Create: `server/tests/test_server_logs.py`
|
|
- Modify: `server/core/runlog.py`
|
|
|
|
- [ ] **Step 1: Write failing unit tests for bounded records and formatted exceptions**
|
|
|
|
```python
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import uuid
|
|
|
|
from core.runlog import RunLog, ServerLogHandler
|
|
|
|
|
|
def isolated_logger(handler: logging.Handler) -> logging.Logger:
|
|
logger = logging.getLogger(f"cp-agent-test-{uuid.uuid4().hex}")
|
|
logger.handlers = [handler]
|
|
logger.propagate = False
|
|
logger.setLevel(logging.DEBUG)
|
|
return logger
|
|
|
|
|
|
def test_runlog_keeps_latest_server_records():
|
|
runlog = RunLog(maxlen=2)
|
|
runlog.add("INFO", "test.one", "first", 1.0)
|
|
runlog.add("WARNING", "test.two", "second", 2.0)
|
|
runlog.add("ERROR", "test.three", "third", 3.0)
|
|
|
|
assert runlog.entries() == [
|
|
{"ts": 2.0, "level": "WARNING", "logger": "test.two", "message": "second"},
|
|
{"ts": 3.0, "level": "ERROR", "logger": "test.three", "message": "third"},
|
|
]
|
|
|
|
|
|
def test_server_log_handler_formats_message_and_traceback():
|
|
runlog = RunLog()
|
|
published = []
|
|
handler = ServerLogHandler(runlog, published.append)
|
|
logger = isolated_logger(handler)
|
|
|
|
logger.info("server started on %s", 60030)
|
|
try:
|
|
raise ValueError("broken")
|
|
except ValueError:
|
|
logger.exception("request failed")
|
|
|
|
entries = runlog.entries()
|
|
assert entries[0]["level"] == "INFO"
|
|
assert entries[0]["logger"] == logger.name
|
|
assert entries[0]["message"] == "server started on 60030"
|
|
assert entries[1]["level"] == "ERROR"
|
|
assert "request failed" in entries[1]["message"]
|
|
assert "ValueError: broken" in entries[1]["message"]
|
|
assert published == entries
|
|
```
|
|
|
|
- [ ] **Step 2: Run the tests and verify RED**
|
|
|
|
Run:
|
|
|
|
```powershell
|
|
cd E:/private/cp_agent/server
|
|
python -m pytest tests/test_server_logs.py -q
|
|
```
|
|
|
|
Expected: collection/import failure because `ServerLogHandler` and the new `RunLog.add` signature do not exist.
|
|
|
|
- [ ] **Step 3: Implement the minimal bounded buffer and handler**
|
|
|
|
Replace `server/core/runlog.py` with:
|
|
|
|
```python
|
|
"""服务器运行日志:捕获 Python logging 记录并保留最近若干条。"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import time
|
|
from collections import deque
|
|
from typing import Any, Callable
|
|
|
|
PublishCallback = Callable[[dict[str, Any]], None]
|
|
|
|
|
|
class RunLog:
|
|
def __init__(self, maxlen: int = 500):
|
|
self._entries: deque[dict[str, Any]] = deque(maxlen=maxlen)
|
|
|
|
def add(
|
|
self,
|
|
level: str,
|
|
logger_name: str,
|
|
message: str,
|
|
timestamp: float | None = None,
|
|
) -> dict[str, Any]:
|
|
entry = {
|
|
"ts": timestamp if timestamp is not None else time.time(),
|
|
"level": level,
|
|
"logger": logger_name,
|
|
"message": message,
|
|
}
|
|
self._entries.append(entry)
|
|
return entry
|
|
|
|
def entries(self) -> list[dict[str, Any]]:
|
|
return list(self._entries)
|
|
|
|
|
|
class ServerLogHandler(logging.Handler):
|
|
def __init__(self, runlog: RunLog, publish: PublishCallback | None = None):
|
|
super().__init__()
|
|
self._runlog = runlog
|
|
self._publish = publish
|
|
self.setFormatter(logging.Formatter("%(message)s"))
|
|
|
|
def set_publish(self, publish: PublishCallback | None) -> None:
|
|
self._publish = publish
|
|
|
|
def emit(self, record: logging.LogRecord) -> None:
|
|
if getattr(record, "_cp_agent_server_log_captured", False):
|
|
return
|
|
record._cp_agent_server_log_captured = True
|
|
try:
|
|
message = self.format(record)
|
|
entry = self._runlog.add(record.levelname, record.name, message, record.created)
|
|
if self._publish is not None:
|
|
self._publish(entry)
|
|
except Exception:
|
|
return
|
|
```
|
|
|
|
- [ ] **Step 4: Run unit tests and verify GREEN**
|
|
|
|
Run:
|
|
|
|
```powershell
|
|
cd E:/private/cp_agent/server
|
|
python -m pytest tests/test_server_logs.py -q
|
|
```
|
|
|
|
Expected: `2 passed`.
|
|
|
|
---
|
|
|
|
### Task 2: FastAPI lifecycle and WebSocket server-log delivery
|
|
|
|
**Files:**
|
|
- Modify: `server/tests/test_server_logs.py`
|
|
- Modify: `server/main.py`
|
|
|
|
- [ ] **Step 1: Add failing integration tests for list and real-time delivery**
|
|
|
|
Append imports and tests to `server/tests/test_server_logs.py`:
|
|
|
|
```python
|
|
import asyncio
|
|
import json
|
|
|
|
import pytest
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_log_list_returns_server_log_schema(ui):
|
|
marker = f"list-marker-{uuid.uuid4().hex}"
|
|
logging.getLogger("cp_agent.integration").warning(marker)
|
|
await asyncio.sleep(0.1)
|
|
|
|
response = await ui.request("log.list", {})
|
|
matching = [item for item in response["payload"]["logs"] if marker in item["message"]]
|
|
assert matching
|
|
assert matching[-1]["level"] == "WARNING"
|
|
assert matching[-1]["logger"] == "cp_agent.integration"
|
|
assert "kind" not in matching[-1]
|
|
assert "deviceId" not in matching[-1]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_server_log_is_pushed_to_ui(ui):
|
|
marker = f"push-marker-{uuid.uuid4().hex}"
|
|
logging.getLogger("cp_agent.integration").error(marker)
|
|
|
|
while True:
|
|
message = json.loads(await asyncio.wait_for(ui.ws.recv(), timeout=5))
|
|
if message.get("type") == "event" and message.get("action") == "event.log":
|
|
if marker in message["payload"]["message"]:
|
|
break
|
|
|
|
assert message["payload"]["level"] == "ERROR"
|
|
assert message["payload"]["logger"] == "cp_agent.integration"
|
|
```
|
|
|
|
The tests use the existing `ui` fixture from `test_phase1.py`; move the shared `Server`, `UiClient`, `server`, and `ui` fixtures into `server/tests/conftest.py` if pytest cannot expose them across modules. The exact shared fixture content must be copied unchanged from `test_phase1.py`, then removed from that file to prevent duplicate fixture definitions.
|
|
|
|
- [ ] **Step 2: Run integration tests and verify RED**
|
|
|
|
Run:
|
|
|
|
```powershell
|
|
cd E:/private/cp_agent/server
|
|
python -m pytest tests/test_server_logs.py -q
|
|
```
|
|
|
|
Expected: integration tests fail because captured Python records are not attached to the application lifecycle or broadcast queue.
|
|
|
|
- [ ] **Step 3: Add the log queue, handler lifecycle, and logger attachment**
|
|
|
|
Update imports and globals in `server/main.py`:
|
|
|
|
```python
|
|
import asyncio
|
|
import contextlib
|
|
# existing imports...
|
|
from core.runlog import RunLog, ServerLogHandler
|
|
|
|
runlog = RunLog()
|
|
server_log_handler = ServerLogHandler(runlog)
|
|
log_queue: asyncio.Queue[dict] | None = None
|
|
log_broadcast_task: asyncio.Task | None = None
|
|
log_loop: asyncio.AbstractEventLoop | None = None
|
|
LOGGERS_TO_CAPTURE = ("", "uvicorn", "uvicorn.error", "uvicorn.access")
|
|
```
|
|
|
|
Add lifecycle helpers:
|
|
|
|
```python
|
|
def enqueue_server_log(entry: dict) -> None:
|
|
if log_loop is None or log_queue is None or log_loop.is_closed():
|
|
return
|
|
log_loop.call_soon_threadsafe(log_queue.put_nowait, entry)
|
|
|
|
|
|
def attach_server_log_handler() -> None:
|
|
for name in LOGGERS_TO_CAPTURE:
|
|
target = logging.getLogger(name)
|
|
if server_log_handler not in target.handlers:
|
|
target.addHandler(server_log_handler)
|
|
|
|
|
|
def detach_server_log_handler() -> None:
|
|
for name in LOGGERS_TO_CAPTURE:
|
|
target = logging.getLogger(name)
|
|
if server_log_handler in target.handlers:
|
|
target.removeHandler(server_log_handler)
|
|
|
|
|
|
async def broadcast_server_logs() -> None:
|
|
assert log_queue is not None
|
|
while True:
|
|
entry = await log_queue.get()
|
|
await hub.broadcast_to_ui({"type": "event", "action": "event.log", "payload": entry})
|
|
```
|
|
|
|
Update startup and shutdown:
|
|
|
|
```python
|
|
@app.on_event("startup")
|
|
async def startup() -> None:
|
|
global log_loop, log_queue, log_broadcast_task
|
|
Path(DB_PATH).parent.mkdir(parents=True, exist_ok=True)
|
|
log_loop = asyncio.get_running_loop()
|
|
log_queue = asyncio.Queue()
|
|
server_log_handler.set_publish(enqueue_server_log)
|
|
attach_server_log_handler()
|
|
log_broadcast_task = log_loop.create_task(broadcast_server_logs())
|
|
hub.start_watchdog()
|
|
logger.info("服务启动完成, DB=%s", DB_PATH)
|
|
|
|
|
|
@app.on_event("shutdown")
|
|
async def shutdown() -> None:
|
|
global log_broadcast_task, log_queue, log_loop
|
|
await hub.shutdown()
|
|
server_log_handler.set_publish(None)
|
|
detach_server_log_handler()
|
|
if log_broadcast_task is not None:
|
|
log_broadcast_task.cancel()
|
|
with contextlib.suppress(asyncio.CancelledError):
|
|
await log_broadcast_task
|
|
log_broadcast_task = None
|
|
log_queue = None
|
|
log_loop = None
|
|
storage.close()
|
|
```
|
|
|
|
Delete `push_log`. Delete its calls after device registration, device disconnection, and UI replies. Keep `log.list` returning `runlog.entries()`. Existing `logger.info`, `logger.warning`, `logger.error`, and `logger.exception` calls become the sole source of server runtime logs.
|
|
|
|
- [ ] **Step 4: Run server-log tests and verify GREEN**
|
|
|
|
Run:
|
|
|
|
```powershell
|
|
cd E:/private/cp_agent/server
|
|
python -m pytest tests/test_server_logs.py -q
|
|
```
|
|
|
|
Expected: all server-log tests pass.
|
|
|
|
---
|
|
|
|
### Task 3: Equal-height cards and level-based frontend rendering
|
|
|
|
**Files:**
|
|
- Create: `server/tests/test_web_ui.py`
|
|
- Modify: `server/web/index.html`
|
|
|
|
- [ ] **Step 1: Write failing static frontend regression tests**
|
|
|
|
```python
|
|
from pathlib import Path
|
|
|
|
HTML = (Path(__file__).parent.parent / "web" / "index.html").read_text(encoding="utf-8")
|
|
|
|
|
|
def test_device_management_cards_stretch_on_desktop_only():
|
|
assert ".two-col { display: grid;" in HTML
|
|
assert "align-items: stretch" in HTML
|
|
assert ".two-col > div { display: flex;" in HTML
|
|
assert ".two-col > div > .card" in HTML
|
|
assert "@media (max-width: 1100px)" in HTML
|
|
assert ".two-col > div { display: block;" in HTML
|
|
|
|
|
|
def test_runtime_log_uses_server_log_fields():
|
|
assert "服务器进程日志" in HTML
|
|
assert "e.level" in HTML
|
|
assert "e.logger" in HTML
|
|
assert "KIND_LABEL" not in HTML
|
|
assert "e.kind" not in HTML
|
|
assert "e.deviceId" not in HTML
|
|
```
|
|
|
|
- [ ] **Step 2: Run frontend tests and verify RED**
|
|
|
|
Run:
|
|
|
|
```powershell
|
|
cd E:/private/cp_agent/server
|
|
python -m pytest tests/test_web_ui.py -q
|
|
```
|
|
|
|
Expected: both tests fail against the current CSS and old `kind/deviceId` log rendering.
|
|
|
|
- [ ] **Step 3: Implement desktop equal-height cards**
|
|
|
|
Update the device-management CSS in `server/web/index.html`:
|
|
|
|
```css
|
|
.two-col { display: grid; grid-template-columns: minmax(280px, 420px) minmax(340px, 560px); gap: 16px; align-items: stretch; justify-content: start; }
|
|
.two-col > div { display: flex; min-height: 0; }
|
|
.two-col > div > .card { width: 100%; display: flex; flex-direction: column; min-height: 0; }
|
|
@media (max-width: 1100px) {
|
|
.two-col { grid-template-columns: 1fr; }
|
|
.two-col > div { display: block; }
|
|
}
|
|
```
|
|
|
|
Keep `.app-list { max-height: 640px; overflow-y: auto; }` so application rows scroll within the stretched card instead of extending the grid row.
|
|
|
|
- [ ] **Step 4: Implement level-based server log UI**
|
|
|
|
Replace old kind styles with:
|
|
|
|
```css
|
|
.log-line .k.debug { color: #8a94a0; }
|
|
.log-line .k.info { color: #4cc2ff; }
|
|
.log-line .k.warning { color: #f5c451; }
|
|
.log-line .k.error, .log-line .k.critical { color: var(--danger); }
|
|
.log-line .logger { color: #8a94a0; }
|
|
```
|
|
|
|
Change the page hint to:
|
|
|
|
```html
|
|
<p class="hint">服务器进程日志:启动、访问、警告与异常(服务端保留最近 500 条,页面实时推送追加)。</p>
|
|
```
|
|
|
|
Replace `KIND_LABEL` and `logLine` with:
|
|
|
|
```javascript
|
|
function logLine(e) {
|
|
const t = new Date(e.ts * 1000).toLocaleTimeString('zh-CN', { hour12: false });
|
|
const level = String(e.level || 'INFO').toUpperCase();
|
|
const loggerName = e.logger ? ` <span class="logger">${escapeHtml(e.logger)}</span>` : '';
|
|
const isErr = level === 'ERROR' || level === 'CRITICAL';
|
|
return `<div class="log-line"><span class="t">[${t}]</span> <span class="k ${escapeHtml(level.toLowerCase())}">${escapeHtml(level)}</span>${loggerName} ${isErr ? '<span class="err">' : ''}${escapeHtml(e.message || '')}${isErr ? '</span>' : ''}</div>`;
|
|
}
|
|
```
|
|
|
|
- [ ] **Step 5: Run frontend tests and verify GREEN**
|
|
|
|
Run:
|
|
|
|
```powershell
|
|
cd E:/private/cp_agent/server
|
|
python -m pytest tests/test_web_ui.py -q
|
|
```
|
|
|
|
Expected: `2 passed`.
|
|
|
|
---
|
|
|
|
### Task 4: Full regression verification
|
|
|
|
**Files:**
|
|
- Verify all modified files.
|
|
|
|
- [ ] **Step 1: Run the complete server test suite**
|
|
|
|
Run:
|
|
|
|
```powershell
|
|
cd E:/private/cp_agent/server
|
|
python -m pytest -q
|
|
```
|
|
|
|
Expected: all tests pass with no unhandled task exceptions.
|
|
|
|
- [ ] **Step 2: Compile Python sources**
|
|
|
|
Run:
|
|
|
|
```powershell
|
|
cd E:/private/cp_agent/server
|
|
python -m compileall -q main.py core tests
|
|
```
|
|
|
|
Expected: exit code 0 and no output.
|
|
|
|
- [ ] **Step 3: Perform a focused browser check**
|
|
|
|
Start the server, open the device-management page, and verify:
|
|
|
|
1. At desktop width, the two cards have the same bottom edge.
|
|
2. Below 1100 px, cards stack and use natural heights.
|
|
3. A generated `logger.warning` or failed request appears as a `WARNING`/`ERROR` server record.
|
|
4. Refreshing after “清空显示” reloads the server buffer.
|
|
|
|
Expected: all four checks succeed without browser console errors.
|