@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,408 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import {
|
|
7
|
+
WORKTREE_ERROR_CODES,
|
|
8
|
+
createGitWorktree,
|
|
9
|
+
openGitWorktree,
|
|
10
|
+
pathInside,
|
|
11
|
+
pruneGitWorktrees,
|
|
12
|
+
removeGitWorktree,
|
|
13
|
+
} from "../git-worktrees.mjs";
|
|
14
|
+
|
|
15
|
+
export function createGitWorktreeSessionService({
|
|
16
|
+
noSession,
|
|
17
|
+
getGitRoot,
|
|
18
|
+
gitMutations,
|
|
19
|
+
formatGitCommand,
|
|
20
|
+
makeHttpError,
|
|
21
|
+
sanitizeError,
|
|
22
|
+
configuredSessionDir,
|
|
23
|
+
currentSessionState,
|
|
24
|
+
tabRestorableSessionFile,
|
|
25
|
+
requireAllowedSessionPath,
|
|
26
|
+
getOpenTabs,
|
|
27
|
+
createTab,
|
|
28
|
+
tabMeta,
|
|
29
|
+
listTabs,
|
|
30
|
+
scheduleSupervisorMetadataUpdate,
|
|
31
|
+
recordEvent,
|
|
32
|
+
markTabWorking,
|
|
33
|
+
markTabIdle,
|
|
34
|
+
promptRequestTimeoutMs,
|
|
35
|
+
}) {
|
|
36
|
+
const {
|
|
37
|
+
readGitOperationSnapshot,
|
|
38
|
+
cleanGitBranchName,
|
|
39
|
+
validateGitBranchName,
|
|
40
|
+
expectedStagedContentHashFromBody,
|
|
41
|
+
readStagedContentHash,
|
|
42
|
+
gitWorkflowMessageCwd,
|
|
43
|
+
commitMessagePaths,
|
|
44
|
+
requestedRemoteRef,
|
|
45
|
+
verifyRemoteGitBranchIntent,
|
|
46
|
+
runGitWorkflowCommand,
|
|
47
|
+
requireConfirmed,
|
|
48
|
+
} = gitMutations;
|
|
49
|
+
|
|
50
|
+
function sameResolvedPath(left, right) {
|
|
51
|
+
return Boolean(left && right) && path.resolve(left) === path.resolve(right);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function gitConflictResolutionAgentPrompt(operation) {
|
|
55
|
+
const conflicts = (operation.conflicts || []).map((conflict) => `- ${conflict.status || "UU"} ${JSON.stringify(String(conflict.path || ""))}`);
|
|
56
|
+
const summary = operation.summary || {};
|
|
57
|
+
return [
|
|
58
|
+
`Resolve the current Git ${operation.operation} conflicts in this working tree.`,
|
|
59
|
+
"",
|
|
60
|
+
`Repository root: ${JSON.stringify(String(operation.root || ""))}`,
|
|
61
|
+
`Branch: ${operation.branch || "detached or unknown"}`,
|
|
62
|
+
`Working tree: ${summary.staged || 0} staged, ${summary.unstaged || 0} unstaged, ${conflicts.length} conflicted`,
|
|
63
|
+
"Conflicted files:",
|
|
64
|
+
...conflicts,
|
|
65
|
+
"",
|
|
66
|
+
"Requirements:",
|
|
67
|
+
"- Inspect git status plus the staged, unstaged, and unmerged diffs before editing.",
|
|
68
|
+
"- Resolve only the currently unmerged files and preserve the intended changes from both sides.",
|
|
69
|
+
"- Stage each resolved file with git add.",
|
|
70
|
+
`- Do not continue, skip, abort, commit, reset, or push the ${operation.operation}.`,
|
|
71
|
+
"- Verify git diff --name-only --diff-filter=U is empty, then report what you resolved and any uncertainty.",
|
|
72
|
+
].join("\n");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function openGitConflictResolutionAgentTab(sourceTab) {
|
|
76
|
+
const operation = await readGitOperationSnapshot(sourceTab.cwd);
|
|
77
|
+
if (!operation.operation || operation.operation === "bisect") throw makeHttpError(409, "No conflict-resolution Git operation is in progress");
|
|
78
|
+
if (!operation.conflicts?.length) throw makeHttpError(409, "No unmerged files remain to send to an agent");
|
|
79
|
+
|
|
80
|
+
const targetTab = await createTab({
|
|
81
|
+
title: `Resolve ${operation.operation} conflicts`,
|
|
82
|
+
titleSource: "explicit",
|
|
83
|
+
conversationStarted: true,
|
|
84
|
+
cwd: operation.root,
|
|
85
|
+
});
|
|
86
|
+
const command = { type: "prompt", message: gitConflictResolutionAgentPrompt(operation) };
|
|
87
|
+
markTabWorking(targetTab);
|
|
88
|
+
let response;
|
|
89
|
+
try {
|
|
90
|
+
response = await targetTab.rpc.send(command, promptRequestTimeoutMs);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
markTabIdle(targetTab);
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
if (response.success === false) {
|
|
96
|
+
markTabIdle(targetTab);
|
|
97
|
+
throw makeHttpError(502, response.error || "The conflict-resolution agent rejected the handoff prompt");
|
|
98
|
+
}
|
|
99
|
+
recordEvent({
|
|
100
|
+
type: "webui_git_conflict_agent_started",
|
|
101
|
+
sourceTabId: sourceTab.id,
|
|
102
|
+
tabId: targetTab.id,
|
|
103
|
+
cwd: operation.root,
|
|
104
|
+
operation: operation.operation,
|
|
105
|
+
conflicts: operation.conflicts.length,
|
|
106
|
+
});
|
|
107
|
+
return {
|
|
108
|
+
sourceTabId: sourceTab.id,
|
|
109
|
+
tab: tabMeta(targetTab),
|
|
110
|
+
tabs: listTabs(),
|
|
111
|
+
operation: {
|
|
112
|
+
operation: operation.operation,
|
|
113
|
+
root: operation.root,
|
|
114
|
+
branch: operation.branch,
|
|
115
|
+
conflicts: operation.conflicts.map(({ path: conflictPath, status }) => ({ path: conflictPath, status })),
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function normalizeWorktreeSessionMode(value) {
|
|
121
|
+
const mode = String(value || "fork-current").trim().toLowerCase();
|
|
122
|
+
if (!mode || mode === "fork" || mode === "fork-current") return "fork-current";
|
|
123
|
+
if (mode === "empty" || mode === "new") return "empty";
|
|
124
|
+
if (mode === "clone-current" || mode === "parent-only") {
|
|
125
|
+
throw makeHttpError(400, `sessionMode ${mode} is not supported yet; use fork-current or empty.`);
|
|
126
|
+
}
|
|
127
|
+
throw makeHttpError(400, "sessionMode must be fork-current or empty");
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function createEmptySessionFileForCwd(cwd) {
|
|
131
|
+
const manager = SessionManager.create(cwd, configuredSessionDir());
|
|
132
|
+
const sessionFile = manager.getSessionFile();
|
|
133
|
+
const header = manager.getHeader();
|
|
134
|
+
if (!sessionFile || !header) return undefined;
|
|
135
|
+
await mkdir(path.dirname(sessionFile), { recursive: true });
|
|
136
|
+
await writeFile(sessionFile, `${JSON.stringify(header)}\n`, { encoding: "utf8", flag: "wx" });
|
|
137
|
+
return sessionFile;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function prepareWorktreeSessionFile(sourceTab, targetCwd, requestedMode = "fork-current") {
|
|
141
|
+
if (noSession) return { mode: "none", requestedMode: "none", sessionFile: undefined, warning: "Web UI was started with --no-session." };
|
|
142
|
+
const mode = normalizeWorktreeSessionMode(requestedMode);
|
|
143
|
+
if (mode === "empty") {
|
|
144
|
+
return { mode, requestedMode: mode, sessionFile: await createEmptySessionFileForCwd(targetCwd) };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const state = await currentSessionState(sourceTab).catch(() => sourceTab?.lastState || {});
|
|
148
|
+
const sourceSessionFile = state.sessionFile || tabRestorableSessionFile(sourceTab);
|
|
149
|
+
if (sourceSessionFile) {
|
|
150
|
+
requireAllowedSessionPath(sourceSessionFile);
|
|
151
|
+
const sourceInfo = await stat(sourceSessionFile).catch(() => null);
|
|
152
|
+
if (sourceInfo?.isFile()) {
|
|
153
|
+
const manager = SessionManager.forkFrom(sourceSessionFile, targetCwd, configuredSessionDir());
|
|
154
|
+
return { mode, requestedMode: mode, sessionFile: manager.getSessionFile(), parentSession: sourceSessionFile };
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return {
|
|
159
|
+
mode: "empty",
|
|
160
|
+
requestedMode: mode,
|
|
161
|
+
sessionFile: await createEmptySessionFileForCwd(targetCwd),
|
|
162
|
+
warning: "Current session is not persisted yet; opened an empty session rooted at the worktree.",
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function gitWorkspaceFromWorktreeResult(result, worktree = result?.worktree) {
|
|
167
|
+
if (!worktree?.path) return null;
|
|
168
|
+
return {
|
|
169
|
+
repoRoot: result.repoRoot || worktree.repoRoot || "",
|
|
170
|
+
commonGitDir: result.commonGitDir || worktree.commonGitDir || "",
|
|
171
|
+
worktreePath: worktree.path,
|
|
172
|
+
branch: worktree.branch || result.branch || null,
|
|
173
|
+
worktreeCount: Array.isArray(result.worktrees) ? result.worktrees.length : undefined,
|
|
174
|
+
isMainWorktree: worktree.isMainWorktree === true,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async function openWorktreeResultForTab(sourceTab, result, body = {}) {
|
|
179
|
+
const worktree = result?.worktree;
|
|
180
|
+
const worktreePath = worktree?.path || result?.path;
|
|
181
|
+
if (!worktreePath) throw makeHttpError(500, "Git worktree operation did not return a path");
|
|
182
|
+
if (body.openTab === false) return { ...result, session: null, tab: null, tabs: listTabs(), openedTab: false };
|
|
183
|
+
|
|
184
|
+
if (sameResolvedPath(worktreePath, sourceTab.cwd)) {
|
|
185
|
+
sourceTab.gitWorkspace = gitWorkspaceFromWorktreeResult(result, worktree);
|
|
186
|
+
scheduleSupervisorMetadataUpdate(sourceTab);
|
|
187
|
+
return { ...result, session: null, tab: tabMeta(sourceTab), tabs: listTabs(), openedTab: false, openedCurrent: true };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const existingTab = [...getOpenTabs()].find((item) => sameResolvedPath(item.cwd, worktreePath));
|
|
191
|
+
if (existingTab) {
|
|
192
|
+
existingTab.gitWorkspace = gitWorkspaceFromWorktreeResult(result, worktree);
|
|
193
|
+
scheduleSupervisorMetadataUpdate(existingTab);
|
|
194
|
+
return { ...result, session: null, tab: tabMeta(existingTab), tabs: listTabs(), openedTab: false, openedExistingTab: true };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const session = await prepareWorktreeSessionFile(sourceTab, worktreePath, body.sessionMode || "fork-current");
|
|
198
|
+
const tab = await createTab({
|
|
199
|
+
title: body.title,
|
|
200
|
+
titleSource: body.title ? "explicit" : undefined,
|
|
201
|
+
cwd: worktreePath,
|
|
202
|
+
sessionFile: session.sessionFile,
|
|
203
|
+
gitWorkspace: gitWorkspaceFromWorktreeResult(result, worktree),
|
|
204
|
+
});
|
|
205
|
+
recordEvent({ type: "webui_worktree_opened", tabId: tab.id, tabTitle: tab.title, cwd: tab.cwd, branch: worktree.branch || result.branch || "", sessionMode: session.mode });
|
|
206
|
+
return {
|
|
207
|
+
...result,
|
|
208
|
+
session,
|
|
209
|
+
tab: tabMeta(tab),
|
|
210
|
+
tabs: listTabs(),
|
|
211
|
+
openedTab: true,
|
|
212
|
+
dependencyHint: "Git worktrees do not share ignored dependency directories such as node_modules or .venv; install/bootstrap dependencies manually if needed.",
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function cleanupCreatedWorktreeAfterFailure(sourceCwd, worktreePath) {
|
|
217
|
+
try {
|
|
218
|
+
return await removeGitWorktree(sourceCwd, worktreePath, { force: true });
|
|
219
|
+
} catch (error) {
|
|
220
|
+
return { ok: false, error: sanitizeError(error), code: error?.code || WORKTREE_ERROR_CODES.GIT_COMMAND_FAILED };
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function readGitWorkflowMessageFilesForTransfer(root, messageCwd = root) {
|
|
225
|
+
const { shortPath, longPath } = commitMessagePaths(messageCwd);
|
|
226
|
+
const files = [];
|
|
227
|
+
for (const sourcePath of [shortPath, longPath]) {
|
|
228
|
+
try {
|
|
229
|
+
const content = await readFile(sourcePath, "utf8");
|
|
230
|
+
files.push({ relativePath: path.relative(root, sourcePath).split(path.sep).join("/"), content });
|
|
231
|
+
} catch (error) {
|
|
232
|
+
if (error?.code !== "ENOENT") throw error;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return files;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function snapshotGitWorkflowBranchState(root, cwd = root, expectedStagedContentHash = "") {
|
|
239
|
+
const messageCwd = gitWorkflowMessageCwd(root, cwd);
|
|
240
|
+
// Preserve raw patch bytes: string decoding would corrupt binary staged
|
|
241
|
+
// changes before `git apply --index` can copy them to the PR worktree.
|
|
242
|
+
const staged = await readStagedContentHash(root);
|
|
243
|
+
if (expectedStagedContentHash && (!staged.hasStagedChanges || staged.stagedContentHash !== expectedStagedContentHash)) {
|
|
244
|
+
throw makeHttpError(409, "Staged content changed after manual approval. Return to Stage and request a new manual review before creating a PR worktree.");
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
stagedPatch: staged.stagedDiff,
|
|
248
|
+
stagedContentHash: staged.stagedContentHash,
|
|
249
|
+
messageFiles: await readGitWorkflowMessageFilesForTransfer(root, messageCwd),
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async function applyGitWorkflowBranchStateToWorktree(snapshot, worktreePath) {
|
|
254
|
+
const copiedMessageFiles = [];
|
|
255
|
+
let appliedStagedPatch = false;
|
|
256
|
+
const patchBytes = Buffer.isBuffer(snapshot?.stagedPatch) ? snapshot.stagedPatch : Buffer.alloc(0);
|
|
257
|
+
if (patchBytes.length > 0) {
|
|
258
|
+
const patchPath = path.join(tmpdir(), `pi-webui-staged-worktree-${process.pid}-${Date.now()}-${randomUUID()}.patch`);
|
|
259
|
+
try {
|
|
260
|
+
await writeFile(patchPath, patchBytes);
|
|
261
|
+
const applyResult = await runGitWorkflowCommand(["apply", "--index", "--whitespace=nowarn", patchPath], {
|
|
262
|
+
cwd: worktreePath,
|
|
263
|
+
label: "git apply --index <staged diff>",
|
|
264
|
+
timeoutMs: 5 * 60 * 1000,
|
|
265
|
+
});
|
|
266
|
+
if (applyResult.exitCode !== 0 || applyResult.timedOut || applyResult.cancelled || applyResult.error) {
|
|
267
|
+
throw new Error((applyResult.stderr || applyResult.stdout || applyResult.error || "Unable to apply staged changes in the PR worktree").trim());
|
|
268
|
+
}
|
|
269
|
+
appliedStagedPatch = true;
|
|
270
|
+
} finally {
|
|
271
|
+
await rm(patchPath, { force: true }).catch(() => {});
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
for (const file of snapshot?.messageFiles || []) {
|
|
276
|
+
const relativePath = String(file.relativePath || "").replace(/\\/g, "/");
|
|
277
|
+
const targetPath = path.resolve(worktreePath, relativePath);
|
|
278
|
+
if (!relativePath || !pathInside(worktreePath, targetPath)) throw new Error(`Refusing to copy Git workflow file outside the worktree: ${relativePath}`);
|
|
279
|
+
await mkdir(path.dirname(targetPath), { recursive: true });
|
|
280
|
+
await writeFile(targetPath, file.content, "utf8");
|
|
281
|
+
copiedMessageFiles.push(relativePath);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return { appliedStagedPatch, copiedMessageFiles };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function gitWorkflowBranchWorktreeStdout({ branch, worktreePath, createdResult, opened, transfer }) {
|
|
288
|
+
const lines = [];
|
|
289
|
+
if (createdResult?.created) lines.push(`Created branch worktree ${branch} at ${worktreePath}.`);
|
|
290
|
+
else if (createdResult?.openedExisting) lines.push(`Opened existing branch worktree ${branch} at ${worktreePath}.`);
|
|
291
|
+
else lines.push(`Opened branch worktree ${branch} at ${worktreePath}.`);
|
|
292
|
+
if (transfer?.appliedStagedPatch) lines.push("Copied the source checkout's staged changes into the worktree index.");
|
|
293
|
+
else if (createdResult?.openedExisting) lines.push("Existing worktree was reused; source staged changes were not copied automatically.");
|
|
294
|
+
else lines.push("No staged changes were copied because the source index was clean.");
|
|
295
|
+
if (transfer?.copiedMessageFiles?.length) lines.push(`Copied ${transfer.copiedMessageFiles.join(", ")} for commit message selection.`);
|
|
296
|
+
if (opened?.tab?.id) lines.push(`Continue the guided Git workflow in Web UI tab ${opened.tab.title || opened.tab.id}.`);
|
|
297
|
+
lines.push("The source checkout was left on its current branch.");
|
|
298
|
+
return lines.join("\n");
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function createGitWorkflowBranchWorktree(tab, body = {}) {
|
|
302
|
+
const root = await getGitRoot(tab.cwd);
|
|
303
|
+
const branch = cleanGitBranchName(body.branch || body.branchName);
|
|
304
|
+
await validateGitBranchName(root, branch);
|
|
305
|
+
const expectedStagedContentHash = expectedStagedContentHashFromBody(body);
|
|
306
|
+
const snapshot = await snapshotGitWorkflowBranchState(root, tab.cwd, expectedStagedContentHash);
|
|
307
|
+
let createdResult = null;
|
|
308
|
+
try {
|
|
309
|
+
createdResult = await createGitWorktree(tab.cwd, { ...body, branchName: branch });
|
|
310
|
+
const worktreePath = createdResult.worktree?.path || createdResult.path;
|
|
311
|
+
if (!worktreePath) throw makeHttpError(500, "Git workflow worktree creation did not return a path");
|
|
312
|
+
const transfer = createdResult.created
|
|
313
|
+
? await applyGitWorkflowBranchStateToWorktree(snapshot, worktreePath)
|
|
314
|
+
: { appliedStagedPatch: false, copiedMessageFiles: [] };
|
|
315
|
+
const opened = await openWorktreeResultForTab(tab, createdResult, { openTab: body.openTab !== false, sessionMode: body.sessionMode || "fork-current", ...body });
|
|
316
|
+
if (createdResult.created) {
|
|
317
|
+
recordEvent({ type: "webui_worktree_created", tabId: opened.tab?.id || tab.id, cwd: opened.worktree?.path || opened.path, branch });
|
|
318
|
+
}
|
|
319
|
+
recordEvent({ type: "webui_git_workflow_worktree", tabId: opened.tab?.id || tab.id, cwd: worktreePath, branch, transferredStagedChanges: transfer.appliedStagedPatch });
|
|
320
|
+
return {
|
|
321
|
+
...opened,
|
|
322
|
+
command: createdResult.created ? formatGitCommand(["worktree", "add", "-b", branch, worktreePath]) : formatGitCommand(["worktree", "list", "--porcelain"]),
|
|
323
|
+
stdout: gitWorkflowBranchWorktreeStdout({ branch, worktreePath, createdResult, opened, transfer }),
|
|
324
|
+
stderr: "",
|
|
325
|
+
exitCode: 0,
|
|
326
|
+
branch: opened.branch || branch,
|
|
327
|
+
carriedStagedChanges: transfer.appliedStagedPatch,
|
|
328
|
+
copiedMessageFiles: transfer.copiedMessageFiles,
|
|
329
|
+
};
|
|
330
|
+
} catch (error) {
|
|
331
|
+
let cleanup = null;
|
|
332
|
+
const createdPath = createdResult?.created && !createdResult?.openedExisting ? createdResult.worktree?.path || createdResult.path : "";
|
|
333
|
+
if (createdPath) cleanup = await cleanupCreatedWorktreeAfterFailure(tab.cwd, createdPath);
|
|
334
|
+
recordEvent({ type: "webui_git_workflow_worktree_failed", tabId: tab.id, cwd: createdPath || tab.cwd, branch, error: sanitizeError(error), cleanup });
|
|
335
|
+
throw error;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async function createGitWorktreeTab(tab, body = {}) {
|
|
340
|
+
const remoteRef = requestedRemoteRef(body);
|
|
341
|
+
const worktreeRequest = remoteRef === null
|
|
342
|
+
? body
|
|
343
|
+
: { ...body, branchName: (await verifyRemoteGitBranchIntent(tab.cwd, body.branchName || body.branch, remoteRef)).branch, remoteRef };
|
|
344
|
+
let createdResult = null;
|
|
345
|
+
try {
|
|
346
|
+
createdResult = await createGitWorktree(tab.cwd, worktreeRequest);
|
|
347
|
+
const opened = await openWorktreeResultForTab(tab, createdResult, { openTab: body.openTab !== false, ...body });
|
|
348
|
+
if (createdResult.created) {
|
|
349
|
+
recordEvent({ type: "webui_worktree_created", tabId: opened.tab?.id || tab.id, cwd: opened.worktree?.path || opened.path, branch: opened.branch || body.branchName || "" });
|
|
350
|
+
}
|
|
351
|
+
return opened;
|
|
352
|
+
} catch (error) {
|
|
353
|
+
let cleanup = null;
|
|
354
|
+
const createdPath = createdResult?.created && !createdResult?.openedExisting ? createdResult.worktree?.path || createdResult.path : "";
|
|
355
|
+
if (createdPath) cleanup = await cleanupCreatedWorktreeAfterFailure(tab.cwd, createdPath);
|
|
356
|
+
recordEvent({ type: "webui_worktree_create_failed", tabId: tab.id, cwd: createdPath || tab.cwd, branch: body.branchName || body.branch || "", error: sanitizeError(error), cleanup });
|
|
357
|
+
throw error;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
async function openExistingGitWorktreeTab(tab, body = {}) {
|
|
362
|
+
const requestedPath = String(body.path || body.worktreePath || "").trim();
|
|
363
|
+
if (!requestedPath) throw makeHttpError(400, "worktree path is required");
|
|
364
|
+
const result = await openGitWorktree(tab.cwd, requestedPath);
|
|
365
|
+
return openWorktreeResultForTab(tab, result, { openTab: body.openTab !== false, ...body });
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async function openTabsInsideWorktree(worktreePath) {
|
|
369
|
+
const activeTabs = [];
|
|
370
|
+
for (const tab of getOpenTabs()) {
|
|
371
|
+
const cwd = await realpath(tab.cwd).catch(() => path.resolve(tab.cwd));
|
|
372
|
+
if (pathInside(worktreePath, cwd)) activeTabs.push(tab);
|
|
373
|
+
}
|
|
374
|
+
return activeTabs;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async function removeGitWorktreeForTab(tab, body = {}) {
|
|
378
|
+
if (body.confirmed !== true) throw makeHttpError(409, "Removing a worktree requires confirmed: true because it deletes files under the worktree path.");
|
|
379
|
+
const requestedPath = String(body.path || body.worktreePath || "").trim();
|
|
380
|
+
if (!requestedPath) throw makeHttpError(400, "worktree path is required");
|
|
381
|
+
const existing = await openGitWorktree(tab.cwd, requestedPath);
|
|
382
|
+
const worktreePath = existing.worktree.path;
|
|
383
|
+
const activeTabs = await openTabsInsideWorktree(worktreePath);
|
|
384
|
+
if (activeTabs.length) {
|
|
385
|
+
const error = makeHttpError(409, `Refusing to remove a worktree that is open in ${activeTabs.length} Web UI tab${activeTabs.length === 1 ? "" : "s"}.`);
|
|
386
|
+
error.code = WORKTREE_ERROR_CODES.WORKTREE_BUSY;
|
|
387
|
+
error.details = { path: requestedPath, tabIds: activeTabs.map((item) => item.id) };
|
|
388
|
+
throw error;
|
|
389
|
+
}
|
|
390
|
+
const result = await removeGitWorktree(tab.cwd, worktreePath, { force: body.force === true });
|
|
391
|
+
recordEvent({ type: "webui_worktree_removed", tabId: tab.id, cwd: result.path || requestedPath, branch: result.branch || "" });
|
|
392
|
+
return { ...result, tabs: listTabs() };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function pruneGitWorktreesData(cwd, body = {}, { dryRun = true } = {}) {
|
|
396
|
+
if (!dryRun) requireConfirmed(body, "Pruning stale worktree records");
|
|
397
|
+
return pruneGitWorktrees(cwd, { dryRun });
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
return {
|
|
401
|
+
createGitWorkflowBranchWorktree,
|
|
402
|
+
createGitWorktreeTab,
|
|
403
|
+
openExistingGitWorktreeTab,
|
|
404
|
+
removeGitWorktreeForTab,
|
|
405
|
+
openGitConflictResolutionAgentTab,
|
|
406
|
+
pruneGitWorktreesData,
|
|
407
|
+
};
|
|
408
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
const WEBUI_HELPER_TIMEOUT_MS = 8 * 1000;
|
|
4
|
+
export const WEBUI_HELPER_COMMAND = "webui-helper";
|
|
5
|
+
const WEBUI_HELPER_RESPONSE_PREFIX = "__PI_WEBUI_HELPER_RESPONSE__:";
|
|
6
|
+
|
|
7
|
+
export function createHelperRequestService({ makeHttpError, sanitizeError }) {
|
|
8
|
+
function parseWebuiHelperResponseEvent(event) {
|
|
9
|
+
if (event?.type !== "extension_ui_request" || event.method !== "notify") return undefined;
|
|
10
|
+
const message = String(event.message || "");
|
|
11
|
+
if (!message.startsWith(WEBUI_HELPER_RESPONSE_PREFIX)) return undefined;
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(message.slice(WEBUI_HELPER_RESPONSE_PREFIX.length));
|
|
14
|
+
} catch (error) {
|
|
15
|
+
return { ok: false, error: `Invalid Web UI helper response: ${sanitizeError(error)}` };
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function resolveWebuiHelperResponse(tab, event) {
|
|
20
|
+
const payload = parseWebuiHelperResponseEvent(event);
|
|
21
|
+
if (!payload) return false;
|
|
22
|
+
const requestId = String(payload.requestId || "");
|
|
23
|
+
const pending = tab?.webuiHelperRequests?.get(requestId);
|
|
24
|
+
if (pending) {
|
|
25
|
+
tab.webuiHelperRequests.delete(requestId);
|
|
26
|
+
clearTimeout(pending.timeout);
|
|
27
|
+
if (payload.ok === false) pending.reject(makeHttpError(400, payload.error || "Web UI helper command failed"));
|
|
28
|
+
else pending.resolve(payload.data || {});
|
|
29
|
+
}
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function resolveWebuiHelperRpcResponse(tab, event) {
|
|
34
|
+
if (event?.type !== "response" || event.command !== "prompt" || !event.id) return false;
|
|
35
|
+
return tab?.webuiHelperResponseIds?.delete(String(event.id)) === true;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function webuiHelperRequestMap(tab) {
|
|
39
|
+
if (!tab.webuiHelperRequests) tab.webuiHelperRequests = new Map();
|
|
40
|
+
return tab.webuiHelperRequests;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function sendWebuiHelperCommand(tab, action, payload = {}, timeoutMs = WEBUI_HELPER_TIMEOUT_MS) {
|
|
44
|
+
const requestId = randomUUID();
|
|
45
|
+
const pending = new Promise((resolve, reject) => {
|
|
46
|
+
const timeout = setTimeout(() => {
|
|
47
|
+
webuiHelperRequestMap(tab).delete(requestId);
|
|
48
|
+
tab.webuiHelperResponseIds?.delete(requestId);
|
|
49
|
+
reject(makeHttpError(504, `Timed out waiting for Web UI helper action: ${action}. Try /reload in this tab, then retry.`));
|
|
50
|
+
}, timeoutMs);
|
|
51
|
+
webuiHelperRequestMap(tab).set(requestId, { resolve, reject, timeout });
|
|
52
|
+
});
|
|
53
|
+
pending.catch(() => {});
|
|
54
|
+
|
|
55
|
+
try {
|
|
56
|
+
tab.webuiHelperResponseIds?.add(requestId);
|
|
57
|
+
const response = await tab.rpc.send({
|
|
58
|
+
id: requestId,
|
|
59
|
+
type: "prompt",
|
|
60
|
+
message: `/${WEBUI_HELPER_COMMAND} ${JSON.stringify({ requestId, action, payload })}`,
|
|
61
|
+
}, timeoutMs);
|
|
62
|
+
if (response.success === false) throw makeHttpError(400, response.error || `Web UI helper action failed: ${action}`);
|
|
63
|
+
return await pending;
|
|
64
|
+
} catch (error) {
|
|
65
|
+
tab.webuiHelperResponseIds?.delete(requestId);
|
|
66
|
+
const request = webuiHelperRequestMap(tab).get(requestId);
|
|
67
|
+
if (request) {
|
|
68
|
+
clearTimeout(request.timeout);
|
|
69
|
+
webuiHelperRequestMap(tab).delete(requestId);
|
|
70
|
+
}
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return {
|
|
76
|
+
parseWebuiHelperResponseEvent,
|
|
77
|
+
resolveWebuiHelperResponse,
|
|
78
|
+
resolveWebuiHelperRpcResponse,
|
|
79
|
+
webuiHelperRequestMap,
|
|
80
|
+
sendWebuiHelperCommand,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, realpath } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const LEAF_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
6
|
+
|
|
7
|
+
function invalid(message) {
|
|
8
|
+
return Object.assign(new Error(`No Project workspace: ${message}`), { statusCode: 400 });
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function within(root, candidate) {
|
|
12
|
+
const relative = path.relative(root, candidate);
|
|
13
|
+
return !relative || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function ownedRoot(agentDir, create = false, validate = true) {
|
|
17
|
+
if (create) await mkdir(agentDir, { recursive: true, mode: 0o700 });
|
|
18
|
+
const agent = await realpath(agentDir).catch((error) => {
|
|
19
|
+
if (!create && error.code === "ENOENT") return path.resolve(agentDir);
|
|
20
|
+
throw error;
|
|
21
|
+
});
|
|
22
|
+
let current = agent;
|
|
23
|
+
for (const component of ["webui", "no-project"]) {
|
|
24
|
+
current = path.join(current, component);
|
|
25
|
+
if (create) await mkdir(current, { mode: 0o700 }).catch((error) => { if (error.code !== "EEXIST") throw error; });
|
|
26
|
+
const info = validate ? await lstat(current).catch((error) => { if (!create && error.code === "ENOENT") return null; throw error; }) : null;
|
|
27
|
+
if (info && (!info.isDirectory() || info.isSymbolicLink())) throw invalid("owned root must be a real directory, not a symlink");
|
|
28
|
+
}
|
|
29
|
+
return current;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Allocate a durable private leaf. No lifecycle operation removes these directories. */
|
|
33
|
+
export async function allocateNoProjectWorkspace(agentDir) {
|
|
34
|
+
const root = await ownedRoot(agentDir, true);
|
|
35
|
+
const noProjectId = randomUUID();
|
|
36
|
+
const cwd = path.join(root, noProjectId);
|
|
37
|
+
await mkdir(cwd, { mode: 0o700 });
|
|
38
|
+
return { cwd, ...await resolveNoProjectWorkspace(agentDir, { cwd, workspaceKind: "no-project", noProjectId }) };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Classify session-header paths and validate persisted identity without allocating. */
|
|
42
|
+
export async function resolveNoProjectWorkspace(agentDir, { cwd, workspaceKind, noProjectId } = {}) {
|
|
43
|
+
if (workspaceKind !== undefined && workspaceKind !== "no-project") throw invalid("unknown workspaceKind");
|
|
44
|
+
const root = await ownedRoot(agentDir, false, false);
|
|
45
|
+
const lexicalRoot = path.resolve(agentDir, "webui", "no-project");
|
|
46
|
+
const candidate = typeof cwd === "string" && cwd ? path.resolve(cwd) : "";
|
|
47
|
+
const canonical = candidate ? await realpath(candidate).catch((error) => {
|
|
48
|
+
if (error.code === "ENOENT") return null;
|
|
49
|
+
throw error;
|
|
50
|
+
}) : null;
|
|
51
|
+
const claimed = workspaceKind === "no-project" || noProjectId !== undefined;
|
|
52
|
+
const owned = candidate && (within(root, candidate) || within(lexicalRoot, candidate) || (canonical && within(root, canonical)));
|
|
53
|
+
if (!claimed && !owned) return {};
|
|
54
|
+
await ownedRoot(agentDir);
|
|
55
|
+
if (!candidate || !canonical) throw invalid("owned working directory is missing");
|
|
56
|
+
const leaf = path.basename(candidate);
|
|
57
|
+
if (!LEAF_ID.test(leaf) || path.dirname(candidate) !== root || canonical !== candidate || cwd !== candidate) throw invalid("working directory must be an exact canonical owned leaf");
|
|
58
|
+
const info = await lstat(candidate);
|
|
59
|
+
if (!info.isDirectory() || info.isSymbolicLink()) throw invalid("owned leaf must be a real directory");
|
|
60
|
+
if (noProjectId !== undefined && noProjectId !== leaf) throw invalid("owned identity does not match the working directory");
|
|
61
|
+
if (claimed && (workspaceKind !== "no-project" || !LEAF_ID.test(noProjectId || ""))) throw invalid("owned identity is required");
|
|
62
|
+
return { workspaceKind: "no-project", noProjectId: leaf };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The public create route accepts intent only; owned paths and identities stay server controlled. */
|
|
66
|
+
export function validateNoProjectCreateIntent(body) {
|
|
67
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) throw invalid("tab creation requires an object");
|
|
68
|
+
if (body.workspaceKind === undefined) {
|
|
69
|
+
if (Object.hasOwn(body, "noProjectId")) throw invalid("clients cannot select an owned identity");
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
if (body.workspaceKind !== "no-project") throw invalid("unknown workspaceKind");
|
|
73
|
+
for (const key of ["cwd", "session", "sessionFile", "sessionPath", "sessionId", "continue", "resume", "noProjectId", "workspace", "root", "agentDir"]) {
|
|
74
|
+
if (Object.hasOwn(body, key)) throw invalid(`creation intent cannot include ${key}`);
|
|
75
|
+
}
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const SESSION_VALUES = new Set(["--session", "--session-id", "--fork", "--prompt", "--initial-prompt"]);
|
|
80
|
+
const SESSION_FLAGS = new Set(["--continue", "-c", "--resume", "-r", "--print", "-p"]);
|
|
81
|
+
const VALUE_OPTIONS = new Set(["--mode", "--provider", "--model", "--api-key", "--system-prompt", "--append-system-prompt", "--name", "-n", "--session-dir", "--models", "--tools", "-t", "--exclude-tools", "-xt", "--thinking", "--export", "--extension", "-e", "--skill", "--prompt-template", "--theme", "--use-theme", "--tui-mode"]);
|
|
82
|
+
const BOOLEAN_OPTIONS = new Set(["--no-session", "--no-tools", "-nt", "--no-builtin-tools", "-nbt", "--no-extensions", "-ne", "--no-mcp", "--no-skills", "-ns", "--no-prompt-templates", "-np", "--no-themes", "--no-context-files", "-nc", "--verbose", "--approve", "-a", "--no-approve", "-na", "--offline", "--help", "-h", "--version", "-v"]);
|
|
83
|
+
|
|
84
|
+
/** Drop session selectors and initial input while preserving Pi options and extension flags. */
|
|
85
|
+
export function noProjectPiArgs(args) {
|
|
86
|
+
const retained = [];
|
|
87
|
+
for (let i = 0; i < args.length; i++) {
|
|
88
|
+
const arg = args[i];
|
|
89
|
+
if (arg === "--") break;
|
|
90
|
+
const flag = arg.split("=", 1)[0];
|
|
91
|
+
if (SESSION_VALUES.has(flag)) {
|
|
92
|
+
if (!arg.includes("=") && i + 1 < args.length) i++;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (SESSION_FLAGS.has(flag)) continue;
|
|
96
|
+
if (!arg.startsWith("-")) continue;
|
|
97
|
+
retained.push(arg);
|
|
98
|
+
if (!arg.includes("=") && (VALUE_OPTIONS.has(arg) || (!BOOLEAN_OPTIONS.has(arg) && arg.startsWith("--") && args[i + 1] && !/^(?:-|@)/.test(args[i + 1])))) {
|
|
99
|
+
if (i + 1 < args.length) retained.push(args[++i]);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return retained;
|
|
103
|
+
}
|