preview-dashboard.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. '',
  51. '启动检查:',
  52. ...summary.checks.map(item => ` ${item.ready ? '[完成]' : '[待处理]'} ${item.label}${item.ready ? '' : ` — ${item.action}`}`),
  53. '',
  54. `下一步:${summary.nextAction}`,
  55. '',
  56. ].join('\n'));
  57. }
  58. async function main() {
  59. const options = parseArgs();
  60. process.env.QIWEI_DASHBOARD_PORT = String(options.port);
  61. const context = applyWorkspaceContext({ packageRoot: path.resolve(__dirname, '..') });
  62. const expectedWorkspaceId = workspaceIdentity(context.workspaceRoot);
  63. const baseUrl = `http://127.0.0.1:${options.port}`;
  64. const current = await inspectRunningServer(baseUrl, expectedWorkspaceId);
  65. if (current.occupied) {
  66. throw new Error(`端口 ${options.port} 正被另一个企微项目使用。请关闭旧工作台,或使用 npm run preview -- --port ${options.port + 1}`);
  67. }
  68. let server = null;
  69. if (!current.running) {
  70. const { startServer } = require('../mcp/src/dashboard/server');
  71. ({ server } = await startServer(options.port));
  72. }
  73. let status = {};
  74. let agent = {};
  75. try {
  76. [status, agent] = await Promise.all([
  77. requestJson(`${baseUrl}/api/status`),
  78. requestJson(`${baseUrl}/api/agent/status`),
  79. ]);
  80. } catch (error) {
  81. process.stderr.write(`工作台已启动,但启动状态读取失败:${error.message}\n`);
  82. }
  83. const summary = buildStartupSummary(status, agent);
  84. printStartupSummary(baseUrl, summary, context.workspaceRoot, current.running);
  85. if (options.openBrowser) openUrl(`${baseUrl}/#agent`);
  86. if (current.running && !server) return;
  87. }
  88. if (require.main === module) {
  89. main().catch(error => {
  90. process.stderr.write(`启动预览失败:${error.message}\n`);
  91. process.exit(1);
  92. });
  93. }
  94. module.exports = {
  95. parseArgs,
  96. inspectRunningServer,
  97. };