@web-auto/webauto 0.1.1 → 0.1.2
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/apps/desktop-console/default-settings.json +1 -0
- package/apps/desktop-console/dist/main/index.mjs +1618 -0
- package/apps/desktop-console/{src → dist}/main/preload.mjs +10 -0
- package/apps/desktop-console/dist/renderer/index.js +3063 -0
- package/apps/desktop-console/entry/ui-console.mjs +299 -0
- package/apps/webauto/entry/account.mjs +356 -0
- package/apps/webauto/entry/lib/account-detect.mjs +160 -0
- package/apps/webauto/entry/lib/account-store.mjs +587 -0
- package/apps/webauto/entry/lib/profilepool.mjs +1 -1
- package/apps/webauto/entry/xhs-install.mjs +27 -3
- package/apps/webauto/entry/xhs-status.mjs +152 -0
- package/apps/webauto/entry/xhs-unified.mjs +595 -17
- package/bin/webauto.mjs +247 -12
- package/dist/apps/webauto/server.js +66 -0
- package/dist/modules/camo-backend/src/index.js +575 -0
- package/dist/modules/camo-backend/src/internal/BrowserSession.js +817 -0
- package/dist/modules/camo-backend/src/internal/ElementRegistry.js +61 -0
- package/dist/modules/camo-backend/src/internal/ProfileLock.js +85 -0
- package/dist/modules/camo-backend/src/internal/SessionManager.js +172 -0
- package/dist/modules/camo-backend/src/internal/container-matcher.js +852 -0
- package/dist/modules/camo-backend/src/internal/engine-manager.js +258 -0
- package/dist/modules/camo-backend/src/internal/fingerprint.js +203 -0
- package/dist/modules/camo-backend/src/internal/pageRuntime.js +29 -0
- package/dist/modules/camo-backend/src/internal/runtimeInjector.js +30 -0
- package/dist/modules/camo-backend/src/internal/state-bus.js +46 -0
- package/dist/modules/camo-backend/src/internal/storage-paths.js +36 -0
- package/dist/modules/camo-backend/src/internal/ws-server.js +1202 -0
- package/dist/modules/camo-runtime/src/utils/browser-service.mjs +423 -0
- package/dist/modules/camo-runtime/src/utils/config.mjs +77 -0
- package/dist/modules/container-registry/src/index.js +184 -0
- package/dist/modules/logging/src/index.js +92 -0
- package/dist/modules/operations/src/builtin.js +27 -0
- package/dist/modules/operations/src/container-binding.js +75 -0
- package/dist/modules/operations/src/executor.js +146 -0
- package/dist/modules/operations/src/operations/click.js +167 -0
- package/dist/modules/operations/src/operations/extract.js +204 -0
- package/dist/modules/operations/src/operations/find-child.js +17 -0
- package/dist/modules/operations/src/operations/highlight.js +138 -0
- package/dist/modules/operations/src/operations/key.js +61 -0
- package/dist/modules/operations/src/operations/navigate.js +148 -0
- package/dist/modules/operations/src/operations/scroll.js +126 -0
- package/dist/modules/operations/src/operations/type.js +190 -0
- package/dist/modules/operations/src/queue.js +100 -0
- package/dist/modules/operations/src/registry.js +11 -0
- package/dist/modules/operations/src/system/mouse.js +33 -0
- package/dist/modules/state/src/atomic-json.js +33 -0
- package/dist/modules/workflow/blocks/AnchorVerificationBlock.js +71 -0
- package/dist/modules/workflow/blocks/BehaviorRandomizer.js +26 -0
- package/dist/modules/workflow/blocks/CallWorkflowBlock.js +38 -0
- package/dist/modules/workflow/blocks/CloseDetailBlock.js +209 -0
- package/dist/modules/workflow/blocks/CollectBatch.js +137 -0
- package/dist/modules/workflow/blocks/CollectCommentsBlock.js +415 -0
- package/dist/modules/workflow/blocks/CollectSearchListBlock.js +599 -0
- package/dist/modules/workflow/blocks/CollectWeiboPosts.js +229 -0
- package/dist/modules/workflow/blocks/DetectPageStateBlock.js +259 -0
- package/dist/modules/workflow/blocks/EnsureLoginBlock.js +162 -0
- package/dist/modules/workflow/blocks/EnsureSession.js +426 -0
- package/dist/modules/workflow/blocks/ErrorClassifier.js +164 -0
- package/dist/modules/workflow/blocks/ErrorRecoveryBlock.js +319 -0
- package/dist/modules/workflow/blocks/ExpandCommentsBlock.js +1032 -0
- package/dist/modules/workflow/blocks/ExtractDetailBlock.js +310 -0
- package/dist/modules/workflow/blocks/ExtractPostFields.js +88 -0
- package/dist/modules/workflow/blocks/GenerateSmartReplyBlock.js +68 -0
- package/dist/modules/workflow/blocks/GoToSearchBlock.js +497 -0
- package/dist/modules/workflow/blocks/GracefulFallbackBlock.js +104 -0
- package/dist/modules/workflow/blocks/HighlightBlock.js +66 -0
- package/dist/modules/workflow/blocks/InitAutoScroll.js +65 -0
- package/dist/modules/workflow/blocks/LoadContainerDefinition.js +50 -0
- package/dist/modules/workflow/blocks/LoadContainerIndex.js +43 -0
- package/dist/modules/workflow/blocks/LocateAndGuardBlock.js +176 -0
- package/dist/modules/workflow/blocks/LoginRecoveryBlock.js +242 -0
- package/dist/modules/workflow/blocks/MatchContainers.js +64 -0
- package/dist/modules/workflow/blocks/MonitoringBlock.js +190 -0
- package/dist/modules/workflow/blocks/OpenDetailBlock.js +1240 -0
- package/dist/modules/workflow/blocks/OrganizeXhsNotesBlock.js +117 -0
- package/dist/modules/workflow/blocks/PersistXhsNoteBlock.js +270 -0
- package/dist/modules/workflow/blocks/PickSinglePost.js +69 -0
- package/dist/modules/workflow/blocks/ProgressTracker.js +125 -0
- package/dist/modules/workflow/blocks/RecordFixtureBlock.js +44 -0
- package/dist/modules/workflow/blocks/RenderMarkdown.js +48 -0
- package/dist/modules/workflow/blocks/SaveFile.js +54 -0
- package/dist/modules/workflow/blocks/ScrollNextBatch.js +72 -0
- package/dist/modules/workflow/blocks/SessionHealthBlock.js +73 -0
- package/dist/modules/workflow/blocks/StartBrowserService.js +45 -0
- package/dist/modules/workflow/blocks/ValidateContainerDefinition.js +67 -0
- package/dist/modules/workflow/blocks/ValidateExtract.js +35 -0
- package/dist/modules/workflow/blocks/WaitSearchPermitBlock.js +162 -0
- package/dist/modules/workflow/blocks/WaitStable.js +74 -0
- package/dist/modules/workflow/blocks/WarmupCommentsBlock.js +120 -0
- package/dist/modules/workflow/blocks/WorkflowExecutor.js +156 -0
- package/dist/modules/workflow/blocks/XiaohongshuCollectFromLinksBlock.js +1004 -0
- package/dist/modules/workflow/blocks/XiaohongshuCollectLinksBlock.js +1049 -0
- package/dist/modules/workflow/blocks/XiaohongshuFullCollectBlock.js +782 -0
- package/dist/modules/workflow/blocks/helpers/anchorVerify.js +198 -0
- package/dist/modules/workflow/blocks/helpers/asyncWorkQueue.js +53 -0
- package/dist/modules/workflow/blocks/helpers/commentScroller.js +334 -0
- package/dist/modules/workflow/blocks/helpers/commentSectionLocator.js +126 -0
- package/dist/modules/workflow/blocks/helpers/containerAnchors.js +301 -0
- package/dist/modules/workflow/blocks/helpers/debugArtifacts.js +6 -0
- package/dist/modules/workflow/blocks/helpers/downloadPaths.js +29 -0
- package/dist/modules/workflow/blocks/helpers/expandCommentsController.js +53 -0
- package/dist/modules/workflow/blocks/helpers/expandCommentsExtractor.js +129 -0
- package/dist/modules/workflow/blocks/helpers/macosVisionOcrPlugin.js +116 -0
- package/dist/modules/workflow/blocks/helpers/mergeXhsMarkdown.js +109 -0
- package/dist/modules/workflow/blocks/helpers/openDetailController.js +56 -0
- package/dist/modules/workflow/blocks/helpers/openDetailTypes.js +7 -0
- package/dist/modules/workflow/blocks/helpers/openDetailViewport.js +474 -0
- package/dist/modules/workflow/blocks/helpers/openDetailWaiter.js +104 -0
- package/dist/modules/workflow/blocks/helpers/operationLogger.js +195 -0
- package/dist/modules/workflow/blocks/helpers/persistedNotes.js +107 -0
- package/dist/modules/workflow/blocks/helpers/replyExpander.js +260 -0
- package/dist/modules/workflow/blocks/helpers/scrollIntoView.js +138 -0
- package/dist/modules/workflow/blocks/helpers/searchExecutor.js +328 -0
- package/dist/modules/workflow/blocks/helpers/searchGate.js +46 -0
- package/dist/modules/workflow/blocks/helpers/searchPageState.js +164 -0
- package/dist/modules/workflow/blocks/helpers/searchResultWaiter.js +64 -0
- package/dist/modules/workflow/blocks/helpers/simpleAnchor.js +134 -0
- package/dist/modules/workflow/blocks/helpers/smartReply.js +40 -0
- package/dist/modules/workflow/blocks/helpers/systemInput.js +635 -0
- package/dist/modules/workflow/blocks/helpers/targetCountMode.js +9 -0
- package/dist/modules/workflow/blocks/helpers/xhsCliArgs.js +80 -0
- package/dist/modules/workflow/blocks/helpers/xhsCommentDom.js +805 -0
- package/dist/modules/workflow/blocks/helpers/xhsNoteOrganizer.js +140 -0
- package/dist/modules/workflow/blocks/restore/RestorePhaseBlock.js +204 -0
- package/dist/modules/workflow/config/workflowRegistry.js +32 -0
- package/dist/modules/workflow/definitions/batch-collect-workflow.js +63 -0
- package/dist/modules/workflow/definitions/scroll-extract-workflow.js +74 -0
- package/dist/modules/workflow/definitions/xiaohongshu-collect-workflow-v2.js +81 -0
- package/dist/modules/workflow/definitions/xiaohongshu-collect-workflow.js +57 -0
- package/dist/modules/workflow/definitions/xiaohongshu-full-collect-workflow-v3.js +68 -0
- package/dist/modules/workflow/definitions/xiaohongshu-note-collect.js +49 -0
- package/dist/modules/workflow/definitions/xiaohongshu-phase1-workflow-v3.js +30 -0
- package/dist/modules/workflow/definitions/xiaohongshu-phase2-links-workflow-v3.js +40 -0
- package/dist/modules/workflow/definitions/xiaohongshu-phase3-collect-workflow-v1.js +54 -0
- package/dist/modules/workflow/definitions/xiaohongshu-phase34-from-links-workflow-v3.js +25 -0
- package/dist/modules/workflow/src/WeiboEventDrivenWorkflowRunner.js +308 -0
- package/dist/modules/workflow/src/context.js +70 -0
- package/dist/modules/workflow/src/index.js +5 -0
- package/dist/modules/workflow/src/orchestrator.js +230 -0
- package/dist/modules/workflow/src/runner.js +55 -0
- package/dist/modules/workflow/src/runtime.js +70 -0
- package/dist/modules/workflow/workflows/WeiboFeedExtractionWorkflow.js +359 -0
- package/dist/modules/workflow/workflows/XiaohongshuLoginWorkflow.js +110 -0
- package/dist/modules/xiaohongshu/app/src/blocks/MatchCommentsBlock.js +139 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase1EnsureServicesBlock.js +36 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase1MonitorCookieBlock.js +213 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase1StartProfileBlock.js +121 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase2CollectLinksBlock.js +1249 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase2SearchBlock.js +703 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase34CloseDetailBlock.js +41 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase34CloseTabsBlock.js +44 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase34CollectCommentsBlock.js +150 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase34ExtractDetailBlock.js +117 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase34OpenDetailBlock.js +102 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase34OpenTabsBlock.js +109 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase34PersistDetailBlock.js +117 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase34ProcessSingleNoteBlock.js +114 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase34ValidateLinksBlock.js +90 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase3InteractBlock.js +1009 -0
- package/dist/modules/xiaohongshu/app/src/blocks/Phase4MultiTabHarvestBlock.js +233 -0
- package/dist/modules/xiaohongshu/app/src/blocks/ReplyInteractBlock.js +291 -0
- package/dist/modules/xiaohongshu/app/src/blocks/XhsDiscoverFallbackBlock.js +240 -0
- package/dist/modules/xiaohongshu/app/src/blocks/helpers/commentMatchDsl.js +126 -0
- package/dist/modules/xiaohongshu/app/src/blocks/helpers/commentMatcher.js +99 -0
- package/dist/modules/xiaohongshu/app/src/blocks/helpers/evidence.js +27 -0
- package/dist/modules/xiaohongshu/app/src/blocks/helpers/sharding.js +42 -0
- package/dist/modules/xiaohongshu/app/src/blocks/helpers/xhsComments.js +270 -0
- package/dist/modules/xiaohongshu/app/src/index.js +9 -0
- package/dist/modules/xiaohongshu/app/src/utils/checkpoints.js +222 -0
- package/dist/modules/xiaohongshu/app/src/utils/controllerAction.js +43 -0
- package/dist/services/controller/src/controller.js +1476 -0
- package/dist/services/controller/src/index.js +2 -0
- package/dist/services/controller/src/payload-normalizer.js +129 -0
- package/dist/services/shared/heartbeat.js +120 -0
- package/dist/services/shared/lib/errorHandler.js +2 -0
- package/dist/services/shared/serviceProcessLogger.js +139 -0
- package/dist/services/unified-api/RemoteBrowserSession.js +176 -0
- package/dist/services/unified-api/RemoteSessionManager.js +148 -0
- package/dist/services/unified-api/container-operations-handler.js +115 -0
- package/dist/services/unified-api/server.js +652 -0
- package/dist/services/unified-api/state-registry.js +274 -0
- package/dist/services/unified-api/task-persistence.js +66 -0
- package/dist/services/unified-api/task-state.js +130 -0
- package/modules/camo-runtime/src/autoscript/action-providers/xhs/search.mjs +12 -5
- package/modules/xiaohongshu/app/pnpm-lock.yaml +24 -0
- package/package.json +37 -9
- package/.beads/README.md +0 -81
- package/.beads/config.yaml +0 -67
- package/.beads/interactions.jsonl +0 -0
- package/.beads/issues.jsonl +0 -180
- package/.beads/metadata.json +0 -4
- package/.claude/settings.local.json +0 -10
- package/.github/workflows/ci.yml +0 -55
- package/AGENTS.md +0 -253
- package/apps/desktop-console/README.md +0 -27
- package/apps/desktop-console/package-lock.json +0 -897
- package/apps/desktop-console/package.json +0 -20
- package/apps/desktop-console/scripts/build-and-install.mjs +0 -19
- package/apps/desktop-console/scripts/build.mjs +0 -45
- package/apps/desktop-console/scripts/test-preload.mjs +0 -13
- package/apps/desktop-console/src/main/config.mts +0 -26
- package/apps/desktop-console/src/main/core-daemon-manager.mts +0 -131
- package/apps/desktop-console/src/main/desktop-settings.mts +0 -267
- package/apps/desktop-console/src/main/heartbeat-watchdog.mts +0 -50
- package/apps/desktop-console/src/main/heartbeat-watchdog.test.mts +0 -68
- package/apps/desktop-console/src/main/index-streaming.test.mts +0 -20
- package/apps/desktop-console/src/main/index.mts +0 -980
- package/apps/desktop-console/src/main/profile-store.mts +0 -239
- package/apps/desktop-console/src/main/profile-store.test.mts +0 -54
- package/apps/desktop-console/src/main/state-bridge.mts +0 -114
- package/apps/desktop-console/src/main/task-state-types.ts +0 -32
- package/apps/desktop-console/src/renderer/hooks/use-task-state.mts +0 -120
- package/apps/desktop-console/src/renderer/index.mts +0 -133
- package/apps/desktop-console/src/renderer/index.test.mts +0 -34
- package/apps/desktop-console/src/renderer/path-helpers.mts +0 -46
- package/apps/desktop-console/src/renderer/path-helpers.test.mts +0 -14
- package/apps/desktop-console/src/renderer/tabs/debug.mts +0 -48
- package/apps/desktop-console/src/renderer/tabs/debug.test.mts +0 -22
- package/apps/desktop-console/src/renderer/tabs/logs.mts +0 -421
- package/apps/desktop-console/src/renderer/tabs/logs.test.mts +0 -27
- package/apps/desktop-console/src/renderer/tabs/preflight.mts +0 -486
- package/apps/desktop-console/src/renderer/tabs/preflight.test.mts +0 -33
- package/apps/desktop-console/src/renderer/tabs/profile-pool.mts +0 -213
- package/apps/desktop-console/src/renderer/tabs/results.mts +0 -171
- package/apps/desktop-console/src/renderer/tabs/run.test.mts +0 -63
- package/apps/desktop-console/src/renderer/tabs/runtime.mts +0 -151
- package/apps/desktop-console/src/renderer/tabs/settings.mts +0 -146
- package/apps/desktop-console/src/renderer/tabs/xiaohongshu/account-flow.mts +0 -486
- package/apps/desktop-console/src/renderer/tabs/xiaohongshu/guide-browser-check.mts +0 -56
- package/apps/desktop-console/src/renderer/tabs/xiaohongshu/helpers.mts +0 -262
- package/apps/desktop-console/src/renderer/tabs/xiaohongshu/layout-block.mts +0 -430
- package/apps/desktop-console/src/renderer/tabs/xiaohongshu/live-stats.mts +0 -847
- package/apps/desktop-console/src/renderer/tabs/xiaohongshu/run-flow.mts +0 -443
- package/apps/desktop-console/src/renderer/tabs/xiaohongshu-state.mts +0 -425
- package/apps/desktop-console/src/renderer/tabs/xiaohongshu.mts +0 -497
- package/apps/desktop-console/src/renderer/tabs/xiaohongshu.test.mts +0 -291
- package/apps/desktop-console/src/renderer/ui-components.mts +0 -31
- package/docs/README_camoufox_chinese.md +0 -141
- package/docs/USAGE_V3.md +0 -163
- package/docs/arch/OCR_MACOS_PLUGIN.md +0 -39
- package/docs/arch/PORTS.md +0 -40
- package/docs/arch/REGRESSION_CHECKLIST.md +0 -121
- package/docs/arch/SEARCH_GATE.md +0 -224
- package/docs/arch/VIEWPORT_SAFETY.md +0 -182
- package/docs/arch/XIAOHONGSHU_OFFLINE_MOCK_DESIGN.md +0 -267
- package/docs/xiaohongshu-container-driven-summary.md +0 -221
- package/docs/xiaohongshu-full-collect-runbook.md +0 -134
- package/docs/xiaohongshu-next-steps.md +0 -228
- package/docs/xiaohongshu-quickstart.md +0 -73
- package/docs/xiaohongshu-workflow-summary.md +0 -227
- package/modules/container-registry/tests/container-registry.test.ts +0 -16
- package/modules/logging/tests/logging.test.ts +0 -38
- package/modules/operations/tests/operations.test.ts +0 -22
- package/modules/operations/tests/viewport-filter.test.ts +0 -161
- package/modules/operations/tests/visible-only.test.ts +0 -250
- package/modules/session-manager/tests/session-manager.test.ts +0 -23
- package/modules/state/src/atomic-json.test.ts +0 -30
- package/modules/state/src/paths.test.ts +0 -59
- package/modules/state/src/xiaohongshu-collect-state.test.ts +0 -259
- package/modules/workflow/blocks/AnchorVerificationBlock.d.ts.map +0 -1
- package/modules/workflow/blocks/AnchorVerificationBlock.js.map +0 -1
- package/modules/workflow/blocks/DetectPageStateBlock.d.ts.map +0 -1
- package/modules/workflow/blocks/DetectPageStateBlock.js.map +0 -1
- package/modules/workflow/blocks/ErrorRecoveryBlock.d.ts.map +0 -1
- package/modules/workflow/blocks/ErrorRecoveryBlock.js.map +0 -1
- package/modules/workflow/blocks/WaitSearchPermitBlock.d.ts.map +0 -1
- package/modules/workflow/blocks/WaitSearchPermitBlock.js.map +0 -1
- package/modules/workflow/blocks/helpers/containerAnchors.d.ts.map +0 -1
- package/modules/workflow/blocks/helpers/containerAnchors.js.map +0 -1
- package/modules/workflow/blocks/helpers/downloadPaths.test.ts +0 -62
- package/modules/workflow/blocks/helpers/mergeXhsMarkdown.test.ts +0 -121
- package/modules/workflow/blocks/helpers/operationLogger.d.ts.map +0 -1
- package/modules/workflow/blocks/helpers/operationLogger.js.map +0 -1
- package/modules/workflow/blocks/helpers/persistedNotes.test.ts +0 -268
- package/modules/workflow/blocks/helpers/searchPageState.d.ts.map +0 -1
- package/modules/workflow/blocks/helpers/searchPageState.js.map +0 -1
- package/modules/workflow/blocks/helpers/targetCountMode.test.ts +0 -29
- package/modules/workflow/blocks/helpers/xhsCliArgs.test.ts +0 -75
- package/modules/workflow/tests/smartReply.test.ts +0 -32
- package/modules/xiaohongshu/app/src/blocks/Phase3Interact.matcher.test.ts +0 -33
- package/modules/xiaohongshu/app/src/utils/__tests__/checkpoints.test.ts +0 -141
- package/modules/xiaohongshu/app/tests/commentMatchDsl.test.ts +0 -50
- package/modules/xiaohongshu/app/tests/commentMatcher.test.ts +0 -46
- package/modules/xiaohongshu/app/tests/sharding.test.ts +0 -31
- package/package-scripts.json +0 -8
- package/runtime/infra/utils/README.md +0 -13
- package/runtime/infra/utils/scripts/README.md +0 -0
- package/runtime/infra/utils/scripts/development/eval-in-session.mjs +0 -40
- package/runtime/infra/utils/scripts/development/highlight-search-containers.mjs +0 -35
- package/runtime/infra/utils/scripts/service/kill-port.mjs +0 -24
- package/runtime/infra/utils/scripts/service/start-api.mjs +0 -39
- package/runtime/infra/utils/scripts/service/start-browser-service.mjs +0 -106
- package/runtime/infra/utils/scripts/service/stop-api.mjs +0 -18
- package/runtime/infra/utils/scripts/service/stop-browser-service.mjs +0 -104
- package/runtime/infra/utils/scripts/test-services.mjs +0 -94
- package/services/shared/heartbeat.test.ts +0 -102
- package/services/unified-api/__tests__/task-state.test.ts +0 -95
- package/sitecustomize.py +0 -19
- package/tests/README.md +0 -194
- package/tests/e2e/workflows/weibo-feed-extraction.test.ts +0 -171
- package/tests/fixtures/data/container-definitions.json +0 -67
- package/tests/fixtures/pages/simple-page.html +0 -69
- package/tests/integration/01-test-container-match.mjs +0 -188
- package/tests/integration/02-test-dom-branch.mjs +0 -161
- package/tests/integration/03-test-container-operation-system.mjs +0 -91
- package/tests/integration/05-test-container-lifecycle-events.mjs +0 -224
- package/tests/integration/05-test-container-lifecycle-with-events.mjs +0 -250
- package/tests/integration/06-test-container-dom-tree-drawing.mjs +0 -256
- package/tests/integration/07-test-weibo-container-lifecycle.mjs +0 -355
- package/tests/integration/08-test-weibo-feed-workflow.test.mjs +0 -164
- package/tests/integration/10-test-visual-analyzer.mjs +0 -312
- package/tests/integration/11-test-visual-loop.mjs +0 -284
- package/tests/integration/12-test-simple-visual-loop.mjs +0 -242
- package/tests/integration/13-test-visual-robust.mjs +0 -185
- package/tests/integration/14-test-visual-highlight-loop.mjs +0 -271
- package/tests/integration/inspect-page.mjs +0 -50
- package/tests/integration/run-all-tests.mjs +0 -95
- package/tests/patch_verification/CODEX_PATCH_TEST.md +0 -103
- package/tests/patch_verification/PHASE2_ANALYSIS.md +0 -179
- package/tests/patch_verification/PHASE2_OPTIMIZATION_REPORT.md +0 -55
- package/tests/patch_verification/PHASE2_TO_PHASE4_SUMMARY.md +0 -126
- package/tests/patch_verification/QUICK_TEST_SEQUENCE.md +0 -262
- package/tests/patch_verification/README.md +0 -143
- package/tests/patch_verification/RUN_TESTS.md +0 -60
- package/tests/patch_verification/TEST_EXECUTION.md +0 -99
- package/tests/patch_verification/TEST_PLAN.md +0 -328
- package/tests/patch_verification/TEST_RESULTS.md +0 -34
- package/tests/patch_verification/TOOL_TEST_PLAN.md +0 -48
- package/tests/patch_verification/run-tool-test.mjs +0 -121
- package/tests/patch_verification/temp_test_files/test01.txt +0 -1
- package/tests/patch_verification/temp_test_files/test02.txt +0 -3
- package/tests/patch_verification/temp_test_files/test02_gnu.txt +0 -3
- package/tests/patch_verification/temp_test_files/test03.txt +0 -1
- package/tests/patch_verification/temp_test_files/test03_multiline.txt +0 -5
- package/tests/patch_verification/temp_test_files/test04_function.ts +0 -5
- package/tests/patch_verification/temp_test_files/test05_import.ts +0 -4
- package/tests/patch_verification/temp_test_files/test06_special_chars.txt +0 -4
- package/tests/patch_verification/temp_test_files/test07_indentation.ts +0 -5
- package/tests/patch_verification/temp_test_files/test08_mismatch.txt +0 -1
- package/tests/patch_verification/temp_test_files/test_add_02.txt +0 -3
- package/tests/patch_verification/temp_test_files/test_simple.txt +0 -1
- package/tests/runner/TestReporter.mjs +0 -57
- package/tests/runner/TestRunner.mjs +0 -244
- package/tests/unit/commands/profile.test.mjs +0 -10
- package/tests/unit/container/change-notifier.test.mjs +0 -181
- package/tests/unit/lifecycle/session-registry.test.mjs +0 -135
- package/tests/unit/operations/registry.test.ts +0 -73
- package/tests/unit/utils/browser-service.test.mjs +0 -153
- package/tests/unit/utils/config.test.mjs +0 -166
- package/tests/unit/utils/fingerprint.test.mjs +0 -166
- package/tsconfig.json +0 -31
- package/tsconfig.services.json +0 -26
- /package/apps/desktop-console/{src → dist}/renderer/index.html +0 -0
- /package/apps/desktop-console/{src/renderer/tabs → dist/renderer}/run.mts +0 -0
|
@@ -0,0 +1,652 @@
|
|
|
1
|
+
import { UiController } from '../../services/controller/src/controller.js';
|
|
2
|
+
import { handleContainerOperations } from './container-operations-handler.js';
|
|
3
|
+
// @ts-ignore
|
|
4
|
+
// import { setupContainerOperationsRoutes } from './container-operations.mjs';
|
|
5
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { RemoteSessionManager } from './RemoteSessionManager.js';
|
|
10
|
+
import { ensureBuiltinOperations } from '../../modules/operations/src/builtin.js';
|
|
11
|
+
import { getContainerExecutor } from '../../modules/operations/src/executor.js';
|
|
12
|
+
import { installServiceProcessLogger } from '../shared/serviceProcessLogger.js';
|
|
13
|
+
import { startHeartbeatWatcher } from '../shared/heartbeat.js';
|
|
14
|
+
import { taskStateRegistry } from './task-state.js';
|
|
15
|
+
import { saveTaskSnapshot, appendEvent } from './task-persistence.js';
|
|
16
|
+
// Ensure builtin operations are registered before handling any operations
|
|
17
|
+
ensureBuiltinOperations();
|
|
18
|
+
import { getStateRegistry } from './state-registry.js';
|
|
19
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
20
|
+
const { logEvent } = installServiceProcessLogger({ serviceName: 'unified-api' });
|
|
21
|
+
const DEFAULT_PORT = Number(process.env.WEBAUTO_UNIFIED_PORT || 7701);
|
|
22
|
+
const DEFAULT_HOST = process.env.WEBAUTO_UNIFIED_HOST || '127.0.0.1';
|
|
23
|
+
// 注意:运行时 server.js 位于 dist/services/unified-api/,因此需要回退三级到仓库根目录
|
|
24
|
+
// 源码构建时同样兼容(__dirname 为 services/unified-api/),此写法在两种场景下都能得到仓库根目录
|
|
25
|
+
const repoRoot = path.resolve(__dirname, '../../..');
|
|
26
|
+
const userContainerRoot = process.env.WEBAUTO_USER_CONTAINER_ROOT || path.join(os.homedir(), '.webauto', 'container-lib');
|
|
27
|
+
const containerIndexPath = process.env.WEBAUTO_CONTAINER_INDEX || path.join(repoRoot, 'apps/webauto/resources/container-library.index.json');
|
|
28
|
+
const defaultWsHost = process.env.WEBAUTO_WS_HOST || '127.0.0.1';
|
|
29
|
+
const defaultWsPort = Number(process.env.WEBAUTO_WS_PORT || 8765);
|
|
30
|
+
const defaultHttpHost = process.env.WEBAUTO_BROWSER_HTTP_HOST || '127.0.0.1';
|
|
31
|
+
const defaultHttpPort = Number(process.env.WEBAUTO_BROWSER_HTTP_PORT || 7704);
|
|
32
|
+
const defaultHttpProtocol = process.env.WEBAUTO_BROWSER_HTTP_PROTO || 'http';
|
|
33
|
+
const cliTargets = {
|
|
34
|
+
'session-manager': path.join(repoRoot, 'dist/modules/session-manager/src/cli.js'),
|
|
35
|
+
logging: path.join(repoRoot, 'dist/modules/logging/src/cli.js'),
|
|
36
|
+
operations: path.join(repoRoot, 'dist/modules/operations/src/cli.js'),
|
|
37
|
+
};
|
|
38
|
+
startHeartbeatWatcher({ serviceName: 'unified-api' });
|
|
39
|
+
class UnifiedApiServer {
|
|
40
|
+
controller;
|
|
41
|
+
wsClients;
|
|
42
|
+
busClients;
|
|
43
|
+
subscriptions;
|
|
44
|
+
containerSubscriptions = new Map();
|
|
45
|
+
containerExecutor;
|
|
46
|
+
sessionManager;
|
|
47
|
+
stateRegistry;
|
|
48
|
+
taskRegistry = taskStateRegistry;
|
|
49
|
+
constructor() {
|
|
50
|
+
this.controller = new UiController({
|
|
51
|
+
repoRoot,
|
|
52
|
+
userContainerRoot,
|
|
53
|
+
containerIndexPath,
|
|
54
|
+
cliTargets,
|
|
55
|
+
defaultWsHost,
|
|
56
|
+
defaultWsPort,
|
|
57
|
+
defaultHttpHost,
|
|
58
|
+
defaultHttpPort,
|
|
59
|
+
defaultHttpProtocol,
|
|
60
|
+
messageBus: {
|
|
61
|
+
publish: (topic, payload) => {
|
|
62
|
+
this.broadcastEvent(topic, payload);
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
this.wsClients = new Set();
|
|
67
|
+
this.busClients = new Set();
|
|
68
|
+
this.subscriptions = new Map();
|
|
69
|
+
// Initialize state registry
|
|
70
|
+
this.stateRegistry = getStateRegistry();
|
|
71
|
+
this.setupTaskRoutes();
|
|
72
|
+
}
|
|
73
|
+
broadcastEvent(topic, payload) {
|
|
74
|
+
const message = {
|
|
75
|
+
type: 'event',
|
|
76
|
+
topic,
|
|
77
|
+
payload,
|
|
78
|
+
timestamp: Date.now()
|
|
79
|
+
};
|
|
80
|
+
this.wsClients.forEach((socket) => {
|
|
81
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
82
|
+
this.safeSend(socket, message);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
// Also broadcast to bus clients so they receive events
|
|
86
|
+
this.busClients.forEach((socket) => {
|
|
87
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
88
|
+
this.safeSend(socket, message);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
addSubscription(socket, topic) {
|
|
93
|
+
const current = this.subscriptions.get(socket) || new Set();
|
|
94
|
+
current.add(topic);
|
|
95
|
+
this.subscriptions.set(socket, current);
|
|
96
|
+
if (topic.startsWith('container:')) {
|
|
97
|
+
const containerId = topic.replace('container:', '');
|
|
98
|
+
this.handleContainerSubscription(containerId, socket);
|
|
99
|
+
}
|
|
100
|
+
this.safeSend(socket, { type: 'subscription:confirmed', topic });
|
|
101
|
+
}
|
|
102
|
+
removeSubscription(socket, topic) {
|
|
103
|
+
if (!topic) {
|
|
104
|
+
this.subscriptions.delete(socket);
|
|
105
|
+
for (const [cid, subs] of this.containerSubscriptions.entries()) {
|
|
106
|
+
subs.delete(socket);
|
|
107
|
+
if (subs.size === 0)
|
|
108
|
+
this.containerSubscriptions.delete(cid);
|
|
109
|
+
}
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const current = this.subscriptions.get(socket);
|
|
113
|
+
if (!current)
|
|
114
|
+
return;
|
|
115
|
+
current.delete(topic);
|
|
116
|
+
if (topic.startsWith('container:')) {
|
|
117
|
+
const containerId = topic.replace('container:', '');
|
|
118
|
+
this.removeContainerSubscription(containerId, socket);
|
|
119
|
+
}
|
|
120
|
+
if (current.size === 0) {
|
|
121
|
+
this.subscriptions.delete(socket);
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
this.subscriptions.set(socket, current);
|
|
125
|
+
}
|
|
126
|
+
this.safeSend(socket, { type: 'subscription:removed', topic });
|
|
127
|
+
}
|
|
128
|
+
handleContainerSubscription(containerId, socket) {
|
|
129
|
+
if (!socket)
|
|
130
|
+
return;
|
|
131
|
+
if (!this.containerSubscriptions.has(containerId)) {
|
|
132
|
+
this.containerSubscriptions.set(containerId, new Set());
|
|
133
|
+
}
|
|
134
|
+
this.containerSubscriptions.get(containerId).add(socket);
|
|
135
|
+
this.safeSend(socket, {
|
|
136
|
+
type: 'subscription:confirmed',
|
|
137
|
+
containerId,
|
|
138
|
+
timestamp: Date.now()
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
removeContainerSubscription(containerId, socket) {
|
|
142
|
+
const subscriptions = this.containerSubscriptions.get(containerId);
|
|
143
|
+
if (subscriptions) {
|
|
144
|
+
subscriptions.delete(socket);
|
|
145
|
+
if (subscriptions.size === 0) {
|
|
146
|
+
this.containerSubscriptions.delete(containerId);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
pushContainerState(containerId, state) {
|
|
151
|
+
const subscribers = this.containerSubscriptions.get(containerId);
|
|
152
|
+
if (subscribers) {
|
|
153
|
+
const message = {
|
|
154
|
+
type: 'container:state:updated',
|
|
155
|
+
containerId,
|
|
156
|
+
state,
|
|
157
|
+
timestamp: Date.now()
|
|
158
|
+
};
|
|
159
|
+
subscribers.forEach(socket => {
|
|
160
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
161
|
+
this.safeSend(socket, message);
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
matchesTopic(pattern, topic) {
|
|
167
|
+
const regexPattern = pattern
|
|
168
|
+
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
|
169
|
+
.replace(/\*/g, '.*')
|
|
170
|
+
.replace(/\?/g, '.');
|
|
171
|
+
return new RegExp(`^${regexPattern}$`).test(topic);
|
|
172
|
+
}
|
|
173
|
+
shouldDeliver(socket, topic) {
|
|
174
|
+
const subs = this.subscriptions.get(socket);
|
|
175
|
+
if (!subs || subs.size === 0)
|
|
176
|
+
return false;
|
|
177
|
+
for (const pattern of subs) {
|
|
178
|
+
if (this.matchesTopic(pattern, topic))
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
return false;
|
|
182
|
+
}
|
|
183
|
+
async readJsonBody(req) {
|
|
184
|
+
const chunks = [];
|
|
185
|
+
for await (const chunk of req) {
|
|
186
|
+
chunks.push(chunk);
|
|
187
|
+
}
|
|
188
|
+
if (chunks.length === 0)
|
|
189
|
+
return {};
|
|
190
|
+
const raw = Buffer.concat(chunks).toString('utf8').trim();
|
|
191
|
+
if (!raw)
|
|
192
|
+
return {};
|
|
193
|
+
return JSON.parse(raw);
|
|
194
|
+
}
|
|
195
|
+
async start() {
|
|
196
|
+
// Start state registry periodic cleanup
|
|
197
|
+
const registry = this.stateRegistry;
|
|
198
|
+
if (registry) {
|
|
199
|
+
setInterval(() => {
|
|
200
|
+
try {
|
|
201
|
+
registry.cleanupOldSessions();
|
|
202
|
+
}
|
|
203
|
+
catch (err) {
|
|
204
|
+
console.warn('[unified-api] stateRegistry cleanup failed:', err?.message || err);
|
|
205
|
+
logEvent('stateRegistry.cleanupOldSessions.error', {
|
|
206
|
+
error: { message: err?.message || String(err) },
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}, 5 * 60 * 1000); // 5 minutes
|
|
210
|
+
}
|
|
211
|
+
const { createServer } = await import('node:http');
|
|
212
|
+
const server = createServer();
|
|
213
|
+
const wss = new WebSocketServer({ server });
|
|
214
|
+
// Initialize builtin operations
|
|
215
|
+
ensureBuiltinOperations();
|
|
216
|
+
// Session manager for container operations
|
|
217
|
+
// 使用 RemoteSessionManager 代理对 Browser Service 的调用
|
|
218
|
+
const browserServiceUrl = `${defaultHttpProtocol}://${defaultHttpHost}:${defaultHttpPort}`;
|
|
219
|
+
console.log(`[unified-api] Using remote browser service at ${browserServiceUrl}`);
|
|
220
|
+
const sessionManager = new RemoteSessionManager({
|
|
221
|
+
host: defaultHttpHost,
|
|
222
|
+
port: defaultHttpPort,
|
|
223
|
+
wsHost: defaultWsHost,
|
|
224
|
+
wsPort: defaultWsPort
|
|
225
|
+
});
|
|
226
|
+
this.sessionManager = sessionManager;
|
|
227
|
+
// Sync sessions to state registry
|
|
228
|
+
try {
|
|
229
|
+
const sessions = await sessionManager.listSessions();
|
|
230
|
+
console.log('[unified-api] Initial session sync:', sessions);
|
|
231
|
+
if (Array.isArray(sessions)) {
|
|
232
|
+
sessions.forEach((session) => {
|
|
233
|
+
const profileId = session.profileId || session.profile_id || session.sessionId || session.session_id;
|
|
234
|
+
if (!profileId)
|
|
235
|
+
return;
|
|
236
|
+
this.stateRegistry.updateSessionState(profileId, {
|
|
237
|
+
profileId,
|
|
238
|
+
sessionId: session.sessionId || session.session_id || profileId,
|
|
239
|
+
currentUrl: session.currentUrl || session.current_url || '',
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
this.stateRegistry.flush();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
catch (err) {
|
|
246
|
+
console.warn('[unified-api] session sync failed:', err?.message || err);
|
|
247
|
+
}
|
|
248
|
+
// Container operations executor (fills selector + merges container op config)
|
|
249
|
+
this.containerExecutor = getContainerExecutor();
|
|
250
|
+
// HTTP routes - unified request handler
|
|
251
|
+
server.on('request', (req, res) => {
|
|
252
|
+
void (async () => {
|
|
253
|
+
const url = new URL(req.url, `http://${req.headers.host}`);
|
|
254
|
+
// Container operations endpoints
|
|
255
|
+
const containerHandled = await handleContainerOperations(req, res, sessionManager, this.containerExecutor);
|
|
256
|
+
if (containerHandled)
|
|
257
|
+
return;
|
|
258
|
+
// Task state API endpoints
|
|
259
|
+
if (req.method === 'GET' && url.pathname === '/api/v1/tasks') {
|
|
260
|
+
const tasks = this.taskRegistry.getAllTasks();
|
|
261
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
262
|
+
res.end(JSON.stringify({ success: true, data: tasks }));
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (req.method === 'GET' && url.pathname.startsWith('/api/v1/tasks/')) {
|
|
266
|
+
const parts = url.pathname.split('/');
|
|
267
|
+
const runId = parts[parts.length - 1];
|
|
268
|
+
const task = this.taskRegistry.getTask(runId);
|
|
269
|
+
if (!task) {
|
|
270
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
271
|
+
res.end(JSON.stringify({ success: false, error: 'Task not found' }));
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
275
|
+
res.end(JSON.stringify({ success: true, data: task }));
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (req.method === 'GET' && url.pathname.includes('/api/v1/tasks/') && url.pathname.includes('/events')) {
|
|
279
|
+
const parts = url.pathname.split('/');
|
|
280
|
+
const tasksIndex = parts.indexOf('tasks');
|
|
281
|
+
const runId = parts[tasksIndex + 1];
|
|
282
|
+
const since = url.searchParams.get('since');
|
|
283
|
+
const events = this.taskRegistry.getEvents(runId, since ? Number(since) : undefined);
|
|
284
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
285
|
+
res.end(JSON.stringify({ success: true, data: events }));
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (req.method === 'POST' && url.pathname.includes('/api/v1/tasks/') && url.pathname.includes('/update')) {
|
|
289
|
+
const parts = url.pathname.split('/');
|
|
290
|
+
const tasksIndex = parts.indexOf('tasks');
|
|
291
|
+
const runId = parts[tasksIndex + 1];
|
|
292
|
+
try {
|
|
293
|
+
const payload = await this.readJsonBody(req);
|
|
294
|
+
this.taskRegistry.updateTask(runId, payload);
|
|
295
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
296
|
+
res.end(JSON.stringify({ success: true }));
|
|
297
|
+
}
|
|
298
|
+
catch (err) {
|
|
299
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
300
|
+
res.end(JSON.stringify({ success: false, error: err?.message || String(err) }));
|
|
301
|
+
}
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
if (req.method === 'POST' && url.pathname.includes('/api/v1/tasks/') && url.pathname.includes('/events')) {
|
|
305
|
+
const parts = url.pathname.split('/');
|
|
306
|
+
const tasksIndex = parts.indexOf('tasks');
|
|
307
|
+
const runId = parts[tasksIndex + 1];
|
|
308
|
+
try {
|
|
309
|
+
const event = await this.readJsonBody(req);
|
|
310
|
+
this.taskRegistry.pushEvent(runId, event.type, event.data);
|
|
311
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
312
|
+
res.end(JSON.stringify({ success: true }));
|
|
313
|
+
}
|
|
314
|
+
catch (err) {
|
|
315
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
316
|
+
res.end(JSON.stringify({ success: false, error: err?.message || String(err) }));
|
|
317
|
+
}
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (req.method === 'POST' && url.pathname.includes('/api/v1/tasks/') && url.pathname.includes('/control')) {
|
|
321
|
+
const parts = url.pathname.split('/');
|
|
322
|
+
const tasksIndex = parts.indexOf('tasks');
|
|
323
|
+
const runId = parts[tasksIndex + 1];
|
|
324
|
+
const action = url.searchParams.get('action');
|
|
325
|
+
try {
|
|
326
|
+
if (action === 'pause') {
|
|
327
|
+
this.taskRegistry.setStatus(runId, 'paused');
|
|
328
|
+
}
|
|
329
|
+
else if (action === 'resume') {
|
|
330
|
+
this.taskRegistry.setStatus(runId, 'running');
|
|
331
|
+
}
|
|
332
|
+
else if (action === 'stop') {
|
|
333
|
+
this.taskRegistry.setStatus(runId, 'aborted');
|
|
334
|
+
}
|
|
335
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
336
|
+
res.end(JSON.stringify({ success: true }));
|
|
337
|
+
}
|
|
338
|
+
catch (err) {
|
|
339
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
340
|
+
res.end(JSON.stringify({ success: false, error: err?.message || String(err) }));
|
|
341
|
+
}
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
if (req.method === 'DELETE' && url.pathname.startsWith('/api/v1/tasks/')) {
|
|
345
|
+
const parts = url.pathname.split('/');
|
|
346
|
+
const runId = parts[parts.length - 1];
|
|
347
|
+
const deleted = this.taskRegistry.deleteTask(runId);
|
|
348
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
349
|
+
res.end(JSON.stringify({ success: true, data: { deleted } }));
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
// 健康检查
|
|
353
|
+
if (url.pathname === '/health') {
|
|
354
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
355
|
+
res.end(JSON.stringify({ ok: true, service: 'unified-api', timestamp: new Date().toISOString() }));
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
// Controller actions
|
|
359
|
+
if (req.method === 'POST' && url.pathname === '/v1/controller/action') {
|
|
360
|
+
try {
|
|
361
|
+
const payload = await this.readJsonBody(req);
|
|
362
|
+
const action = payload?.action;
|
|
363
|
+
if (!action) {
|
|
364
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
365
|
+
res.end(JSON.stringify({ success: false, error: 'Missing action' }));
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
const result = await this.controller.handleAction(action, payload.payload || {});
|
|
369
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
370
|
+
res.end(JSON.stringify(this.normalizeResult(result)));
|
|
371
|
+
}
|
|
372
|
+
catch (err) {
|
|
373
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
374
|
+
res.end(JSON.stringify({ success: false, error: err?.message || String(err) }));
|
|
375
|
+
}
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
// Health check for browser service
|
|
379
|
+
if (req.method === 'GET' && url.pathname === '/v1/browser/health') {
|
|
380
|
+
try {
|
|
381
|
+
const result = await this.controller.handleAction('browser:status', {});
|
|
382
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
383
|
+
res.end(JSON.stringify(result));
|
|
384
|
+
}
|
|
385
|
+
catch (err) {
|
|
386
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
387
|
+
res.end(JSON.stringify({ success: false, error: err?.message || String(err) }));
|
|
388
|
+
}
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
// System state endpoints
|
|
392
|
+
if (req.method === 'GET' && url.pathname === '/v1/system/state') {
|
|
393
|
+
const state = this.stateRegistry.getState();
|
|
394
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
395
|
+
res.end(JSON.stringify({ success: true, data: state }));
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
if (req.method === 'GET' && url.pathname === '/v1/system/sessions') {
|
|
399
|
+
const profileId = url.searchParams.get('profileId');
|
|
400
|
+
const sessions = this.stateRegistry.getAllSessionStates();
|
|
401
|
+
if (profileId) {
|
|
402
|
+
const session = sessions[profileId];
|
|
403
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
404
|
+
res.end(JSON.stringify({ success: true, data: session ? [session] : [] }));
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
408
|
+
res.end(JSON.stringify({ success: true, data: Object.values(sessions) }));
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (req.method === 'POST' && url.pathname === '/v1/system/sessionPhase') {
|
|
412
|
+
try {
|
|
413
|
+
const payload = await this.readJsonBody(req);
|
|
414
|
+
const profileId = payload?.profileId;
|
|
415
|
+
const phase = payload?.phase;
|
|
416
|
+
if (!profileId || !phase) {
|
|
417
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
418
|
+
res.end(JSON.stringify({ success: false, error: 'Missing profileId or phase' }));
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
this.stateRegistry.updateSessionState(profileId, { lastPhase: phase });
|
|
422
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
423
|
+
res.end(JSON.stringify({ success: true }));
|
|
424
|
+
}
|
|
425
|
+
catch (err) {
|
|
426
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
427
|
+
res.end(JSON.stringify({ success: false, error: err?.message || String(err) }));
|
|
428
|
+
}
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
// WebSocket endpoints
|
|
432
|
+
if (url.pathname === '/ws' || url.pathname === '/bus') {
|
|
433
|
+
res.writeHead(426, { 'Content-Type': 'text/plain' });
|
|
434
|
+
res.end('Upgrade Required');
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
437
|
+
// Not found
|
|
438
|
+
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
|
439
|
+
res.end('Not Found');
|
|
440
|
+
})().catch((err) => {
|
|
441
|
+
// IMPORTANT: http server doesn't await async handlers; ensure no unhandledRejection kills the service.
|
|
442
|
+
logEvent('http.request.error', {
|
|
443
|
+
method: req?.method,
|
|
444
|
+
url: req?.url,
|
|
445
|
+
error: { message: err?.message || String(err), stack: err?.stack },
|
|
446
|
+
});
|
|
447
|
+
try {
|
|
448
|
+
if (!res.headersSent) {
|
|
449
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
450
|
+
}
|
|
451
|
+
res.end(JSON.stringify({ success: false, error: 'Internal Server Error' }));
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
// ignore
|
|
455
|
+
}
|
|
456
|
+
});
|
|
457
|
+
});
|
|
458
|
+
// WebSocket event handling
|
|
459
|
+
wss.on('connection', (socket, request) => {
|
|
460
|
+
const url = new URL(request.url, `http://${request.headers.host}`);
|
|
461
|
+
if (url.pathname === '/ws') {
|
|
462
|
+
this.wsClients.add(socket);
|
|
463
|
+
socket.on('message', (raw) => {
|
|
464
|
+
let message;
|
|
465
|
+
try {
|
|
466
|
+
message = JSON.parse(raw.toString());
|
|
467
|
+
}
|
|
468
|
+
catch {
|
|
469
|
+
this.safeSend(socket, { type: 'error', error: 'Invalid JSON payload' });
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
if (message?.type === 'subscribe' && message.topic) {
|
|
473
|
+
this.addSubscription(socket, message.topic);
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
if (message?.type === 'unsubscribe' && message.topic) {
|
|
477
|
+
this.removeSubscription(socket, message.topic);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
void this.handleMessage(socket, raw instanceof Buffer ? raw : Buffer.from(raw)).catch((err) => {
|
|
481
|
+
logEvent('ws.handleMessage.error', {
|
|
482
|
+
error: { message: err?.message || String(err), stack: err?.stack },
|
|
483
|
+
});
|
|
484
|
+
});
|
|
485
|
+
});
|
|
486
|
+
socket.on('close', () => {
|
|
487
|
+
this.wsClients.delete(socket);
|
|
488
|
+
this.removeSubscription(socket);
|
|
489
|
+
});
|
|
490
|
+
socket.on('error', () => {
|
|
491
|
+
this.wsClients.delete(socket);
|
|
492
|
+
this.removeSubscription(socket);
|
|
493
|
+
});
|
|
494
|
+
this.safeSend(socket, { type: 'ready' });
|
|
495
|
+
}
|
|
496
|
+
else if (url.pathname === '/bus') {
|
|
497
|
+
this.busClients.add(socket);
|
|
498
|
+
socket.on('message', (raw) => {
|
|
499
|
+
void this.handleBusMessage(socket, raw instanceof Buffer ? raw : Buffer.from(raw)).catch((err) => {
|
|
500
|
+
logEvent('ws.handleBusMessage.error', {
|
|
501
|
+
error: { message: err?.message || String(err), stack: err?.stack },
|
|
502
|
+
});
|
|
503
|
+
});
|
|
504
|
+
});
|
|
505
|
+
socket.on('close', () => this.busClients.delete(socket));
|
|
506
|
+
socket.on('error', () => this.busClients.delete(socket));
|
|
507
|
+
this.safeSend(socket, { type: 'ready' });
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
// Start server
|
|
511
|
+
const host = DEFAULT_HOST;
|
|
512
|
+
const port = DEFAULT_PORT;
|
|
513
|
+
server.listen(port, host, () => {
|
|
514
|
+
console.log(`[unified-api] Server running at http://${host}:${port}`);
|
|
515
|
+
console.log(`[unified-api] WebSocket endpoint: ws://${host}:${port}/ws`);
|
|
516
|
+
console.log(`[unified-api] Bus endpoint: ws://${host}:${port}/bus`);
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
async handleMessage(socket, raw) {
|
|
520
|
+
let envelope;
|
|
521
|
+
try {
|
|
522
|
+
envelope = JSON.parse(raw.toString());
|
|
523
|
+
}
|
|
524
|
+
catch (err) {
|
|
525
|
+
this.safeSend(socket, { type: 'error', error: 'Invalid JSON payload' });
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
if (!envelope)
|
|
529
|
+
return;
|
|
530
|
+
console.log('[unified-api] recv', envelope.type || 'unknown', envelope.action || envelope.topic || '');
|
|
531
|
+
if (envelope.type === 'ping') {
|
|
532
|
+
this.safeSend(socket, { type: 'pong', requestId: envelope.requestId });
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
if (envelope.type === 'action' || envelope.action) {
|
|
536
|
+
const action = envelope.action;
|
|
537
|
+
const payload = envelope.payload || {};
|
|
538
|
+
const requestId = envelope.requestId || envelope.id;
|
|
539
|
+
if (!action) {
|
|
540
|
+
this.safeSend(socket, { type: 'response', requestId, success: false, error: 'Missing action' });
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
try {
|
|
544
|
+
const result = await this.controller.handleAction(action, payload);
|
|
545
|
+
console.log('[unified-api] action result', action, !!result && typeof result);
|
|
546
|
+
this.safeSend(socket, { type: 'response', action, requestId, ...this.normalizeResult(result) });
|
|
547
|
+
}
|
|
548
|
+
catch (err) {
|
|
549
|
+
console.warn('[unified-api] action failed', action, err?.message || err);
|
|
550
|
+
this.safeSend(socket, { type: 'response', action, requestId, success: false, error: err?.message || String(err) });
|
|
551
|
+
}
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
this.safeSend(socket, { type: 'error', requestId: envelope.requestId, error: 'Unsupported message type' });
|
|
555
|
+
}
|
|
556
|
+
async handleBusMessage(socket, raw) {
|
|
557
|
+
this.broadcastEvent('bus.message', { data: raw.toString(), timestamp: new Date().toISOString() });
|
|
558
|
+
}
|
|
559
|
+
safeSend(socket, payload) {
|
|
560
|
+
if (!socket || socket.readyState !== WebSocket.OPEN)
|
|
561
|
+
return;
|
|
562
|
+
try {
|
|
563
|
+
socket.send(JSON.stringify(payload));
|
|
564
|
+
}
|
|
565
|
+
catch (err) {
|
|
566
|
+
console.warn('[unified-api] send failed', err?.message || err);
|
|
567
|
+
logEvent('ws.send.error', {
|
|
568
|
+
error: { message: err?.message || String(err), stack: err?.stack },
|
|
569
|
+
payloadType: typeof payload,
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
normalizeResult(result) {
|
|
574
|
+
if (!result || typeof result !== 'object')
|
|
575
|
+
return { success: true, data: result };
|
|
576
|
+
if (typeof result.success === 'boolean')
|
|
577
|
+
return result;
|
|
578
|
+
return { success: true, data: result };
|
|
579
|
+
}
|
|
580
|
+
setupTaskRoutes() {
|
|
581
|
+
// Subscribe to task state updates and broadcast to WebSocket clients
|
|
582
|
+
this.taskRegistry.subscribe((update) => {
|
|
583
|
+
const message = {
|
|
584
|
+
type: 'task:update',
|
|
585
|
+
data: update,
|
|
586
|
+
timestamp: Date.now()
|
|
587
|
+
};
|
|
588
|
+
this.wsClients.forEach((socket) => {
|
|
589
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
590
|
+
this.safeSend(socket, message);
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
// Persist to disk
|
|
594
|
+
if (update.type === 'event') {
|
|
595
|
+
appendEvent(update.data);
|
|
596
|
+
}
|
|
597
|
+
else {
|
|
598
|
+
const task = this.taskRegistry.getTask(update.runId);
|
|
599
|
+
if (task)
|
|
600
|
+
saveTaskSnapshot(task);
|
|
601
|
+
}
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
// ============================================================================
|
|
606
|
+
// Global Error Handlers (防止进程静默退出)
|
|
607
|
+
// ============================================================================
|
|
608
|
+
// 捕获未处理的 Promise rejection
|
|
609
|
+
process.on('unhandledRejection', (reason, promise) => {
|
|
610
|
+
console.error('[unified-api] UNHANDLED PROMISE REJECTION:', reason);
|
|
611
|
+
logEvent('process.unhandledRejection', {
|
|
612
|
+
reason: String(reason),
|
|
613
|
+
stack: reason instanceof Error ? reason.stack : undefined,
|
|
614
|
+
promise: String(promise),
|
|
615
|
+
});
|
|
616
|
+
// 不退出进程,只记录错误
|
|
617
|
+
});
|
|
618
|
+
// 捕获未捕获的异常
|
|
619
|
+
process.on('uncaughtException', (err) => {
|
|
620
|
+
console.error('[unified-api] UNCAUGHT EXCEPTION:', err);
|
|
621
|
+
logEvent('process.uncaughtException', {
|
|
622
|
+
error: { message: err?.message || String(err), stack: err?.stack },
|
|
623
|
+
});
|
|
624
|
+
// 不立即退出,给现有请求完成的机会
|
|
625
|
+
setTimeout(() => {
|
|
626
|
+
console.error('[unified-api] Exiting due to uncaught exception');
|
|
627
|
+
process.exit(1);
|
|
628
|
+
}, 5000);
|
|
629
|
+
});
|
|
630
|
+
// 监听进程退出信号
|
|
631
|
+
process.on('SIGTERM', () => {
|
|
632
|
+
console.log('[unified-api] Received SIGTERM, shutting down gracefully');
|
|
633
|
+
logEvent('process.SIGTERM', {});
|
|
634
|
+
setTimeout(() => process.exit(0), 1000);
|
|
635
|
+
});
|
|
636
|
+
process.on('SIGINT', () => {
|
|
637
|
+
console.log('[unified-api] Received SIGINT, shutting down gracefully');
|
|
638
|
+
logEvent('process.SIGINT', {});
|
|
639
|
+
setTimeout(() => process.exit(0), 1000);
|
|
640
|
+
});
|
|
641
|
+
// ============================================================================
|
|
642
|
+
// Start Server
|
|
643
|
+
// ============================================================================
|
|
644
|
+
const server = new UnifiedApiServer();
|
|
645
|
+
server.start().catch(err => {
|
|
646
|
+
console.error('[unified-api] Server failed to start:', err);
|
|
647
|
+
logEvent('server.start.error', {
|
|
648
|
+
error: { message: err?.message || String(err), stack: err?.stack },
|
|
649
|
+
});
|
|
650
|
+
process.exit(1);
|
|
651
|
+
});
|
|
652
|
+
//# sourceMappingURL=server.js.map
|