preview-dashboard.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #!/usr/bin/env node
  2. const path = require('path');
  3. const { spawn } = require('child_process');
  4. const { pathToFileURL } = require('url');
  5. const { applyWorkspaceContext, workspaceIdentity } = require('../mcp/src/core/runtime-context');
  6. const { buildStartupSummary } = require('../mcp/src/core/startup-summary');
  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. const expectedWorkspaceId = workspaceIdentity(context.workspaceRoot);
  65. const baseUrl = `http://127.0.0.1:${options.port}`;
  66. const current = await inspectRunningServer(baseUrl, expectedWorkspaceId);
  67. if (current.occupied) {
  68. throw new Error(`端口 ${options.port} 正被另一个企微项目使用。请关闭旧工作台,或使用 npm run preview -- --port ${options.port + 1}`);
  69. }
  70. let server = null;
  71. let runtime = null;
  72. if (!current.running) {
  73. const { startServer } = require('../mcp/src/dashboard/server');
  74. ({ server } = await startServer(options.port));
  75. try {
  76. const runtimeModuleUrl = pathToFileURL(path.join(__dirname, '..', 'runtime', 'callback-service', 'src', 'index.mjs')).href;
  77. const runtimeModule = await import(runtimeModuleUrl);
  78. runtime = await runtimeModule.startRuntime({ embedded: true, dashboard: false });
  79. } catch (error) {
  80. process.stderr.write(`Qiwei runtime startup is pending: ${error.message}\n`);
  81. }
  82. }
  83. let status = {};
  84. let agent = {};
  85. try {
  86. [status, agent] = await Promise.all([
  87. requestJson(`${baseUrl}/api/status`),
  88. requestJson(`${baseUrl}/api/agent/status`),
  89. ]);
  90. } catch (error) {
  91. process.stderr.write(`工作台已启动,但启动状态读取失败:${error.message}\n`);
  92. }
  93. const summary = buildStartupSummary(status, agent);
  94. printStartupSummary(baseUrl, summary, context.workspaceRoot, current.running);
  95. if (options.openBrowser) openUrl(`${baseUrl}/#agent`);
  96. if (current.running && !server) return;
  97. if (runtime) {
  98. let shuttingDown = false;
  99. const shutdown = signal => {
  100. if (shuttingDown) return;
  101. shuttingDown = true;
  102. runtime.stop(signal).finally(() => process.exit(0));
  103. };
  104. process.once('SIGINT', () => shutdown('SIGINT'));
  105. process.once('SIGTERM', () => shutdown('SIGTERM'));
  106. }
  107. }
  108. if (require.main === module) {
  109. main().catch(error => {
  110. process.stderr.write(`启动预览失败:${error.message}\n`);
  111. process.exit(1);
  112. });
  113. }
  114. module.exports = {
  115. parseArgs,
  116. inspectRunningServer,
  117. };