@firstpick/pi-package-webui 0.11.1 → 0.11.3
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/DEVELOPMENT.md +151 -12
- package/README.md +34 -6
- package/TECHNICAL.md +75 -8
- package/bin/pi-webui.mjs +5390 -11423
- package/index.ts +10 -3
- package/lib/component-update-state.mjs +2 -2
- package/lib/git-workflow-preference-values.mjs +122 -0
- package/lib/git-workflow-preferences.mjs +35 -563
- package/lib/package-updates.mjs +260 -0
- package/lib/rpc-supervisor-client.mjs +8 -4
- package/lib/server/app-runners.mjs +1667 -0
- package/lib/server/codex-fast-mode.mjs +161 -0
- package/lib/server/conversation-mode.mjs +218 -0
- package/lib/server/conversation-voice.mjs +318 -0
- package/lib/server/extension-ui-requests.mjs +114 -0
- package/lib/server/git-generation.mjs +459 -0
- package/lib/server/git-mutations.mjs +1827 -0
- package/lib/server/git-reads.mjs +608 -0
- package/lib/server/git-worktree-sessions.mjs +408 -0
- package/lib/server/helper-requests.mjs +82 -0
- package/lib/server/no-project-workspaces.mjs +103 -0
- package/lib/server/rpc-transports.mjs +394 -0
- package/lib/server/settings-store.mjs +544 -0
- package/lib/server/sse-delivery.mjs +138 -0
- package/lib/server/workspace-files.mjs +563 -0
- package/lib/update/supervisor.mjs +4 -0
- package/lib/webui-workspaces.mjs +2 -0
- package/package.json +4 -4
- package/public/activity-agents-controller.mjs +269 -0
- package/public/activity-events-controller.mjs +236 -0
- package/public/activity-intercom-controller.mjs +627 -0
- package/public/activity-queue-controller.mjs +534 -0
- package/public/activity-todo-view.mjs +89 -0
- package/public/activity-usage-controller.mjs +589 -0
- package/public/app.js +3761 -3886
- package/public/conversation-overview.css +84 -0
- package/public/conversation-overview.mjs +193 -0
- package/public/draft-conversations.mjs +135 -0
- package/public/focused-composer-controls.css +111 -0
- package/public/focused-composer-controls.mjs +143 -0
- package/public/focused-composer-disclosure.mjs +223 -0
- package/public/focused-shell-adapter.css +264 -0
- package/public/focused-shell-adapter.mjs +257 -0
- package/public/index.html +137 -80
- package/public/model-catalog-order.mjs +63 -0
- package/public/platform-event-stream.mjs +64 -0
- package/public/project-artifact-controller.mjs +218 -0
- package/public/project-file-viewer-controller.mjs +383 -0
- package/public/project-git-tools-controller.mjs +181 -0
- package/public/project-runners-controller.mjs +220 -0
- package/public/service-worker.js +52 -1
- package/public/session-attention-scheduler.mjs +182 -0
- package/public/session-composer-store.mjs +56 -0
- package/public/session-context.mjs +51 -0
- package/public/session-extension-requests.mjs +63 -0
- package/public/session-shelf-state.mjs +151 -0
- package/public/session-shelves.css +171 -0
- package/public/session-shelves.mjs +95 -0
- package/public/settings-navigation-controller.mjs +249 -0
- package/public/settings-navigation.css +61 -0
- package/public/settings-resource-controller.mjs +232 -0
- package/public/settings-workspace.css +19 -0
- package/public/settings-workspace.mjs +175 -0
- package/public/shell-actions.mjs +87 -0
- package/public/shell-attention-inbox.css +72 -0
- package/public/shell-attention-inbox.mjs +198 -0
- package/public/shell-context-actions.css +61 -0
- package/public/shell-context-actions.mjs +168 -0
- package/public/shell-inspector-resize.mjs +124 -0
- package/public/shell-navigation-resize.mjs +107 -0
- package/public/shell-navigation.mjs +127 -0
- package/public/shell-preferences.mjs +108 -0
- package/public/shell-surfaces.mjs +99 -0
- package/public/shell-tools-launcher.css +97 -0
- package/public/shell-tools-launcher.mjs +222 -0
- package/public/shell-view-host.mjs +115 -0
- package/public/shell-workspace.css +266 -0
- package/public/shell-workspace.mjs +402 -0
- package/public/sidebar-update-menu.css +190 -0
- package/public/sidebar-update-menu.mjs +512 -0
- package/public/styles.css +322 -169
- package/public/subagent-launch-slot-state.mjs +2 -2
- package/public/themed-selects.css +156 -0
- package/public/workspace-choices.mjs +104 -0
- package/tests/activity-agents-controller.test.mjs +652 -0
- package/tests/activity-events-controller.test.mjs +511 -0
- package/tests/app-runner-terminal-static.test.mjs +3 -3
- package/tests/append-system-http.test.mjs +7 -6
- package/tests/append-system-selector-static.test.mjs +6 -6
- package/tests/aur-review-widget-static.test.mjs +11 -3
- package/tests/boot-failure-diagnostics.test.mjs +8 -3
- package/tests/browser/action-feedback-gutter.spec.mjs +251 -0
- package/tests/browser/activity-intercom-controller.spec.mjs +457 -0
- package/tests/browser/activity-navigation-integration.spec.mjs +45 -0
- package/tests/browser/activity-owner-integration.spec.mjs +201 -0
- package/tests/browser/activity-queue-controller.spec.mjs +405 -0
- package/tests/browser/activity-section-picker.spec.mjs +294 -0
- package/tests/browser/activity-todo-view.spec.mjs +60 -0
- package/tests/browser/activity-usage-controller.spec.mjs +416 -0
- package/tests/browser/compact-layout-integration.spec.mjs +58 -0
- package/tests/browser/composer-action-grid-reorder.spec.mjs +16 -0
- package/tests/browser/composer-disclosure.spec.mjs +389 -0
- package/tests/browser/composer-toolbar-polish.spec.mjs +343 -0
- package/tests/browser/control-deck-component-updates.spec.mjs +5 -14
- package/tests/browser/control-deck-side-panels.spec.mjs +27 -12
- package/tests/browser/control-visibility.spec.mjs +5 -0
- package/tests/browser/controls-layout.spec.mjs +21 -2
- package/tests/browser/conversation-overview.spec.mjs +251 -0
- package/tests/browser/draft-conversations.spec.mjs +276 -0
- package/tests/browser/empty-startup-fixture.mjs +135 -0
- package/tests/browser/empty-startup.spec.mjs +282 -0
- package/tests/browser/events-tree-context-menu.spec.mjs +1 -0
- package/tests/browser/focused-composer-more.spec.mjs +127 -0
- package/tests/browser/focused-model-shortcuts.spec.mjs +120 -0
- package/tests/browser/focused-navigation-fixture.mjs +32 -0
- package/tests/browser/focused-project-activity.spec.mjs +111 -0
- package/tests/browser/focused-shell-integration.spec.mjs +208 -0
- package/tests/browser/folder-picker-layout-fixture.mjs +13 -0
- package/tests/browser/folder-picker-layout.spec.mjs +302 -0
- package/tests/browser/footer-model-advanced-layout.spec.mjs +27 -14
- package/tests/browser/git-setup-cancel.spec.mjs +251 -0
- package/tests/browser/guided-git-fallback.spec.mjs +40 -21
- package/tests/browser/inspector-header.spec.mjs +221 -0
- package/tests/browser/inspector-overview-integration.spec.mjs +104 -0
- package/tests/browser/inspector-resize.spec.mjs +227 -0
- package/tests/browser/inspector-topic-overflow.spec.mjs +56 -0
- package/tests/browser/interaction-action-discovery.spec.mjs +332 -0
- package/tests/browser/interaction-attention-inbox.spec.mjs +364 -0
- package/tests/browser/interaction-attention-integration.spec.mjs +53 -0
- package/tests/browser/interaction-composer-controls.spec.mjs +267 -0
- package/tests/browser/interaction-composer-integration.spec.mjs +175 -0
- package/tests/browser/interaction-continuity.spec.mjs +50 -26
- package/tests/browser/interaction-model-picker.spec.mjs +86 -0
- package/tests/browser/last-terminal-close.spec.mjs +280 -0
- package/tests/browser/mobile-foundation.spec.mjs +172 -20
- package/tests/browser/model-catalog-groups.spec.mjs +104 -0
- package/tests/browser/more-row-menus.spec.mjs +258 -0
- package/tests/browser/new-tab-hit-target.spec.mjs +228 -0
- package/tests/browser/no-project-conversation.spec.mjs +113 -0
- package/tests/browser/optimistic-prompt.spec.mjs +3 -0
- package/tests/browser/overhaul-w7-accessibility.spec.mjs +227 -0
- package/tests/browser/overhaul-w7-capabilities.spec.mjs +298 -0
- package/tests/browser/overhaul-w7-companions.spec.mjs +290 -0
- package/tests/browser/overhaul-w7-focus-repairs.spec.mjs +210 -0
- package/tests/browser/overhaul-w7-layout-repairs.spec.mjs +183 -0
- package/tests/browser/overhaul-w7-parent-repairs.spec.mjs +97 -0
- package/tests/browser/overhaul-w7-pwa.spec.mjs +247 -0
- package/tests/browser/overhaul-w7-responsive.spec.mjs +450 -0
- package/tests/browser/overhaul-w7-update.spec.mjs +215 -0
- package/tests/browser/overhaul-w7-zoom.spec.mjs +243 -0
- package/tests/browser/overview-agent-ownership.spec.mjs +45 -0
- package/tests/browser/persistent-ui-layout.spec.mjs +3 -0
- package/tests/browser/project-artifact-controller.spec.mjs +324 -0
- package/tests/browser/project-artifact-integration.spec.mjs +103 -0
- package/tests/browser/project-file-buffer-integration.spec.mjs +230 -0
- package/tests/browser/project-git-tools-integration.spec.mjs +369 -0
- package/tests/browser/session-fixture.mjs +118 -0
- package/tests/browser/session-ownership.spec.mjs +175 -0
- package/tests/browser/session-shelves-integration.spec.mjs +219 -0
- package/tests/browser/session-shelves.spec.mjs +340 -0
- package/tests/browser/session-sidebar-resize.spec.mjs +138 -0
- package/tests/browser/session-summary.spec.mjs +17 -12
- package/tests/browser/settings-complete-home.spec.mjs +463 -0
- package/tests/browser/settings-entrypoint.spec.mjs +104 -0
- package/tests/browser/settings-navigation-controller.spec.mjs +383 -0
- package/tests/browser/settings-navigation-integration.spec.mjs +348 -0
- package/tests/browser/settings-resource-lifetime.spec.mjs +349 -0
- package/tests/browser/settings-workspace-integration.spec.mjs +132 -0
- package/tests/browser/shell-ownership.spec.mjs +398 -0
- package/tests/browser/shell-rollout-fixture.mjs +259 -0
- package/tests/browser/shell-rollout.spec.mjs +357 -0
- package/tests/browser/shell-tools-launcher.spec.mjs +260 -0
- package/tests/browser/shell-workspace.spec.mjs +433 -0
- package/tests/browser/side-panel-section-reorder.spec.mjs +3 -1
- package/tests/browser/sidebar-floating-tooltips.spec.mjs +37 -0
- package/tests/browser/sidebar-update-integration.spec.mjs +277 -0
- package/tests/browser/sidebar-update-menu.spec.mjs +402 -0
- package/tests/browser/sidebar-update-progress.spec.mjs +472 -0
- package/tests/browser/stream-output-isolation.spec.mjs +6 -3
- package/tests/browser/themed-selects.spec.mjs +297 -0
- package/tests/browser/thread-start-flow.spec.mjs +481 -0
- package/tests/browser/ui-polish-activity-controls.spec.mjs +177 -0
- package/tests/browser/ui-polish-features.spec.mjs +85 -0
- package/tests/browser/ui-polish-file-header.spec.mjs +43 -0
- package/tests/browser/ui-polish-local-git.spec.mjs +183 -0
- package/tests/browser/ui-polish-mobile-recovery.spec.mjs +36 -0
- package/tests/browser/ui-polish-navigation.spec.mjs +127 -0
- package/tests/browser/ui-polish-session-actions.spec.mjs +282 -0
- package/tests/browser/user-noticeable-fixes.spec.mjs +10 -3
- package/tests/browser/windows-drive-parent.spec.mjs +4 -2
- package/tests/browser/workspace-draft-selection.spec.mjs +266 -0
- package/tests/codex-fast-mode-static.test.mjs +16 -11
- package/tests/codex-speed-mode-browser-state.test.mjs +6 -3
- package/tests/codex-usage-source.test.mjs +4 -3
- package/tests/component-update-api-static.test.mjs +2 -2
- package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
- package/tests/control-deck-component-updates-static.test.mjs +9 -4
- package/tests/control-visibility-static.test.mjs +3 -3
- package/tests/controls-layout-static.test.mjs +5 -5
- package/tests/conversation-overview-adapter.test.mjs +100 -0
- package/tests/document-artifact-static.test.mjs +2 -1
- package/tests/draft-conversations.test.mjs +205 -0
- package/tests/empty-startup-launcher.test.mjs +197 -0
- package/tests/events-tree-context-menu-static.test.mjs +22 -18
- package/tests/fake-pi-session-ownership.test.mjs +302 -0
- package/tests/fast-mode-client-static.test.mjs +1 -1
- package/tests/feature-decision-output-popup-static.test.mjs +2 -2
- package/tests/feature-system-prompt-optional-feature-static.test.mjs +1 -1
- package/tests/file-viewer-image-static.test.mjs +15 -11
- package/tests/file-viewer-search-static.test.mjs +5 -5
- package/tests/fixtures/fake-pi.mjs +41 -9
- package/tests/footer-provider-usage-visual-static.test.mjs +7 -6
- package/tests/foreground-transcript-catch-up-static.test.mjs +7 -4
- package/tests/git-footer-context-menu-static.test.mjs +1 -1
- package/tests/git-panel-file-preview-static.test.mjs +41 -48
- package/tests/git-panel-live-updates-static.test.mjs +2 -1
- package/tests/git-workflow-dispatch.test.mjs +66 -0
- package/tests/git-workflow-preferences.test.mjs +9 -1
- package/tests/guided-git-activation-static.test.mjs +14 -11
- package/tests/guided-git-fallback-ui-static.test.mjs +8 -5
- package/tests/guided-git-message-reliability-static.test.mjs +10 -6
- package/tests/guided-git-publication-backend-static.test.mjs +16 -11
- package/tests/http-endpoints-harness.test.mjs +21 -9
- package/tests/interaction-state-stability-static.test.mjs +4 -3
- package/tests/intercom-conversation-viewer-static.test.mjs +29 -17
- package/tests/intercom-tag-layout-static.test.mjs +13 -12
- package/tests/intercom-tag-overflow-layout.test.mjs +11 -10
- package/tests/main-output-loading-static.test.mjs +4 -4
- package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
- package/tests/mobile-compact-layout.test.mjs +2 -2
- package/tests/mobile-continuity-tablet-static.test.mjs +3 -3
- package/tests/mobile-foundation-static.test.mjs +10 -7
- package/tests/mobile-phone-experience-static.test.mjs +3 -2
- package/tests/mobile-static.test.mjs +173 -135
- package/tests/model-catalog-order.test.mjs +103 -0
- package/tests/native-parity.test.mjs +6 -4
- package/tests/native-session-choice-owner.test.mjs +102 -0
- package/tests/native-update-lifecycle.test.mjs +10 -5
- package/tests/no-project-http-harness.test.mjs +328 -0
- package/tests/no-project-navigation.test.mjs +54 -0
- package/tests/no-project-workspaces.test.mjs +77 -0
- package/tests/open-issue-wizard-static.test.mjs +1 -1
- package/tests/optional-feature-migration-frontend.test.mjs +4 -4
- package/tests/optional-feature-prompt-impact-static.test.mjs +3 -3
- package/tests/package-updates.test.mjs +630 -0
- package/tests/persistent-ui-layout-static.test.mjs +3 -3
- package/tests/platform-event-stream.test.mjs +253 -0
- package/tests/project-file-viewer-controller.test.mjs +652 -0
- package/tests/project-git-tools-adapter.test.mjs +103 -0
- package/tests/project-git-tools-controller.test.mjs +577 -0
- package/tests/project-runners-controller.test.mjs +453 -0
- package/tests/prompt-input-vertical-scroll-static.test.mjs +3 -3
- package/tests/prompt-routing-input-clear-static.test.mjs +2 -2
- package/tests/questionnaire-dialog.test.mjs +6 -6
- package/tests/queue-edit-reorder-static.test.mjs +48 -51
- package/tests/rpc-supervisor-host.test.mjs +4 -1
- package/tests/safety-guard-auto-review-static.test.mjs +1 -1
- package/tests/sampling-native-controls-user-flow.test.mjs +7 -1
- package/tests/server-app-runners.test.mjs +536 -0
- package/tests/server-codex-fast-mode.test.mjs +346 -0
- package/tests/server-conversation-mode.test.mjs +386 -0
- package/tests/server-conversation-voice.test.mjs +426 -0
- package/tests/server-extension-ui-requests.test.mjs +357 -0
- package/tests/server-git-generation.test.mjs +558 -0
- package/tests/server-git-mutations.test.mjs +729 -0
- package/tests/server-git-reads.test.mjs +381 -0
- package/tests/server-git-worktree-sessions.test.mjs +502 -0
- package/tests/server-helper-requests.test.mjs +364 -0
- package/tests/server-rpc-transports.test.mjs +553 -0
- package/tests/server-settings-store.test.mjs +132 -0
- package/tests/server-shell-rollout.test.mjs +478 -0
- package/tests/server-sse-delivery.test.mjs +410 -0
- package/tests/server-workspace-files.test.mjs +546 -0
- package/tests/session-attention-scheduler.test.mjs +514 -0
- package/tests/session-composer-store.test.mjs +153 -0
- package/tests/session-context.test.mjs +134 -0
- package/tests/session-extension-requests.test.mjs +193 -0
- package/tests/session-ownership-adapter.test.mjs +130 -0
- package/tests/session-sampling-ui-static.test.mjs +10 -4
- package/tests/session-send-lifetime.test.mjs +140 -0
- package/tests/session-shelf-state.test.mjs +348 -0
- package/tests/session-shelves-adapter.test.mjs +79 -0
- package/tests/session-summary-lifetime.test.mjs +54 -0
- package/tests/settings-resource-controller.test.mjs +548 -0
- package/tests/shell-action-adapter.test.mjs +169 -0
- package/tests/shell-actions.test.mjs +182 -0
- package/tests/shell-navigation.test.mjs +348 -0
- package/tests/shell-preferences.test.mjs +367 -0
- package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
- package/tests/stream-output-isolation-static.test.mjs +1 -1
- package/tests/subagent-gate-visibility.test.mjs +1 -1
- package/tests/subagent-launch-slot-state.test.mjs +2 -2
- package/tests/subagent-launch-slots-static.test.mjs +1 -1
- package/tests/subagent-observability-static.test.mjs +2 -2
- package/tests/subagent-reliability-integration.test.mjs +13 -30
- package/tests/syntax-highlighting-static.test.mjs +3 -3
- package/tests/tab-close-continuity-static.test.mjs +1 -1
- package/tests/tab-metadata-ordering.test.mjs +99 -0
- package/tests/terminal-cwd-grouping-static.test.mjs +2 -2
- package/tests/terminal-tab-prompt-tooltip-static.test.mjs +2 -0
- package/tests/terminal-tab-workspace-static.test.mjs +5 -4
- package/tests/terminal-tabs-resize-static.test.mjs +1 -1
- package/tests/theme-customizer-static.test.mjs +1 -1
- package/tests/thread-display-title.test.mjs +44 -0
- package/tests/update-api-harness.test.mjs +15 -14
- package/tests/update-tab-restore-harness.test.mjs +3 -0
- package/tests/webui-settings-locking.test.mjs +2 -2
- package/tests/windows-drive-cwd-picker-static.test.mjs +7 -9
- package/tests/workspace-choices.test.mjs +114 -0
- package/tests/workspace-save-load-static.test.mjs +7 -4
|
@@ -0,0 +1,1667 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { access, open, readFile, readdir, realpath, rename, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { terminateProcessTree } from "../process-tree.mjs";
|
|
6
|
+
import { consumeAppRunnerTerminalChunk } from "../app-runner-terminal.mjs";
|
|
7
|
+
|
|
8
|
+
const APP_RUNNER_CONFIG_FILE = ".pi-webui-runners.json";
|
|
9
|
+
const APP_RUNNER_CUSTOM_LIMIT = 48;
|
|
10
|
+
const APP_RUNNER_CUSTOM_ARG_LIMIT = 32;
|
|
11
|
+
const APP_RUNNER_SEARCH_PATH_LIMIT = 24;
|
|
12
|
+
const APP_RUNNER_SEARCH_PATH_MAX_CHARS = 4_096;
|
|
13
|
+
const APP_RUNNER_FILE_PICKER_LIMIT = 500;
|
|
14
|
+
const APP_RUNNER_DETECTION_TIMEOUT_MS = 1_200;
|
|
15
|
+
const APP_RUNNER_COMMAND_CACHE_TTL_MS = 30_000;
|
|
16
|
+
const APP_RUNNER_OUTPUT_LINE_LIMIT = 1_000;
|
|
17
|
+
const APP_RUNNER_OUTPUT_MAX_CHARS = 240_000;
|
|
18
|
+
const APP_RUNNER_INPUT_MAX_CHARS = 16_000;
|
|
19
|
+
const APP_RUNNER_CONTEXT_DEFAULT_LINES = 80;
|
|
20
|
+
const APP_RUNNER_CONTEXT_MAX_LINES = APP_RUNNER_OUTPUT_LINE_LIMIT;
|
|
21
|
+
const APP_RUNNER_STOP_GRACE_MS = 2_500;
|
|
22
|
+
const APP_RUNNER_PTY_DISABLED_VALUES = new Set(["0", "false", "no", "off"]);
|
|
23
|
+
const APP_RUNNER_PTY_SCRIPT_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
24
|
+
const APP_RUNNER_PYTHON_ENTRIES = ["Main.py", "main.py", "src/main.py", "src/Main.py", "app.py", "src/app.py"];
|
|
25
|
+
const APP_RUNNER_JS_ENTRIES = ["main.js", "src/main.js", "index.js", "src/index.js", "server.js", "src/server.js", "app.js", "src/app.js"];
|
|
26
|
+
const APP_RUNNER_ZIG_ENTRIES = ["src/main.zig", "main.zig"];
|
|
27
|
+
const APP_RUNNER_C_ENTRIES = ["main.c", "src/main.c"];
|
|
28
|
+
const APP_RUNNER_CPP_ENTRIES = ["main.cpp", "src/main.cpp", "main.cc", "src/main.cc", "main.cxx", "src/main.cxx"];
|
|
29
|
+
const APP_RUNNER_DOCKER_COMPOSE_FILES = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
|
|
30
|
+
const APP_RUNNER_SHELL_SCRIPT_DIRS = ["", "dev", "scripts", "dev/scripts"];
|
|
31
|
+
const APP_RUNNER_SHELL_SCRIPT_LIMIT = 24;
|
|
32
|
+
const APP_RUNNER_PYTHON_SCRIPT_LIMIT = 24;
|
|
33
|
+
const APP_RUNNER_CONFIGURED_SCRIPT_SCAN_LIMIT = (APP_RUNNER_SHELL_SCRIPT_LIMIT + APP_RUNNER_PYTHON_SCRIPT_LIMIT) * 2;
|
|
34
|
+
const APP_RUNNER_SHELL_EXTENSIONS = new Map([
|
|
35
|
+
[".sh", "bash"],
|
|
36
|
+
[".bash", "bash"],
|
|
37
|
+
[".zsh", "zsh"],
|
|
38
|
+
[".fish", "fish"],
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
function formatCommandForDisplay(command, args) {
|
|
42
|
+
return [command, ...args].map((part) => (/\s/.test(part) ? JSON.stringify(part) : part)).join(" ");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Create one runner owner per server. Runs and timers stay on the supplied tab
|
|
47
|
+
* records; the caller stops them when a tab, cwd or server is retired.
|
|
48
|
+
*/
|
|
49
|
+
export function createAppRunnerService({
|
|
50
|
+
defaultCwd,
|
|
51
|
+
runCommand,
|
|
52
|
+
resolveCwd,
|
|
53
|
+
normalizeSuggestionPath,
|
|
54
|
+
readJsonFileIfExists,
|
|
55
|
+
makeHttpError,
|
|
56
|
+
formatCliError,
|
|
57
|
+
sanitizeError,
|
|
58
|
+
displayPath,
|
|
59
|
+
stripAnsi,
|
|
60
|
+
hasTab,
|
|
61
|
+
broadcastTabEvent,
|
|
62
|
+
tabActivitySnapshot,
|
|
63
|
+
recordEvent,
|
|
64
|
+
sendWebuiHelperCommand,
|
|
65
|
+
}) {
|
|
66
|
+
const appRunnerCommandAvailability = new Map();
|
|
67
|
+
let appRunnerPtyScriptAvailability = { available: false, expiresAt: 0 };
|
|
68
|
+
let appRunnerNodePtyPromise = null;
|
|
69
|
+
|
|
70
|
+
async function fileStatsIfExists(filePath) {
|
|
71
|
+
try {
|
|
72
|
+
return await stat(filePath);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (error?.code === "ENOENT" || error?.code === "ENOTDIR") return null;
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function appRunnerFileExists(cwd, relativePath) {
|
|
80
|
+
const stats = await fileStatsIfExists(path.join(cwd, relativePath));
|
|
81
|
+
return !!stats?.isFile();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function appRunnerDirectoryExists(cwd, relativePath) {
|
|
85
|
+
const stats = await fileStatsIfExists(path.join(cwd, relativePath));
|
|
86
|
+
return !!stats?.isDirectory();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function appRunnerTextIfExists(cwd, relativePath, maxLength = 120_000) {
|
|
90
|
+
try {
|
|
91
|
+
const text = await readFile(path.join(cwd, relativePath), "utf8");
|
|
92
|
+
return text.slice(0, maxLength);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (error?.code === "ENOENT" || error?.code === "ENOTDIR") return "";
|
|
95
|
+
return "";
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function appRunnerFilePrefix(filePath, maxLength = 256) {
|
|
100
|
+
let handle;
|
|
101
|
+
try {
|
|
102
|
+
handle = await open(filePath, "r");
|
|
103
|
+
const buffer = Buffer.alloc(maxLength);
|
|
104
|
+
const { bytesRead } = await handle.read(buffer, 0, maxLength, 0);
|
|
105
|
+
return buffer.subarray(0, bytesRead).toString("utf8");
|
|
106
|
+
} catch {
|
|
107
|
+
return "";
|
|
108
|
+
} finally {
|
|
109
|
+
await handle?.close().catch(() => {});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function firstExistingRunnerFile(cwd, candidates) {
|
|
114
|
+
for (const candidate of candidates) {
|
|
115
|
+
if (await appRunnerFileExists(cwd, candidate)) return candidate;
|
|
116
|
+
}
|
|
117
|
+
return "";
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function appRunnerCommandAvailable(command, cwd) {
|
|
121
|
+
const name = String(command || "").trim();
|
|
122
|
+
if (!name) return false;
|
|
123
|
+
const key = `${name}\0${cwd || ""}`;
|
|
124
|
+
const cached = appRunnerCommandAvailability.get(key);
|
|
125
|
+
const now = Date.now();
|
|
126
|
+
if (cached && cached.expiresAt > now) return cached.available;
|
|
127
|
+
|
|
128
|
+
const result = await runCommand(name, ["--version"], {
|
|
129
|
+
cwd,
|
|
130
|
+
timeoutMs: APP_RUNNER_DETECTION_TIMEOUT_MS,
|
|
131
|
+
maxOutputLength: 2_000,
|
|
132
|
+
});
|
|
133
|
+
const available = !result.error && !result.timedOut && (result.exitCode === 0 || Boolean(result.stdout || result.stderr));
|
|
134
|
+
appRunnerCommandAvailability.set(key, { available, expiresAt: now + APP_RUNNER_COMMAND_CACHE_TTL_MS });
|
|
135
|
+
return available;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function appRunnerPtyDisabled() {
|
|
139
|
+
return APP_RUNNER_PTY_DISABLED_VALUES.has(String(process.env.PI_WEBUI_APP_RUNNER_PTY || "").trim().toLowerCase());
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function appRunnerWindowsPty() {
|
|
143
|
+
if (process.platform !== "win32" || appRunnerPtyDisabled()) return null;
|
|
144
|
+
if (!appRunnerNodePtyPromise) {
|
|
145
|
+
appRunnerNodePtyPromise = import("node-pty")
|
|
146
|
+
.then((module) => module?.spawn ? module : module?.default?.spawn ? module.default : null)
|
|
147
|
+
.catch(() => null);
|
|
148
|
+
}
|
|
149
|
+
return appRunnerNodePtyPromise;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function resolveWindowsAppRunnerExecutable(command, cwd) {
|
|
153
|
+
const value = String(command || "").trim();
|
|
154
|
+
if (process.platform !== "win32" || !value) return value;
|
|
155
|
+
const hasDirectory = path.isAbsolute(value) || value.includes("/") || value.includes("\\");
|
|
156
|
+
const bases = hasDirectory
|
|
157
|
+
? [path.isAbsolute(value) ? value : path.resolve(cwd, value)]
|
|
158
|
+
: String(process.env.PATH || process.env.Path || "").split(path.delimiter).filter(Boolean).map((directory) => path.join(directory, value));
|
|
159
|
+
const extensions = path.extname(value)
|
|
160
|
+
? [""]
|
|
161
|
+
: String(process.env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((extension) => extension.toLowerCase()).concat("");
|
|
162
|
+
for (const base of bases) {
|
|
163
|
+
for (const extension of extensions) {
|
|
164
|
+
const candidate = `${base}${extension}`;
|
|
165
|
+
try {
|
|
166
|
+
await access(candidate);
|
|
167
|
+
return candidate;
|
|
168
|
+
} catch {
|
|
169
|
+
// Keep searching PATH/PATHEXT.
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return value;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function appRunnerScriptPtyAvailable(cwd) {
|
|
177
|
+
if (process.platform === "win32" || appRunnerPtyDisabled()) return false;
|
|
178
|
+
const now = Date.now();
|
|
179
|
+
if (appRunnerPtyScriptAvailability.expiresAt > now) return appRunnerPtyScriptAvailability.available;
|
|
180
|
+
const result = await runCommand("script", ["--version"], {
|
|
181
|
+
cwd,
|
|
182
|
+
timeoutMs: APP_RUNNER_DETECTION_TIMEOUT_MS,
|
|
183
|
+
maxOutputLength: 4_000,
|
|
184
|
+
});
|
|
185
|
+
const output = `${result.stdout || ""}\n${result.stderr || ""}`;
|
|
186
|
+
const available = !result.error && !result.timedOut && /util-linux/i.test(output);
|
|
187
|
+
appRunnerPtyScriptAvailability = { available, expiresAt: now + APP_RUNNER_PTY_SCRIPT_CACHE_TTL_MS };
|
|
188
|
+
return available;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function appRunnerPackageScripts(pkg) {
|
|
192
|
+
return pkg && typeof pkg.scripts === "object" && pkg.scripts ? pkg.scripts : {};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function preferredPackageScript(pkg) {
|
|
196
|
+
const scripts = appRunnerPackageScripts(pkg);
|
|
197
|
+
for (const script of ["dev", "start", "serve"]) {
|
|
198
|
+
if (typeof scripts[script] === "string" && scripts[script].trim()) return script;
|
|
199
|
+
}
|
|
200
|
+
return "";
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function packageDependencyNames(pkg) {
|
|
204
|
+
return new Set([
|
|
205
|
+
...Object.keys(pkg?.dependencies || {}),
|
|
206
|
+
...Object.keys(pkg?.devDependencies || {}),
|
|
207
|
+
...Object.keys(pkg?.optionalDependencies || {}),
|
|
208
|
+
]);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function appRunnerId(...parts) {
|
|
212
|
+
return parts
|
|
213
|
+
.map((part) => String(part || "").trim())
|
|
214
|
+
.filter(Boolean)
|
|
215
|
+
.join(":")
|
|
216
|
+
.replace(/[^a-z0-9_.:-]+/gi, "-")
|
|
217
|
+
.replace(/^-+|-+$/g, "")
|
|
218
|
+
.slice(0, 160);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function shellQuote(value) {
|
|
222
|
+
return `'${String(value ?? "").replace(/'/g, `'\\''`)}'`;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function appRunnerShellCommandLine(command, args = []) {
|
|
226
|
+
return [command, ...args].map(shellQuote).join(" ");
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function spawnAppRunnerChild(run) {
|
|
230
|
+
const baseOptions = {
|
|
231
|
+
cwd: run.cwd,
|
|
232
|
+
env: process.env,
|
|
233
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
234
|
+
windowsHide: true,
|
|
235
|
+
detached: process.platform !== "win32",
|
|
236
|
+
};
|
|
237
|
+
const windowsPty = await appRunnerWindowsPty();
|
|
238
|
+
if (windowsPty) {
|
|
239
|
+
run.executionMode = "conpty";
|
|
240
|
+
const command = await resolveWindowsAppRunnerExecutable(run.command, run.cwd);
|
|
241
|
+
return windowsPty.spawn(command, run.args || [], {
|
|
242
|
+
name: process.env.TERM || "xterm-256color",
|
|
243
|
+
cols: Math.max(20, Number.parseInt(process.env.COLUMNS || "120", 10) || 120),
|
|
244
|
+
rows: Math.max(5, Number.parseInt(process.env.LINES || "40", 10) || 40),
|
|
245
|
+
cwd: run.cwd,
|
|
246
|
+
env: process.env,
|
|
247
|
+
useConpty: true,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
if (await appRunnerScriptPtyAvailable(run.cwd)) {
|
|
251
|
+
run.executionMode = "pty";
|
|
252
|
+
return spawn("script", [
|
|
253
|
+
"-q",
|
|
254
|
+
"-e",
|
|
255
|
+
"-f",
|
|
256
|
+
"-c",
|
|
257
|
+
`stty -echo 2>/dev/null || true; exec ${appRunnerShellCommandLine(run.command, run.args || [])}`,
|
|
258
|
+
"/dev/null",
|
|
259
|
+
], {
|
|
260
|
+
...baseOptions,
|
|
261
|
+
env: {
|
|
262
|
+
...process.env,
|
|
263
|
+
TERM: process.env.TERM || "xterm-256color",
|
|
264
|
+
COLUMNS: process.env.COLUMNS || "120",
|
|
265
|
+
LINES: process.env.LINES || "40",
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
run.executionMode = "pipe";
|
|
270
|
+
return spawn(run.command, run.args || [], baseOptions);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function appRunnerCandidate({ id, label, kind, command, args = [], projectFile = "", description = "", shortDisplayCommand = "", priority = 100, cwd = "", custom = false, configFile = "" }) {
|
|
274
|
+
return {
|
|
275
|
+
id,
|
|
276
|
+
label,
|
|
277
|
+
kind,
|
|
278
|
+
command,
|
|
279
|
+
args,
|
|
280
|
+
displayCommand: formatCommandForDisplay(command, args),
|
|
281
|
+
shortDisplayCommand,
|
|
282
|
+
projectFile,
|
|
283
|
+
description,
|
|
284
|
+
priority,
|
|
285
|
+
cwd,
|
|
286
|
+
custom,
|
|
287
|
+
configFile,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function addAppRunner(runners, runner) {
|
|
292
|
+
if (!runner?.id || !runner.command) return;
|
|
293
|
+
if (runners.some((item) => item.id === runner.id)) return;
|
|
294
|
+
const duplicateIndex = runners.findIndex((item) => item.displayCommand === runner.displayCommand);
|
|
295
|
+
if (duplicateIndex >= 0) {
|
|
296
|
+
if (runner.custom && !runners[duplicateIndex].custom) runners.splice(duplicateIndex, 1, runner);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
runners.push(runner);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function appRunnerPathInside(root, target) {
|
|
303
|
+
const relative = path.relative(root, target);
|
|
304
|
+
return !relative || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function normalizeAppRunnerSearchPath(value) {
|
|
308
|
+
if (typeof value !== "string") throw makeHttpError(400, "Search path must be a string");
|
|
309
|
+
const raw = normalizeSuggestionPath(value).trim();
|
|
310
|
+
if (!raw) throw makeHttpError(400, "Search path is required");
|
|
311
|
+
if (raw.includes("\0")) throw makeHttpError(400, "Search path cannot contain null bytes");
|
|
312
|
+
if (raw.length > APP_RUNNER_SEARCH_PATH_MAX_CHARS) throw makeHttpError(400, `Search path is too long; limit is ${APP_RUNNER_SEARCH_PATH_MAX_CHARS} characters`);
|
|
313
|
+
if (path.isAbsolute(raw) || /^[a-z]:\//i.test(raw)) throw makeHttpError(400, "Search path must be relative to the project root");
|
|
314
|
+
if (raw === "." || /^\.\/+$/i.test(raw)) return ".";
|
|
315
|
+
const normalized = raw.replace(/^\.\/+/, "").replace(/\/+$/g, "");
|
|
316
|
+
if (!normalized) return ".";
|
|
317
|
+
const parts = normalized.split("/").filter(Boolean);
|
|
318
|
+
if (parts.some((part) => part === "." || part === "..")) throw makeHttpError(400, "Search path cannot contain . or .. segments");
|
|
319
|
+
return parts.join("/");
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function canonicalAppRunnerProjectRoot(projectRoot) {
|
|
323
|
+
try {
|
|
324
|
+
return await realpath(projectRoot);
|
|
325
|
+
} catch (error) {
|
|
326
|
+
throw makeHttpError(400, `Cannot resolve project root: ${formatCliError(error)}`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async function appRunnerSearchPathStatus(projectRoot, relativePath, canonicalProjectRoot) {
|
|
331
|
+
const absolutePath = resolveProjectRelativePath(projectRoot, relativePath === "." ? "" : relativePath);
|
|
332
|
+
let canonicalPath;
|
|
333
|
+
try {
|
|
334
|
+
canonicalPath = await realpath(absolutePath);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
if (error?.code === "ENOENT" || error?.code === "ENOTDIR") return { available: false, reason: `Search path does not exist: ${relativePath}` };
|
|
337
|
+
return { available: false, reason: `Cannot access search path ${relativePath}: ${formatCliError(error)}` };
|
|
338
|
+
}
|
|
339
|
+
if (!appRunnerPathInside(canonicalProjectRoot, canonicalPath)) {
|
|
340
|
+
return { available: false, reason: `Search path resolves outside the project root: ${relativePath}` };
|
|
341
|
+
}
|
|
342
|
+
const info = await fileStatsIfExists(canonicalPath).catch(() => null);
|
|
343
|
+
if (!info?.isDirectory()) return { available: false, reason: `Search path is not a directory: ${relativePath}` };
|
|
344
|
+
return { available: true, absolutePath, canonicalPath };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async function appRunnerCanonicalFileInsideProject(projectRoot, relativePath, canonicalProjectRoot) {
|
|
348
|
+
let absolutePath;
|
|
349
|
+
try {
|
|
350
|
+
absolutePath = resolveProjectRelativePath(projectRoot, relativePath);
|
|
351
|
+
} catch {
|
|
352
|
+
return null;
|
|
353
|
+
}
|
|
354
|
+
let canonicalPath;
|
|
355
|
+
try {
|
|
356
|
+
canonicalPath = await realpath(absolutePath);
|
|
357
|
+
} catch {
|
|
358
|
+
return null;
|
|
359
|
+
}
|
|
360
|
+
if (!appRunnerPathInside(canonicalProjectRoot, canonicalPath)) return null;
|
|
361
|
+
const info = await fileStatsIfExists(canonicalPath).catch(() => null);
|
|
362
|
+
return info?.isFile() ? { absolutePath, canonicalPath, info } : null;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function normalizeProjectRelativePath(value, { allowEmpty = false } = {}) {
|
|
366
|
+
const raw = normalizeSuggestionPath(value).replace(/\0/g, "").trim();
|
|
367
|
+
const withoutDot = raw.replace(/^\.\/+/, "").replace(/\/+$/g, "");
|
|
368
|
+
if (!withoutDot) {
|
|
369
|
+
if (allowEmpty) return "";
|
|
370
|
+
throw makeHttpError(400, "Path to file is required");
|
|
371
|
+
}
|
|
372
|
+
if (path.isAbsolute(withoutDot) || /^[a-z]:\//i.test(withoutDot)) throw makeHttpError(400, "Path must be relative to the project root");
|
|
373
|
+
const parts = withoutDot.split("/").filter(Boolean);
|
|
374
|
+
if (parts.some((part) => part === "." || part === "..")) throw makeHttpError(400, "Path cannot contain . or .. segments");
|
|
375
|
+
return parts.join("/").slice(0, 4096);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function resolveProjectRelativePath(projectRoot, relativePath) {
|
|
379
|
+
const target = path.resolve(projectRoot, relativePath || ".");
|
|
380
|
+
if (!appRunnerPathInside(projectRoot, target)) throw makeHttpError(400, "Path must stay inside the project root");
|
|
381
|
+
return target;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async function findAppRunnerProjectRoot(cwd) {
|
|
385
|
+
const start = await resolveCwd(cwd || defaultCwd, defaultCwd);
|
|
386
|
+
let fallback = "";
|
|
387
|
+
for (let current = start; current; current = path.dirname(current)) {
|
|
388
|
+
if (await appRunnerFileExists(current, APP_RUNNER_CONFIG_FILE)) return current;
|
|
389
|
+
if (!fallback && (await appRunnerFileExists(current, "package.json") || await appRunnerDirectoryExists(current, ".git"))) fallback = current;
|
|
390
|
+
const parent = path.dirname(current);
|
|
391
|
+
if (parent === current) break;
|
|
392
|
+
}
|
|
393
|
+
return fallback || start;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function cleanCustomRunnerCommand(value) {
|
|
397
|
+
const command = String(value || "./").trim().replace(/\s+/g, " ") || "./";
|
|
398
|
+
if (command.includes("\0") || /[\r\n]/.test(command)) throw makeHttpError(400, "Command cannot contain newlines or null bytes");
|
|
399
|
+
if (command.length > 512) throw makeHttpError(400, "Command is too long");
|
|
400
|
+
return command === "." ? "./" : command;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function customRunnerCommandParts(command) {
|
|
404
|
+
const clean = cleanCustomRunnerCommand(command);
|
|
405
|
+
return clean === "./" ? ["./"] : clean.split(" ").filter(Boolean);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function parseCustomRunnerArgs(value) {
|
|
409
|
+
const rawItems = Array.isArray(value)
|
|
410
|
+
? value
|
|
411
|
+
: String(value || "").trim()
|
|
412
|
+
? String(value || "").trim().split(/\s+/)
|
|
413
|
+
: [];
|
|
414
|
+
const args = [];
|
|
415
|
+
for (const item of rawItems) {
|
|
416
|
+
const text = String(item || "").trim();
|
|
417
|
+
if (!text) continue;
|
|
418
|
+
if (text.includes("\0") || /[\r\n]/.test(text)) throw makeHttpError(400, "Args cannot contain newlines or null bytes");
|
|
419
|
+
if (text.length > 2048) throw makeHttpError(400, "One arg is too long");
|
|
420
|
+
args.push(text);
|
|
421
|
+
if (args.length > APP_RUNNER_CUSTOM_ARG_LIMIT) throw makeHttpError(400, `Too many args; limit is ${APP_RUNNER_CUSTOM_ARG_LIMIT}`);
|
|
422
|
+
}
|
|
423
|
+
return args;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function publicCustomRunnerDefinition(runner) {
|
|
427
|
+
const command = cleanCustomRunnerCommand(runner.command);
|
|
428
|
+
const args = parseCustomRunnerArgs(runner.args);
|
|
429
|
+
const filePath = normalizeProjectRelativePath(runner.path || runner.projectFile);
|
|
430
|
+
const commandParts = customRunnerCommandParts(command);
|
|
431
|
+
const effectiveCommand = command === "./" ? `./${filePath}` : commandParts[0];
|
|
432
|
+
const effectiveArgs = command === "./" ? args : [...commandParts.slice(1), filePath, ...args];
|
|
433
|
+
return {
|
|
434
|
+
id: runner.id,
|
|
435
|
+
label: runner.label,
|
|
436
|
+
command,
|
|
437
|
+
path: filePath,
|
|
438
|
+
args,
|
|
439
|
+
displayCommand: formatCommandForDisplay(effectiveCommand, effectiveArgs),
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function normalizeCustomRunnerDefinition(raw, projectRoot, { strict = false } = {}) {
|
|
444
|
+
const filePath = normalizeProjectRelativePath(raw?.path || raw?.projectFile);
|
|
445
|
+
const absolutePath = resolveProjectRelativePath(projectRoot, filePath);
|
|
446
|
+
const command = cleanCustomRunnerCommand(raw?.command);
|
|
447
|
+
const args = parseCustomRunnerArgs(raw?.args);
|
|
448
|
+
const label = String(raw?.label || path.basename(filePath)).trim().slice(0, 120) || path.basename(filePath);
|
|
449
|
+
const rawId = String(raw?.id || "").trim();
|
|
450
|
+
const id = appRunnerId(rawId) || appRunnerId(label, command, filePath) || appRunnerId(command, filePath);
|
|
451
|
+
if (!id) throw makeHttpError(400, "Custom runner id could not be generated");
|
|
452
|
+
if (strict && !appRunnerPathInside(projectRoot, absolutePath)) throw makeHttpError(400, "Path must stay inside the project root");
|
|
453
|
+
return { id, label, command, path: filePath, args };
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function customAppRunnerDiagnostic(severity, message, runner = {}) {
|
|
457
|
+
const source = runner && typeof runner === "object" ? runner : {};
|
|
458
|
+
return {
|
|
459
|
+
severity,
|
|
460
|
+
message,
|
|
461
|
+
runnerId: source.id || "",
|
|
462
|
+
runnerLabel: source.label || "",
|
|
463
|
+
path: source.path || source.projectFile || "",
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function directCustomRunnerUnavailableReason(filePath, stats) {
|
|
468
|
+
if (process.platform !== "win32" && stats && (stats.mode & 0o111) === 0) {
|
|
469
|
+
return `Path is not executable: ${filePath}. Run chmod +x ${filePath} or set Command to bash, python3, node, etc.`;
|
|
470
|
+
}
|
|
471
|
+
return "";
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
async function customAppRunnerUnavailableReason(projectRoot, runner) {
|
|
475
|
+
const filePath = runner.path;
|
|
476
|
+
const canonicalProjectRoot = await canonicalAppRunnerProjectRoot(projectRoot);
|
|
477
|
+
const file = await appRunnerCanonicalFileInsideProject(projectRoot, filePath, canonicalProjectRoot);
|
|
478
|
+
if (!file) {
|
|
479
|
+
const absolutePath = resolveProjectRelativePath(projectRoot, filePath);
|
|
480
|
+
const info = await fileStatsIfExists(absolutePath).catch(() => null);
|
|
481
|
+
if (info?.isFile()) return `Path resolves outside the project root: ${filePath}`;
|
|
482
|
+
return `Path to file does not exist: ${filePath}`;
|
|
483
|
+
}
|
|
484
|
+
const command = cleanCustomRunnerCommand(runner.command);
|
|
485
|
+
const directReason = command === "./" ? directCustomRunnerUnavailableReason(filePath, file.info) : "";
|
|
486
|
+
if (directReason) return directReason;
|
|
487
|
+
const commandParts = customRunnerCommandParts(command);
|
|
488
|
+
if (command !== "./" && !await appRunnerCommandAvailable(commandParts[0], projectRoot)) return `Command is not available: ${commandParts[0]}`;
|
|
489
|
+
return "";
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function appRunnerSearchPathDiagnostic(severity, message, pathValue) {
|
|
493
|
+
return customAppRunnerDiagnostic(severity, message, { path: pathValue });
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
async function normalizeAppRunnerSearchPaths(rawSearchPaths, projectRoot, { requireDirectories = false, diagnostics = null } = {}) {
|
|
497
|
+
if (!Array.isArray(rawSearchPaths)) throw makeHttpError(400, `${APP_RUNNER_CONFIG_FILE} searchPaths must be an array`);
|
|
498
|
+
if (rawSearchPaths.length > APP_RUNNER_SEARCH_PATH_LIMIT) {
|
|
499
|
+
throw makeHttpError(400, `Search path limit reached (${APP_RUNNER_SEARCH_PATH_LIMIT})`);
|
|
500
|
+
}
|
|
501
|
+
const canonicalProjectRoot = await canonicalAppRunnerProjectRoot(projectRoot);
|
|
502
|
+
const searchPaths = [];
|
|
503
|
+
const availableSearchPaths = [];
|
|
504
|
+
const seen = new Set();
|
|
505
|
+
for (const rawPath of rawSearchPaths) {
|
|
506
|
+
let searchPath;
|
|
507
|
+
try {
|
|
508
|
+
searchPath = normalizeAppRunnerSearchPath(rawPath);
|
|
509
|
+
} catch (error) {
|
|
510
|
+
if (!diagnostics) throw error;
|
|
511
|
+
diagnostics.push(appRunnerSearchPathDiagnostic("error", `Invalid search path ignored: ${formatCliError(error)}`, typeof rawPath === "string" ? rawPath : ""));
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (seen.has(searchPath)) {
|
|
515
|
+
const message = `Duplicate search path ignored: ${searchPath}`;
|
|
516
|
+
if (!diagnostics) throw makeHttpError(400, message);
|
|
517
|
+
diagnostics.push(appRunnerSearchPathDiagnostic("warning", message, searchPath));
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
seen.add(searchPath);
|
|
521
|
+
searchPaths.push(searchPath);
|
|
522
|
+
const status = await appRunnerSearchPathStatus(projectRoot, searchPath, canonicalProjectRoot);
|
|
523
|
+
if (!status.available) {
|
|
524
|
+
if (requireDirectories) throw makeHttpError(400, status.reason);
|
|
525
|
+
diagnostics?.push(appRunnerSearchPathDiagnostic("warning", status.reason, searchPath));
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
availableSearchPaths.push({ path: searchPath, ...status });
|
|
529
|
+
}
|
|
530
|
+
return { searchPaths, availableSearchPaths, canonicalProjectRoot };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
async function readAppRunnerConfig(projectRoot, { strictRead = false } = {}) {
|
|
534
|
+
const configPath = path.join(projectRoot, APP_RUNNER_CONFIG_FILE);
|
|
535
|
+
let source = {};
|
|
536
|
+
const diagnostics = [];
|
|
537
|
+
try {
|
|
538
|
+
const parsed = JSON.parse(await readFile(configPath, "utf8"));
|
|
539
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
540
|
+
source = parsed;
|
|
541
|
+
} else {
|
|
542
|
+
const message = `${APP_RUNNER_CONFIG_FILE} must contain a JSON object`;
|
|
543
|
+
if (strictRead) throw makeHttpError(400, message);
|
|
544
|
+
diagnostics.push(customAppRunnerDiagnostic("error", message));
|
|
545
|
+
}
|
|
546
|
+
} catch (error) {
|
|
547
|
+
if (error?.code !== "ENOENT") {
|
|
548
|
+
const message = `Cannot read ${APP_RUNNER_CONFIG_FILE}: ${formatCliError(error)}`;
|
|
549
|
+
if (strictRead) throw makeHttpError(400, message);
|
|
550
|
+
diagnostics.push(customAppRunnerDiagnostic("error", message));
|
|
551
|
+
console.warn(`failed to read custom app runner config ${configPath}: ${sanitizeError(error)}`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
if (source.runners !== undefined && !Array.isArray(source.runners)) {
|
|
555
|
+
const message = `${APP_RUNNER_CONFIG_FILE} runners must be an array`;
|
|
556
|
+
if (strictRead) throw makeHttpError(400, message);
|
|
557
|
+
diagnostics.push(customAppRunnerDiagnostic("error", message));
|
|
558
|
+
}
|
|
559
|
+
if (source.searchPaths !== undefined && !Array.isArray(source.searchPaths)) {
|
|
560
|
+
const message = `${APP_RUNNER_CONFIG_FILE} searchPaths must be an array`;
|
|
561
|
+
if (strictRead) throw makeHttpError(400, message);
|
|
562
|
+
diagnostics.push(appRunnerSearchPathDiagnostic("error", message, ""));
|
|
563
|
+
}
|
|
564
|
+
const rawRunners = Array.isArray(source.runners) ? source.runners : [];
|
|
565
|
+
const runners = [];
|
|
566
|
+
for (const raw of rawRunners) {
|
|
567
|
+
try {
|
|
568
|
+
const runner = normalizeCustomRunnerDefinition(raw, projectRoot);
|
|
569
|
+
if (runners.some((item) => item.id === runner.id)) {
|
|
570
|
+
diagnostics.push(customAppRunnerDiagnostic("warning", `Duplicate custom runner ignored: ${runner.label || runner.path || runner.id}`, runner));
|
|
571
|
+
} else {
|
|
572
|
+
runners.push(runner);
|
|
573
|
+
}
|
|
574
|
+
} catch (error) {
|
|
575
|
+
const message = `Invalid custom runner ignored: ${formatCliError(error)}`;
|
|
576
|
+
diagnostics.push(customAppRunnerDiagnostic("error", message, raw));
|
|
577
|
+
console.warn(`skipping invalid custom app runner in ${configPath}: ${sanitizeError(error)}`);
|
|
578
|
+
}
|
|
579
|
+
if (runners.length >= APP_RUNNER_CUSTOM_LIMIT) break;
|
|
580
|
+
}
|
|
581
|
+
let searchPathData = { searchPaths: [], availableSearchPaths: [], canonicalProjectRoot: await canonicalAppRunnerProjectRoot(projectRoot) };
|
|
582
|
+
if (Array.isArray(source.searchPaths)) {
|
|
583
|
+
try {
|
|
584
|
+
searchPathData = await normalizeAppRunnerSearchPaths(source.searchPaths, projectRoot, { diagnostics });
|
|
585
|
+
} catch (error) {
|
|
586
|
+
const message = `Invalid search paths ignored: ${formatCliError(error)}`;
|
|
587
|
+
if (strictRead) throw makeHttpError(400, message);
|
|
588
|
+
diagnostics.push(appRunnerSearchPathDiagnostic("error", message, ""));
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
return { projectRoot, configPath, runners, diagnostics, ...searchPathData };
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
async function writeAppRunnerConfig(projectRoot, runners, searchPaths = []) {
|
|
595
|
+
const configPath = path.join(projectRoot, APP_RUNNER_CONFIG_FILE);
|
|
596
|
+
const normalizedRunners = [];
|
|
597
|
+
for (const runner of runners) {
|
|
598
|
+
normalizedRunners.push(normalizeCustomRunnerDefinition(runner, projectRoot, { strict: true }));
|
|
599
|
+
if (normalizedRunners.length >= APP_RUNNER_CUSTOM_LIMIT) break;
|
|
600
|
+
}
|
|
601
|
+
const { searchPaths: normalizedSearchPaths } = await normalizeAppRunnerSearchPaths(searchPaths, projectRoot);
|
|
602
|
+
const tmpFile = `${configPath}.${process.pid}.${Date.now()}.tmp`;
|
|
603
|
+
await writeFile(tmpFile, `${JSON.stringify({ version: 2, searchPaths: normalizedSearchPaths, runners: normalizedRunners }, null, 2)}\n`, { mode: 0o600 });
|
|
604
|
+
await rename(tmpFile, configPath);
|
|
605
|
+
return { projectRoot, configPath, runners: normalizedRunners, searchPaths: normalizedSearchPaths };
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
async function customAppRunnerCandidate(projectRoot, configPath, runner) {
|
|
609
|
+
const filePath = runner.path;
|
|
610
|
+
if (await customAppRunnerUnavailableReason(projectRoot, runner)) return null;
|
|
611
|
+
const command = cleanCustomRunnerCommand(runner.command);
|
|
612
|
+
const args = parseCustomRunnerArgs(runner.args);
|
|
613
|
+
const commandParts = customRunnerCommandParts(command);
|
|
614
|
+
const effectiveCommand = command === "./" ? `./${filePath}` : commandParts[0];
|
|
615
|
+
const effectiveArgs = command === "./" ? args : [...commandParts.slice(1), filePath, ...args];
|
|
616
|
+
return appRunnerCandidate({
|
|
617
|
+
id: appRunnerId("custom", runner.id),
|
|
618
|
+
label: runner.label || path.basename(filePath),
|
|
619
|
+
kind: "custom",
|
|
620
|
+
command: effectiveCommand,
|
|
621
|
+
args: effectiveArgs,
|
|
622
|
+
projectFile: filePath,
|
|
623
|
+
description: `Custom project runner from ${APP_RUNNER_CONFIG_FILE}`,
|
|
624
|
+
priority: 8,
|
|
625
|
+
cwd: projectRoot,
|
|
626
|
+
custom: true,
|
|
627
|
+
configFile: configPath,
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
async function addCustomAppRunners(runners, cwd) {
|
|
632
|
+
const projectRoot = await findAppRunnerProjectRoot(cwd);
|
|
633
|
+
const config = await readAppRunnerConfig(projectRoot);
|
|
634
|
+
for (const runner of config.runners) {
|
|
635
|
+
const candidate = await customAppRunnerCandidate(projectRoot, config.configPath, runner);
|
|
636
|
+
if (candidate) addAppRunner(runners, candidate);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
async function getCustomAppRunnerConfigData(tab) {
|
|
641
|
+
const projectRoot = await findAppRunnerProjectRoot(tab?.cwd || defaultCwd);
|
|
642
|
+
const config = await readAppRunnerConfig(projectRoot);
|
|
643
|
+
const runners = [];
|
|
644
|
+
for (const runner of config.runners) {
|
|
645
|
+
const unavailableReason = await customAppRunnerUnavailableReason(projectRoot, runner);
|
|
646
|
+
runners.push({
|
|
647
|
+
...publicCustomRunnerDefinition(runner),
|
|
648
|
+
available: !unavailableReason,
|
|
649
|
+
unavailableReason,
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
return {
|
|
653
|
+
version: 2,
|
|
654
|
+
projectRoot,
|
|
655
|
+
displayProjectRoot: displayPath(projectRoot),
|
|
656
|
+
configFile: config.configPath,
|
|
657
|
+
displayConfigFile: displayPath(config.configPath),
|
|
658
|
+
relativeConfigFile: APP_RUNNER_CONFIG_FILE,
|
|
659
|
+
searchPaths: config.searchPaths,
|
|
660
|
+
runners,
|
|
661
|
+
diagnostics: config.diagnostics,
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
async function saveCustomAppRunner(tab, rawRunner) {
|
|
666
|
+
const projectRoot = await findAppRunnerProjectRoot(tab?.cwd || defaultCwd);
|
|
667
|
+
const config = await readAppRunnerConfig(projectRoot, { strictRead: true });
|
|
668
|
+
const normalized = normalizeCustomRunnerDefinition(rawRunner, projectRoot, { strict: true });
|
|
669
|
+
const unavailableReason = await customAppRunnerUnavailableReason(projectRoot, normalized);
|
|
670
|
+
if (unavailableReason) throw makeHttpError(400, unavailableReason);
|
|
671
|
+
const runners = config.runners.filter((runner) => runner.id !== normalized.id);
|
|
672
|
+
if (runners.length >= APP_RUNNER_CUSTOM_LIMIT) throw makeHttpError(400, `Custom runner limit reached (${APP_RUNNER_CUSTOM_LIMIT})`);
|
|
673
|
+
runners.push(normalized);
|
|
674
|
+
await writeAppRunnerConfig(projectRoot, runners, config.searchPaths);
|
|
675
|
+
return getAppRunnerData(tab);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
async function saveAppRunnerSearchPaths(tab, rawSearchPaths) {
|
|
679
|
+
const projectRoot = await findAppRunnerProjectRoot(tab?.cwd || defaultCwd);
|
|
680
|
+
const config = await readAppRunnerConfig(projectRoot, { strictRead: true });
|
|
681
|
+
const { searchPaths } = await normalizeAppRunnerSearchPaths(rawSearchPaths, projectRoot, { requireDirectories: true });
|
|
682
|
+
await writeAppRunnerConfig(projectRoot, config.runners, searchPaths);
|
|
683
|
+
return getAppRunnerData(tab);
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
async function deleteCustomAppRunner(tab, runnerId) {
|
|
687
|
+
const id = appRunnerId(String(runnerId || "").replace(/^custom:/, ""));
|
|
688
|
+
if (!id) throw makeHttpError(400, "Custom runner id is required");
|
|
689
|
+
const projectRoot = await findAppRunnerProjectRoot(tab?.cwd || defaultCwd);
|
|
690
|
+
const config = await readAppRunnerConfig(projectRoot);
|
|
691
|
+
const runners = config.runners.filter((runner) => runner.id !== id);
|
|
692
|
+
if (runners.length === config.runners.length) throw makeHttpError(404, "Custom runner not found");
|
|
693
|
+
await writeAppRunnerConfig(projectRoot, runners, config.searchPaths);
|
|
694
|
+
return getAppRunnerData(tab);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
async function getAppRunnerFileBrowserData(tab, rawPath) {
|
|
698
|
+
const projectRoot = await findAppRunnerProjectRoot(tab?.cwd || defaultCwd);
|
|
699
|
+
const relativeDir = normalizeProjectRelativePath(rawPath || "", { allowEmpty: true });
|
|
700
|
+
const absoluteDir = resolveProjectRelativePath(projectRoot, relativeDir || ".");
|
|
701
|
+
const stats = await fileStatsIfExists(absoluteDir);
|
|
702
|
+
if (!stats?.isDirectory()) throw makeHttpError(400, `Not a directory inside project root: ${relativeDir || "."}`);
|
|
703
|
+
let entries;
|
|
704
|
+
try {
|
|
705
|
+
entries = await readdir(absoluteDir, { withFileTypes: true });
|
|
706
|
+
} catch (error) {
|
|
707
|
+
throw makeHttpError(error?.code === "EACCES" ? 403 : 400, `Cannot read directory ${relativeDir || "."}: ${sanitizeError(error)}`);
|
|
708
|
+
}
|
|
709
|
+
const sorted = entries.sort((a, b) => {
|
|
710
|
+
if (a.isDirectory() !== b.isDirectory()) return a.isDirectory() ? -1 : 1;
|
|
711
|
+
return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" });
|
|
712
|
+
});
|
|
713
|
+
const directories = [];
|
|
714
|
+
const files = [];
|
|
715
|
+
for (const entry of sorted) {
|
|
716
|
+
if (entry.name === ".git") continue;
|
|
717
|
+
const entryRelativePath = normalizeSuggestionPath(relativeDir ? `${relativeDir}/${entry.name}` : entry.name);
|
|
718
|
+
if (entry.isDirectory()) directories.push({ name: entry.name, path: entryRelativePath, hidden: entry.name.startsWith(".") });
|
|
719
|
+
else if (entry.isFile()) files.push({ name: entry.name, path: entryRelativePath, hidden: entry.name.startsWith(".") });
|
|
720
|
+
if (directories.length + files.length >= APP_RUNNER_FILE_PICKER_LIMIT) break;
|
|
721
|
+
}
|
|
722
|
+
const parent = relativeDir ? normalizeSuggestionPath(path.posix.dirname(relativeDir)) : "";
|
|
723
|
+
return {
|
|
724
|
+
projectRoot,
|
|
725
|
+
displayProjectRoot: displayPath(projectRoot),
|
|
726
|
+
relativeDir,
|
|
727
|
+
displayRelativeDir: relativeDir || ".",
|
|
728
|
+
parent: relativeDir && parent !== "." ? parent : relativeDir ? "" : null,
|
|
729
|
+
directories,
|
|
730
|
+
files,
|
|
731
|
+
truncated: sorted.length > directories.length + files.length,
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
function packageManagerArgs(manager, script) {
|
|
736
|
+
if (manager === "bun") return ["run", script];
|
|
737
|
+
if (manager === "yarn") return script === "start" ? ["start"] : [script];
|
|
738
|
+
return script === "start" ? ["start"] : ["run", script];
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
async function addPackageManagerRunners(runners, cwd, pkg) {
|
|
742
|
+
const script = preferredPackageScript(pkg);
|
|
743
|
+
if (!script) return;
|
|
744
|
+
const packageManager = String(pkg?.packageManager || "").toLowerCase();
|
|
745
|
+
const [hasBunLock, hasPnpmLock, hasYarnLock, hasPackageLock] = await Promise.all([
|
|
746
|
+
appRunnerFileExists(cwd, "bun.lock").then((exists) => exists || appRunnerFileExists(cwd, "bun.lockb")),
|
|
747
|
+
appRunnerFileExists(cwd, "pnpm-lock.yaml"),
|
|
748
|
+
appRunnerFileExists(cwd, "yarn.lock"),
|
|
749
|
+
appRunnerFileExists(cwd, "package-lock.json"),
|
|
750
|
+
]);
|
|
751
|
+
const managers = [
|
|
752
|
+
{ id: "bun", command: "bun", label: "Bun", hint: hasBunLock || packageManager.startsWith("bun@"), priority: hasBunLock || packageManager.startsWith("bun@") ? 20 : 54 },
|
|
753
|
+
{ id: "pnpm", command: "pnpm", label: "pnpm", hint: hasPnpmLock || packageManager.startsWith("pnpm@"), priority: hasPnpmLock || packageManager.startsWith("pnpm@") ? 24 : 58 },
|
|
754
|
+
{ id: "npm", command: "npm", label: "npm", hint: hasPackageLock || packageManager.startsWith("npm@") || !packageManager, priority: hasPackageLock || packageManager.startsWith("npm@") || !packageManager ? 28 : 62 },
|
|
755
|
+
{ id: "yarn", command: "yarn", label: "Yarn", hint: hasYarnLock || packageManager.startsWith("yarn@"), priority: hasYarnLock || packageManager.startsWith("yarn@") ? 34 : 72 },
|
|
756
|
+
];
|
|
757
|
+
|
|
758
|
+
for (const manager of managers) {
|
|
759
|
+
if (!await appRunnerCommandAvailable(manager.command, cwd)) continue;
|
|
760
|
+
const args = packageManagerArgs(manager.id, script);
|
|
761
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
762
|
+
id: appRunnerId("pkg", manager.id, script),
|
|
763
|
+
label: `${manager.label} ${script}`,
|
|
764
|
+
kind: manager.id === "bun" ? "bun" : "node",
|
|
765
|
+
command: manager.command,
|
|
766
|
+
args,
|
|
767
|
+
projectFile: "package.json",
|
|
768
|
+
description: `${manager.label} package script: ${script}`,
|
|
769
|
+
priority: manager.priority + (manager.hint ? 0 : 12),
|
|
770
|
+
}));
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
async function addNpxFrameworkRunners(runners, cwd, pkg) {
|
|
775
|
+
const dependencyNames = packageDependencyNames(pkg);
|
|
776
|
+
if (!dependencyNames.size || !await appRunnerCommandAvailable("npx", cwd)) return;
|
|
777
|
+
const frameworks = [
|
|
778
|
+
{ dep: "vite", label: "npx vite", args: ["--no-install", "vite"], priority: 78 },
|
|
779
|
+
{ dep: "next", label: "npx next dev", args: ["--no-install", "next", "dev"], priority: 80 },
|
|
780
|
+
{ dep: "astro", label: "npx astro dev", args: ["--no-install", "astro", "dev"], priority: 82 },
|
|
781
|
+
{ dep: "@storybook/react", label: "npx storybook dev", args: ["--no-install", "storybook", "dev"], priority: 86 },
|
|
782
|
+
{ dep: "storybook", label: "npx storybook dev", args: ["--no-install", "storybook", "dev"], priority: 86 },
|
|
783
|
+
];
|
|
784
|
+
for (const framework of frameworks) {
|
|
785
|
+
if (!dependencyNames.has(framework.dep)) continue;
|
|
786
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
787
|
+
id: appRunnerId("npx", framework.dep),
|
|
788
|
+
label: framework.label,
|
|
789
|
+
kind: "node",
|
|
790
|
+
command: "npx",
|
|
791
|
+
args: framework.args,
|
|
792
|
+
projectFile: "package.json",
|
|
793
|
+
description: `Detected ${framework.dep} dependency`,
|
|
794
|
+
priority: framework.priority,
|
|
795
|
+
}));
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
async function addNodeEntrypointRunner(runners, cwd, hasPackageJson) {
|
|
800
|
+
if (hasPackageJson) return;
|
|
801
|
+
const entry = await firstExistingRunnerFile(cwd, APP_RUNNER_JS_ENTRIES);
|
|
802
|
+
if (!entry || !await appRunnerCommandAvailable("node", cwd)) return;
|
|
803
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
804
|
+
id: appRunnerId("node", entry),
|
|
805
|
+
label: `node ${entry}`,
|
|
806
|
+
kind: "node",
|
|
807
|
+
command: "node",
|
|
808
|
+
args: [entry],
|
|
809
|
+
projectFile: entry,
|
|
810
|
+
description: "Detected JavaScript entry file",
|
|
811
|
+
priority: 88,
|
|
812
|
+
}));
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
async function addPythonRunners(runners, cwd) {
|
|
816
|
+
const entry = await firstExistingRunnerFile(cwd, APP_RUNNER_PYTHON_ENTRIES);
|
|
817
|
+
if (!entry) return;
|
|
818
|
+
if (await appRunnerCommandAvailable("uv", cwd)) {
|
|
819
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
820
|
+
id: appRunnerId("python", "uv", entry),
|
|
821
|
+
label: `uv run ${entry}`,
|
|
822
|
+
kind: "python",
|
|
823
|
+
command: "uv",
|
|
824
|
+
args: ["run", entry],
|
|
825
|
+
projectFile: entry,
|
|
826
|
+
description: "Detected Python entry file",
|
|
827
|
+
priority: 36,
|
|
828
|
+
}));
|
|
829
|
+
}
|
|
830
|
+
const pythonCommand = await appRunnerCommandAvailable("python3", cwd) ? "python3" : await appRunnerCommandAvailable("python", cwd) ? "python" : "";
|
|
831
|
+
if (pythonCommand) {
|
|
832
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
833
|
+
id: appRunnerId("python", pythonCommand, entry),
|
|
834
|
+
label: `${pythonCommand} ${entry}`,
|
|
835
|
+
kind: "python",
|
|
836
|
+
command: pythonCommand,
|
|
837
|
+
args: [entry],
|
|
838
|
+
projectFile: entry,
|
|
839
|
+
description: "Detected Python entry file",
|
|
840
|
+
priority: 68,
|
|
841
|
+
}));
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
async function addRustRunner(runners, cwd) {
|
|
846
|
+
if (!await appRunnerFileExists(cwd, "Cargo.toml") || !await appRunnerCommandAvailable("cargo", cwd)) return;
|
|
847
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
848
|
+
id: "rust:cargo-run",
|
|
849
|
+
label: "cargo run",
|
|
850
|
+
kind: "rust",
|
|
851
|
+
command: "cargo",
|
|
852
|
+
args: ["run"],
|
|
853
|
+
projectFile: "Cargo.toml",
|
|
854
|
+
description: "Detected Rust Cargo project",
|
|
855
|
+
priority: 18,
|
|
856
|
+
}));
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
async function goRunTarget(cwd) {
|
|
860
|
+
if (await appRunnerFileExists(cwd, "main.go")) return ".";
|
|
861
|
+
if (await appRunnerDirectoryExists(cwd, "cmd")) {
|
|
862
|
+
const entries = await readdir(path.join(cwd, "cmd"), { withFileTypes: true }).catch(() => []);
|
|
863
|
+
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
864
|
+
if (!entry.isDirectory()) continue;
|
|
865
|
+
if (await appRunnerFileExists(cwd, path.join("cmd", entry.name, "main.go"))) return `./cmd/${entry.name}`;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
return await appRunnerFileExists(cwd, "go.mod") ? "." : "";
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
async function addGoRunner(runners, cwd) {
|
|
872
|
+
const target = await goRunTarget(cwd);
|
|
873
|
+
if (!target || !await appRunnerCommandAvailable("go", cwd)) return;
|
|
874
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
875
|
+
id: appRunnerId("go", target),
|
|
876
|
+
label: `go run ${target}`,
|
|
877
|
+
kind: "go",
|
|
878
|
+
command: "go",
|
|
879
|
+
args: ["run", target],
|
|
880
|
+
projectFile: await appRunnerFileExists(cwd, "go.mod") ? "go.mod" : target,
|
|
881
|
+
description: "Detected Go/Golang app entry",
|
|
882
|
+
priority: 46,
|
|
883
|
+
}));
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
function buildZigHasRunStep(text) {
|
|
887
|
+
return /\.step\(\s*["']run["']/.test(String(text || ""));
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
async function addZigRunner(runners, cwd) {
|
|
891
|
+
if (!await appRunnerCommandAvailable("zig", cwd)) return;
|
|
892
|
+
const buildZig = await appRunnerTextIfExists(cwd, "build.zig");
|
|
893
|
+
if (buildZig && buildZigHasRunStep(buildZig)) {
|
|
894
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
895
|
+
id: "zig:build-run",
|
|
896
|
+
label: "zig build run",
|
|
897
|
+
kind: "zig",
|
|
898
|
+
command: "zig",
|
|
899
|
+
args: ["build", "run"],
|
|
900
|
+
projectFile: "build.zig",
|
|
901
|
+
description: "Detected Zig build.zig run step",
|
|
902
|
+
priority: 44,
|
|
903
|
+
}));
|
|
904
|
+
}
|
|
905
|
+
const entry = await firstExistingRunnerFile(cwd, APP_RUNNER_ZIG_ENTRIES);
|
|
906
|
+
if (entry) {
|
|
907
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
908
|
+
id: appRunnerId("zig", entry),
|
|
909
|
+
label: `zig run ${entry}`,
|
|
910
|
+
kind: "zig",
|
|
911
|
+
command: "zig",
|
|
912
|
+
args: ["run", entry],
|
|
913
|
+
projectFile: entry,
|
|
914
|
+
description: "Detected Zig app entry file",
|
|
915
|
+
priority: 66,
|
|
916
|
+
}));
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
function firstCmakeExecutableTarget(text) {
|
|
921
|
+
const match = String(text || "").match(/add_executable\s*\(\s*([A-Za-z0-9_.+-]+)/i);
|
|
922
|
+
return match ? match[1] : "";
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
async function addCompiledLanguageRunner(runners, cwd, { language, kind, compiler, entry, outputName, priority }) {
|
|
926
|
+
if (!entry || !await appRunnerCommandAvailable("sh", cwd) || !await appRunnerCommandAvailable(compiler, cwd)) return;
|
|
927
|
+
const output = `.pi-webui-runner/${outputName}`;
|
|
928
|
+
const compileAndRun = `mkdir -p .pi-webui-runner && ${compiler} ${shellQuote(entry)} -o ${shellQuote(output)} && ${shellQuote(`./${output}`)}`;
|
|
929
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
930
|
+
id: appRunnerId(kind, entry),
|
|
931
|
+
label: `${compiler} ${entry}`,
|
|
932
|
+
kind,
|
|
933
|
+
command: "sh",
|
|
934
|
+
args: ["-lc", compileAndRun],
|
|
935
|
+
projectFile: entry,
|
|
936
|
+
description: `Detected ${language} app entry file`,
|
|
937
|
+
priority,
|
|
938
|
+
}));
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
async function addCppRunners(runners, cwd) {
|
|
942
|
+
const cmakeText = await appRunnerTextIfExists(cwd, "CMakeLists.txt");
|
|
943
|
+
const cmakeTarget = firstCmakeExecutableTarget(cmakeText);
|
|
944
|
+
const hasShell = await appRunnerCommandAvailable("sh", cwd);
|
|
945
|
+
if (cmakeTarget && hasShell && await appRunnerCommandAvailable("cmake", cwd)) {
|
|
946
|
+
const configureBuildRun = `cmake -S . -B build && cmake --build build --target ${shellQuote(cmakeTarget)} && ${shellQuote(`./build/${cmakeTarget}`)}`;
|
|
947
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
948
|
+
id: appRunnerId("cmake", cmakeTarget),
|
|
949
|
+
label: `cmake run ${cmakeTarget}`,
|
|
950
|
+
kind: "cpp",
|
|
951
|
+
command: "sh",
|
|
952
|
+
args: ["-lc", configureBuildRun],
|
|
953
|
+
projectFile: "CMakeLists.txt",
|
|
954
|
+
description: "Detected C/C++ CMake executable target",
|
|
955
|
+
priority: 42,
|
|
956
|
+
}));
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
await Promise.all([
|
|
961
|
+
addCompiledLanguageRunner(runners, cwd, {
|
|
962
|
+
language: "C",
|
|
963
|
+
kind: "c",
|
|
964
|
+
compiler: "cc",
|
|
965
|
+
entry: await firstExistingRunnerFile(cwd, APP_RUNNER_C_ENTRIES),
|
|
966
|
+
outputName: "main-c",
|
|
967
|
+
priority: 64,
|
|
968
|
+
}),
|
|
969
|
+
addCompiledLanguageRunner(runners, cwd, {
|
|
970
|
+
language: "C++",
|
|
971
|
+
kind: "cpp",
|
|
972
|
+
compiler: "c++",
|
|
973
|
+
entry: await firstExistingRunnerFile(cwd, APP_RUNNER_CPP_ENTRIES),
|
|
974
|
+
outputName: "main-cpp",
|
|
975
|
+
priority: 65,
|
|
976
|
+
}),
|
|
977
|
+
]);
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
async function dockerComposePluginAvailable(cwd) {
|
|
981
|
+
const result = await runCommand("docker", ["compose", "version"], {
|
|
982
|
+
cwd,
|
|
983
|
+
timeoutMs: APP_RUNNER_DETECTION_TIMEOUT_MS,
|
|
984
|
+
maxOutputLength: 2_000,
|
|
985
|
+
});
|
|
986
|
+
return !result.error && !result.timedOut && result.exitCode === 0;
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
async function addDockerComposeRunner(runners, cwd) {
|
|
990
|
+
const composeFile = await firstExistingRunnerFile(cwd, APP_RUNNER_DOCKER_COMPOSE_FILES);
|
|
991
|
+
if (!composeFile) return;
|
|
992
|
+
if (await appRunnerCommandAvailable("docker", cwd) && await dockerComposePluginAvailable(cwd)) {
|
|
993
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
994
|
+
id: appRunnerId("docker-compose", composeFile),
|
|
995
|
+
label: "docker compose up",
|
|
996
|
+
kind: "docker",
|
|
997
|
+
command: "docker",
|
|
998
|
+
args: ["compose", "-f", composeFile, "up"],
|
|
999
|
+
projectFile: composeFile,
|
|
1000
|
+
description: "Detected Docker Compose file",
|
|
1001
|
+
priority: 82,
|
|
1002
|
+
}));
|
|
1003
|
+
}
|
|
1004
|
+
if (await appRunnerCommandAvailable("docker-compose", cwd)) {
|
|
1005
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
1006
|
+
id: appRunnerId("docker-compose-standalone", composeFile),
|
|
1007
|
+
label: "docker-compose up",
|
|
1008
|
+
kind: "docker",
|
|
1009
|
+
command: "docker-compose",
|
|
1010
|
+
args: ["-f", composeFile, "up"],
|
|
1011
|
+
projectFile: composeFile,
|
|
1012
|
+
description: "Detected Docker Compose file",
|
|
1013
|
+
priority: 84,
|
|
1014
|
+
}));
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
function shellFromShebang(text) {
|
|
1019
|
+
const firstLine = String(text || "").split(/\r?\n/, 1)[0] || "";
|
|
1020
|
+
if (!firstLine.startsWith("#!")) return "";
|
|
1021
|
+
if (/\bfish\b/.test(firstLine)) return "fish";
|
|
1022
|
+
if (/\bzsh\b/.test(firstLine)) return "zsh";
|
|
1023
|
+
if (/\bbash\b/.test(firstLine)) return "bash";
|
|
1024
|
+
if (/\bsh\b/.test(firstLine)) return "bash";
|
|
1025
|
+
return "";
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
function pythonFromShebang(text) {
|
|
1029
|
+
const firstLine = String(text || "").split(/\r?\n/, 1)[0] || "";
|
|
1030
|
+
return firstLine.startsWith("#!") && /\bpython(?:3(?:\.\d+)?)?\b/i.test(firstLine);
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
function shellScriptPriority(relativePath, shell) {
|
|
1034
|
+
const base = path.basename(relativePath).replace(/\.(?:sh|bash|zsh|fish)$/i, "").toLowerCase();
|
|
1035
|
+
const directory = path.dirname(relativePath).replace(/\\/g, "/");
|
|
1036
|
+
const nameRank = ["dev", "start", "run", "serve", "server", "app", "main"].indexOf(base);
|
|
1037
|
+
const dirRank = APP_RUNNER_SHELL_SCRIPT_DIRS.indexOf(directory === "." ? "" : directory);
|
|
1038
|
+
const shellRank = shell === "bash" ? 0 : shell === "zsh" ? 1 : shell === "fish" ? 2 : 3;
|
|
1039
|
+
return 70 + (nameRank === -1 ? 18 : nameRank) + (dirRank === -1 ? 8 : dirRank) + shellRank / 10;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
async function shellScriptRunnerForFile(cwd, relativePath, { canonicalProjectRoot = "", runnerCwd = "" } = {}) {
|
|
1043
|
+
let file;
|
|
1044
|
+
if (canonicalProjectRoot) {
|
|
1045
|
+
file = await appRunnerCanonicalFileInsideProject(cwd, relativePath, canonicalProjectRoot);
|
|
1046
|
+
if (!file) return null;
|
|
1047
|
+
}
|
|
1048
|
+
const extensionShell = APP_RUNNER_SHELL_EXTENSIONS.get(path.extname(relativePath).toLowerCase()) || "";
|
|
1049
|
+
let shell = extensionShell;
|
|
1050
|
+
if (!shell) {
|
|
1051
|
+
const text = file
|
|
1052
|
+
? await appRunnerFilePrefix(file.canonicalPath)
|
|
1053
|
+
: await appRunnerTextIfExists(cwd, relativePath, 256);
|
|
1054
|
+
shell = shellFromShebang(text);
|
|
1055
|
+
}
|
|
1056
|
+
if (!shell || !await appRunnerCommandAvailable(shell, cwd)) return null;
|
|
1057
|
+
const fileName = path.basename(relativePath);
|
|
1058
|
+
const directory = path.dirname(relativePath);
|
|
1059
|
+
return appRunnerCandidate({
|
|
1060
|
+
id: appRunnerId("shell", shell, relativePath),
|
|
1061
|
+
label: fileName,
|
|
1062
|
+
kind: "shell",
|
|
1063
|
+
command: shell,
|
|
1064
|
+
args: [relativePath],
|
|
1065
|
+
projectFile: relativePath,
|
|
1066
|
+
description: `Detected ${shell} shell script${directory && directory !== "." ? ` in ${directory}` : ""}`,
|
|
1067
|
+
priority: shellScriptPriority(relativePath, shell),
|
|
1068
|
+
cwd: runnerCwd,
|
|
1069
|
+
});
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
async function pythonScriptRunnersForFile(cwd, relativePath, { canonicalProjectRoot, runnerCwd, uvAvailable, pythonCommand }) {
|
|
1073
|
+
if (!uvAvailable && !pythonCommand) return [];
|
|
1074
|
+
const file = await appRunnerCanonicalFileInsideProject(cwd, relativePath, canonicalProjectRoot);
|
|
1075
|
+
if (!file) return [];
|
|
1076
|
+
const extension = path.extname(relativePath).toLowerCase();
|
|
1077
|
+
if (extension !== ".py") {
|
|
1078
|
+
if (path.basename(relativePath).includes(".")) return [];
|
|
1079
|
+
const text = await appRunnerFilePrefix(file.canonicalPath);
|
|
1080
|
+
if (!pythonFromShebang(text)) return [];
|
|
1081
|
+
}
|
|
1082
|
+
const directory = path.dirname(relativePath);
|
|
1083
|
+
const descriptionSuffix = directory && directory !== "." ? ` in ${directory}` : "";
|
|
1084
|
+
const candidates = [];
|
|
1085
|
+
if (uvAvailable) {
|
|
1086
|
+
candidates.push(appRunnerCandidate({
|
|
1087
|
+
id: appRunnerId("python", "uv", relativePath),
|
|
1088
|
+
label: `uv run ${path.basename(relativePath)}`,
|
|
1089
|
+
kind: "python",
|
|
1090
|
+
command: "uv",
|
|
1091
|
+
args: ["run", relativePath],
|
|
1092
|
+
projectFile: relativePath,
|
|
1093
|
+
description: `Detected Python script${descriptionSuffix} from a configured project discovery path`,
|
|
1094
|
+
priority: 56,
|
|
1095
|
+
cwd: runnerCwd,
|
|
1096
|
+
}));
|
|
1097
|
+
}
|
|
1098
|
+
if (pythonCommand) {
|
|
1099
|
+
candidates.push(appRunnerCandidate({
|
|
1100
|
+
id: appRunnerId("python", pythonCommand, relativePath),
|
|
1101
|
+
label: `${pythonCommand} ${path.basename(relativePath)}`,
|
|
1102
|
+
kind: "python",
|
|
1103
|
+
command: pythonCommand,
|
|
1104
|
+
args: [relativePath],
|
|
1105
|
+
projectFile: relativePath,
|
|
1106
|
+
description: `Detected Python script${descriptionSuffix} from a configured project discovery path`,
|
|
1107
|
+
priority: 69,
|
|
1108
|
+
cwd: runnerCwd,
|
|
1109
|
+
}));
|
|
1110
|
+
}
|
|
1111
|
+
return candidates;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
function shellScriptEntrySupported(entry) {
|
|
1115
|
+
const extension = path.extname(entry.name).toLowerCase();
|
|
1116
|
+
return APP_RUNNER_SHELL_EXTENSIONS.has(extension) || !entry.name.includes(".");
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
function configuredScriptEntrySupported(entry) {
|
|
1120
|
+
return shellScriptEntrySupported(entry) || path.extname(entry.name).toLowerCase() === ".py";
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
async function addConfiguredScriptRunners(runners, cwd) {
|
|
1124
|
+
const projectRoot = await findAppRunnerProjectRoot(cwd);
|
|
1125
|
+
const config = await readAppRunnerConfig(projectRoot);
|
|
1126
|
+
const [uvAvailable, python3Available, pythonAvailable] = await Promise.all([
|
|
1127
|
+
appRunnerCommandAvailable("uv", projectRoot),
|
|
1128
|
+
appRunnerCommandAvailable("python3", projectRoot),
|
|
1129
|
+
appRunnerCommandAvailable("python", projectRoot),
|
|
1130
|
+
]);
|
|
1131
|
+
const pythonCommand = python3Available ? "python3" : pythonAvailable ? "python" : "";
|
|
1132
|
+
let pythonFilesAdded = 0;
|
|
1133
|
+
for (const directory of config.availableSearchPaths) {
|
|
1134
|
+
const shellLimitReached = runners.filter((item) => item.kind === "shell").length >= APP_RUNNER_SHELL_SCRIPT_LIMIT;
|
|
1135
|
+
if (shellLimitReached && pythonFilesAdded >= APP_RUNNER_PYTHON_SCRIPT_LIMIT) break;
|
|
1136
|
+
const entries = await readdir(directory.canonicalPath, { withFileTypes: true }).catch(() => []);
|
|
1137
|
+
const sortedEntries = entries
|
|
1138
|
+
.filter((entry) => (entry.isFile() || entry.isSymbolicLink()) && configuredScriptEntrySupported(entry))
|
|
1139
|
+
.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }))
|
|
1140
|
+
.slice(0, APP_RUNNER_CONFIGURED_SCRIPT_SCAN_LIMIT);
|
|
1141
|
+
for (const entry of sortedEntries) {
|
|
1142
|
+
const relativePath = directory.path === "." ? entry.name : `${directory.path}/${entry.name}`;
|
|
1143
|
+
if (runners.filter((item) => item.kind === "shell").length < APP_RUNNER_SHELL_SCRIPT_LIMIT && shellScriptEntrySupported(entry)) {
|
|
1144
|
+
const shellRunner = await shellScriptRunnerForFile(projectRoot, relativePath, {
|
|
1145
|
+
canonicalProjectRoot: config.canonicalProjectRoot,
|
|
1146
|
+
runnerCwd: projectRoot,
|
|
1147
|
+
});
|
|
1148
|
+
if (shellRunner) addAppRunner(runners, shellRunner);
|
|
1149
|
+
}
|
|
1150
|
+
if (pythonFilesAdded < APP_RUNNER_PYTHON_SCRIPT_LIMIT && (path.extname(entry.name).toLowerCase() === ".py" || !entry.name.includes("."))) {
|
|
1151
|
+
const pythonRunners = await pythonScriptRunnersForFile(projectRoot, relativePath, {
|
|
1152
|
+
canonicalProjectRoot: config.canonicalProjectRoot,
|
|
1153
|
+
runnerCwd: projectRoot,
|
|
1154
|
+
uvAvailable,
|
|
1155
|
+
pythonCommand,
|
|
1156
|
+
});
|
|
1157
|
+
for (const pythonRunner of pythonRunners) addAppRunner(runners, pythonRunner);
|
|
1158
|
+
if (pythonRunners.length) pythonFilesAdded += 1;
|
|
1159
|
+
}
|
|
1160
|
+
if (runners.filter((item) => item.kind === "shell").length >= APP_RUNNER_SHELL_SCRIPT_LIMIT && pythonFilesAdded >= APP_RUNNER_PYTHON_SCRIPT_LIMIT) break;
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
async function addShellScriptRunners(runners, cwd) {
|
|
1166
|
+
const candidates = [];
|
|
1167
|
+
for (const directory of APP_RUNNER_SHELL_SCRIPT_DIRS) {
|
|
1168
|
+
const absoluteDirectory = path.join(cwd, directory || ".");
|
|
1169
|
+
const stats = await fileStatsIfExists(absoluteDirectory);
|
|
1170
|
+
if (!stats?.isDirectory()) continue;
|
|
1171
|
+
const entries = await readdir(absoluteDirectory, { withFileTypes: true }).catch(() => []);
|
|
1172
|
+
for (const entry of entries) {
|
|
1173
|
+
if (!entry.isFile()) continue;
|
|
1174
|
+
const relativePath = directory ? `${directory}/${entry.name}` : entry.name;
|
|
1175
|
+
if (!shellScriptEntrySupported(entry)) continue;
|
|
1176
|
+
candidates.push(relativePath);
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
for (const relativePath of candidates.slice(0, APP_RUNNER_SHELL_SCRIPT_LIMIT * 2)) {
|
|
1181
|
+
const runner = await shellScriptRunnerForFile(cwd, relativePath);
|
|
1182
|
+
if (runner) addAppRunner(runners, runner);
|
|
1183
|
+
if (runners.filter((item) => item.kind === "shell").length >= APP_RUNNER_SHELL_SCRIPT_LIMIT) break;
|
|
1184
|
+
}
|
|
1185
|
+
await addConfiguredScriptRunners(runners, cwd);
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
function firstTaskFromText(text, names) {
|
|
1189
|
+
for (const name of names) {
|
|
1190
|
+
const pattern = new RegExp(`^[\\s\"']*${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\"']*[:=]`, "m");
|
|
1191
|
+
if (pattern.test(text)) return name;
|
|
1192
|
+
}
|
|
1193
|
+
return "";
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
async function addDenoRunner(runners, cwd) {
|
|
1197
|
+
const hasDenoConfig = await appRunnerFileExists(cwd, "deno.json") || await appRunnerFileExists(cwd, "deno.jsonc");
|
|
1198
|
+
if (!hasDenoConfig || !await appRunnerCommandAvailable("deno", cwd)) return;
|
|
1199
|
+
const configText = (await appRunnerTextIfExists(cwd, "deno.json")) || (await appRunnerTextIfExists(cwd, "deno.jsonc"));
|
|
1200
|
+
const task = firstTaskFromText(configText, ["dev", "start", "serve"]);
|
|
1201
|
+
if (task) {
|
|
1202
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
1203
|
+
id: appRunnerId("deno", task),
|
|
1204
|
+
label: `deno task ${task}`,
|
|
1205
|
+
kind: "deno",
|
|
1206
|
+
command: "deno",
|
|
1207
|
+
args: ["task", task],
|
|
1208
|
+
projectFile: "deno.json",
|
|
1209
|
+
description: "Detected Deno task",
|
|
1210
|
+
priority: 52,
|
|
1211
|
+
}));
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
async function addTaskFileRunners(runners, cwd) {
|
|
1216
|
+
const [justText, makeText] = await Promise.all([
|
|
1217
|
+
appRunnerTextIfExists(cwd, "justfile").then((text) => text || appRunnerTextIfExists(cwd, "Justfile")),
|
|
1218
|
+
appRunnerTextIfExists(cwd, "Makefile").then((text) => text || appRunnerTextIfExists(cwd, "makefile")),
|
|
1219
|
+
]);
|
|
1220
|
+
const justTarget = firstTaskFromText(justText, ["dev", "run", "start"]);
|
|
1221
|
+
if (justTarget && await appRunnerCommandAvailable("just", cwd)) {
|
|
1222
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
1223
|
+
id: appRunnerId("just", justTarget),
|
|
1224
|
+
label: `just ${justTarget}`,
|
|
1225
|
+
kind: "task",
|
|
1226
|
+
command: "just",
|
|
1227
|
+
args: [justTarget],
|
|
1228
|
+
projectFile: "Justfile",
|
|
1229
|
+
description: "Detected just recipe",
|
|
1230
|
+
priority: 74,
|
|
1231
|
+
}));
|
|
1232
|
+
}
|
|
1233
|
+
const makeTarget = firstTaskFromText(makeText, ["dev", "run", "start"]);
|
|
1234
|
+
if (makeTarget && await appRunnerCommandAvailable("make", cwd)) {
|
|
1235
|
+
addAppRunner(runners, appRunnerCandidate({
|
|
1236
|
+
id: appRunnerId("make", makeTarget),
|
|
1237
|
+
label: `make ${makeTarget}`,
|
|
1238
|
+
kind: "task",
|
|
1239
|
+
command: "make",
|
|
1240
|
+
args: [makeTarget],
|
|
1241
|
+
projectFile: "Makefile",
|
|
1242
|
+
description: "Detected Make target",
|
|
1243
|
+
priority: 76,
|
|
1244
|
+
}));
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
function publicAppRunner(runner) {
|
|
1249
|
+
if (!runner) return null;
|
|
1250
|
+
const { priority: _priority, ...publicRunner } = runner;
|
|
1251
|
+
return publicRunner;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
async function detectAppRunners(tab) {
|
|
1255
|
+
const cwd = tab?.cwd || defaultCwd;
|
|
1256
|
+
const runners = [];
|
|
1257
|
+
const pkg = await readJsonFileIfExists(path.join(cwd, "package.json"));
|
|
1258
|
+
await Promise.all([
|
|
1259
|
+
addCustomAppRunners(runners, cwd),
|
|
1260
|
+
addRustRunner(runners, cwd),
|
|
1261
|
+
pkg ? addPackageManagerRunners(runners, cwd, pkg) : Promise.resolve(),
|
|
1262
|
+
pkg ? addNpxFrameworkRunners(runners, cwd, pkg) : Promise.resolve(),
|
|
1263
|
+
addPythonRunners(runners, cwd),
|
|
1264
|
+
addGoRunner(runners, cwd),
|
|
1265
|
+
addZigRunner(runners, cwd),
|
|
1266
|
+
addCppRunners(runners, cwd),
|
|
1267
|
+
addDockerComposeRunner(runners, cwd),
|
|
1268
|
+
addShellScriptRunners(runners, cwd),
|
|
1269
|
+
addDenoRunner(runners, cwd),
|
|
1270
|
+
addTaskFileRunners(runners, cwd),
|
|
1271
|
+
addNodeEntrypointRunner(runners, cwd, !!pkg),
|
|
1272
|
+
]);
|
|
1273
|
+
return runners
|
|
1274
|
+
.sort((a, b) => a.priority - b.priority || a.label.localeCompare(b.label))
|
|
1275
|
+
.map(publicAppRunner);
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
function appRunnerPendingLine(run) {
|
|
1279
|
+
if (!run || run.status !== "running") return "";
|
|
1280
|
+
return [run.stdoutRemainder, run.stderrRemainder].map((part) => String(part || "")).filter(Boolean).join("");
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
function publicAppRunnerState(run) {
|
|
1284
|
+
if (!run) return null;
|
|
1285
|
+
return {
|
|
1286
|
+
id: run.id,
|
|
1287
|
+
runnerId: run.runnerId,
|
|
1288
|
+
kind: run.kind,
|
|
1289
|
+
label: run.label,
|
|
1290
|
+
command: run.command,
|
|
1291
|
+
args: run.args,
|
|
1292
|
+
displayCommand: run.displayCommand,
|
|
1293
|
+
cwd: run.cwd,
|
|
1294
|
+
pid: run.pid,
|
|
1295
|
+
status: run.status,
|
|
1296
|
+
executionMode: run.executionMode || "pipe",
|
|
1297
|
+
startedAt: run.startedAt,
|
|
1298
|
+
endedAt: run.endedAt,
|
|
1299
|
+
exitCode: run.exitCode,
|
|
1300
|
+
signal: run.signal,
|
|
1301
|
+
stopping: run.stopping === true,
|
|
1302
|
+
truncated: run.truncated === true,
|
|
1303
|
+
lineCount: run.lineCount || run.lines?.length || 0,
|
|
1304
|
+
lines: Array.isArray(run.lines) ? [...run.lines] : [],
|
|
1305
|
+
pendingLine: appRunnerPendingLine(run),
|
|
1306
|
+
stdinClosed: run.stdinClosed === true,
|
|
1307
|
+
stdinError: run.stdinError || "",
|
|
1308
|
+
stdinWrites: run.stdinWrites || 0,
|
|
1309
|
+
lastStdinAt: run.lastStdinAt || "",
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
async function getAppRunnerData(tab) {
|
|
1314
|
+
const [runners, customRunnerConfig] = await Promise.all([
|
|
1315
|
+
detectAppRunners(tab),
|
|
1316
|
+
getCustomAppRunnerConfigData(tab),
|
|
1317
|
+
]);
|
|
1318
|
+
return {
|
|
1319
|
+
cwd: tab.cwd,
|
|
1320
|
+
runners,
|
|
1321
|
+
customRunnerConfig,
|
|
1322
|
+
activeRun: publicAppRunnerState(tab.appRunner),
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
function appendAppRunnerLine(run, line) {
|
|
1327
|
+
if (!run) return;
|
|
1328
|
+
const text = String(line ?? "");
|
|
1329
|
+
run.lines.push(text);
|
|
1330
|
+
run.lineCount = (run.lineCount || 0) + 1;
|
|
1331
|
+
run.outputChars = (run.outputChars || 0) + text.length + 1;
|
|
1332
|
+
while (run.lines.length > APP_RUNNER_OUTPUT_LINE_LIMIT || run.outputChars > APP_RUNNER_OUTPUT_MAX_CHARS) {
|
|
1333
|
+
const removed = run.lines.shift();
|
|
1334
|
+
run.outputChars -= String(removed || "").length + 1;
|
|
1335
|
+
run.truncated = true;
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
function appendAppRunnerChunk(tab, run, chunk, streamName) {
|
|
1340
|
+
if (!run || run.status !== "running") return;
|
|
1341
|
+
const key = streamName === "stderr" ? "stderrRemainder" : "stdoutRemainder";
|
|
1342
|
+
const carriageReturnKey = streamName === "stderr" ? "stderrCarriageReturnPending" : "stdoutCarriageReturnPending";
|
|
1343
|
+
const reduced = consumeAppRunnerTerminalChunk({
|
|
1344
|
+
line: run[key],
|
|
1345
|
+
carriageReturnPending: run[carriageReturnKey],
|
|
1346
|
+
}, chunk);
|
|
1347
|
+
run[key] = reduced.line;
|
|
1348
|
+
run[carriageReturnKey] = reduced.carriageReturnPending;
|
|
1349
|
+
for (const line of reduced.lines) appendAppRunnerLine(run, line);
|
|
1350
|
+
scheduleAppRunnerBroadcast(tab);
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
function flushAppRunnerRemainders(run) {
|
|
1354
|
+
for (const [key, carriageReturnKey] of [
|
|
1355
|
+
["stdoutRemainder", "stdoutCarriageReturnPending"],
|
|
1356
|
+
["stderrRemainder", "stderrCarriageReturnPending"],
|
|
1357
|
+
]) {
|
|
1358
|
+
if (run?.[key]) {
|
|
1359
|
+
appendAppRunnerLine(run, run[key]);
|
|
1360
|
+
run[key] = "";
|
|
1361
|
+
}
|
|
1362
|
+
if (run) run[carriageReturnKey] = false;
|
|
1363
|
+
}
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
function appRunnerStatusLabel(run) {
|
|
1367
|
+
if (run?.stopping && run.status === "running") return "stopping";
|
|
1368
|
+
if (run?.status === "done") return "exit 0";
|
|
1369
|
+
if (run?.status === "failed") return run.signal ? `signal ${run.signal}` : `exit ${run.exitCode ?? "?"}`;
|
|
1370
|
+
if (run?.status === "error") return "error";
|
|
1371
|
+
return run?.status || "running";
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
function broadcastAppRunnerState(tab) {
|
|
1375
|
+
broadcastTabEvent(tab, {
|
|
1376
|
+
type: "webui_app_runner_update",
|
|
1377
|
+
tabId: tab.id,
|
|
1378
|
+
tabTitle: tab.title,
|
|
1379
|
+
cwd: tab.cwd,
|
|
1380
|
+
command: tab.appRunner?.displayCommand,
|
|
1381
|
+
activeRun: publicAppRunnerState(tab.appRunner),
|
|
1382
|
+
tabActivity: tabActivitySnapshot(tab),
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
function scheduleAppRunnerBroadcast(tab) {
|
|
1387
|
+
if (!tab || tab.appRunnerBroadcastTimer) return;
|
|
1388
|
+
tab.appRunnerBroadcastTimer = setTimeout(() => {
|
|
1389
|
+
tab.appRunnerBroadcastTimer = null;
|
|
1390
|
+
if (hasTab(tab.id)) broadcastAppRunnerState(tab);
|
|
1391
|
+
}, 120);
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
function appRunnerChildActive(run) {
|
|
1395
|
+
if (!run?.child || run.settled) return false;
|
|
1396
|
+
if (run.executionMode === "conpty") return true;
|
|
1397
|
+
return run.child.exitCode === null && run.child.signalCode === null;
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
function terminateAppRunnerChild(run, signal = "SIGTERM") {
|
|
1401
|
+
if (!appRunnerChildActive(run)) return false;
|
|
1402
|
+
return terminateProcessTree(run.child, signal);
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
function appRunnerStdinWritable(run) {
|
|
1406
|
+
if (!appRunnerChildActive(run) || run.stdinClosed === true) return false;
|
|
1407
|
+
if (run.executionMode === "conpty") return typeof run.child.write === "function";
|
|
1408
|
+
const stdin = run.child.stdin;
|
|
1409
|
+
return !!stdin && !stdin.destroyed && !stdin.writableEnded;
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
function interruptAppRunnerChild(run) {
|
|
1413
|
+
if (!appRunnerChildActive(run)) return false;
|
|
1414
|
+
if (run.executionMode === "conpty" && appRunnerStdinWritable(run)) {
|
|
1415
|
+
try {
|
|
1416
|
+
run.child.write("\x03");
|
|
1417
|
+
return true;
|
|
1418
|
+
} catch {
|
|
1419
|
+
// Fall back to process-tree termination below.
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
// Writing ETX to a Windows pipe is data, not a console Ctrl+C event. Kill the
|
|
1423
|
+
// complete tree there so npm/bash wrappers cannot leave orphaned servers.
|
|
1424
|
+
if (process.platform === "win32") return terminateAppRunnerChild(run, "SIGKILL");
|
|
1425
|
+
if (appRunnerStdinWritable(run) && run.executionMode === "pty") {
|
|
1426
|
+
try {
|
|
1427
|
+
run.child.stdin.write("\x03", "utf8");
|
|
1428
|
+
return true;
|
|
1429
|
+
} catch {
|
|
1430
|
+
// Fall back to process signals below.
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
return terminateAppRunnerChild(run, "SIGINT");
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
function finishAppRunner(tab, run, patch = {}) {
|
|
1437
|
+
if (!run || run.settled) return;
|
|
1438
|
+
run.settled = true;
|
|
1439
|
+
clearTimeout(run.stopTimer);
|
|
1440
|
+
flushAppRunnerRemainders(run);
|
|
1441
|
+
run.endedAt = new Date().toISOString();
|
|
1442
|
+
run.exitCode = patch.exitCode;
|
|
1443
|
+
run.signal = patch.signal;
|
|
1444
|
+
run.error = patch.error;
|
|
1445
|
+
run.status = patch.error ? "error" : patch.exitCode === 0 ? "done" : "failed";
|
|
1446
|
+
for (const disposable of run.ptyDisposables || []) {
|
|
1447
|
+
try {
|
|
1448
|
+
disposable?.dispose?.();
|
|
1449
|
+
} catch {
|
|
1450
|
+
// The PTY has already exited; listener cleanup is best effort.
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
run.ptyDisposables = [];
|
|
1454
|
+
run.child = null;
|
|
1455
|
+
run.stdinClosed = true;
|
|
1456
|
+
run.stopping = false;
|
|
1457
|
+
appendAppRunnerLine(run, `# ${appRunnerStatusLabel(run)} after ${Math.max(0, Math.round((Date.parse(run.endedAt) - Date.parse(run.startedAt)) / 1000))}s`);
|
|
1458
|
+
if (patch.error) appendAppRunnerLine(run, `# ${patch.error}`);
|
|
1459
|
+
recordEvent({ type: "webui_app_runner_exit", tabId: tab.id, tabTitle: tab.title, command: run.displayCommand, code: run.exitCode, signal: run.signal, error: run.error });
|
|
1460
|
+
clearTimeout(tab.appRunnerBroadcastTimer);
|
|
1461
|
+
tab.appRunnerBroadcastTimer = null;
|
|
1462
|
+
broadcastAppRunnerState(tab);
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
function normalizeAppRunnerInputText(value) {
|
|
1466
|
+
const text = String(value ?? "");
|
|
1467
|
+
if (text.includes("\0")) throw makeHttpError(400, "App runner input cannot contain null bytes");
|
|
1468
|
+
if (text.length > APP_RUNNER_INPUT_MAX_CHARS) throw makeHttpError(413, `App runner input is too long; limit is ${APP_RUNNER_INPUT_MAX_CHARS} characters`);
|
|
1469
|
+
return text;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
function sendAppRunnerInput(tab, value, { appendNewline = true, closeStdin = false } = {}) {
|
|
1473
|
+
const run = tab?.appRunner;
|
|
1474
|
+
if (!run || run.status !== "running") throw makeHttpError(409, "No app runner is running in this tab");
|
|
1475
|
+
if (!appRunnerStdinWritable(run)) throw makeHttpError(409, "App runner stdin is closed");
|
|
1476
|
+
const text = normalizeAppRunnerInputText(value);
|
|
1477
|
+
const newline = run.executionMode === "conpty" && process.platform === "win32" ? "\r" : "\n";
|
|
1478
|
+
const chunk = `${text}${appendNewline === false ? "" : newline}`;
|
|
1479
|
+
if (!chunk && !closeStdin) throw makeHttpError(400, "App runner input is empty");
|
|
1480
|
+
let buffered = false;
|
|
1481
|
+
try {
|
|
1482
|
+
if (run.executionMode === "conpty") {
|
|
1483
|
+
if (chunk) run.child.write(chunk);
|
|
1484
|
+
else if (closeStdin) run.child.write("\x04");
|
|
1485
|
+
if (closeStdin) run.stdinClosed = true;
|
|
1486
|
+
} else {
|
|
1487
|
+
const stdin = run.child.stdin;
|
|
1488
|
+
if (closeStdin) {
|
|
1489
|
+
if (chunk) stdin.end(chunk, "utf8");
|
|
1490
|
+
else stdin.end();
|
|
1491
|
+
run.stdinClosed = true;
|
|
1492
|
+
} else {
|
|
1493
|
+
buffered = stdin.write(chunk, "utf8") === false;
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
} catch (error) {
|
|
1497
|
+
run.stdinClosed = true;
|
|
1498
|
+
run.stdinError = sanitizeError(error);
|
|
1499
|
+
throw makeHttpError(409, `App runner stdin write failed: ${run.stdinError}`);
|
|
1500
|
+
}
|
|
1501
|
+
run.stdinWrites = (run.stdinWrites || 0) + 1;
|
|
1502
|
+
run.lastStdinAt = new Date().toISOString();
|
|
1503
|
+
const closeSuffix = closeStdin ? " and closed" : "";
|
|
1504
|
+
if (chunk) appendAppRunnerLine(run, text ? `# stdin sent (${text.length} char${text.length === 1 ? "" : "s"})${closeSuffix}` : `# stdin sent (Enter)${closeSuffix}`);
|
|
1505
|
+
else appendAppRunnerLine(run, "# stdin closed (EOF)");
|
|
1506
|
+
recordEvent({ type: "webui_app_runner_stdin", tabId: tab.id, tabTitle: tab.title, command: run.displayCommand, chars: text.length, newline: appendNewline !== false, closed: closeStdin === true });
|
|
1507
|
+
scheduleAppRunnerBroadcast(tab);
|
|
1508
|
+
return { cwd: tab.cwd, activeRun: publicAppRunnerState(run), inputBuffered: buffered };
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
async function startAppRunner(tab, runnerId) {
|
|
1512
|
+
if (tab.appRunner?.status === "running") throw makeHttpError(409, `App runner already running: ${tab.appRunner.displayCommand}`);
|
|
1513
|
+
const runners = await detectAppRunners(tab);
|
|
1514
|
+
const runner = runners.find((item) => item.id === runnerId) || (runners.length === 1 && !runnerId ? runners[0] : null);
|
|
1515
|
+
if (!runner) throw makeHttpError(400, "Selected app runner is unavailable in this tab cwd");
|
|
1516
|
+
|
|
1517
|
+
const run = {
|
|
1518
|
+
id: randomUUID(),
|
|
1519
|
+
runnerId: runner.id,
|
|
1520
|
+
kind: runner.kind,
|
|
1521
|
+
label: runner.label,
|
|
1522
|
+
command: runner.command,
|
|
1523
|
+
args: runner.args || [],
|
|
1524
|
+
displayCommand: runner.displayCommand,
|
|
1525
|
+
cwd: runner.cwd || tab.cwd,
|
|
1526
|
+
status: "running",
|
|
1527
|
+
startedAt: new Date().toISOString(),
|
|
1528
|
+
lines: [],
|
|
1529
|
+
lineCount: 0,
|
|
1530
|
+
outputChars: 0,
|
|
1531
|
+
stdinClosed: false,
|
|
1532
|
+
stdinWrites: 0,
|
|
1533
|
+
};
|
|
1534
|
+
appendAppRunnerLine(run, `$ ${run.displayCommand}`);
|
|
1535
|
+
const child = await spawnAppRunnerChild(run);
|
|
1536
|
+
run.child = child;
|
|
1537
|
+
run.pid = child.pid;
|
|
1538
|
+
tab.appRunner = run;
|
|
1539
|
+
|
|
1540
|
+
if (run.executionMode === "conpty") {
|
|
1541
|
+
run.ptyDisposables = [
|
|
1542
|
+
child.onData((chunk) => appendAppRunnerChunk(tab, run, chunk, "stdout")),
|
|
1543
|
+
child.onExit(({ exitCode, signal }) => finishAppRunner(tab, run, { exitCode, signal })),
|
|
1544
|
+
];
|
|
1545
|
+
} else {
|
|
1546
|
+
child.stdin?.on("error", (error) => {
|
|
1547
|
+
run.stdinClosed = true;
|
|
1548
|
+
run.stdinError = sanitizeError(error);
|
|
1549
|
+
if (run.status === "running") {
|
|
1550
|
+
appendAppRunnerLine(run, `# stdin error: ${run.stdinError}`);
|
|
1551
|
+
scheduleAppRunnerBroadcast(tab);
|
|
1552
|
+
}
|
|
1553
|
+
});
|
|
1554
|
+
child.stdin?.on("close", () => {
|
|
1555
|
+
run.stdinClosed = true;
|
|
1556
|
+
if (run.status === "running") scheduleAppRunnerBroadcast(tab);
|
|
1557
|
+
});
|
|
1558
|
+
child.stdout.on("data", (chunk) => appendAppRunnerChunk(tab, run, chunk, "stdout"));
|
|
1559
|
+
child.stderr.on("data", (chunk) => appendAppRunnerChunk(tab, run, chunk, "stderr"));
|
|
1560
|
+
child.on("error", (error) => finishAppRunner(tab, run, { error: sanitizeError(error) }));
|
|
1561
|
+
child.on("exit", (exitCode, signal) => finishAppRunner(tab, run, { exitCode, signal }));
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
recordEvent({ type: "webui_app_runner_start", tabId: tab.id, tabTitle: tab.title, command: run.displayCommand, cwd: run.cwd, pid: run.pid });
|
|
1565
|
+
broadcastAppRunnerState(tab);
|
|
1566
|
+
return { runners, customRunnerConfig: await getCustomAppRunnerConfigData(tab), activeRun: publicAppRunnerState(run), cwd: tab.cwd };
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
function stopAppRunnerForTab(tab, reason = "stop requested", { force = false } = {}) {
|
|
1570
|
+
const run = tab?.appRunner;
|
|
1571
|
+
if (!run || run.status !== "running") return false;
|
|
1572
|
+
run.stopping = true;
|
|
1573
|
+
const action = run.executionMode === "conpty" && !force
|
|
1574
|
+
? "sending Ctrl+C"
|
|
1575
|
+
: process.platform === "win32" ? "terminating Windows process tree" : `sending ${force ? "SIGKILL" : "Ctrl+C"}`;
|
|
1576
|
+
appendAppRunnerLine(run, `# ${reason}; ${action}`);
|
|
1577
|
+
if (force) terminateAppRunnerChild(run, "SIGKILL");
|
|
1578
|
+
else interruptAppRunnerChild(run);
|
|
1579
|
+
if (!force) {
|
|
1580
|
+
clearTimeout(run.stopTimer);
|
|
1581
|
+
run.stopTimer = setTimeout(() => {
|
|
1582
|
+
if (run.status === "running") {
|
|
1583
|
+
appendAppRunnerLine(run, "# app runner did not stop within the grace period; forcing process-tree termination");
|
|
1584
|
+
terminateAppRunnerChild(run, "SIGKILL");
|
|
1585
|
+
scheduleAppRunnerBroadcast(tab);
|
|
1586
|
+
}
|
|
1587
|
+
}, APP_RUNNER_STOP_GRACE_MS);
|
|
1588
|
+
}
|
|
1589
|
+
broadcastAppRunnerState(tab);
|
|
1590
|
+
return true;
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
function clearAppRunnerForTab(tab) {
|
|
1594
|
+
if (!tab?.appRunner || tab.appRunner.status === "running") return false;
|
|
1595
|
+
tab.appRunner = null;
|
|
1596
|
+
broadcastAppRunnerState(tab);
|
|
1597
|
+
return true;
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
function normalizeAppRunnerContextLineCount(value) {
|
|
1601
|
+
const number = Number.parseInt(String(value ?? ""), 10);
|
|
1602
|
+
if (!Number.isFinite(number)) return APP_RUNNER_CONTEXT_DEFAULT_LINES;
|
|
1603
|
+
return Math.max(1, Math.min(APP_RUNNER_CONTEXT_MAX_LINES, number));
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
function appRunnerOutputLinesForContext(run) {
|
|
1607
|
+
const lines = Array.isArray(run?.lines) ? [...run.lines] : [];
|
|
1608
|
+
const pendingLine = appRunnerPendingLine(run);
|
|
1609
|
+
if (pendingLine) lines.push(pendingLine);
|
|
1610
|
+
return lines.map((line) => stripAnsi(line).replace(/\r\n?/g, "\n"));
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
function formatAppRunnerContextContent(tab, run, { requestedLineCount, lines, totalAvailableLines }) {
|
|
1614
|
+
const status = appRunnerStatusLabel(run);
|
|
1615
|
+
const capturedAt = new Date().toISOString();
|
|
1616
|
+
const header = [
|
|
1617
|
+
"App runner output transferred from Pi Web UI.",
|
|
1618
|
+
`Command: ${stripAnsi(run?.displayCommand || run?.command || "app runner")}`,
|
|
1619
|
+
`Cwd: ${stripAnsi(run?.cwd || tab?.cwd || "")}`,
|
|
1620
|
+
`Status: ${status}`,
|
|
1621
|
+
`Captured: last ${lines.length} of ${totalAvailableLines} available line${totalAvailableLines === 1 ? "" : "s"} (requested ${requestedLineCount})`,
|
|
1622
|
+
run?.truncated ? "Note: earlier app runner output had already been truncated before this capture." : "",
|
|
1623
|
+
`Captured at: ${capturedAt}`,
|
|
1624
|
+
].filter(Boolean);
|
|
1625
|
+
return `${header.join("\n")}\n\n\`\`\`\`text\n${lines.join("\n").trimEnd()}\n\`\`\`\``;
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
async function transferAppRunnerContext(tab, body = {}) {
|
|
1629
|
+
const run = tab?.appRunner;
|
|
1630
|
+
if (!run) throw makeHttpError(409, "No app runner output is available in this tab");
|
|
1631
|
+
const requestedLineCount = normalizeAppRunnerContextLineCount(body.lineCount ?? body.lines ?? body.count);
|
|
1632
|
+
const allLines = appRunnerOutputLinesForContext(run);
|
|
1633
|
+
const lines = allLines.slice(-requestedLineCount);
|
|
1634
|
+
if (!lines.some((line) => stripAnsi(line).trim())) throw makeHttpError(400, "App runner output is empty");
|
|
1635
|
+
const details = {
|
|
1636
|
+
runId: run.id,
|
|
1637
|
+
runnerId: run.runnerId,
|
|
1638
|
+
command: run.displayCommand || run.command || "",
|
|
1639
|
+
cwd: run.cwd || tab.cwd,
|
|
1640
|
+
status: run.status || "running",
|
|
1641
|
+
requestedLineCount,
|
|
1642
|
+
lineCount: lines.length,
|
|
1643
|
+
totalAvailableLines: allLines.length,
|
|
1644
|
+
truncated: run.truncated === true,
|
|
1645
|
+
capturedAt: new Date().toISOString(),
|
|
1646
|
+
};
|
|
1647
|
+
const content = formatAppRunnerContextContent(tab, run, { requestedLineCount, lines, totalAvailableLines: allLines.length });
|
|
1648
|
+
const helperData = await sendWebuiHelperCommand(tab, "app-runner-context", { content, details });
|
|
1649
|
+
recordEvent({ type: "webui_app_runner_context", tabId: tab.id, tabTitle: tab.title, command: details.command, lineCount: lines.length, requestedLineCount, delivery: helperData?.delivery || "context" });
|
|
1650
|
+
return { ...details, delivery: helperData?.delivery || "context", activeRun: publicAppRunnerState(run) };
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
return {
|
|
1654
|
+
getAppRunnerData,
|
|
1655
|
+
getCustomAppRunnerConfigData,
|
|
1656
|
+
saveCustomAppRunner,
|
|
1657
|
+
saveAppRunnerSearchPaths,
|
|
1658
|
+
deleteCustomAppRunner,
|
|
1659
|
+
getAppRunnerFileBrowserData,
|
|
1660
|
+
startAppRunner,
|
|
1661
|
+
sendAppRunnerInput,
|
|
1662
|
+
transferAppRunnerContext,
|
|
1663
|
+
stopAppRunnerForTab,
|
|
1664
|
+
clearAppRunnerForTab,
|
|
1665
|
+
publicAppRunnerState,
|
|
1666
|
+
};
|
|
1667
|
+
}
|