preview-dashboard.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #!/usr/bin/env node
  2. const path = require('path');
  3. const { spawn } = require('child_process');
  4. const { applyWorkspaceContext, workspaceIdentity } = require('../mcp/src/core/runtime-context');
  5. const { buildStartupSummary } = require('../mcp/src/core/startup-summary');
  6. const { ensureRelayDaemon } = require('../mcp/src/core/relay-daemon');
  7. function parseArgs(argv = process.argv.slice(2)) {
  8. const portIndex = argv.indexOf('--port');
  9. const port = portIndex >= 0 ? Number(argv[portIndex + 1]) : Number(process.env.QIWEI_DASHBOARD_PORT || 4320);
  10. if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('端口无效,请使用 --port 4320 这类有效端口');
  11. return { port, openBrowser: !argv.includes('--no-open') };
  12. }
  13. async function requestJson(url, timeoutMs = 15000) {
  14. const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
  15. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  16. return response.json();
  17. }
  18. async function inspectRunningServer(baseUrl, expectedWorkspaceId) {
  19. try {
  20. const health = await requestJson(`${baseUrl}/api/health`, 2500);
  21. const actualWorkspaceId = health.data?.workspaceId || '';
  22. if (actualWorkspaceId && actualWorkspaceId !== expectedWorkspaceId) {
  23. return { running: false, occupied: true, actualWorkspaceId };
  24. }
  25. return { running: health.status === 'ok', occupied: false, health };
  26. } catch {
  27. return { running: false, occupied: false };
  28. }
  29. }
  30. function openUrl(url) {
  31. let command;
  32. let args;
  33. if (process.platform === 'win32') {
  34. command = 'cmd.exe';
  35. args = ['/d', '/s', '/c', 'start', '', url];
  36. } else if (process.platform === 'darwin') {
  37. command = 'open';
  38. args = [url];
  39. } else {
  40. command = 'xdg-open';
  41. args = [url];
  42. }
  43. const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: true });
  44. child.unref();
  45. }
  46. function printStartupSummary(baseUrl, summary, workspaceRoot, alreadyRunning) {
  47. process.stdout.write([
  48. '',
  49. `企微工作台${alreadyRunning ? '已在运行' : '启动成功'}:${baseUrl}/#agent`,
  50. `项目目录:${workspaceRoot}`,
  51. `产品模式:${summary.product?.label || '个人版'} · ${summary.product?.collectionLabel || '本地主动监听'}`,
  52. '',
  53. '启动检查:',
  54. ...summary.checks.map(item => ` ${item.ready ? '[完成]' : '[待处理]'} ${item.label}${item.ready ? '' : ` — ${item.action}`}`),
  55. '',
  56. `下一步:${summary.nextAction}`,
  57. '',
  58. ].join('\n'));
  59. }
  60. async function main() {
  61. const options = parseArgs();
  62. process.env.QIWEI_DASHBOARD_PORT = String(options.port);
  63. const context = applyWorkspaceContext({ packageRoot: path.resolve(__dirname, '..') });
  64. ensureRelayDaemon();
  65. const expectedWorkspaceId = workspaceIdentity(context.workspaceRoot);
  66. const baseUrl = `http://127.0.0.1:${options.port}`;
  67. const current = await inspectRunningServer(baseUrl, expectedWorkspaceId);
  68. if (current.occupied) {
  69. throw new Error(`端口 ${options.port} 正被另一个企微项目使用。请关闭旧工作台,或使用 npm run preview -- --port ${options.port + 1}`);
  70. }
  71. let server = null;
  72. if (!current.running) {
  73. const { startServer } = require('../mcp/src/dashboard/server');
  74. ({ server } = await startServer(options.port));
  75. }
  76. let status = {};
  77. let agent = {};
  78. try {
  79. [status, agent] = await Promise.all([
  80. requestJson(`${baseUrl}/api/status`),
  81. requestJson(`${baseUrl}/api/agent/status`),
  82. ]);
  83. } catch (error) {
  84. process.stderr.write(`工作台已启动,但启动状态读取失败:${error.message}\n`);
  85. }
  86. const summary = buildStartupSummary(status, agent);
  87. printStartupSummary(baseUrl, summary, context.workspaceRoot, current.running);
  88. if (options.openBrowser) openUrl(`${baseUrl}/#agent`);
  89. if (current.running && !server) return;
  90. }
  91. if (require.main === module) {
  92. main().catch(error => {
  93. process.stderr.write(`启动预览失败:${error.message}\n`);
  94. process.exit(1);
  95. });
  96. }
  97. module.exports = {
  98. parseArgs,
  99. inspectRunningServer,
  100. };