github-actions[bot] commited on
Commit
0196166
·
1 Parent(s): 6d4f5fa

Update from GitHub Actions

Browse files
.cnb.yml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ master:
2
+ push:
3
+ - docker:
4
+ image: node:18
5
+ imports: https://cnb.cool/godgodgame/oci-private-key/-/blob/main/envs.yml
6
+ stages:
7
+ - name: 环境检查
8
+ script: echo $GITHUB_TOKEN_GK && echo $GITHUB_TOKEN && node -v && npm -v
9
+ - name: 将master分支同步更新到github的master分支
10
+ script: git push https://$GITHUB_TOKEN_GK:$GITHUB_TOKEN@github.com/zhezzma/cloudstudio-runner.git HEAD:master
.env.example ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 环境变量配置示例文件
2
+ # 复制此文件为 .env 并根据需要修改配置
3
+
4
+ # WebIDE URL - 如果设置了此环境变量,将覆盖 config.js 中的默认 webideUrl
5
+ # WEBIDE_URL=https://your-custom-webide-url.com/edit
6
+
7
+ # 调度器时间间隔(毫秒)- 如果设置了此环境变量,将覆盖 config.js 中的默认值
8
+ # 默认为 600000 毫秒(10分钟)
9
+ # SCHEDULER_INTERVAL=600000
10
+
11
+ # 浏览器无头模式 - 如果设置了此环境变量,将覆盖 config.js 中的默认值
12
+ # 默认为 true(无头模式),设置为 false 可以显示浏览器界面
13
+ # HEADLESS=false
14
+
15
+ # Cookies - 如果设置了此环境变量,将优先使用环境变量中的cookies而不是cookies.json文件
16
+ # 格式为JSON字符串,包含从浏览器导出的cookies数组
17
+ # COOKIES='[{"name":"session","value":"abc123","domain":".example.com","path":"/"}]'
18
+
19
+ # 示例:
20
+ # WEBIDE_URL=https://3e8ccf585a6c4fbd9f1aa9f05ac5e415.ap-shanghai.cloudstudio.club/?mode=edit
21
+ # SCHEDULER_INTERVAL=300000 # 5分钟
22
+ # SCHEDULER_INTERVAL=900000 # 15分钟
Dockerfile ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 基础镜像:使用 Node.js 20 的 Alpine Linux 版本
2
+ FROM node:20-alpine
3
+
4
+ # 设置工作目录
5
+ WORKDIR /app
6
+
7
+ # 安装系统依赖
8
+ RUN apk add --no-cache \
9
+ # 基本构建工具
10
+ python3 \
11
+ make \
12
+ g++ \
13
+ # Playwright 依赖
14
+ chromium \
15
+ nss \
16
+ freetype \
17
+ freetype-dev \
18
+ harfbuzz \
19
+ ca-certificates \
20
+ ttf-freefont \
21
+ # 其他依赖
22
+ gcompat
23
+
24
+ # 设置 Playwright 的环境变量
25
+ ENV PLAYWRIGHT_BROWSERS_PATH=/usr/bin
26
+ ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
27
+ ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium-browser
28
+ ENV PLAYWRIGHT_SKIP_BROWSER_VALIDATION=1
29
+
30
+ # 复制 package.json 和 package-lock.json
31
+ COPY package*.json ./
32
+
33
+ # 复制应用程序文件
34
+ COPY src/ ./src/
35
+
36
+ # 复制 cookies.json 文件(如果存在)
37
+ # 使用通配符语法,如果文件不存在则跳过,不会报错
38
+ COPY cookies.json* ./
39
+
40
+ # 安装 Node.js 依赖
41
+ RUN npm ci --only=production
42
+
43
+ # 设置非 root 用户(安全最佳实践)
44
+ RUN addgroup -g 1001 -S nodejs && \
45
+ adduser -S nodejs -u 1001
46
+
47
+ # 创建 screenshots 和 logs 目录,并设置正确的权限
48
+ RUN mkdir -p /app/screenshots && \
49
+ mkdir -p /app/logs && \
50
+ chown -R nodejs:nodejs /app && \
51
+ chmod -R 777 /app/screenshots && \
52
+ chmod -R 777 /app/logs
53
+
54
+ # 切换到非 root 用户
55
+ USER nodejs
56
+
57
+ # 暴露端口 7860 用于 Web 服务器
58
+ EXPOSE 7860
59
+
60
+ # 设置默认命令 - 启动 Web 服务器
61
+ CMD ["npm", "start"]
package-lock.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "cloudstudio-runner",
3
+ "version": "1.0.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "cloudstudio-runner",
9
+ "version": "1.0.0",
10
+ "license": "ISC",
11
+ "dependencies": {
12
+ "@hono/node-server": "^1.14.2",
13
+ "dotenv": "^16.5.0",
14
+ "hono": "^4.7.10",
15
+ "playwright": "^1.52.0"
16
+ }
17
+ },
18
+ "node_modules/@hono/node-server": {
19
+ "version": "1.14.2",
20
+ "resolved": "https://registry.npmmirror.com/@hono/node-server/-/node-server-1.14.2.tgz",
21
+ "integrity": "sha512-GHjpOeHYbr9d1vkID2sNUYkl5IxumyhDrUJB7wBp7jvqYwPFt+oNKsAPBRcdSbV7kIrXhouLE199ks1QcK4r7A==",
22
+ "license": "MIT",
23
+ "engines": {
24
+ "node": ">=18.14.1"
25
+ },
26
+ "peerDependencies": {
27
+ "hono": "^4"
28
+ }
29
+ },
30
+ "node_modules/dotenv": {
31
+ "version": "16.5.0",
32
+ "resolved": "https://registry.npmmirror.com/dotenv/-/dotenv-16.5.0.tgz",
33
+ "integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==",
34
+ "license": "BSD-2-Clause",
35
+ "engines": {
36
+ "node": ">=12"
37
+ },
38
+ "funding": {
39
+ "url": "https://dotenvx.com"
40
+ }
41
+ },
42
+ "node_modules/fsevents": {
43
+ "version": "2.3.2",
44
+ "resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.2.tgz",
45
+ "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
46
+ "hasInstallScript": true,
47
+ "license": "MIT",
48
+ "optional": true,
49
+ "os": [
50
+ "darwin"
51
+ ],
52
+ "engines": {
53
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
54
+ }
55
+ },
56
+ "node_modules/hono": {
57
+ "version": "4.7.10",
58
+ "resolved": "https://registry.npmmirror.com/hono/-/hono-4.7.10.tgz",
59
+ "integrity": "sha512-QkACju9MiN59CKSY5JsGZCYmPZkA6sIW6OFCUp7qDjZu6S6KHtJHhAc9Uy9mV9F8PJ1/HQ3ybZF2yjCa/73fvQ==",
60
+ "license": "MIT",
61
+ "engines": {
62
+ "node": ">=16.9.0"
63
+ }
64
+ },
65
+ "node_modules/playwright": {
66
+ "version": "1.52.0",
67
+ "resolved": "https://registry.npmmirror.com/playwright/-/playwright-1.52.0.tgz",
68
+ "integrity": "sha512-JAwMNMBlxJ2oD1kce4KPtMkDeKGHQstdpFPcPH3maElAXon/QZeTvtsfXmTMRyO9TslfoYOXkSsvao2nE1ilTw==",
69
+ "license": "Apache-2.0",
70
+ "dependencies": {
71
+ "playwright-core": "1.52.0"
72
+ },
73
+ "bin": {
74
+ "playwright": "cli.js"
75
+ },
76
+ "engines": {
77
+ "node": ">=18"
78
+ },
79
+ "optionalDependencies": {
80
+ "fsevents": "2.3.2"
81
+ }
82
+ },
83
+ "node_modules/playwright-core": {
84
+ "version": "1.52.0",
85
+ "resolved": "https://registry.npmmirror.com/playwright-core/-/playwright-core-1.52.0.tgz",
86
+ "integrity": "sha512-l2osTgLXSMeuLZOML9qYODUQoPPnUsKsb5/P6LJ2e6uPKXUdPK5WYhN4z03G+YNbWmGDY4YENauNu4ZKczreHg==",
87
+ "license": "Apache-2.0",
88
+ "bin": {
89
+ "playwright-core": "cli.js"
90
+ },
91
+ "engines": {
92
+ "node": ">=18"
93
+ }
94
+ }
95
+ }
96
+ }
package.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "cloudstudio-runner",
3
+ "version": "1.0.0",
4
+ "description": "Playwright automation for CloudStudio WebIDE",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "login": "node src/login.js",
8
+ "execute": "node src/execute-command.js",
9
+ "scheduler": "node src/scheduler.js",
10
+ "web-server": "node src/web-server.js",
11
+ "start": "node src/start-services.js"
12
+ },
13
+ "keywords": ["playwright", "automation", "webide"],
14
+ "author": "",
15
+ "license": "ISC",
16
+ "type": "module",
17
+ "dependencies": {
18
+ "@hono/node-server": "^1.13.7",
19
+ "dotenv": "^16.5.0",
20
+ "hono": "^4.6.12",
21
+ "playwright": "^1.52.0"
22
+ }
23
+ }
src/config.js ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // 配置文件
2
+ import dotenv from 'dotenv';
3
+
4
+ // 加载环境变量
5
+ dotenv.config();
6
+
7
+ const config = {
8
+ // WebIDE URL - 可以通过环境变量 WEBIDE_URL 覆盖
9
+ webideUrl: process.env.WEBIDE_URL || '',
10
+
11
+ // 调度器时间间隔(毫秒)- 可以通过环境变量 SCHEDULER_INTERVAL 覆盖
12
+ // 默认为 10 分钟 (10 * 60 * 1000 = 600000 毫秒)
13
+ schedulerInterval: parseInt(process.env.SCHEDULER_INTERVAL) || 9 * 60 * 1000,
14
+
15
+ // Cookie文件路径
16
+ cookieFile: './cookies.json',
17
+
18
+ // Cookie环境变量 - 如果设置了此环境变量,将优先使用环境变量中的cookies
19
+ cookiesFromEnv: process.env.COOKIES,
20
+
21
+ // 浏览器配置
22
+ browserOptions: {
23
+ // 默认无头模式,可通过环境变量 HEADLESS=false 设置为有头模式
24
+ // 支持 false/False/FALSE 等不同大小写形式
25
+ headless: (process.env.HEADLESS || 'true').toLowerCase() !== 'false',
26
+ slowMo: 100, // 操作间隔时间(毫秒)
27
+ timeout: 30000, // 超时时间(毫秒)
28
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
29
+ },
30
+
31
+ // 要执行的命令
32
+ command: 'service cron start && date',
33
+
34
+ // 截图保存目录
35
+ screenshotDir: './screenshots',
36
+
37
+ // 等待时间配置(毫秒)
38
+ waitTimes: {
39
+ pageLoad: 5000, // 页面加载等待时间
40
+ terminalOpen: 3000, // 终端打开等待时间
41
+ commandExecution: 2000 // 命令执行等待时间
42
+ },
43
+
44
+ // 页面选择器(需要根据实际登录页面调整)
45
+ selectors: {
46
+ // 这些选择器需要根据实际的登录页面进行调整
47
+ editor: '.monaco-grid-view',
48
+ dialogButton: '.monaco-dialog-modal-block .dialog-buttons a.monaco-button',
49
+ terminals: [
50
+ '.terminal',
51
+ // '.xterm',
52
+ // '.console',
53
+ // '.terminal-container',
54
+ // '.xterm-screen',
55
+ // '.monaco-workbench .part.panel .terminal',
56
+ // '[data-testid="terminal"]',
57
+ // '.integrated-terminal'
58
+ ],
59
+ }
60
+ };
61
+
62
+ export default config;
src/execute-command.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import config from './config.js';
2
+ import { fileURLToPath } from 'url';
3
+ import path from 'path';
4
+
5
+ import { createBrowserSession, navigateToWebIDE, executeCommandFlow } from './utils/webide-utils.js';
6
+ import { info, error } from './utils/logger.js';
7
+
8
+ async function executeCommand() {
9
+
10
+ let browser;
11
+ try {
12
+ // 创建浏览器会话
13
+ const { browser: browserInstance, page } = await createBrowserSession(config.cookieFile, config.cookiesFromEnv);
14
+ browser = browserInstance;
15
+
16
+ // 导航到WebIDE页面
17
+ await navigateToWebIDE(page);
18
+
19
+ // 执行命令流程
20
+ const success = await executeCommandFlow(page, 'screenshot');
21
+
22
+ // 保持浏览器打开一段时间以便查看结果
23
+ if (!config.browserOptions.headless) {
24
+ info('浏览器将保持打开5秒以便查看结果...');
25
+ await page.waitForTimeout(5000);
26
+ }
27
+
28
+ } catch (err) {
29
+ error('执行命令过程中发生错误:', err);
30
+ } finally {
31
+ if (browser) {
32
+ await browser.close();
33
+ info('浏览器已关闭');
34
+ }
35
+ }
36
+ }
37
+
38
+ // 运行命令执行脚本
39
+ const __filename = fileURLToPath(import.meta.url);
40
+ const scriptPath = path.resolve(process.argv[1]);
41
+
42
+ if (path.resolve(__filename) === scriptPath) {
43
+ executeCommand().catch(error);
44
+ }
45
+
46
+ export { executeCommand };
src/login.js ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { chromium } from 'playwright';
2
+ import fs from 'fs';
3
+ import config from './config.js';
4
+ import { fileURLToPath } from 'url';
5
+ import path from 'path';
6
+ import { loadCookies } from './utils/common-utils.js';
7
+ import { info, error } from './utils/logger.js';
8
+ async function login() {
9
+ info('启动浏览器...');
10
+ const browser = await chromium.launch(config.browserOptions);
11
+ const context = await browser.newContext();
12
+
13
+ const cookies = loadCookies(config.cookieFile, config.cookiesFromEnv);
14
+ await context.addCookies(cookies);
15
+
16
+ const page = await context.newPage();
17
+
18
+ try {
19
+ info(`导航到登录页面:${config.webideUrl}...`);
20
+ // 首先访问主页面,通常会重定向到登录页面
21
+ await page.goto(config.webideUrl);
22
+
23
+ // 等待页面加载
24
+ await page.waitForTimeout(config.waitTimes.pageLoad);
25
+
26
+ info('当前页面URL:', page.url());
27
+ info('页面标题:', await page.title());
28
+
29
+ // 检查是否已经登录(如果页面包含编辑器元素,说明已登录)
30
+ const isLoggedIn = await page.locator(config.selectors.editor).count() > 0;
31
+
32
+ if (isLoggedIn) {
33
+ info('检测到已经登录状态,保存cookie...');
34
+ } else {
35
+ info('需要登录,请在浏览器中手动完成登录过程...');
36
+ info('登录完成后,请按 Enter 键继续...');
37
+
38
+ // 等待用户手动登录
39
+ await waitForUserInput();
40
+
41
+ // 等待登录完成,检查是否出现编辑器界面
42
+ info('等待登录完成...');
43
+ try {
44
+ await page.goto(config.webideUrl);
45
+ await page.waitForSelector(config.selectors.editor, {
46
+ timeout: 60000
47
+ });
48
+
49
+ } catch (err) {
50
+ info('未检测到编辑器界面,但继续保存cookie...');
51
+ }
52
+ }
53
+
54
+ // 保存cookies
55
+ const cookies = await context.cookies();
56
+ fs.writeFileSync(config.cookieFile, JSON.stringify(cookies, null, 2));
57
+ info(`Cookies已保存到 ${config.cookieFile}`);
58
+ info(`保存了 ${cookies.length} 个cookies`);
59
+
60
+ // 显示保存的cookie信息(仅显示名称,不显示值)
61
+ info('保存的cookie名称:');
62
+ cookies.forEach(cookie => {
63
+ info(` - ${cookie.name} (域名: ${cookie.domain})`);
64
+ });
65
+
66
+ } catch (err) {
67
+ error('登录过程中发生错误:', err);
68
+ } finally {
69
+ await browser.close();
70
+ }
71
+ }
72
+
73
+ // 等待用户输入的辅助函数
74
+ async function waitForUserInput() {
75
+ const { default: readline } = await import('readline');
76
+ return new Promise((resolve) => {
77
+ const rl = readline.createInterface({
78
+ input: process.stdin,
79
+ output: process.stdout
80
+ });
81
+
82
+ rl.question('', () => {
83
+ rl.close();
84
+ resolve();
85
+ });
86
+ });
87
+ }
88
+
89
+ // 运行命令执行脚本
90
+ const __filename = fileURLToPath(import.meta.url);
91
+ const scriptPath = path.resolve(process.argv[1]);
92
+
93
+ if (path.resolve(__filename) === scriptPath) {
94
+ login().catch(error);
95
+ }
96
+
src/scheduler.js ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import config from './config.js';
2
+ import { fileURLToPath } from 'url';
3
+ import path from 'path';
4
+ import { getHumanReadableTimestamp } from './utils/common-utils.js';
5
+ import { createBrowserSession, navigateToWebIDE, executeCommandFlow } from './utils/webide-utils.js';
6
+ import { info, error } from './utils/logger.js';
7
+
8
+ // 执行单次命令的函数
9
+ async function executeCommandOnce(page) {
10
+ info(`[${getHumanReadableTimestamp()}] 开始执行命令...`);
11
+ return executeCommandFlow(page, 'scheduler');
12
+ }
13
+
14
+ // 主调度器函数
15
+ async function startScheduler() {
16
+
17
+ info(`[${getHumanReadableTimestamp()}] 启动调度器...`);
18
+ const intervalSeconds = Math.round(config.schedulerInterval / 1000);
19
+ info(`调度器将每${intervalSeconds}秒执行一次命令以防止编辑器休眠`);
20
+
21
+ let browser;
22
+ try {
23
+ // 创建浏览器会话
24
+ const { browser: browserInstance, page } = await createBrowserSession(config.cookieFile, config.cookiesFromEnv);
25
+ browser = browserInstance;
26
+
27
+ // 导航到WebIDE页面
28
+ await navigateToWebIDE(page);
29
+
30
+ // 立即执行一次命令
31
+ await executeCommandOnce(page);
32
+
33
+ // 设置定时器,按配置的时间间隔执行
34
+ const intervalId = setInterval(async () => {
35
+ try {
36
+ // 重新导航到页面以确保页面活跃
37
+ info(`[${getHumanReadableTimestamp()}] 重新导航到WebIDE页面...`);
38
+ await navigateToWebIDE(page);
39
+
40
+ // 执行命令
41
+ await executeCommandOnce(page);
42
+ } catch (err) {
43
+ error(`[${getHumanReadableTimestamp()}] 定时任务执行失败:`, err);
44
+ }
45
+ }, config.schedulerInterval);
46
+
47
+ info(`[${getHumanReadableTimestamp()}] 调度器已启动,将每${intervalSeconds}秒执行一次命令`);
48
+ info('按 Ctrl+C 停止调度器');
49
+
50
+ // 监听进程退出信号
51
+ process.on('SIGINT', async () => {
52
+ info(`\n[${getHumanReadableTimestamp()}] 收到停止信号,正在关闭调度器...`);
53
+ clearInterval(intervalId);
54
+ if (browser) {
55
+ await browser.close();
56
+ }
57
+ info('调度器已停止,浏览器已关闭');
58
+ process.exit(0);
59
+ });
60
+
61
+ // 保持进程运行
62
+ process.on('SIGTERM', async () => {
63
+ info(`\n[${getHumanReadableTimestamp()}] 收到终止信号,正在关闭调度器...`);
64
+ clearInterval(intervalId);
65
+ if (browser) {
66
+ await browser.close();
67
+ }
68
+ info('调度器已停止,浏览器已关闭');
69
+ process.exit(0);
70
+ });
71
+
72
+ } catch (err) {
73
+ error(`[${getHumanReadableTimestamp()}] 调度器启动失败:`, err);
74
+ if (browser) {
75
+ await browser.close();
76
+ }
77
+ }
78
+ }
79
+
80
+ // 运行调度器
81
+ const __filename = fileURLToPath(import.meta.url);
82
+ const scriptPath = path.resolve(process.argv[1]);
83
+
84
+ if (path.resolve(__filename) === scriptPath) {
85
+ startScheduler().catch(error);
86
+ }
87
+
88
+ export { startScheduler };
src/start-services.js ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * 服务启动脚本
5
+ * 同时启动 Web 服务器和调度器
6
+ */
7
+
8
+ import { spawn } from 'child_process';
9
+ import { info as log, error as logError } from './utils/logger.js';
10
+
11
+ // 存储子进程
12
+ const processes = [];
13
+
14
+ /**
15
+ * 启动子进程
16
+ */
17
+ function startProcess(name, command, args = []) {
18
+ log(`启动 ${name}...`);
19
+
20
+ const child = spawn('node', [command, ...args], {
21
+ stdio: 'inherit',
22
+ cwd: process.cwd()
23
+ });
24
+
25
+ child.on('error', (error) => {
26
+ logError(`${name} 启动失败:`, error);
27
+ });
28
+
29
+ child.on('exit', (code, signal) => {
30
+ if (code !== 0) {
31
+ logError(`${name} 异常退出,代码: ${code}, 信号: ${signal}`);
32
+ } else {
33
+ log(`${name} 正常退出`);
34
+ }
35
+ });
36
+
37
+ processes.push({ name, process: child });
38
+ return child;
39
+ }
40
+
41
+ /**
42
+ * 优雅关闭所有进程
43
+ */
44
+ function gracefulShutdown() {
45
+ log('收到关闭信号,正在停止所有服务...');
46
+
47
+ processes.forEach(({ name, process }) => {
48
+ if (!process.killed) {
49
+ log(`停止 ${name}...`);
50
+ process.kill('SIGTERM');
51
+ }
52
+ });
53
+
54
+ // 等待一段时间后强制关闭
55
+ setTimeout(() => {
56
+ processes.forEach(({ name, process }) => {
57
+ if (!process.killed) {
58
+ log(`强制停止 ${name}...`);
59
+ process.kill('SIGKILL');
60
+ }
61
+ });
62
+ process.exit(0);
63
+ }, 5000);
64
+ }
65
+
66
+ /**
67
+ * 主函数
68
+ */
69
+ async function main() {
70
+ log('🚀 启动 CloudStudio Runner 服务');
71
+ log('='.repeat(50));
72
+
73
+ try {
74
+ // 启动 Web 服务器
75
+ const webServer = startProcess('Web 服务器', 'src/web-server.js');
76
+
77
+ // 等待一下确保 Web 服务器启动
78
+ await new Promise(resolve => setTimeout(resolve, 2000));
79
+
80
+ // 启动调度器
81
+ const scheduler = startProcess('调度器', 'src/scheduler.js');
82
+
83
+ log('='.repeat(50));
84
+ log('✅ 所有服务已启动');
85
+ log('📊 Web 界面: http://localhost:7860');
86
+ log('⏰ 调度器: 每10分钟执行一次任务');
87
+ log('按 Ctrl+C 停止所有服务');
88
+
89
+ // 监听退出信号
90
+ process.on('SIGINT', gracefulShutdown);
91
+ process.on('SIGTERM', gracefulShutdown);
92
+
93
+ // 保持主进程运行
94
+ process.on('exit', () => {
95
+ log('主进程退出');
96
+ });
97
+
98
+ } catch (error) {
99
+ logError('启动服务失败:', error);
100
+ process.exit(1);
101
+ }
102
+ }
103
+
104
+ // 运行主函数
105
+ import { fileURLToPath } from 'url';
106
+ import path from 'path';
107
+
108
+ const __filename = fileURLToPath(import.meta.url);
109
+ const scriptPath = path.resolve(process.argv[1]);
110
+
111
+ if (path.resolve(__filename) === scriptPath) {
112
+ main().catch(error => {
113
+ logError('服务启动异常:', error);
114
+ process.exit(1);
115
+ });
116
+ }
117
+
118
+ export { main };
src/utils/common-utils.js ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { info, error } from './logger.js';
4
+
5
+ /**
6
+ * 创建人类可读的时间戳
7
+ * @returns {string} 格式化的时间戳 YYYY-MM-DD_HH-MM-SS
8
+ */
9
+ export function getHumanReadableTimestamp() {
10
+ const now = new Date();
11
+ const year = now.getFullYear();
12
+ const month = String(now.getMonth() + 1).padStart(2, '0');
13
+ const day = String(now.getDate()).padStart(2, '0');
14
+ const hours = String(now.getHours()).padStart(2, '0');
15
+ const minutes = String(now.getMinutes()).padStart(2, '0');
16
+ const seconds = String(now.getSeconds()).padStart(2, '0');
17
+
18
+ return `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`;
19
+ }
20
+
21
+ /**
22
+ * 确保截图目录存在
23
+ * @param {string} dir - 目录路径
24
+ */
25
+ export function ensureScreenshotDirectory(dir) {
26
+ if (!fs.existsSync(dir)) {
27
+ fs.mkdirSync(dir, { recursive: true });
28
+ info(`创建截图目录: ${dir}`);
29
+ }
30
+ }
31
+
32
+ /**
33
+ * 检查 Cookie 是否可用(环境变量或文件)
34
+ * @param {string} cookieFile - Cookie 文件路径
35
+ * @param {string} cookiesFromEnv - 环境变量中的cookies
36
+ * @returns {boolean} Cookie是否可用
37
+ */
38
+ export function checkCookieAvailability(cookieFile, cookiesFromEnv) {
39
+ // 优先检查环境变量
40
+ if (cookiesFromEnv) {
41
+ info('发现环境变量COOKIES,将使用环境变量中的cookies');
42
+ try {
43
+ JSON.parse(cookiesFromEnv);
44
+ return true;
45
+ } catch (err) {
46
+ error('环境变量COOKIES格式无效:', err.message);
47
+ info('将尝试使用cookie文件...');
48
+ }
49
+ }
50
+
51
+ // 检查cookie文件
52
+ if (!fs.existsSync(cookieFile)) {
53
+ error(`Cookie文件不存在: ${cookieFile}`);
54
+ info('请先运行 npm run login 进行登录,或设置环境变量COOKIES');
55
+ return false;
56
+ }
57
+ return true;
58
+ }
59
+
60
+ /**
61
+ * 检查 Cookie 文件是否存在(保持向后兼容)
62
+ * @param {string} cookieFile - Cookie 文件路径
63
+ * @returns {boolean} 文件是否存在
64
+ */
65
+ export function checkCookieFile(cookieFile) {
66
+ if (!fs.existsSync(cookieFile)) {
67
+ error(`Cookie文件不存在: ${cookieFile}`);
68
+ info('请先运行 npm run login 进行登录');
69
+ return false;
70
+ }
71
+ return true;
72
+ }
73
+
74
+ /**
75
+ * 读取并解析 Cookie(优先使用环境变量)
76
+ * @param {string} cookieFile - Cookie 文件路径
77
+ * @param {string} cookiesFromEnv - 环境变量中的cookies
78
+ * @returns {Array} Cookie 数组
79
+ */
80
+ export function loadCookies(cookieFile, cookiesFromEnv) {
81
+ try {
82
+ // 优先使用环境变量
83
+ if (cookiesFromEnv) {
84
+ info('从环境变量COOKIES加载cookies...');
85
+ const cookies = JSON.parse(cookiesFromEnv);
86
+ info(`已从环境变量加载 ${cookies.length} 个cookies`);
87
+ return cookies;
88
+ }
89
+
90
+ // 使用文件
91
+ if (fs.existsSync(cookieFile)) {
92
+ info(`从文件加载cookies: ${cookieFile}`);
93
+ const cookies = JSON.parse(fs.readFileSync(cookieFile, 'utf8'));
94
+ info(`已从文件加载 ${cookies.length} 个cookies`);
95
+ return cookies;
96
+ }
97
+ return [];
98
+ } catch (err) {
99
+ error('读取 Cookie 失败:', err);
100
+ throw err;
101
+ }
102
+ }
103
+
104
+ /**
105
+ * 保存截图
106
+ * @param {Object} page - Playwright 页面对象
107
+ * @param {string} screenshotDir - 截图目录
108
+ * @param {string} prefix - 文件名前缀
109
+ * @returns {string} 截图文件路径
110
+ */
111
+ export async function saveScreenshot(page, screenshotDir, prefix = 'screenshot') {
112
+ ensureScreenshotDirectory(screenshotDir);
113
+ const timestamp = getHumanReadableTimestamp();
114
+ const screenshotPath = path.join(screenshotDir, `${prefix}.png`);
115
+ await page.screenshot({ path: screenshotPath });
116
+ info(`截图已保存: ${screenshotPath}`);
117
+ return screenshotPath;
118
+ }
src/utils/logger.js ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from 'fs';
2
+
3
+ // 日志级别枚举
4
+ export const LogLevel = {
5
+ DEBUG: 'DEBUG',
6
+ INFO: 'INFO',
7
+ WARN: 'WARN',
8
+ ERROR: 'ERROR'
9
+ };
10
+
11
+ // 日志配置
12
+ const LOG_CONFIG = {
13
+ logFile: './logs/app.log',
14
+ logDir: './logs',
15
+ enableConsole: true,
16
+ enableFile: true,
17
+ logLevel: LogLevel.INFO
18
+ };
19
+
20
+ /**
21
+ * 确保日志目录存在
22
+ */
23
+ function ensureLogDirectory() {
24
+ if (!fs.existsSync(LOG_CONFIG.logDir)) {
25
+ fs.mkdirSync(LOG_CONFIG.logDir, { recursive: true });
26
+ }
27
+ }
28
+
29
+ /**
30
+ * 格式化日志消息
31
+ * @param {...any} args - 要记录的参数
32
+ * @returns {string} 格式化后的消息
33
+ */
34
+ function formatMessage(...args) {
35
+ return args.map(arg =>
36
+ typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
37
+ ).join(' ');
38
+ }
39
+
40
+ /**
41
+ * 写入日志到文件
42
+ * @param {string} level - 日志级别
43
+ * @param {string} message - 日志消息
44
+ */
45
+ function writeToFile(level, message) {
46
+ if (!LOG_CONFIG.enableFile) return;
47
+
48
+ ensureLogDirectory();
49
+ const timestamp = new Date().toISOString();
50
+ const logEntry = `[${timestamp}] [${level}] ${message}\n`;
51
+
52
+ try {
53
+ fs.appendFileSync(LOG_CONFIG.logFile, logEntry);
54
+ } catch (error) {
55
+ // 避免循环调用,直接使用console
56
+ console.error('写入日志文件失败:', error);
57
+ }
58
+ }
59
+
60
+ /**
61
+ * 输出到控制台
62
+ * @param {string} level - 日志级别
63
+ * @param {...any} args - 要记录的参数
64
+ */
65
+ function writeToConsole(level, ...args) {
66
+ if (!LOG_CONFIG.enableConsole) return;
67
+
68
+ switch (level) {
69
+ case LogLevel.DEBUG:
70
+ console.debug(...args);
71
+ break;
72
+ case LogLevel.INFO:
73
+ console.log(...args);
74
+ break;
75
+ case LogLevel.WARN:
76
+ console.warn(...args);
77
+ break;
78
+ case LogLevel.ERROR:
79
+ console.error(...args);
80
+ break;
81
+ default:
82
+ console.log(...args);
83
+ }
84
+ }
85
+
86
+ /**
87
+ * 通用日志记录函数
88
+ * @param {string} level - 日志级别
89
+ * @param {...any} args - 要记录的参数
90
+ */
91
+ function writeLog(level, ...args) {
92
+ const message = formatMessage(...args);
93
+
94
+ // 输出到控制台
95
+ writeToConsole(level, ...args);
96
+
97
+ // 写入文件
98
+ writeToFile(level, message);
99
+ }
100
+
101
+ /**
102
+ * DEBUG级别日志
103
+ * @param {...any} args - 要记录的参数
104
+ */
105
+ export function debug(...args) {
106
+ writeLog(LogLevel.DEBUG, ...args);
107
+ }
108
+
109
+ /**
110
+ * INFO级别日志(替代console.log)
111
+ * @param {...any} args - 要记录的参数
112
+ */
113
+ export function info(...args) {
114
+ writeLog(LogLevel.INFO, ...args);
115
+ }
116
+
117
+ /**
118
+ * WARN级别日志(替代console.warn)
119
+ * @param {...any} args - 要记录的参数
120
+ */
121
+ export function warn(...args) {
122
+ writeLog(LogLevel.WARN, ...args);
123
+ }
124
+
125
+ /**
126
+ * ERROR级别日志(替代console.error)
127
+ * @param {...any} args - 要记录的参数
128
+ */
129
+ export function error(...args) {
130
+ writeLog(LogLevel.ERROR, ...args);
131
+ }
132
+
133
+ /**
134
+ * 读取最近的日志
135
+ * @param {number} lines - 要读取的行数,默认100行
136
+ * @returns {Array} 日志行数组
137
+ */
138
+ export function getRecentLogs(lines = 100) {
139
+ try {
140
+ if (!fs.existsSync(LOG_CONFIG.logFile)) {
141
+ return [];
142
+ }
143
+
144
+ const content = fs.readFileSync(LOG_CONFIG.logFile, 'utf8');
145
+ const logLines = content.trim().split('\n').filter(line => line.length > 0);
146
+
147
+ // 返回最后 N 行
148
+ return logLines.slice(-lines);
149
+ } catch (err) {
150
+ console.error('读取日志文件失败:', err);
151
+ return [];
152
+ }
153
+ }
154
+
155
+ /**
156
+ * 清空日志文件
157
+ * @returns {boolean} 是否成功清空
158
+ */
159
+ export function clearLogFile() {
160
+ try {
161
+ ensureLogDirectory();
162
+ fs.writeFileSync(LOG_CONFIG.logFile, '');
163
+ info('日志文件已清空');
164
+ return true;
165
+ } catch (err) {
166
+ error('清空日志文件失败:', err);
167
+ return false;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * 配置日志设置
173
+ * @param {Object} config - 日志配置
174
+ */
175
+ export function configureLogger(config = {}) {
176
+ Object.assign(LOG_CONFIG, config);
177
+ }
178
+
179
+ // 为了向后兼容,导出原有的函数名
180
+ export const log = info;
181
+ export const logError = error;
182
+
183
+ // 默认导出logger对象
184
+ export default {
185
+ debug,
186
+ info,
187
+ warn,
188
+ error,
189
+ log: info,
190
+ logError: error,
191
+ getRecentLogs,
192
+ clearLogFile,
193
+ configureLogger,
194
+ LogLevel
195
+ };
src/utils/webide-utils.js ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { chromium } from 'playwright';
2
+ import config from '../config.js';
3
+ import { loadCookies, saveScreenshot, getHumanReadableTimestamp } from './common-utils.js';
4
+ import { info, error } from './logger.js';
5
+
6
+ /**
7
+ * 创建浏览器实例和上下文
8
+ * @param {string} cookieFile - Cookie 文件路径
9
+ * @param {string} cookiesFromEnv - 环境变量中的cookies
10
+ * @returns {Object} { browser, context, page }
11
+ */
12
+ export async function createBrowserSession(cookieFile, cookiesFromEnv) {
13
+ info('启动浏览器...');
14
+ const browser = await chromium.launch(config.browserOptions);
15
+ const context = await browser.newContext();
16
+
17
+ // 读取并设置cookies(优先使用环境变量)
18
+ const cookies = loadCookies(cookieFile, cookiesFromEnv);
19
+ await context.addCookies(cookies);
20
+
21
+ const page = await context.newPage();
22
+
23
+ return { browser, context, page };
24
+ }
25
+
26
+ /**
27
+ * 导航到 WebIDE 页面并验证登录状态
28
+ * @param {Object} page - Playwright 页面对象
29
+ */
30
+ export async function navigateToWebIDE(page) {
31
+ info('导航到WebIDE页面...');
32
+ await page.goto(config.webideUrl);
33
+
34
+ // 等待页面加载
35
+ await page.waitForTimeout(config.waitTimes.pageLoad);
36
+
37
+ info('当前页面URL:', page.url());
38
+ info('页面标题:', await page.title());
39
+
40
+ // 检查并处理"立即重试"按钮 这个是企业版的才会有的
41
+ await handleRetryButton(page);
42
+
43
+
44
+ // 检查是否成功登录
45
+ try {
46
+ await page.waitForSelector(config.selectors.editor, {
47
+ timeout: 60000
48
+ });
49
+ info('成功进入WebIDE界面');
50
+ return true;
51
+ } catch (err) {
52
+ info('警告: 未检测到编辑器界面,可能需要重新登录');
53
+ return false;
54
+ }
55
+ }
56
+
57
+ /**
58
+ * 检查并点击"立即重试"按钮
59
+ * @param {Object} page - Playwright 页面对象
60
+ * @returns {boolean} 是否找到并点击了重试按钮
61
+ */
62
+ export async function handleRetryButton(page) {
63
+ try {
64
+ const retryButton = await page.waitForSelector('button.btn__21_ID', { timeout: 5000 });
65
+ if (retryButton && await retryButton.isVisible()) {
66
+ info('发现"立即重试"按钮,点击处理...');
67
+ await retryButton.click();
68
+ return true;
69
+ }
70
+ } catch (err) {
71
+ // 没有找到重试按钮,继续执行
72
+ info('未发现"立即重试"按钮,继续执行...');
73
+ }
74
+ return false;
75
+ }
76
+
77
+ /**
78
+ * 处理模态对话框
79
+ * @param {Object} page - Playwright 页面对象
80
+ */
81
+ export async function handleModalDialog(page) {
82
+ try {
83
+ const dialogButton = await page.waitForSelector(config.selectors.dialogButton, { timeout: 30000 });
84
+ if (dialogButton && await dialogButton.isVisible()) {
85
+ info('发现模态对话框按钮,点击处理...');
86
+ await dialogButton.click();
87
+ await page.waitForTimeout(500);
88
+ return true;
89
+ }
90
+ } catch (err) {
91
+ // 没有找到对话框按钮,继续执行
92
+ info('未发现模态对话框,继续执行...');
93
+ }
94
+ return false;
95
+ }
96
+
97
+ /**
98
+ * 打开终端
99
+ * @param {Object} page - Playwright 页面对象
100
+ * @returns {Object|null} 终端元素或 null
101
+ */
102
+ export async function openTerminal(page) {
103
+ info('尝试打开终端 (Ctrl+~)...');
104
+
105
+ // 确保页面获得焦点
106
+ await page.click('body');
107
+ await page.waitForTimeout(500);
108
+
109
+ // 按下 Ctrl+~ 打开终端
110
+ await page.keyboard.press('Control+`');
111
+
112
+ // 等待终端打开
113
+ await page.waitForTimeout(config.waitTimes.terminalOpen);
114
+
115
+ // 尝试多种方式查找终端
116
+ const terminalSelectors = config.selectors.terminals;
117
+
118
+ let terminalFound = false;
119
+ let terminalElement = null;
120
+
121
+ for (const selector of terminalSelectors) {
122
+ try {
123
+ terminalElement = await page.waitForSelector(selector, { timeout: 2000 });
124
+ if (terminalElement) {
125
+ info(`找到终端元素: ${selector}`);
126
+ terminalFound = true;
127
+ break;
128
+ }
129
+ } catch (err) {
130
+ // 继续尝试下一个选择器
131
+ }
132
+ }
133
+
134
+ if (!terminalFound) {
135
+ info('未找到终端元素,尝试直接输入命令...');
136
+ return null;
137
+ } else {
138
+ // 点击终端区域确保焦点
139
+ await terminalElement.click();
140
+ await page.waitForTimeout(500);
141
+ return terminalElement;
142
+ }
143
+ }
144
+
145
+ /**
146
+ * 在终端中执行命令
147
+ * @param {Object} page - Playwright 页面对象
148
+ * @param {string} command - 要执行的命令
149
+ */
150
+ export async function executeTerminalCommand(page, command) {
151
+ info(`执行命令: ${command}`);
152
+
153
+ // 输入命令
154
+ await page.keyboard.type(command);
155
+ await page.waitForTimeout(500);
156
+
157
+ // 按回车执行命令
158
+ await page.keyboard.press('Enter');
159
+
160
+ // 等待命令执行
161
+ await page.waitForTimeout(config.waitTimes.commandExecution);
162
+
163
+ info('命令已执行');
164
+ }
165
+
166
+ /**
167
+ * 完整的命令执行流程
168
+ * @param {Object} page - Playwright 页面对象
169
+ * @param {string} screenshotPrefix - 截图文件名前缀
170
+ * @returns {boolean} 执行是否成功
171
+ */
172
+ export async function executeCommandFlow(page, screenshotPrefix = 'screenshot') {
173
+ try {
174
+
175
+ // 处理模态��话框
176
+ await handleModalDialog(page);
177
+
178
+ // 打开终端
179
+ await openTerminal(page);
180
+
181
+ // 执行命令
182
+ await executeTerminalCommand(page, config.command);
183
+
184
+ // 截图保存执行结果
185
+ const screenshotDir = config.screenshotDir || './screenshots';
186
+ const screenshotPath = await saveScreenshot(page, screenshotDir, screenshotPrefix);
187
+
188
+ return true;
189
+ } catch (err) {
190
+ error(`[${getHumanReadableTimestamp()}] 执行命令时发生错误:`, err);
191
+ return false;
192
+ }
193
+ }
src/web-server.js ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Hono } from 'hono';
2
+ import { serve } from '@hono/node-server';
3
+ import { serveStatic } from '@hono/node-server/serve-static';
4
+ import { getRecentLogs, clearLogFile } from './utils/logger.js';
5
+ import { info as log, error as logError } from './utils/logger.js';
6
+ import config from './config.js';
7
+
8
+ const app = new Hono();
9
+
10
+ // 静态文件服务 - 提供 screenshots 目录
11
+ app.use('/screenshots/*', serveStatic({ root: './' }));
12
+
13
+ // 静态 HTML 页面
14
+ const indexHTML = `
15
+ <!DOCTYPE html>
16
+ <html lang="zh-CN">
17
+ <head>
18
+ <meta charset="UTF-8">
19
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
20
+ <title>CloudStudio Runner - 日志查看器</title>
21
+ <style>
22
+ body {
23
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
24
+ margin: 0;
25
+ padding: 20px;
26
+ background-color: #f5f5f5;
27
+ color: #333;
28
+ }
29
+ .container {
30
+ max-width: 1200px;
31
+ margin: 0 auto;
32
+ background: white;
33
+ border-radius: 8px;
34
+ box-shadow: 0 2px 10px rgba(0,0,0,0.1);
35
+ overflow: hidden;
36
+ }
37
+ .header {
38
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
39
+ color: white;
40
+ padding: 20px;
41
+ text-align: center;
42
+ }
43
+ .header h1 {
44
+ margin: 0;
45
+ font-size: 2em;
46
+ }
47
+ .header p {
48
+ margin: 10px 0 0 0;
49
+ opacity: 0.9;
50
+ }
51
+ .controls {
52
+ padding: 20px;
53
+ border-bottom: 1px solid #eee;
54
+ display: flex;
55
+ gap: 10px;
56
+ align-items: center;
57
+ flex-wrap: wrap;
58
+ }
59
+ .controls label {
60
+ font-weight: bold;
61
+ }
62
+ .controls select, .controls button {
63
+ padding: 8px 12px;
64
+ border: 1px solid #ddd;
65
+ border-radius: 4px;
66
+ font-size: 14px;
67
+ }
68
+ .controls button {
69
+ background: #667eea;
70
+ color: white;
71
+ border: none;
72
+ cursor: pointer;
73
+ transition: background 0.3s;
74
+ }
75
+ .controls button:hover {
76
+ background: #5a6fd8;
77
+ }
78
+ .log-container {
79
+ padding: 20px;
80
+ max-height: 600px;
81
+ overflow-y: auto;
82
+ }
83
+ .log-entry {
84
+ margin-bottom: 8px;
85
+ padding: 8px;
86
+ border-radius: 4px;
87
+ font-family: 'Courier New', monospace;
88
+ font-size: 13px;
89
+ line-height: 1.4;
90
+ border-left: 3px solid #ddd;
91
+ }
92
+ .log-entry.info {
93
+ background-color: #f8f9fa;
94
+ border-left-color: #28a745;
95
+ }
96
+ .log-entry.error {
97
+ background-color: #fff5f5;
98
+ border-left-color: #dc3545;
99
+ color: #721c24;
100
+ }
101
+ .log-entry.warn {
102
+ background-color: #fffbf0;
103
+ border-left-color: #ffc107;
104
+ color: #856404;
105
+ }
106
+ .timestamp {
107
+ color: #6c757d;
108
+ font-weight: bold;
109
+ }
110
+ .level {
111
+ font-weight: bold;
112
+ margin: 0 8px;
113
+ }
114
+ .level.info { color: #28a745; }
115
+ .level.error { color: #dc3545; }
116
+ .level.warn { color: #ffc107; }
117
+ .message {
118
+ word-break: break-word;
119
+ }
120
+ .status {
121
+ padding: 10px 20px;
122
+ background: #e9ecef;
123
+ border-top: 1px solid #ddd;
124
+ font-size: 14px;
125
+ color: #6c757d;
126
+ }
127
+ .loading {
128
+ text-align: center;
129
+ padding: 40px;
130
+ color: #6c757d;
131
+ }
132
+ .empty {
133
+ text-align: center;
134
+ padding: 40px;
135
+ color: #6c757d;
136
+ font-style: italic;
137
+ }
138
+ .screenshot-section {
139
+ padding: 20px;
140
+ border-bottom: 1px solid #eee;
141
+ text-align: center;
142
+ }
143
+ .screenshot-section h2 {
144
+ margin: 0 0 15px 0;
145
+ color: #333;
146
+ font-size: 1.2em;
147
+ }
148
+ .screenshot-section img {
149
+ max-width: 100%;
150
+ height: auto;
151
+ border: 1px solid #ddd;
152
+ border-radius: 4px;
153
+ box-shadow: 0 2px 8px rgba(0,0,0,0.1);
154
+ }
155
+ </style>
156
+ </head>
157
+ <body>
158
+ <div class="container">
159
+ <div class="header">
160
+ <h1>🚀 CloudStudio Runner</h1>
161
+ <p>实时日志查看器 - 监控自动化任务执行状态</p>
162
+ </div>
163
+
164
+ <div class="controls">
165
+ <label for="lines">显示行数:</label>
166
+ <select id="lines">
167
+ <option value="50">50 行</option>
168
+ <option value="100" selected>100 行</option>
169
+ <option value="200">200 行</option>
170
+ <option value="500">500 行</option>
171
+ <option value="1000">1000 行</option>
172
+ </select>
173
+
174
+ <button onclick="refreshLogs()">🔄 刷新日志</button>
175
+ <button onclick="toggleAutoRefresh()">⏱️ 自动刷新</button>
176
+ <button onclick="clearLogs()">🗑️ 清空显示</button>
177
+ </div>
178
+
179
+ <div class="log-container" id="logContainer">
180
+ <div class="loading">正在加载日志...</div>
181
+ </div>
182
+
183
+ <div class="status" id="status">
184
+ 准备就绪
185
+ </div>
186
+ <div class="screenshot-section">
187
+ <h2>📸 最新截图</h2>
188
+ <img src="/screenshots/scheduler.png" alt="Scheduler Screenshot" onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
189
+ <div style="display: none; color: #6c757d; font-style: italic;">截图文件不存在或无法加载</div>
190
+ </div>
191
+ </div>
192
+
193
+ <script>
194
+ let autoRefreshInterval = null;
195
+ let isAutoRefresh = false;
196
+
197
+ async function fetchLogs() {
198
+ try {
199
+ const lines = document.getElementById('lines').value;
200
+ const response = await fetch(\`/api/logs?lines=\${lines}\`);
201
+ const data = await response.json();
202
+
203
+ if (data.success) {
204
+ displayLogs(data.logs);
205
+ updateStatus(\`已加载 \${data.logs.length} 条日志 - \${new Date().toLocaleString()}\`);
206
+ } else {
207
+ updateStatus('获取日志失败: ' + data.error);
208
+ }
209
+ } catch (error) {
210
+ updateStatus('网络错误: ' + error.message);
211
+ }
212
+ }
213
+
214
+ function displayLogs(logs) {
215
+ const container = document.getElementById('logContainer');
216
+
217
+ if (logs.length === 0) {
218
+ container.innerHTML = '<div class="empty">暂无日志数据</div>';
219
+ return;
220
+ }
221
+
222
+ const logHTML = logs.map(log => {
223
+ const match = log.match(/\\[(.*?)\\]\\s*\\[(.*?)\\]\\s*(.*)/);
224
+ if (match) {
225
+ const [, timestamp, level, message] = match;
226
+ const levelClass = level.toLowerCase();
227
+ return \`
228
+ <div class="log-entry \${levelClass}">
229
+ <span class="timestamp">\${timestamp}</span>
230
+ <span class="level \${levelClass}">[\${level}]</span>
231
+ <span class="message">\${message}</span>
232
+ </div>
233
+ \`;
234
+ } else {
235
+ return \`
236
+ <div class="log-entry">
237
+ <span class="message">\${log}</span>
238
+ </div>
239
+ \`;
240
+ }
241
+ }).join('');
242
+
243
+ container.innerHTML = logHTML;
244
+ container.scrollTop = container.scrollHeight;
245
+ }
246
+
247
+ function updateStatus(message) {
248
+ document.getElementById('status').textContent = message;
249
+ }
250
+
251
+ function refreshLogs() {
252
+ fetchLogs();
253
+ }
254
+
255
+ function toggleAutoRefresh() {
256
+ const button = event.target;
257
+
258
+ if (isAutoRefresh) {
259
+ clearInterval(autoRefreshInterval);
260
+ autoRefreshInterval = null;
261
+ isAutoRefresh = false;
262
+ button.textContent = '⏱️ 自动刷新';
263
+ updateStatus('自动刷新已停止');
264
+ } else {
265
+ autoRefreshInterval = setInterval(fetchLogs, 5000);
266
+ isAutoRefresh = true;
267
+ button.textContent = '⏹️ 停止刷新';
268
+ updateStatus('自动刷新已启动 (每5秒)');
269
+ }
270
+ }
271
+
272
+ async function clearLogs() {
273
+ try {
274
+ updateStatus('正在清空日志...');
275
+
276
+ const response = await fetch('/api/clear-logs', {
277
+ method: 'POST',
278
+ headers: {
279
+ 'Content-Type': 'application/json'
280
+ }
281
+ });
282
+
283
+ const data = await response.json();
284
+
285
+ if (data.success) {
286
+ document.getElementById('logContainer').innerHTML = '<div class="empty">日志已清空</div>';
287
+ updateStatus('日志文件已清空 - ' + new Date().toLocaleString());
288
+ } else {
289
+ updateStatus('清空日志失败: ' + data.error);
290
+ }
291
+ } catch (error) {
292
+ updateStatus('清空日志时发生网络错误: ' + error.message);
293
+ }
294
+ }
295
+
296
+ // 页面加载时获取日志
297
+ document.addEventListener('DOMContentLoaded', fetchLogs);
298
+ </script>
299
+ </body>
300
+ </html>
301
+ `;
302
+
303
+ // 路由定义
304
+ app.get('/', (c) => {
305
+ return c.html(indexHTML);
306
+ });
307
+
308
+ // API 路由 - 获取日志
309
+ app.get('/api/logs', (c) => {
310
+ try {
311
+ const lines = parseInt(c.req.query('lines') || '100');
312
+ const logs = getRecentLogs(lines);
313
+
314
+ return c.json({
315
+ success: true,
316
+ logs: logs,
317
+ count: logs.length,
318
+ timestamp: new Date().toISOString()
319
+ });
320
+ } catch (error) {
321
+ logError('获取日志API错误:', error);
322
+ return c.json({
323
+ success: false,
324
+ error: error.message
325
+ }, 500);
326
+ }
327
+ });
328
+
329
+ // API 路由 - 清空日志
330
+ app.post('/api/clear-logs', (c) => {
331
+ try {
332
+ const success = clearLogFile();
333
+
334
+ if (success) {
335
+ log('日志文件已通过Web界面清空');
336
+ return c.json({
337
+ success: true,
338
+ message: '日志文件已清空',
339
+ timestamp: new Date().toISOString()
340
+ });
341
+ } else {
342
+ return c.json({
343
+ success: false,
344
+ error: '清空日志文件失败'
345
+ }, 500);
346
+ }
347
+ } catch (error) {
348
+ logError('清空日志API错误:', error);
349
+ return c.json({
350
+ success: false,
351
+ error: error.message
352
+ }, 500);
353
+ }
354
+ });
355
+
356
+ // API 路由 - 系统状态
357
+ app.get('/api/status', (c) => {
358
+ return c.json({
359
+ success: true,
360
+ status: 'running',
361
+ uptime: process.uptime(),
362
+ memory: process.memoryUsage(),
363
+ timestamp: new Date().toISOString(),
364
+ config: {
365
+ webideUrl: config.webideUrl,
366
+ schedulerInterval: config.schedulerInterval,
367
+ headless: config.browserOptions.headless
368
+ }
369
+ });
370
+ });
371
+
372
+ // 健康检查
373
+ app.get('/health', (c) => {
374
+ return c.json({ status: 'ok', timestamp: new Date().toISOString() });
375
+ });
376
+
377
+ // 启动服务器
378
+ const port = process.env.PORT || 7860;
379
+
380
+ async function startServer() {
381
+ try {
382
+ log(`启动 Web 服务器,端口: ${port}`);
383
+ log(`访问地址: http://localhost:${port}`);
384
+
385
+ serve({
386
+ fetch: app.fetch,
387
+ port: port,
388
+ });
389
+
390
+ log('Web 服务器启动成功');
391
+ } catch (error) {
392
+ logError('启动 Web 服务器失败:', error);
393
+ process.exit(1);
394
+ }
395
+ }
396
+
397
+ // 如果直接运行此文件,启动服务器
398
+ import { fileURLToPath } from 'url';
399
+ import path from 'path';
400
+
401
+ const __filename = fileURLToPath(import.meta.url);
402
+ const scriptPath = path.resolve(process.argv[1]);
403
+
404
+ if (path.resolve(__filename) === scriptPath) {
405
+ startServer();
406
+ }
407
+
408
+ export { app, startServer };