diff --git a/apps/api/src/domain/control-plane.ts b/apps/api/src/domain/control-plane.ts index 1b73375..7aa99f8 100644 --- a/apps/api/src/domain/control-plane.ts +++ b/apps/api/src/domain/control-plane.ts @@ -276,7 +276,15 @@ export class ControlPlane { return providers.map(id => { const { name, binaryVariable, proxied } = providerCatalog[id]; const native = id === 'claude-code' && nativeClaudeEnabled(this.env, awaitedTenantId); - const configured = connected(id) || native; + const tenantCredential = connected(id); + const configured = tenantCredential || native; + const credentialSource: ProviderInfo['credentialSource'] = native + ? tenantCredential + ? 'mixed' + : 'native_account' + : tenantCredential + ? 'tenant_credential' + : 'none'; const productionAllowed = !isProduction(this.env) || (proxied && providerProxyConfigured(this.env)); const installed = !binaryVariable || Boolean(this.env[binaryVariable]); const enabled = configured && productionAllowed && installed; @@ -286,13 +294,16 @@ export class ControlPlane { ? 'Connect a tenant-owned provider credential to execute tasks.' : !installed ? `The ${name} executable is not configured on the worker (${binaryVariable}).` - : native - ? 'Available through the explicitly configured local Claude CLI account; trusted local operators only.' - : 'Available for worker preflight; account/model access is checked when a task starts.'; + : credentialSource === 'mixed' + ? 'Native Claude account mode and a tenant credential are both configured; authentication precedence has not been verified.' + : native + ? 'Available through the explicitly configured local Claude CLI account; trusted local operators only.' + : 'Available for worker preflight; account/model access is checked when a task starts.'; return { id, name, configured, + credentialSource, enabled, reason, capabilities: { diff --git a/apps/runner/src/health.ts b/apps/runner/src/health.ts new file mode 100644 index 0000000..de3a28a --- /dev/null +++ b/apps/runner/src/health.ts @@ -0,0 +1,50 @@ +import { mkdir, rename, writeFile } from 'node:fs/promises'; +import path from 'node:path'; + +type Status = 'starting' | 'idle' | 'executing' | 'poll_error' | 'task_error' | 'stopped'; +export interface RunnerHealthSnapshot { + schemaVersion: 1; + pid: number; + status: Status; + updatedAt: string; + lastPollSuccessAt?: string; +} + +/** Local diagnostic evidence only. Never includes credentials, arguments or task payloads. */ +export class RunnerHealth { + private status: Status = 'starting'; + private lastPollSuccessAt?: string; + private writes: Promise = Promise.resolve(); + constructor( + private readonly directory: string, + private readonly pid = process.pid, + private readonly now = () => new Date().toISOString(), + private readonly failed = () => console.error('Runner health snapshot could not be written'), + ) {} + update(status: Status, pollSucceeded = false) { + this.status = status; + if (pollSucceeded) this.lastPollSuccessAt = this.now(); + return this.heartbeat(); + } + heartbeat() { + const snapshot: RunnerHealthSnapshot = { + schemaVersion: 1, + pid: this.pid, + status: this.status, + updatedAt: this.now(), + ...(this.lastPollSuccessAt ? { lastPollSuccessAt: this.lastPollSuccessAt } : {}), + }; + this.writes = this.writes + .then(async () => { + await mkdir(this.directory, { recursive: true, mode: 0o700 }); + const file = path.join(this.directory, 'health.json'); + const temporary = `${file}.${this.pid}.tmp`; + await writeFile(temporary, `${JSON.stringify(snapshot)}\n`, { mode: 0o600 }); + await rename(temporary, file); + }) + .catch(() => { + this.failed(); + }); + return this.writes; + } +} diff --git a/apps/runner/src/main.ts b/apps/runner/src/main.ts index 28fe04b..60ac341 100644 --- a/apps/runner/src/main.ts +++ b/apps/runner/src/main.ts @@ -9,6 +9,7 @@ import { requireDeploymentMode } from '@wishforge/contracts'; import { OutboundRunner } from './runner.js'; import { createRunnerTransport } from './transport.js'; import { createRunnerAdapters } from './adapters.js'; +import { RunnerHealth } from './health.js'; async function main() { requireDeploymentMode(process.env); @@ -39,29 +40,44 @@ async function main() { trustedPocDelivery, }); let stopped = false; + const health = new RunnerHealth(process.env.WF_RUNNER_STATE_DIR!); + await health.heartbeat(); + const healthTimer = setInterval(() => { + void health.heartbeat(); + }, 10000); process.once('SIGTERM', () => { stopped = true; }); process.once('SIGINT', () => { stopped = true; }); - while (!stopped) { - try { - const task = (await request( - `/internal/runner/tasks?environmentId=${encodeURIComponent(process.env.WF_ENVIRONMENT_ID!)}`, - )) as SignedRunnerTask | null; - if (task) { - const result = await runner.execute(task); - await request(`/internal/runner/tasks/${encodeURIComponent(task.payload.id)}/result`, { result }); + try { + while (!stopped) { + let phase: 'poll' | 'task' = 'poll'; + try { + const task = (await request( + `/internal/runner/tasks?environmentId=${encodeURIComponent(process.env.WF_ENVIRONMENT_ID!)}`, + )) as SignedRunnerTask | null; + await health.update(task ? 'executing' : 'idle', true); + if (task) { + phase = 'task'; + const result = await runner.execute(task); + await request(`/internal/runner/tasks/${encodeURIComponent(task.payload.id)}/result`, { result }); + await health.update('idle'); + } + } catch (error) { + await health.update(phase === 'poll' ? 'poll_error' : 'task_error'); + console.error( + JSON.stringify({ level: 'error', message: error instanceof Error ? error.message : 'Runner poll failed' }), + ); } - } catch (error) { - console.error( - JSON.stringify({ level: 'error', message: error instanceof Error ? error.message : 'Runner poll failed' }), - ); + await new Promise(resolve => setTimeout(resolve, 5_000)); } - await new Promise(resolve => setTimeout(resolve, 5_000)); + } finally { + clearInterval(healthTimer); + await health.update('stopped'); + close(); } - close(); } void main().catch(error => { console.error(error.message); diff --git a/apps/runner/test/health.test.ts b/apps/runner/test/health.test.ts new file mode 100644 index 0000000..ec07e34 --- /dev/null +++ b/apps/runner/test/health.test.ts @@ -0,0 +1,49 @@ +import { afterEach, expect, it } from 'vitest'; +import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { RunnerHealth } from '../src/health.js'; +const dirs: string[] = []; +afterEach(async () => { + await Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))); +}); +async function temporary() { + const dir = await mkdtemp(path.join(os.tmpdir(), 'wishforge-runner-health-')); + dirs.push(dir); + return dir; +} + +it('publishes private atomic state and records successful polling without losing executing status on heartbeat', async () => { + const directory = await temporary(); + const health = new RunnerHealth(directory, 123, () => '2026-10-25T00:00:00Z'); + await health.heartbeat(); + const file = path.join(directory, 'health.json'); + expect(JSON.parse(await readFile(file, 'utf8'))).not.toHaveProperty('lastPollSuccessAt'); + await health.update('executing', true); + await health.heartbeat(); + expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({ + schemaVersion: 1, + pid: 123, + status: 'executing', + updatedAt: '2026-10-25T00:00:00Z', + lastPollSuccessAt: '2026-10-25T00:00:00Z', + }); + expect((await stat(file)).mode & 0o777).toBe(0o600); + await health.update('poll_error'); + expect(JSON.parse(await readFile(file, 'utf8')).status).toBe('poll_error'); +}); + +it('diagnostic disk failures do not reject execution and concurrent writes preserve the latest state', async () => { + const directory = await temporary(); + const blockingFile = path.join(directory, 'not-a-directory'); + await writeFile(blockingFile, 'fixture'); + let failures = 0; + const broken = new RunnerHealth(blockingFile, 123, undefined, () => { + failures++; + }); + await expect(broken.update('executing', true)).resolves.toBeUndefined(); + expect(failures).toBe(1); + const health = new RunnerHealth(directory); + await Promise.all([health.update('idle', true), health.update('executing'), health.update('stopped')]); + expect(JSON.parse(await readFile(path.join(directory, 'health.json'), 'utf8')).status).toBe('stopped'); +}); diff --git a/apps/web/src/components/ui.tsx b/apps/web/src/components/ui.tsx index f6b24bb..fb0e40f 100644 --- a/apps/web/src/components/ui.tsx +++ b/apps/web/src/components/ui.tsx @@ -126,7 +126,15 @@ const errorTitles: Record = { 429: '已达到配额或并发上限', 503: '所需的服务尚未配置或暂不可用', }; -export function ErrorNotice({ error, retry }: { error: unknown; retry?: () => void }) { +export function ErrorNotice({ + error, + retry, + retrying = false, +}: { + error: unknown; + retry?: () => void; + retrying?: boolean; +}) { const status = error instanceof ApiError ? error.status : 0; const unauthorized = status === 401; return ( @@ -142,8 +150,8 @@ export function ErrorNotice({ error, retry }: { error: unknown; retry?: () => vo ) : retry ? ( - ) : null} diff --git a/apps/web/src/features/dashboard.tsx b/apps/web/src/features/dashboard.tsx index 4e8a7b7..213b5ac 100644 --- a/apps/web/src/features/dashboard.tsx +++ b/apps/web/src/features/dashboard.tsx @@ -2,6 +2,7 @@ import Link from 'next/link'; import { ArrowRight, CircleAlert, GitBranch, Laptop, Plus, Settings2 } from 'lucide-react'; import { formatNumber, useResource } from '@/lib/api'; +import { resourceState } from '@/lib/readiness'; import type { Dashboard } from '@/lib/types'; import { ButtonLink, EmptyState, ErrorNotice, Loading, PageHeader, Panel } from '@/components/ui'; import { RunTable } from '@/components/run-table'; @@ -13,7 +14,16 @@ const journey = [ ['部署与观察', '部署到目标环境,并持续观察运行状态。'], ]; export function DashboardView() { - const { data, error, isLoading, mutate } = useResource('/dashboard', 10000); + const { data: cachedData, error, isLoading, isValidating, mutate } = useResource('/dashboard', 10000); + const data = error && [401, 403].includes(error.status) ? undefined : cachedData; + const connectionState = resourceState(Boolean(data), Boolean(error), isValidating); + const connectionTitle = { + ready: '控制面已连接', + refreshing: '正在刷新控制面', + loading: '正在连接控制面', + stale: '控制面连接已中断', + unavailable: '控制面尚未连接', + }[connectionState]; const metrics = [ { title: '进行中的运行', @@ -32,9 +42,9 @@ export function DashboardView() { note: '需要你的判断', }, { - title: '已连接执行器', + title: '配置可用的执行器', value: data?.providers.filter(provider => provider.configured && provider.enabled).length, - note: '可用于新的运行', + note: '账号权限在任务启动时检查', }, ]; return ( @@ -49,13 +59,15 @@ export function DashboardView() { } /> - {error ? void mutate()} /> : null} + {error ? ( + void mutate().catch(() => undefined)} retrying={isValidating} /> + ) : null}
{metrics.map(metric => (

{metric.title}

{formatNumber(metric.value)} -

{data ? metric.note : '等待控制面数据'}

+

{data ? (connectionState === 'ready' ? metric.note : '上次结果,当前状态待刷新') : '等待控制面数据'}

))}
@@ -90,11 +102,25 @@ export function DashboardView() { ))} -
+
- {data ? '控制面已连接' : '控制面尚未连接'} -

{data ? `${data.system.region} · ${data.system.authMode}` : '请完成工作空间配置以启用完整功能。'}

+ {connectionTitle} +

+ {connectionState === 'stale' + ? '保留上次成功读取的记录;重新连接后更新。' + : connectionState === 'refreshing' + ? '正在校验最新状态,暂显示上次结果。' + : data + ? `${data.system.region} · ${data.system.authMode}` + : error + ? '请查看上方错误提示,处理后重新连接。' + : '正在读取当前工作空间状态。'} +

diff --git a/apps/web/src/features/providers.tsx b/apps/web/src/features/providers.tsx index 3616038..e787ca9 100644 --- a/apps/web/src/features/providers.tsx +++ b/apps/web/src/features/providers.tsx @@ -3,6 +3,7 @@ import { ArrowRight, Check, CheckCircle2, Cpu, KeyRound, Minus, Terminal } from import { useState } from 'react'; import { providerCatalog } from '@wishforge/contracts/providers'; import { messageOf, mutateApi, useResource } from '@/lib/api'; +import { credentialSourceLabel } from '@/lib/readiness'; import type { ProviderConnection, ProviderInfo } from '@/lib/types'; import { Button, @@ -18,9 +19,9 @@ import { Status, } from '@/components/ui'; const descriptions: Record = { - codex: 'OpenAI Codex,在隔离的任务环境中实现与修复代码。', - codebuddy: '腾讯 CodeBuddy 命令行执行器,运行于隔离的任务环境。', - 'claude-code': 'Anthropic Claude Code 命令行执行器,运行于隔离的任务环境。', + codex: 'OpenAI Codex,实现与修复代码;执行方式由运行环境配置决定。', + codebuddy: '腾讯 CodeBuddy 命令行执行器,执行方式由运行环境配置决定。', + 'claude-code': 'Anthropic Claude Code 命令行执行器,支持运行主机配置的本机账号。', }; // Keys match ProviderInfo.capabilities returned by the control plane. const capabilityLabels: Record = { @@ -31,12 +32,15 @@ const capabilityLabels: Record = { usage: '用量计量', }; export function ProvidersView() { - const { data, error, isLoading, mutate } = useResource('/providers', 10000); + const { data: cachedData, error, isLoading, isValidating, mutate } = useResource('/providers', 10000); + const data = error && [401, 403].includes(error.status) ? undefined : cachedData; const [selected, setSelected] = useState(null); return ( <> - {error ? void mutate()} /> : null} + {error ? ( + void mutate().catch(() => undefined)} retrying={isValidating} /> + ) : null} 模型费用由你的服务商直接计费。WorkBuddy 通过 MCP 连接器发起愿望,不需要在这里配置。 {isLoading ? ( @@ -54,25 +58,40 @@ export function ProvidersView() {

{descriptions[provider.id]}

{Object.entries(provider.capabilities).map(([capability, value]) => ( - - {value === true ? : }{' '} + + {value === true && !error ? : }{' '} {capabilityLabels[capability] ?? capability} ))}
+

+ {error + ? '以下配置来自上次成功读取,当前状态尚未确认。' + : credentialSourceLabel(provider.credentialSource)} +

{provider.reason || '连接配置已由控制面确认。'}

- + {provider.credentialSource === 'native_account' ? ( +

本机账号由运行主机维护,账号与模型权限会在任务启动时检查。

+ ) : ( + + )}
))} @@ -86,7 +105,10 @@ export function ProvidersView() {

能力由适配器声明,执行由策略约束

-

界面不会把未配置的能力视为可用。凭据仅通过服务端代理发送,保存后不再回显。

+

+ 配置可用不代表账号或模型已经验证;实际检查在任务启动时进行。API Key + 保存后不再回显,本机账号无需在此重复填写。 +

{selected ? ( @@ -156,7 +178,7 @@ function CredentialDialog({ ); } function ConnectionList() { - const { data, error, mutate } = useResource('/provider-connections', 15000); + const { data, error, isValidating, mutate } = useResource('/provider-connections', 15000); const [removing, setRemoving] = useState(null); const [busy, setBusy] = useState(false); const [actionError, setError] = useState(''); @@ -178,7 +200,7 @@ function ConnectionList() { return ( {error ? ( - + void mutate().catch(() => undefined)} retrying={isValidating} /> ) : (
{data?.map(connection => ( diff --git a/apps/web/src/features/runs.tsx b/apps/web/src/features/runs.tsx index 396aab0..1db4b56 100644 --- a/apps/web/src/features/runs.tsx +++ b/apps/web/src/features/runs.tsx @@ -50,6 +50,7 @@ import { providers as providerIds } from '@wishforge/contracts/providers'; import { providerNames, RunTable, stages } from '@/components/run-table'; import { waitingGuide } from '@/lib/waiting'; import { browserId } from '@/lib/browser-id'; +import { credentialSourceLabel, initialWishProvider, wishProviderReady } from '@/lib/readiness'; export function RunsView() { const runs = useResource('/runs', 5000); @@ -156,15 +157,18 @@ export function NewWishView() { 'https://gitea.d-robotics.cc/longtao.wu/droboticflow.git', 'git@gitea.d-robotics.cc:longtao.wu/droboticflow.git', ].includes(project.repositoryUrl ?? ''); - const provider = - chosenProvider ?? - (localPoc && providers.data?.some(item => item.id === 'claude-code' && item.enabled) ? 'claude-code' : 'codex'); + const provider = chosenProvider ?? initialWishProvider(providers.data, Boolean(localPoc)); const maxTokens = chosenMaxTokens ?? (localPoc && provider === 'claude-code' ? 1000000 : 300000); const branches = useResource(effectiveProject ? `/projects/${effectiveProject}/branches` : null); const targetBranch = projects.data?.find(project => project.id === effectiveProject)?.targetBranch ?? 'main'; const selectedProvider = providers.data?.find(item => item.id === provider); + const providerReady = wishProviderReady(selectedProvider, providers.error, projects.error); async function submit(event: React.FormEvent) { event.preventDefault(); + if (!providerReady) { + setError('请先确认项目与执行器的最新可用状态。'); + return; + } setBusy(true); setError(''); try { @@ -267,7 +271,7 @@ export function NewWishView() { {providerIds.map(id => { const info = providers.data?.find(item => item.id === id); return ( - @@ -275,9 +279,26 @@ export function NewWishView() { })} - {selectedProvider && !selectedProvider.configured ? ( + {providers.error ? ( + void providers.mutate().catch(() => undefined)} + retrying={providers.isValidating} + /> + ) : providers.isLoading ? ( +

+ 正在读取执行器状态… +

+ ) : null} + {selectedProvider && !providers.error ? ( +

{credentialSourceLabel(selectedProvider.credentialSource)}

+ ) : null} + {!providers.error && !providers.isLoading && !selectedProvider ? ( + 尚未取得执行器状态,暂时无法提交。请在执行器页检查配置后重试。 + ) : null} + {selectedProvider && !selectedProvider.enabled && !providers.error ? ( - {selectedProvider.reason ?? '此执行器尚未连接凭据。提交后,后端会依据实际能力检查决定是否执行。'}{' '} + {selectedProvider.reason ?? '此执行器尚未就绪,请先完成配置后再提交愿望。'}{' '} 查看执行器 @@ -326,10 +347,16 @@ export function NewWishView() {
- {projects.error ? : null} + {projects.error ? ( + void projects.mutate().catch(() => undefined)} + retrying={projects.isValidating} + /> + ) : null}

提交后可在运行详情中补充信息、暂停或取消。

- diff --git a/apps/web/src/lib/readiness.test.ts b/apps/web/src/lib/readiness.test.ts new file mode 100644 index 0000000..12ee4dc --- /dev/null +++ b/apps/web/src/lib/readiness.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from 'vitest'; +import type { ProviderInfo } from './types'; +import { credentialSourceLabel, initialWishProvider, resourceState, wishProviderReady } from './readiness'; + +const codex: ProviderInfo = { + id: 'codex', + name: 'Codex', + configured: false, + enabled: false, + credentialSource: 'none', + capabilities: {}, +}; +const claude: ProviderInfo = { + id: 'claude-code', + name: 'Claude Code', + configured: true, + enabled: true, + credentialSource: 'native_account', + capabilities: {}, +}; + +describe('control-plane connection display', () => { + it('never treats cached data as proof of connectivity after failure', () => { + expect(resourceState(true, true, false)).toBe('stale'); + expect(resourceState(true, true, true)).toBe('stale'); + expect(resourceState(false, true, false)).toBe('unavailable'); + }); + it('distinguishes initial loading, background validation and confirmed data', () => { + expect(resourceState(false, false, true)).toBe('loading'); + expect(resourceState(true, false, true)).toBe('refreshing'); + expect(resourceState(true, false, false)).toBe('ready'); + }); +}); + +describe('new-wish executor selection and submission boundary', () => { + it('selects the available executor when the ordinary preferred Codex is unconfigured', () => { + expect(initialWishProvider([codex, claude], false)).toBe('claude-code'); + expect(initialWishProvider([claude, { ...codex, configured: true, enabled: true }], false)).toBe('codex'); + }); + it('prefers available native Claude for the POC but does not impose operator policy from a UI hint', () => { + expect(initialWishProvider([codex, claude], true)).toBe('claude-code'); + expect(initialWishProvider([{ ...codex, configured: true, enabled: true }], true)).toBe('codex'); + }); + it('blocks unknown, disabled or contradictory provider state', () => { + expect(wishProviderReady(undefined, undefined, undefined)).toBe(false); + expect(wishProviderReady(codex, undefined, undefined)).toBe(false); + expect(wishProviderReady({ ...claude, configured: false }, undefined, undefined)).toBe(false); + }); + it('blocks submission after a provider or project read fails even with cached ready metadata', () => { + expect(wishProviderReady(claude, new Error('offline'), undefined)).toBe(false); + expect(wishProviderReady(claude, undefined, new Error('forbidden'))).toBe(false); + expect(wishProviderReady(claude, undefined, undefined)).toBe(true); + }); +}); + +describe('credential source disclosure', () => { + it('does not turn mixed or missing metadata into a native/tenant authentication claim', () => { + expect(credentialSourceLabel('native_account')).toContain('本机 CLI'); + expect(credentialSourceLabel('native_account')).toContain('启动时验证'); + expect(credentialSourceLabel('mixed')).toContain('认证来源待确认'); + expect(credentialSourceLabel(undefined)).toContain('尚未确认'); + expect(credentialSourceLabel('tenant_credential')).toContain('租户 API Key'); + }); +}); diff --git a/apps/web/src/lib/readiness.ts b/apps/web/src/lib/readiness.ts new file mode 100644 index 0000000..76fb290 --- /dev/null +++ b/apps/web/src/lib/readiness.ts @@ -0,0 +1,36 @@ +import type { ProviderId, ProviderInfo } from './types'; + +export function resourceState(hasData: boolean, hasError: boolean, validating: boolean) { + if (hasError) return hasData ? 'stale' : 'unavailable'; + if (validating) return hasData ? 'refreshing' : 'loading'; + return hasData ? 'ready' : 'loading'; +} + +export function initialWishProvider(providers: ProviderInfo[] | undefined, localPoc: boolean): ProviderId { + // This hint chooses a default only; operator-bound execution policy lives in the API. + if (localPoc && providers?.some(provider => provider.id === 'claude-code' && provider.enabled)) return 'claude-code'; + return ( + providers?.find(provider => provider.id === 'codex' && provider.enabled)?.id ?? + providers?.find(provider => provider.enabled)?.id ?? + 'codex' + ); +} + +export function wishProviderReady(provider: ProviderInfo | undefined, providerError: unknown, projectError: unknown) { + return Boolean(provider?.configured && provider.enabled && !providerError && !projectError); +} + +export function credentialSourceLabel(source: ProviderInfo['credentialSource']) { + switch (source) { + case 'native_account': + return '本机 CLI 账号配置 · 启动时验证'; + case 'tenant_credential': + return '租户 API Key 配置 · 启动时验证'; + case 'mixed': + return '混合凭据配置 · 认证来源待确认'; + case 'none': + return '尚无可用凭据配置'; + default: + return '凭据来源尚未确认'; + } +} diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts index 5e55f88..20ae936 100644 --- a/apps/web/src/lib/types.ts +++ b/apps/web/src/lib/types.ts @@ -67,6 +67,7 @@ export type ProviderInfo = { configured: boolean; enabled: boolean; reason?: string; + credentialSource?: 'native_account' | 'tenant_credential' | 'mixed' | 'none'; capabilities: Record; }; export type Release = { diff --git a/apps/worker/src/executor.ts b/apps/worker/src/executor.ts index 0016e9d..010d22c 100644 --- a/apps/worker/src/executor.ts +++ b/apps/worker/src/executor.ts @@ -300,7 +300,10 @@ export async function executeRun(config: WorkerConfig, input: RunInput): Promise model: bundle.model, }); providerStarted = true; - if (keeper.error) abort(); + // Cancellation can arrive while start awaits filesystem/process preparation, + // before the abort listener knows there is a provider attempt to stop. + if (keeper.signal.aborted || keeper.error) abort(); + await keeper.ensure(); let summary: string | undefined; const finalUsage: Array<{ operationId: string; tokens: number }> = []; for await (const event of provider.events(input.runId)) { diff --git a/apps/worker/src/lease.ts b/apps/worker/src/lease.ts index 3aa7e3b..41b87cf 100644 --- a/apps/worker/src/lease.ts +++ b/apps/worker/src/lease.ts @@ -58,7 +58,12 @@ export class LeaseKeeper { } /** Fails fast once the lease is lost; call before every external side effect. */ async ensure() { + this.assertActive(); await this.beat(); + this.assertActive(); + } + private assertActive() { + if (this.signal.aborted && !this.failure) this.stop(new RuntimeError('CANCELED', 'Execution was canceled')); if (this.failure) throw this.failure; } close() { @@ -67,14 +72,15 @@ export class LeaseKeeper { private beat() { this.busy ??= (async () => { if (this.failure) return; - this.activity?.heartbeat({ runId: this.runId, leaseToken: this.token }); try { + this.assertActive(); + this.activity?.heartbeat({ runId: this.runId, leaseToken: this.token }); const run = await this.api.request(`/internal/runs/${this.runId}/heartbeat`, { leaseToken: this.token }); this.lastSuccess = Date.now(); if (run.status !== 'running') this.stop(new RunStopped(run)); } catch (error) { const rejected = error instanceof ControlPlaneError && !error.transient; - if (rejected || Date.now() - this.lastSuccess > GIVE_UP_MS) + if (this.signal.aborted || rejected || Date.now() - this.lastSuccess > GIVE_UP_MS) this.stop(error instanceof Error ? error : new Error('Lease heartbeat failed')); } })().finally(() => { diff --git a/apps/worker/test/cancellation.test.ts b/apps/worker/test/cancellation.test.ts new file mode 100644 index 0000000..8003532 --- /dev/null +++ b/apps/worker/test/cancellation.test.ts @@ -0,0 +1,137 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { Context } from '@temporalio/activity'; +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import type { Run } from '@wishforge/contracts'; +import type { ProviderAdapter } from '@wishforge/runtime'; +import { BASELINE_VERSION } from '@wishforge/agent'; +import { LeaseKeeper } from '../src/lease.js'; +import { executeRun } from '../src/executor.js'; +import type { RunContext } from '../src/common.js'; + +const directories: string[] = []; +afterEach(async () => { + vi.restoreAllMocks(); + await Promise.all(directories.splice(0).map(directory => rm(directory, { recursive: true, force: true }))); +}); +function activity(controller: AbortController) { + return { cancellationSignal: controller.signal, heartbeat: vi.fn() } as unknown as Context; +} +describe('execution cancellation at side-effect boundaries', () => { + it('rejects an already canceled activity before calling the control plane', async () => { + const controller = new AbortController(); + controller.abort(); + const request = vi.fn().mockResolvedValue({ status: 'running' }); + const keeper = new LeaseKeeper({ request }, 'run', 1, activity(controller)); + await expect(keeper.ensure()).rejects.toMatchObject({ code: 'CANCELED' }); + expect(request).not.toHaveBeenCalled(); + }); + it('rejects cancellation arriving during a successful lease heartbeat', async () => { + const controller = new AbortController(); + const request = vi.fn().mockImplementation(async () => { + controller.abort(); + return { status: 'running' }; + }); + const keeper = new LeaseKeeper({ request }, 'run', 1, activity(controller)); + await expect(keeper.ensure()).rejects.toMatchObject({ code: 'CANCELED' }); + }); + it('stops a provider canceled while start was in flight and retains its workspace', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'wishforge-cancel-start-')); + directories.push(directory); + const controller = new AbortController(); + vi.spyOn(Context, 'current').mockReturnValue(activity(controller)); + const at = new Date().toISOString(); + const run = { + id: 'run', + tenantId: 'tenant', + projectId: 'project', + stage: 'implement', + status: 'queued', + revision: 1, + repairCount: 0, + provider: 'claude-code', + bundleVersion: BASELINE_VERSION, + goal: 'Fixture only', + acceptanceCriteria: ['No model or network operations'], + executionGeneration: 'generation', + budget: { maxTokens: 1000, maxMinutes: 60, maxRepairRounds: 3 }, + } as Run; + const context: RunContext = { + run, + project: { + id: 'project', + tenantId: 'tenant', + version: 1, + createdAt: at, + updatedAt: at, + name: 'Cancellation fixture', + repositoryStorage: 'platform', + repositoryStatus: 'unconfigured', + autoDeploy: false, + targetBranch: 'main', + verificationCommands: [], + memberIds: [], + }, + }; + const cancel = vi.fn().mockResolvedValue(undefined), + events = vi.fn(async function* () {}); + const provider = { + capabilities: () => ({ provider: 'claude-code', availability: 'available', coding: true }), + start: vi.fn(async () => { + run.status = 'canceled'; + controller.abort(); + return { id: 'run', provider: 'claude-code', status: 'running' }; + }), + cancel, + events, + inspect: vi.fn(async () => ({ id: 'run', provider: 'claude-code', status: 'running' })), + exportCheckpoint: vi.fn(async () => { + throw new Error('Canceled work cannot export a completed checkpoint'); + }), + } as unknown as ProviderAdapter; + const fetcher: typeof fetch = async (url, init) => { + const route = new URL(String(url)).pathname, + body = init?.body ? JSON.parse(String(init.body)) : undefined; + if (route.endsWith('/lease')) { + run.status = 'running'; + run.lease = { token: 1, workerId: 'fixture', expiresAt: new Date(Date.now() + 60000).toISOString() }; + return Response.json({ data: run }); + } + if (route.endsWith('/transition')) { + run.stage = body.stage; + run.status = body.status; + return Response.json({ data: run }); + } + if (route.endsWith('/heartbeat') || route.endsWith('/lease/release')) return Response.json({ data: run }); + if (route.endsWith('/context')) return Response.json({ data: context }); + throw new Error(`Unexpected fixture request ${route}`); + }; + const outcome = await executeRun( + { + controlPlaneUrl: 'http://127.0.0.1:4000', + workerToken: 'fixture-token', + workerId: 'fixture', + workspaceRoot: directory, + isolatedProviderHomeRoot: directory, + sandboxMode: 'host', + sandboxRunId: 'run', + sandboxTenantId: 'tenant', + sandboxGeneration: 'generation', + providerFactory: () => provider, + fetcher, + execute: async command => ({ + exitCode: 0, + stdout: command.args.includes('rev-parse') ? 'a'.repeat(40) + '\n' : '', + stderr: '', + }), + }, + { tenantId: 'tenant', runId: 'run', generation: 'generation' }, + ); + expect(outcome).toEqual({ status: 'canceled' }); + expect(cancel).toHaveBeenCalledWith('run'); + expect(events).not.toHaveBeenCalled(); + expect(provider.exportCheckpoint).not.toHaveBeenCalled(); + expect(await readdir(path.join(directory, 'tenant'))).toContain('run-a1.recovery.json'); + }); +}); diff --git a/docs/local-browser-access.md b/docs/local-browser-access.md index e2f5e61..52167ae 100644 --- a/docs/local-browser-access.md +++ b/docs/local-browser-access.md @@ -17,10 +17,22 @@ WF_WEB_PORT=3000 WF_WEB_SERVE_MODE=production ``` -将示例地址替换为本机实际局域网地址。白名单必须是完整、精确的 HTTP(S) origin,不含路径或结尾斜杠。先执行 `npm run build -w @wishforge/web`,再执行 `npm run dev:all` 启动。`WF_WEB_SERVE_MODE=production` 使用构建好的 Next 应用,避免开发热更新影响持续运行;控制 API 和执行服务仍使用显式 development 配置。本机会话验证独立于 Node 的开发模式,生产 Web 不会放行匿名 dev token。 +将示例地址替换为本机实际局域网地址。白名单必须是完整、精确的 HTTP(S) origin,不含路径或结尾斜杠。先执行 `npm run local:build`,再执行 `npm run dev:all` 启动。构建脚本加载根目录本机配置,但只将 Web 所需变量传给 Next。`WF_WEB_SERVE_MODE=production` 使用构建好的 Next 应用,避免开发热更新影响持续运行;控制 API 和执行服务仍使用显式 development 配置。本机会话验证独立于 Node 的开发模式,生产 Web 不会放行匿名 dev token。 代码变更后先停止旧 Web,再重新构建和启动。环境变更后也需要重启 Web;已运行的进程不会自动继承新环境。直接运行 Next 时必须传入这些 `WF_LOCAL_*` 变量。省略 `WF_WEB_SERVE_MODE` 时保留原有开发服务器行为。 +### 切换局域网后恢复入口 + +IP 变化时,旧地址不可达,而新地址尚未获准会返回 `403`。使用以下命令查看本机地址、预览变更,再明确应用选择的地址: + +```sh +npm run local:network +npm run local:network -- --address 192.168.1.20 +npm run local:network -- --address 192.168.1.20 --apply +``` + +地址必须是当前网卡实际持有的 RFC1918 IPv4。工具只替换相同端口的旧 HTTP 局域网地址,保留回环及其他已有入口;不添加通配符,不修改登录凭据,不创建公网入口。默认只预览;`--apply` 将原配置备份到忽略提交的 `.wishforge/local-poc/network-backups/`,权限 `0600`,然后原子更新根目录 `.env.local`。其他配置保留不变。应用后重启服务,并用新地址登录、刷新项目列表验证。`npm run local:doctor` 可检查网络与服务状态,诊断不会自动授权新地址。 + 所有入口包括页面、API、事件流、IDE 启动、交付文件均经过本机会话检查。登录页、框架静态资源和站点图标允许未登录访问。`/api/session` 未登录返回 `401`,因此本机模式的启动探活使用 `/login`。 ## 登录与退出 diff --git a/docs/local-poc-operations.md b/docs/local-poc-operations.md index ce861fc..aed3fd4 100644 --- a/docs/local-poc-operations.md +++ b/docs/local-poc-operations.md @@ -8,6 +8,7 @@ ```sh node scripts/local-poc-service.mjs status +node scripts/local-poc-service.mjs doctor node scripts/local-poc-service.mjs install node scripts/local-poc-service.mjs stop node scripts/local-poc-service.mjs start @@ -32,7 +33,11 @@ node scripts/local-poc-service.mjs start 3. 确认 `WF_WEB_HOST=0.0.0.0`、`WF_LOCAL_ACCESS=true`,停止并重新启动后台服务。 4. 从另一台设备打开新地址并实际登录、刷新项目列表,确认网络和会话都可用。 -网页使用 `WF_WEB_SERVE_MODE=production` 时,修改 WishForge 网页源码后先在项目根运行 `node scripts/build-local-web.mjs`,再重启本机服务。此开关只决定 Next.js 使用预构建网页;控制面的本机运行模式仍为 `WF_DEPLOYMENT_MODE=development`。 +网页使用 `WF_WEB_SERVE_MODE=production` 时,先确认没有执行中的愿望或发布,再运行 `node scripts/local-poc-service.mjs stop`,随后运行 `node scripts/build-local-web.mjs`,最后运行 `node scripts/local-poc-service.mjs start`。构建工具在 LaunchAgent 已注册或网页端口仍有进程监听时会拒绝构建;它不依赖登录页是否返回 200 来判断端口是否占用。 + +离线构建前,工具将当前 `.next` 保存到私有 `.wishforge/local-poc/web-builds/previous-`。编译失败或产物不完整时自动还原上一版;成功时保留上一版并将路径写入 `.wishforge/local-poc/last-web-build.json`。若新版本上线后检查失败,先停止服务,再按回执中的确切路径还原上一版 `.next`;保留新版本目录供排查。这个备份只覆盖网页构建产物,服务端源码和数据库变化需要分别核对。构建锁位于 `.wishforge/local-poc/web-build.lock`;异常断电后先确认记录的构建进程已结束并检查备份,再处理残留锁。 + +`start` 和 `install` 会等待网页、API、数据库、provisioner、Git 服务及 Runner 就绪,最长约 90 秒;超时返回非零状态并输出具体诊断,已启动的进程继续保留以便排查。这个等待不代替登录后的业务验收。`WF_WEB_SERVE_MODE` 只决定 Next.js 使用预构建网页,控制面的本机运行模式仍为 `WF_DEPLOYMENT_MODE=development`。 ## 配置与日志 @@ -42,7 +47,11 @@ node scripts/local-poc-service.mjs start - `.wishforge/local-poc/logs/platform.log`、`runner.log`、`supervisor.log`:目录 0700、文件 0600。每个文件达到 5 MiB 时轮转,保留 3 个历史文件。 - `.wishforge/local-poc/service-state.json`:监督进程和直接子进程状态;`status` 以 launchd 实时状态为准,不用陈旧 PID 杀进程。 -`status` 只输出运行状态、PID 和日志位置,不显示任何凭据。排查时先看 `supervisor.log` 的启动/退出记录,再看对应服务日志。持续重启通常意味着依赖服务、构建产物、环境文件或权限未满足。请修复原因后再启动,不要复制完整环境文件到聊天或工单。 +`status` 只输出 launchd 进程状态、匹配当前 supervisor 的子进程 PID 和日志位置。`doctor` 进一步读取实际 HTTP 就绪状态及服务身份、网页构建产物、Runner 健康快照和 LAN 入口配置。Runner 必须是当前 supervisor 的存活子进程,且健康快照来自相同 PID、具有成功认证轮询证据,才会显示 `ready`;执行任务时显示 `busy`,旧版 Runner 没有快照时显示 `unverified`。快照每 10 秒更新到独立 Runner 状态目录的 `health.json`,不含参数、环境变量或任务内容;写快照失败不会取消部署。 + +LAN 检查默认排除 VPN 接口,只需要一个当前可用且已授权的地址。它还通过 loopback 请求携带该地址的 Host 头,检测“磁盘配置已更新,但旧网页进程仍拒绝新地址”的状态。此检查不会自动授权地址,也不证明其他设备已能通过路由和防火墙访问。`doctor` 只读取状态,不领取 Runner 任务,不调用模型或执行部署。 + +排查时先看 `supervisor.log` 的启动/退出记录,再看对应服务日志。持续重启通常意味着依赖服务、构建产物、环境文件或权限未满足。请修复原因后再启动,不要复制完整环境文件到聊天或工单。 ## 验证和电脑睡眠 diff --git a/package.json b/package.json index 8704443..af0400d 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,10 @@ "db:migrate": "tsx apps/api/src/db/migrate.ts", "db:seed": "tsx apps/api/src/db/seed.ts", "setup:local": "node scripts/setup-local.mjs", + "local:status": "node scripts/local-poc-service.mjs status", + "local:doctor": "node scripts/local-poc-service.mjs doctor", + "local:network": "node scripts/configure-local-network.mjs", + "local:build": "node scripts/build-local-web.mjs", "format": "prettier --write .", "format:check": "prettier --check .", "tenant:create": "tsx scripts/provision-tenant.ts" diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 394a1b3..0fff22e 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -289,6 +289,8 @@ export interface ProviderInfo { id: ProviderId; name: string; configured: boolean; + /** Configured authority only; account validity is checked when execution starts. */ + credentialSource: 'native_account' | 'tenant_credential' | 'mixed' | 'none'; enabled: boolean; reason: string; capabilities: Record; diff --git a/scripts/build-local-web.mjs b/scripts/build-local-web.mjs index b50cf6b..ba7e783 100644 --- a/scripts/build-local-web.mjs +++ b/scripts/build-local-web.mjs @@ -1,32 +1,56 @@ import { spawn } from 'node:child_process'; import { resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { environment, loadLocalEnvironment } from './local-services.mjs'; +import { buildWithRollback } from './local-web-build.mjs'; -loadLocalEnvironment(); -// Load env in this parent, not Node's --env-file argv: Next forwards execArgv to -// worker NODE_OPTIONS, where Node rejects --env-file. No database credentials go to Web. -const child = spawn(process.execPath, [resolve('node_modules/next/dist/bin/next'), 'build'], { - cwd: resolve('apps/web'), - env: environment( - [ - /^WF_LOCAL_ACCESS/, - /^WF_LOCAL_ALLOWED_ORIGINS$/, - /^WF_DEV_AUTH_TOKEN$/, - /^WF_SESSION_SECRET$/, - /^WF_PUBLIC_URL$/, - /^WF_API_URL$/, - /^WF_WEB_/, - /^WF_IDE_/, - /^OIDC_/, - ], - { NODE_ENV: 'production', NEXT_TELEMETRY_DISABLED: '1' }, - ), - stdio: 'inherit', -}); -child.on('error', error => { - console.error(error.message); - process.exitCode = 1; -}); -child.on('exit', code => { - process.exitCode = code ?? 1; -}); +export async function main() { + const root = fileURLToPath(new URL('..', import.meta.url)); + process.chdir(root); + loadLocalEnvironment(); + // Load env in this parent, not Node's --env-file argv: Next forwards execArgv to + // worker NODE_OPTIONS, where Node rejects --env-file. No database credentials go to Web. + const build = () => + new Promise((resolveBuild, reject) => { + const child = spawn(process.execPath, [resolve('node_modules/next/dist/bin/next'), 'build'], { + cwd: resolve('apps/web'), + env: environment( + [ + /^WF_LOCAL_ACCESS/, + /^WF_LOCAL_ALLOWED_ORIGINS$/, + /^WF_DEV_AUTH_TOKEN$/, + /^WF_SESSION_SECRET$/, + /^WF_PUBLIC_URL$/, + /^WF_API_URL$/, + /^WF_WEB_/, + /^WF_IDE_/, + /^OIDC_/, + ], + { NODE_ENV: 'production', NEXT_TELEMETRY_DISABLED: '1' }, + ), + stdio: 'inherit', + }); + const stop = () => child.kill('SIGTERM'); + process.once('SIGINT', stop); + process.once('SIGTERM', stop); + child.on('error', reject); + child.on('close', code => { + process.removeListener('SIGINT', stop); + process.removeListener('SIGTERM', stop); + code === 0 + ? resolveBuild() + : reject(new Error(`Web build failed (${code ?? 'signal'}); the previous build was restored when available`)); + }); + }); + const receipt = await buildWithRollback(root, build, { + port: Number(process.env.WF_WEB_PORT || 3000), + host: process.env.WF_WEB_HOST || '0.0.0.0', + }); + console.log(JSON.stringify(receipt, null, 2)); +} + +if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) + main().catch(error => { + console.error(error.message); + process.exitCode = 1; + }); diff --git a/scripts/configure-local-network.mjs b/scripts/configure-local-network.mjs new file mode 100644 index 0000000..f88a299 --- /dev/null +++ b/scripts/configure-local-network.mjs @@ -0,0 +1,141 @@ +#!/usr/bin/env node +import { constants } from 'node:fs'; +import { lstat, mkdir, open, readFile, rename, rm } from 'node:fs/promises'; +import { networkInterfaces } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import { isIP } from 'node:net'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { parseEnv } from 'node:util'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const KEY = 'WF_LOCAL_ALLOWED_ORIGINS'; + +export function isPrivateAddress(address) { + if (isIP(address) !== 4) return false; + const [a, b] = address.split('.').map(Number); + return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168); +} + +export function lanAddresses(interfaces = networkInterfaces()) { + return Object.entries(interfaces).flatMap(([name, entries]) => + (entries ?? []) + .filter(entry => !entry.internal && isPrivateAddress(entry.address)) + .map(entry => ({ interface: name, address: entry.address })), + ); +} + +/** Only an explicitly selected address already assigned to this machine may be added. */ +export function networkPlan(source, address, interfaces = networkInterfaces()) { + const env = parseEnv(source); + if (env.WF_LOCAL_ACCESS !== 'true' || env.WF_DEPLOYMENT_MODE !== 'development') + throw new Error('This command requires explicit local access in development mode.'); + if (!lanAddresses(interfaces).some(entry => entry.address === address)) + throw new Error('Select an RFC1918 IPv4 address currently assigned to this machine.'); + const port = Number(env.WF_WEB_PORT || 3000); + if (!Number.isSafeInteger(port) || port < 1 || port > 65535) throw new Error('Invalid local Web port.'); + const previous = (env[KEY] || '') + .split(',') + .map(value => value.trim()) + .filter(Boolean); + const origins = previous.map(value => { + const url = new URL(value); + if (!['http:', 'https:'].includes(url.protocol) || url.origin !== value || url.username || url.password) + throw new Error('Existing origins must be exact HTTP(S) origins; fix malformed entries first.'); + return url; + }); + const selected = new URL(`http://${address}:${port}`).origin; + const retained = origins + .filter(url => !(url.protocol === 'http:' && isPrivateAddress(url.hostname) && Number(url.port || 80) === port)) + .map(url => url.origin); + const next = [ + ...new Set([ + new URL(`http://localhost:${port}`).origin, + new URL(`http://127.0.0.1:${port}`).origin, + ...retained, + selected, + ]), + ]; + const pattern = /^(?:export\s+)?WF_LOCAL_ALLOWED_ORIGINS\s*=.*$/gm; + const matches = [...source.matchAll(pattern)]; + if (matches.length !== 1 || parseEnv(matches[0][0])[KEY] !== env[KEY]) + throw new Error('Expected one single-line WF_LOCAL_ALLOWED_ORIGINS assignment.'); + const updated = source.replace(pattern, `${KEY}=${next.join(',')}`); + return { + address, + url: selected, + previous, + origins: next, + removed: previous.filter(value => !next.includes(value)), + changed: updated !== source, + source: updated, + }; +} + +export async function configureNetwork({ root = ROOT, address, apply = false, interfaces = networkInterfaces() }) { + const file = path.join(root, '.env.local'); + const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW); + let source; + try { + const stat = await handle.stat(); + if (!stat.isFile() || stat.mode & 0o077 || stat.uid !== process.getuid()) + throw new Error('The local environment file must be operator-owned with mode 0600.'); + source = await handle.readFile('utf8'); + } finally { + await handle.close(); + } + const plan = networkPlan(source, address, interfaces); + const { source: updated, ...summary } = plan; + if (!apply || !plan.changed) return { ...summary, applied: false }; + const backups = path.join(root, '.wishforge/local-poc/network-backups'); + await mkdir(backups, { recursive: true, mode: 0o700 }); + const directory = await lstat(backups); + if (!directory.isDirectory() || directory.mode & 0o077 || directory.uid !== process.getuid()) + throw new Error('Network backups must be an operator-owned private directory.'); + const id = randomUUID(); + const backup = path.join(backups, `${id}.env`); + const temporary = path.join(root, `.env.network-${id}.local`); + const saved = await open(backup, 'wx', 0o600); + try { + await saved.writeFile(source); + } finally { + await saved.close(); + } + const next = await open(temporary, 'wx', 0o600); + try { + await next.writeFile(updated); + } finally { + await next.close(); + } + try { + const latest = await lstat(file); + if (!latest.isFile() || latest.isSymbolicLink() || (await readFile(file, 'utf8')) !== source) + throw new Error('Local configuration changed during update; no configuration was replaced.'); + await rename(temporary, file); + } finally { + await rm(temporary, { force: true }); + } + return { ...summary, applied: true, backup, restartRequired: true }; +} + +export async function main(args) { + if (!args.length) { + console.log( + JSON.stringify( + { addresses: lanAddresses(), usage: 'configure-local-network.mjs --address [--apply]' }, + null, + 2, + ), + ); + return; + } + if (args[0] !== '--address' || !args[1] || args.length > 3 || (args[2] && args[2] !== '--apply')) + throw new Error('Usage: configure-local-network.mjs --address [--apply]'); + console.log(JSON.stringify(await configureNetwork({ address: args[1], apply: args[2] === '--apply' }), null, 2)); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) + main(process.argv.slice(2)).catch(error => { + console.error(error.message); + process.exitCode = 1; + }); diff --git a/scripts/configure-local-network.test.mjs b/scripts/configure-local-network.test.mjs new file mode 100644 index 0000000..1c4b7d1 --- /dev/null +++ b/scripts/configure-local-network.test.mjs @@ -0,0 +1,67 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, writeFile, readFile, stat, rm, symlink } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { configureNetwork, networkPlan } from './configure-local-network.mjs'; + +const interfaces = { en0: [{ internal: false, family: 'IPv4', address: '192.168.6.207' }] }; +const source = [ + '# Private config stays private', + 'WF_DEPLOYMENT_MODE=development', + 'WF_LOCAL_ACCESS=true', + 'WF_WEB_PORT=3000', + 'WF_LOCAL_ALLOWED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000,http://172.20.10.5:3000,https://trusted.example', + 'OTHER_TEST_SECRET="fixture-kept-verbatim"', + '', +].join('\n'); + +test('network change replaces only prior same-port LAN origins and preserves unrelated configuration', () => { + const plan = networkPlan(source, '192.168.6.207', interfaces); + assert.deepEqual(plan.removed, ['http://172.20.10.5:3000']); + assert.deepEqual(plan.origins, [ + 'http://localhost:3000', + 'http://127.0.0.1:3000', + 'https://trusted.example', + 'http://192.168.6.207:3000', + ]); + assert.match(plan.source, /OTHER_TEST_SECRET="fixture-kept-verbatim"/); + assert.equal(networkPlan(plan.source, '192.168.6.207', interfaces).changed, false); +}); + +test('rejects unassigned or public addresses, disabled authentication, and duplicate/malformed origins', () => { + for (const address of ['192.168.6.208', '8.8.8.8', '0.0.0.0', '192.168.6.207:3000']) + assert.throws(() => networkPlan(source, address, interfaces)); + for (const invalid of [ + source.replace('WF_LOCAL_ACCESS=true', 'WF_LOCAL_ACCESS=false'), + source.replace('development', 'production'), + `${source}WF_LOCAL_ALLOWED_ORIGINS=http://localhost:3000\n`, + source.replace('https://trusted.example', 'https://user:password@trusted.example'), + ]) + assert.throws(() => networkPlan(invalid, '192.168.6.207', interfaces)); +}); + +test('preview does not write; apply backs up privately, preserves credentials, and is idempotent', async () => { + const root = await mkdtemp(path.join(tmpdir(), 'wishforge-network-')); + try { + const file = path.join(root, '.env.local'); + await writeFile(file, source, { mode: 0o600 }); + const options = { root, address: '192.168.6.207', interfaces }; + const preview = await configureNetwork(options); + assert.equal(preview.applied, false); + assert.equal(await readFile(file, 'utf8'), source); + assert.equal(JSON.stringify(preview).includes('fixture-kept-verbatim'), false); + const applied = await configureNetwork({ ...options, apply: true }); + assert.equal(applied.applied, true); + assert.equal(await readFile(applied.backup, 'utf8'), source); + assert.equal((await stat(applied.backup)).mode & 0o777, 0o600); + assert.equal((await stat(file)).mode & 0o777, 0o600); + assert.equal(await readFile(file, 'utf8'), networkPlan(source, options.address, interfaces).source); + assert.equal((await configureNetwork({ ...options, apply: true })).applied, false); + await rm(file); + await symlink(applied.backup, file); + await assert.rejects(configureNetwork({ ...options, apply: true })); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/scripts/local-poc-doctor.mjs b/scripts/local-poc-doctor.mjs new file mode 100644 index 0000000..8a206d3 --- /dev/null +++ b/scripts/local-poc-doctor.mjs @@ -0,0 +1,260 @@ +// Read-only diagnostics. Never poll /internal/runner/tasks: that endpoint claims deployment work. +import { readFile, stat } from 'node:fs/promises'; +import { networkInterfaces } from 'node:os'; +import path from 'node:path'; +import { parseEnv } from 'node:util'; +import { spawnSync } from 'node:child_process'; +import { setTimeout as delay } from 'node:timers/promises'; +import { request as httpRequest } from 'node:http'; +import { Readable } from 'node:stream'; + +export function checkRunnerHealth(health, pid, now = Date.now()) { + if (!pid) return { status: 'unavailable', reason: 'No matching live runner process' }; + if (!health || health.schemaVersion !== 1 || health.pid !== pid) + return { status: 'unverified', reason: 'No health snapshot for the current runner process' }; + const updated = Date.parse(health.updatedAt), + polled = Date.parse(health.lastPollSuccessAt); + if (!Number.isFinite(updated) || updated > now + 5000 || now - updated > 30000) + return { status: 'unavailable', reason: 'Runner health snapshot is stale' }; + if (health.status === 'poll_error') + return { status: 'unavailable', reason: 'Runner cannot complete authenticated polling' }; + if (health.status === 'task_error') + return { status: 'unavailable', reason: 'Runner task or receipt failed; reconciliation is required' }; + if (!Number.isFinite(polled) || polled > now + 5000) + return { status: 'unverified', reason: 'Runner has not completed authenticated polling yet' }; + if (health.status === 'executing') return { status: 'busy', lastPollSuccessAt: health.lastPollSuccessAt }; + if (health.status !== 'idle' || now - polled > 30000) + return { status: 'unavailable', reason: 'Runner has no recent successful authenticated poll' }; + return { status: 'ready', lastPollSuccessAt: health.lastPollSuccessAt }; +} + +export function checkLanOrigins(env, interfaces = networkInterfaces()) { + const port = String(env.WF_WEB_PORT || '3000'); + const binding = env.WF_WEB_HOST || '127.0.0.1'; + const addresses = [ + ...new Set( + Object.entries(interfaces) + .filter(([name]) => !/^(utun|tun|tap|wg|ppp|ipsec)/i.test(name)) + .flatMap(([, items]) => + (items ?? []) + .filter( + item => + !item.internal && + item.family === 'IPv4' && + /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(item.address), + ) + .map(item => item.address), + ), + ), + ] + .filter(address => ['0.0.0.0', '::'].includes(binding) || address === binding) + .sort(); + const allowed = (env.WF_LOCAL_ALLOWED_ORIGINS ?? '') + .split(',') + .map(item => item.trim()) + .filter(Boolean); + const origins = addresses.map(address => new URL(`http://${address}:${port}`).origin); + const missingOrigins = origins.filter(origin => !allowed.includes(origin)); + const approvedOrigins = origins.filter(origin => allowed.includes(origin)); + const bindsLan = !['127.0.0.1', 'localhost', '::1'].includes(env.WF_WEB_HOST || '127.0.0.1'); + return { + status: !bindsLan + ? 'loopback-only' + : approvedOrigins.length + ? 'configured' + : origins.length + ? 'mismatch' + : 'unverified', + currentOrigins: origins, + approvedOrigins, + missingOrigins, + note: 'VPN interfaces excluded; one approved current LAN address suffices. External reachability still requires a client check', + }; +} + +export function liveChildPids(supervisor, processList) { + const records = processList.split('\n').flatMap(line => { + const match = line.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/); + return match ? [{ pid: Number(match[1]), parent: Number(match[2]), command: match[3] }] : []; + }); + return Object.fromEntries( + ['platform', 'runner'].map(name => { + const recorded = supervisor.children?.find(child => child.name === name); + const expected = path.join( + supervisor.workspace, + name === 'platform' ? 'scripts/dev.mjs' : 'apps/runner/src/main.ts', + ); + const live = + supervisor.state === 'running' && + recorded && + records.some( + record => + record.pid === recorded.pid && record.parent === supervisor.pid && record.command.includes(expected), + ); + return [name, live ? recorded.pid : null]; + }), + ); +} + +async function bodyText(response) { + if (!response.body) return ''; + const reader = response.body.getReader(); + const chunks = []; + let bytes = 0; + try { + while (true) { + const next = await reader.read(); + if (next.done) break; + bytes += next.value.length; + if (bytes > 128 * 1024) throw new Error('Oversized health response'); + chunks.push(Buffer.from(next.value)); + } + return Buffer.concat(chunks).toString('utf8'); + } finally { + await reader.cancel().catch(() => undefined); + } +} + +export async function probeEndpoint(url, expected, fetcher = fetch, timeoutMs = 1500, headers = {}) { + try { + // Node's fetch replaces custom Host headers. Use the HTTP client for this local + // request so the diagnostic exercises the same origin check as a LAN browser. + const request = headers.Host && fetcher === fetch ? loopbackHostRequest : fetcher; + const response = await request(url, { redirect: 'manual', signal: AbortSignal.timeout(timeoutMs), headers }); + if (response.status !== 200) { + await response.body?.cancel().catch(() => undefined); + return { status: 'unavailable', httpStatus: response.status }; + } + const text = await bodyText(response); + const matches = + expected === 'web-login' + ? text.includes('WishForge') && text.includes('name="username"') + : Object.entries(expected).every(([key, value]) => JSON.parse(text)[key] === value); + return matches + ? { status: 'ready', httpStatus: 200 } + : { status: 'unavailable', reason: 'Response identity or readiness does not match' }; + } catch { + return { status: 'unavailable', reason: 'Request failed, timed out or returned an invalid health response' }; + } +} + +export function loopbackHostRequest(url, options) { + return new Promise((resolve, reject) => { + const target = new URL(url); + if (target.protocol !== 'http:' || target.hostname !== '127.0.0.1' || target.username || target.password) + return reject(new Error('LAN origin diagnostics only connect to the IPv4 loopback listener')); + const request = httpRequest( + target, + { method: 'GET', headers: options.headers, signal: options.signal }, + response => { + resolve(new Response(Readable.toWeb(response), { status: response.statusCode })); + }, + ); + request.once('error', reject); + request.end(); + }); +} + +export async function inspectLocalPoc({ + root, + supervisor, + env, + runnerEnv, + processList, + health, + interfaces, + fetcher = fetch, + now = Date.now(), +}) { + const port = Number(env.WF_WEB_PORT || 3000); + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid local web port'); + const children = liveChildPids(supervisor, processList); + const targets = { + web: [`http://127.0.0.1:${port}/login`, 'web-login'], + api: ['http://127.0.0.1:4000/health', { service: 'wishforge-control-plane', status: 'ok' }], + database: ['http://127.0.0.1:4000/readyz', { status: 'ready' }], + provisioner: ['http://127.0.0.1:4450/healthz', { service: 'wishforge-provisioner' }], + git: ['http://127.0.0.1:4504/health', { service: 'git-storage' }], + }; + const services = Object.fromEntries( + await Promise.all( + Object.entries(targets).map(async ([name, [url, expected]]) => [ + name, + await probeEndpoint(url, expected, fetcher), + ]), + ), + ); + const runner = checkRunnerHealth(health, children.runner, now); + let build = { status: 'not-required' }; + if (env.WF_WEB_SERVE_MODE === 'production') { + const buildId = await readFile(path.join(root, 'apps/web/.next/BUILD_ID'), 'utf8').catch(() => ''); + build = buildId.trim() + ? { status: 'ready', buildId: buildId.trim().slice(0, 200) } + : { status: 'unavailable', reason: 'No completed production web build' }; + } + const coreReady = + supervisor.state === 'running' && + Boolean(children.platform) && + Object.values(services).every(service => service.status === 'ready') && + build.status !== 'unavailable'; + const ready = coreReady && ['ready', 'busy'].includes(runner.status); + const lan = checkLanOrigins(env, interfaces); + if (lan.status === 'configured') { + lan.runtimeOrigin = lan.approvedOrigins[0]; + lan.runtime = await probeEndpoint(`http://127.0.0.1:${port}/login`, 'web-login', fetcher, 1500, { + Host: new URL(lan.runtimeOrigin).host, + }); + if (lan.runtime.status !== 'ready') lan.status = 'runtime-mismatch'; + } + return { + checkedAt: new Date(now).toISOString(), + ready, + status: ready ? (['mismatch', 'runtime-mismatch'].includes(lan.status) ? 'degraded' : 'ready') : 'not-ready', + supervisor, + children, + services, + runner, + build, + lan, + note: 'Read-only checks; no task is claimed and no model or deployment is started', + }; +} + +export async function localPocDoctor(root, supervisor, options = {}) { + const env = parseEnv(await readFile(path.join(root, '.env.local'), 'utf8')); + const runnerEnv = parseEnv(await readFile(path.join(root, '.wishforge/local-poc/runner.env'), 'utf8')); + let health; + if (path.isAbsolute(runnerEnv.WF_RUNNER_STATE_DIR || '')) { + const file = path.join(runnerEnv.WF_RUNNER_STATE_DIR, 'health.json'); + const info = await stat(file).catch(() => undefined); + if (info?.isFile() && info.size <= 4096 && info.uid === process.getuid() && !(info.mode & 0o077)) + health = await readFile(file, 'utf8') + .then(JSON.parse) + .catch(() => undefined); + } + const processes = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,command='], { encoding: 'utf8', timeout: 3000 }); + return inspectLocalPoc({ + root, + supervisor, + env, + runnerEnv, + health, + processList: processes.status === 0 ? processes.stdout : '', + ...options, + }); +} + +export async function waitForReadiness( + inspect, + { timeoutMs = 90000, intervalMs = 1000, now = Date.now, sleep = delay } = {}, +) { + const deadline = now() + timeoutMs; + let report; + do { + report = await inspect(); + if (report.ready) return report; + if (now() >= deadline) return report; + await sleep(Math.min(intervalMs, Math.max(0, deadline - now()))); + } while (now() <= deadline); + return report; +} diff --git a/scripts/local-poc-doctor.test.mjs b/scripts/local-poc-doctor.test.mjs new file mode 100644 index 0000000..fd08a6f --- /dev/null +++ b/scripts/local-poc-doctor.test.mjs @@ -0,0 +1,197 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { + checkLanOrigins, + checkRunnerHealth, + inspectLocalPoc, + liveChildPids, + probeEndpoint, + waitForReadiness, +} from './local-poc-doctor.mjs'; + +const now = Date.parse('2026-10-25T00:00:00Z'); +const recent = new Date(now - 1000).toISOString(); +const supervisor = { + state: 'running', + pid: 10, + workspace: '/owned/wishforge', + children: [ + { name: 'platform', pid: 11 }, + { name: 'runner', pid: 12 }, + ], +}; +const processList = + '11 10 node /owned/wishforge/scripts/dev.mjs\n12 10 node /owned/wishforge/apps/runner/src/main.ts\n'; +const health = { schemaVersion: 1, pid: 12, status: 'idle', updatedAt: recent, lastPollSuccessAt: recent }; +const interfaces = { en0: [{ family: 'IPv4', address: '192.168.6.207', internal: false }] }; +const healthyFetch = async url => { + if (url.endsWith('/login')) return new Response('WishForge'); + if (url.endsWith('/readyz')) return Response.json({ status: 'ready' }); + if (url.includes(':4000')) return Response.json({ status: 'ok', service: 'wishforge-control-plane' }); + if (url.includes(':4450')) return Response.json({ service: 'wishforge-provisioner' }); + return Response.json({ service: 'git-storage' }); +}; + +test('launchd running is insufficient when the API is unhealthy', async () => { + const report = await inspectLocalPoc({ + root: '/unused', + supervisor, + processList, + health, + env: {}, + interfaces: {}, + now, + fetcher: async url => (url.endsWith('/readyz') ? new Response('', { status: 503 }) : healthyFetch(url)), + }); + assert.equal(report.ready, false); + assert.equal(report.services.database.httpStatus, 503); +}); + +test('a correct body identity is required and redirects are not followed', async () => { + assert.equal( + ( + await probeEndpoint('http://localhost/health', { service: 'wishforge' }, async (_url, options) => { + assert.equal(options.redirect, 'manual'); + return Response.json({ service: 'other-process' }); + }) + ).status, + 'unavailable', + ); + assert.equal( + (await probeEndpoint('http://localhost/health', {}, async () => new Response('', { status: 302 }))).httpStatus, + 302, + ); +}); + +test('runner readiness requires a matching live process and successful recent authenticated polling', () => { + assert.equal(checkRunnerHealth(undefined, 12, now).status, 'unverified'); + assert.equal(checkRunnerHealth(health, null, now).status, 'unavailable'); + assert.equal(checkRunnerHealth(health, 99, now).status, 'unverified'); + assert.equal(checkRunnerHealth({ ...health, lastPollSuccessAt: undefined }, 12, now).status, 'unverified'); + assert.equal(checkRunnerHealth({ ...health, status: 'poll_error' }, 12, now).status, 'unavailable'); + assert.equal(checkRunnerHealth(health, 12, now + 60000).status, 'unavailable'); + assert.equal(checkRunnerHealth(health, 12, now).status, 'ready'); + assert.equal( + checkRunnerHealth( + { ...health, status: 'executing', lastPollSuccessAt: new Date(now - 600000).toISOString() }, + 12, + now, + ).status, + 'busy', + ); + assert.equal(liveChildPids(supervisor, processList.replace('12 10', '12 99')).runner, null); +}); + +test('reports the changed LAN origin without authorizing or sending requests to it', async () => { + const env = { + WF_WEB_HOST: '0.0.0.0', + WF_LOCAL_ALLOWED_ORIGINS: 'http://172.20.10.5:3000', + WF_DEV_AUTH_TOKEN: 'never-print-fixture', + }; + const lan = checkLanOrigins(env, interfaces); + assert.equal(lan.status, 'mismatch'); + assert.deepEqual(lan.missingOrigins, ['http://192.168.6.207:3000']); + const requests = []; + const report = await inspectLocalPoc({ + root: '/unused', + supervisor, + processList, + health, + env, + interfaces, + now, + fetcher: url => { + requests.push(url); + return healthyFetch(url); + }, + }); + assert.equal(report.status, 'degraded'); + assert.equal(report.ready, true); + assert.ok(requests.every(url => url.startsWith('http://127.0.0.1:'))); + assert.ok(!requests.some(url => url.includes('/runner/tasks'))); + assert.ok(!JSON.stringify(report).includes('never-print-fixture')); +}); + +test('readiness waits for evidence and returns the last diagnosis at a bounded deadline', async () => { + let time = 0, + calls = 0; + const ready = await waitForReadiness(async () => ({ ready: ++calls === 3 }), { + timeoutMs: 30, + intervalMs: 10, + now: () => time, + sleep: async ms => { + time += ms; + }, + }); + assert.equal(ready.ready, true); + assert.equal(time, 20); + const failed = await waitForReadiness(async () => ({ ready: false, reason: 'runner unavailable' }), { + timeoutMs: 30, + intervalMs: 10, + now: () => time, + sleep: async ms => { + time += ms; + }, + }); + assert.equal(failed.reason, 'runner unavailable'); + assert.equal(time, 50); +}); + +test('an approved current LAN interface is sufficient without approving VPN addresses', () => { + const env = { WF_WEB_HOST: '0.0.0.0', WF_LOCAL_ALLOWED_ORIGINS: 'http://192.168.6.207:3000' }; + const lan = checkLanOrigins(env, { + ...interfaces, + utun0: [{ family: 'IPv4', address: '10.251.1.1', internal: false }], + }); + assert.equal(lan.status, 'configured'); + assert.deepEqual(lan.currentOrigins, ['http://192.168.6.207:3000']); +}); + +test('detects runtime origin drift via a loopback request with the approved local Host', async () => { + const env = { WF_WEB_HOST: '0.0.0.0', WF_LOCAL_ALLOWED_ORIGINS: 'http://192.168.6.207:3000' }; + const calls = []; + const report = await inspectLocalPoc({ + root: '/unused', + supervisor, + processList, + health, + env, + interfaces, + now, + fetcher: (url, options) => { + calls.push({ url, host: options.headers?.Host }); + return options.headers?.Host ? new Response('Forbidden', { status: 403 }) : healthyFetch(url); + }, + }); + assert.equal(report.lan.status, 'runtime-mismatch'); + assert.equal(report.lan.runtime.httpStatus, 403); + assert.equal(report.status, 'degraded'); + assert.ok(calls.some(call => call.host === '192.168.6.207:3000')); + assert.ok(calls.every(call => call.url.startsWith('http://127.0.0.1:'))); +}); + +test('canonicalizes port 80 and respects an explicit interface binding', () => { + const env = { WF_WEB_HOST: '192.168.6.207', WF_WEB_PORT: '80', WF_LOCAL_ALLOWED_ORIGINS: 'http://192.168.6.207' }; + assert.equal(checkLanOrigins(env, interfaces).status, 'configured'); + assert.deepEqual(checkLanOrigins({ ...env, WF_WEB_HOST: '192.168.0.10' }, interfaces).approvedOrigins, []); +}); + +test('the real HTTP probe preserves Host, unlike Node fetch, and does not follow redirects', async () => { + const hosts = []; + const server = createServer((request, response) => { + hosts.push(request.headers.host); + response.writeHead(403); + response.end(); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const response = await probeEndpoint(`http://127.0.0.1:${server.address().port}/login`, 'web-login', fetch, 1000, { + Host: '192.168.6.207:3000', + }); + assert.equal(response.httpStatus, 403); + assert.deepEqual(hosts, ['192.168.6.207:3000']); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); diff --git a/scripts/local-poc-service.mjs b/scripts/local-poc-service.mjs index 92aac5d..41fd4e8 100644 --- a/scripts/local-poc-service.mjs +++ b/scripts/local-poc-service.mjs @@ -15,6 +15,7 @@ import { import { homedir } from 'node:os'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; +import { localPocDoctor, waitForReadiness } from './local-poc-doctor.mjs'; export const LABEL = 'cc.d-robotics.wishforge.local-poc'; export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); @@ -31,8 +32,8 @@ const MAX_LOG_BYTES = 5 * 1024 * 1024; export function parseServiceAction(argv) { if (!argv.length) return 'status'; - if (argv.length !== 1 || !['install', 'start', 'status', 'stop', 'run'].includes(argv[0])) - throw new Error('Usage: local-poc-service.mjs install|start|status|stop'); + if (argv.length !== 1 || !['install', 'start', 'status', 'doctor', 'stop', 'run'].includes(argv[0])) + throw new Error('Usage: local-poc-service.mjs install|start|status|doctor|stop'); return argv[0]; } @@ -96,6 +97,8 @@ function requirePrivateFile(file) { function preflight() { if (process.platform !== 'darwin') throw new Error('This service uses the macOS user LaunchAgent domain'); + if (existsSync(path.join(STATE_ROOT, 'web-build.lock'))) + throw new Error('A protected web build is in progress; finish or recover it before starting services'); for (const file of [NODE, SCRIPT, path.join(ROOT, 'scripts/dev.mjs'), path.join(ROOT, 'apps/runner/src/main.ts')]) if (!statSync(file).isFile()) throw new Error(`Missing required file: ${file}`); requirePrivateFile(path.join(ROOT, '.env.local')); @@ -128,6 +131,30 @@ function launchctl(args, checked = true) { } const registered = () => launchctl(['print', SERVICE], false).status === 0; +export function processStatus(result, state) { + const pid = result.status === 0 ? Number(result.stdout.match(/^\s*pid = (\d+)$/m)?.[1]) || null : null; + const current = Boolean(pid && state?.supervisorPid === pid); + return { + label: LABEL, + installed: existsSync(PLIST), + registered: result.status === 0, + state: result.status === 0 ? (result.stdout.match(/^\s*state = (.+)$/m)?.[1] ?? 'unknown') : 'stopped', + pid, + lastExitCode: result.stdout?.match(/^\s*last exit code = (.+)$/m)?.[1] ?? null, + workspace: ROOT, + logs: LOG_ROOT, + stateSnapshot: current ? 'current' : state ? 'stale' : 'absent', + children: + current && Array.isArray(state.children) + ? state.children + .filter( + child => ['platform', 'runner'].includes(child.name) && Number.isSafeInteger(child.pid) && child.pid > 0, + ) + .map(({ name, pid }) => ({ name, pid })) + : [], + }; +} + function status() { const result = launchctl(['print', SERVICE], false); let state = null; @@ -136,17 +163,7 @@ function status() { } catch { /* A stopped or never-started service has no state. */ } - return { - label: LABEL, - installed: existsSync(PLIST), - registered: result.status === 0, - state: result.status === 0 ? (result.stdout.match(/^\s*state = (.+)$/m)?.[1] ?? 'unknown') : 'stopped', - pid: result.status === 0 ? Number(result.stdout.match(/^\s*pid = (\d+)$/m)?.[1]) || null : null, - lastExitCode: result.stdout?.match(/^\s*last exit code = (.+)$/m)?.[1] ?? null, - workspace: ROOT, - logs: LOG_ROOT, - children: result.status === 0 ? (state?.children ?? []) : [], - }; + return processStatus(result, state); } async function supervise() { @@ -224,6 +241,11 @@ export async function main(argv = process.argv.slice(2)) { const action = parseServiceAction(argv); if (action === 'run') return supervise(); if (process.platform !== 'darwin') throw new Error('This service uses macOS launchd'); + if (action === 'doctor') { + const report = await localPocDoctor(ROOT, status()); + console.log(JSON.stringify(report, null, 2)); + return report.status === 'ready' ? 0 : 1; + } if (action === 'install') { preflight(); const content = launchAgentPlist(); @@ -254,6 +276,12 @@ export async function main(argv = process.argv.slice(2)) { launchctl(['disable', SERVICE]); if (registered()) launchctl(['bootout', SERVICE]); } + if (action === 'install' || action === 'start') { + const report = await waitForReadiness(() => localPocDoctor(ROOT, status())); + console.log(JSON.stringify(report, null, 2)); + // Local listeners alone are insufficient when the requested LAN entry is rejected. + return report.status === 'ready' ? 0 : 1; + } console.log(JSON.stringify(status(), null, 2)); return 0; } diff --git a/scripts/local-poc-service.test.mjs b/scripts/local-poc-service.test.mjs index 69a83cb..0b97d9c 100644 --- a/scripts/local-poc-service.test.mjs +++ b/scripts/local-poc-service.test.mjs @@ -4,7 +4,23 @@ import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync import { spawnSync } from 'node:child_process'; import os from 'node:os'; import path from 'node:path'; -import { LABEL, launchAgentPlist, minimalEnvironment, parseServiceAction, rotateAppend } from './local-poc-service.mjs'; +import { + LABEL, + launchAgentPlist, + minimalEnvironment, + parseServiceAction, + processStatus, + rotateAppend, +} from './local-poc-service.mjs'; + +test('a restarted supervisor must not report children retained from an older process', () => { + const report = processStatus( + { status: 0, stdout: 'state = running\n pid = 200\n' }, + { supervisorPid: 100, children: [{ name: 'runner', pid: 101 }] }, + ); + assert.deepEqual(report.children, []); + assert.equal(report.stateSnapshot, 'stale'); +}); test('defaults to read-only status and rejects arbitrary service commands', () => { assert.equal(parseServiceAction([]), 'status'); diff --git a/scripts/local-web-build.mjs b/scripts/local-web-build.mjs new file mode 100644 index 0000000..e8456ff --- /dev/null +++ b/scripts/local-web-build.mjs @@ -0,0 +1,113 @@ +import { spawnSync } from 'node:child_process'; +import { createConnection } from 'node:net'; +import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { randomUUID } from 'node:crypto'; +import path from 'node:path'; + +export function portOccupied(host, port, timeoutMs = 1000) { + return new Promise((resolve, reject) => { + const socket = createConnection({ host, port }); + const finish = (error, occupied) => { + socket.destroy(); + error ? reject(error) : resolve(occupied); + }; + socket.once('connect', () => finish(undefined, true)); + socket.once('error', error => + ['ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EAFNOSUPPORT'].includes(error.code) + ? finish(undefined, false) + : finish(new Error('Cannot establish whether the local web listener is stopped')), + ); + socket.setTimeout(timeoutMs, () => finish(new Error('Timed out checking the local web listener; build refused'))); + }); +} + +export async function assertWebOffline(port, host = '0.0.0.0') { + if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid local web port'); + if (process.platform === 'darwin') { + const registered = spawnSync( + '/bin/launchctl', + ['print', `gui/${process.getuid()}/cc.d-robotics.wishforge.local-poc`], + { encoding: 'utf8', timeout: 3000 }, + ); + if (registered.error) throw new Error('Cannot determine LaunchAgent state; build refused'); + if (registered.status === 0) + throw new Error('Stop the local POC LaunchAgent before rebuilding the web application'); + } + const addresses = [ + ...new Set(['127.0.0.1', '::1', ...(!['0.0.0.0', '::', 'localhost'].includes(host) ? [host] : [])]), + ]; + if ((await Promise.all(addresses.map(address => portOccupied(address, port)))).some(Boolean)) + throw new Error(`Port ${port} is still in use; stop the web process before rebuilding`); +} + +export async function buildWithRollback( + root, + build, + { port = 3000, host = '0.0.0.0', offline = assertWebOffline } = {}, +) { + await offline(port, host); + const state = path.join(root, '.wishforge/local-poc'); + await mkdir(state, { recursive: true, mode: 0o700 }); + const lock = path.join(state, 'web-build.lock'); + try { + await mkdir(lock, { mode: 0o700 }); + } catch (error) { + if (error.code === 'EEXIST') throw new Error('Another protected web build is in progress'); + throw error; + } + const current = path.join(root, 'apps/web/.next'); + const archive = path.join(state, 'web-builds'); + const id = randomUUID(); + const previous = path.join(archive, `previous-${id}`); + const failed = path.join(archive, `failed-${id}`); + let saved = false, + started = false; + try { + await writeFile( + path.join(lock, 'owner.json'), + JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }), + { mode: 0o600 }, + ); + await offline(port, host); + await mkdir(archive, { recursive: true, mode: 0o700 }); + if ( + await stat(current).then( + () => true, + error => { + if (error.code === 'ENOENT') return false; + throw error; + }, + ) + ) { + await rename(current, previous); + saved = true; + } + started = true; + await build(); + const buildId = (await readFile(path.join(current, 'BUILD_ID'), 'utf8')).trim(); + if (!buildId || !(await stat(path.join(current, 'server'))).isDirectory()) + throw new Error('Next did not produce a complete production web build'); + const receipt = { + buildId: buildId.slice(0, 200), + completedAt: new Date().toISOString(), + previousBuild: saved ? previous : null, + currentBuild: current, + }; + await writeFile(path.join(state, 'last-web-build.json'), `${JSON.stringify(receipt, null, 2)}\n`, { mode: 0o600 }); + return receipt; + } catch (error) { + if (started) { + if ( + await stat(current).then( + () => true, + () => false, + ) + ) + await rename(current, failed); + if (saved) await rename(previous, current); + } + throw error; + } finally { + await rm(lock, { recursive: true, force: true }); + } +} diff --git a/scripts/local-web-build.test.mjs b/scripts/local-web-build.test.mjs new file mode 100644 index 0000000..77dce20 --- /dev/null +++ b/scripts/local-web-build.test.mjs @@ -0,0 +1,98 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { buildWithRollback, portOccupied } from './local-web-build.mjs'; + +async function fixture() { + const root = await mkdtemp(path.join(os.tmpdir(), 'wishforge-web-build-')); + const current = path.join(root, 'apps/web/.next'); + await mkdir(path.join(current, 'server'), { recursive: true }); + await writeFile(path.join(current, 'BUILD_ID'), 'previous-build'); + return { root, current, cleanup: () => rm(root, { recursive: true, force: true }) }; +} +const offline = async () => undefined; + +test('an occupied port is detected without relying on HTTP auth or page status', async () => { + const server = createServer(socket => socket.end()); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + assert.equal(await portOccupied('127.0.0.1', server.address().port), true); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); + +test('refuses before touching the active build when offline checks fail', async () => { + const f = await fixture(); + try { + let called = false; + await assert.rejects( + buildWithRollback( + f.root, + async () => { + called = true; + }, + { + offline: async () => { + throw new Error('still listening'); + }, + }, + ), + /still listening/, + ); + assert.equal(called, false); + assert.equal(await readFile(path.join(f.current, 'BUILD_ID'), 'utf8'), 'previous-build'); + } finally { + await f.cleanup(); + } +}); + +test('a failed build restores the previous artifact and retains failure output in a private directory', async () => { + const f = await fixture(); + try { + await assert.rejects( + buildWithRollback( + f.root, + async () => { + await mkdir(f.current); + await writeFile(path.join(f.current, 'partial'), 'new incomplete output'); + throw new Error('compiler failed'); + }, + { offline }, + ), + /compiler failed/, + ); + assert.equal(await readFile(path.join(f.current, 'BUILD_ID'), 'utf8'), 'previous-build'); + const archive = path.join(f.root, '.wishforge/local-poc/web-builds'); + assert.equal((await stat(archive)).mode & 0o777, 0o700); + assert.equal((await readdir(archive)).filter(name => name.startsWith('failed-')).length, 1); + await assert.rejects(stat(path.join(f.root, '.wishforge/local-poc/web-build.lock')), { code: 'ENOENT' }); + } finally { + await f.cleanup(); + } +}); + +test('a successful build preserves the previous artifact and refuses concurrent builds', async () => { + const f = await fixture(); + try { + const result = await buildWithRollback( + f.root, + async () => { + await assert.rejects( + buildWithRollback(f.root, async () => {}, { offline }), + /Another protected web build/, + ); + await mkdir(path.join(f.current, 'server'), { recursive: true }); + await writeFile(path.join(f.current, 'BUILD_ID'), 'new-build'); + }, + { offline }, + ); + assert.equal(result.buildId, 'new-build'); + assert.equal(await readFile(path.join(result.previousBuild, 'BUILD_ID'), 'utf8'), 'previous-build'); + } finally { + await f.cleanup(); + } +}); diff --git a/tests/providers.test.ts b/tests/providers.test.ts index 2ccd342..fbb0275 100644 --- a/tests/providers.test.ts +++ b/tests/providers.test.ts @@ -103,10 +103,54 @@ describe('executor registry', () => { }); it('enables a CLI executor only where its executable is configured', async () => { const info = await availability({ WF_CLAUDE_BIN: '/usr/local/bin/claude' }); - expect(info['claude-code']).toMatchObject({ name: 'Claude Code', configured: true, enabled: true }); + expect(info['claude-code']).toMatchObject({ + name: 'Claude Code', + configured: true, + enabled: true, + credentialSource: 'tenant_credential', + }); expect(info.codebuddy).toMatchObject({ enabled: false, reason: expect.stringContaining('WF_CODEBUDDY_BIN') }); expect(info.codex).toMatchObject({ enabled: true }); }); + it('distinguishes native account configuration, missing credentials, and unresolved mixed authentication', async () => { + const store = new MemoryStore(); + store.seed('alpha'); + store.seed('beta'); + const env = { + ...base, + WF_DEPLOYMENT_MODE: 'development', + WF_PROVISIONER_BACKEND: 'local', + WF_TENANT_ID: 'alpha', + WF_CLAUDE_BIN: '/fixture/claude', + WF_CLAUDE_LOCAL_AUTH_HOME: '/fixture/operator', + }; + const control = new ControlPlane(store, env); + const claude = async (actor = owner) => (await control.providers(actor)).find(info => info.id === 'claude-code'); + expect(await claude()).toMatchObject({ credentialSource: 'native_account', configured: true, enabled: true }); + expect(await claude({ ...owner, tenantId: 'beta' })).toMatchObject({ + credentialSource: 'none', + configured: false, + enabled: false, + }); + await store.transaction('alpha', tx => + tx.put('provider_connection', { + id: 'claude-credential', + tenantId: 'alpha', + version: 1, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + provider: 'claude-code', + label: 'Fixture connection', + status: 'active', + }), + ); + expect(await claude()).toMatchObject({ + credentialSource: 'mixed', + configured: true, + reason: expect.stringContaining('precedence has not been verified'), + }); + expect(JSON.stringify(await claude())).not.toContain('/fixture/operator'); + }); it('runs in production only executors whose credentials the model proxy isolates', async () => { const info = await availability({ WF_DEPLOYMENT_MODE: 'production', WF_CLAUDE_BIN: '/usr/local/bin/claude' }); for (const id of providers.filter(id => !providerCatalog[id].proxied))