@zhushanwen/subagent-core 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +114 -0
- package/dist/chunk-3VOERJPJ.js +22 -0
- package/dist/chunk-A4IVZWVX.js +31 -0
- package/dist/execution/engine/engines/zcode/constants.cjs +54 -0
- package/dist/execution/engine/engines/zcode/constants.d.cts +31 -0
- package/dist/execution/engine/engines/zcode/constants.d.ts +31 -0
- package/dist/execution/engine/engines/zcode/constants.js +22 -0
- package/dist/execution/engine/engines/zcode/reader.cjs +276 -0
- package/dist/execution/engine/engines/zcode/reader.d.cts +20 -0
- package/dist/execution/engine/engines/zcode/reader.d.ts +20 -0
- package/dist/execution/engine/engines/zcode/reader.js +239 -0
- package/dist/execution/engine/paths.cjs +55 -0
- package/dist/execution/engine/paths.d.cts +8 -0
- package/dist/execution/engine/paths.d.ts +8 -0
- package/dist/execution/engine/paths.js +26 -0
- package/dist/execution/relay-env.cjs +62 -0
- package/dist/execution/relay-env.d.cts +33 -0
- package/dist/execution/relay-env.d.ts +33 -0
- package/dist/execution/relay-env.js +20 -0
- package/dist/index.cjs +1852 -0
- package/dist/index.d.cts +1184 -0
- package/dist/index.d.ts +1184 -0
- package/dist/index.js +1810 -0
- package/dist/types-BxyAidGf.d.cts +875 -0
- package/dist/types-BxyAidGf.d.ts +875 -0
- package/package.json +99 -0
- package/src/__tests__/agent-opts-resolver-schema-prompt.test.ts +142 -0
- package/src/__tests__/append-system-prompt-assembly.test.ts +242 -0
- package/src/__tests__/builtin-workflows-structure.test.ts +180 -0
- package/src/__tests__/derive-closed-display-parity.test.ts +93 -0
- package/src/__tests__/fr4-get-state-handshake.test.ts +125 -0
- package/src/__tests__/fr8-orphan-recovery.test.ts +259 -0
- package/src/__tests__/m2-append-content-probe.test.ts +73 -0
- package/src/__tests__/manifest-store.test.ts +368 -0
- package/src/__tests__/record-store-cache.test.ts +335 -0
- package/src/__tests__/record-store-index.test.ts +560 -0
- package/src/__tests__/record-store-last-line.test.ts +129 -0
- package/src/__tests__/review-fix-loop-script.test.ts +288 -0
- package/src/__tests__/review-fix-loop-utils.test.ts +2377 -0
- package/src/__tests__/robustness-low-batch1.test.ts +286 -0
- package/src/__tests__/robustness-medium-batch1.test.ts +69 -0
- package/src/__tests__/robustness-medium-batch2.test.ts +65 -0
- package/src/__tests__/robustness-medium-batch3.test.ts +30 -0
- package/src/__tests__/robustness-medium-batch4.test.ts +358 -0
- package/src/__tests__/session-runner.test.ts +69 -0
- package/src/__tests__/smoke.test.ts +9 -0
- package/src/__tests__/stream-sink.test.ts +203 -0
- package/src/core/__tests__/host-services.test.ts +144 -0
- package/src/core/__tests__/logger.test.ts +78 -0
- package/src/core/__tests__/notify-ports.test.ts +104 -0
- package/src/core/host-services.ts +97 -0
- package/src/core/logger.ts +47 -0
- package/src/core/notify-ports.ts +126 -0
- package/src/execution/__tests__/__fixtures__/notifier-golden-snapshots.json +53 -0
- package/src/execution/__tests__/__fixtures__/truncline.snapshot.json +1 -0
- package/src/execution/__tests__/agent-result-mapper.test.ts +150 -0
- package/src/execution/__tests__/alive-store.test.ts +147 -0
- package/src/execution/__tests__/ask-user-transit-e2e.test.ts +490 -0
- package/src/execution/__tests__/channel-registry-handshake.test.ts +242 -0
- package/src/execution/__tests__/chat-engine-routing.test.ts +610 -0
- package/src/execution/__tests__/chatmode-first-round-closure-spawn.test.ts +190 -0
- package/src/execution/__tests__/concurrency-pool.test.ts +250 -0
- package/src/execution/__tests__/config.test.ts +302 -0
- package/src/execution/__tests__/delivery-methods.test.ts +424 -0
- package/src/execution/__tests__/dialog-queue.test.ts +299 -0
- package/src/execution/__tests__/epipe-fallback.test.ts +241 -0
- package/src/execution/__tests__/execute-and-await-worktree.test.ts +243 -0
- package/src/execution/__tests__/execute-nesting.test.ts +323 -0
- package/src/execution/__tests__/execute-options-mapper.test.ts +200 -0
- package/src/execution/__tests__/execution-record.test.ts +1394 -0
- package/src/execution/__tests__/explicit-agent-ref-guard.test.ts +171 -0
- package/src/execution/__tests__/finalize-record.test.ts +367 -0
- package/src/execution/__tests__/finalized-marker.test.ts +104 -0
- package/src/execution/__tests__/format-schema-instruction.test.ts +169 -0
- package/src/execution/__tests__/gc-timer.test.ts +184 -0
- package/src/execution/__tests__/get-record-for-action-restart.test.ts +254 -0
- package/src/execution/__tests__/helpers/mock-extension-api.ts +30 -0
- package/src/execution/__tests__/helpers/spawn-mock.ts +242 -0
- package/src/execution/__tests__/host-mode.test.ts +87 -0
- package/src/execution/__tests__/lifecycle-manager-lock.test.ts +211 -0
- package/src/execution/__tests__/lifecycle-manager.test.ts +383 -0
- package/src/execution/__tests__/lifecycle-predicates.test.ts +116 -0
- package/src/execution/__tests__/manifest-parentid.test.ts +117 -0
- package/src/execution/__tests__/model-resolver.test.ts +465 -0
- package/src/execution/__tests__/nested-visibility-env-propagation.test.ts +287 -0
- package/src/execution/__tests__/nested-visibility.test.ts +325 -0
- package/src/execution/__tests__/output-collector.test.ts +358 -0
- package/src/execution/__tests__/path-encoding.test.ts +104 -0
- package/src/execution/__tests__/pi-invocation.test.ts +134 -0
- package/src/execution/__tests__/record-store.test.ts +1057 -0
- package/src/execution/__tests__/records-cwd-isolation.test.ts +91 -0
- package/src/execution/__tests__/recursive-visibility-baseline.test.ts +339 -0
- package/src/execution/__tests__/recursive-visibility-env.test.ts +273 -0
- package/src/execution/__tests__/relay-env.test.ts +42 -0
- package/src/execution/__tests__/resource-policy.test.ts +109 -0
- package/src/execution/__tests__/rpc-mode.test.ts +89 -0
- package/src/execution/__tests__/run-and-finalize-chatmode.test.ts +267 -0
- package/src/execution/__tests__/run-spawn-chatmode-settled.test.ts +253 -0
- package/src/execution/__tests__/run-spawn-edges.test.ts +687 -0
- package/src/execution/__tests__/run-spawn-integration.test.ts +933 -0
- package/src/execution/__tests__/run-spawn-resume.test.ts +322 -0
- package/src/execution/__tests__/run-spawn-rpc-mode.test.ts +196 -0
- package/src/execution/__tests__/run-spawn-stdout-callback-throw.test.ts +199 -0
- package/src/execution/__tests__/session-context-resolver.test.ts +167 -0
- package/src/execution/__tests__/session-file-gc.test.ts +293 -0
- package/src/execution/__tests__/session-reconstructor.test.ts +379 -0
- package/src/execution/__tests__/session-runner-epipe.test.ts +178 -0
- package/src/execution/__tests__/session-runner-schema-env.test.ts +350 -0
- package/src/execution/__tests__/spawn-args.test.ts +445 -0
- package/src/execution/__tests__/spawn-event-adapter-rpc.test.ts +189 -0
- package/src/execution/__tests__/spawn-event-adapter.test.ts +167 -0
- package/src/execution/__tests__/spawn-worktree-guidance.test.ts +207 -0
- package/src/execution/__tests__/spawned-children.test.ts +92 -0
- package/src/execution/__tests__/start-sync-model-guard.test.ts +150 -0
- package/src/execution/__tests__/stdin-writer.test.ts +462 -0
- package/src/execution/__tests__/stream-sink-retirement.test.ts +261 -0
- package/src/execution/__tests__/subagent-service-abort.test.ts +60 -0
- package/src/execution/__tests__/subagent-service-message-close.test.ts +629 -0
- package/src/execution/__tests__/subagent-service-parent-guard.test.ts +180 -0
- package/src/execution/__tests__/subagent-service.test.ts +788 -0
- package/src/execution/__tests__/subprocess-agent-runner-routing.test.ts +310 -0
- package/src/execution/__tests__/subprocess-agent-runner.test.ts +612 -0
- package/src/execution/__tests__/temp-prompt.test.ts +53 -0
- package/src/execution/__tests__/timeout-integration.test.ts +615 -0
- package/src/execution/__tests__/tombstone-store.test.ts +73 -0
- package/src/execution/__tests__/turn-limiter-semantics.test.ts +194 -0
- package/src/execution/__tests__/turn-limiter.test.ts +65 -0
- package/src/execution/__tests__/ui-channels.test.ts +187 -0
- package/src/execution/__tests__/ui-interaction-model.test.ts +67 -0
- package/src/execution/__tests__/ui-request-handler-factory.test.ts +369 -0
- package/src/execution/__tests__/ui-request-handler.test.ts +204 -0
- package/src/execution/__tests__/ui-request-observability.test.ts +113 -0
- package/src/execution/__tests__/ui-request-queue.test.ts +133 -0
- package/src/execution/__tests__/worktree-manager.test.ts +633 -0
- package/src/execution/__tests__/worktree-pid-registration.integration.test.ts +229 -0
- package/src/execution/__tests__/worktree-reconcile.integration.test.ts +181 -0
- package/src/execution/__tests__/worktree-registry.test.ts +199 -0
- package/src/execution/agent-registry.ts +199 -0
- package/src/execution/agent-result-mapper.ts +90 -0
- package/src/execution/alive-store.ts +119 -0
- package/src/execution/argv-mirror.ts +113 -0
- package/src/execution/best-effort.ts +38 -0
- package/src/execution/channel-registry-access.ts +144 -0
- package/src/execution/concurrency-pool.ts +116 -0
- package/src/execution/config.ts +165 -0
- package/src/execution/dialog-queue.ts +330 -0
- package/src/execution/engine/__tests__/common/data-dir.test.ts +78 -0
- package/src/execution/engine/__tests__/common/errors.test.ts +132 -0
- package/src/execution/engine/__tests__/common/event-journal.test.ts +177 -0
- package/src/execution/engine/__tests__/common/kill-chain.test.ts +192 -0
- package/src/execution/engine/__tests__/common/nesting-guard.test.ts +81 -0
- package/src/execution/engine/__tests__/common/persona-router.test.ts +123 -0
- package/src/execution/engine/__tests__/common/pool-manager.test.ts +154 -0
- package/src/execution/engine/__tests__/common/schema-emulation.test.ts +128 -0
- package/src/execution/engine/__tests__/conformance/__fixtures__/pi-golden-events.json +28 -0
- package/src/execution/engine/__tests__/conformance/agent-event-invariants.ts +141 -0
- package/src/execution/engine/__tests__/conformance/contract.abort.test.ts +109 -0
- package/src/execution/engine/__tests__/conformance/contract.agent-events.test.ts +101 -0
- package/src/execution/engine/__tests__/conformance/contract.probe.test.ts +77 -0
- package/src/execution/engine/__tests__/conformance/contract.read-degradation.test.ts +104 -0
- package/src/execution/engine/__tests__/conformance/engine-conformance.live.test.ts +201 -0
- package/src/execution/engine/__tests__/conformance/golden-replay.pi.test.ts +76 -0
- package/src/execution/engine/__tests__/conformance/golden-replay.zcode.test.ts +79 -0
- package/src/execution/engine/__tests__/engine-discovery.test.ts +87 -0
- package/src/execution/engine/__tests__/model-prompt.test.ts +197 -0
- package/src/execution/engine/__tests__/paths.test.ts +39 -0
- package/src/execution/engine/__tests__/registry.test.ts +120 -0
- package/src/execution/engine/__tests__/routing.test.ts +231 -0
- package/src/execution/engine/common/data-dir.ts +66 -0
- package/src/execution/engine/common/errors.ts +183 -0
- package/src/execution/engine/common/event-journal.ts +254 -0
- package/src/execution/engine/common/journal-replay.ts +62 -0
- package/src/execution/engine/common/kill-chain.ts +221 -0
- package/src/execution/engine/common/nesting-guard.ts +50 -0
- package/src/execution/engine/common/persona-router.ts +108 -0
- package/src/execution/engine/common/pool-manager.ts +226 -0
- package/src/execution/engine/common/schema-emulation.ts +189 -0
- package/src/execution/engine/common/session-view-projection.ts +51 -0
- package/src/execution/engine/engine-discovery.ts +65 -0
- package/src/execution/engine/engines/pi/__tests__/pi-engine.test.ts +469 -0
- package/src/execution/engine/engines/pi/__tests__/reader.test.ts +155 -0
- package/src/execution/engine/engines/pi/__tests__/task-spec-mapper.test.ts +164 -0
- package/src/execution/engine/engines/pi/pi-engine.ts +415 -0
- package/src/execution/engine/engines/pi/reader.ts +48 -0
- package/src/execution/engine/engines/pi/registration.ts +35 -0
- package/src/execution/engine/engines/pi/task-spec-mapper.ts +100 -0
- package/src/execution/engine/engines/zcode/__tests__/__fixtures__/zcode-golden-spawn.json +39 -0
- package/src/execution/engine/engines/zcode/__tests__/launcher.test.ts +150 -0
- package/src/execution/engine/engines/zcode/__tests__/parser.test.ts +246 -0
- package/src/execution/engine/engines/zcode/__tests__/preparer.test.ts +228 -0
- package/src/execution/engine/engines/zcode/__tests__/reader.test.ts +210 -0
- package/src/execution/engine/engines/zcode/__tests__/registration.test.ts +71 -0
- package/src/execution/engine/engines/zcode/__tests__/zcode-engine.live.test.ts +127 -0
- package/src/execution/engine/engines/zcode/__tests__/zcode-engine.test.ts +580 -0
- package/src/execution/engine/engines/zcode/constants.ts +43 -0
- package/src/execution/engine/engines/zcode/golden-sample.ts +39 -0
- package/src/execution/engine/engines/zcode/launcher.ts +161 -0
- package/src/execution/engine/engines/zcode/parser.ts +436 -0
- package/src/execution/engine/engines/zcode/preparer.ts +363 -0
- package/src/execution/engine/engines/zcode/reader.ts +381 -0
- package/src/execution/engine/engines/zcode/registration.ts +37 -0
- package/src/execution/engine/engines/zcode/zcode-engine.ts +658 -0
- package/src/execution/engine/host-task-spec.ts +47 -0
- package/src/execution/engine/model-prompt.ts +158 -0
- package/src/execution/engine/paths.ts +42 -0
- package/src/execution/engine/port.ts +153 -0
- package/src/execution/engine/registry.ts +133 -0
- package/src/execution/engine/routing.ts +218 -0
- package/src/execution/engine/types.ts +309 -0
- package/src/execution/execute-options-mapper.ts +115 -0
- package/src/execution/execution-record.ts +984 -0
- package/src/execution/finalize-record.ts +254 -0
- package/src/execution/finalized-marker.ts +70 -0
- package/src/execution/get-state-handshake.ts +104 -0
- package/src/execution/host-mode.ts +56 -0
- package/src/execution/idle-gc.ts +47 -0
- package/src/execution/lifecycle-manager.ts +513 -0
- package/src/execution/lifecycle-predicates.ts +65 -0
- package/src/execution/manifest-store.ts +256 -0
- package/src/execution/model-config-service.ts +250 -0
- package/src/execution/model-resolver.ts +248 -0
- package/src/execution/notifier.ts +372 -0
- package/src/execution/notify-ledger.ts +580 -0
- package/src/execution/output-collector.ts +228 -0
- package/src/execution/path-encoding.ts +60 -0
- package/src/execution/pi-invocation.ts +120 -0
- package/src/execution/record-entry.ts +132 -0
- package/src/execution/record-store.ts +1265 -0
- package/src/execution/relay-env.ts +37 -0
- package/src/execution/session-context-resolver.ts +64 -0
- package/src/execution/session-file-gc.ts +120 -0
- package/src/execution/session-pending.ts +170 -0
- package/src/execution/session-reconstructor.ts +678 -0
- package/src/execution/session-runner.ts +1789 -0
- package/src/execution/sessions-index.ts +304 -0
- package/src/execution/spawn-event-adapter.ts +363 -0
- package/src/execution/stdin-writer.ts +198 -0
- package/src/execution/stream-sink.ts +126 -0
- package/src/execution/subagent-service.ts +2268 -0
- package/src/execution/subprocess-agent-runner.ts +317 -0
- package/src/execution/temp-prompt.ts +62 -0
- package/src/execution/tombstone-store.ts +72 -0
- package/src/execution/turn-limiter.ts +102 -0
- package/src/execution/types.ts +1023 -0
- package/src/execution/ui-channels.ts +216 -0
- package/src/execution/ui-interaction-model.ts +48 -0
- package/src/execution/ui-request-handler-factory.ts +243 -0
- package/src/execution/ui-request-observability.ts +81 -0
- package/src/execution/ui-request-queue.ts +184 -0
- package/src/execution/worktree-manager.ts +688 -0
- package/src/execution/worktree-registry.ts +279 -0
- package/src/index.ts +87 -0
- package/src/orchestration/__tests__/__fixtures__/worker-template.snapshot.txt +349 -0
- package/src/orchestration/__tests__/agent-call-catch-fallback.test.ts +202 -0
- package/src/orchestration/__tests__/agent-call-stream.test.ts +152 -0
- package/src/orchestration/__tests__/args-validator.test.ts +143 -0
- package/src/orchestration/__tests__/config-loader.test.ts +503 -0
- package/src/orchestration/__tests__/error-recovery-handlers.test.ts +809 -0
- package/src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts +404 -0
- package/src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts +56 -0
- package/src/orchestration/__tests__/error-recovery-workflow-call.test.ts +166 -0
- package/src/orchestration/__tests__/execute-agent-call.test.ts +451 -0
- package/src/orchestration/__tests__/launcher-nested-workflow.test.ts +600 -0
- package/src/orchestration/__tests__/lifecycle-runid-injection.test.ts +96 -0
- package/src/orchestration/__tests__/lifecycle.test.ts +659 -0
- package/src/orchestration/__tests__/non-cloneable-return-e2e.test.ts +95 -0
- package/src/orchestration/__tests__/review-fix-loop-scriptpath-failfast.test.ts +183 -0
- package/src/orchestration/__tests__/script-lint.test.ts +831 -0
- package/src/orchestration/__tests__/skill-discovery.test.ts +210 -0
- package/src/orchestration/__tests__/test-mocks.ts +197 -0
- package/src/orchestration/__tests__/worker-exit-without-result.test.ts +368 -0
- package/src/orchestration/__tests__/worker-host.test.ts +120 -0
- package/src/orchestration/__tests__/worker-returnmeta-passthrough.test.ts +164 -0
- package/src/orchestration/__tests__/worker-script-builder-runtime.test.ts +563 -0
- package/src/orchestration/__tests__/worker-script-builder.test.ts +309 -0
- package/src/orchestration/__tests__/worker-script-template-snapshot.test.ts +129 -0
- package/src/orchestration/__tests__/workflow-nesting-e2e.test.ts +317 -0
- package/src/orchestration/__tests__/workflow-script-lint-memo.test.ts +110 -0
- package/src/orchestration/agent-opts-resolver.ts +174 -0
- package/src/orchestration/args-validator.ts +127 -0
- package/src/orchestration/config-loader.ts +316 -0
- package/src/orchestration/error-recovery.ts +1018 -0
- package/src/orchestration/execute-agent-call.ts +256 -0
- package/src/orchestration/launcher.ts +455 -0
- package/src/orchestration/lifecycle.ts +399 -0
- package/src/orchestration/models/__tests__/budget.test.ts +307 -0
- package/src/orchestration/models/agent-call.ts +83 -0
- package/src/orchestration/models/budget.ts +118 -0
- package/src/orchestration/models/ports.ts +164 -0
- package/src/orchestration/models/run-runtime.ts +104 -0
- package/src/orchestration/models/run-spec.ts +83 -0
- package/src/orchestration/models/run-state.ts +44 -0
- package/src/orchestration/models/trace.ts +183 -0
- package/src/orchestration/models/types.ts +301 -0
- package/src/orchestration/models/workflow-run.ts +254 -0
- package/src/orchestration/models/workflow-script-registry.ts +35 -0
- package/src/orchestration/models/workflow-script.ts +117 -0
- package/src/orchestration/script-lint.ts +766 -0
- package/src/orchestration/skill-discovery.ts +135 -0
- package/src/orchestration/worker-handle.ts +115 -0
- package/src/orchestration/worker-host.ts +98 -0
- package/src/orchestration/worker-script-builder.ts +421 -0
- package/src/orchestration/workflow-files.ts +85 -0
- package/src/orchestration/workflow-script-registry-impl.ts +133 -0
- package/src/shared/__tests__/agent-ref.test.ts +34 -0
- package/src/shared/__tests__/meta-parser.test.ts +304 -0
- package/src/shared/__tests__/model-ref.test.ts +306 -0
- package/src/shared/__tests__/resource-discovery-manifest-cache.test.ts +288 -0
- package/src/shared/__tests__/resource-discovery.test.ts +749 -0
- package/src/shared/__tests__/resource-meta.test.ts +51 -0
- package/src/shared/__tests__/schema-jsonify.test.ts +81 -0
- package/src/shared/__tests__/timer-delay.test.ts +61 -0
- package/src/shared/agent-event.ts +13 -0
- package/src/shared/agent-ref.ts +57 -0
- package/src/shared/meta-parser.ts +261 -0
- package/src/shared/model-ref.ts +286 -0
- package/src/shared/resource-discovery.ts +835 -0
- package/src/shared/resource-meta.ts +65 -0
- package/src/shared/schema-env.ts +44 -0
- package/src/shared/schema-jsonify.ts +58 -0
- package/src/shared/timer-delay.ts +54 -0
- package/src/shared/xml-injection.ts +35 -0
- package/workflows/README.md +81 -0
- package/workflows/_shared/agent-refs.cjs +40 -0
- package/workflows/chain.js +137 -0
- package/workflows/map-reduce.js +180 -0
- package/workflows/parallel.js +154 -0
- package/workflows/review-fix-loop-utils.cjs +1542 -0
- package/workflows/review-fix-loop.js +1605 -0
- package/workflows/scatter-gather.js +184 -0
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
// src/orchestration/__tests__/error-recovery-postmessage-defense.test.ts
|
|
2
|
+
//
|
|
3
|
+
// W2: 主线程层 postMessage 防御测试。
|
|
4
|
+
//
|
|
5
|
+
// 背景:主线程有 3 处 run.runtime?.worker.postMessage(...) 调用(经 helper 函数),
|
|
6
|
+
// 全部没有 try/catch。若 result 对象含不可克隆成员(function/Symbol/循环引用),
|
|
7
|
+
// postMessage 同步抛 DataCloneError:
|
|
8
|
+
// - postAgentResult:result 是 agent 返回值,不可克隆概率最高。DataCloneError 冒泡到
|
|
9
|
+
// dispatchAgentCall 的 .then 回调,中断后续 postBudgetUpdate/store.save/budget 检查,
|
|
10
|
+
// run 卡在 running。
|
|
11
|
+
// - postBudgetUpdate:payload 是 number,风险低但无兜底。
|
|
12
|
+
// - dispatchWorkflowCall 的 postResult:result 是子 workflow 任意返回值。
|
|
13
|
+
//
|
|
14
|
+
// 修复后三处均包 try/catch + fallback。本测试通过 mock worker.postMessage 抛
|
|
15
|
+
// DataCloneError,验证:
|
|
16
|
+
// 1. 调用方不抛错(流程不中断)
|
|
17
|
+
// 2. fallback result(纯字符串,必可克隆)被发送
|
|
18
|
+
// 3. console.error 记录诊断
|
|
19
|
+
|
|
20
|
+
import { readFileSync } from "node:fs";
|
|
21
|
+
import { dirname, join } from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
|
|
24
|
+
import { describe, expect, it, vi } from "vitest";
|
|
25
|
+
|
|
26
|
+
// Mock 共享 logger,让 logger.error 可被 spy(源码已从 console.error 改为 logger.error)
|
|
27
|
+
const { loggerMock } = vi.hoisted(() => ({
|
|
28
|
+
loggerMock: {
|
|
29
|
+
debug: vi.fn(),
|
|
30
|
+
warn: vi.fn(),
|
|
31
|
+
error: vi.fn(),
|
|
32
|
+
},
|
|
33
|
+
}));
|
|
34
|
+
vi.mock("../../core/logger.ts", () => ({
|
|
35
|
+
getLogger: () => loggerMock,
|
|
36
|
+
}));
|
|
37
|
+
|
|
38
|
+
import { handleWorkerMessage, postBudgetUpdate } from "../error-recovery.ts";
|
|
39
|
+
import type { LifecycleDeps, WorkerHandlers } from "../models/ports.ts";
|
|
40
|
+
import type { WorkflowRun } from "../models/workflow-run.ts";
|
|
41
|
+
|
|
42
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
43
|
+
const ERROR_RECOVERY_SRC = readFileSync(
|
|
44
|
+
join(__dirname, "../error-recovery.ts"),
|
|
45
|
+
"utf-8",
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
// ── helpers ──────────────────────────────────────────────────
|
|
49
|
+
|
|
50
|
+
/** flush microtask 队列,让 void .then().catch() 链路跑完。 */
|
|
51
|
+
async function flushMicrotasks(): Promise<void> {
|
|
52
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 构造一个 postMessage mock:前 n 次抛 DataCloneError,之后正常(模拟 fallback 成功)。 */
|
|
56
|
+
function makeFailingPostMessage(failTimes: number): ReturnType<typeof vi.fn> {
|
|
57
|
+
let calls = 0;
|
|
58
|
+
return vi.fn(() => {
|
|
59
|
+
calls += 1;
|
|
60
|
+
if (calls <= failTimes) {
|
|
61
|
+
const err = new Error("Could not clone object: function found");
|
|
62
|
+
err.name = "DataCloneError";
|
|
63
|
+
throw err;
|
|
64
|
+
}
|
|
65
|
+
// fallback 成功路径:no-op
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 构造一个永远抛 DataCloneError 的 postMessage mock(fallback 也失败)。 */
|
|
70
|
+
function makeAlwaysFailingPostMessage(): ReturnType<typeof vi.fn> {
|
|
71
|
+
return vi.fn(() => {
|
|
72
|
+
const err = new Error("Could not clone object");
|
|
73
|
+
err.name = "DataCloneError";
|
|
74
|
+
throw err;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 构造 status="running" 的 mock WorkflowRun,postMessage 由调用方注入。 */
|
|
79
|
+
function makeRunningRun(postMessage: ReturnType<typeof vi.fn>): WorkflowRun {
|
|
80
|
+
return {
|
|
81
|
+
state: { status: "running" },
|
|
82
|
+
runtime: { worker: { postMessage } },
|
|
83
|
+
} as unknown as WorkflowRun;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** LifecycleDeps 只需 onWorkflowCall(dispatchWorkflowCall 唯一消费的 dep)。 */
|
|
87
|
+
function makeDeps(onWorkflowCall?: LifecycleDeps["onWorkflowCall"]): LifecycleDeps {
|
|
88
|
+
return { onWorkflowCall } as unknown as LifecycleDeps;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** WorkerHandlers 占位(workflow-call 路径不触发 handler 回调)。 */
|
|
92
|
+
function makeHandlers(): WorkerHandlers {
|
|
93
|
+
return {
|
|
94
|
+
onMessage: vi.fn(async () => {}),
|
|
95
|
+
onError: vi.fn(async () => {}),
|
|
96
|
+
onExit: vi.fn(async () => {}),
|
|
97
|
+
} as unknown as WorkerHandlers;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
interface PostedMsg {
|
|
101
|
+
type: string;
|
|
102
|
+
callId?: number;
|
|
103
|
+
result?: { content: string; error?: string };
|
|
104
|
+
budget?: { usedTokens: number; usedCost: number };
|
|
105
|
+
cached?: boolean;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 从 postMessage mock 取第 idx 次调用的第 0 参。 */
|
|
109
|
+
function postedAt(postMessage: ReturnType<typeof vi.fn>, idx: number): PostedMsg {
|
|
110
|
+
return postMessage.mock.calls[idx]![0] as PostedMsg;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 清空 logger.error 调用记录(防御路径会打印诊断,避免污染跨用例断言)。 */
|
|
114
|
+
function silenceConsoleError(): () => void {
|
|
115
|
+
loggerMock.error.mockClear();
|
|
116
|
+
return () => {
|
|
117
|
+
loggerMock.error.mockClear();
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ── W2a: postBudgetUpdate try/catch ──
|
|
122
|
+
|
|
123
|
+
describe("W2a: postBudgetUpdate 防御 DataCloneError", () => {
|
|
124
|
+
it("postMessage 抛错时不向上传播(流程不中断)", () => {
|
|
125
|
+
const restore = silenceConsoleError();
|
|
126
|
+
try {
|
|
127
|
+
const postMessage = makeAlwaysFailingPostMessage();
|
|
128
|
+
const run = {
|
|
129
|
+
state: {
|
|
130
|
+
status: "running",
|
|
131
|
+
budget: { usedTokens: 42, usedCost: 0.5 },
|
|
132
|
+
},
|
|
133
|
+
runtime: { worker: { postMessage } },
|
|
134
|
+
} as unknown as WorkflowRun;
|
|
135
|
+
|
|
136
|
+
// 不应抛错——防御性兜底
|
|
137
|
+
expect(() => postBudgetUpdate(run)).not.toThrow();
|
|
138
|
+
} finally {
|
|
139
|
+
restore();
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("postMessage 失败时记录 console.error 诊断", () => {
|
|
144
|
+
const restore = silenceConsoleError();
|
|
145
|
+
try {
|
|
146
|
+
const postMessage = makeAlwaysFailingPostMessage();
|
|
147
|
+
const run = {
|
|
148
|
+
state: {
|
|
149
|
+
status: "running",
|
|
150
|
+
budget: { usedTokens: 42, usedCost: 0.5 },
|
|
151
|
+
},
|
|
152
|
+
runtime: { worker: { postMessage } },
|
|
153
|
+
} as unknown as WorkflowRun;
|
|
154
|
+
|
|
155
|
+
postBudgetUpdate(run);
|
|
156
|
+
|
|
157
|
+
expect(loggerMock.error).toHaveBeenCalledTimes(1);
|
|
158
|
+
const diag = loggerMock.error.mock.calls[0]![0] as string;
|
|
159
|
+
expect(diag).toContain("postBudgetUpdate failed");
|
|
160
|
+
expect(diag).toContain("Could not clone object");
|
|
161
|
+
} finally {
|
|
162
|
+
restore();
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("正常 payload(纯 number)成功发送", () => {
|
|
167
|
+
const postMessage = vi.fn();
|
|
168
|
+
const run = {
|
|
169
|
+
state: {
|
|
170
|
+
status: "running",
|
|
171
|
+
budget: { usedTokens: 42, usedCost: 0.5 },
|
|
172
|
+
},
|
|
173
|
+
runtime: { worker: { postMessage } },
|
|
174
|
+
} as unknown as WorkflowRun;
|
|
175
|
+
|
|
176
|
+
postBudgetUpdate(run);
|
|
177
|
+
|
|
178
|
+
expect(postMessage).toHaveBeenCalledTimes(1);
|
|
179
|
+
expect(postedAt(postMessage, 0)).toEqual({
|
|
180
|
+
type: "budget-update",
|
|
181
|
+
budget: { usedTokens: 42, usedCost: 0.5 },
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
// ── W2b: dispatchWorkflowCall postResult 闭包防御 ──
|
|
187
|
+
|
|
188
|
+
describe("W2b: dispatchWorkflowCall postResult 防御 DataCloneError", () => {
|
|
189
|
+
it("result 不可克隆 → 回发纯字符串 fallback result", async () => {
|
|
190
|
+
const restore = silenceConsoleError();
|
|
191
|
+
try {
|
|
192
|
+
// 第 1 次 postMessage 抛 DataCloneError(原始 result 不可克隆),
|
|
193
|
+
// 第 2 次(fallback)成功。
|
|
194
|
+
const postMessage = makeFailingPostMessage(1);
|
|
195
|
+
const onWorkflowCall = vi.fn(async () => ({ nonCloneable: () => {} }));
|
|
196
|
+
const run = makeRunningRun(postMessage);
|
|
197
|
+
const deps = makeDeps(onWorkflowCall);
|
|
198
|
+
|
|
199
|
+
await handleWorkerMessage(
|
|
200
|
+
run,
|
|
201
|
+
{ type: "workflow-call", callId: 9, name: "sub", args: {} },
|
|
202
|
+
deps,
|
|
203
|
+
makeHandlers(),
|
|
204
|
+
);
|
|
205
|
+
await flushMicrotasks();
|
|
206
|
+
|
|
207
|
+
// 调用两次:1 原始(失败)+ 1 fallback(成功)
|
|
208
|
+
expect(postMessage).toHaveBeenCalledTimes(2);
|
|
209
|
+
const fallback = postedAt(postMessage, 1);
|
|
210
|
+
expect(fallback.type).toBe("workflow-result");
|
|
211
|
+
expect(fallback.callId).toBe(9);
|
|
212
|
+
expect(fallback.result?.content).toBe("");
|
|
213
|
+
expect(fallback.result?.error).toContain("Workflow result serialization failed");
|
|
214
|
+
} finally {
|
|
215
|
+
restore();
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("postResult 不抛错到调用方(不中断 onWorkflowCall 链路)", async () => {
|
|
220
|
+
const restore = silenceConsoleError();
|
|
221
|
+
try {
|
|
222
|
+
const postMessage = makeAlwaysFailingPostMessage();
|
|
223
|
+
const onWorkflowCall = vi.fn(async () => ({ bad: () => {} }));
|
|
224
|
+
const run = makeRunningRun(postMessage);
|
|
225
|
+
const deps = makeDeps(onWorkflowCall);
|
|
226
|
+
|
|
227
|
+
// handleWorkerMessage 自身不应抛——postResult 内部已 catch
|
|
228
|
+
await expect(
|
|
229
|
+
handleWorkerMessage(
|
|
230
|
+
run,
|
|
231
|
+
{ type: "workflow-call", callId: 10, name: "sub", args: {} },
|
|
232
|
+
deps,
|
|
233
|
+
makeHandlers(),
|
|
234
|
+
),
|
|
235
|
+
).resolves.toBeUndefined();
|
|
236
|
+
await flushMicrotasks();
|
|
237
|
+
} finally {
|
|
238
|
+
restore();
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
it("fallback 也失败 → console.error 记录 worker pending 将挂起", async () => {
|
|
243
|
+
const restore = silenceConsoleError();
|
|
244
|
+
try {
|
|
245
|
+
const postMessage = makeAlwaysFailingPostMessage();
|
|
246
|
+
const onWorkflowCall = vi.fn(async () => ({ bad: () => {} }));
|
|
247
|
+
const run = makeRunningRun(postMessage);
|
|
248
|
+
const deps = makeDeps(onWorkflowCall);
|
|
249
|
+
|
|
250
|
+
await handleWorkerMessage(
|
|
251
|
+
run,
|
|
252
|
+
{ type: "workflow-call", callId: 11, name: "sub", args: {} },
|
|
253
|
+
deps,
|
|
254
|
+
makeHandlers(),
|
|
255
|
+
);
|
|
256
|
+
await flushMicrotasks();
|
|
257
|
+
|
|
258
|
+
// 至少 2 次尝试(原始 + fallback),fallback 失败也记日志
|
|
259
|
+
expect(postMessage.mock.calls.length).toBeGreaterThanOrEqual(2);
|
|
260
|
+
const errorCalls = loggerMock.error.mock.calls.map((c) => c[0] as string);
|
|
261
|
+
expect(errorCalls.some((s) => s.includes("fallback also failed"))).toBe(true);
|
|
262
|
+
} finally {
|
|
263
|
+
restore();
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
// ── W2c: postAgentResult 防御(经 handleWorkerMessage 触发) ──
|
|
269
|
+
//
|
|
270
|
+
// postAgentResult 是私有函数,通过 workflow-call 路径无法触发。但它可经 agent-call
|
|
271
|
+
// 路径的「cached replay」分支触发:dispatchAgentCall 发现 run.state.calls.get(callId)
|
|
272
|
+
// 已是 done 时,直接 postAgentResult(run, callId, cached.result, true)(无需 spawn
|
|
273
|
+
// 子进程)。利用这一点构造行为测试——往 cached.result 里塞不可克隆值(function),
|
|
274
|
+
// mock postMessage 在首次发送 agent-result 时抛 DataCloneError,验证 fallback 路径。
|
|
275
|
+
//
|
|
276
|
+
// 另外补充:验证 error-recovery.ts 源码中三处 postMessage 调用点都有 try/catch 包裹,
|
|
277
|
+
// 防止未来重构误删防御(类似 worker-script-builder.test.ts 的源码字符串断言模式)。
|
|
278
|
+
|
|
279
|
+
/** 构造 status="running" 且 calls 已含一个 done 结果(含不可克隆成员)的 mock run。
|
|
280
|
+
* 触发 dispatchAgentCall 的 cached replay 分支(line ~234),直接走 postAgentResult。 */
|
|
281
|
+
function makeRunningRunWithCachedDone(
|
|
282
|
+
postMessage: ReturnType<typeof vi.fn>,
|
|
283
|
+
callId: number,
|
|
284
|
+
result: unknown,
|
|
285
|
+
): WorkflowRun {
|
|
286
|
+
const calls = new Map();
|
|
287
|
+
calls.set(callId, { status: "done", result });
|
|
288
|
+
return {
|
|
289
|
+
state: {
|
|
290
|
+
status: "running",
|
|
291
|
+
calls,
|
|
292
|
+
trace: { append: vi.fn(), update: vi.fn() },
|
|
293
|
+
budget: { isExceeded: vi.fn(() => false) },
|
|
294
|
+
},
|
|
295
|
+
runtime: { worker: { postMessage } },
|
|
296
|
+
} as unknown as WorkflowRun;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
describe("W2c: postAgentResult 行为测试(cached replay 路径)", () => {
|
|
300
|
+
it("result 不可克隆 → 回发纯字符串 fallback result(cached: false)", async () => {
|
|
301
|
+
const restore = silenceConsoleError();
|
|
302
|
+
try {
|
|
303
|
+
// 第 1 次 postMessage 抛 DataCloneError(原始 cached.result 含 function 不可克隆),
|
|
304
|
+
// 第 2 次(fallback)成功。
|
|
305
|
+
const postMessage = makeFailingPostMessage(1);
|
|
306
|
+
// cached.result 含 function 成员 → 模拟 agent 返回不可克隆值({ bad: () => {} })
|
|
307
|
+
const run = makeRunningRunWithCachedDone(postMessage, 7, { bad: () => {} });
|
|
308
|
+
const deps = makeDeps();
|
|
309
|
+
|
|
310
|
+
await handleWorkerMessage(
|
|
311
|
+
run,
|
|
312
|
+
{ type: "agent-call", callId: 7, opts: { prompt: "noop" } },
|
|
313
|
+
deps,
|
|
314
|
+
makeHandlers(),
|
|
315
|
+
);
|
|
316
|
+
await flushMicrotasks();
|
|
317
|
+
|
|
318
|
+
// 调用两次:1 原始 agent-result(失败)+ 1 fallback(成功)
|
|
319
|
+
expect(postMessage).toHaveBeenCalledTimes(2);
|
|
320
|
+
|
|
321
|
+
// 第 1 次:原始 agent-result,result 透传原值,cached 为 replay 的 true
|
|
322
|
+
const original = postedAt(postMessage, 0);
|
|
323
|
+
expect(original.type).toBe("agent-result");
|
|
324
|
+
expect(original.callId).toBe(7);
|
|
325
|
+
expect(original.cached).toBe(true);
|
|
326
|
+
|
|
327
|
+
// 第 2 次:fallback agent-result,result 形状为 {content:"", error:"Result serialization failed: ..."},
|
|
328
|
+
// 且 cached 固定为 false(fallback result 非缓存命中,透传原值含义失真)
|
|
329
|
+
const fallback = postedAt(postMessage, 1);
|
|
330
|
+
expect(fallback.type).toBe("agent-result");
|
|
331
|
+
expect(fallback.callId).toBe(7);
|
|
332
|
+
expect(fallback.result?.content).toBe("");
|
|
333
|
+
expect(fallback.result?.error).toContain("Result serialization failed");
|
|
334
|
+
expect(fallback.result?.error).toContain("Could not clone object");
|
|
335
|
+
expect(fallback.cached).toBe(false);
|
|
336
|
+
} finally {
|
|
337
|
+
restore();
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
it("fallback 也失败 → 不向上抛错,记录 worker pending 将挂起", async () => {
|
|
342
|
+
const restore = silenceConsoleError();
|
|
343
|
+
try {
|
|
344
|
+
// postMessage 永远抛 DataCloneError(原始 + fallback 均失败)
|
|
345
|
+
const postMessage = makeAlwaysFailingPostMessage();
|
|
346
|
+
const run = makeRunningRunWithCachedDone(postMessage, 8, { bad: () => {} });
|
|
347
|
+
const deps = makeDeps();
|
|
348
|
+
|
|
349
|
+
// handleWorkerMessage 自身不应抛——postAgentResult 内部已 catch
|
|
350
|
+
await expect(
|
|
351
|
+
handleWorkerMessage(
|
|
352
|
+
run,
|
|
353
|
+
{ type: "agent-call", callId: 8, opts: { prompt: "noop" } },
|
|
354
|
+
deps,
|
|
355
|
+
makeHandlers(),
|
|
356
|
+
),
|
|
357
|
+
).resolves.toBeUndefined();
|
|
358
|
+
await flushMicrotasks();
|
|
359
|
+
|
|
360
|
+
// 至少 2 次尝试(原始 + fallback),fallback 失败也记日志
|
|
361
|
+
expect(postMessage.mock.calls.length).toBeGreaterThanOrEqual(2);
|
|
362
|
+
const errorCalls = loggerMock.error.mock.calls.map((c) => c[0] as string);
|
|
363
|
+
expect(errorCalls.some((s) => s.includes("postAgentResult failed"))).toBe(true);
|
|
364
|
+
expect(errorCalls.some((s) => s.includes("fallback also failed"))).toBe(true);
|
|
365
|
+
} finally {
|
|
366
|
+
restore();
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
describe("W2c: postAgentResult 防御(源码结构断言)", () => {
|
|
372
|
+
/** 校验:给定函数体内的 postMessage 调用被 try/catch 包裹。
|
|
373
|
+
* 简化策略——在函数体片段中确认存在 try { ... postMessage ... } catch。 */
|
|
374
|
+
function hasTryCatchAroundPostMessage(funcBody: string): boolean {
|
|
375
|
+
return /try\s*\{[\s\S]*?postMessage[\s\S]*?\}\s*catch/.test(funcBody);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
it("postAgentResult 包含 try/catch + fallback result", () => {
|
|
379
|
+
const match = ERROR_RECOVERY_SRC.match(/function postAgentResult\([\s\S]*?\n\}/);
|
|
380
|
+
expect(match, "postAgentResult 函数定义应存在").toBeTruthy();
|
|
381
|
+
expect(hasTryCatchAroundPostMessage(match![0])).toBe(true);
|
|
382
|
+
// fallback 通过共享工厂 makeSerializeFailedResult 构造纯字符串 result(必可克隆)
|
|
383
|
+
expect(match![0]).toContain('result: makeSerializeFailedResult("Result serialization failed"');
|
|
384
|
+
expect(match![0]).toContain("Result serialization failed");
|
|
385
|
+
// 原 result 不可克隆时 cached 透传原值含义失真 → fallback 固定 cached: false
|
|
386
|
+
expect(match![0]).toContain("cached: false");
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
it("postBudgetUpdate 包含 try/catch", () => {
|
|
390
|
+
const match = ERROR_RECOVERY_SRC.match(/export function postBudgetUpdate\([\s\S]*?\n\}/);
|
|
391
|
+
expect(match, "postBudgetUpdate 函数定义应存在").toBeTruthy();
|
|
392
|
+
expect(hasTryCatchAroundPostMessage(match![0])).toBe(true);
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
it("dispatchWorkflowCall postResult 闭包包含 try/catch + fallback", () => {
|
|
396
|
+
// postResult 是 const 闭包,匹配到下一个 }; 结尾
|
|
397
|
+
const match = ERROR_RECOVERY_SRC.match(/const postResult = \(result[\s\S]*?\n \};/);
|
|
398
|
+
expect(match, "postResult 闭包定义应存在").toBeTruthy();
|
|
399
|
+
expect(hasTryCatchAroundPostMessage(match![0])).toBe(true);
|
|
400
|
+
expect(match![0]).toContain("Workflow result serialization failed");
|
|
401
|
+
// 防御变量名遮蔽:错误变量用 err 而非 msg(外层参数名 msg)
|
|
402
|
+
expect(match![0]).toMatch(/catch \(err\)/);
|
|
403
|
+
});
|
|
404
|
+
});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// src/orchestration/__tests__/error-recovery-serialize-failed-result.test.ts
|
|
2
|
+
//
|
|
3
|
+
// makeSerializeFailedResult 独立单测(W2 防御关键纯函数)。
|
|
4
|
+
//
|
|
5
|
+
// 背景:postMessage 序列化失败时,主线程需回发「必可克隆」的 fallback result
|
|
6
|
+
// 让 worker 内 pending Promise resolve(否则 agent()/workflow() 永久挂起,只能靠
|
|
7
|
+
// timeout 兜底)。两条 fallback 路径(postAgentResult / dispatchWorkflowCall.postResult)
|
|
8
|
+
// 共享 makeSerializeFailedResult 构造逻辑——本测试锁住其返回 shape,确保两条路径
|
|
9
|
+
// 不漂移。
|
|
10
|
+
//
|
|
11
|
+
// 验证点:
|
|
12
|
+
// 1. content 恒为 ""(纯字符串 fallback,必可克隆——不含 function/Symbol/循环引用)
|
|
13
|
+
// 2. error 形如 "<prefix>: <errMsg>"(前缀区分调用方,便于诊断定位)
|
|
14
|
+
// 3. prefix / errMsg 各自原样透传(含空串、特殊字符、多行)
|
|
15
|
+
|
|
16
|
+
import { describe, expect, it } from "vitest";
|
|
17
|
+
|
|
18
|
+
import { makeSerializeFailedResult } from "../error-recovery.ts";
|
|
19
|
+
|
|
20
|
+
describe("makeSerializeFailedResult", () => {
|
|
21
|
+
it("返回 {content:'', error:'<prefix>: <errMsg>'} 形状(必可克隆 fallback)", () => {
|
|
22
|
+
const result = makeSerializeFailedResult("Result serialization failed", "DataCloneError: ...");
|
|
23
|
+
expect(result).toEqual({
|
|
24
|
+
content: "",
|
|
25
|
+
error: "Result serialization failed: DataCloneError: ...",
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it("content 恒为空串(纯字符串 fallback,不含不可克隆成员)", () => {
|
|
30
|
+
// 无论入参如何,content 必为 ""——postMessage 必须能克隆这个 fallback result。
|
|
31
|
+
const result = makeSerializeFailedResult("any prefix", "any error");
|
|
32
|
+
expect(result.content).toBe("");
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("error 由 prefix + ': ' + errMsg 拼接(前缀区分调用方,便于诊断)", () => {
|
|
36
|
+
const result = makeSerializeFailedResult("Workflow result serialization failed", "boom");
|
|
37
|
+
expect(result.error).toBe("Workflow result serialization failed: boom");
|
|
38
|
+
// 分隔符固定为 ": "——两条 fallback 路径共享同一构造逻辑。
|
|
39
|
+
expect(result.error).toContain(": ");
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("prefix 与 errMsg 原样透传(含空串、特殊字符、多行)", () => {
|
|
43
|
+
// 空串 prefix
|
|
44
|
+
expect(makeSerializeFailedResult("", "err").error).toBe(": err");
|
|
45
|
+
// 空串 errMsg
|
|
46
|
+
expect(makeSerializeFailedResult("prefix", "").error).toBe("prefix: ");
|
|
47
|
+
// 含冒号 / 换行 / unicode 的 errMsg(原样透传,不做转义)
|
|
48
|
+
const weird = "err: with: colons\nand newline 中文 🚀";
|
|
49
|
+
expect(makeSerializeFailedResult("P", weird).error).toBe(`P: ${weird}`);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("返回对象字段仅 content + error(无多余字段,shape 稳定不漂移)", () => {
|
|
53
|
+
const result = makeSerializeFailedResult("p", "e");
|
|
54
|
+
expect(Object.keys(result).sort()).toEqual(["content", "error"]);
|
|
55
|
+
});
|
|
56
|
+
});
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dispatchWorkflowCall — workflow-call 消息路由测试。
|
|
3
|
+
*
|
|
4
|
+
* 通过 handleWorkerMessage 触发 workflow-call case,验证:
|
|
5
|
+
* - onWorkflowCall 回调被正确调用(name + args + parentRun)
|
|
6
|
+
* - 成功时 postMessage(workflow-result, result)
|
|
7
|
+
* - onWorkflowCall reject 时 postMessage 含 error
|
|
8
|
+
* - onWorkflowCall 未注入时 postMessage 含 error(向后兼容)
|
|
9
|
+
* - stale 完成守卫(resolve 前 run 已终态 → 不 postMessage)
|
|
10
|
+
*/
|
|
11
|
+
import { describe, expect, it, vi } from "vitest";
|
|
12
|
+
|
|
13
|
+
import { handleWorkerMessage } from "../error-recovery.ts";
|
|
14
|
+
import type { LifecycleDeps, WorkerHandlers } from "../models/ports.ts";
|
|
15
|
+
import type { WorkflowRun } from "../models/workflow-run.ts";
|
|
16
|
+
|
|
17
|
+
// ── helpers ──────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
/** flush microtask 队列,让 void .then().catch() 链路跑完。 */
|
|
20
|
+
async function flushMicrotasks(): Promise<void> {
|
|
21
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 构造一个 status="running" 的 mock WorkflowRun,postMessage 可观测。 */
|
|
25
|
+
function makeRunningRun(postMessage: ReturnType<typeof vi.fn>): WorkflowRun {
|
|
26
|
+
return {
|
|
27
|
+
state: { status: "running" },
|
|
28
|
+
runtime: { worker: { postMessage } },
|
|
29
|
+
} as unknown as WorkflowRun;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** LifecycleDeps 只需 onWorkflowCall(dispatchWorkflowCall 唯一消费的 dep)。 */
|
|
33
|
+
function makeDeps(onWorkflowCall?: LifecycleDeps["onWorkflowCall"]): LifecycleDeps {
|
|
34
|
+
return { onWorkflowCall } as unknown as LifecycleDeps;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** WorkerHandlers 占位(workflow-call 路径不触发 handler 回调)。 */
|
|
38
|
+
function makeHandlers(): WorkerHandlers {
|
|
39
|
+
return {
|
|
40
|
+
onMessage: vi.fn(async () => {}),
|
|
41
|
+
onError: vi.fn(async () => {}),
|
|
42
|
+
onExit: vi.fn(async () => {}),
|
|
43
|
+
} as unknown as WorkerHandlers;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface PostedMsg {
|
|
47
|
+
type: string;
|
|
48
|
+
callId: number;
|
|
49
|
+
result: { content: string; error?: string };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 从 postMessage mock 取第 0 次调用的第 0 参,类型安全窄化。 */
|
|
53
|
+
function firstPosted(postMessage: ReturnType<typeof vi.fn>): PostedMsg {
|
|
54
|
+
return postMessage.mock.calls[0]![0] as PostedMsg;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ── tests ────────────────────────────────────────────────────
|
|
58
|
+
|
|
59
|
+
describe("dispatchWorkflowCall (workflow-call routing)", () => {
|
|
60
|
+
it("calls onWorkflowCall with name and args", async () => {
|
|
61
|
+
const postMessage = vi.fn();
|
|
62
|
+
const onWorkflowCall = vi.fn(async () => ({ content: "ok" }));
|
|
63
|
+
const run = makeRunningRun(postMessage);
|
|
64
|
+
const deps = makeDeps(onWorkflowCall);
|
|
65
|
+
|
|
66
|
+
await handleWorkerMessage(
|
|
67
|
+
run,
|
|
68
|
+
{ type: "workflow-call", callId: 1, name: "sub", args: { k: 1 } },
|
|
69
|
+
deps,
|
|
70
|
+
makeHandlers(),
|
|
71
|
+
);
|
|
72
|
+
await flushMicrotasks();
|
|
73
|
+
|
|
74
|
+
expect(onWorkflowCall).toHaveBeenCalledTimes(1);
|
|
75
|
+
expect(onWorkflowCall).toHaveBeenCalledWith("sub", { k: 1 }, run);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("posts workflow-result on success", async () => {
|
|
79
|
+
const postMessage = vi.fn();
|
|
80
|
+
const onWorkflowCall = vi.fn(async () => ({ content: "result-data" }));
|
|
81
|
+
const run = makeRunningRun(postMessage);
|
|
82
|
+
const deps = makeDeps(onWorkflowCall);
|
|
83
|
+
|
|
84
|
+
await handleWorkerMessage(
|
|
85
|
+
run,
|
|
86
|
+
{ type: "workflow-call", callId: 2, name: "sub", args: {} },
|
|
87
|
+
deps,
|
|
88
|
+
makeHandlers(),
|
|
89
|
+
);
|
|
90
|
+
await flushMicrotasks();
|
|
91
|
+
|
|
92
|
+
expect(postMessage).toHaveBeenCalledWith({
|
|
93
|
+
type: "workflow-result",
|
|
94
|
+
callId: 2,
|
|
95
|
+
result: { content: "result-data" },
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it("posts error result when onWorkflowCall rejects", async () => {
|
|
100
|
+
const postMessage = vi.fn();
|
|
101
|
+
const onWorkflowCall = vi.fn(async () => {
|
|
102
|
+
throw new Error("boom");
|
|
103
|
+
});
|
|
104
|
+
const run = makeRunningRun(postMessage);
|
|
105
|
+
const deps = makeDeps(onWorkflowCall);
|
|
106
|
+
|
|
107
|
+
await handleWorkerMessage(
|
|
108
|
+
run,
|
|
109
|
+
{ type: "workflow-call", callId: 3, name: "sub", args: {} },
|
|
110
|
+
deps,
|
|
111
|
+
makeHandlers(),
|
|
112
|
+
);
|
|
113
|
+
await flushMicrotasks();
|
|
114
|
+
|
|
115
|
+
expect(postMessage).toHaveBeenCalledTimes(1);
|
|
116
|
+
const sent = firstPosted(postMessage);
|
|
117
|
+
expect(sent.type).toBe("workflow-result");
|
|
118
|
+
expect(sent.callId).toBe(3);
|
|
119
|
+
expect(sent.result.error).toBe("boom");
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it("posts error result when onWorkflowCall not injected", async () => {
|
|
123
|
+
const postMessage = vi.fn();
|
|
124
|
+
const run = makeRunningRun(postMessage);
|
|
125
|
+
const deps = makeDeps(undefined);
|
|
126
|
+
|
|
127
|
+
await handleWorkerMessage(
|
|
128
|
+
run,
|
|
129
|
+
{ type: "workflow-call", callId: 4, name: "sub", args: {} },
|
|
130
|
+
deps,
|
|
131
|
+
makeHandlers(),
|
|
132
|
+
);
|
|
133
|
+
await flushMicrotasks();
|
|
134
|
+
|
|
135
|
+
expect(postMessage).toHaveBeenCalledTimes(1);
|
|
136
|
+
const sent = firstPosted(postMessage);
|
|
137
|
+
expect(sent.type).toBe("workflow-result");
|
|
138
|
+
expect(sent.result.error).toContain("onWorkflowCall not injected");
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("does not post when run reaches terminal state before result arrives", async () => {
|
|
142
|
+
const postMessage = vi.fn();
|
|
143
|
+
let resolveWorkflow: (value: unknown) => void = () => {};
|
|
144
|
+
const workflowPromise = new Promise<unknown>((r) => {
|
|
145
|
+
resolveWorkflow = r;
|
|
146
|
+
});
|
|
147
|
+
const onWorkflowCall = vi.fn(() => workflowPromise);
|
|
148
|
+
const run = makeRunningRun(postMessage);
|
|
149
|
+
const deps = makeDeps(onWorkflowCall);
|
|
150
|
+
|
|
151
|
+
await handleWorkerMessage(
|
|
152
|
+
run,
|
|
153
|
+
{ type: "workflow-call", callId: 5, name: "sub", args: {} },
|
|
154
|
+
deps,
|
|
155
|
+
makeHandlers(),
|
|
156
|
+
);
|
|
157
|
+
|
|
158
|
+
// dispatchWorkflowCall 已触发,onWorkflowCall pending。
|
|
159
|
+
// 在 resolve 前终止 run(转终态 done)—— stale 完成守卫应阻止 postMessage。
|
|
160
|
+
run.state.status = "done";
|
|
161
|
+
resolveWorkflow({ content: "late" });
|
|
162
|
+
await flushMicrotasks();
|
|
163
|
+
|
|
164
|
+
expect(postMessage).not.toHaveBeenCalled();
|
|
165
|
+
});
|
|
166
|
+
});
|