@firstpick/pi-package-webui 0.8.0 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -5
- package/bin/pi-webui.mjs +606 -102
- package/lib/component-update-state.mjs +126 -0
- package/lib/npm-command.mjs +81 -0
- package/lib/queue-mutation.mjs +6 -0
- package/lib/trust-boundaries.mjs +1 -0
- package/lib/workspace-files-live-watcher.mjs +138 -0
- package/package.json +8 -3
- package/public/app.js +4231 -376
- package/public/index.html +265 -52
- package/public/mobile-shell-state.mjs +166 -0
- package/public/service-worker.js +60 -13
- package/public/styles.css +1790 -383
- package/public/subagent-gate-visibility.mjs +16 -0
- package/public/subagent-launch-slot-state.mjs +16 -0
- package/public/transcript-renderer.mjs +433 -0
- package/tests/boot-failure-diagnostics.test.mjs +63 -5
- package/tests/browser/control-deck-component-updates.spec.mjs +180 -0
- package/tests/browser/interaction-continuity.spec.mjs +897 -0
- package/tests/browser/mobile-foundation.spec.mjs +363 -0
- package/tests/browser/optimistic-prompt.spec.mjs +130 -0
- package/tests/browser/side-panel-section-reorder.spec.mjs +101 -0
- package/tests/browser/stats-overlay.spec.mjs +265 -0
- package/tests/chat-scroll-intent-static.test.mjs +6 -1
- package/tests/codex-fast-mode-static.test.mjs +8 -5
- package/tests/compact-sections-static.test.mjs +20 -2
- package/tests/compaction-mutation-contract.test.mjs +18 -4
- package/tests/compaction-static.test.mjs +1 -0
- package/tests/completion-signal-contract.test.mjs +13 -2
- package/tests/component-update-api-static.test.mjs +67 -0
- package/tests/component-update-state.test.mjs +80 -0
- package/tests/control-deck-component-updates-static.test.mjs +251 -0
- package/tests/fast-mode-client-static.test.mjs +7 -4
- package/tests/fixtures/fake-pi.mjs +305 -2
- package/tests/footer-provider-usage-visual-static.test.mjs +71 -0
- package/tests/git-panel-gitignore-static.test.mjs +104 -0
- package/tests/http-endpoints-harness.test.mjs +228 -2
- package/tests/interaction-state-stability-static.test.mjs +271 -0
- package/tests/mobile-continuity-tablet-static.test.mjs +55 -0
- package/tests/mobile-foundation-static.test.mjs +71 -0
- package/tests/mobile-phone-experience-static.test.mjs +65 -0
- package/tests/mobile-shell-state.test.mjs +69 -0
- package/tests/mobile-static.test.mjs +246 -39
- package/tests/mobile-transcript-cache-characterization.test.mjs +34 -0
- package/tests/native-parity-harness.test.mjs +2 -0
- package/tests/npm-command.test.mjs +64 -1
- package/tests/open-issue-wizard-static.test.mjs +2 -1
- package/tests/queue-edit-reorder-static.test.mjs +9 -1
- package/tests/queue-mutation-contract.test.mjs +22 -0
- package/tests/service-worker-lifecycle.test.mjs +120 -0
- package/tests/side-panel-section-reorder-static.test.mjs +68 -0
- package/tests/sse-backpressure-harness.test.mjs +137 -0
- package/tests/stats-dashboard-static.test.mjs +266 -0
- package/tests/streaming-ui-coupling.test.mjs +7 -1
- package/tests/subagent-gate-visibility.test.mjs +18 -2
- package/tests/subagent-launch-slot-state.test.mjs +32 -0
- package/tests/subagent-launch-slots-static.test.mjs +8 -2
- package/tests/subagents-helper.test.mjs +90 -0
- package/tests/terminal-tab-workspace-static.test.mjs +1 -1
- package/tests/update-commands.test.mjs +4 -0
- package/tests/workspace-files-live-updates-static.test.mjs +76 -0
- package/tests/workspace-files-live-watcher.test.mjs +95 -0
- package/webui-rpc-helper.mjs +175 -3
package/bin/pi-webui.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
3
|
import { createHash, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
|
|
4
|
-
import { createReadStream, readFileSync, realpathSync, statSync } from "node:fs";
|
|
4
|
+
import { constants as fsConstants, createReadStream, readFileSync, realpathSync, statSync } from "node:fs";
|
|
5
5
|
import { createServer } from "node:http";
|
|
6
6
|
import { createRequire } from "node:module";
|
|
7
7
|
import { access, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
@@ -39,7 +39,8 @@ import {
|
|
|
39
39
|
windowsReservedGitPathFailure,
|
|
40
40
|
} from "../lib/git-command-errors.mjs";
|
|
41
41
|
import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
|
|
42
|
-
import {
|
|
42
|
+
import { ComponentUpdateState, validateComponentUpdateRequest } from "../lib/component-update-state.mjs";
|
|
43
|
+
import { prependedPathEnvironment, resolveCommandDirectory, resolveNpmCommandInvocation, resolvePiCommandInvocation } from "../lib/npm-command.mjs";
|
|
43
44
|
import {
|
|
44
45
|
GIT_WORKFLOW_DEFAULT_VARIANTS,
|
|
45
46
|
GIT_WORKFLOW_DELIVERY_MODES,
|
|
@@ -110,6 +111,7 @@ import {
|
|
|
110
111
|
removeGitWorktree,
|
|
111
112
|
} from "../lib/git-worktrees.mjs";
|
|
112
113
|
import { createGitLiveWatcher } from "../lib/git-live-watcher.mjs";
|
|
114
|
+
import { createWorkspaceFilesLiveWatcher } from "../lib/workspace-files-live-watcher.mjs";
|
|
113
115
|
import {
|
|
114
116
|
gitMessageArtifactPairReadiness,
|
|
115
117
|
readStableGitMessageArtifactPair,
|
|
@@ -154,6 +156,9 @@ const WEBUI_SUBAGENT_GATE_LIMIT = 32;
|
|
|
154
156
|
const WEBUI_SUBAGENT_GATE_ATTEMPT_LIMIT = 100;
|
|
155
157
|
const WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT = 120;
|
|
156
158
|
const WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
|
|
159
|
+
const WEBUI_SUBAGENT_TELEMETRY_TOKEN_LIMIT = 1_000_000_000;
|
|
160
|
+
const WEBUI_SUBAGENT_TELEMETRY_CONTEXT_WINDOW_LIMIT = 16_000_000;
|
|
161
|
+
const WEBUI_SUBAGENT_TELEMETRY_SPEED_LIMIT = 1_000_000;
|
|
157
162
|
const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
158
163
|
const WEBUI_PACKAGE = packageJson.name || "@firstpick/pi-package-webui";
|
|
159
164
|
const PI_LATEST_VERSION_URL = process.env.PI_WEBUI_PI_LATEST_VERSION_URL || "https://pi.dev/api/latest-version";
|
|
@@ -250,6 +255,7 @@ const UPLOAD_TEMP_TTL_MS = 24 * 60 * 60 * 1000;
|
|
|
250
255
|
const NATIVE_EXPORT_TEMP_TTL_MS = 60 * 60 * 1000;
|
|
251
256
|
const TEMP_ARTIFACT_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
|
|
252
257
|
const AUTO_TAB_TITLE_MAX_LENGTH = 44;
|
|
258
|
+
const AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH = 160;
|
|
253
259
|
const AUTO_TAB_TITLE_WORD_LIMIT = 8;
|
|
254
260
|
const AUTO_TAB_TITLE_STOP_WORDS = new Set([
|
|
255
261
|
"a",
|
|
@@ -1269,12 +1275,104 @@ function sendRemoteAuthRequired(req, res, url) {
|
|
|
1269
1275
|
sendJson(res, 401, { ok: false, error: "Remote PIN required", remoteAuthRequired: true }, { "www-authenticate": "PiRemotePin" });
|
|
1270
1276
|
}
|
|
1271
1277
|
|
|
1272
|
-
|
|
1278
|
+
// A false ServerResponse.write() result means the frame was accepted but the
|
|
1279
|
+
// writable buffer crossed its high-water mark. Treating that as a dead client
|
|
1280
|
+
// disconnects healthy Chromium EventSource streams as soon as a frame exceeds
|
|
1281
|
+
// roughly 16 KiB. Queue subsequent frames until "drain", with strict bounds so
|
|
1282
|
+
// a client that truly stops reading cannot grow server memory indefinitely.
|
|
1283
|
+
const SSE_BACKPRESSURE_MAX_PENDING_BYTES = 512 * 1024;
|
|
1284
|
+
const SSE_BACKPRESSURE_MAX_PENDING_FRAMES = 256;
|
|
1285
|
+
const SSE_BACKPRESSURE_TIMEOUT_MS = 10_000;
|
|
1286
|
+
|
|
1287
|
+
function clearSseBackpressureTimer(client) {
|
|
1288
|
+
if (!client?.backpressureTimer) return;
|
|
1289
|
+
clearTimeout(client.backpressureTimer);
|
|
1290
|
+
client.backpressureTimer = undefined;
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
function evictSlowSseClient(client) {
|
|
1294
|
+
if (!client || client.evicted) return;
|
|
1295
|
+
client.evicted = true;
|
|
1296
|
+
client.backpressured = false;
|
|
1297
|
+
clearSseBackpressureTimer(client);
|
|
1298
|
+
client.pendingFrames = [];
|
|
1299
|
+
client.pendingFrameBytes = 0;
|
|
1300
|
+
client.tab?.sseClients?.delete(client);
|
|
1301
|
+
try {
|
|
1302
|
+
// Complete the chunked response so Chromium can reconnect without
|
|
1303
|
+
// ERR_INCOMPLETE_CHUNKED_ENCODING.
|
|
1304
|
+
client.res?.end();
|
|
1305
|
+
} catch {
|
|
1306
|
+
// A closed browser socket needs no further cleanup.
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
function scheduleSseBackpressureTimeout(client) {
|
|
1311
|
+
clearSseBackpressureTimer(client);
|
|
1312
|
+
client.backpressureTimer = setTimeout(() => evictSlowSseClient(client), SSE_BACKPRESSURE_TIMEOUT_MS);
|
|
1313
|
+
client.backpressureTimer.unref?.();
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
function flushSseClient(client) {
|
|
1317
|
+
const res = client?.res;
|
|
1318
|
+
if (!client || client.evicted) return;
|
|
1319
|
+
if (!res || res.destroyed || res.writableEnded) {
|
|
1320
|
+
evictSlowSseClient(client);
|
|
1321
|
+
return;
|
|
1322
|
+
}
|
|
1323
|
+
client.backpressured = false;
|
|
1324
|
+
clearSseBackpressureTimer(client);
|
|
1325
|
+
while (client.pendingFrames?.length) {
|
|
1326
|
+
const frame = client.pendingFrames.shift();
|
|
1327
|
+
client.pendingFrameBytes -= Buffer.byteLength(frame);
|
|
1328
|
+
try {
|
|
1329
|
+
if (!res.write(frame)) {
|
|
1330
|
+
client.backpressured = true;
|
|
1331
|
+
scheduleSseBackpressureTimeout(client);
|
|
1332
|
+
res.once("drain", () => flushSseClient(client));
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
} catch {
|
|
1336
|
+
evictSlowSseClient(client);
|
|
1337
|
+
return;
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
client.pendingFrameBytes = 0;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
function writeSseFrame(client, frame) {
|
|
1273
1344
|
const res = client?.res || client;
|
|
1345
|
+
if (!res || res.destroyed || res.writableEnded || client?.evicted) return false;
|
|
1346
|
+
if (client?.res && client.backpressured) {
|
|
1347
|
+
const frameBytes = Buffer.byteLength(frame);
|
|
1348
|
+
const pendingFrames = client.pendingFrames || (client.pendingFrames = []);
|
|
1349
|
+
const pendingBytes = Number(client.pendingFrameBytes) || 0;
|
|
1350
|
+
if (pendingFrames.length >= SSE_BACKPRESSURE_MAX_PENDING_FRAMES || pendingBytes + frameBytes > SSE_BACKPRESSURE_MAX_PENDING_BYTES) {
|
|
1351
|
+
evictSlowSseClient(client);
|
|
1352
|
+
return false;
|
|
1353
|
+
}
|
|
1354
|
+
pendingFrames.push(frame);
|
|
1355
|
+
client.pendingFrameBytes = pendingBytes + frameBytes;
|
|
1356
|
+
return true;
|
|
1357
|
+
}
|
|
1358
|
+
try {
|
|
1359
|
+
if (!res.write(frame) && client?.res) {
|
|
1360
|
+
client.backpressured = true;
|
|
1361
|
+
scheduleSseBackpressureTimeout(client);
|
|
1362
|
+
res.once("drain", () => flushSseClient(client));
|
|
1363
|
+
}
|
|
1364
|
+
// write() returning false still accepted this frame.
|
|
1365
|
+
return true;
|
|
1366
|
+
} catch {
|
|
1367
|
+
if (client?.res) evictSlowSseClient(client);
|
|
1368
|
+
return false;
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
function sendSse(client, event) {
|
|
1274
1373
|
const payload = encodeBrowserSseEvent(event, { outputMode: client?.activeMode || OUTPUT_MODE_NORMAL });
|
|
1275
1374
|
if (payload === undefined) return false;
|
|
1276
|
-
|
|
1277
|
-
return true;
|
|
1375
|
+
return writeSseFrame(client, `data: ${payload}\n\n`);
|
|
1278
1376
|
}
|
|
1279
1377
|
|
|
1280
1378
|
function rpcSuccess(command, data = {}) {
|
|
@@ -1621,7 +1719,7 @@ function generatedTabTitleFromPrompt(message) {
|
|
|
1621
1719
|
const words = cleaned.split(/\s+/).map((word) => word.replace(/^[^\w]+|[^\w]+$/g, "")).filter(Boolean);
|
|
1622
1720
|
const meaningfulWords = words.filter((word) => !AUTO_TAB_TITLE_STOP_WORDS.has(word.toLowerCase()));
|
|
1623
1721
|
const selectedWords = (meaningfulWords.length >= 3 ? meaningfulWords : words).slice(0, AUTO_TAB_TITLE_WORD_LIMIT);
|
|
1624
|
-
return truncateTabTitle(titleCaseTabTitle(selectedWords.join(" ")));
|
|
1722
|
+
return truncateTabTitle(titleCaseTabTitle(selectedWords.join(" ")), AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH);
|
|
1625
1723
|
}
|
|
1626
1724
|
|
|
1627
1725
|
function uniqueTabTitle(title, currentTab, maxLength = AUTO_TAB_TITLE_MAX_LENGTH) {
|
|
@@ -5511,6 +5609,117 @@ function normalizeGitRelativePath(root, relativePath) {
|
|
|
5511
5609
|
return path.relative(root, resolved).split(path.sep).join("/");
|
|
5512
5610
|
}
|
|
5513
5611
|
|
|
5612
|
+
const GITIGNORE_MAX_BYTES = 5 * 1024 * 1024;
|
|
5613
|
+
const gitignoreMutationQueues = new Map();
|
|
5614
|
+
|
|
5615
|
+
function serializeGitignoreMutation(root, mutation) {
|
|
5616
|
+
const previous = gitignoreMutationQueues.get(root) || Promise.resolve();
|
|
5617
|
+
const current = previous.catch(() => {}).then(mutation);
|
|
5618
|
+
gitignoreMutationQueues.set(root, current);
|
|
5619
|
+
return current.finally(() => {
|
|
5620
|
+
if (gitignoreMutationQueues.get(root) === current) gitignoreMutationQueues.delete(root);
|
|
5621
|
+
});
|
|
5622
|
+
}
|
|
5623
|
+
|
|
5624
|
+
function gitignoreEntryForTarget(root, requestedPath, kind) {
|
|
5625
|
+
if (kind !== "file" && kind !== "folder") throw makeHttpError(400, "Gitignore target kind must be file or folder");
|
|
5626
|
+
if (typeof requestedPath !== "string" || requestedPath.length === 0) throw makeHttpError(400, "Gitignore target path is required");
|
|
5627
|
+
if (/[\0-\x1f\x7f]/.test(requestedPath)) throw makeHttpError(400, "Gitignore target path cannot contain control characters");
|
|
5628
|
+
|
|
5629
|
+
const slashPath = requestedPath.replace(/\\/g, "/");
|
|
5630
|
+
if (path.posix.isAbsolute(slashPath) || path.win32.isAbsolute(requestedPath) || /^[A-Za-z]:/.test(requestedPath)) {
|
|
5631
|
+
throw makeHttpError(400, "Gitignore target path must be repository-relative");
|
|
5632
|
+
}
|
|
5633
|
+
const segments = slashPath.split("/").filter(Boolean);
|
|
5634
|
+
if (!segments.length || segments.some((segment) => segment === "." || segment === "..")) {
|
|
5635
|
+
throw makeHttpError(400, "Gitignore target path cannot be the repository root or contain traversal segments");
|
|
5636
|
+
}
|
|
5637
|
+
|
|
5638
|
+
const normalized = segments.join("/");
|
|
5639
|
+
const target = path.resolve(root, ...segments);
|
|
5640
|
+
const relative = path.relative(root, target);
|
|
5641
|
+
if (!relative || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
5642
|
+
throw makeHttpError(400, "Gitignore target path must stay inside the repository");
|
|
5643
|
+
}
|
|
5644
|
+
const escaped = normalized.replace(/([*?\[\] ])/g, "\\$1");
|
|
5645
|
+
return { path: normalized, kind, entry: `/${escaped}${kind === "folder" ? "/" : ""}` };
|
|
5646
|
+
}
|
|
5647
|
+
|
|
5648
|
+
function sameFileIdentity(first, second) {
|
|
5649
|
+
return first?.dev === second?.dev && first?.ino === second?.ino;
|
|
5650
|
+
}
|
|
5651
|
+
|
|
5652
|
+
function gitignoreHasExactEntry(content, entry) {
|
|
5653
|
+
const existing = content.toString("latin1").split(/\r\n|\n|\r/);
|
|
5654
|
+
return existing.includes(Buffer.from(entry, "utf8").toString("latin1"));
|
|
5655
|
+
}
|
|
5656
|
+
|
|
5657
|
+
async function appendGitignoreEntry(root, entry) {
|
|
5658
|
+
const target = path.join(root, ".gitignore");
|
|
5659
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
5660
|
+
let before;
|
|
5661
|
+
try {
|
|
5662
|
+
before = await lstat(target);
|
|
5663
|
+
} catch (error) {
|
|
5664
|
+
if (error?.code !== "ENOENT") throw error;
|
|
5665
|
+
before = null;
|
|
5666
|
+
}
|
|
5667
|
+
|
|
5668
|
+
if (!before) {
|
|
5669
|
+
let handle;
|
|
5670
|
+
try {
|
|
5671
|
+
handle = await open(target, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (fsConstants.O_NOFOLLOW || 0), 0o666);
|
|
5672
|
+
await handle.writeFile(`${entry}\n`, "utf8");
|
|
5673
|
+
return true;
|
|
5674
|
+
} catch (error) {
|
|
5675
|
+
if (error?.code === "EEXIST" && attempt === 0) continue;
|
|
5676
|
+
throw error;
|
|
5677
|
+
} finally {
|
|
5678
|
+
await handle?.close();
|
|
5679
|
+
}
|
|
5680
|
+
}
|
|
5681
|
+
|
|
5682
|
+
if (before.isSymbolicLink() || !before.isFile()) throw makeHttpError(409, "Repository .gitignore must be a regular file and cannot be a symbolic link");
|
|
5683
|
+
if (before.nlink !== 1) throw makeHttpError(409, "Repository .gitignore must have exactly one hard link; replace linked copies with a regular file before retrying");
|
|
5684
|
+
|
|
5685
|
+
let handle;
|
|
5686
|
+
try {
|
|
5687
|
+
handle = await open(target, fsConstants.O_RDWR | fsConstants.O_APPEND | (fsConstants.O_NOFOLLOW || 0));
|
|
5688
|
+
const opened = await handle.stat();
|
|
5689
|
+
if (!opened.isFile() || !sameFileIdentity(before, opened)) throw makeHttpError(409, "Repository .gitignore changed while it was being opened");
|
|
5690
|
+
if (opened.nlink !== 1) throw makeHttpError(409, "Repository .gitignore must have exactly one hard link; replace linked copies with a regular file before retrying");
|
|
5691
|
+
if (opened.size > GITIGNORE_MAX_BYTES) throw makeHttpError(409, `Repository .gitignore exceeds the ${formatBytes(GITIGNORE_MAX_BYTES)} safe modification limit`);
|
|
5692
|
+
const content = await handle.readFile();
|
|
5693
|
+
if (gitignoreHasExactEntry(content, entry)) return false;
|
|
5694
|
+
const newline = content.includes(Buffer.from("\r\n")) ? "\r\n" : "\n";
|
|
5695
|
+
const lastByte = content.length ? content[content.length - 1] : null;
|
|
5696
|
+
const separator = content.length && lastByte !== 0x0a && lastByte !== 0x0d ? newline : "";
|
|
5697
|
+
await handle.writeFile(`${separator}${entry}${newline}`, "utf8");
|
|
5698
|
+
return true;
|
|
5699
|
+
} catch (error) {
|
|
5700
|
+
if (error?.code === "ENOENT" && attempt === 0) continue;
|
|
5701
|
+
if (error?.code === "ELOOP") throw makeHttpError(409, "Repository .gitignore cannot be a symbolic link");
|
|
5702
|
+
throw error;
|
|
5703
|
+
} finally {
|
|
5704
|
+
await handle?.close();
|
|
5705
|
+
}
|
|
5706
|
+
}
|
|
5707
|
+
}
|
|
5708
|
+
|
|
5709
|
+
async function addGitignoreEntry(cwd, body = {}) {
|
|
5710
|
+
try {
|
|
5711
|
+
const root = await realpath(await getGitRoot(cwd));
|
|
5712
|
+
const target = gitignoreEntryForTarget(root, body.path, body.kind);
|
|
5713
|
+
const added = await serializeGitignoreMutation(root, () => appendGitignoreEntry(root, target.entry));
|
|
5714
|
+
return { root, ...target, added, changes: await readGitChanges(root) };
|
|
5715
|
+
} catch (error) {
|
|
5716
|
+
if (error?.statusCode) throw error;
|
|
5717
|
+
const wrapped = makeHttpError(500, formatCliError(error));
|
|
5718
|
+
if (error?.code) wrapped.code = error.code;
|
|
5719
|
+
throw wrapped;
|
|
5720
|
+
}
|
|
5721
|
+
}
|
|
5722
|
+
|
|
5514
5723
|
async function readGitUntrackedEntry(root, file, { maxBytes = Number.POSITIVE_INFINITY } = {}) {
|
|
5515
5724
|
const normalized = normalizeGitRelativePath(root, file);
|
|
5516
5725
|
const filePath = resolveGitRelativePath(root, normalized);
|
|
@@ -7771,7 +7980,7 @@ async function readBundledThemes() {
|
|
|
7771
7980
|
function normalizeStaticPath(urlPath) {
|
|
7772
7981
|
if (urlPath === "/") return "index.html";
|
|
7773
7982
|
const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
|
|
7774
|
-
if (!["index.html", "app.js", "issue-wizard-state.mjs", "issue-bot-client.mjs", "fast-output-live.mjs", "subagent-launch-slot-state.mjs", "subagent-gate-visibility.mjs", "workflow-status-stack.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
|
|
7983
|
+
if (!["index.html", "app.js", "mobile-shell-state.mjs", "issue-wizard-state.mjs", "issue-bot-client.mjs", "fast-output-live.mjs", "transcript-renderer.mjs", "subagent-launch-slot-state.mjs", "subagent-gate-visibility.mjs", "workflow-status-stack.mjs", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
|
|
7775
7984
|
return name;
|
|
7776
7985
|
}
|
|
7777
7986
|
|
|
@@ -8361,17 +8570,17 @@ async function resolvedPiCliScript() {
|
|
|
8361
8570
|
return "";
|
|
8362
8571
|
}
|
|
8363
8572
|
|
|
8573
|
+
function resolveSelectedPiCommand(piArgs) {
|
|
8574
|
+
const invocation = resolvePiCommandInvocation(options.piBin, piArgs);
|
|
8575
|
+
return {
|
|
8576
|
+
command: invocation.command,
|
|
8577
|
+
args: invocation.args,
|
|
8578
|
+
displayCommand: formatCommandForDisplay(invocation.command, invocation.args),
|
|
8579
|
+
};
|
|
8580
|
+
}
|
|
8581
|
+
|
|
8364
8582
|
async function resolvePiCommand(piArgs) {
|
|
8365
|
-
if (options.piBinExplicit)
|
|
8366
|
-
if (isNodeScriptCommand(options.piBin)) {
|
|
8367
|
-
return {
|
|
8368
|
-
command: process.execPath,
|
|
8369
|
-
args: [options.piBin, ...piArgs],
|
|
8370
|
-
displayCommand: `${process.execPath} ${options.piBin} ${piArgs.join(" ")}`,
|
|
8371
|
-
};
|
|
8372
|
-
}
|
|
8373
|
-
return { command: options.piBin, args: piArgs, displayCommand: `${options.piBin} ${piArgs.join(" ")}` };
|
|
8374
|
-
}
|
|
8583
|
+
if (options.piBinExplicit) return resolveSelectedPiCommand(piArgs);
|
|
8375
8584
|
|
|
8376
8585
|
const bundledCli = await resolvedPiCliScript();
|
|
8377
8586
|
if (bundledCli) {
|
|
@@ -8382,7 +8591,7 @@ async function resolvePiCommand(piArgs) {
|
|
|
8382
8591
|
};
|
|
8383
8592
|
}
|
|
8384
8593
|
|
|
8385
|
-
return
|
|
8594
|
+
return resolveSelectedPiCommand(piArgs);
|
|
8386
8595
|
}
|
|
8387
8596
|
|
|
8388
8597
|
const tabs = new Map();
|
|
@@ -8660,6 +8869,10 @@ function createTabActivity(now = new Date().toISOString()) {
|
|
|
8660
8869
|
status: "idle",
|
|
8661
8870
|
isWorking: false,
|
|
8662
8871
|
runStarted: false,
|
|
8872
|
+
// Opaque server-issued identity for the current/recent parent turn. It is
|
|
8873
|
+
// deliberately separate from subagent/workflow IDs and contains no prompt,
|
|
8874
|
+
// title, cwd, or user-derived data.
|
|
8875
|
+
runId: null,
|
|
8663
8876
|
completionSerial: 0,
|
|
8664
8877
|
lastChangedAt: now,
|
|
8665
8878
|
lastStartedAt: null,
|
|
@@ -9029,8 +9242,10 @@ function queueMutationRequest(body) {
|
|
|
9029
9242
|
} else if (request.operation.type === "move") {
|
|
9030
9243
|
request.operation.from = queueMutationIndex(operation.from, "operation.from");
|
|
9031
9244
|
request.operation.to = queueMutationIndex(operation.to, "operation.to");
|
|
9245
|
+
} else if (request.operation.type === "delete") {
|
|
9246
|
+
request.operation.index = queueMutationIndex(operation.index, "operation.index");
|
|
9032
9247
|
} else {
|
|
9033
|
-
throw makeHttpError(400, "Queue mutation operation type must be edit or
|
|
9248
|
+
throw makeHttpError(400, "Queue mutation operation type must be edit, move, or delete");
|
|
9034
9249
|
}
|
|
9035
9250
|
if (source === "webui-compaction") {
|
|
9036
9251
|
if (!Number.isSafeInteger(body.revision) || body.revision < 0) throw makeHttpError(400, "Compaction queue mutation requires a non-negative revision");
|
|
@@ -9116,13 +9331,18 @@ function mutateCompactionFollowUpQueue(tab, request) {
|
|
|
9116
9331
|
if (operation.type === "edit") {
|
|
9117
9332
|
if (operation.index >= slots.length || current.followUp[operation.index] !== operation.expectedText) return failed("invalid-request");
|
|
9118
9333
|
queue[slots[operation.index]].command.message = operation.text;
|
|
9119
|
-
} else {
|
|
9334
|
+
} else if (operation.type === "move") {
|
|
9120
9335
|
if (operation.from >= slots.length || operation.to >= slots.length || operation.from === operation.to
|
|
9121
9336
|
|| current.followUp[operation.from] !== operation.expectedText) return failed("invalid-request");
|
|
9122
9337
|
const followUps = slots.map((index) => queue[index]);
|
|
9123
9338
|
const [moved] = followUps.splice(operation.from, 1);
|
|
9124
9339
|
followUps.splice(operation.to, 0, moved);
|
|
9125
9340
|
slots.forEach((slot, index) => { queue[slot] = followUps[index]; });
|
|
9341
|
+
} else if (operation.type === "delete") {
|
|
9342
|
+
if (operation.index >= slots.length || current.followUp[operation.index] !== operation.expectedText) return failed("invalid-request");
|
|
9343
|
+
queue.splice(slots[operation.index], 1);
|
|
9344
|
+
} else {
|
|
9345
|
+
return failed("invalid-request");
|
|
9126
9346
|
}
|
|
9127
9347
|
|
|
9128
9348
|
advanceCompactionQueueRevision(tab);
|
|
@@ -9394,6 +9614,7 @@ async function cancelPendingExtensionUiRequests(tab) {
|
|
|
9394
9614
|
|
|
9395
9615
|
function markTabWorking(tab, timestamp = new Date().toISOString(), { runStarted = false } = {}) {
|
|
9396
9616
|
const activity = tab.activity || createTabActivity(timestamp);
|
|
9617
|
+
if (!activity.isWorking || !activity.runId) activity.runId = randomUUID();
|
|
9397
9618
|
activity.status = "working";
|
|
9398
9619
|
activity.isWorking = true;
|
|
9399
9620
|
activity.runStarted = activity.runStarted === true || runStarted === true;
|
|
@@ -9413,10 +9634,24 @@ function markTabDone(tab, timestamp = new Date().toISOString()) {
|
|
|
9413
9634
|
tab.activity = activity;
|
|
9414
9635
|
}
|
|
9415
9636
|
|
|
9637
|
+
function markTabFailed(tab, timestamp = new Date().toISOString()) {
|
|
9638
|
+
const activity = tab.activity || createTabActivity(timestamp);
|
|
9639
|
+
activity.status = "failed";
|
|
9640
|
+
activity.isWorking = false;
|
|
9641
|
+
activity.runStarted = false;
|
|
9642
|
+
activity.completionSerial = (Number(activity.completionSerial) || 0) + 1;
|
|
9643
|
+
activity.lastCompletedAt = timestamp;
|
|
9644
|
+
activity.lastChangedAt = timestamp;
|
|
9645
|
+
tab.activity = activity;
|
|
9646
|
+
}
|
|
9647
|
+
|
|
9416
9648
|
function markTabIdle(tab, timestamp = new Date().toISOString()) {
|
|
9417
9649
|
const activity = tab.activity || createTabActivity(timestamp);
|
|
9418
9650
|
activity.status = "idle";
|
|
9419
9651
|
activity.isWorking = false;
|
|
9652
|
+
// An idle pre-start operation never became a parent turn. Completed turns
|
|
9653
|
+
// retain their opaque ID so a later Activity view can resolve recent work.
|
|
9654
|
+
if (!activity.runStarted) activity.runId = null;
|
|
9420
9655
|
activity.runStarted = false;
|
|
9421
9656
|
activity.lastChangedAt = timestamp;
|
|
9422
9657
|
tab.activity = activity;
|
|
@@ -9486,19 +9721,30 @@ function updateTabActivityFromEvent(tab, event) {
|
|
|
9486
9721
|
switch (event?.type) {
|
|
9487
9722
|
case "agent_start":
|
|
9488
9723
|
patchTabState(tab, { isStreaming: true });
|
|
9724
|
+
tab.pendingTurnFailure = false;
|
|
9489
9725
|
markTabWorking(tab, timestamp, { runStarted: true });
|
|
9490
9726
|
break;
|
|
9491
9727
|
case "compaction_start":
|
|
9492
9728
|
patchTabState(tab, { isCompacting: true });
|
|
9493
9729
|
markTabWorking(tab, timestamp);
|
|
9494
9730
|
break;
|
|
9495
|
-
case "agent_end":
|
|
9731
|
+
case "agent_end": {
|
|
9496
9732
|
// A low-level run ended, but Pi may still retry, compact, or process a follow-up.
|
|
9733
|
+
const assistant = Array.isArray(event.messages) ? event.messages.findLast((item) => item?.role === "assistant") : null;
|
|
9734
|
+
if (event.willRetry === true) tab.pendingTurnFailure = false;
|
|
9735
|
+
else if (assistant?.stopReason === "error") tab.pendingTurnFailure = true;
|
|
9736
|
+
break;
|
|
9737
|
+
}
|
|
9738
|
+
case "message_end":
|
|
9739
|
+
if (event.message?.role === "assistant" && event.message.stopReason === "error") tab.pendingTurnFailure = true;
|
|
9497
9740
|
break;
|
|
9498
9741
|
case "agent_settled":
|
|
9499
9742
|
patchTabState(tab, { isStreaming: false });
|
|
9500
|
-
if (tab.activity?.runStarted)
|
|
9501
|
-
|
|
9743
|
+
if (tab.activity?.runStarted) {
|
|
9744
|
+
if (tab.pendingTurnFailure) markTabFailed(tab, timestamp);
|
|
9745
|
+
else markTabDone(tab, timestamp);
|
|
9746
|
+
} else if (tab.activity?.isWorking) markTabIdle(tab, timestamp);
|
|
9747
|
+
tab.pendingTurnFailure = false;
|
|
9502
9748
|
break;
|
|
9503
9749
|
case "compaction_end":
|
|
9504
9750
|
patchTabState(tab, { isCompacting: false });
|
|
@@ -9508,8 +9754,14 @@ function updateTabActivityFromEvent(tab, event) {
|
|
|
9508
9754
|
patchTabState(tab, { pendingMessageCount: (event.steering?.length || 0) + (event.followUp?.length || 0) });
|
|
9509
9755
|
break;
|
|
9510
9756
|
case "pi_process_exit":
|
|
9757
|
+
if (tab.activity?.runStarted && (Number(event.code) !== 0 || event.signal)) markTabFailed(tab, timestamp);
|
|
9758
|
+
else markTabIdle(tab, timestamp);
|
|
9759
|
+
tab.pendingTurnFailure = false;
|
|
9760
|
+
break;
|
|
9511
9761
|
case "pi_process_error":
|
|
9512
|
-
|
|
9762
|
+
if (tab.activity?.runStarted) markTabFailed(tab, timestamp);
|
|
9763
|
+
else markTabIdle(tab, timestamp);
|
|
9764
|
+
tab.pendingTurnFailure = false;
|
|
9513
9765
|
break;
|
|
9514
9766
|
case "response":
|
|
9515
9767
|
if (event.command === "get_state" && event.success !== false) {
|
|
@@ -9591,6 +9843,8 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
|
|
|
9591
9843
|
extensionStatuses: new Map(),
|
|
9592
9844
|
extensionWidgets: new Map(),
|
|
9593
9845
|
webuiSubagents: null,
|
|
9846
|
+
subagentDisplayTitle: undefined,
|
|
9847
|
+
subagentDisplayTitlePromise: undefined,
|
|
9594
9848
|
webuiHelperRequests: new Map(),
|
|
9595
9849
|
webuiHelperResponseIds: new Set(),
|
|
9596
9850
|
bashQueue: [],
|
|
@@ -9602,6 +9856,7 @@ function createTabRecord({ id, index, title, titleSource, conversationStarted, c
|
|
|
9602
9856
|
rpc,
|
|
9603
9857
|
rpcUnsubscribe: undefined,
|
|
9604
9858
|
sseClients: new Set(),
|
|
9859
|
+
browserPromptRequests: new Map(),
|
|
9605
9860
|
};
|
|
9606
9861
|
resetNaturalConversationMode(tab);
|
|
9607
9862
|
resetCodexFastMode(tab);
|
|
@@ -9639,6 +9894,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
|
|
|
9639
9894
|
|
|
9640
9895
|
attachRpcToTab(tab, rpc);
|
|
9641
9896
|
tabs.set(id, tab);
|
|
9897
|
+
workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
|
|
9642
9898
|
try {
|
|
9643
9899
|
if (rpc instanceof SupervisorPiRpcProcess) {
|
|
9644
9900
|
const snapshot = await rpcSupervisor.createTab({
|
|
@@ -9656,6 +9912,7 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
|
|
|
9656
9912
|
tab.rpcUnsubscribe?.();
|
|
9657
9913
|
rpc.dispose?.();
|
|
9658
9914
|
gitLiveWatcher.unsubscribe(id);
|
|
9915
|
+
workspaceFilesLiveWatcher.unsubscribe(id);
|
|
9659
9916
|
tabs.delete(id);
|
|
9660
9917
|
throw new Error(`Pi RPC process failed while starting ${tabTitle}: ${sanitizeError(error)}`);
|
|
9661
9918
|
}
|
|
@@ -9701,12 +9958,14 @@ async function hydrateManagedTabs(snapshot) {
|
|
|
9701
9958
|
});
|
|
9702
9959
|
attachRpcToTab(tab, rpc);
|
|
9703
9960
|
tabs.set(tab.id, tab);
|
|
9961
|
+
workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
|
|
9704
9962
|
hydrated.push(tab);
|
|
9705
9963
|
}
|
|
9706
9964
|
} catch (error) {
|
|
9707
9965
|
for (const tab of hydrated) {
|
|
9708
9966
|
tab.rpcUnsubscribe?.();
|
|
9709
9967
|
tab.rpc.dispose?.();
|
|
9968
|
+
workspaceFilesLiveWatcher.unsubscribe(tab.id);
|
|
9710
9969
|
tabs.delete(tab.id);
|
|
9711
9970
|
}
|
|
9712
9971
|
throw error;
|
|
@@ -9748,16 +10007,37 @@ function listTabs() {
|
|
|
9748
10007
|
return [...tabs.values()].map(tabMeta);
|
|
9749
10008
|
}
|
|
9750
10009
|
|
|
9751
|
-
function
|
|
10010
|
+
async function resolveSubagentDisplayTitle(tab) {
|
|
10011
|
+
const fallback = tab?.title || "";
|
|
10012
|
+
if (!tab || tab.titleSource !== "auto") return fallback;
|
|
10013
|
+
if (tab.subagentDisplayTitle) return tab.subagentDisplayTitle;
|
|
10014
|
+
if (!tab.subagentDisplayTitlePromise) {
|
|
10015
|
+
tab.subagentDisplayTitlePromise = safeRpcResponse(tab, { type: "get_messages" }, TAB_ACTIVITY_STATE_RECONCILE_TIMEOUT_MS)
|
|
10016
|
+
.then((response) => {
|
|
10017
|
+
const firstUserMessage = (Array.isArray(response.data?.messages) ? response.data.messages : []).find((message) => message?.role === "user");
|
|
10018
|
+
const title = generatedTabTitleFromPrompt(extractSessionTextContent(firstUserMessage?.content)) || fallback;
|
|
10019
|
+
tab.subagentDisplayTitle = title;
|
|
10020
|
+
return title;
|
|
10021
|
+
})
|
|
10022
|
+
.catch(() => {
|
|
10023
|
+
tab.subagentDisplayTitle = fallback;
|
|
10024
|
+
return fallback;
|
|
10025
|
+
});
|
|
10026
|
+
}
|
|
10027
|
+
return tab.subagentDisplayTitlePromise;
|
|
10028
|
+
}
|
|
10029
|
+
|
|
10030
|
+
async function webuiSubagentsData() {
|
|
9752
10031
|
const sortedTabs = [...tabs.values()].sort((a, b) => a.index - b.index || a.title.localeCompare(b.title));
|
|
9753
|
-
const tabSummaries = sortedTabs.map((tab) => {
|
|
10032
|
+
const tabSummaries = await Promise.all(sortedTabs.map(async (tab) => {
|
|
9754
10033
|
const status = tab.webuiSubagents || { version: 1, available: false, updatedAt: null, receivedAt: null, runs: [], gates: [] };
|
|
9755
10034
|
const runs = Array.isArray(status.runs) ? status.runs : [];
|
|
9756
10035
|
const gates = Array.isArray(status.gates) ? status.gates : [];
|
|
10036
|
+
const tabTitle = runs.length || gates.length ? await resolveSubagentDisplayTitle(tab) : tab.title;
|
|
9757
10037
|
return {
|
|
9758
10038
|
tabId: tab.id,
|
|
9759
10039
|
tabIndex: tab.index,
|
|
9760
|
-
tabTitle
|
|
10040
|
+
tabTitle,
|
|
9761
10041
|
cwd: tab.cwd,
|
|
9762
10042
|
sessionName: normalizeWebuiSubagentText(tab.lastState?.sessionName || tab.title, 160),
|
|
9763
10043
|
sessionFile: tabRestorableSessionFile(tab) || null,
|
|
@@ -9772,7 +10052,7 @@ function webuiSubagentsData() {
|
|
|
9772
10052
|
runningAgents: runs.reduce((count, run) => count + run.agents.filter((agent) => agent.status === "running").length, 0),
|
|
9773
10053
|
gateCount: gates.length,
|
|
9774
10054
|
};
|
|
9775
|
-
});
|
|
10055
|
+
}));
|
|
9776
10056
|
return {
|
|
9777
10057
|
version: 1,
|
|
9778
10058
|
updatedAt: Date.now(),
|
|
@@ -9859,6 +10139,29 @@ function normalizeWebuiSubagentTranscript(value) {
|
|
|
9859
10139
|
return messages;
|
|
9860
10140
|
}
|
|
9861
10141
|
|
|
10142
|
+
function normalizeWebuiSubagentTelemetry(value, fallback = {}) {
|
|
10143
|
+
const telemetry = value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
10144
|
+
const number = (candidate, limit = WEBUI_SUBAGENT_TELEMETRY_TOKEN_LIMIT) => (
|
|
10145
|
+
typeof candidate === "number" && Number.isFinite(candidate) && candidate >= 0 && candidate <= limit ? candidate : null
|
|
10146
|
+
);
|
|
10147
|
+
const model = normalizeWebuiSubagentText(telemetry?.model, 240)
|
|
10148
|
+
|| normalizeWebuiSubagentText(fallback.model, 240)
|
|
10149
|
+
|| null;
|
|
10150
|
+
const effort = normalizeWebuiSubagentText(telemetry?.effort, 40)
|
|
10151
|
+
|| normalizeWebuiSubagentText(fallback.effort, 40)
|
|
10152
|
+
|| null;
|
|
10153
|
+
return {
|
|
10154
|
+
promptInjectionTokens: number(telemetry?.promptInjectionTokens),
|
|
10155
|
+
inputTokens: number(telemetry?.inputTokens),
|
|
10156
|
+
outputTokens: number(telemetry?.outputTokens),
|
|
10157
|
+
tokenSpeed: number(telemetry?.tokenSpeed, WEBUI_SUBAGENT_TELEMETRY_SPEED_LIMIT),
|
|
10158
|
+
contextTokens: number(telemetry?.contextTokens),
|
|
10159
|
+
contextWindow: number(telemetry?.contextWindow, WEBUI_SUBAGENT_TELEMETRY_CONTEXT_WINDOW_LIMIT),
|
|
10160
|
+
model,
|
|
10161
|
+
effort,
|
|
10162
|
+
};
|
|
10163
|
+
}
|
|
10164
|
+
|
|
9862
10165
|
function normalizeWebuiSubagentOutput(value, selection) {
|
|
9863
10166
|
if (!value || typeof value !== "object" || value.version !== 1) throw makeHttpError(502, "Invalid subagent output response from Web UI helper");
|
|
9864
10167
|
const rawAgent = value.agent && typeof value.agent === "object" ? value.agent : {};
|
|
@@ -9893,6 +10196,10 @@ function normalizeWebuiSubagentOutput(value, selection) {
|
|
|
9893
10196
|
tokens: Number.isFinite(rawAgent.tokens) ? rawAgent.tokens : undefined,
|
|
9894
10197
|
model: normalizeWebuiSubagentText(rawAgent.model, 240) || selection.agent.model || undefined,
|
|
9895
10198
|
thinking: normalizeWebuiSubagentText(rawAgent.thinking, 40) || selection.agent.thinking || undefined,
|
|
10199
|
+
telemetry: normalizeWebuiSubagentTelemetry(rawAgent.telemetry, {
|
|
10200
|
+
model: normalizeWebuiSubagentText(rawAgent.model, 240) || selection.agent.model,
|
|
10201
|
+
effort: normalizeWebuiSubagentText(rawAgent.thinking, 40) || selection.agent.thinking,
|
|
10202
|
+
}),
|
|
9896
10203
|
recentTools,
|
|
9897
10204
|
recentOutput,
|
|
9898
10205
|
transcript,
|
|
@@ -10117,6 +10424,28 @@ function spawnRestartServer(restorableTabs, supervisorCursor) {
|
|
|
10117
10424
|
let updateStatusCache = null;
|
|
10118
10425
|
let updateStatusCacheAt = 0;
|
|
10119
10426
|
let piUpdateInProgress = false;
|
|
10427
|
+
const componentUpdateState = new ComponentUpdateState();
|
|
10428
|
+
|
|
10429
|
+
function webuiComponentUpdateUnavailableReason() {
|
|
10430
|
+
if (webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules")) {
|
|
10431
|
+
return "Automatic Web UI update is unavailable from a source or development checkout.";
|
|
10432
|
+
}
|
|
10433
|
+
return "";
|
|
10434
|
+
}
|
|
10435
|
+
|
|
10436
|
+
function privilegedUpdateInProgress() {
|
|
10437
|
+
return piUpdateInProgress || componentUpdateState.hasRunning();
|
|
10438
|
+
}
|
|
10439
|
+
|
|
10440
|
+
function componentUpdatesForRequest(req) {
|
|
10441
|
+
const webuiUnavailableReason = webuiComponentUpdateUnavailableReason();
|
|
10442
|
+
return componentUpdateState.publicStates({
|
|
10443
|
+
localRequest: isLocalRequest(req),
|
|
10444
|
+
updateInProgress: privilegedUpdateInProgress(),
|
|
10445
|
+
webuiAvailable: !webuiUnavailableReason,
|
|
10446
|
+
webuiUnavailableReason,
|
|
10447
|
+
});
|
|
10448
|
+
}
|
|
10120
10449
|
|
|
10121
10450
|
function updateChecksSkippedReason() {
|
|
10122
10451
|
if (process.env.PI_OFFLINE) return "PI_OFFLINE is set";
|
|
@@ -10199,7 +10528,8 @@ function updateStatusForRequest(status, req) {
|
|
|
10199
10528
|
return {
|
|
10200
10529
|
...status,
|
|
10201
10530
|
canRunUpdate: isLocalRequest(req),
|
|
10202
|
-
updateInProgress:
|
|
10531
|
+
updateInProgress: privilegedUpdateInProgress(),
|
|
10532
|
+
componentUpdates: componentUpdatesForRequest(req),
|
|
10203
10533
|
};
|
|
10204
10534
|
}
|
|
10205
10535
|
|
|
@@ -10243,31 +10573,37 @@ async function piUpdateCommandSupportsAll(command) {
|
|
|
10243
10573
|
async function resolvePiUpdateCommands({ all = false } = {}) {
|
|
10244
10574
|
let resolveCommand;
|
|
10245
10575
|
let labelPrefix = "";
|
|
10576
|
+
let useBundledPi = false;
|
|
10246
10577
|
|
|
10247
10578
|
if (options.piBinExplicit) {
|
|
10248
10579
|
resolveCommand = (args) => resolvePiCommand(args);
|
|
10249
10580
|
} else {
|
|
10250
|
-
const
|
|
10581
|
+
const selectedPi = resolveSelectedPiCommand(["--version"]);
|
|
10582
|
+
const pathPi = await runCommand(selectedPi.command, selectedPi.args, { timeoutMs: 3000, maxOutputLength: 4000 });
|
|
10251
10583
|
if (pathPi.exitCode === 0 && !pathPi.timedOut && !pathPi.error) {
|
|
10252
|
-
resolveCommand = async (args) => (
|
|
10253
|
-
command: options.piBin,
|
|
10254
|
-
args,
|
|
10255
|
-
displayCommand: formatCommandForDisplay(options.piBin, args),
|
|
10256
|
-
});
|
|
10584
|
+
resolveCommand = async (args) => resolveSelectedPiCommand(args);
|
|
10257
10585
|
} else {
|
|
10258
10586
|
resolveCommand = (args) => resolvePiCommand(args);
|
|
10259
10587
|
labelPrefix = "bundled ";
|
|
10588
|
+
useBundledPi = true;
|
|
10260
10589
|
}
|
|
10261
10590
|
}
|
|
10262
10591
|
|
|
10263
10592
|
const supportsAll = all && await piUpdateCommandSupportsAll(await resolveCommand(["update", "--help"]));
|
|
10264
10593
|
const steps = piUpdateCommandSteps({ all, supportsAll });
|
|
10265
|
-
return Promise.all(steps.map(async (step) =>
|
|
10266
|
-
|
|
10267
|
-
|
|
10268
|
-
|
|
10269
|
-
|
|
10270
|
-
|
|
10594
|
+
return Promise.all(steps.map(async (step) => {
|
|
10595
|
+
const command = await resolveCommand(step.args);
|
|
10596
|
+
const selectedPiDirectory = useBundledPi || isNodeScriptCommand(options.piBin) ? "" : resolveCommandDirectory(options.piBin);
|
|
10597
|
+
const piInstallDirectory = selectedPiDirectory || resolveCommandDirectory(command.command);
|
|
10598
|
+
return {
|
|
10599
|
+
...command,
|
|
10600
|
+
label: `${labelPrefix}${step.label}`,
|
|
10601
|
+
timeoutMs: PI_UPDATE_TIMEOUT_MS,
|
|
10602
|
+
maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS,
|
|
10603
|
+
piInstallDirectory,
|
|
10604
|
+
env: piInstallDirectory ? prependedPathEnvironment(piInstallDirectory) : undefined,
|
|
10605
|
+
};
|
|
10606
|
+
}));
|
|
10271
10607
|
}
|
|
10272
10608
|
|
|
10273
10609
|
function packageNodeModulesPath(nodeModulesRoot, packageName) {
|
|
@@ -10345,8 +10681,8 @@ function packageInstallSpecs(packageNames) {
|
|
|
10345
10681
|
return packageNames.map((packageName) => `${packageName}@latest`);
|
|
10346
10682
|
}
|
|
10347
10683
|
|
|
10348
|
-
function resolvedNpmCommand(args) {
|
|
10349
|
-
const invocation = resolveNpmCommandInvocation(args);
|
|
10684
|
+
function resolvedNpmCommand(args, runtime = {}) {
|
|
10685
|
+
const invocation = resolveNpmCommandInvocation(args, runtime);
|
|
10350
10686
|
return {
|
|
10351
10687
|
command: invocation.command,
|
|
10352
10688
|
args: invocation.args,
|
|
@@ -10354,9 +10690,9 @@ function resolvedNpmCommand(args) {
|
|
|
10354
10690
|
};
|
|
10355
10691
|
}
|
|
10356
10692
|
|
|
10357
|
-
function npmPrefixUpdateTask(label, installRoot, packageNames) {
|
|
10693
|
+
function npmPrefixUpdateTask(label, installRoot, packageNames, npmRuntime = {}) {
|
|
10358
10694
|
if (!packageNames.length) return null;
|
|
10359
|
-
const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)]);
|
|
10695
|
+
const npmCommand = resolvedNpmCommand(["install", "--prefix", installRoot, "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packageNames)], npmRuntime);
|
|
10360
10696
|
return {
|
|
10361
10697
|
label,
|
|
10362
10698
|
command: npmCommand.command,
|
|
@@ -10366,31 +10702,31 @@ function npmPrefixUpdateTask(label, installRoot, packageNames) {
|
|
|
10366
10702
|
};
|
|
10367
10703
|
}
|
|
10368
10704
|
|
|
10369
|
-
async function currentWebuiPackageUpdateTask() {
|
|
10705
|
+
async function currentWebuiPackageUpdateTask(npmRuntime = {}) {
|
|
10370
10706
|
const sourceCheckout = webuiDevServer || !String(packageRoot).split(path.sep).includes("node_modules");
|
|
10371
10707
|
if (sourceCheckout) {
|
|
10372
10708
|
const manifest = await readJsonFileIfExists(path.join(packageRoot, "package.json"));
|
|
10373
10709
|
const packages = declaredWebuiPiPackageNames(manifest);
|
|
10374
|
-
return npmPrefixUpdateTask("current Web UI checkout package dependencies", packageRoot, packages);
|
|
10710
|
+
return npmPrefixUpdateTask("current Web UI checkout package dependencies", packageRoot, packages, npmRuntime);
|
|
10375
10711
|
}
|
|
10376
10712
|
|
|
10377
10713
|
const installRoot = nodeModulesParentForPackageRoot(packageRoot);
|
|
10378
10714
|
const packages = await packagesPresentInInstallPrefix(installRoot);
|
|
10379
|
-
return npmPrefixUpdateTask("current Web UI install root", installRoot, packages);
|
|
10715
|
+
return npmPrefixUpdateTask("current Web UI install root", installRoot, packages, npmRuntime);
|
|
10380
10716
|
}
|
|
10381
10717
|
|
|
10382
|
-
async function agentPackageRootUpdateTask() {
|
|
10718
|
+
async function agentPackageRootUpdateTask(npmRuntime = {}) {
|
|
10383
10719
|
const installRoot = configuredAgentNpmRoot();
|
|
10384
10720
|
const packages = await packagesPresentInInstallPrefix(installRoot);
|
|
10385
|
-
return npmPrefixUpdateTask("Pi agent npm package root", installRoot, packages);
|
|
10721
|
+
return npmPrefixUpdateTask("Pi agent npm package root", installRoot, packages, npmRuntime);
|
|
10386
10722
|
}
|
|
10387
10723
|
|
|
10388
|
-
async function optionalFeatureInstallRootUpdateTask() {
|
|
10724
|
+
async function optionalFeatureInstallRootUpdateTask(npmRuntime = {}) {
|
|
10389
10725
|
const configuredRoot = process.env[OPTIONAL_FEATURE_INSTALL_ROOT_ENV];
|
|
10390
10726
|
if (!configuredRoot) return null;
|
|
10391
10727
|
const installRoot = path.resolve(expandUserPath(configuredRoot));
|
|
10392
10728
|
const packages = await packagesPresentInInstallPrefix(installRoot);
|
|
10393
|
-
return npmPrefixUpdateTask("configured optional-feature npm root", installRoot, packages);
|
|
10729
|
+
return npmPrefixUpdateTask("configured optional-feature npm root", installRoot, packages, npmRuntime);
|
|
10394
10730
|
}
|
|
10395
10731
|
|
|
10396
10732
|
function activeProjectPackageRoots() {
|
|
@@ -10405,28 +10741,28 @@ function activeProjectPackageRoots() {
|
|
|
10405
10741
|
return [...roots].sort();
|
|
10406
10742
|
}
|
|
10407
10743
|
|
|
10408
|
-
async function projectPackageRootUpdateTasks() {
|
|
10744
|
+
async function projectPackageRootUpdateTasks(npmRuntime = {}) {
|
|
10409
10745
|
const tasks = [];
|
|
10410
10746
|
for (const installRoot of activeProjectPackageRoots()) {
|
|
10411
10747
|
const packages = await packagesPresentInInstallPrefix(installRoot);
|
|
10412
|
-
const task = npmPrefixUpdateTask(`project Pi package root (${displayPath(path.dirname(installRoot))})`, installRoot, packages);
|
|
10748
|
+
const task = npmPrefixUpdateTask(`project Pi package root (${displayPath(path.dirname(installRoot))})`, installRoot, packages, npmRuntime);
|
|
10413
10749
|
if (task) tasks.push(task);
|
|
10414
10750
|
}
|
|
10415
10751
|
return tasks;
|
|
10416
10752
|
}
|
|
10417
10753
|
|
|
10418
|
-
async function npmGlobalNodeModulesRoot() {
|
|
10419
|
-
const npmCommand = resolvedNpmCommand(["root", "-g"]);
|
|
10754
|
+
async function npmGlobalNodeModulesRoot(npmRuntime = {}) {
|
|
10755
|
+
const npmCommand = resolvedNpmCommand(["root", "-g"], npmRuntime);
|
|
10420
10756
|
const result = await runCommand(npmCommand.command, npmCommand.args, { timeoutMs: 5000, maxOutputLength: 8000 });
|
|
10421
10757
|
if (result.exitCode !== 0 || result.timedOut || result.error) return null;
|
|
10422
10758
|
return result.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1) || null;
|
|
10423
10759
|
}
|
|
10424
10760
|
|
|
10425
|
-
async function npmGlobalPackageRootUpdateTask() {
|
|
10426
|
-
const nodeModulesRoot = await npmGlobalNodeModulesRoot();
|
|
10761
|
+
async function npmGlobalPackageRootUpdateTask(npmRuntime = {}) {
|
|
10762
|
+
const nodeModulesRoot = await npmGlobalNodeModulesRoot(npmRuntime);
|
|
10427
10763
|
const packages = await packagesPresentInNodeModulesRoot(nodeModulesRoot);
|
|
10428
10764
|
if (!packages.length) return null;
|
|
10429
|
-
const npmCommand = resolvedNpmCommand(["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)]);
|
|
10765
|
+
const npmCommand = resolvedNpmCommand(["install", "-g", "--ignore-scripts", "--min-release-age=0", ...packageInstallSpecs(packages)], npmRuntime);
|
|
10430
10766
|
return {
|
|
10431
10767
|
label: "global npm package root",
|
|
10432
10768
|
command: npmCommand.command,
|
|
@@ -10463,6 +10799,42 @@ async function bunGlobalPackageRootUpdateTask() {
|
|
|
10463
10799
|
};
|
|
10464
10800
|
}
|
|
10465
10801
|
|
|
10802
|
+
async function currentWebuiComponentUpdateTask(npmRuntime = {}) {
|
|
10803
|
+
const unavailableReason = webuiComponentUpdateUnavailableReason();
|
|
10804
|
+
if (unavailableReason) throw makeHttpError(409, unavailableReason);
|
|
10805
|
+
|
|
10806
|
+
const normalizedPackageRoot = path.resolve(packageRoot);
|
|
10807
|
+
for (const nodeModulesRoot of await bunGlobalNodeModulesRoots()) {
|
|
10808
|
+
if (path.resolve(packageNodeModulesPath(nodeModulesRoot, WEBUI_PACKAGE)) !== normalizedPackageRoot) continue;
|
|
10809
|
+
return {
|
|
10810
|
+
label: "global Bun Web UI package",
|
|
10811
|
+
command: "bun",
|
|
10812
|
+
args: ["install", "-g", "--ignore-scripts", "--minimum-release-age=0", `${WEBUI_PACKAGE}@latest`],
|
|
10813
|
+
cwd: homedir(),
|
|
10814
|
+
};
|
|
10815
|
+
}
|
|
10816
|
+
|
|
10817
|
+
const installRoot = nodeModulesParentForPackageRoot(packageRoot);
|
|
10818
|
+
return npmPrefixUpdateTask("current Web UI package", installRoot, [WEBUI_PACKAGE], npmRuntime);
|
|
10819
|
+
}
|
|
10820
|
+
|
|
10821
|
+
async function resolveComponentUpdateTasks(target) {
|
|
10822
|
+
if (target === "pi") return resolvePiUpdateCommands({ all: false });
|
|
10823
|
+
if (target === "webui") {
|
|
10824
|
+
let npmRuntime = {};
|
|
10825
|
+
try {
|
|
10826
|
+
const piTasks = await resolvePiUpdateCommands({ all: false });
|
|
10827
|
+
npmRuntime = {
|
|
10828
|
+
preferredDirectories: [...new Set(piTasks.map((task) => task.piInstallDirectory).filter(Boolean))],
|
|
10829
|
+
};
|
|
10830
|
+
} catch {
|
|
10831
|
+
recordEvent({ type: "webui_component_update_npm_resolution_fallback", target });
|
|
10832
|
+
}
|
|
10833
|
+
return [await currentWebuiComponentUpdateTask(npmRuntime)];
|
|
10834
|
+
}
|
|
10835
|
+
throw makeHttpError(400, "Unsupported component update target.");
|
|
10836
|
+
}
|
|
10837
|
+
|
|
10466
10838
|
function updateTaskDisplay(task) {
|
|
10467
10839
|
return task.displayCommand || formatCommandForDisplay(task.command, task.args || []);
|
|
10468
10840
|
}
|
|
@@ -10483,6 +10855,9 @@ async function resolveUpdateTasks({ all = false } = {}) {
|
|
|
10483
10855
|
const piTasks = await resolvePiUpdateCommands({ all });
|
|
10484
10856
|
if (!all) return uniqueUpdateTasks(piTasks);
|
|
10485
10857
|
|
|
10858
|
+
const npmRuntime = {
|
|
10859
|
+
preferredDirectories: [...new Set(piTasks.map((task) => task.piInstallDirectory).filter(Boolean))],
|
|
10860
|
+
};
|
|
10486
10861
|
const [
|
|
10487
10862
|
currentWebuiTask,
|
|
10488
10863
|
agentTask,
|
|
@@ -10491,11 +10866,11 @@ async function resolveUpdateTasks({ all = false } = {}) {
|
|
|
10491
10866
|
globalNpmTask,
|
|
10492
10867
|
globalBunTask,
|
|
10493
10868
|
] = await Promise.all([
|
|
10494
|
-
currentWebuiPackageUpdateTask(),
|
|
10495
|
-
agentPackageRootUpdateTask(),
|
|
10496
|
-
optionalFeatureInstallRootUpdateTask(),
|
|
10497
|
-
projectPackageRootUpdateTasks(),
|
|
10498
|
-
npmGlobalPackageRootUpdateTask(),
|
|
10869
|
+
currentWebuiPackageUpdateTask(npmRuntime),
|
|
10870
|
+
agentPackageRootUpdateTask(npmRuntime),
|
|
10871
|
+
optionalFeatureInstallRootUpdateTask(npmRuntime),
|
|
10872
|
+
projectPackageRootUpdateTasks(npmRuntime),
|
|
10873
|
+
npmGlobalPackageRootUpdateTask(npmRuntime),
|
|
10499
10874
|
bunGlobalPackageRootUpdateTask(),
|
|
10500
10875
|
]);
|
|
10501
10876
|
|
|
@@ -10521,6 +10896,7 @@ async function runUpdateTask(task) {
|
|
|
10521
10896
|
cwd: task.cwd || process.cwd(),
|
|
10522
10897
|
timeoutMs: task.timeoutMs || PACKAGE_UPDATE_TIMEOUT_MS,
|
|
10523
10898
|
maxOutputLength: task.maxOutputLength || PACKAGE_UPDATE_OUTPUT_MAX_CHARS,
|
|
10899
|
+
env: task.env,
|
|
10524
10900
|
});
|
|
10525
10901
|
const ok = result.exitCode === 0 && !result.timedOut && !result.error;
|
|
10526
10902
|
if (!ok) {
|
|
@@ -10547,8 +10923,43 @@ function combinedUpdateOutput(results, field) {
|
|
|
10547
10923
|
.join("\n\n");
|
|
10548
10924
|
}
|
|
10549
10925
|
|
|
10926
|
+
function componentUpdateSuccessMessage(target) {
|
|
10927
|
+
if (target === "pi") return "Pi update completed. New or reloaded Pi sessions use the update.";
|
|
10928
|
+
return "Web UI update completed. Restart the Web UI to use the update.";
|
|
10929
|
+
}
|
|
10930
|
+
|
|
10931
|
+
async function runComponentUpdate(target) {
|
|
10932
|
+
try {
|
|
10933
|
+
const updateTasks = (await resolveComponentUpdateTasks(target)).filter(Boolean);
|
|
10934
|
+
if (!updateTasks.length) throw new Error(`No ${target} update command could be resolved.`);
|
|
10935
|
+
const command = updateTasks.map(updateTaskDisplay).join(" && ");
|
|
10936
|
+
recordEvent({ type: "webui_component_update_started", target, command });
|
|
10937
|
+
for (const task of updateTasks) await runUpdateTask(task);
|
|
10938
|
+
updateStatusCache = null;
|
|
10939
|
+
updateStatusCacheAt = 0;
|
|
10940
|
+
componentUpdateState.succeed(target, componentUpdateSuccessMessage(target));
|
|
10941
|
+
recordEvent({ type: "webui_component_update_completed", target, command });
|
|
10942
|
+
} catch (error) {
|
|
10943
|
+
updateStatusCache = null;
|
|
10944
|
+
updateStatusCacheAt = 0;
|
|
10945
|
+
componentUpdateState.fail(target, error);
|
|
10946
|
+
recordEvent({ type: "webui_component_update_failed", target, error: componentUpdateState.get(target).error });
|
|
10947
|
+
}
|
|
10948
|
+
}
|
|
10949
|
+
|
|
10950
|
+
function startComponentUpdate(target) {
|
|
10951
|
+
if (piUpdateInProgress || componentUpdateState.hasRunning()) throw makeHttpError(409, "Another privileged update is already running.");
|
|
10952
|
+
const unavailableReason = target === "webui" ? webuiComponentUpdateUnavailableReason() : "";
|
|
10953
|
+
if (unavailableReason) throw makeHttpError(409, unavailableReason);
|
|
10954
|
+
componentUpdateState.begin(target);
|
|
10955
|
+
recordEvent({ type: "webui_component_update_accepted", target });
|
|
10956
|
+
setImmediate(() => { void runComponentUpdate(target); });
|
|
10957
|
+
return componentUpdateState.get(target);
|
|
10958
|
+
}
|
|
10959
|
+
|
|
10550
10960
|
async function runPiUpdateAndPrepareRestart({ all = false } = {}) {
|
|
10551
10961
|
if (piUpdateInProgress) throw makeHttpError(409, "A Pi update is already running.");
|
|
10962
|
+
if (componentUpdateState.hasRunning()) throw makeHttpError(409, "A component update is already running.");
|
|
10552
10963
|
piUpdateInProgress = true;
|
|
10553
10964
|
let restartPrepared = false;
|
|
10554
10965
|
try {
|
|
@@ -10617,6 +11028,21 @@ const gitLiveWatcher = createGitLiveWatcher({
|
|
|
10617
11028
|
},
|
|
10618
11029
|
});
|
|
10619
11030
|
|
|
11031
|
+
const workspaceFilesLiveWatcher = createWorkspaceFilesLiveWatcher({
|
|
11032
|
+
onChange: ({ root, tabIds, changedAt }) => {
|
|
11033
|
+
for (const tabId of tabIds) {
|
|
11034
|
+
const tab = tabs.get(tabId);
|
|
11035
|
+
if (!tab || workspaceFilesLiveWatcher.subscribedRootForTab(tab.id) !== root) continue;
|
|
11036
|
+
broadcastTabEvent(tab, { type: "webui_workspace_files_changed", tabId: tab.id, root, changedAt });
|
|
11037
|
+
}
|
|
11038
|
+
},
|
|
11039
|
+
onError: ({ root, error }) => {
|
|
11040
|
+
const message = sanitizeError(error);
|
|
11041
|
+
recordEvent({ type: "webui_workspace_files_watch_error", root, error: message });
|
|
11042
|
+
console.warn(`Workspace files live watcher disabled for ${root}: ${message}`);
|
|
11043
|
+
},
|
|
11044
|
+
});
|
|
11045
|
+
|
|
10620
11046
|
function trackGitRepositoryForTab(tab, root) {
|
|
10621
11047
|
if (tab?.id && root) gitLiveWatcher.subscribe(tab.id, root);
|
|
10622
11048
|
return root;
|
|
@@ -10631,6 +11057,8 @@ function renameTab(tab, title, { source = "explicit", maxLength, unique = source
|
|
|
10631
11057
|
const previousTitle = tab.title;
|
|
10632
11058
|
tab.title = nextTitle;
|
|
10633
11059
|
tab.titleSource = source;
|
|
11060
|
+
tab.subagentDisplayTitle = source === "auto" ? truncateTabTitle(title, AUTO_TAB_TITLE_DISPLAY_MAX_LENGTH) : undefined;
|
|
11061
|
+
tab.subagentDisplayTitlePromise = undefined;
|
|
10634
11062
|
if (previousTitle === nextTitle) return false;
|
|
10635
11063
|
scheduleSupervisorMetadataUpdate(tab);
|
|
10636
11064
|
|
|
@@ -10656,6 +11084,11 @@ function maybeNameTabForConversation(tab, command) {
|
|
|
10656
11084
|
return renameTab(tab, title, { source: "auto", maxLength: AUTO_TAB_TITLE_MAX_LENGTH });
|
|
10657
11085
|
}
|
|
10658
11086
|
|
|
11087
|
+
function resetAutomaticTabTitleForNewSession(tab) {
|
|
11088
|
+
if (!tab || tab.titleSource === "explicit") return false;
|
|
11089
|
+
return renameTab(tab, defaultTabTitle(tab.index), { source: "default", unique: false });
|
|
11090
|
+
}
|
|
11091
|
+
|
|
10659
11092
|
function responseWithTab(response, tab) {
|
|
10660
11093
|
if (!response || typeof response !== "object") return response;
|
|
10661
11094
|
return { ...response, tab: tabMeta(tab) };
|
|
@@ -10733,6 +11166,8 @@ async function performTabCwdUpdate(tab, cwd) {
|
|
|
10733
11166
|
attachRpcToTab(tab, rpc);
|
|
10734
11167
|
if (startDirectRpc) rpc.start();
|
|
10735
11168
|
gitLiveWatcher.unsubscribe(tab.id);
|
|
11169
|
+
workspaceFilesLiveWatcher.unsubscribe(tab.id);
|
|
11170
|
+
workspaceFilesLiveWatcher.subscribe(tab.id, tab.cwd);
|
|
10736
11171
|
// Non-fatal: a failed start surfaces through pi_process_error/exit events.
|
|
10737
11172
|
await primeTabRpc(tab).catch(() => {});
|
|
10738
11173
|
|
|
@@ -12907,6 +13342,7 @@ async function handleNativeSlashCommand(tab, body, req) {
|
|
|
12907
13342
|
const response = await tab.rpc.send({ type: "new_session" });
|
|
12908
13343
|
if (response.success === false) return response;
|
|
12909
13344
|
tab.conversationStarted = false;
|
|
13345
|
+
resetAutomaticTabTitleForNewSession(tab);
|
|
12910
13346
|
forgetTabState(tab);
|
|
12911
13347
|
rememberTabState(tab, response.data);
|
|
12912
13348
|
clearPendingExtensionUiRequests(tab);
|
|
@@ -13006,6 +13442,7 @@ async function closeTab(id, { allowLast = false } = {}) {
|
|
|
13006
13442
|
}
|
|
13007
13443
|
rememberClosedRestorableTab(tab, restorableState);
|
|
13008
13444
|
gitLiveWatcher.unsubscribe(tab.id);
|
|
13445
|
+
workspaceFilesLiveWatcher.unsubscribe(tab.id);
|
|
13009
13446
|
|
|
13010
13447
|
const closingEvent = { type: "webui_tab_closing", tabId: tab.id, tabTitle: tab.title };
|
|
13011
13448
|
recordEvent(closingEvent);
|
|
@@ -13026,6 +13463,7 @@ async function closeTab(id, { allowLast = false } = {}) {
|
|
|
13026
13463
|
async function discardTab(tab) {
|
|
13027
13464
|
if (!tab || !tabs.has(tab.id)) return;
|
|
13028
13465
|
gitLiveWatcher.unsubscribe(tab.id);
|
|
13466
|
+
workspaceFilesLiveWatcher.unsubscribe(tab.id);
|
|
13029
13467
|
tab.rpcUnsubscribe?.();
|
|
13030
13468
|
rejectTabBashQueue(tab, new Error("Pi recovery tab initialization failed"));
|
|
13031
13469
|
stopAppRunnerForTab(tab, "recovery initialization failed", { force: true });
|
|
@@ -13199,8 +13637,9 @@ function activateOutputMode(client, activeMode, reason = "server-default-change"
|
|
|
13199
13637
|
}
|
|
13200
13638
|
|
|
13201
13639
|
function sendSseToClient(client, event) {
|
|
13202
|
-
sendSse(client, event);
|
|
13203
|
-
if (client?.pendingMode && isOutputModeSemanticBarrier(event)) activateOutputMode(client, client.pendingMode);
|
|
13640
|
+
const sent = sendSse(client, event);
|
|
13641
|
+
if (sent && client?.pendingMode && isOutputModeSemanticBarrier(event)) activateOutputMode(client, client.pendingMode);
|
|
13642
|
+
return sent;
|
|
13204
13643
|
}
|
|
13205
13644
|
|
|
13206
13645
|
function refreshAutoOutputModes() {
|
|
@@ -13220,6 +13659,58 @@ function refreshAutoOutputModes() {
|
|
|
13220
13659
|
}
|
|
13221
13660
|
}
|
|
13222
13661
|
|
|
13662
|
+
const BROWSER_PROMPT_REQUEST_ID = /^[A-Za-z0-9_-]{16,128}$/;
|
|
13663
|
+
const BROWSER_PROMPT_REQUEST_TTL_MS = 10 * 60 * 1000;
|
|
13664
|
+
const BROWSER_PROMPT_REQUEST_LIMIT = 256;
|
|
13665
|
+
|
|
13666
|
+
function browserPromptRequestId(value) {
|
|
13667
|
+
if (value === undefined) return null;
|
|
13668
|
+
const id = String(value || "");
|
|
13669
|
+
if (!BROWSER_PROMPT_REQUEST_ID.test(id)) throw makeHttpError(400, "requestId must be an opaque 16-128 character identifier");
|
|
13670
|
+
return id;
|
|
13671
|
+
}
|
|
13672
|
+
|
|
13673
|
+
function browserPromptFingerprint(body) {
|
|
13674
|
+
return createHash("sha256").update(JSON.stringify({
|
|
13675
|
+
message: String(body?.message || ""),
|
|
13676
|
+
streamingBehavior: body?.streamingBehavior === "steer" || body?.streamingBehavior === "followUp" ? body.streamingBehavior : "",
|
|
13677
|
+
images: Array.isArray(body?.images) ? body.images : [],
|
|
13678
|
+
})).digest("base64url");
|
|
13679
|
+
}
|
|
13680
|
+
|
|
13681
|
+
function pruneBrowserPromptRequests(tab, now = Date.now()) {
|
|
13682
|
+
const requests = tab?.browserPromptRequests;
|
|
13683
|
+
if (!requests) return;
|
|
13684
|
+
for (const [id, entry] of requests) {
|
|
13685
|
+
if (entry.settledAt && entry.settledAt + BROWSER_PROMPT_REQUEST_TTL_MS <= now) requests.delete(id);
|
|
13686
|
+
}
|
|
13687
|
+
}
|
|
13688
|
+
|
|
13689
|
+
async function deduplicateBrowserPromptRequest(tab, body, dispatch) {
|
|
13690
|
+
const requestId = browserPromptRequestId(body?.requestId);
|
|
13691
|
+
if (!requestId) return dispatch();
|
|
13692
|
+
const requests = tab.browserPromptRequests || (tab.browserPromptRequests = new Map());
|
|
13693
|
+
const fingerprint = browserPromptFingerprint(body);
|
|
13694
|
+
pruneBrowserPromptRequests(tab);
|
|
13695
|
+
const known = requests.get(requestId);
|
|
13696
|
+
if (known) {
|
|
13697
|
+
if (known.fingerprint !== fingerprint) throw makeHttpError(409, "requestId was already used for a different prompt");
|
|
13698
|
+
return known.promise;
|
|
13699
|
+
}
|
|
13700
|
+
while (requests.size >= BROWSER_PROMPT_REQUEST_LIMIT) {
|
|
13701
|
+
const settled = [...requests.entries()].find(([, entry]) => entry.settledAt);
|
|
13702
|
+
if (!settled) throw makeHttpError(429, "too many in-flight prompt requests for this tab");
|
|
13703
|
+
requests.delete(settled[0]);
|
|
13704
|
+
}
|
|
13705
|
+
const entry = { fingerprint, settledAt: 0, promise: null };
|
|
13706
|
+
entry.promise = Promise.resolve().then(dispatch).finally(() => {
|
|
13707
|
+
entry.settledAt = Date.now();
|
|
13708
|
+
pruneBrowserPromptRequests(tab, entry.settledAt);
|
|
13709
|
+
});
|
|
13710
|
+
requests.set(requestId, entry);
|
|
13711
|
+
return entry.promise;
|
|
13712
|
+
}
|
|
13713
|
+
|
|
13223
13714
|
async function saveOutputModeDefault(value) {
|
|
13224
13715
|
let mode;
|
|
13225
13716
|
try {
|
|
@@ -13625,6 +14116,36 @@ async function webuiStatus({ detailed = false, eventLimit = 40, includeAuthPin =
|
|
|
13625
14116
|
return data;
|
|
13626
14117
|
}
|
|
13627
14118
|
|
|
14119
|
+
async function handlePromptRequest(tab, body, req) {
|
|
14120
|
+
if (isNaturalConversationActive(tab) && naturalConversationSlashCommandName(body.message) && !isNaturalConversationSlashCommand(body.message)) {
|
|
14121
|
+
blockNaturalConversationAction("slash commands are blocked from the Web UI shell");
|
|
14122
|
+
}
|
|
14123
|
+
const nativeResponse = await handleNativeSlashCommand(tab, body, req);
|
|
14124
|
+
if (nativeResponse) {
|
|
14125
|
+
return { status: nativeResponse.success === false ? 400 : 200, payload: responseWithTab(nativeResponse, tab) };
|
|
14126
|
+
}
|
|
14127
|
+
const command = commandFromPost("/api/prompt", body);
|
|
14128
|
+
enforceNaturalConversationCommandAllowed(tab, command);
|
|
14129
|
+
const queuedForCompaction = maybeQueueCommandDuringCompaction(tab, command);
|
|
14130
|
+
if (queuedForCompaction) return { status: 202, payload: responseWithTab(queuedForCompaction, tab) };
|
|
14131
|
+
const naturalConversationSafetyResponse = await ensureNaturalConversationPromptSafety(tab, command);
|
|
14132
|
+
if (naturalConversationSafetyResponse?.success === false) {
|
|
14133
|
+
return { status: 400, payload: responseWithTab(naturalConversationSafetyResponse, tab) };
|
|
14134
|
+
}
|
|
14135
|
+
const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
|
|
14136
|
+
if (pendingThinkingResponse?.success === false) {
|
|
14137
|
+
return { status: 400, payload: responseWithTab(pendingThinkingResponse, tab) };
|
|
14138
|
+
}
|
|
14139
|
+
const startsVisibleWork = commandStartsVisibleWork(command);
|
|
14140
|
+
if (startsVisibleWork) {
|
|
14141
|
+
maybeNameTabForConversation(tab, command);
|
|
14142
|
+
markTabWorking(tab);
|
|
14143
|
+
}
|
|
14144
|
+
const response = await tab.rpc.send(command, PROMPT_REQUEST_TIMEOUT_MS);
|
|
14145
|
+
if (response.success === false && startsVisibleWork) markTabIdle(tab);
|
|
14146
|
+
return { status: response.success === false ? 400 : 200, payload: responseWithTab(response, tab) };
|
|
14147
|
+
}
|
|
14148
|
+
|
|
13628
14149
|
const server = createServer(async (req, res) => {
|
|
13629
14150
|
try {
|
|
13630
14151
|
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
|
|
@@ -13785,7 +14306,7 @@ const server = createServer(async (req, res) => {
|
|
|
13785
14306
|
}
|
|
13786
14307
|
|
|
13787
14308
|
if (url.pathname === "/api/subagents" && req.method === "GET") {
|
|
13788
|
-
sendJson(res, 200, { ok: true, data: webuiSubagentsData() });
|
|
14309
|
+
sendJson(res, 200, { ok: true, data: await webuiSubagentsData() });
|
|
13789
14310
|
return;
|
|
13790
14311
|
}
|
|
13791
14312
|
|
|
@@ -13871,6 +14392,7 @@ const server = createServer(async (req, res) => {
|
|
|
13871
14392
|
});
|
|
13872
14393
|
const client = {
|
|
13873
14394
|
res,
|
|
14395
|
+
tab,
|
|
13874
14396
|
requestedMode: negotiated.requestedMode,
|
|
13875
14397
|
protocolVersion: negotiated.protocolVersion,
|
|
13876
14398
|
activeMode: negotiated.activeMode,
|
|
@@ -13927,10 +14449,10 @@ const server = createServer(async (req, res) => {
|
|
|
13927
14449
|
replayExtensionStatuses(tab, client);
|
|
13928
14450
|
replayExtensionWidgets(tab, client);
|
|
13929
14451
|
replayPendingExtensionUiRequests(tab, client);
|
|
13930
|
-
const keepAlive = setInterval(() =>
|
|
14452
|
+
const keepAlive = setInterval(() => writeSseFrame(client, ": keepalive\n\n"), 15000);
|
|
13931
14453
|
req.on("close", () => {
|
|
13932
14454
|
clearInterval(keepAlive);
|
|
13933
|
-
|
|
14455
|
+
evictSlowSseClient(client);
|
|
13934
14456
|
});
|
|
13935
14457
|
return;
|
|
13936
14458
|
}
|
|
@@ -14073,6 +14595,16 @@ const server = createServer(async (req, res) => {
|
|
|
14073
14595
|
return;
|
|
14074
14596
|
}
|
|
14075
14597
|
|
|
14598
|
+
if (url.pathname === "/api/component-update" && req.method === "POST") {
|
|
14599
|
+
requireLocalhostRoute(req, url.pathname);
|
|
14600
|
+
const body = await readJsonBody(req);
|
|
14601
|
+
const validation = validateComponentUpdateRequest(body);
|
|
14602
|
+
if (!validation.ok) throw makeHttpError(400, validation.error);
|
|
14603
|
+
startComponentUpdate(validation.target);
|
|
14604
|
+
sendJson(res, 202, { ok: true, data: componentUpdatesForRequest(req)[validation.target] });
|
|
14605
|
+
return;
|
|
14606
|
+
}
|
|
14607
|
+
|
|
14076
14608
|
if (url.pathname === "/api/update" && req.method === "POST") {
|
|
14077
14609
|
requireLocalhostRoute(req, url.pathname);
|
|
14078
14610
|
const body = await readJsonBody(req);
|
|
@@ -14620,39 +15152,8 @@ const server = createServer(async (req, res) => {
|
|
|
14620
15152
|
if (url.pathname === "/api/prompt" && req.method === "POST") {
|
|
14621
15153
|
const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
|
|
14622
15154
|
const tab = getRequestedTab(req, url, body);
|
|
14623
|
-
|
|
14624
|
-
|
|
14625
|
-
}
|
|
14626
|
-
const nativeResponse = await handleNativeSlashCommand(tab, body, req);
|
|
14627
|
-
if (nativeResponse) {
|
|
14628
|
-
sendJson(res, nativeResponse.success === false ? 400 : 200, responseWithTab(nativeResponse, tab));
|
|
14629
|
-
return;
|
|
14630
|
-
}
|
|
14631
|
-
const command = commandFromPost(url.pathname, body);
|
|
14632
|
-
enforceNaturalConversationCommandAllowed(tab, command);
|
|
14633
|
-
const queuedForCompaction = maybeQueueCommandDuringCompaction(tab, command);
|
|
14634
|
-
if (queuedForCompaction) {
|
|
14635
|
-
sendJson(res, 202, responseWithTab(queuedForCompaction, tab));
|
|
14636
|
-
return;
|
|
14637
|
-
}
|
|
14638
|
-
const naturalConversationSafetyResponse = await ensureNaturalConversationPromptSafety(tab, command);
|
|
14639
|
-
if (naturalConversationSafetyResponse?.success === false) {
|
|
14640
|
-
sendJson(res, 400, responseWithTab(naturalConversationSafetyResponse, tab));
|
|
14641
|
-
return;
|
|
14642
|
-
}
|
|
14643
|
-
const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
|
|
14644
|
-
if (pendingThinkingResponse?.success === false) {
|
|
14645
|
-
sendJson(res, 400, responseWithTab(pendingThinkingResponse, tab));
|
|
14646
|
-
return;
|
|
14647
|
-
}
|
|
14648
|
-
const startsVisibleWork = commandStartsVisibleWork(command);
|
|
14649
|
-
if (startsVisibleWork) {
|
|
14650
|
-
maybeNameTabForConversation(tab, command);
|
|
14651
|
-
markTabWorking(tab);
|
|
14652
|
-
}
|
|
14653
|
-
const response = await tab.rpc.send(command, PROMPT_REQUEST_TIMEOUT_MS);
|
|
14654
|
-
if (response.success === false && startsVisibleWork) markTabIdle(tab);
|
|
14655
|
-
sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));
|
|
15155
|
+
const result = await deduplicateBrowserPromptRequest(tab, body, () => handlePromptRequest(tab, body, req));
|
|
15156
|
+
sendJson(res, result.status, result.payload);
|
|
14656
15157
|
return;
|
|
14657
15158
|
}
|
|
14658
15159
|
|
|
@@ -14838,6 +15339,7 @@ const server = createServer(async (req, res) => {
|
|
|
14838
15339
|
"/api/git-changes/unstage-all": (cwd) => unstageAllGitChanges(cwd),
|
|
14839
15340
|
"/api/git-changes/discard-file": (cwd, body) => discardGitFile(cwd, body),
|
|
14840
15341
|
"/api/git-changes/delete-untracked": (cwd, body) => deleteGitUntrackedFile(cwd, body),
|
|
15342
|
+
"/api/git-changes/add-to-gitignore": (cwd, body) => addGitignoreEntry(cwd, body),
|
|
14841
15343
|
"/api/git-operation/continue": (cwd, body) => gitOperationAction(cwd, "continue", body),
|
|
14842
15344
|
"/api/git-operation/skip": (cwd, body) => gitOperationAction(cwd, "skip", body),
|
|
14843
15345
|
"/api/git-operation/abort": (cwd, body) => gitOperationAction(cwd, "abort", body),
|
|
@@ -14957,6 +15459,7 @@ const server = createServer(async (req, res) => {
|
|
|
14957
15459
|
if (response.success === false && startsVisibleWork) markTabIdle(tab);
|
|
14958
15460
|
if (response.success !== false && command.type === "new_session") {
|
|
14959
15461
|
tab.conversationStarted = false;
|
|
15462
|
+
resetAutomaticTabTitleForNewSession(tab);
|
|
14960
15463
|
forgetTabState(tab);
|
|
14961
15464
|
rememberTabState(tab, response.data);
|
|
14962
15465
|
clearPendingExtensionUiRequests(tab);
|
|
@@ -15015,6 +15518,7 @@ async function shutdown(signal, { preserveSessions = false, exitCode = 0 } = {})
|
|
|
15015
15518
|
shutdownInProgress = true;
|
|
15016
15519
|
console.log(`\n${signal}: shutting down Pi Web UI...`);
|
|
15017
15520
|
gitLiveWatcher.closeAll();
|
|
15521
|
+
workspaceFilesLiveWatcher.closeAll();
|
|
15018
15522
|
for (const tab of tabs.values()) stopAppRunnerForTab(tab, "server shutdown", { force: true });
|
|
15019
15523
|
|
|
15020
15524
|
const forceExit = setTimeout(() => process.exit(exitCode), 4000);
|