preview-dashboard.js 3.9 KB

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