@firstpick/pi-package-webui 0.6.5 → 0.6.7

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/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 } from "node:fs";
4
+ import { 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, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
@@ -21,6 +21,24 @@ import {
21
21
  validateSessionDelete,
22
22
  } from "../lib/session-actions.mjs";
23
23
  import { sweepStaleTempEntries } from "../lib/temp-artifacts.mjs";
24
+ import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
25
+ import {
26
+ GIT_WORKFLOW_DEFAULT_VARIANTS,
27
+ GIT_WORKFLOW_DELIVERY_MODES,
28
+ GIT_WORKFLOW_LANGUAGES,
29
+ GIT_WORKFLOW_SCOPE_POLICIES,
30
+ GIT_WORKFLOW_STAGING_POLICIES,
31
+ GIT_WORKFLOW_THINKING_LEVELS,
32
+ GIT_WORKFLOW_VERIFICATION_POLICIES,
33
+ isGitWorkflowSetupComplete,
34
+ mergeGitWorkflowPreferences,
35
+ readGitWorkflowPreferences,
36
+ readWebuiSettings,
37
+ supportedGitWorkflowThinkingLevels,
38
+ webuiSettingsFile,
39
+ writeGitWorkflowPreferences,
40
+ writeWebuiSettings,
41
+ } from "../lib/git-workflow-preferences.mjs";
24
42
  import {
25
43
  evaluateDispatchTrustGuards,
26
44
  guardsForNativeCommand,
@@ -55,7 +73,6 @@ const publicDir = path.join(packageRoot, "public");
55
73
  const webuiHelperExtensionPath = path.join(packageRoot, "webui-rpc-helper.mjs");
56
74
  const agentDir = process.env.PI_CODING_AGENT_DIR || path.join(homedir(), ".pi", "agent");
57
75
  const OPTIONAL_FEATURE_INSTALL_ROOT_ENV = "PI_WEBUI_OPTIONAL_FEATURE_INSTALL_ROOT";
58
- const WEBUI_SETTINGS_FILE_ENV = "PI_WEBUI_SETTINGS_FILE";
59
76
  const packageJson = JSON.parse(await readFile(path.join(packageRoot, "package.json"), "utf8"));
60
77
  let piPackageJson = {};
61
78
  try {
@@ -75,6 +92,12 @@ const PROMPT_REQUEST_TIMEOUT_MS = Math.max(REQUEST_TIMEOUT_MS, Number.parseInt(p
75
92
  const WEBUI_HELPER_TIMEOUT_MS = 8 * 1000;
76
93
  const WEBUI_HELPER_COMMAND = "webui-helper";
77
94
  const WEBUI_HELPER_RESPONSE_PREFIX = "__PI_WEBUI_HELPER_RESPONSE__:";
95
+ const WEBUI_SUBAGENTS_STATUS_KEY = "webui-subagents";
96
+ const WEBUI_SUBAGENTS_PAYLOAD_PREFIX = "PI_WEBUI_SUBAGENTS_V1 ";
97
+ const WEBUI_SUBAGENT_RUN_LIMIT = 128;
98
+ const WEBUI_SUBAGENT_AGENT_LIMIT = 256;
99
+ const WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT = 120;
100
+ const WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH = 1000;
78
101
  const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
79
102
  const WEBUI_PACKAGE = packageJson.name || "@firstpick/pi-package-webui";
80
103
  const PI_LATEST_VERSION_URL = process.env.PI_WEBUI_PI_LATEST_VERSION_URL || "https://pi.dev/api/latest-version";
@@ -116,7 +139,7 @@ const ATTACHMENT_UPLOAD_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
116
139
  const INLINE_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
117
140
  const INLINE_IMAGE_TOTAL_MAX_BYTES = 16 * 1024 * 1024;
118
141
  const RPC_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
119
- const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
142
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
120
143
  const SETTINGS_TRANSPORT_CHOICES = ["sse", "websocket", "websocket-cached", "auto"];
121
144
  const SETTINGS_HTTP_IDLE_TIMEOUT_CHOICES = [
122
145
  { label: "30 sec", timeoutMs: 30_000 },
@@ -237,6 +260,11 @@ const MIME_TYPES = new Map([
237
260
  [".css", "text/css; charset=utf-8"],
238
261
  [".svg", "image/svg+xml"],
239
262
  [".png", "image/png"],
263
+ [".jpg", "image/jpeg"],
264
+ [".jpeg", "image/jpeg"],
265
+ [".pdf", "application/pdf"],
266
+ [".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
267
+ [".json", "application/json; charset=utf-8"],
240
268
  [".webp", "image/webp"],
241
269
  [".webmanifest", "application/manifest+json; charset=utf-8"],
242
270
  ]);
@@ -448,16 +476,44 @@ function formatUrlHost(host) {
448
476
  return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
449
477
  }
450
478
 
479
+ function makeUserFacingError(message, props = {}) {
480
+ const text = String(message || "Unknown error").trim() || "Unknown error";
481
+ const error = new Error(text);
482
+ error.userMessage = text;
483
+ Object.assign(error, props);
484
+ return error;
485
+ }
486
+
451
487
  function sanitizeError(error) {
452
488
  if (!error) return "Unknown error";
453
489
  if (typeof error === "string") return error;
490
+ if (error.userMessage) return error.userMessage;
454
491
  return error.stack || error.message || String(error);
455
492
  }
456
493
 
457
494
  function formatCliError(error) {
458
495
  if (!error) return "Unknown error";
459
496
  if (typeof error === "string") return error;
460
- return error.message || String(error);
497
+ return error.userMessage || error.message || String(error);
498
+ }
499
+
500
+ function formatCommandSpawnError(command, error) {
501
+ const commandText = String(command || "command");
502
+ const executable = commandText.split(/[\\/]/).pop() || commandText;
503
+ const isGit = /^git(?:\.exe)?$/i.test(executable);
504
+ if (error?.code === "ENOENT") {
505
+ if (isGit) {
506
+ const windowsHint = process.platform === "win32"
507
+ ? " On Windows, install Git for Windows and choose 'Git from the command line and also from 3rd-party software', or add Git's cmd/bin directory to PATH."
508
+ : "";
509
+ return `Git executable not found on PATH (spawn ${executable} ENOENT). Install Git and ensure the 'git' command is available to the Pi Web UI process, then restart Pi Web UI.${windowsHint}`;
510
+ }
511
+ return `${executable} executable not found on PATH (spawn ${executable} ENOENT). Install it or add it to PATH, then restart Pi Web UI.`;
512
+ }
513
+ if (error?.code === "EACCES" || error?.code === "EPERM") {
514
+ return `Cannot start ${executable}: permission denied. Check executable permissions and PATH.`;
515
+ }
516
+ return formatCliError(error);
461
517
  }
462
518
 
463
519
  function delay(ms) {
@@ -960,6 +1016,163 @@ async function sendNativeDownload(res, token, { inline = false } = {}) {
960
1016
  });
961
1017
  }
962
1018
 
1019
+ const documentArtifactTokens = new Map();
1020
+ const DEFAULT_DOCUMENT_ARTIFACT_ROOT = path.join(tmpdir(), "pi-extension-docx");
1021
+ const DOCUMENT_ARTIFACT_MANIFEST_LIMIT_BYTES = 2 * 1024 * 1024;
1022
+ const DOCUMENT_ARTIFACT_PAGE_LIMIT = 10_000;
1023
+
1024
+ function documentArtifactRoots() {
1025
+ return [...new Set([DEFAULT_DOCUMENT_ARTIFACT_ROOT, ...String(process.env.PI_WEBUI_ARTIFACT_ROOTS || "").split(path.delimiter).map((item) => item.trim()).filter(Boolean)].map((item) => path.resolve(item)))];
1026
+ }
1027
+
1028
+ function documentArtifactPath(filePath) {
1029
+ if (typeof filePath !== "string" || !path.isAbsolute(filePath)) throw new Error("artifact path is unavailable");
1030
+ const info = statSync(filePath, { throwIfNoEntry: false });
1031
+ if (!info?.isFile()) throw new Error("artifact file is unavailable");
1032
+ const real = realpathSync(filePath);
1033
+ const root = documentArtifactRoots().map((candidate) => { try { return realpathSync(candidate); } catch { return null; } }).find((candidate) => candidate && (candidate === real || pathInside(candidate, real)));
1034
+ if (!root) throw new Error("artifact path is outside configured roots");
1035
+ return { path: real, root, size: info.size };
1036
+ }
1037
+
1038
+ function pruneDocumentArtifactTokens(now = Date.now()) {
1039
+ for (const [token, item] of documentArtifactTokens) if (!item || item.expiresAt <= now) documentArtifactTokens.delete(token);
1040
+ }
1041
+
1042
+ const PRIVATE_ARTIFACT_KEYS = new Set(["manifestPath", "downloadPath", "outputPath", "sourcePath", "stagedPath", "pdfPath", "workspace", "recoveryPath", "artifactPath", "fullOutputPath"]);
1043
+ function sanitizeArtifactMetadata(value, depth = 0) {
1044
+ if (depth > 20) return "[depth limit]";
1045
+ if (Array.isArray(value)) return value.map((item) => sanitizeArtifactMetadata(item, depth + 1));
1046
+ if (!value || typeof value !== "object") return typeof value === "string" && value.length > 100_000 ? `${value.slice(0, 100_000)}…` : value;
1047
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !PRIVATE_ARTIFACT_KEYS.has(key)).map(([key, item]) => [key, sanitizeArtifactMetadata(item, depth + 1)]));
1048
+ }
1049
+
1050
+ function artifactSessionIdentity(tab) {
1051
+ return normalizedRestoreString(tab?.lastState?.sessionId || tabRestorableSessionFile(tab), 4096) || null;
1052
+ }
1053
+
1054
+ function publicDocumentArtifact(record) {
1055
+ const tabQuery = `tab=${encodeURIComponent(record.tabId)}`;
1056
+ const base = `/api/artifacts/${encodeURIComponent(record.token)}`;
1057
+ return {
1058
+ schema: "pi.artifact/v1",
1059
+ kind: "document",
1060
+ id: record.id,
1061
+ revisionId: record.revisionId,
1062
+ title: record.title,
1063
+ mimeType: record.mimeType,
1064
+ pageCount: record.pageCount,
1065
+ expiresAt: new Date(record.expiresAt).toISOString(),
1066
+ manifestUrl: `${base}/manifest?${tabQuery}`,
1067
+ downloadUrl: record.downloadPath ? `${base}/download?${tabQuery}` : undefined,
1068
+ };
1069
+ }
1070
+
1071
+ function registerDocumentArtifact(tab, artifact) {
1072
+ if (!artifact || artifact.schema !== "pi.artifact/v1" || artifact.kind !== "document" || typeof artifact.id !== "string" || !artifact.id.trim()) throw new Error("invalid pi.artifact/v1 document envelope");
1073
+ pruneDocumentArtifactTokens();
1074
+ const sessionIdentity = artifactSessionIdentity(tab), existing = [...documentArtifactTokens.values()].find((item) => item.tabId === tab.id && item.sessionIdentity === sessionIdentity && item.id === artifact.id && item.revisionId === (artifact.revisionId || undefined));
1075
+ if (existing) return publicDocumentArtifact(existing);
1076
+ const manifestFile = documentArtifactPath(artifact.manifestPath);
1077
+ if (manifestFile.size > DOCUMENT_ARTIFACT_MANIFEST_LIMIT_BYTES) throw new Error("artifact manifest is too large");
1078
+ let manifest;
1079
+ try { manifest = JSON.parse(readFileSync(manifestFile.path, "utf8")); } catch { throw new Error("artifact manifest is malformed"); }
1080
+ const declared = manifest?.artifact;
1081
+ if (declared?.schema !== "pi.artifact/v1" || declared?.kind !== "document" || declared?.id !== artifact.id || (declared?.revisionId || undefined) !== (artifact.revisionId || undefined)) throw new Error("artifact manifest identity mismatch");
1082
+ const downloadPath = artifact.downloadPath ? documentArtifactPath(artifact.downloadPath).path : undefined;
1083
+ const rawPages = Array.isArray(manifest.pages) ? manifest.pages : [];
1084
+ if (rawPages.length > DOCUMENT_ARTIFACT_PAGE_LIMIT) throw new Error("artifact page count exceeds the registry limit");
1085
+ const pages = rawPages.map((page, index) => {
1086
+ const pageNum = Number(page?.pageNum);
1087
+ if (!Number.isInteger(pageNum) || pageNum < 1) throw new Error(`artifact page ${index + 1} is invalid`);
1088
+ const image = documentArtifactPath(page.outputPath);
1089
+ if (MIME_TYPES.get(path.extname(image.path).toLowerCase()) !== "image/png") throw new Error(`artifact page ${pageNum} is not PNG`);
1090
+ return { pageNum, width: Number(page.width) || undefined, height: Number(page.height) || undefined, bytes: image.size, path: image.path };
1091
+ });
1092
+ const declaredExpiry = Date.parse(String(artifact.expiresAt || declared?.expiresAt || "")), now = Date.now();
1093
+ if (!Number.isFinite(declaredExpiry) || declaredExpiry <= now) throw new Error("artifact is expired");
1094
+ const token = randomUUID(), expiresAt = Math.min(declaredExpiry, now + NATIVE_DOWNLOAD_TOKEN_TTL_MS);
1095
+ const record = {
1096
+ token,
1097
+ tabId: tab.id,
1098
+ sessionIdentity,
1099
+ id: artifact.id,
1100
+ revisionId: artifact.revisionId || undefined,
1101
+ title: safeDownloadFileName(artifact.title || declared?.title || "document.docx", "document.docx"),
1102
+ mimeType: String(artifact.mimeType || declared?.mimeType || "application/octet-stream"),
1103
+ pageCount: Number(artifact.pageCount ?? declared?.pageCount ?? pages.length) || pages.length,
1104
+ manifest: {
1105
+ sourceSha256: typeof manifest.sourceSha256 === "string" ? manifest.sourceSha256 : undefined,
1106
+ renderer: manifest.renderer && typeof manifest.renderer === "object" ? sanitizeArtifactMetadata(manifest.renderer) : undefined,
1107
+ warnings: Array.isArray(manifest.warnings) ? sanitizeArtifactMetadata(manifest.warnings.slice(0, 100)) : [],
1108
+ outline: Array.isArray(manifest.outline) ? sanitizeArtifactMetadata(manifest.outline.slice(0, 10_000)) : [],
1109
+ comments: Array.isArray(manifest.comments) ? sanitizeArtifactMetadata(manifest.comments.slice(0, 10_000)) : [],
1110
+ revisions: Array.isArray(manifest.revisions) ? sanitizeArtifactMetadata(manifest.revisions.slice(0, 10_000)) : [],
1111
+ diff: manifest.diff && typeof manifest.diff === "object" ? sanitizeArtifactMetadata(manifest.diff) : undefined,
1112
+ },
1113
+ manifestPath: manifestFile.path,
1114
+ downloadPath,
1115
+ pages,
1116
+ expiresAt,
1117
+ };
1118
+ documentArtifactTokens.set(token, record);
1119
+ return publicDocumentArtifact(record);
1120
+ }
1121
+
1122
+ function rewriteArtifactInResult(tab, result) {
1123
+ if (!result || typeof result !== "object") return result;
1124
+ const details = result.details;
1125
+ if (!details || typeof details !== "object" || details.artifact?.schema !== "pi.artifact/v1") return result;
1126
+ let artifact;
1127
+ try { artifact = registerDocumentArtifact(tab, details.artifact); }
1128
+ catch { artifact = { schema: "pi.artifact/v1", kind: "document", id: String(details.artifact?.id || "unavailable"), title: safeDownloadFileName(details.artifact?.title || "Document"), unavailable: true }; }
1129
+ return { ...result, details: { ...details, artifact } };
1130
+ }
1131
+
1132
+ function rewriteArtifactsForTab(tab, payload) {
1133
+ if (!payload || typeof payload !== "object") return payload;
1134
+ let next = payload;
1135
+ if (payload.result) next = { ...next, result: rewriteArtifactInResult(tab, payload.result) };
1136
+ if (payload.partialResult) next = { ...next, partialResult: rewriteArtifactInResult(tab, payload.partialResult) };
1137
+ if (payload.message?.role === "toolResult") next = { ...next, message: rewriteArtifactInResult(tab, payload.message) };
1138
+ if (Array.isArray(payload.data?.messages)) next = { ...next, data: { ...payload.data, messages: payload.data.messages.map((message) => message?.role === "toolResult" ? rewriteArtifactInResult(tab, message) : message) } };
1139
+ return next;
1140
+ }
1141
+
1142
+ function documentArtifactRecord(req, url, token) {
1143
+ pruneDocumentArtifactTokens();
1144
+ const record = documentArtifactTokens.get(token);
1145
+ if (!record) throw makeHttpError(404, "Artifact token expired or not found");
1146
+ const tab = getRequestedTab(req, url);
1147
+ if (tab.id !== record.tabId || (record.sessionIdentity && artifactSessionIdentity(tab) !== record.sessionIdentity)) throw makeHttpError(404, "Artifact token expired or not found");
1148
+ return record;
1149
+ }
1150
+
1151
+ async function sendDocumentArtifactFile(req, res, filePath, { contentType, fileName, inline = false } = {}) {
1152
+ const resolved = documentArtifactPath(filePath), range = String(req.headers.range || "").trim();
1153
+ let start = 0, end = resolved.size - 1, status = 200;
1154
+ if (range) {
1155
+ const match = range.match(/^bytes=(\d*)-(\d*)$/);
1156
+ if (!match) throw makeHttpError(416, "Unsupported artifact byte range");
1157
+ if (match[1]) start = Number(match[1]);
1158
+ if (match[2]) end = Number(match[2]);
1159
+ if (!match[1] && match[2]) { const suffix = Number(match[2]); start = Math.max(0, resolved.size - suffix); end = resolved.size - 1; }
1160
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || start >= resolved.size) throw makeHttpError(416, "Artifact byte range is unsatisfiable");
1161
+ end = Math.min(end, resolved.size - 1); status = 206;
1162
+ }
1163
+ const headers = {
1164
+ "content-type": contentType || MIME_TYPES.get(path.extname(resolved.path).toLowerCase()) || "application/octet-stream",
1165
+ "content-length": String(Math.max(0, end - start + 1)),
1166
+ "cache-control": "private, no-store",
1167
+ "x-content-type-options": "nosniff",
1168
+ "accept-ranges": "bytes",
1169
+ };
1170
+ if (status === 206) headers["content-range"] = `bytes ${start}-${end}/${resolved.size}`;
1171
+ if (fileName) headers["content-disposition"] = inline ? contentDispositionInline(fileName) : contentDispositionAttachment(fileName);
1172
+ res.writeHead(status, headers);
1173
+ await new Promise((resolve, reject) => { const stream = createReadStream(resolved.path, { start, end }); stream.on("error", reject); res.on("error", reject); res.on("close", resolve); stream.on("end", resolve); stream.pipe(res); });
1174
+ }
1175
+
963
1176
  const ACTION_FEEDBACK_REACTIONS = new Set(["up", "down", "question"]);
964
1177
 
965
1178
  function trimFeedbackField(value, maxLength) {
@@ -1149,7 +1362,10 @@ function runCommand(command, args, { cwd, timeoutMs = 2000, maxOutputLength = 20
1149
1362
  stderr += String(chunk);
1150
1363
  if (stderr.length > maxOutputLength) stderr = stderr.slice(-maxOutputLength);
1151
1364
  });
1152
- child.on("error", (error) => finish({ exitCode: undefined, stdout, stderr: sanitizeError(error), error: sanitizeError(error) }));
1365
+ child.on("error", (error) => {
1366
+ const message = formatCommandSpawnError(command, error);
1367
+ finish({ exitCode: undefined, stdout, stderr: message, error: message, errorCode: error?.code });
1368
+ });
1153
1369
  // "close", not "exit": exit can fire before the stdio pipes flush, which
1154
1370
  // intermittently truncates stdout (empty `git rev-parse --show-toplevel`
1155
1371
  // output resolves to process.cwd() and reads the wrong repository).
@@ -1550,48 +1766,168 @@ async function writePathFastPicks(picks) {
1550
1766
  return normalized;
1551
1767
  }
1552
1768
 
1553
- function webuiSettingsFile() {
1554
- if (process.env[WEBUI_SETTINGS_FILE_ENV]) return path.resolve(expandUserPath(process.env[WEBUI_SETTINGS_FILE_ENV]));
1555
- const configRoot = process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config");
1556
- return path.join(configRoot, "pi-webui", "settings.json");
1769
+ async function readPersistedRemoteAuthEnabled() {
1770
+ return (await readWebuiSettings()).remoteAuthEnabled === true;
1771
+ }
1772
+
1773
+ async function saveRemoteAuthPreference(enabled) {
1774
+ const nextEnabled = enabled === true;
1775
+ await writeWebuiSettings({ remoteAuthEnabled: nextEnabled });
1776
+ persistedRemoteAuthEnabled = nextEnabled;
1777
+ return persistedRemoteAuthEnabled;
1778
+ }
1779
+
1780
+ function gitWorkflowModelKey(model) {
1781
+ return model?.provider && model?.id ? `${model.provider}/${model.id}` : "";
1782
+ }
1783
+
1784
+ async function availableGitWorkflowModels(tab) {
1785
+ const response = await safeRpcData(tab, { type: "get_available_models" });
1786
+ if (!response.ok) throw makeHttpError(400, response.error || "Failed to load available models");
1787
+ return (Array.isArray(response.data?.models) ? response.data.models : [])
1788
+ .filter((model) => model?.provider && model?.id)
1789
+ .sort((left, right) => gitWorkflowModelKey(left).localeCompare(gitWorkflowModelKey(right)));
1557
1790
  }
1558
1791
 
1559
- function normalizeWebuiSettings(value) {
1792
+ function gitWorkflowPreferenceOptions() {
1560
1793
  return {
1561
- version: 1,
1562
- remoteAuthEnabled: value?.remoteAuthEnabled === true,
1794
+ thinkingLevels: GIT_WORKFLOW_THINKING_LEVELS,
1795
+ languages: GIT_WORKFLOW_LANGUAGES,
1796
+ defaultVariants: GIT_WORKFLOW_DEFAULT_VARIANTS,
1797
+ scopePolicies: GIT_WORKFLOW_SCOPE_POLICIES,
1798
+ stagingPolicies: GIT_WORKFLOW_STAGING_POLICIES,
1799
+ deliveryModes: GIT_WORKFLOW_DELIVERY_MODES,
1800
+ verificationPolicies: GIT_WORKFLOW_VERIFICATION_POLICIES,
1563
1801
  };
1564
1802
  }
1565
1803
 
1566
- let webuiSettingsCache = null;
1804
+ async function gitWorkflowPreferencesData(tab) {
1805
+ const [preferences, models] = await Promise.all([
1806
+ readGitWorkflowPreferences(),
1807
+ availableGitWorkflowModels(tab),
1808
+ ]);
1809
+ return {
1810
+ preferences,
1811
+ configured: isGitWorkflowSetupComplete(preferences),
1812
+ models,
1813
+ modelThinkingLevels: Object.fromEntries(models.map((model) => [gitWorkflowModelKey(model), supportedGitWorkflowThinkingLevels(model)])),
1814
+ options: gitWorkflowPreferenceOptions(),
1815
+ path: webuiSettingsFile(),
1816
+ };
1817
+ }
1567
1818
 
1568
- async function readWebuiSettings() {
1569
- if (webuiSettingsCache) return webuiSettingsCache;
1570
- webuiSettingsCache = normalizeWebuiSettings(await readJsonFileIfExists(webuiSettingsFile()));
1571
- return webuiSettingsCache;
1819
+ function requireGitWorkflowChoice(value, key, choices) {
1820
+ const text = String(value ?? "").trim();
1821
+ if (!choices.includes(text)) throw makeHttpError(400, `${key} must be one of: ${choices.join(", ")}`);
1822
+ return text;
1572
1823
  }
1573
1824
 
1574
- async function writeWebuiSettings(patch) {
1575
- const current = await readWebuiSettings();
1576
- const next = normalizeWebuiSettings({ ...current, ...(patch || {}) });
1577
- const storageFile = webuiSettingsFile();
1578
- await mkdir(path.dirname(storageFile), { recursive: true });
1579
- const tmpFile = `${storageFile}.${process.pid}.${Date.now()}.tmp`;
1580
- await writeFile(tmpFile, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
1581
- await rename(tmpFile, storageFile);
1582
- webuiSettingsCache = next;
1583
- return next;
1825
+ async function saveGitWorkflowPreferencesData(tab, body = {}) {
1826
+ const submitted = body.preferences && typeof body.preferences === "object" ? body.preferences : body;
1827
+ if (submitted.generation?.thinkingLevel !== undefined) requireGitWorkflowChoice(submitted.generation.thinkingLevel, "generation.thinkingLevel", GIT_WORKFLOW_THINKING_LEVELS);
1828
+ if (submitted.commit?.language !== undefined) requireGitWorkflowChoice(submitted.commit.language, "commit.language", GIT_WORKFLOW_LANGUAGES);
1829
+ if (submitted.commit?.defaultVariant !== undefined) requireGitWorkflowChoice(submitted.commit.defaultVariant, "commit.defaultVariant", GIT_WORKFLOW_DEFAULT_VARIANTS);
1830
+ if (submitted.commit?.scope !== undefined) requireGitWorkflowChoice(submitted.commit.scope, "commit.scope", GIT_WORKFLOW_SCOPE_POLICIES);
1831
+ if (submitted.stagingPolicy !== undefined) requireGitWorkflowChoice(submitted.stagingPolicy, "stagingPolicy", GIT_WORKFLOW_STAGING_POLICIES);
1832
+ if (submitted.deliveryMode !== undefined) requireGitWorkflowChoice(submitted.deliveryMode, "deliveryMode", GIT_WORKFLOW_DELIVERY_MODES);
1833
+ if (submitted.verificationPolicy !== undefined) requireGitWorkflowChoice(submitted.verificationPolicy, "verificationPolicy", GIT_WORKFLOW_VERIFICATION_POLICIES);
1834
+
1835
+ const current = await readGitWorkflowPreferences();
1836
+ const next = mergeGitWorkflowPreferences(current, submitted);
1837
+ const provider = String(next.generation.provider || "").trim();
1838
+ const modelId = String(next.generation.modelId || "").trim();
1839
+ if (!provider || !modelId) throw makeHttpError(400, "Select a Git-writing model before saving setup");
1840
+
1841
+ const models = await availableGitWorkflowModels(tab);
1842
+ const model = models.find((candidate) => candidate.provider === provider && candidate.id === modelId);
1843
+ if (!model) throw makeHttpError(400, `Selected model is not currently available: ${provider}/${modelId}`);
1844
+ const supportedLevels = supportedGitWorkflowThinkingLevels(model);
1845
+ if (!supportedLevels.includes(next.generation.thinkingLevel)) {
1846
+ throw makeHttpError(400, `${provider}/${modelId} does not support thinking level ${next.generation.thinkingLevel}`);
1847
+ }
1848
+
1849
+ await writeGitWorkflowPreferences(next);
1850
+ return gitWorkflowPreferencesData(tab);
1584
1851
  }
1585
1852
 
1586
- async function readPersistedRemoteAuthEnabled() {
1587
- return (await readWebuiSettings()).remoteAuthEnabled === true;
1853
+ function gitWorkflowGenerationPrompt(kind, preferences) {
1854
+ switch (kind) {
1855
+ case "commit":
1856
+ return `/git-staged-msg ${preferences.commit.language} ${preferences.commit.scope}`;
1857
+ case "branch":
1858
+ return "/git-branch-name";
1859
+ case "pr":
1860
+ return `/pr ${preferences.commit.language}`;
1861
+ default:
1862
+ throw makeHttpError(400, "generation kind must be commit, branch, or pr");
1863
+ }
1588
1864
  }
1589
1865
 
1590
- async function saveRemoteAuthPreference(enabled) {
1591
- const nextEnabled = enabled === true;
1592
- await writeWebuiSettings({ remoteAuthEnabled: nextEnabled });
1593
- persistedRemoteAuthEnabled = nextEnabled;
1594
- return persistedRemoteAuthEnabled;
1866
+ async function restoreGitWorkflowGenerationProfile(tab) {
1867
+ const restore = tab?.gitWorkflowGenerationRestore;
1868
+ if (!restore) return;
1869
+ tab.gitWorkflowGenerationRestore = null;
1870
+ try {
1871
+ if (!tab.rpc?.isRunning?.()) return;
1872
+ if (restore.model?.provider && restore.model?.id) {
1873
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider: restore.model.provider, modelId: restore.model.id });
1874
+ if (modelResponse.success === false) throw new Error(modelResponse.error || "Failed to restore model");
1875
+ }
1876
+ if (restore.thinkingLevel) {
1877
+ const thinkingResponse = await setThinkingLevelForTab(tab, restore.thinkingLevel, { allowPending: false });
1878
+ if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || "Failed to restore thinking level");
1879
+ }
1880
+ recordEvent({ type: "git_workflow_generation_profile_restored", tabId: tab.id, tabTitle: tab.title });
1881
+ } catch (error) {
1882
+ recordEvent({ type: "git_workflow_generation_profile_restore_failed", tabId: tab.id, tabTitle: tab.title, error: sanitizeError(error) });
1883
+ }
1884
+ }
1885
+
1886
+ async function startGitWorkflowGeneration(tab, body = {}) {
1887
+ if (tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
1888
+ const preferences = await readGitWorkflowPreferences();
1889
+ if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
1890
+
1891
+ const state = await currentSessionState(tab);
1892
+ if (stateIsBusyForSettings(state)) throw makeHttpError(409, "Wait for the current agent run to finish before generating Git text");
1893
+ const models = await availableGitWorkflowModels(tab);
1894
+ const selectedModel = models.find((model) => model.provider === preferences.generation.provider && model.id === preferences.generation.modelId);
1895
+ if (!selectedModel) throw makeHttpError(409, `Configured Git-writing model is unavailable: ${preferences.generation.provider}/${preferences.generation.modelId}. Open Guided Git Setup to choose another model.`);
1896
+ const supportedLevels = supportedGitWorkflowThinkingLevels(selectedModel);
1897
+ if (!supportedLevels.includes(preferences.generation.thinkingLevel)) {
1898
+ throw makeHttpError(409, `Configured thinking level ${preferences.generation.thinkingLevel} is unavailable for ${gitWorkflowModelKey(selectedModel)}. Open Guided Git Setup to update it.`);
1899
+ }
1900
+
1901
+ const restore = { model: state.model || null, thinkingLevel: state.thinkingLevel || "off" };
1902
+ tab.gitWorkflowGenerationRestore = restore;
1903
+ try {
1904
+ if (gitWorkflowModelKey(state.model) !== gitWorkflowModelKey(selectedModel)) {
1905
+ const modelResponse = await tab.rpc.send({ type: "set_model", provider: selectedModel.provider, modelId: selectedModel.id });
1906
+ if (modelResponse.success === false) throw new Error(modelResponse.error || `Failed to select ${gitWorkflowModelKey(selectedModel)}`);
1907
+ }
1908
+ const thinkingResponse = await setThinkingLevelForTab(tab, preferences.generation.thinkingLevel, { allowPending: false });
1909
+ if (thinkingResponse.success === false) throw new Error(thinkingResponse.error || `Failed to select thinking level ${preferences.generation.thinkingLevel}`);
1910
+
1911
+ const kind = String(body.kind || "").trim();
1912
+ const message = gitWorkflowGenerationPrompt(kind, preferences);
1913
+ markTabWorking(tab);
1914
+ const response = await tab.rpc.send({ type: "prompt", message });
1915
+ if (response.success === false) throw new Error(response.error || "Guided Git generation prompt was rejected");
1916
+ return {
1917
+ accepted: true,
1918
+ kind,
1919
+ message,
1920
+ generation: {
1921
+ provider: selectedModel.provider,
1922
+ modelId: selectedModel.id,
1923
+ thinkingLevel: preferences.generation.thinkingLevel,
1924
+ },
1925
+ };
1926
+ } catch (error) {
1927
+ markTabIdle(tab);
1928
+ await restoreGitWorkflowGenerationProfile(tab);
1929
+ throw error;
1930
+ }
1595
1931
  }
1596
1932
 
1597
1933
  function parseCliScopedModelPatterns() {
@@ -3957,7 +4293,7 @@ const GIT_STATUS_KIND_RANK = Object.freeze({ changed: 0, untracked: 1, modified:
3957
4293
  async function getGitRoot(cwd) {
3958
4294
  const result = await runCommand("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 2000 });
3959
4295
  if (result.exitCode !== 0) {
3960
- throw new Error((result.stderr || result.stdout || "Not inside a git repository").trim());
4296
+ throw makeUserFacingError((result.stderr || result.stdout || "Not inside a git repository").trim());
3961
4297
  }
3962
4298
  return path.resolve(result.stdout.trim());
3963
4299
  }
@@ -3971,7 +4307,7 @@ async function runGitReadCommandDetailed(root, args, { timeoutMs = GIT_CHANGES_C
3971
4307
  const message = result.timedOut
3972
4308
  ? `${command} timed out`
3973
4309
  : (result.stderr || result.stdout || result.error || `${command} failed with exit code ${result.exitCode ?? "unknown"}`);
3974
- throw new Error(String(message).trim());
4310
+ throw makeUserFacingError(String(message).trim());
3975
4311
  }
3976
4312
 
3977
4313
  async function runGitReadCommand(root, args, options = {}) {
@@ -5673,7 +6009,10 @@ function runWorkflowCommand(command, args, { cwd, label = formatWorkflowCommand(
5673
6009
  stderr += String(chunk);
5674
6010
  if (stderr.length > 100000) stderr = stderr.slice(-100000);
5675
6011
  });
5676
- child.on("error", (error) => finish({ exitCode: undefined, stderr: stderr || sanitizeError(error), error: sanitizeError(error) }));
6012
+ child.on("error", (error) => {
6013
+ const message = formatCommandSpawnError(command, error);
6014
+ finish({ exitCode: undefined, stderr: stderr || message, error: message, errorCode: error?.code });
6015
+ });
5677
6016
  // "close", not "exit": exit can fire before the stdio pipes flush,
5678
6017
  // intermittently truncating collected stdout/stderr.
5679
6018
  child.on("close", (exitCode, signal) => finish({ exitCode, signal }));
@@ -6543,7 +6882,7 @@ function responseWithPendingThinking(tab, response) {
6543
6882
 
6544
6883
  function eventForTabClients(tab, event) {
6545
6884
  return {
6546
- ...responseWithPendingThinking(tab, event),
6885
+ ...rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, event)),
6547
6886
  tabId: tab.id,
6548
6887
  tabTitle: tab.title,
6549
6888
  tabActivity: tabActivitySnapshot(tab),
@@ -6627,6 +6966,71 @@ function clearExtensionWidgets(tab) {
6627
6966
  tab?.extensionWidgets?.clear();
6628
6967
  }
6629
6968
 
6969
+ function clearWebuiSubagents(tab) {
6970
+ if (tab) tab.webuiSubagents = null;
6971
+ }
6972
+
6973
+ function normalizeWebuiSubagentText(value, maxLength = 240) {
6974
+ const text = String(value || "").trim();
6975
+ return text ? text.slice(0, maxLength) : "";
6976
+ }
6977
+
6978
+ function normalizeWebuiSubagentPayload(value) {
6979
+ if (!value || typeof value !== "object" || value.version !== 1) return null;
6980
+ const runs = [];
6981
+ for (const rawRun of Array.isArray(value.runs) ? value.runs.slice(0, WEBUI_SUBAGENT_RUN_LIMIT) : []) {
6982
+ if (!rawRun || typeof rawRun !== "object") continue;
6983
+ const id = normalizeWebuiSubagentText(rawRun.id, 160);
6984
+ if (!id) continue;
6985
+ const agents = [];
6986
+ for (const rawAgent of Array.isArray(rawRun.agents) ? rawRun.agents.slice(0, WEBUI_SUBAGENT_AGENT_LIMIT) : []) {
6987
+ const name = normalizeWebuiSubagentText(rawAgent?.name, 160);
6988
+ if (!name || rawAgent?.status !== "running") continue;
6989
+ agents.push({
6990
+ id: normalizeWebuiSubagentText(rawAgent.id || `${id}:${agents.length}`, 240),
6991
+ name,
6992
+ status: "running",
6993
+ index: Number.isInteger(rawAgent.index) ? rawAgent.index : agents.length,
6994
+ currentTool: normalizeWebuiSubagentText(rawAgent.currentTool, 120) || undefined,
6995
+ activityState: normalizeWebuiSubagentText(rawAgent.activityState, 80) || undefined,
6996
+ nested: rawAgent.nested === true,
6997
+ });
6998
+ }
6999
+ if (!agents.length) continue;
7000
+ runs.push({
7001
+ id,
7002
+ source: rawRun.source === "foreground" ? "foreground" : "async",
7003
+ mode: ["single", "parallel", "chain"].includes(rawRun.mode) ? rawRun.mode : "single",
7004
+ status: "running",
7005
+ startedAt: Number.isFinite(rawRun.startedAt) ? rawRun.startedAt : Date.now(),
7006
+ agents: agents.sort((a, b) => a.index - b.index || a.name.localeCompare(b.name)),
7007
+ });
7008
+ }
7009
+ return {
7010
+ version: 1,
7011
+ available: value.available === true,
7012
+ updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
7013
+ receivedAt: Date.now(),
7014
+ runs: runs.sort((a, b) => a.startedAt - b.startedAt || a.id.localeCompare(b.id)),
7015
+ };
7016
+ }
7017
+
7018
+ function rememberWebuiSubagentsStatusEvent(tab, event) {
7019
+ if (event?.type !== "extension_ui_request" || event.method !== "setStatus" || event.statusKey !== WEBUI_SUBAGENTS_STATUS_KEY) return false;
7020
+ const statusText = String(event.statusText || "");
7021
+ if (!statusText) {
7022
+ clearWebuiSubagents(tab);
7023
+ return true;
7024
+ }
7025
+ if (!statusText.startsWith(WEBUI_SUBAGENTS_PAYLOAD_PREFIX)) return true;
7026
+ try {
7027
+ tab.webuiSubagents = normalizeWebuiSubagentPayload(JSON.parse(statusText.slice(WEBUI_SUBAGENTS_PAYLOAD_PREFIX.length)));
7028
+ } catch {
7029
+ tab.webuiSubagents = null;
7030
+ }
7031
+ return true;
7032
+ }
7033
+
6630
7034
  function naturalConversationStatusState(statusText) {
6631
7035
  const text = stripAnsi(statusText).replace(/\s+/g, " ").trim();
6632
7036
  if (!text) return { enabled: false, uiState: "off", statusText: "" };
@@ -7207,13 +7611,15 @@ function attachRpcToTab(tab, rpc) {
7207
7611
  tab.rpcUnsubscribe?.();
7208
7612
  tab.rpc = rpc;
7209
7613
  tab.rpcUnsubscribe = rpc.onEvent((event) => {
7210
- if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event)) return;
7614
+ if (resolveWebuiHelperResponse(tab, event) || resolveWebuiHelperRpcResponse(tab, event) || rememberWebuiSubagentsStatusEvent(tab, event)) return;
7211
7615
  updateTabActivityFromEvent(tab, event);
7212
7616
  let scopedEvent = eventForTabClients(tab, event);
7213
7617
  if (event?.type === "pi_process_exit" || event?.type === "pi_process_error") {
7618
+ tab.gitWorkflowGenerationRestore = null;
7214
7619
  clearPendingExtensionUiRequests(tab);
7215
7620
  clearExtensionStatuses(tab);
7216
7621
  clearExtensionWidgets(tab);
7622
+ clearWebuiSubagents(tab);
7217
7623
  resetNaturalConversationMode(tab);
7218
7624
  } else {
7219
7625
  rememberExtensionStatusEvent(tab, scopedEvent);
@@ -7225,6 +7631,7 @@ function attachRpcToTab(tab, rpc) {
7225
7631
  recordEvent(scopedEvent);
7226
7632
  for (const client of tab.sseClients) sendSse(client, scopedEvent);
7227
7633
  if (event?.type === "compaction_end" && event.aborted !== true) void flushCompactionQueue(tab, event);
7634
+ if (event?.type === "agent_settled") void restoreGitWorkflowGenerationProfile(tab);
7228
7635
  });
7229
7636
  }
7230
7637
 
@@ -7254,10 +7661,12 @@ async function createTab({ id: requestedId, index, title, titleSource, conversat
7254
7661
  gitWorkspace: gitWorkspace || null,
7255
7662
  lastState: null,
7256
7663
  pendingThinkingLevel: undefined,
7664
+ gitWorkflowGenerationRestore: null,
7257
7665
  activity: createTabActivity(createdAt),
7258
7666
  pendingExtensionUiRequests: new Map(),
7259
7667
  extensionStatuses: new Map(),
7260
7668
  extensionWidgets: new Map(),
7669
+ webuiSubagents: null,
7261
7670
  webuiHelperRequests: new Map(),
7262
7671
  webuiHelperResponseIds: new Set(),
7263
7672
  bashQueue: [],
@@ -7320,6 +7729,84 @@ function listTabs() {
7320
7729
  return [...tabs.values()].map(tabMeta);
7321
7730
  }
7322
7731
 
7732
+ function webuiSubagentsData() {
7733
+ const sortedTabs = [...tabs.values()].sort((a, b) => a.index - b.index || a.title.localeCompare(b.title));
7734
+ const tabSummaries = sortedTabs.map((tab) => {
7735
+ const status = tab.webuiSubagents || { version: 1, available: false, updatedAt: null, receivedAt: null, runs: [] };
7736
+ const runs = Array.isArray(status.runs) ? status.runs : [];
7737
+ return {
7738
+ tabId: tab.id,
7739
+ tabIndex: tab.index,
7740
+ tabTitle: tab.title,
7741
+ cwd: tab.cwd,
7742
+ sessionName: normalizeWebuiSubagentText(tab.lastState?.sessionName || tab.title, 160),
7743
+ sessionFile: tabRestorableSessionFile(tab) || null,
7744
+ running: tab.rpc.isRunning(),
7745
+ available: status.available === true,
7746
+ updatedAt: status.updatedAt || null,
7747
+ receivedAt: status.receivedAt || null,
7748
+ runs,
7749
+ agentCount: runs.reduce((count, run) => count + run.agents.length, 0),
7750
+ };
7751
+ });
7752
+ return {
7753
+ version: 1,
7754
+ updatedAt: Date.now(),
7755
+ available: tabSummaries.some((tab) => tab.available),
7756
+ totalRuns: tabSummaries.reduce((count, tab) => count + tab.runs.length, 0),
7757
+ totalAgents: tabSummaries.reduce((count, tab) => count + tab.agentCount, 0),
7758
+ tabs: tabSummaries,
7759
+ };
7760
+ }
7761
+
7762
+ function normalizeWebuiSubagentOutput(value, selection) {
7763
+ if (!value || typeof value !== "object" || value.version !== 1) throw makeHttpError(502, "Invalid subagent output response from Web UI helper");
7764
+ const rawAgent = value.agent && typeof value.agent === "object" ? value.agent : {};
7765
+ const recentOutput = (Array.isArray(rawAgent.recentOutput) ? rawAgent.recentOutput : [])
7766
+ .slice(-WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT)
7767
+ .map((line) => String(line ?? "").replace(/\r/g, "").slice(0, WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH));
7768
+ const recentTools = (Array.isArray(rawAgent.recentTools) ? rawAgent.recentTools : []).slice(-20).map((entry) => ({
7769
+ tool: normalizeWebuiSubagentText(entry?.tool, 120),
7770
+ args: normalizeWebuiSubagentText(entry?.args, 500),
7771
+ endMs: Number.isFinite(entry?.endMs) ? entry.endMs : undefined,
7772
+ })).filter((entry) => entry.tool);
7773
+ return {
7774
+ version: 1,
7775
+ runId: normalizeWebuiSubagentText(value.runId, 160) || selection.run.id,
7776
+ source: value.source === "foreground" ? "foreground" : "async",
7777
+ mode: ["single", "parallel", "chain"].includes(value.mode) ? value.mode : selection.run.mode,
7778
+ startedAt: Number.isFinite(value.startedAt) ? value.startedAt : selection.run.startedAt,
7779
+ updatedAt: Number.isFinite(value.updatedAt) ? value.updatedAt : Date.now(),
7780
+ agent: {
7781
+ id: selection.agent.id,
7782
+ name: normalizeWebuiSubagentText(rawAgent.name, 160) || selection.agent.name,
7783
+ index: Number.isInteger(rawAgent.index) ? rawAgent.index : selection.agent.index,
7784
+ nested: rawAgent.nested === true,
7785
+ status: normalizeWebuiSubagentText(rawAgent.status, 40) || "running",
7786
+ activityState: normalizeWebuiSubagentText(rawAgent.activityState, 80) || undefined,
7787
+ currentTool: normalizeWebuiSubagentText(rawAgent.currentTool, 120) || undefined,
7788
+ currentToolArgs: normalizeWebuiSubagentText(rawAgent.currentToolArgs, 500) || undefined,
7789
+ currentPath: normalizeWebuiSubagentText(rawAgent.currentPath, 1000) || undefined,
7790
+ turnCount: Number.isFinite(rawAgent.turnCount) ? rawAgent.turnCount : undefined,
7791
+ toolCount: Number.isFinite(rawAgent.toolCount) ? rawAgent.toolCount : undefined,
7792
+ tokens: Number.isFinite(rawAgent.tokens) ? rawAgent.tokens : undefined,
7793
+ recentTools,
7794
+ recentOutput,
7795
+ error: normalizeWebuiSubagentText(rawAgent.error, 1000) || undefined,
7796
+ },
7797
+ };
7798
+ }
7799
+
7800
+ async function webuiSubagentOutputData(tab, runId, agentId) {
7801
+ const runs = Array.isArray(tab.webuiSubagents?.runs) ? tab.webuiSubagents.runs : [];
7802
+ const run = runs.find((candidate) => candidate.id === runId);
7803
+ if (!run) throw makeHttpError(404, `Running subagent run not found: ${runId}`);
7804
+ const agent = (Array.isArray(run.agents) ? run.agents : []).find((candidate) => candidate.id === agentId);
7805
+ if (!agent) throw makeHttpError(404, `Running subagent not found: ${agentId}`);
7806
+ const data = await sendWebuiHelperCommand(tab, "subagent-output", { runId, agentId });
7807
+ return normalizeWebuiSubagentOutput(data, { run, agent });
7808
+ }
7809
+
7323
7810
  function restorableTabDescriptor(tab, state = null) {
7324
7811
  return normalizeRestoreTabDescriptor({
7325
7812
  id: tab.id,
@@ -7488,35 +7975,59 @@ async function getUpdateStatus({ force = false } = {}) {
7488
7975
  checkedAt: new Date(now).toISOString(),
7489
7976
  updateAvailable,
7490
7977
  restartRequired: true,
7491
- command: "pi update",
7492
- allCommand: "pi update --all",
7978
+ command: piUpdateCommandText(),
7979
+ allCommand: piUpdateCommandText({ all: true, supportsAll: true }),
7980
+ allFallbackCommand: piUpdateCommandText({ all: true }),
7493
7981
  webuiDev: webuiDevServer,
7494
7982
  pi: piStatus,
7495
7983
  webui: webuiStatus,
7496
7984
  packages: {
7497
7985
  checked: false,
7498
- note: "Default update runs pi update for Pi only. Use update all to run pi update --all for Pi and configured packages."
7986
+ note: "Update all checks whether the selected Pi executable supports pi update --all. If not, it falls back to pi update --self followed by pi update --extensions."
7499
7987
  },
7500
7988
  };
7501
7989
  updateStatusCacheAt = now;
7502
7990
  return updateStatusCache;
7503
7991
  }
7504
7992
 
7505
- async function resolvePiUpdateCommand({ all = false } = {}) {
7506
- const updateArgs = all ? ["update", "--all"] : ["update"];
7507
- const label = all ? "Pi CLI and configured packages" : "Pi CLI";
7508
- if (options.piBinExplicit) {
7509
- const command = await resolvePiCommand(updateArgs);
7510
- return { ...command, label, timeoutMs: PI_UPDATE_TIMEOUT_MS, maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS };
7511
- }
7993
+ async function piUpdateCommandSupportsAll(command) {
7994
+ const result = await runCommand(command.command, command.args || [], {
7995
+ cwd: process.cwd(),
7996
+ timeoutMs: 5000,
7997
+ maxOutputLength: 20_000,
7998
+ });
7999
+ if (result.exitCode !== 0 || result.timedOut || result.error) return false;
8000
+ return piUpdateHelpSupportsAll(`${result.stdout}\n${result.stderr}`);
8001
+ }
8002
+
8003
+ async function resolvePiUpdateCommands({ all = false } = {}) {
8004
+ let resolveCommand;
8005
+ let labelPrefix = "";
7512
8006
 
7513
- const pathPi = await runCommand(options.piBin, ["--version"], { timeoutMs: 3000, maxOutputLength: 4000 });
7514
- if (pathPi.exitCode === 0 && !pathPi.timedOut && !pathPi.error) {
7515
- return { label, command: options.piBin, args: updateArgs, displayCommand: formatCommandForDisplay(options.piBin, updateArgs), timeoutMs: PI_UPDATE_TIMEOUT_MS, maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS };
8007
+ if (options.piBinExplicit) {
8008
+ resolveCommand = (args) => resolvePiCommand(args);
8009
+ } else {
8010
+ const pathPi = await runCommand(options.piBin, ["--version"], { timeoutMs: 3000, maxOutputLength: 4000 });
8011
+ if (pathPi.exitCode === 0 && !pathPi.timedOut && !pathPi.error) {
8012
+ resolveCommand = async (args) => ({
8013
+ command: options.piBin,
8014
+ args,
8015
+ displayCommand: formatCommandForDisplay(options.piBin, args),
8016
+ });
8017
+ } else {
8018
+ resolveCommand = (args) => resolvePiCommand(args);
8019
+ labelPrefix = "bundled ";
8020
+ }
7516
8021
  }
7517
8022
 
7518
- const fallback = await resolvePiCommand(updateArgs);
7519
- return { ...fallback, label: `bundled ${label}`, timeoutMs: PI_UPDATE_TIMEOUT_MS, maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS };
8023
+ const supportsAll = all && await piUpdateCommandSupportsAll(await resolveCommand(["update", "--help"]));
8024
+ const steps = piUpdateCommandSteps({ all, supportsAll });
8025
+ return Promise.all(steps.map(async (step) => ({
8026
+ ...(await resolveCommand(step.args)),
8027
+ label: `${labelPrefix}${step.label}`,
8028
+ timeoutMs: PI_UPDATE_TIMEOUT_MS,
8029
+ maxOutputLength: PI_UPDATE_OUTPUT_MAX_CHARS,
8030
+ })));
7520
8031
  }
7521
8032
 
7522
8033
  function packageNodeModulesPath(nodeModulesRoot, packageName) {
@@ -7722,8 +8233,8 @@ function uniqueUpdateTasks(tasks) {
7722
8233
  }
7723
8234
 
7724
8235
  async function resolveUpdateTasks({ all = false } = {}) {
7725
- const piTask = await resolvePiUpdateCommand({ all });
7726
- if (!all) return uniqueUpdateTasks([piTask]);
8236
+ const piTasks = await resolvePiUpdateCommands({ all });
8237
+ if (!all) return uniqueUpdateTasks(piTasks);
7727
8238
 
7728
8239
  const [
7729
8240
  currentWebuiTask,
@@ -7742,7 +8253,7 @@ async function resolveUpdateTasks({ all = false } = {}) {
7742
8253
  ]);
7743
8254
 
7744
8255
  return uniqueUpdateTasks([
7745
- piTask,
8256
+ ...piTasks,
7746
8257
  currentWebuiTask,
7747
8258
  agentTask,
7748
8259
  optionalFeatureTask,
@@ -7909,6 +8420,7 @@ async function updateTabCwd(id, cwd) {
7909
8420
  clearPendingExtensionUiRequests(tab);
7910
8421
  clearExtensionStatuses(tab);
7911
8422
  clearExtensionWidgets(tab);
8423
+ clearWebuiSubagents(tab);
7912
8424
  resetNaturalConversationMode(tab);
7913
8425
  const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
7914
8426
  attachRpcToTab(tab, rpc);
@@ -7948,6 +8460,7 @@ async function restartTabRpc(tab, reason = "reload") {
7948
8460
  clearPendingExtensionUiRequests(tab);
7949
8461
  clearExtensionStatuses(tab);
7950
8462
  clearExtensionWidgets(tab);
8463
+ clearWebuiSubagents(tab);
7951
8464
  resetNaturalConversationMode(tab);
7952
8465
  const rpc = new PiRpcProcess({ ...piCommand, cwd: tab.cwd });
7953
8466
  attachRpcToTab(tab, rpc);
@@ -8002,7 +8515,7 @@ function fallbackRpcResponse(tab, command, error) {
8002
8515
 
8003
8516
  async function safeRpcResponse(tab, command, timeoutMs = REQUEST_TIMEOUT_MS) {
8004
8517
  try {
8005
- return responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs));
8518
+ return rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs)));
8006
8519
  } catch (error) {
8007
8520
  const message = sanitizeError(error);
8008
8521
  if (/Pi RPC process is not running/i.test(message)) return responseWithPendingThinking(tab, fallbackRpcResponse(tab, command, error));
@@ -9877,6 +10390,7 @@ async function handleNativeSlashCommand(tab, body, req) {
9877
10390
  clearPendingExtensionUiRequests(tab);
9878
10391
  clearExtensionStatuses(tab);
9879
10392
  clearExtensionWidgets(tab);
10393
+ clearWebuiSubagents(tab);
9880
10394
  resetNaturalConversationMode(tab);
9881
10395
  return respondNative("new", {
9882
10396
  status: "succeeded",
@@ -10471,6 +10985,20 @@ const server = createServer(async (req, res) => {
10471
10985
  return;
10472
10986
  }
10473
10987
 
10988
+ if (url.pathname === "/api/subagents" && req.method === "GET") {
10989
+ sendJson(res, 200, { ok: true, data: webuiSubagentsData() });
10990
+ return;
10991
+ }
10992
+
10993
+ if (url.pathname === "/api/subagents/output" && req.method === "GET") {
10994
+ const tab = getRequestedTab(req, url);
10995
+ const runId = normalizeWebuiSubagentText(url.searchParams.get("run"), 160);
10996
+ const agentId = normalizeWebuiSubagentText(url.searchParams.get("agent"), 240);
10997
+ if (!runId || !agentId) throw makeHttpError(400, "run and agent query parameters are required");
10998
+ sendJson(res, 200, { ok: true, data: await webuiSubagentOutputData(tab, runId, agentId) });
10999
+ return;
11000
+ }
11001
+
10474
11002
  if (url.pathname === "/api/tabs" && req.method === "POST") {
10475
11003
  const body = await readJsonBody(req);
10476
11004
  const tab = await createTab({ title: body.title, cwd: body.cwd });
@@ -10573,6 +11101,24 @@ const server = createServer(async (req, res) => {
10573
11101
  return;
10574
11102
  }
10575
11103
 
11104
+ const artifactRoute = url.pathname.match(/^\/api\/artifacts\/([^/]+)\/(manifest|download|page\/(\d+))$/);
11105
+ if (artifactRoute && req.method === "GET") {
11106
+ const token = decodeURIComponent(artifactRoute[1]), record = documentArtifactRecord(req, url, token), tabQuery = `tab=${encodeURIComponent(record.tabId)}`;
11107
+ if (artifactRoute[2] === "manifest") {
11108
+ sendJson(res, 200, { ok: true, data: { artifact: publicDocumentArtifact(record), ...record.manifest, pages: record.pages.map(({ path: _path, ...page }) => ({ ...page, imageUrl: `/api/artifacts/${encodeURIComponent(token)}/page/${page.pageNum}?${tabQuery}` })) } }, { "cache-control": "private, no-store" });
11109
+ return;
11110
+ }
11111
+ if (artifactRoute[2] === "download") {
11112
+ if (!record.downloadPath) throw makeHttpError(404, "Artifact download is unavailable");
11113
+ await sendDocumentArtifactFile(req, res, record.downloadPath, { contentType: record.mimeType, fileName: record.title });
11114
+ return;
11115
+ }
11116
+ const pageNum = Number(artifactRoute[3]), page = record.pages.find((item) => item.pageNum === pageNum);
11117
+ if (!page) throw makeHttpError(404, "Artifact page is unavailable");
11118
+ await sendDocumentArtifactFile(req, res, page.path, { contentType: "image/png", fileName: `page-${pageNum}.png`, inline: true });
11119
+ return;
11120
+ }
11121
+
10576
11122
  if (url.pathname.startsWith("/api/native-download/") && req.method === "GET") {
10577
11123
  await sendNativeDownload(res, decodeURIComponent(url.pathname.slice("/api/native-download/".length)), {
10578
11124
  inline: url.searchParams.get("disposition") === "inline",
@@ -11070,6 +11616,28 @@ const server = createServer(async (req, res) => {
11070
11616
  return;
11071
11617
  }
11072
11618
 
11619
+ if (url.pathname === "/api/git-workflow/preferences" && req.method === "GET") {
11620
+ const tab = getRequestedTab(req, url);
11621
+ sendJson(res, 200, { ok: true, data: await gitWorkflowPreferencesData(tab) });
11622
+ return;
11623
+ }
11624
+
11625
+ if (url.pathname === "/api/git-workflow/preferences" && req.method === "POST") {
11626
+ const body = await readJsonBody(req);
11627
+ const tab = getRequestedTab(req, url, body);
11628
+ ensureNaturalConversationRouteAllowed(tab, "guided Git setup changes are blocked");
11629
+ sendJson(res, 200, { ok: true, data: await saveGitWorkflowPreferencesData(tab, body) });
11630
+ return;
11631
+ }
11632
+
11633
+ if (url.pathname === "/api/git-workflow/generate" && req.method === "POST") {
11634
+ const body = await readJsonBody(req);
11635
+ const tab = getRequestedTab(req, url, body);
11636
+ ensureNaturalConversationRouteAllowed(tab, "guided Git generation is blocked");
11637
+ sendJson(res, 200, { ok: true, data: await startGitWorkflowGeneration(tab, body) });
11638
+ return;
11639
+ }
11640
+
11073
11641
  if (url.pathname === "/api/settings" && req.method === "GET") {
11074
11642
  const tab = getRequestedTab(req, url);
11075
11643
  sendJson(res, 200, { ok: true, data: nativeSettingsPayload(settingsManagerForTab(tab)) });
@@ -11406,6 +11974,7 @@ const server = createServer(async (req, res) => {
11406
11974
  clearPendingExtensionUiRequests(tab);
11407
11975
  clearExtensionStatuses(tab);
11408
11976
  clearExtensionWidgets(tab);
11977
+ clearWebuiSubagents(tab);
11409
11978
  resetNaturalConversationMode(tab);
11410
11979
  }
11411
11980
  sendJson(res, response.success === false ? 400 : 200, responseWithTab(response, tab));