终端在 Windows 上起不来 (打包规则漏解包)
- 根因: build.asarUnpack 写的是 "**/node_modules/@lydell/node-pty-*/*", 只匹配一层,
于是 prebuilds/<plat>/ 下的文件没被解包, 留在 app.asar 里
- Windows 上这些必须是磁盘上的真实文件: conpty.dll (OS loader 加载)、
OpenConsole.exe (CreateProcess)、以及 node-pty 用 worker_threads.Worker 起的
conoutSocketWorker.js —— node-pty 本身就写了
__dirname.replace('node_modules.asar', 'node_modules.asar.unpacked') 来适配
- Linux 上看不出来: 只需要一个 pty.node, Electron 的 asar 层能 dlopen 归档里的 .node
- 修复: 规则递归化为 "**/node_modules/@lydell/node-pty-*/**/*"
- 验证: 重新打包后 pty.node 已落到 app.asar.unpacked, 安装版真实 spawn 成功
Windows 保留设备名 / 尾部点空格导致落盘写错
- 新增 src/main/safe-name.ts 的 safeFileName()
- Win32 把 CON/PRN/AUX/NUL/COM1-9/LPT1-9 (带扩展名也算) 当设备, open() 打开的不是文件;
还会悄悄吃掉文件名结尾的点和空格, 导致 existsSync 判断和实际落盘对不上
- 两处落盘都接上: file-server.ts 的 targetPath()、drive.ts 的 downloadDriveFile()
(后者名字来自对端共享目录, 属不可信输入)
- 策略是"最小必要": 非法字符全平台都清, 保留名和尾点空格只在 win32 上改写,
避免动到 Linux 上合法的文件名
其他
- 终端 cwd: Windows 优先用 USERPROFILE (装了 Git Bash 时 HOME 可能是 POSIX 路径, Win32 下不存在)
- USB 面板空列表提示按平台给, 不再一律说"Linux 用户需要在 dialout 组"
分析文档与自测
- 新增 docs/windows-compat.md: 各原生模块的 N-API 情况、已有 win32 分支的位置、
已知限制 (ConPTY 需 Win10 1809+、防火墙首次弹窗、USB 需 WinUSB 驱动等)、
以及一份 Windows 真机验证清单
- 自测新增 S1-S8 组: 保留名改写、尾部点空格、非法字符、跨平台不过度清洗、
超长截断、默认 shell/cwd、asarUnpack 规则回归护栏、上传落盘 + 路径穿越
- 全部 38 条用例通过
8.0 KiB
LocalNetMsg Agent Guide
LAN instant-messaging desktop app. Stack: Electron 32 + Vue 3 + TypeScript + Vite + Pinia + Element Plus + SQLite (better-sqlite3). Three independent processes built by electron-vite.
Commands
| Task | Command |
|---|---|
| Dev (Electron + HMR) | npm run dev |
| Build (no installer) | npm run build |
| Typecheck main+preload | npm run typecheck:node |
| Typecheck renderer | npm run typecheck:web |
| Typecheck both | npm run typecheck |
| Remote feature self-test (terminal / forward / USB) | npm run selftest |
| Windows installer | npm run package:win → dist-Electron\LocalNetMsg-0.1.0-Setup.exe |
| macOS / Linux | npm run package:mac / npm run package:linux |
| Unpacked dir only | npm run package:dir |
All package:* scripts bake in ELECTRON_MIRROR + ELECTRON_BUILDER_BINARIES_MIRROR (npmmirror.com). Do not remove unless on the open internet.
npm run selftest runs the remote (terminal / port-forward / USB) self-test: one process, two virtual
nodes, real ChatServer + ChatClient + remote managers. See scripts/selftest/.
Verify changes via npm run typecheck + npm run selftest + manual npm run dev.
Layout
src/
main/ Electron main process (Node) — entry: index.ts
discovery.ts UDP broadcast beacon (multi-NIC, per-interface subnet bcast)
chat-server.ts WebSocketServer on 0.0.0.0:47900
chat-client.ts Outgoing WS with backoff reconnect
file-server.ts HTTP /upload + /file, default cap 100GB
db.ts SQLite via better-sqlite3 (data/app.db)
settings.ts electron-store wrapper (~/AppData/Roaming/local-net-msg/config.json)
notify.ts System Notification + Windows overlay badge
ipc.ts All ipcMain.handle() wiring
protocol.ts MessageEnvelope, WsFrame, DeviceInfo types
preload/ contextBridge exposing typed API to renderer
renderer/ Vue 3 SPA (Vite root)
src/
main.ts createApp + Pinia + ElementPlus (full import) + zhCn
App.vue Global event listeners (device:*, message:*, settings:*)
components/ Sidebar, ChatView, MessageInput, MessageItem, SettingsView, MarkdownView
stores/ Pinia: device.ts, message.ts, session.ts
api.ts IPC typings (mirrors preload)
utils/ format.ts (colorFor, initialsOf, formatSize, ...)
electron.vite.config.ts Three builds → out/{main,preload,renderer}/
Renderer alias: @ → src/renderer/src.
Network protocol
UDP discovery on 47800, chat WS on 47900, file HTTP on 47901. All three bind 0.0.0.0 and auto-shift on conflict.
DeviceInfo carries address (chosen from the first non-internal IPv4 of the responding NIC) plus chatPort/filePort. The chat server sends no broadcast of its own — discovery comes purely from UDP. Receiver uses rinfo.address (real source IP), never the payload's self.address.
Hard-won pitfalls (don't repeat these)
-
chat-clientMUST have anon('error')listener. Node EventEmitter throwsERR_UNHANDLED_ERRORand kills the main process if'error'fires with no listener. The WS'error'event is followed by'close'which triggers reconnect. Don't try to "fix" by emitting on the client; justconsole.warnand move on. -
Drag-drop file path. Electron 32 removed
File.path. UsewebUtils.getPathForFile(file)fromelectron— exposed insrc/preload/index.tsasgetPathForFile(file). Callers must read it viawindow.api.getPathForFile(f)BEFORE the await boundary. -
Native rebuild.
postinstallrunselectron-builder install-app-depsto rebuildbetter-sqlite3against the bundled Electron ABI. Afternpm ior upgrading Electron, this must run. If you forget, sqlite open will throw on launch. -
mkdirfor Windows reserved names. Output dir isdist-Electron\(escaped;dist\electronchokes on Windows). Don't rename without verifying the build still produces a valid path. -
nsisisoneClick: false. Installer asks for install path + creates Desktop/Start-Menu shortcuts. Permissions are user-scoped. -
Renderer global drag highlight. Track
dragenter/dragleavewith a depth counter (not a boolean) — child elements fire leave/enter pairs. SeeMessageInput.vue'sdragDepth. -
WS 通道状态要"拉取式"同步, 不能只靠事件推送. 聊天框顶部显示的是"通道可用"(outgoing 或 inbound 任一 WS 活着),跟侧边栏的"设备在线"(UDP 发现)是两回事。启动时主进程往往先连上对端(
index.ts里connectTo早于createMainWindow),那条device:wsState事件会在渲染层订阅之前就发出去被丢掉 —— 早期实现只有事件推送,UI 因此永久停在"等待重连…",而连接其实一直是好的。规矩:(1)device:wsState推全量快照而不是增量;(2) 渲染层 mount 时主动invoke('app:state')拉一次;(3) 渲染层先注册监听再 await,否则 await 期间的事件也会丢。详见docs/connection-status.md。 -
File conflict naming. Append
_Nbefore the first.:archive.tar.gz→archive_1.tar.gz,.bashrc→.bashrc_1. Logic infile-server.tstargetPath().
Configuration knobs
LNM_MAX_FILE_SIZE=<bytes>env var overrides the 100 GB default infile-server.ts. Useful for testing the limit path.deviceName,downloadDir,notifications,autoStartlive in~/AppData/Roaming/local-net-msg/config.jsonviaelectron-store. Edit the file directly while dev is stopped.data/app.db— SQLite DB. DELETE to reset all devices/messages. Auto-migrates on next launch.
Packaging gotcha
release/ contains an app.asar Windows cannot delete while the previous app instance holds a file handle. Build now writes to dist-Electron\ to dodge this. If you ever switch back, kill the running app first or you'll get EPERM.
Linux packaging (icon + taskbar)
Ubuntu 装完"没图标"是个坑,有两个独立原因:
-
linux.icon必须指向目录,不能是单张 PNG。 electron-builder 把图标装进/usr/share/icons/hicolor/<size>x<size>/apps/<exe>.png,而单张 PNG 交给app-builder时它解析不出尺寸(返回size: 0),于是装进hicolor/0x0/这种非法目录,桌面环境根本找不到 → 启动器没图标。正确做法是给一个目录,里面按<size>x<size>.png命名:resources/icons/{16,24,32,48,64,128,256,512}x{...}.png,然后linux.icon = "resources/icons"。图标集用node scripts/make-icon.js生成(需要 ImageMagick 的convert;生成结果已提交,平时不用跑)。 -
StartupWMClass要跟窗口真实的 WM_CLASS 一致。 electron-builder 默认填productName(LocalNetMsg),但 Electron 实际设的是可执行文件名(local-net-msg)—— 对不上,任务栏就找不到对应启动器,显示成通用图标。用xprop -id <wid> WM_CLASS确认真实值,然后在build.linux.desktop.StartupWMClass里写它。
Windows / macOS 仍用单张 resources/icon.png(那里不按尺寸分目录)。
Windows 兼容性
完整的分析、已修问题和待验证清单见 docs/windows-compat.md。最容易踩的两个:
-
build.asarUnpack里的原生模块规则必须递归(**/*)。 node-pty 1.2 是"主包 + 平台包"拆包架构,平台包@lydell/node-pty-<platform>-<arch>里除了.node还有conpty.dll/OpenConsole.exe,而 node-pty 的 ConPTY worker 用worker_threads.Worker起脚本——都必须是磁盘上的真实文件。规则写成.../node-pty-*/*(单层)会把prebuilds/<plat>/下的东西留在 asar 里,Windows 终端直接起不来(Linux 上看不出来,因为只需要一个.node)。自测 S7 守着这条规则。 -
Windows 保留设备名:
CONPRNAUXNULCOM1-9LPT1-9(带扩展名也算)不能直接当文件名——对它们open()打开的是设备不是文件。落盘前统一走src/main/safe-name.ts的safeFileName()(按本机平台决定要不要改写,Linux 上CON是合法文件名,不该动)。