File size: 10,410 Bytes
e59bd9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
"""LPU AI Accelerator V7.1 — NATIVE desktop app (no browser window).

Runs the SAME FastAPI server + dashboard, but inside a real OS window via
`pywebview` (WebView2 on Windows 11 — an embedded runtime, not a browser
window: no address bar, its own taskbar entry, native close/minimize).

Modes resolved automatically:

  1. native            — server started here + native window (default)
  2. native-attached   — an accelerator server is ALREADY running on the
                         port: just open a second window on it and never
                         start a duplicate server
  3. browser fallback  — pywebview missing OR window creation failed:
                         honest fallback to the plain loopback server +
                         system browser, with a clear one-line reason

V7.1.1 hardening (user report: `run_lpu.py --desktop` did nothing and a
Windows Electron/Chromium warning was printed — the .py file association
handed the script to an Electron app, so Python never ran at all; use the
new .cmd launchers, which call python.exe explicitly):

- if pywebview import OR window creation raises, we fall back to browser
  mode WITH the reason printed (never silently exit, never a fake window)
- the fallback serve loop is interruptible in-process via
  request_shutdown() (tests call it instead of killing the thread)
- Ctrl+C still stops ONLY this app's accelerator; training untouched

Guarantees (unchanged):
- closing the window stops ONLY the server/accelerator owned by THIS app;
  training processes are never touched (attach mode never stops anything)
- loopback only; if an LPU server is already on the port we attach to it,
  if something ELSE occupies the port we move to the next free port
- every mode is fully testable headless (server thread lifecycle + attach
  detection + fallback routing + window-failure fallback) — the window
  itself needs a display and is exercised on the rig
"""

from __future__ import annotations

import json
import sys
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path
from typing import Optional

import uvicorn

ROOT = Path(__file__).resolve().parent
WINDOW_TITLE = "LPU AI Accelerator — Intelligent Training Control Center"
DEFAULT_SIZE = (1440, 920)
MIN_SIZE = (1024, 660)

# in-process shutdown signal for the fallback serve loop (tests + embedders)
_SHUTDOWN = threading.Event()


def request_shutdown() -> None:
    """Ask a running fallback session to unwind (idempotent, thread-safe)."""
    _SHUTDOWN.set()


def _reset_shutdown() -> None:
    _SHUTDOWN.clear()


def _pywebview():
    try:
        import webview  # noqa: PLC0415 - optional dependency, lazy import
        return webview
    except Exception:  # noqa: BLE001 - missing or no GUI backend
        return None


def _get_status(host: str, port: int, timeout: float = 1.5) -> Optional[dict]:
    """Read /api/status over loopback. None = nothing answering."""
    url = f"http://{host}:{port}/api/status"
    try:
        with urllib.request.urlopen(url, timeout=timeout) as resp:
            return json.loads(resp.read().decode("utf-8"))
    except (urllib.error.URLError, OSError, ValueError):
        return None


def is_lpu_server_running(host: str, port: int) -> bool:
    st = _get_status(host, port)
    return bool(st) and str(st.get("runtime_version", "")).startswith("7.") \
        and "accelerator_status" in st


def find_port(host: str, start_port: int, tries: int = 10) -> int:
    """First port that either hosts OUR accelerator (attach) or is free.
    Ports occupied by NON-LPU services are skipped, never hijacked."""
    for port in range(start_port, start_port + tries):
        if is_lpu_server_running(host, port):
            return port            # attach case: same port returned
        probe = _get_status(host, port)
        if probe is None:
            import socket
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.settimeout(0.4)
                try:
                    s.bind((host, port))
                    return port     # truly free
                except OSError:
                    continue        # occupied by something else
    raise RuntimeError(
        f"no free port in {start_port}..{start_port + tries - 1} "
        f"(all busy or occupied by non-LPU services)")


class ServerThread:
    """uvicorn in a daemon thread with readiness polling + clean stop."""

    def __init__(self, app, host: str, port: int):
        config = uvicorn.Config(app, host=host, port=port, log_level="warning")
        self.server = uvicorn.Server(config)
        self.host, self.port = host, port
        self.thread = threading.Thread(target=self.server.run,
                                       name="lpu-server", daemon=True)
        self._ready = threading.Event()

    def start(self, timeout: float = 20.0) -> bool:
        self.thread.start()
        deadline = time.time() + timeout
        while time.time() < deadline:
            if self.server.should_exit:
                return False
            if _get_status(self.host, self.port, timeout=0.8) is not None:
                self._ready.set()
                return True
            time.sleep(0.1)
        return False

    def stop(self, timeout: float = 8.0) -> None:
        """Stop ONLY this server (training processes are never touched)."""
        self.server.should_exit = True
        self.thread.join(timeout=timeout)


