preview-dashboard.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
  47. function runtimeIsRunning(state, isAlive) {
  48. return state?.status === 'running' && isAlive(state.pid);
  49. }
  50. async function ensureCallbackRuntime({ workspaceRoot, timeoutMs = 15000 } = {}) {
  51. const stateModuleUrl = pathToFileURL(path.join(
  52. __dirname,
  53. '..',
  54. 'runtime',
  55. 'callback-service',
  56. 'src',
  57. 'runtime-state.mjs',
  58. )).href;
  59. const { isProcessAlive, readRuntimeState } = await import(stateModuleUrl);
  60. let state = readRuntimeState();
  61. if (runtimeIsRunning(state, isProcessAlive)) {
  62. return { ...state, reused: true };
  63. }
  64. const deadline = Date.now() + timeoutMs;
  65. while (state.pid && isProcessAlive(state.pid) && state.status !== 'stopped' && Date.now() < deadline) {
  66. await delay(100);
  67. state = readRuntimeState();
  68. if (runtimeIsRunning(state, isProcessAlive)) return { ...state, reused: true };
  69. }
  70. if (state.pid && isProcessAlive(state.pid) && state.status !== 'stopped') {
  71. throw new Error(`Qiwei runtime pid=${state.pid} is still ${state.status || 'unknown'}.`);
  72. }
  73. const runtimeScript = path.join(__dirname, 'start-callback-runtime.mjs');
  74. const child = spawn(process.execPath, [runtimeScript, 'start', '--no-dashboard'], {
  75. cwd: workspaceRoot,
  76. env: { ...process.env, QIWEI_WORKSPACE_ROOT: workspaceRoot },
  77. detached: true,
  78. stdio: 'ignore',
  79. windowsHide: true,
  80. });
  81. child.unref();
  82. while (Date.now() < deadline) {
  83. await delay(100);
  84. state = readRuntimeState();
  85. if (runtimeIsRunning(state, isProcessAlive)) {
  86. return { ...state, reused: false };
  87. }
  88. if (state.pid === child.pid && state.status === 'stopped') {
  89. throw new Error(`Qiwei runtime stopped during startup: ${state.stopReason || 'unknown reason'}`);
  90. }
  91. }
  92. throw new Error(`Qiwei runtime did not become ready within ${timeoutMs}ms.`);
  93. }
  94. function printStartupSummary(baseUrl, summary, workspaceRoot, alreadyRunning) {
  95. process.stdout.write([
  96. '',
  97. `企微工作台${alreadyRunning ? '已在运行' : '启动成功'}:${baseUrl}/#agent`,
  98. `项目目录:${workspaceRoot}`,
  99. `产品模式:${summary.product?.label || '个人版'} · ${summary.product?.collectionLabel || '本地主动监听'}`,
  100. '',
  101. '启动检查:',
  102. ...summary.checks.map(item => ` ${item.ready ? '[完成]' : '[待处理]'} ${item.label}${item.ready ? '' : ` — ${item.action}`}`),
  103. '',
  104. `下一步:${summary.nextAction}`,
  105. '',
  106. ].join('\n'));
  107. }
  108. async function main() {
  109. const options = parseArgs();
  110. process.env.QIWEI_DASHBOARD_PORT = String(options.port);
  111. const context = applyWorkspaceContext({ packageRoot: path.resolve(__dirname, '..') });
  112. const expectedWorkspaceId = workspaceIdentity(context.workspaceRoot);
  113. const baseUrl = `http://127.0.0.1:${options.port}`;
  114. const current = await inspectRunningServer(baseUrl, expectedWorkspaceId);
  115. if (current.occupied) {
  116. throw new Error(`端口 ${options.port} 正被另一个企微项目使用。请关闭旧工作台,或使用 npm run preview -- --port ${options.port + 1}`);
  117. }
  118. let server = null;
  119. if (!current.running) {
  120. const { startServer } = require('../mcp/src/dashboard/server');
  121. ({ server } = await startServer(options.port));
  122. }
  123. try {
  124. const runtime = await ensureCallbackRuntime({ workspaceRoot: context.workspaceRoot });
  125. process.stdout.write(`Qiwei runtime ${runtime.reused ? 'reused' : 'started'} independently (pid=${runtime.pid}).\n`);
  126. } catch (error) {
  127. process.stderr.write(`Qiwei runtime startup is pending: ${error.message}\n`);
  128. }
  129. let status = {};
  130. let agent = {};
  131. try {
  132. [status, agent] = await Promise.all([
  133. requestJson(`${baseUrl}/api/status`),
  134. requestJson(`${baseUrl}/api/agent/status`),
  135. ]);
  136. } catch (error) {
  137. process.stderr.write(`工作台已启动,但启动状态读取失败:${error.message}\n`);
  138. }
  139. const summary = buildStartupSummary(status, agent);
  140. printStartupSummary(baseUrl, summary, context.workspaceRoot, current.running);
  141. if (options.openBrowser) openUrl(`${baseUrl}/#agent`);
  142. if (current.running && !server) return;
  143. if (server) {
  144. let shuttingDown = false;
  145. const shutdown = signal => {
  146. if (shuttingDown) return;
  147. shuttingDown = true;
  148. process.stdout.write(`Closing dashboard after ${signal}; callback runtime remains active.\n`);
  149. server.close(() => process.exit(0));
  150. setTimeout(() => process.exit(0), 3000).unref();
  151. };
  152. process.once('SIGINT', () => shutdown('SIGINT'));
  153. process.once('SIGTERM', () => shutdown('SIGTERM'));
  154. }
  155. }
  156. if (require.main === module) {
  157. main().catch(error => {
  158. process.stderr.write(`启动预览失败:${error.message}\n`);
  159. process.exit(1);
  160. });
  161. }
  162. module.exports = {
  163. parseArgs,
  164. inspectRunningServer,
  165. runtimeIsRunning,
  166. ensureCallbackRuntime,
  167. };