refactor(cmdline): make command providers ordinary

This commit is contained in:
Turtle
2026-08-10 21:49:11 +08:00
parent 668bdb3d8e
commit 09e2d2ddc1
46 changed files with 400 additions and 742 deletions

View File

@@ -1,8 +1,6 @@
/**
* The web app's startup row over a REAL Loader tree: every flag lands in the
* `webStartup` service the web rows read, the bind it reports comes from the
* flag or from what the composition falls back to, `--help` resolves nothing,
* and a rejected argument exits without resolving anything.
* The Web command-line provider over a real Loader tree: its ordinary service
* releases a consumer whose config reads `ctx.webStartup` directly.
*/
import { mkdtempSync, writeFileSync } from 'node:fs'
@@ -13,21 +11,14 @@ import { Context } from 'cordis'
import Loader from '@cordisjs/plugin-loader'
import Include from '@cordisjs/plugin-include'
import { internals, provideCmdline } from '@deepseek-ai/dsh-cmdline'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, describe, expect, it } from 'vitest'
import { apply, WEB_STARTUP_SERVICE, type WebStartupValues } from '../src/startup.ts'
vi.mock('node:os', async importOriginal => ({
...await importOriginal<typeof import('node:os')>(),
networkInterfaces: () => ({
lo0: [{ family: 'IPv4', internal: true, address: '127.0.0.1' }],
en0: [{ family: 'IPv4', internal: false, address: '192.168.1.5' }],
}),
}))
/** What one boot of the fixture tree observed. */
/** What one fixture boot observed. */
interface Observed {
exits: number[]
out: string
readerConfig?: unknown
}
const disposers: (() => Promise<void>)[] = []
@@ -39,67 +30,48 @@ afterEach(async () => {
})
/**
* Mount the real startup row over a stand-in for the `webserver` row whose
* composed bind it reads before the dependent rows activate.
* Mount the real provider and a consumer using injection-ordered config.
* @param args - the invocation's inner arguments.
* @param webserverConfig - the composed `webserver` row config, or `null` to omit the row.
* @param trustedHosts - authorities the composed connection row already carries, or `null` when it carries none.
* @returns the resolved service value (absent when the app requested exit) and what the boot observed.
* @returns the service value and observed consumer/process effects.
*/
async function bootStartup(
args: string[],
webserverConfig: Record<string, unknown> | null = { host: '127.0.0.1', port: 3080 },
trustedHosts: unknown = [],
): Promise<{ values: WebStartupValues | undefined; observed: Observed; ctx: Context }> {
async function bootProvider(args: string[]): Promise<{
values: WebStartupValues | undefined
observed: Observed
}> {
const dir = mkdtempSync(join(tmpdir(), 'dsh-web-startup-'))
const observed: Observed = { exits: [], out: '' }
writeFileSync(join(dir, 'row.mjs'), 'export function apply() {}\n')
// The Loader imports a row through Node's own resolver, which cannot resolve
// this workspace's sources; the row delegates to the real plugin the test
// imported through the source-plane path mapping.
writeFileSync(join(dir, 'startup.mjs'), `
writeFileSync(join(dir, 'reader.mjs'), `
export function apply(_ctx, config) { globalThis.__webStartupObserved.readerConfig = config }
`)
// Node imports the fixture row outside Vite's source resolver, so delegate
// to the source-plane plugin already imported by this test.
writeFileSync(join(dir, 'provider.mjs'), `
export const name = 'web-startup'
export const inject = ['cmdlineArgs']
export const apply = ctx => globalThis.__webStartupApply(ctx)
`)
const rowUrl = pathToFileURL(join(dir, 'row.mjs')).href
writeFileSync(join(dir, 'cordis.yml'), [
...webserverConfig === null ? [] : [
'- id: webserver',
` name: ${rowUrl}`,
` inject: [${WEB_STARTUP_SERVICE}]`,
' disabled: true',
' config:',
...Object.entries(webserverConfig).map(([key, value]) => ` ${key}: !!js ctx.get('${WEB_STARTUP_SERVICE}')?.${key} ?? ${JSON.stringify(value)}`),
],
'- id: connection',
` name: ${rowUrl}`,
'- id: reader',
` name: ${pathToFileURL(join(dir, 'reader.mjs')).href}`,
` inject: [${WEB_STARTUP_SERVICE}]`,
' disabled: true',
...trustedHosts === null ? [] : [
' config:',
` trustedHosts: !!js ctx.get('${WEB_STARTUP_SERVICE}')?.trustedHosts ?? ${JSON.stringify(trustedHosts)}`,
],
// A second reader keeps the composition honest when the webserver row is
// the one under test: the service must still have someone to serve.
'- id: web-runtime',
` name: ${rowUrl}`,
` inject: [${WEB_STARTUP_SERVICE}]`,
' disabled: true',
// The reload chain this bundle ships off, which `--dev` turns on.
'- id: client-hmr',
` name: ${rowUrl}`,
` inject: [${WEB_STARTUP_SERVICE}]`,
' disabled: true',
'- id: web-startup',
` name: ${pathToFileURL(join(dir, 'startup.mjs')).href}`,
' inject: [cmdlineArgs]',
' config:',
" host: !!js ctx.webStartup.host ?? '127.0.0.1'",
' port: !!js ctx.webStartup.port ?? 3080',
' mode: !!js ctx.webStartup.mode',
' trustedHosts: !!js ctx.webStartup.trustedHosts',
'- id: provider',
` name: ${pathToFileURL(join(dir, 'provider.mjs')).href}`,
'',
].join('\n'))
const observing = { write: (chunk: string) => { observed.out += chunk; return true } }
internals.stdout = observing
internals.stderr = observing
;(globalThis as unknown as { __webStartupApply: typeof apply }).__webStartupApply = apply
const globals = globalThis as unknown as {
__webStartupApply: typeof apply
__webStartupObserved: Observed
}
globals.__webStartupApply = apply
globals.__webStartupObserved = observed
const ctx = new Context()
await ctx.plugin(Loader)
@@ -108,89 +80,56 @@ export const apply = ctx => globalThis.__webStartupApply(ctx)
await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(join(dir, 'cordis.yml')).href } })
await ctx.loader.await()
disposers.push(async () => { await ctx.fiber.dispose() })
return { values: ctx.get(WEB_STARTUP_SERVICE) as WebStartupValues | undefined, observed, ctx }
return {
values: ctx.get(WEB_STARTUP_SERVICE) as WebStartupValues | undefined,
observed,
}
}
describe('web startup', () => {
it('resolves each flag into the value its row reads', async () => {
const { values } = await bootStartup(['--port', '8080'])
describe('web command-line provider', () => {
it('publishes each flag and releases direct service expressions', async () => {
const { values, observed } = await bootProvider([
'--host', '0.0.0.0',
'--port', '8080',
'--dev',
'--trusted-host', 'lab.internal', 'lab-2.internal',
'--trusted-host', '10.0.0.9',
])
expect(values).toEqual({
host: '0.0.0.0',
port: 8080,
mode: 'development',
trustedHosts: ['lab.internal', 'lab-2.internal', '10.0.0.9'],
})
expect(observed.readerConfig).toEqual(values)
expect(observed.exits).toEqual([])
})
it('leaves deployment values to each consumer when flags omit them', async () => {
const { values, observed } = await bootProvider([])
expect(values).toEqual({ mode: 'production', trustedHosts: [] })
expect(observed.readerConfig).toEqual({
host: '127.0.0.1',
port: 3080,
mode: 'production',
trustedHosts: [],
lanAddresses: [],
})
})
it('names no value for a flag the invocation left out, so each row keeps its own', async () => {
const { values } = await bootStartup([])
expect(values).toEqual({ mode: 'production', trustedHosts: [], lanAddresses: [] })
expect(values).not.toHaveProperty('host')
expect(values).not.toHaveProperty('port')
})
it('adds LAN literals and explicit extras after the composed fence authorities', async () => {
const { values } = await bootStartup(
['--host', '0.0.0.0', '--trusted-host', 'lab.internal', 'lab-2.internal', '--trusted-host', '10.0.0.9'],
{ host: '127.0.0.1', port: 3080 },
['profile.internal'],
)
expect(values?.trustedHosts).toEqual([
'profile.internal', '192.168.1.5', 'lab.internal', 'lab-2.internal', '10.0.0.9',
])
// Display gets the same single sample the fence was configured with.
expect(values?.lanAddresses).toEqual(['192.168.1.5'])
})
it('starts from an empty trust list when the composed connection row names none', async () => {
const { values } = await bootStartup(
['--trusted-host', 'lab.internal'],
{ host: '127.0.0.1', port: 3080 },
null,
)
expect(values?.trustedHosts).toEqual(['lab.internal'])
})
it.each([
'profile.internal',
['profile.internal', 1],
])('rejects an invalid composed trust list before transforming it (%j)', async (trustedHosts) => {
await expect(bootStartup([], { host: '127.0.0.1', port: 3080 }, trustedHosts))
.rejects.toThrow('the composed connection trustedHosts must be an array of strings')
})
it('reads the composed bind when no flag names one, so a configured 0.0.0.0 still derives them', async () => {
const { values } = await bootStartup([], { host: '0.0.0.0', port: 3080 })
expect(values?.lanAddresses).toEqual(['192.168.1.5'])
})
it('reports the development mode for --dev, which the web runtime reads', async () => {
const { values } = await bootStartup(['--dev'])
// The runtime row turns the reload chain on after its host dependencies
// activate; this row only reports the mode.
expect(values?.mode).toBe('development')
})
it('prints its own help and resolves nothing', async () => {
const { values, observed } = await bootStartup(['--help'])
it('prints its own help and leaves the consumer pending', async () => {
const { values, observed } = await bootProvider(['--help'])
expect(observed.out).toContain('dsh --profile web')
expect(observed.out).toContain('--trusted-host')
expect(values).toBeUndefined()
expect(observed.readerConfig).toBeUndefined()
expect(observed.exits).toEqual([0])
})
it('rejects a non-numeric port before anything binds', async () => {
const { values, observed } = await bootStartup(['--port', 'abc'])
it('rejects a non-numeric port before the consumer activates', async () => {
const { values, observed } = await bootProvider(['--port', 'abc'])
expect(observed.out).toContain('--port must be a number')
expect(values).toBeUndefined()
expect(observed.readerConfig).toBeUndefined()
expect(observed.exits).toEqual([1])
})
it('fails the boot when the composition lost the row whose bind it reads', async () => {
// The bundle patch and this startup row must agree on the row set; a
// missing row would otherwise silently drop the flag that targets it.
await expect(bootStartup([], null))
.rejects.toThrow('the web composition has no waiting "webserver" row to configure')
})
})

View File

@@ -1,7 +1,7 @@
/** Single-sample LAN-trust resolution for the /api browser-trust fence (`resolveLanTrust`). */
import { describe, expect, it, vi } from 'vitest'
import { resolveLanTrust } from '../src/startup.ts'
import { resolveLanTrust } from '../src/index.ts'
vi.mock('node:os', () => ({
networkInterfaces: () => ({
@@ -26,8 +26,9 @@ describe('resolveLanTrust', () => {
expect(trustedHosts).toEqual(['192.168.1.5', '10.0.0.7', 'harness.internal:3080'])
})
it('derives nothing for a loopback or unresolved bind — extras alone stand, no LAN URL to print', () => {
it('derives nothing for a loopback bind — extras alone stand, no LAN URL to print', () => {
expect(resolveLanTrust('127.0.0.1', [])).toEqual({ lanAddresses: [], trustedHosts: [] })
expect(resolveLanTrust(undefined, ['lab.internal'])).toEqual({ lanAddresses: [], trustedHosts: ['lab.internal'] })
expect(resolveLanTrust('127.0.0.1', ['lab.internal']))
.toEqual({ lanAddresses: [], trustedHosts: ['lab.internal'] })
})
})

View File

@@ -2,7 +2,7 @@
* Web runtime glue behavior: dist resolution through the bundle's own hook,
* the frontend-static child claiming the fallback seat, the web-surface
* prompt section and bash runtime variables, and URL-line printing with the
* app startup row's LAN snapshot.
* runtime's bind-dependent LAN snapshot.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
@@ -14,6 +14,14 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import type { HttpServerService } from '@deepseek-ai/dsh-host-webserver'
import { apply, Config, internals } from '../src/index.ts'
vi.mock('node:os', async importOriginal => ({
...await importOriginal<typeof import('node:os')>(),
networkInterfaces: () => ({
lo0: [{ family: 'IPv4', internal: true, address: '127.0.0.1' }],
en0: [{ family: 'IPv4', internal: false, address: '192.168.1.5' }],
}),
}))
let dist: string | undefined
afterEach(() => {
@@ -36,9 +44,10 @@ function stageDist(): string {
}
/** A fake httpServer capturing the fallback seat and index taps. */
function fakeHttpServer(): { server: HttpServerService; seat: () => unknown } {
function fakeHttpServer(host: '127.0.0.1' | '0.0.0.0' = '127.0.0.1'): { server: HttpServerService; seat: () => unknown } {
let fallback: unknown
const server = {
host,
port: 4567,
registerFallback: (handler: unknown) => {
fallback = handler
@@ -72,7 +81,7 @@ describe('web-app runtime glue', () => {
it('mounts dist serving, prompt section, bash variables, and prints the URL with the LAN snapshot', async () => {
stageDist()
const ctx = new Context()
const { server, seat } = fakeHttpServer()
const { server, seat } = fakeHttpServer('0.0.0.0')
ctx.provide('httpServer', server)
const contributions: BashContribution[] = []
ctx.provide('bashEnv', {
@@ -83,14 +92,17 @@ describe('web-app runtime glue', () => {
} as never)
const enabledRows = provideHmrRow(ctx)
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await apply(ctx, new Config({ mode: 'development', printUrl: true, surfaceContext: true, lanAddresses: ['192.168.1.5'] }))
await apply(ctx, new Config({ mode: 'development', printUrl: true, surfaceContext: true, trustedHosts: ['lab.internal'] }))
await ctx.plugin(SystemPrompt, { persona: '' })
// Settle the injected registrations.
await new Promise(resolve => setTimeout(resolve, 0))
expect(seat()).toBeDefined() // frontend-static claimed the fallback
expect(enabledRows).toEqual(['client-hmr'])
expect(ctx.get('webClientRoster')).toBe(true)
expect(ctx.get('webRuntime')).toEqual({
lanAddresses: ['192.168.1.5'],
trustedHosts: ['192.168.1.5', 'lab.internal'],
})
expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567 (LAN: http://192.168.1.5:4567)')
const assembly = await ctx.systemPrompt.assemble()
expect(assembly.sections.find(entry => entry.name === 'harness:source')?.text).toContain('DeepSeek Harness implementation checkout')
@@ -107,7 +119,7 @@ describe('web-app runtime glue', () => {
const ctx = new Context()
ctx.provide('httpServer', fakeHttpServer().server)
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: true, lanAddresses: [] }))
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: true, trustedHosts: [] }))
await ctx.plugin(SystemPrompt, { persona: '' })
await new Promise(resolve => setTimeout(resolve, 0))
expect(log).not.toHaveBeenCalled()
@@ -128,7 +140,7 @@ describe('web-app runtime glue', () => {
return () => {}
},
} as never)
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: false, lanAddresses: [] }))
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: false, trustedHosts: [] }))
await ctx.plugin(SystemPrompt, { persona: '' })
await new Promise(resolve => setTimeout(resolve, 0))
const assembly = await ctx.systemPrompt.assemble()
@@ -143,7 +155,7 @@ describe('web-app runtime glue', () => {
const ctx = new Context()
ctx.provide('httpServer', fakeHttpServer().server)
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await apply(ctx, new Config({ mode: 'production', printUrl: true, surfaceContext: true, lanAddresses: [] }))
await apply(ctx, new Config({ mode: 'production', printUrl: true, surfaceContext: true, trustedHosts: [] }))
await new Promise(resolve => setTimeout(resolve, 0))
expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567')
await ctx.fiber.dispose()
@@ -159,7 +171,7 @@ describe('web-app runtime glue', () => {
const settlement = new Promise<void>((resolve) => { release = resolve })
provideHmrRow(settled, () => settlement)
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
await apply(settled, new Config({ mode: 'production', printUrl: true, surfaceContext: true, lanAddresses: [] }))
await apply(settled, new Config({ mode: 'production', printUrl: true, surfaceContext: true, trustedHosts: [] }))
await new Promise(resolve => setTimeout(resolve, 0))
expect(log).not.toHaveBeenCalled()
release!()
@@ -173,7 +185,7 @@ describe('web-app runtime glue', () => {
const failed = new Context()
failed.provide('httpServer', fakeHttpServer().server)
provideHmrRow(failed, async () => { throw new Error('boot failed') })
await apply(failed, new Config({ mode: 'production', printUrl: true, surfaceContext: true, lanAddresses: [] }))
await apply(failed, new Config({ mode: 'production', printUrl: true, surfaceContext: true, trustedHosts: [] }))
await new Promise(resolve => setTimeout(resolve, 0))
expect(log).not.toHaveBeenCalled()
await failed.fiber.dispose()
@@ -189,7 +201,7 @@ describe('web-app runtime glue', () => {
let releaseTorn: () => void
const tornSettlement = new Promise<void>((resolve) => { releaseTorn = resolve })
provideHmrRow(torn, () => tornSettlement)
await apply(torn, new Config({ mode: 'production', printUrl: true, surfaceContext: true, lanAddresses: [] }))
await apply(torn, new Config({ mode: 'production', printUrl: true, surfaceContext: true, trustedHosts: [] }))
await child.dispose() // the httpServer service goes away
releaseTorn!()
await new Promise(resolve => setTimeout(resolve, 0))
@@ -205,7 +217,7 @@ describe('web-app runtime glue', () => {
const { server } = fakeHttpServer()
Object.defineProperty(server, 'port', { get: () => undefined })
ctx.provide('httpServer', server)
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: true, lanAddresses: [] }))
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: true, trustedHosts: [] }))
await ctx.plugin(SystemPrompt, { persona: '' })
await new Promise(resolve => setTimeout(resolve, 0))
await expect(ctx.systemPrompt.assemble()).rejects.toThrow('httpServer service missing')