Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions apps/desktop/src/main/core/detectors/config-detector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' }])
Expand Down
26 changes: 23 additions & 3 deletions apps/desktop/src/main/core/detectors/config-detector.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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,
Expand All @@ -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 } : {})
})
}
Expand Down
64 changes: 17 additions & 47 deletions apps/desktop/src/main/core/devhub-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
})

Expand Down Expand Up @@ -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)
})
Expand Down
94 changes: 94 additions & 0 deletions apps/desktop/src/main/core/health/health-monitor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
})
})
13 changes: 11 additions & 2 deletions apps/desktop/src/main/core/health/health-monitor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof setTimeout>
}

Expand Down Expand Up @@ -68,7 +69,11 @@ export function createHealthMonitor({
}

const poll = async (runId: string, tracker: Tracker, target: HealthTarget): Promise<void> => {
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
Expand All @@ -84,7 +89,11 @@ export function createHealthMonitor({
}

const track = async (run: ScriptRun): Promise<void> => {
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)
Expand Down
Loading