From a2fcc265af43fa277985477b84058028c51a3240 Mon Sep 17 00:00:00 2001 From: delta <528491526@qq.com> Date: Sun, 22 Nov 2026 22:36:31 +0800 Subject: [PATCH] =?UTF-8?q?feat(health):=20=E4=B8=BA=E6=AF=8F=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E8=84=9A=E6=9C=AC=E5=A2=9E=E5=8A=A0=E5=90=AF=E5=8A=A8?= =?UTF-8?q?=E6=88=90=E5=8A=9F=E7=9A=84=E6=A3=80=E6=B5=8B=E6=A0=87=E8=AF=86?= =?UTF-8?q?=E4=B8=8E=E5=A4=9A=E6=A8=A1=E6=80=81=E5=B0=B1=E7=BB=AA=E6=84=9F?= =?UTF-8?q?=E7=9F=A5=20(Closes=20#141)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/detectors/config-detector.test.ts | 26 +++++ .../main/core/detectors/config-detector.ts | 26 ++++- apps/desktop/src/main/core/devhub-core.ts | 64 ++++--------- .../main/core/health/health-monitor.test.ts | 94 +++++++++++++++++++ .../src/main/core/health/health-monitor.ts | 13 ++- .../main/core/health/health-target.test.ts | 60 +++++++++++- .../src/main/core/health/health-target.ts | 91 ++++++++++++++---- .../main/core/schedules/schedule-executor.ts | 64 +++++++++++++ .../src/features/groups/group-step-card.tsx | 16 +++- .../src/features/runs/run-controls.tsx | 19 +++- .../src/features/terminal/terminal-panel.tsx | 1 + docs/PROGRESS.md | 1 + packages/shared/src/domain.ts | 31 +++++- 13 files changed, 429 insertions(+), 77 deletions(-) create mode 100644 apps/desktop/src/main/core/schedules/schedule-executor.ts diff --git a/apps/desktop/src/main/core/detectors/config-detector.test.ts b/apps/desktop/src/main/core/detectors/config-detector.test.ts index 250dcec..bd5a379 100644 --- a/apps/desktop/src/main/core/detectors/config-detector.test.ts +++ b/apps/desktop/src/main/core/detectors/config-detector.test.ts @@ -83,6 +83,32 @@ scripts: await expect(detect()).rejects.toThrow('scripts.api.health 必须以 / 开头且不含空白') }) + it('reads output and alive health configs', async () => { + await write(` +scripts: + worker: + command: node worker.js + health: + type: output + pattern: worker ready + watch: + command: npm run watch + health: + type: alive + delayMs: 1500 +`) + await expect(detect()).resolves.toMatchObject([ + { + id: 'custom:worker', + healthConfig: { type: 'output', pattern: 'worker ready' } + }, + { + id: 'custom:watch', + healthConfig: { type: 'alive', delayMs: 1500 } + } + ]) + }) + it('also reads .devhub.yml', async () => { await write('scripts:\n a:\n command: echo a\n', '.devhub.yml') await expect(detect()).resolves.toMatchObject([{ id: 'custom:a' }]) diff --git a/apps/desktop/src/main/core/detectors/config-detector.ts b/apps/desktop/src/main/core/detectors/config-detector.ts index 33d3d07..5390d12 100644 --- a/apps/desktop/src/main/core/detectors/config-detector.ts +++ b/apps/desktop/src/main/core/detectors/config-detector.ts @@ -1,6 +1,6 @@ import { isAbsolute, join, relative, resolve } from 'path' import { parse, YAMLParseError } from 'yaml' -import { projectConfigSchema, type Script } from '@devhub/shared' +import { projectConfigSchema, type Script, type ScriptHealthConfig } from '@devhub/shared' import { inferNpmPorts } from '../ports/infer-ports' import { readOptionalFile } from './fs-utils' import type { ScriptDetector } from './types' @@ -68,9 +68,28 @@ export function createConfigDetector({ platform }: ConfigDetectorDeps): ScriptDe } const ports = entry.ports ?? (entry.port ? [entry.port] : inferNpmPorts(command)) - if (entry.health && ports.length === 0) { + if (typeof entry.health === 'string' && ports.length === 0) { throw new Error(`${fileName} 中脚本 ${name} 设置了 health,但不知道端口:请同时填写 port`) } + if ( + entry.health && + typeof entry.health === 'object' && + entry.health.type === 'http' && + !entry.health.port && + ports.length === 0 + ) { + throw new Error( + `${fileName} 中脚本 ${name} 设置了 http health,但不知道端口:请同时填写 port` + ) + } + + const healthConfig: ScriptHealthConfig | undefined = + typeof entry.health === 'string' + ? ports.length > 0 + ? { type: 'http', path: entry.health, port: ports[0] } + : undefined + : entry.health + scripts.push({ id: `custom:${name}`, name, @@ -82,7 +101,8 @@ export function createConfigDetector({ platform }: ConfigDetectorDeps): ScriptDe ...(ports.length > 0 && entry.ports === undefined && entry.port === undefined ? { portsInferred: true } : {}), - ...(entry.health ? { healthPath: entry.health } : {}), + ...(typeof entry.health === 'string' ? { healthPath: entry.health } : {}), + ...(healthConfig ? { healthConfig } : {}), ...(entry.portConflictPolicy ? { portConflictPolicy: entry.portConflictPolicy } : {}) }) } diff --git a/apps/desktop/src/main/core/devhub-core.ts b/apps/desktop/src/main/core/devhub-core.ts index fef2357..3383524 100644 --- a/apps/desktop/src/main/core/devhub-core.ts +++ b/apps/desktop/src/main/core/devhub-core.ts @@ -32,11 +32,11 @@ import { } from './groups/group-history' import { createGroupRunner } from './groups/group-runner' import { createGroupService, emptyGroupsFile, groupsFileSchema } from './groups/group-service' +import { createScheduleTargetExecutor } from './schedules/schedule-executor' import { createScheduleService, emptySchedulesFile, - schedulesFileSchema, - type ScheduleTargetExecutor + schedulesFileSchema } from './schedules/schedule-service' import { createEventBus } from './events/event-bus' import { createIdentityReader } from './process/process-identity' @@ -228,56 +228,13 @@ export function createDevhubCore(env: CoreEnvironment): DevhubCore { ) }) - const scheduleExecutor: ScheduleTargetExecutor = { - validate: async (target) => { - if (target.kind === 'script') { - await scripts.find(target.projectId, target.scriptId) - } else { - await groupService.get(target.groupId) - } - }, - isRunning: async (target) => { - if (target.kind === 'script') { - return runs - .list() - .some( - (run) => - run.kind === 'script' && - run.projectId === target.projectId && - run.scriptId === target.scriptId && - run.status !== 'exited' - ) - } - return groupRunner.isRunning(target.groupId) - }, - start: async (target) => { - if (target.kind === 'script') await runs.start(target.projectId, target.scriptId) - else await groupRunner.start(target.groupId) - }, - stop: async (target) => { - if (target.kind === 'script') { - const activeRuns = runs - .list() - .filter( - (run) => - run.kind === 'script' && - run.projectId === target.projectId && - run.scriptId === target.scriptId && - run.status !== 'exited' - ) - await Promise.all(activeRuns.map((run) => runs.stop(run.id))) - } else { - await groupRunner.stop(target.groupId) - } - } - } const schedules = createScheduleService({ store: createJsonStore({ filePath: join(env.dataDir, 'schedules.json'), schema: schedulesFileSchema, fallback: emptySchedulesFile }), - executor: scheduleExecutor, + executor: createScheduleTargetExecutor({ scripts, runs, groupService, groupRunner }), emit: (event) => events.emit(event) }) @@ -307,7 +264,20 @@ export function createDevhubCore(env: CoreEnvironment): DevhubCore { healthTargetOf((await scripts.find(run.projectId, run.scriptId)).script), checkers: { checkPort: checkLocalPort, - checkHttp: (port, path) => checkLocalHttp(port, path) + checkHttp: (port, path) => checkLocalHttp(port, path), + checkAlive: async (runId) => + runs.list().some((r) => r.id === runId && r.status === 'running'), + checkOutput: async (runId, pattern, regex) => { + try { + const text = runs.output(runId).data + if (regex) { + return new RegExp(pattern).test(text) + } + return text.includes(pattern) + } catch { + return false + } + } }, emit: (event) => events.emit(event) }) diff --git a/apps/desktop/src/main/core/health/health-monitor.test.ts b/apps/desktop/src/main/core/health/health-monitor.test.ts index f28b72b..6df54e0 100644 --- a/apps/desktop/src/main/core/health/health-monitor.test.ts +++ b/apps/desktop/src/main/core/health/health-monitor.test.ts @@ -153,4 +153,98 @@ describe('createHealthMonitor', () => { await vi.advanceTimersByTimeAsync(0) expect(states()).toEqual(['starting', null]) }) + + it('handles alive targets: transitions to ready after delay if still running', async () => { + target = { type: 'alive', delayMs: 2000 } + monitor.dispose() + monitor = createHealthMonitor({ + subscribe: (listener) => { + listeners.push(listener) + return () => (listeners = listeners.filter((l) => l !== listener)) + }, + resolveTarget: async () => target, + checkers: { + checkPort: async () => false, + checkHttp: async () => false, + checkAlive: async () => true + }, + emit: (event) => emitted.push(event), + startingIntervalMs: 1000, + readyIntervalMs: 5000, + now: () => new Date('2026-10-02T00:00:00.000Z') + }) + + const run = scriptRun({ startedAt: '2026-10-02T00:00:00.000Z' }) + publish({ type: 'run-updated', run }) + await vi.advanceTimersByTimeAsync(0) + expect(states()).toEqual(['starting']) + expect(monitor.list()).toMatchObject([ + { runId: 'r1', state: 'starting', target: '进程稳定运行' } + ]) + + // After 1000ms: still starting + await vi.advanceTimersByTimeAsync(1000) + expect(states()).toEqual(['starting']) + + // Advancing time past 2000ms + monitor.dispose() + let currentTime = 0 + monitor = createHealthMonitor({ + subscribe: (listener) => { + listeners.push(listener) + return () => (listeners = listeners.filter((l) => l !== listener)) + }, + resolveTarget: async () => target, + checkers: { + checkPort: async () => false, + checkHttp: async () => false, + checkAlive: async () => true + }, + emit: (event) => emitted.push(event), + startingIntervalMs: 1000, + readyIntervalMs: 5000, + now: () => new Date(Date.parse('2026-10-02T00:00:00.000Z') + currentTime) + }) + emitted = [] + publish({ type: 'run-updated', run }) + await vi.advanceTimersByTimeAsync(0) + expect(states()).toEqual(['starting']) + currentTime = 2500 + await vi.advanceTimersByTimeAsync(1000) + expect(states()).toEqual(['starting', 'ready']) + }) + + it('handles output targets: transitions to ready when pattern is found', async () => { + target = { type: 'output', pattern: 'Server started' } + let hasOutput = false + monitor.dispose() + monitor = createHealthMonitor({ + subscribe: (listener) => { + listeners.push(listener) + return () => (listeners = listeners.filter((l) => l !== listener)) + }, + resolveTarget: async () => target, + checkers: { + checkPort: async () => false, + checkHttp: async () => false, + checkOutput: async () => hasOutput + }, + emit: (event) => emitted.push(event), + startingIntervalMs: 1000 + }) + + publish({ type: 'run-updated', run: scriptRun() }) + await vi.advanceTimersByTimeAsync(0) + expect(states()).toEqual(['starting']) + expect(monitor.list()).toMatchObject([ + { runId: 'r1', state: 'starting', target: '输出包含「Server started」' } + ]) + + await vi.advanceTimersByTimeAsync(2000) + expect(states()).toEqual(['starting']) + + hasOutput = true + await vi.advanceTimersByTimeAsync(1000) + expect(states()).toEqual(['starting', 'ready']) + }) }) diff --git a/apps/desktop/src/main/core/health/health-monitor.ts b/apps/desktop/src/main/core/health/health-monitor.ts index 70fa448..4158f36 100644 --- a/apps/desktop/src/main/core/health/health-monitor.ts +++ b/apps/desktop/src/main/core/health/health-monitor.ts @@ -33,6 +33,7 @@ interface Tracker { /** Null while the target is being resolved, or when the run has nothing to check. */ health: RunHealth | null failures: number + startedAt?: string timer?: ReturnType } @@ -68,7 +69,11 @@ export function createHealthMonitor({ } const poll = async (runId: string, tracker: Tracker, target: HealthTarget): Promise => { - const ok = await checkHealthTarget(target, checkers) + const ok = await checkHealthTarget(target, checkers, { + runId, + startedAt: tracker.startedAt, + now: now() + }) // The run may have stopped while the check was in flight. const health = tracker.health if (tracked.get(runId) !== tracker || !health) return @@ -84,7 +89,11 @@ export function createHealthMonitor({ } const track = async (run: ScriptRun): Promise => { - const tracker: Tracker = { health: null, failures: 0 } + const tracker: Tracker = { + health: null, + failures: 0, + startedAt: run.startedAt + } // Registered before resolving, so repeated `run-updated` events do not track twice. tracked.set(run.id, tracker) const target = await resolveTarget(run).catch(() => null) diff --git a/apps/desktop/src/main/core/health/health-target.test.ts b/apps/desktop/src/main/core/health/health-target.test.ts index 1f2fa70..014c07b 100644 --- a/apps/desktop/src/main/core/health/health-target.test.ts +++ b/apps/desktop/src/main/core/health/health-target.test.ts @@ -16,7 +16,7 @@ const script = (overrides: Partial