refactor(desktop): 使用预分配端口替代 stdout 解析获取服务器端口

This commit is contained in:
2026-02-07 19:32:56 +08:00
parent 14bcdb33af
commit 3306e18395
2 changed files with 53 additions and 59 deletions

View File

@@ -62,8 +62,9 @@ The desktop build is orchestrated by Turbo. It depends on the server's productio
### Server Lifecycle
In production, the main process manages the embedded server:
- **Spawn**: Spawns server from `server-output/server/index.mjs` using `Bun.spawn`.
- **Port Allocation**: Server is started with `PORT=0` and `HOST=127.0.0.1`.
- **Port Detection**: The main process parses the server's `stdout` using a regex to find the dynamically assigned port.
- **Port Allocation**: A free port is pre-allocated via `node:net` (`createServer` on `127.0.0.1:0`), then passed to the server as the `PORT` environment variable.
- **Readiness Check**: The main process polls the server URL with `fetch` until it responds, rather than parsing stdout.
- **Retry**: If the server fails to become ready (timeout or early exit), the process is killed and a new attempt is made with a fresh port (up to 3 retries).
- **Lifecycle**: The server process is tied to the app; it is killed on `SIGTERM`, `SIGINT`, or app exit. If the server process crashes, the app exits with an error.
## Environment Detection
@@ -119,7 +120,7 @@ const serverEntryPath = join(PATHS.VIEWS_FOLDER, '..', 'server-output', 'server'
**DO:**
- Use arrow functions for all components and utility functions.
- Ensure `apps/server` is built before building `apps/desktop` (handled by Turbo).
- Parse the server's stdout for the port instead of hardcoding ports in production.
- Pre-allocate a free port and pass it via `PORT` env var instead of parsing stdout.
- Handle server process termination to avoid orphan processes.
- Use `catalog:` for all dependency versions in `package.json`.