def _serve_until_closed(server_thread: "ServerThread",
                        poll: float = 0.5) -> None:
    """Fallback serve loop: run until the thread dies, Ctrl+C, or an
    in-process request_shutdown() (unwindable without killing anything)."""
    try:
        while server_thread.thread.is_alive():
            if _SHUTDOWN.is_set():
                break
            time.sleep(poll)
    except KeyboardInterrupt:
        pass


def launch_desktop(config: Optional[dict] = None, host: str = "127.0.0.1",
                   start_port: int = 8710,
                   fallback_open_browser: bool = True) -> dict:
    """Resolve the mode and run the app. Blocking (returns after the window
    closes). Returns {'mode': ..., 'port': ...} for tests and logging."""
    _reset_shutdown()
    cfg = config or {}
    from server.app import create_app

    # security rule kept: non-loopback host => expose+token in config
    if host not in ("127.0.0.1", "localhost", "::1"):
        srv = cfg.setdefault("server", {})
        srv["host"] = host
        srv["expose"] = True

    port = find_port(host, start_port)
    attached = is_lpu_server_running(host, port)
    url = f"http://{host}:{port}"

    owns_server = False
    server_thread: Optional[ServerThread] = None
    if not attached:
        # open_browser only applies to the plain server path, not desktop
        cfg.setdefault("server", {})["open_browser"] = False
        app = create_app(cfg)
        server_thread = ServerThread(app, host, port)
        if not server_thread.start():
            raise RuntimeError("accelerator server failed to start")
        owns_server = True

    webview = _pywebview()
    try:
        if webview is not None:
            try:
                window = webview.create_window(
                    WINDOW_TITLE, url, width=DEFAULT_SIZE[0],
                    height=DEFAULT_SIZE[1], min_size=MIN_SIZE)
                webview.start()    # blocks until the window is closed
                return {"mode": "native-attached" if attached else "native",
                        "port": port}
            except Exception as exc:  # noqa: BLE001
                # window creation failed (no GUI backend / WebView2 missing /
                # driver error) -> honest browser fallback WITH the reason
                print(f"[LPU] native window unavailable ({exc}) -> "
                      "falling back to the system browser")
                webview = None     # fall through to the browser path
        # ---- honest fallback: no pywebview or window failed ----
        if webview is None and not _pywebview() and not _SHUTDOWN.is_set():
            print("[LPU] pywebview is not installed -> falling back to the "
                  "system browser (install once with: "
                  "pip install pywebview)")
        if fallback_open_browser and not _SHUTDOWN.is_set():
            # covers BOTH cases: our own server (not attached) and an
            # already-running accelerator we attached to (V7.1.1 fix:
            # previously the attached case exited silently doing nothing)
            try:
                import webbrowser
                webbrowser.open(url)
            except Exception:  # noqa: BLE001
                pass
        print(f"[LPU] Accelerator server running at {url} "
              "(Ctrl+C stops ONLY the accelerator; training is untouched)")
        if server_thread is not None:
            _serve_until_closed(server_thread)
        return {"mode": "browser-fallback", "port": port}
    finally:
        # attach mode: the server belongs to ANOTHER process - never stop it
        if owns_server and server_thread is not None:
            server_thread.stop()
            print("[LPU] native window closed -> accelerator server stopped "
                  "(training processes untouched)")


def main(argv: Optional[list] = None) -> int:
    import argparse

    parser = argparse.ArgumentParser(
        prog="lpu-desktop",
        description="LPU AI Accelerator V7 — native desktop control center "
                    "(no browser required)")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=8710)
    parser.add_argument("--config", default=None)
    parser.add_argument("--no-browser-fallback", action="store_true",
                        help="in fallback mode, do not open the system browser")
    args = parser.parse_args(argv)

    cfg = {}
    if args.config:
        import yaml
        cfg = yaml.safe_load(Path(args.config).read_text(encoding="utf-8")) or {}
    result = launch_desktop(cfg, host=args.host, start_port=args.port,
                            fallback_open_browser=not args.no_browser_fallback)
    print(f"[LPU] desktop session ended (mode={result['mode']}, "
          f"port={result['port']})")
    return 0


if __name__ == "__main__":  # pragma: no cover
    raise SystemExit(main())