@firstpick/pi-package-webui 0.6.6 → 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/README.md +2 -2
- package/bin/pi-webui.mjs +226 -21
- package/lib/update-commands.mjs +20 -0
- package/package.json +2 -2
- package/public/app.js +88 -15
- package/public/styles.css +59 -0
- package/tests/document-artifact-static.test.mjs +18 -0
- package/tests/fixtures/fake-pi.mjs +12 -0
- package/tests/http-endpoints-harness.test.mjs +34 -0
- package/tests/mobile-static.test.mjs +13 -7
- package/tests/update-commands.test.mjs +44 -0
package/README.md
CHANGED
|
@@ -159,7 +159,7 @@ Optional Natural Conversation server-side voice fallback variables:
|
|
|
159
159
|
- Detected app runner dropdown for the active tab cwd, including Cargo, Bun, npm/npx/pnpm, Python/uv, Go/Golang, Zig, C/C++, Docker Compose, root/dev/scripts shell scripts, and other common project runners with live output pinned at the top of the terminal. Running app runners expose line-oriented stdin in the widget for interactive scripts. Projects can add browseable custom runners in `.pi-webui-runners.json` with a command (default `./`) plus a relative path to the file to run.
|
|
160
160
|
- Guided Git workflow for existing repos and new repos with persistent model/reasoning preferences, review-first staging, generated or typed commit messages, explicit push/PR confirmation, and optional PR worktrees.
|
|
161
161
|
- Browser support for Pi extension UI prompts, widgets, status updates, `/btw` side-question output widgets with optional context transfer/live steering, browser notifications when a tab needs an extension UI response, and an optional side-panel toggle for agent-done notifications.
|
|
162
|
-
- Localhost-only Pi/Web UI update checks with a top-right update notification and confirmed restart actions: **Update Pi & restart** runs `pi update` for Pi-only updates, while **Update Pi + Packages & Restart**
|
|
162
|
+
- Localhost-only Pi/Web UI update checks with a top-right update notification and confirmed restart actions: **Update Pi & restart** runs `pi update --self` for Pi-only updates, while **Update Pi + Packages & Restart** first checks the selected Pi executable's `pi update --help`. It uses `pi update --all` when advertised, otherwise falls back to `pi update --self` followed by `pi update --extensions`, then updates detected Web UI/Optional Feature package roots for configured, local agent, project, global npm, and global Bun installs.
|
|
163
163
|
- Feedback reactions (`👍`, `👎`, `?`) on final assistant output plus tool/bash action cards, which can ask Pi to create or update a LEARNING.
|
|
164
164
|
- Mobile-friendly layout, PWA install support where the browser allows it, backend-offline recovery, and a dedicated server-restart overlay while confirmed restart/update actions run.
|
|
165
165
|
|
|
@@ -334,7 +334,7 @@ Useful browser endpoints exposed by the local server include:
|
|
|
334
334
|
- `POST /api/action-feedback?tab=<tabId>` for feedback on final assistant output and action cards.
|
|
335
335
|
- `GET /api/optional-features` for optional companion package install/update status.
|
|
336
336
|
- `POST /api/optional-feature-install` for installing or updating known optional companion packages from the side panel.
|
|
337
|
-
- `GET /api/update-status`, localhost-only `POST /api/restart`, and localhost-only `POST /api/update` for checking Pi/Web UI updates and restarting the Web UI.
|
|
337
|
+
- `GET /api/update-status`, localhost-only `POST /api/restart`, and localhost-only `POST /api/update` for checking Pi/Web UI updates and restarting the Web UI. `POST /api/update?all=1` probes the selected Pi executable for `pi update --all`, uses the split `pi update --self` plus `pi update --extensions` fallback when unavailable, and then updates detected Web UI/Optional Feature package roots for configured, local agent, project, global npm, and global Bun installs.
|
|
338
338
|
- `GET /api/network`, localhost-only `POST /api/network/open`, localhost-only `POST /api/network/close`, `GET /api/remote-auth`, `POST /api/remote-auth`, and localhost-only `POST /api/remote-auth/settings` for trusted-LAN exposure and optional 4-digit PIN authentication when serving non-local browser clients.
|
|
339
339
|
|
|
340
340
|
For local development, run the checkout helper directly, for example:
|
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,7 @@ 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";
|
|
24
25
|
import {
|
|
25
26
|
GIT_WORKFLOW_DEFAULT_VARIANTS,
|
|
26
27
|
GIT_WORKFLOW_DELIVERY_MODES,
|
|
@@ -259,6 +260,11 @@ const MIME_TYPES = new Map([
|
|
|
259
260
|
[".css", "text/css; charset=utf-8"],
|
|
260
261
|
[".svg", "image/svg+xml"],
|
|
261
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"],
|
|
262
268
|
[".webp", "image/webp"],
|
|
263
269
|
[".webmanifest", "application/manifest+json; charset=utf-8"],
|
|
264
270
|
]);
|
|
@@ -1010,6 +1016,163 @@ async function sendNativeDownload(res, token, { inline = false } = {}) {
|
|
|
1010
1016
|
});
|
|
1011
1017
|
}
|
|
1012
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
|
+
|
|
1013
1176
|
const ACTION_FEEDBACK_REACTIONS = new Set(["up", "down", "question"]);
|
|
1014
1177
|
|
|
1015
1178
|
function trimFeedbackField(value, maxLength) {
|
|
@@ -6719,7 +6882,7 @@ function responseWithPendingThinking(tab, response) {
|
|
|
6719
6882
|
|
|
6720
6883
|
function eventForTabClients(tab, event) {
|
|
6721
6884
|
return {
|
|
6722
|
-
...responseWithPendingThinking(tab, event),
|
|
6885
|
+
...rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, event)),
|
|
6723
6886
|
tabId: tab.id,
|
|
6724
6887
|
tabTitle: tab.title,
|
|
6725
6888
|
tabActivity: tabActivitySnapshot(tab),
|
|
@@ -7812,35 +7975,59 @@ async function getUpdateStatus({ force = false } = {}) {
|
|
|
7812
7975
|
checkedAt: new Date(now).toISOString(),
|
|
7813
7976
|
updateAvailable,
|
|
7814
7977
|
restartRequired: true,
|
|
7815
|
-
command:
|
|
7816
|
-
allCommand:
|
|
7978
|
+
command: piUpdateCommandText(),
|
|
7979
|
+
allCommand: piUpdateCommandText({ all: true, supportsAll: true }),
|
|
7980
|
+
allFallbackCommand: piUpdateCommandText({ all: true }),
|
|
7817
7981
|
webuiDev: webuiDevServer,
|
|
7818
7982
|
pi: piStatus,
|
|
7819
7983
|
webui: webuiStatus,
|
|
7820
7984
|
packages: {
|
|
7821
7985
|
checked: false,
|
|
7822
|
-
note: "
|
|
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."
|
|
7823
7987
|
},
|
|
7824
7988
|
};
|
|
7825
7989
|
updateStatusCacheAt = now;
|
|
7826
7990
|
return updateStatusCache;
|
|
7827
7991
|
}
|
|
7828
7992
|
|
|
7829
|
-
async function
|
|
7830
|
-
const
|
|
7831
|
-
|
|
7832
|
-
|
|
7833
|
-
|
|
7834
|
-
|
|
7835
|
-
|
|
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 = "";
|
|
7836
8006
|
|
|
7837
|
-
|
|
7838
|
-
|
|
7839
|
-
|
|
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
|
+
}
|
|
7840
8021
|
}
|
|
7841
8022
|
|
|
7842
|
-
const
|
|
7843
|
-
|
|
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
|
+
})));
|
|
7844
8031
|
}
|
|
7845
8032
|
|
|
7846
8033
|
function packageNodeModulesPath(nodeModulesRoot, packageName) {
|
|
@@ -8046,8 +8233,8 @@ function uniqueUpdateTasks(tasks) {
|
|
|
8046
8233
|
}
|
|
8047
8234
|
|
|
8048
8235
|
async function resolveUpdateTasks({ all = false } = {}) {
|
|
8049
|
-
const
|
|
8050
|
-
if (!all) return uniqueUpdateTasks(
|
|
8236
|
+
const piTasks = await resolvePiUpdateCommands({ all });
|
|
8237
|
+
if (!all) return uniqueUpdateTasks(piTasks);
|
|
8051
8238
|
|
|
8052
8239
|
const [
|
|
8053
8240
|
currentWebuiTask,
|
|
@@ -8066,7 +8253,7 @@ async function resolveUpdateTasks({ all = false } = {}) {
|
|
|
8066
8253
|
]);
|
|
8067
8254
|
|
|
8068
8255
|
return uniqueUpdateTasks([
|
|
8069
|
-
|
|
8256
|
+
...piTasks,
|
|
8070
8257
|
currentWebuiTask,
|
|
8071
8258
|
agentTask,
|
|
8072
8259
|
optionalFeatureTask,
|
|
@@ -8328,7 +8515,7 @@ function fallbackRpcResponse(tab, command, error) {
|
|
|
8328
8515
|
|
|
8329
8516
|
async function safeRpcResponse(tab, command, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
8330
8517
|
try {
|
|
8331
|
-
return responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs));
|
|
8518
|
+
return rewriteArtifactsForTab(tab, responseWithPendingThinking(tab, await tab.rpc.send(command, timeoutMs)));
|
|
8332
8519
|
} catch (error) {
|
|
8333
8520
|
const message = sanitizeError(error);
|
|
8334
8521
|
if (/Pi RPC process is not running/i.test(message)) return responseWithPendingThinking(tab, fallbackRpcResponse(tab, command, error));
|
|
@@ -10914,6 +11101,24 @@ const server = createServer(async (req, res) => {
|
|
|
10914
11101
|
return;
|
|
10915
11102
|
}
|
|
10916
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
|
+
|
|
10917
11122
|
if (url.pathname.startsWith("/api/native-download/") && req.method === "GET") {
|
|
10918
11123
|
await sendNativeDownload(res, decodeURIComponent(url.pathname.slice("/api/native-download/".length)), {
|
|
10919
11124
|
inline: url.searchParams.get("disposition") === "inline",
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export function piUpdateHelpSupportsAll(output) {
|
|
2
|
+
return /(?:^|[^A-Za-z0-9_-])--all(?:$|[^A-Za-z0-9_-])/.test(String(output || ""));
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function piUpdateCommandSteps({ all = false, supportsAll = false } = {}) {
|
|
6
|
+
if (!all) return [{ label: "Pi CLI", args: ["update", "--self"] }];
|
|
7
|
+
if (supportsAll) return [{ label: "Pi CLI and configured packages", args: ["update", "--all"] }];
|
|
8
|
+
|
|
9
|
+
// Explicit flags remain compatible with Pi releases that predate `--all`.
|
|
10
|
+
return [
|
|
11
|
+
{ label: "Pi CLI", args: ["update", "--self"] },
|
|
12
|
+
{ label: "configured Pi packages", args: ["update", "--extensions"] },
|
|
13
|
+
];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function piUpdateCommandText(options = {}) {
|
|
17
|
+
return piUpdateCommandSteps(options)
|
|
18
|
+
.map((step) => `pi ${step.args.join(" ")}`)
|
|
19
|
+
.join(" && ");
|
|
20
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@firstpick/pi-package-webui",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.7",
|
|
4
4
|
"description": "Pi Web UI companion package with a local browser UI CLI plus /webui-start and /webui-status commands.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://github.com/Firstp1ck/npm-packages/tree/main/pi-package-webui#readme",
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
"@firstpick/pi-extension-tools": "^0.1.6",
|
|
73
73
|
"@firstpick/pi-extension-workflows": "^0.1.2",
|
|
74
74
|
"@firstpick/pi-package-remote-webui": "^0.1.5",
|
|
75
|
-
"@firstpick/pi-prompts-git-pr": "^0.1.
|
|
75
|
+
"@firstpick/pi-prompts-git-pr": "^0.1.3",
|
|
76
76
|
"@firstpick/pi-themes-bundle": "^0.1.4"
|
|
77
77
|
},
|
|
78
78
|
"files": [
|
package/public/app.js
CHANGED
|
@@ -409,7 +409,7 @@ let statsOverlayCalibrationMessage = "";
|
|
|
409
409
|
let statsOverlayCalibrationBusy = "";
|
|
410
410
|
let latestStatsOverlayPayload = null;
|
|
411
411
|
let latestBtwWidgetPayload = null;
|
|
412
|
-
|
|
412
|
+
const btwWidgetDismissedIdsByTab = new Map();
|
|
413
413
|
let btwWidgetComposerOpen = false;
|
|
414
414
|
let btwWidgetInputDraft = "";
|
|
415
415
|
let btwWidgetFocusAfterRender = false;
|
|
@@ -3296,9 +3296,9 @@ function renderUpdateNotification(status = latestUpdateStatus, { force = false }
|
|
|
3296
3296
|
if (elements.updateNotificationMessage) {
|
|
3297
3297
|
let message = "Updates are available. Direct Web UI updates are only enabled from localhost on the host machine.";
|
|
3298
3298
|
if (canRunUpdate) {
|
|
3299
|
-
if (hasPiUpdate && hasPackageUpdate) message = "Run pi update for Pi only, or update all to include Web UI, Optional Features, configured Pi packages, and detected Pi package roots, then restart this Web UI server automatically.";
|
|
3300
|
-
else if (hasPackageUpdate) message = "Update all
|
|
3301
|
-
else message = "Run pi update for Pi only, then restart this Web UI server automatically.";
|
|
3299
|
+
if (hasPiUpdate && hasPackageUpdate) message = "Run pi update --self for Pi only, or update all to use pi update --all when supported and include Web UI, Optional Features, configured Pi packages, and detected Pi package roots, then restart this Web UI server automatically.";
|
|
3300
|
+
else if (hasPackageUpdate) message = "Update all checks for pi update --all support, then refreshes Web UI/package entries, Optional Features, configured Pi packages, and detected Pi package roots before restarting this Web UI server automatically.";
|
|
3301
|
+
else message = "Run pi update --self for Pi only, then restart this Web UI server automatically.";
|
|
3302
3302
|
}
|
|
3303
3303
|
elements.updateNotificationMessage.textContent = message;
|
|
3304
3304
|
}
|
|
@@ -3352,10 +3352,10 @@ function piUpdateConfirmationText({ all = false } = {}) {
|
|
|
3352
3352
|
const items = updateNotificationItems();
|
|
3353
3353
|
const workingWarning = hasWorkingTab() ? "\n\nOne or more Pi tabs look busy or blocked. Finish or abort in-flight work before updating if you need to preserve it." : "";
|
|
3354
3354
|
const versionText = items.length ? `\n\nDetected update: ${items.join(" · ")}.` : "";
|
|
3355
|
-
const
|
|
3355
|
+
const commandText = all ? '"pi update --all" when supported, otherwise "pi update --self" followed by "pi update --extensions"' : '"pi update --self"';
|
|
3356
3356
|
const scope = all ? "Pi, configured packages, Optional Features, and detected Pi package roots" : "Pi only";
|
|
3357
3357
|
const extra = all ? " It will also run npm/bun package updates for detected Web UI, Optional Feature, agent, project, and global Pi package roots." : "";
|
|
3358
|
-
return `Run ${scope} now?${versionText}\n\nThis will run
|
|
3358
|
+
return `Run ${scope} now?${versionText}\n\nThis will run ${commandText} on the Web UI host.${extra} After it finishes, Pi Web UI will restart itself. Browser clients will briefly disconnect, and managed Pi tabs/RPC processes will be restarted from saved session state when possible.${workingWarning}`;
|
|
3359
3359
|
}
|
|
3360
3360
|
|
|
3361
3361
|
async function runPiUpdateAndRestart({ all = false } = {}) {
|
|
@@ -5005,7 +5005,7 @@ function setOptionalFeatureDisabled(featureId, disabled) {
|
|
|
5005
5005
|
widgets.delete(BTW_OUTPUT_WIDGET_KEY);
|
|
5006
5006
|
widgets.delete(BTW_FOOTER_WIDGET_KEY);
|
|
5007
5007
|
latestBtwWidgetPayload = null;
|
|
5008
|
-
|
|
5008
|
+
btwWidgetDismissedIdsByTab.delete(activeTabId);
|
|
5009
5009
|
btwWidgetComposerOpen = false;
|
|
5010
5010
|
btwWidgetInputDraft = "";
|
|
5011
5011
|
}
|
|
@@ -7161,7 +7161,6 @@ function resetActiveTabUi() {
|
|
|
7161
7161
|
latestStats = null;
|
|
7162
7162
|
latestStatsOverlayPayload = null;
|
|
7163
7163
|
latestBtwWidgetPayload = null;
|
|
7164
|
-
btwWidgetDismissedId = "";
|
|
7165
7164
|
btwWidgetComposerOpen = false;
|
|
7166
7165
|
btwWidgetInputDraft = "";
|
|
7167
7166
|
latestWorkspace = null;
|
|
@@ -7856,6 +7855,7 @@ async function closeTerminalTabs(tabIds, { label = "selected terminal tabs" } =
|
|
|
7856
7855
|
clearGitWorkflowForTab(id);
|
|
7857
7856
|
appRunnerDataByTab.delete(id);
|
|
7858
7857
|
tabMessagesCache.delete(id);
|
|
7858
|
+
btwWidgetDismissedIdsByTab.delete(id);
|
|
7859
7859
|
}
|
|
7860
7860
|
syncTerminalCustomGroupsWithTabs(tabs);
|
|
7861
7861
|
clearOpenTerminalTabGroup(null, { force: true });
|
|
@@ -15712,7 +15712,7 @@ function currentBtwWidgetPayload() {
|
|
|
15712
15712
|
if (isOptionalFeatureDisabled("btwCommand")) return null;
|
|
15713
15713
|
const outputLines = widgets.get(BTW_OUTPUT_WIDGET_KEY)?.widgetLines || [];
|
|
15714
15714
|
const payload = parseBtwWidgetPayload(outputLines) || parseBtwWebuiPayloadRaw(statusEntries.get(BTW_WEBUI_STATUS_KEY)) || latestBtwWidgetPayload;
|
|
15715
|
-
if (payload?.id && payload.id ===
|
|
15715
|
+
if (payload?.id && payload.id === btwWidgetDismissedIdsByTab.get(activeTabId)) return null;
|
|
15716
15716
|
return payload;
|
|
15717
15717
|
}
|
|
15718
15718
|
|
|
@@ -15743,7 +15743,7 @@ function focusBtwWidgetInput() {
|
|
|
15743
15743
|
|
|
15744
15744
|
function openBtwComposerWidget() {
|
|
15745
15745
|
btwWidgetComposerOpen = true;
|
|
15746
|
-
|
|
15746
|
+
btwWidgetDismissedIdsByTab.delete(activeTabId);
|
|
15747
15747
|
btwWidgetFocusAfterRender = true;
|
|
15748
15748
|
setComposerActionsOpen(false);
|
|
15749
15749
|
setPublishMenuOpen(false);
|
|
@@ -15755,7 +15755,7 @@ function openBtwComposerWidget() {
|
|
|
15755
15755
|
|
|
15756
15756
|
function closeBtwOutputWidget() {
|
|
15757
15757
|
const payload = currentBtwWidgetPayload();
|
|
15758
|
-
if (payload?.id)
|
|
15758
|
+
if (payload?.id && activeTabId) btwWidgetDismissedIdsByTab.set(activeTabId, payload.id);
|
|
15759
15759
|
widgets.delete(BTW_OUTPUT_WIDGET_KEY);
|
|
15760
15760
|
widgets.delete(BTW_FOOTER_WIDGET_KEY);
|
|
15761
15761
|
statusEntries.delete(BTW_WEBUI_STATUS_KEY);
|
|
@@ -20385,10 +20385,83 @@ function renderLsToolExecution(parent, tool) {
|
|
|
20385
20385
|
appendToolWarnings(parent, tool.details);
|
|
20386
20386
|
}
|
|
20387
20387
|
|
|
20388
|
+
let documentArtifactDialog = null;
|
|
20389
|
+
|
|
20390
|
+
function addDocumentArtifactPageToComposer(artifact, pageNum) {
|
|
20391
|
+
const reference = `[Document artifact ${artifact.id}${artifact.revisionId ? ` revision ${artifact.revisionId}` : ""}, page ${pageNum}]`;
|
|
20392
|
+
const current = elements.promptInput.value.trim();
|
|
20393
|
+
elements.promptInput.value = [current, reference].filter(Boolean).join("\n\n");
|
|
20394
|
+
resizePromptInput();
|
|
20395
|
+
renderCommandSuggestions();
|
|
20396
|
+
focusPromptInput({ defer: true });
|
|
20397
|
+
}
|
|
20398
|
+
|
|
20399
|
+
function ensureDocumentArtifactDialog() {
|
|
20400
|
+
if (documentArtifactDialog?.isConnected) return documentArtifactDialog;
|
|
20401
|
+
const dialog = make("dialog", "document-artifact-dialog");
|
|
20402
|
+
dialog.addEventListener("click", (event) => { if (event.target === dialog) dialog.close(); });
|
|
20403
|
+
document.body.append(dialog);
|
|
20404
|
+
documentArtifactDialog = dialog;
|
|
20405
|
+
return dialog;
|
|
20406
|
+
}
|
|
20407
|
+
|
|
20408
|
+
async function openDocumentArtifact(artifact) {
|
|
20409
|
+
const dialog = ensureDocumentArtifactDialog();
|
|
20410
|
+
dialog.replaceChildren(make("div", "document-artifact-loading", "Loading document artifact…"));
|
|
20411
|
+
if (!dialog.open) dialog.showModal();
|
|
20412
|
+
try {
|
|
20413
|
+
const response = await api(artifact.manifestUrl);
|
|
20414
|
+
const manifest = response.data || {}, pages = Array.isArray(manifest.pages) ? manifest.pages : [];
|
|
20415
|
+
let pageIndex = 0, zoom = 1, rotation = 0;
|
|
20416
|
+
const shell = make("section", "document-artifact-shell"), header = make("header", "document-artifact-header"), title = make("div", "document-artifact-title"), actions = make("div", "document-artifact-actions"), body = make("div", "document-artifact-body"), sidebar = make("aside", "document-artifact-sidebar"), stage = make("main", "document-artifact-stage"), image = make("img", "document-artifact-page"), toolbar = make("div", "document-artifact-toolbar"), meta = make("span", "document-artifact-meta"), search = make("input", "document-artifact-search"), semantic = make("details", "document-artifact-semantic");
|
|
20417
|
+
title.append(make("strong", undefined, artifact.title || "Document"), make("span", "muted", `${artifact.pageCount || pages.length || 0} page${Number(artifact.pageCount || pages.length) === 1 ? "" : "s"} · ${manifest.renderer?.engine || "document artifact"}`));
|
|
20418
|
+
const close = make("button", undefined, "Close"); close.type = "button"; close.addEventListener("click", () => dialog.close());
|
|
20419
|
+
if (artifact.downloadUrl) { const download = make("a", "button-like", "Download"); download.href = artifact.downloadUrl; download.download = artifact.title || "document"; actions.append(download); }
|
|
20420
|
+
actions.append(close); header.append(title, actions);
|
|
20421
|
+
search.type = "search"; search.placeholder = "Search outline, comments, revisions, or metadata";
|
|
20422
|
+
const previous = make("button", undefined, "Previous"), next = make("button", undefined, "Next"), zoomOut = make("button", undefined, "−"), zoomIn = make("button", undefined, "+"), fit = make("button", undefined, "Fit"), rotate = make("button", undefined, "Rotate"), send = make("button", undefined, "Send page to composer");
|
|
20423
|
+
for (const button of [previous, next, zoomOut, zoomIn, fit, rotate, send]) button.type = "button";
|
|
20424
|
+
const renderPage = () => {
|
|
20425
|
+
const page = pages[pageIndex];
|
|
20426
|
+
image.hidden = !page;
|
|
20427
|
+
if (page) { image.src = page.imageUrl; image.alt = `Rendered page ${page.pageNum} of ${artifact.title || "document"}`; image.style.transform = `scale(${zoom}) rotate(${rotation}deg)`; meta.textContent = `Page ${page.pageNum} of ${artifact.pageCount || pages.length} · ${Math.round(zoom * 100)}% · ${rotation}°`; }
|
|
20428
|
+
else meta.textContent = "No rendered pages are available";
|
|
20429
|
+
previous.disabled = pageIndex <= 0; next.disabled = pageIndex >= pages.length - 1; send.disabled = !page;
|
|
20430
|
+
for (const [index, button] of [...sidebar.querySelectorAll("button")].entries()) button.classList.toggle("active", index === pageIndex);
|
|
20431
|
+
};
|
|
20432
|
+
previous.addEventListener("click", () => { pageIndex = Math.max(0, pageIndex - 1); renderPage(); });
|
|
20433
|
+
next.addEventListener("click", () => { pageIndex = Math.min(pages.length - 1, pageIndex + 1); renderPage(); });
|
|
20434
|
+
zoomOut.addEventListener("click", () => { zoom = Math.max(0.25, zoom - 0.25); renderPage(); });
|
|
20435
|
+
zoomIn.addEventListener("click", () => { zoom = Math.min(3, zoom + 0.25); renderPage(); });
|
|
20436
|
+
fit.addEventListener("click", () => { zoom = 1; renderPage(); });
|
|
20437
|
+
rotate.addEventListener("click", () => { rotation = (rotation + 90) % 360; renderPage(); });
|
|
20438
|
+
send.addEventListener("click", () => { const page = pages[pageIndex]; if (page) { addDocumentArtifactPageToComposer(artifact, page.pageNum); dialog.close(); } });
|
|
20439
|
+
toolbar.append(previous, next, zoomOut, zoomIn, fit, rotate, send, meta);
|
|
20440
|
+
for (const [index, page] of pages.entries()) { const button = make("button", "document-artifact-thumbnail"); button.type = "button"; const thumb = make("img"); thumb.src = page.imageUrl; thumb.alt = ""; button.append(thumb, make("span", undefined, `Page ${page.pageNum}`)); button.addEventListener("click", () => { pageIndex = index; renderPage(); }); sidebar.append(button); }
|
|
20441
|
+
const semanticData = { outline: manifest.outline || [], comments: manifest.comments || [], revisions: manifest.revisions || [], warnings: manifest.warnings || [], diff: manifest.diff || undefined, renderer: manifest.renderer || undefined };
|
|
20442
|
+
semantic.append(make("summary", undefined, "Semantic structure, revisions, warnings, and diff"), make("pre", undefined, JSON.stringify(semanticData, null, 2)));
|
|
20443
|
+
search.addEventListener("input", () => { const query = search.value.trim().toLocaleLowerCase(); semantic.hidden = !!query && !JSON.stringify(semanticData).toLocaleLowerCase().includes(query); if (query && semantic.hidden) search.setCustomValidity("No semantic match"); else search.setCustomValidity(""); });
|
|
20444
|
+
stage.append(toolbar, search, image, semantic); body.append(sidebar, stage); shell.append(header, body); dialog.replaceChildren(shell); renderPage();
|
|
20445
|
+
} catch (error) {
|
|
20446
|
+
const close = make("button", undefined, "Close"); close.type = "button"; close.addEventListener("click", () => dialog.close());
|
|
20447
|
+
dialog.replaceChildren(make("div", "document-artifact-error", `Document artifact is stale or unavailable: ${error.message || error}`), close);
|
|
20448
|
+
}
|
|
20449
|
+
}
|
|
20450
|
+
|
|
20451
|
+
function appendDocumentArtifact(parent, artifact) {
|
|
20452
|
+
if (artifact?.schema !== "pi.artifact/v1" || artifact?.kind !== "document") return;
|
|
20453
|
+
const card = make("div", `document-artifact-card${artifact.unavailable ? " unavailable" : ""}`), text = make("div"), actions = make("div", "document-artifact-card-actions");
|
|
20454
|
+
text.append(make("strong", undefined, artifact.title || "Document artifact"), make("span", "muted", artifact.unavailable ? "Preview unavailable" : `${artifact.pageCount || 0} page${Number(artifact.pageCount) === 1 ? "" : "s"}`));
|
|
20455
|
+
if (!artifact.unavailable && artifact.manifestUrl) { const open = make("button", undefined, "Open viewer"); open.type = "button"; open.addEventListener("click", () => openDocumentArtifact(artifact)); actions.append(open); }
|
|
20456
|
+
if (!artifact.unavailable && artifact.downloadUrl) { const download = make("a", "button-like", "Download"); download.href = artifact.downloadUrl; download.download = artifact.title || "document"; actions.append(download); }
|
|
20457
|
+
card.append(text, actions); parent.append(card);
|
|
20458
|
+
}
|
|
20459
|
+
|
|
20388
20460
|
function renderGenericToolExecution(parent, tool) {
|
|
20389
20461
|
appendToolTitle(parent, tool.name, "", toolStateMeta(tool));
|
|
20390
20462
|
appendToolOutput(parent, JSON.stringify(tool.args ?? {}, null, 2), { label: "arguments", previewLines: 12 });
|
|
20391
20463
|
appendToolImages(parent, tool.result);
|
|
20464
|
+
appendDocumentArtifact(parent, tool.details?.artifact);
|
|
20392
20465
|
appendToolOutput(parent, tool.text, { label: "result", previewLines: 10, open: tool.isError });
|
|
20393
20466
|
appendToolWarnings(parent, tool.details);
|
|
20394
20467
|
}
|
|
@@ -21393,7 +21466,7 @@ async function sendBtwQuestion(question, { clearComposerDraft = false } = {}) {
|
|
|
21393
21466
|
const message = /^\/btw(?:\s|$)/.test(cleanQuestion) ? cleanQuestion : `/btw ${cleanQuestion}`;
|
|
21394
21467
|
const targetTabId = activeTabId;
|
|
21395
21468
|
btwWidgetComposerOpen = true;
|
|
21396
|
-
|
|
21469
|
+
btwWidgetDismissedIdsByTab.delete(targetTabId);
|
|
21397
21470
|
try {
|
|
21398
21471
|
await sendPrompt("prompt", message, { targetTabId, throwOnError: true });
|
|
21399
21472
|
} catch {
|
|
@@ -25027,8 +25100,8 @@ function updateServerActionButton() {
|
|
|
25027
25100
|
button.textContent = action === "restart" ? "Restart" : action === "update" || action === "update-all" ? "Update" : action === "stop" ? "Stop" : "Run";
|
|
25028
25101
|
button.classList.toggle("danger", action === "stop");
|
|
25029
25102
|
if (action === "restart") setServerActionStatus("Ready to restart the Web UI server.", "info");
|
|
25030
|
-
else if (action === "update") setServerActionStatus("Ready to run pi update for Pi only, then restart the Web UI server.", "info");
|
|
25031
|
-
else if (action === "update-all") setServerActionStatus("Ready to
|
|
25103
|
+
else if (action === "update") setServerActionStatus("Ready to run pi update --self for Pi only, then restart the Web UI server.", "info");
|
|
25104
|
+
else if (action === "update-all") setServerActionStatus("Ready to check pi update --all support, use the compatible fallback when needed, update detected Web UI/Optional Feature Pi package roots, then restart the Web UI server.", "info");
|
|
25032
25105
|
else if (action === "stop") setServerActionStatus("Ready to stop the Web UI server.", "info");
|
|
25033
25106
|
else setServerActionStatus();
|
|
25034
25107
|
}
|
|
@@ -25677,7 +25750,7 @@ function handleEvent(event) {
|
|
|
25677
25750
|
statusEntries.clear();
|
|
25678
25751
|
clearWidgetsForTab(event.tabId || activeTabId);
|
|
25679
25752
|
latestBtwWidgetPayload = null;
|
|
25680
|
-
|
|
25753
|
+
btwWidgetDismissedIdsByTab.delete(event.tabId || activeTabId);
|
|
25681
25754
|
btwWidgetComposerOpen = false;
|
|
25682
25755
|
btwWidgetInputDraft = "";
|
|
25683
25756
|
resetOptionalFeatureAvailability();
|
package/public/styles.css
CHANGED
|
@@ -10947,3 +10947,62 @@ button.workspace-dashboard-chip {
|
|
|
10947
10947
|
gap: 0.15rem;
|
|
10948
10948
|
padding: 0.3rem 0.1rem;
|
|
10949
10949
|
}
|
|
10950
|
+
|
|
10951
|
+
/* Tokenized pi.artifact/v1 document viewer */
|
|
10952
|
+
.document-artifact-card {
|
|
10953
|
+
display: flex;
|
|
10954
|
+
align-items: center;
|
|
10955
|
+
justify-content: space-between;
|
|
10956
|
+
gap: 0.8rem;
|
|
10957
|
+
margin-top: 0.55rem;
|
|
10958
|
+
padding: 0.65rem 0.75rem;
|
|
10959
|
+
border: 1px solid rgba(137, 220, 235, 0.32);
|
|
10960
|
+
border-radius: 0.72rem;
|
|
10961
|
+
background: rgba(137, 220, 235, 0.08);
|
|
10962
|
+
}
|
|
10963
|
+
.document-artifact-card > div:first-child,
|
|
10964
|
+
.document-artifact-title { display: grid; gap: 0.15rem; min-width: 0; }
|
|
10965
|
+
.document-artifact-card-actions,
|
|
10966
|
+
.document-artifact-actions,
|
|
10967
|
+
.document-artifact-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4rem; }
|
|
10968
|
+
.document-artifact-card.unavailable { border-color: rgba(249, 226, 175, 0.32); background: rgba(249, 226, 175, 0.08); }
|
|
10969
|
+
.document-artifact-dialog {
|
|
10970
|
+
width: min(96vw, 92rem);
|
|
10971
|
+
height: min(94vh, 70rem);
|
|
10972
|
+
padding: 0;
|
|
10973
|
+
border: 1px solid rgba(180, 190, 254, 0.3);
|
|
10974
|
+
border-radius: 1rem;
|
|
10975
|
+
background: var(--ctp-base);
|
|
10976
|
+
color: var(--ctp-text);
|
|
10977
|
+
}
|
|
10978
|
+
.document-artifact-dialog::backdrop { background: rgba(0, 0, 0, 0.72); backdrop-filter: blur(4px); }
|
|
10979
|
+
.document-artifact-shell { display: grid; grid-template-rows: auto minmax(0, 1fr); height: 100%; }
|
|
10980
|
+
.document-artifact-header {
|
|
10981
|
+
display: flex;
|
|
10982
|
+
align-items: center;
|
|
10983
|
+
justify-content: space-between;
|
|
10984
|
+
gap: 1rem;
|
|
10985
|
+
padding: 0.75rem 0.9rem;
|
|
10986
|
+
border-bottom: 1px solid rgba(180, 190, 254, 0.18);
|
|
10987
|
+
}
|
|
10988
|
+
.document-artifact-body { display: grid; grid-template-columns: minmax(8rem, 12rem) minmax(0, 1fr); min-height: 0; }
|
|
10989
|
+
.document-artifact-sidebar { overflow: auto; display: grid; align-content: start; gap: 0.5rem; padding: 0.65rem; border-right: 1px solid rgba(180, 190, 254, 0.16); }
|
|
10990
|
+
.document-artifact-thumbnail { display: grid; gap: 0.25rem; padding: 0.35rem; border-radius: 0.55rem; }
|
|
10991
|
+
.document-artifact-thumbnail.active { border-color: var(--ctp-blue); box-shadow: 0 0 0 1px var(--ctp-blue); }
|
|
10992
|
+
.document-artifact-thumbnail img { width: 100%; max-height: 9rem; object-fit: contain; background: white; }
|
|
10993
|
+
.document-artifact-stage { overflow: auto; display: grid; align-content: start; justify-items: center; gap: 0.65rem; padding: 0.75rem; }
|
|
10994
|
+
.document-artifact-toolbar { position: sticky; z-index: 2; top: 0; width: 100%; padding: 0.45rem; border-radius: 0.65rem; background: rgba(var(--ctp-mantle-rgb), 0.94); }
|
|
10995
|
+
.document-artifact-meta { margin-left: auto; color: rgba(var(--ctp-subtext-rgb), 0.82); font-size: 0.76rem; }
|
|
10996
|
+
.document-artifact-search { width: min(100%, 46rem); }
|
|
10997
|
+
.document-artifact-page { max-width: min(100%, 70rem); height: auto; transform-origin: top center; background: white; box-shadow: 0 0.7rem 2rem rgba(0, 0, 0, 0.32); transition: transform 120ms ease; }
|
|
10998
|
+
.document-artifact-semantic { width: min(100%, 70rem); }
|
|
10999
|
+
.document-artifact-semantic pre { overflow: auto; max-height: 24rem; white-space: pre-wrap; }
|
|
11000
|
+
.document-artifact-loading,
|
|
11001
|
+
.document-artifact-error { padding: 1.2rem; }
|
|
11002
|
+
@media (max-width: 720px) {
|
|
11003
|
+
.document-artifact-dialog { width: 100vw; height: 100dvh; max-width: none; max-height: none; border-radius: 0; }
|
|
11004
|
+
.document-artifact-body { grid-template-columns: 1fr; }
|
|
11005
|
+
.document-artifact-sidebar { display: flex; overflow-x: auto; border-right: 0; border-bottom: 1px solid rgba(180, 190, 254, 0.16); }
|
|
11006
|
+
.document-artifact-thumbnail { flex: 0 0 6rem; }
|
|
11007
|
+
.document-artifact-header { align-items: flex-start; }
|
|
11008
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
7
|
+
const [server, app, styles] = await Promise.all([
|
|
8
|
+
readFile(join(root, "bin", "pi-webui.mjs"), "utf8"),
|
|
9
|
+
readFile(join(root, "public", "app.js"), "utf8"),
|
|
10
|
+
readFile(join(root, "public", "styles.css"), "utf8"),
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
for (const contract of ["pi.artifact/v1", "registerDocumentArtifact", "rewriteArtifactsForTab", "documentArtifactRecord", "sendDocumentArtifactFile", "/api/artifacts/"]) assert.ok(server.includes(contract), `server should contain ${contract}`);
|
|
14
|
+
for (const privateField of ["manifestPath", "downloadPath", "outputPath", "sourcePath", "stagedPath", "pdfPath", "workspace", "recoveryPath"]) assert.match(server, new RegExp(`PRIVATE_ARTIFACT_KEYS[^;]+[\\s\\S]*?${privateField}`), `artifact sanitizer should cover ${privateField}`);
|
|
15
|
+
for (const feature of ["openDocumentArtifact", "appendDocumentArtifact", "Send page to composer", "Previous", "Rotate", "Semantic structure, revisions, warnings, and diff"]) assert.ok(app.includes(feature), `browser viewer should contain ${feature}`);
|
|
16
|
+
for (const selector of [".document-artifact-dialog", ".document-artifact-sidebar", ".document-artifact-page", "@media (max-width: 720px)"]) assert.ok(styles.includes(selector), `viewer stylesheet should contain ${selector}`);
|
|
17
|
+
assert.equal(/details\.artifact\s*=/.test(server), false, "server should replace details immutably rather than mutating raw RPC artifacts");
|
|
18
|
+
console.log("document-artifact-static.test.mjs passed");
|
|
@@ -240,6 +240,17 @@ function handleWebuiHelperPrompt(command, base) {
|
|
|
240
240
|
}
|
|
241
241
|
}
|
|
242
242
|
|
|
243
|
+
function handleDocumentArtifactFixturePrompt(command, base) {
|
|
244
|
+
const message = String(command.message || "").trim();
|
|
245
|
+
if (message === "fixture document artifact clear") { for (let index = dynamicMessages.length - 1; index >= 0; index--) if (dynamicMessages[index]?.toolName === "docx_render") { dynamicMessages.splice(index, 1); dynamicEntries.splice(index, 1); } dynamicLeafId = dynamicEntries.at(-1)?.id || "u0000002"; respond({ ...base, data: { output: "fake document artifacts cleared" } }); return true; }
|
|
246
|
+
if (message !== "fixture document artifact" || !process.env.FAKE_PI_ARTIFACT_MANIFEST) return false;
|
|
247
|
+
const toolCallId = `artifact-${randomUUID()}`, artifact = { schema: "pi.artifact/v1", kind: "document", id: "fixture-document-artifact", revisionId: "fixture-revision", title: "fixture.docx", mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", pageCount: 1, manifestPath: process.env.FAKE_PI_ARTIFACT_MANIFEST, downloadPath: process.env.FAKE_PI_ARTIFACT_DOWNLOAD, expiresAt: new Date(Date.now() + 60 * 60 * 1000).toISOString() }, result = { content: [{ type: "text", text: "Rendered fixture document" }], details: { artifact } };
|
|
248
|
+
appendDynamicMessage({ role: "toolResult", toolCallId, toolName: "docx_render", content: result.content, details: result.details, isError: false, timestamp: Date.now() });
|
|
249
|
+
respond({ ...base, data: { output: "fake document artifact emitted" } });
|
|
250
|
+
emitEvent({ type: "tool_execution_end", toolCallId, toolName: "docx_render", isError: false, result });
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
|
|
243
254
|
function handleSubagentFixturePrompt(command, base) {
|
|
244
255
|
const message = String(command.message || "").trim();
|
|
245
256
|
if (message !== "fixture subagents running" && message !== "fixture subagents clear") return false;
|
|
@@ -368,6 +379,7 @@ rl.on("line", (line) => {
|
|
|
368
379
|
case "prompt":
|
|
369
380
|
if (handleWebuiHelperPrompt(command, base)) return;
|
|
370
381
|
if (handleSubagentFixturePrompt(command, base)) return;
|
|
382
|
+
if (handleDocumentArtifactFixturePrompt(command, base)) return;
|
|
371
383
|
if (handleTalkPrompt(command, base)) return;
|
|
372
384
|
if (handleVoiceScriptPrompt(command, base)) return;
|
|
373
385
|
respond({ ...base, data: { output: "fake prompt accepted" } });
|
|
@@ -79,6 +79,11 @@ const settingsFile = path.join(harnessSideEffectsRoot, "webui-settings.json");
|
|
|
79
79
|
const openCommandLog = path.join(harnessSideEffectsRoot, "open-default.log");
|
|
80
80
|
const openCommandScript = path.join(harnessSideEffectsRoot, "fake-open-default.mjs");
|
|
81
81
|
const fakeOpenBinDir = path.join(harnessSideEffectsRoot, "bin");
|
|
82
|
+
const artifactRoot = path.join(harnessSideEffectsRoot, "artifacts"), artifactDir = path.join(artifactRoot, "fixture-document-artifact"), artifactManifest = path.join(artifactDir, "manifest.json"), artifactDownload = path.join(artifactDir, "document.docx"), artifactPage = path.join(artifactDir, "page-1.png"), artifactExpiresAt = new Date(Date.now() + 60 * 60 * 1000).toISOString();
|
|
83
|
+
await mkdir(artifactDir, { recursive: true });
|
|
84
|
+
await writeFile(artifactDownload, Buffer.from("fixture docx download bytes"));
|
|
85
|
+
await writeFile(artifactPage, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
|
|
86
|
+
await writeFile(artifactManifest, JSON.stringify({ artifact: { schema: "pi.artifact/v1", kind: "document", id: "fixture-document-artifact", revisionId: "fixture-revision", title: "fixture.docx", mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", pageCount: 1, manifestPath: artifactManifest, downloadPath: artifactDownload, expiresAt: artifactExpiresAt }, sourcePath: "/private/source.docx", sourceSha256: "a".repeat(64), renderer: { engine: "fixture" }, pages: [{ pageNum: 1, width: 10, height: 20, outputPath: artifactPage }], warnings: [] }));
|
|
82
87
|
await chmod(fakePi, 0o755);
|
|
83
88
|
await mkdir(fakeOpenBinDir, { recursive: true });
|
|
84
89
|
await writeFile(openCommandScript, `#!/usr/bin/env node\nimport { appendFile } from "node:fs/promises";\nawait appendFile(process.env.PI_WEBUI_OPEN_LOG, "custom-open\\t" + process.argv.slice(2).join("\\t") + "\\n", "utf8");\n`, "utf8");
|
|
@@ -123,6 +128,9 @@ const child = spawn(process.execPath, [serverScript, "--cwd", cwd, "--host", "0.
|
|
|
123
128
|
PI_WEBUI_SETTINGS_FILE: settingsFile,
|
|
124
129
|
...(process.platform === "linux" ? {} : { PI_WEBUI_OPEN_COMMAND: openCommandScript }),
|
|
125
130
|
PI_WEBUI_OPEN_LOG: openCommandLog,
|
|
131
|
+
PI_WEBUI_ARTIFACT_ROOTS: artifactRoot,
|
|
132
|
+
FAKE_PI_ARTIFACT_MANIFEST: artifactManifest,
|
|
133
|
+
FAKE_PI_ARTIFACT_DOWNLOAD: artifactDownload,
|
|
126
134
|
FAKE_PI_VOICE_SCRIPTS: "1",
|
|
127
135
|
PI_VOICE_STT_URL: `http://127.0.0.1:${voiceProviderPort}/stt`,
|
|
128
136
|
PI_VOICE_TTS_URL: `http://127.0.0.1:${voiceProviderPort}/tts`,
|
|
@@ -217,6 +225,32 @@ try {
|
|
|
217
225
|
const tabId = tabList[0].id;
|
|
218
226
|
assert.ok(tabId, "tab should have an id");
|
|
219
227
|
|
|
228
|
+
const artifactFixture = await request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture document artifact" } });
|
|
229
|
+
assert.equal(artifactFixture.status, 200, "document artifact fixture should be accepted");
|
|
230
|
+
const artifactMessages = await request("127.0.0.1", `/api/messages?tab=${encodeURIComponent(tabId)}`);
|
|
231
|
+
const artifactToolResult = artifactMessages.body?.data?.messages?.findLast?.((message) => message?.role === "toolResult" && message?.toolName === "docx_render");
|
|
232
|
+
const publicArtifact = artifactToolResult?.details?.artifact;
|
|
233
|
+
assert.equal(publicArtifact?.schema, "pi.artifact/v1", "document artifact should survive transcript sanitization");
|
|
234
|
+
assert.ok(publicArtifact?.manifestUrl, "document artifact should receive a manifest URL");
|
|
235
|
+
assert.ok(publicArtifact?.downloadUrl, "document artifact should receive a download URL");
|
|
236
|
+
assert.equal(JSON.stringify(artifactToolResult).includes(harnessSideEffectsRoot), false, "browser transcript must not expose artifact host paths");
|
|
237
|
+
const artifactManifestResponse = await fetch(`http://127.0.0.1:${port}${publicArtifact.manifestUrl}`, { signal: AbortSignal.timeout(5_000) });
|
|
238
|
+
assert.equal(artifactManifestResponse.status, 200, "artifact manifest token should resolve for its tab");
|
|
239
|
+
const artifactManifestPayload = await artifactManifestResponse.json();
|
|
240
|
+
assert.equal(artifactManifestPayload.data.pages[0].pageNum, 1);
|
|
241
|
+
assert.equal(JSON.stringify(artifactManifestPayload).includes(harnessSideEffectsRoot), false, "artifact manifest response must not expose host paths");
|
|
242
|
+
const artifactPageResponse = await fetch(`http://127.0.0.1:${port}${artifactManifestPayload.data.pages[0].imageUrl}`, { signal: AbortSignal.timeout(5_000) });
|
|
243
|
+
assert.equal(artifactPageResponse.status, 200, "artifact page token should resolve");
|
|
244
|
+
assert.equal(artifactPageResponse.headers.get("content-type"), "image/png");
|
|
245
|
+
const artifactRangeResponse = await fetch(`http://127.0.0.1:${port}${publicArtifact.downloadUrl}`, { headers: { range: "bytes=0-6" }, signal: AbortSignal.timeout(5_000) });
|
|
246
|
+
assert.equal(artifactRangeResponse.status, 206, "artifact downloads should support bounded byte ranges");
|
|
247
|
+
assert.equal(artifactRangeResponse.headers.get("content-range"), `bytes 0-6/${(await stat(artifactDownload)).size}`);
|
|
248
|
+
const otherArtifactTab = await request("127.0.0.1", "/api/tabs", { method: "POST", body: { cwd, title: "artifact-isolation" } });
|
|
249
|
+
const wrongTabManifestUrl = new URL(publicArtifact.manifestUrl, `http://127.0.0.1:${port}`); wrongTabManifestUrl.searchParams.set("tab", otherArtifactTab.body?.data?.tab?.id);
|
|
250
|
+
assert.equal((await fetch(wrongTabManifestUrl, { signal: AbortSignal.timeout(5_000) })).status, 404, "artifact tokens must be tab-bound");
|
|
251
|
+
await request("127.0.0.1", `/api/tabs/${encodeURIComponent(otherArtifactTab.body?.data?.tab?.id)}`, { method: "DELETE" });
|
|
252
|
+
await request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture document artifact clear" } });
|
|
253
|
+
|
|
220
254
|
const subagentFixtureStart = await request("127.0.0.1", "/api/prompt", { method: "POST", body: { tab: tabId, message: "fixture subagents running" } });
|
|
221
255
|
assert.equal(subagentFixtureStart.status, 200, "subagent fixture status should be accepted");
|
|
222
256
|
let subagentsResponse;
|
|
@@ -39,7 +39,7 @@ const companionDependencies = {
|
|
|
39
39
|
"@firstpick/pi-extension-tools": "^0.1.6",
|
|
40
40
|
"@firstpick/pi-extension-workflows": "^0.1.2",
|
|
41
41
|
"@firstpick/pi-package-remote-webui": "^0.1.5",
|
|
42
|
-
"@firstpick/pi-prompts-git-pr": "^0.1.
|
|
42
|
+
"@firstpick/pi-prompts-git-pr": "^0.1.3",
|
|
43
43
|
"@firstpick/pi-themes-bundle": "^0.1.4",
|
|
44
44
|
};
|
|
45
45
|
|
|
@@ -528,7 +528,7 @@ assert.match(server, /cwdExplicit: false/, "server should track whether startup
|
|
|
528
528
|
assert.match(server, /return options\.cwdExplicit \? \[await createTab\(\)\] : \[\]/, "server should wait for UI cwd selection when no --cwd is supplied");
|
|
529
529
|
assert.match(server, /async function resolvedPiCliScript\(\)[\s\S]*require\.resolve\.paths\(PI_CODING_AGENT_PACKAGE\)[\s\S]*nodeModulesRoot[\s\S]*dist[\s\S]*cli\.js/, "server should resolve the bundled Pi CLI through Node resolution roots so hoisted global installs can spawn RPC tabs");
|
|
530
530
|
assert.match(server, /const bundledCli = await resolvedPiCliScript\(\)/, "standalone server should prefer the resolved Pi CLI script before falling back to PATH pi");
|
|
531
|
-
assert.match(server, /if \(options\.piBinExplicit\) \{\n\s+
|
|
531
|
+
assert.match(server, /if \(options\.piBinExplicit\) \{\n\s+resolveCommand = \(args\) => resolvePiCommand\(args\)/, "explicit --pi JavaScript launchers should also work for capability checks and update commands");
|
|
532
532
|
assert.match(app, /serverActionSelect\.addEventListener\("change", updateServerActionButton\)/, "Server action dropdown should control the guarded run button");
|
|
533
533
|
assert.match(app, /runServerActionButton\.addEventListener\("click"[\s\S]*runSelectedServerAction/, "Server action run button should execute the selected action");
|
|
534
534
|
assert.match(app, /api\("\/api\/restart", \{ method: "POST", scoped: false \}\)/, "Restart Server action should call the unscoped restart endpoint");
|
|
@@ -538,14 +538,15 @@ assert.match(app, /api\("\/api\/shutdown", \{ method: "POST", scoped: false \}\)
|
|
|
538
538
|
assert.match(server, /url\.pathname === "\/api\/restart" && req\.method === "POST"/, "server should expose restart endpoint");
|
|
539
539
|
assert.match(server, /PI_WEBUI_RESTORE_TABS: JSON\.stringify\(restorableTabs \|\| \[\]\)/, "server restart should preserve restorable tab metadata");
|
|
540
540
|
assert.match(server, /if \(webuiDevServer\) env\.PI_WEBUI_DEV = "1";/, "server restart should explicitly preserve dev mode");
|
|
541
|
-
assert.match(server, /
|
|
542
|
-
assert.match(server, /
|
|
541
|
+
assert.match(server, /async function piUpdateCommandSupportsAll\(command\)[\s\S]*runCommand\(command\.command, command\.args \|\| \[\][\s\S]*piUpdateHelpSupportsAll/, "server should check the selected Pi executable's update help");
|
|
542
|
+
assert.match(server, /const supportsAll = all && await piUpdateCommandSupportsAll\(await resolveCommand\(\["update", "--help"\]\)\)[\s\S]*piUpdateCommandSteps\(\{ all, supportsAll \}\)/, "server should prefer --all only when the capability check succeeds");
|
|
543
|
+
assert.match(server, /async function resolveUpdateTasks\(\{ all = false \} = \{\}\)[\s\S]*const piTasks = await resolvePiUpdateCommands\(\{ all \}\)[\s\S]*if \(!all\) return uniqueUpdateTasks\(piTasks\)[\s\S]*currentWebuiPackageUpdateTask\(\)[\s\S]*agentPackageRootUpdateTask\(\)[\s\S]*projectPackageRootUpdateTasks\(\)[\s\S]*npmGlobalPackageRootUpdateTask\(\)[\s\S]*bunGlobalPackageRootUpdateTask\(\)/, "server all-update should run the selected Pi plan plus detected local/global Pi package root tasks");
|
|
543
544
|
assert.match(server, /const UPDATE_PACKAGE_NAMES = \[\.\.\.new Set\(\[[\s\S]*WEBUI_CONTROLLED_PACKAGES[\s\S]*OPTIONAL_FEATURE_PACKAGES\.values\(\)/, "package-inclusive updates should include Web UI controlled Optional Feature packages");
|
|
544
|
-
assert.match(app, /const
|
|
545
|
+
assert.match(app, /const commandText = all \? '"pi update --all" when supported, otherwise "pi update --self" followed by "pi update --extensions"' : '"pi update --self"'/, "frontend update confirmation should describe capability selection and fallback");
|
|
545
546
|
assert.match(app, /Optional Features, and detected Pi package roots/, "frontend all-update confirmation should describe optional-feature and detected-root coverage");
|
|
546
547
|
assert.match(app, /api\(all \? "\/api\/update\?all=1" : "\/api\/update"/, "frontend all update should call the explicit all-mode endpoint");
|
|
547
|
-
assert.match(html, /<option value="update-all">Update Pi \+ Packages & Restart<\/option>/, "side panel should expose
|
|
548
|
-
assert.match(readme,
|
|
548
|
+
assert.match(html, /<option value="update-all">Update Pi \+ Packages & Restart<\/option>/, "side panel should expose package-inclusive updates as a separate server action");
|
|
549
|
+
assert.match(readme, /first checks the selected Pi executable's `pi update --help`[\s\S]*uses `pi update --all` when advertised[\s\S]*otherwise falls back/, "README should document the checked preferred and fallback update modes");
|
|
549
550
|
assert.match(server, /async function closeNetworkAccess\(\)/, "server should expose a local-only rebind helper for closing network access");
|
|
550
551
|
assert.match(server, /url\.pathname === "\/api\/network\/close" && req\.method === "POST"/, "server should route network close requests");
|
|
551
552
|
assert.match(server, /server\.closeAllConnections\?\.\(\)/, "network rebind should force-close long-lived clients so close-to-localhost can complete");
|
|
@@ -1077,6 +1078,11 @@ assert.match(app, /setBusyPromptBehavior\(controls\.busyBehavior\.select\.value\
|
|
|
1077
1078
|
assert.match(app, /sendPromptFromModeButton\("steer", elements\.steerButton\)/, "Steer should show tooltip instead of silently doing nothing when input is empty");
|
|
1078
1079
|
assert.match(app, /sendPromptFromModeButton\("follow-up", elements\.followUpButton\)/, "Follow-up should show tooltip instead of silently doing nothing when input is empty");
|
|
1079
1080
|
assert.match(app, /async function sendBtwQuestion\(question,[\s\S]*?`\/btw \$\{cleanQuestion\}`[\s\S]*?await sendPrompt\("prompt", message, \{ targetTabId, throwOnError: true \}\)/, "/btw helper should send text as an ephemeral slash command");
|
|
1081
|
+
assert.match(app, /const btwWidgetDismissedIdsByTab = new Map\(\)/, "/btw dismissals should be scoped to terminal tabs");
|
|
1082
|
+
assert.match(app, /function currentBtwWidgetPayload\(\)[\s\S]*?payload\.id === btwWidgetDismissedIdsByTab\.get\(activeTabId\)/, "/btw rendering should honor the active tab's dismissed payload ID");
|
|
1083
|
+
assert.match(app, /function closeBtwOutputWidget\(\)[\s\S]*?btwWidgetDismissedIdsByTab\.set\(activeTabId, payload\.id\)/, "closing /btw should remember the dismissed payload ID for its tab");
|
|
1084
|
+
const resetActiveTabUiSource = app.slice(app.indexOf("function resetActiveTabUi()"), app.indexOf("function tabGroupStatusRank"));
|
|
1085
|
+
assert.doesNotMatch(resetActiveTabUiSource, /btwWidgetDismissedIdsByTab/, "switching tabs should not clear remembered /btw dismissals");
|
|
1080
1086
|
assert.match(app, /async function sendBtwPromptFromButton\(\)[\s\S]*?if \(!question\) \{\n\s+openBtwComposerWidget\(\);/, "empty /btw button should open the side-question widget input");
|
|
1081
1087
|
assert.match(app, /function renderBtwComposerForm\(\)[\s\S]*?form\.requestSubmit\(\)[\s\S]*?sendBtwQuestion\(question\)/, "/btw widget input should submit each message as a /btw trigger");
|
|
1082
1088
|
assert.match(app, /function makeBtwTransferIcon\(\)[\s\S]*?class", "btw-transfer-icon"[\s\S]*?function transferBtwContextToMain\(button, \{ transferMode = "full" \} = \{\}\)[\s\S]*?`\/btw-transfer \$\{encoded\}`[\s\S]*?streamingBehavior: "steer"[\s\S]*?Summarize & Steer/, "/btw widget should expose full-context and summary transfer actions that send steering context during active runs");
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { piUpdateCommandSteps, piUpdateCommandText, piUpdateHelpSupportsAll } from "../lib/update-commands.mjs";
|
|
6
|
+
|
|
7
|
+
const packageRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
8
|
+
|
|
9
|
+
assert.deepEqual(piUpdateCommandSteps(), [
|
|
10
|
+
{ label: "Pi CLI", args: ["update", "--self"] },
|
|
11
|
+
], "Pi-only updates should use the explicit cross-version self flag");
|
|
12
|
+
|
|
13
|
+
assert.deepEqual(piUpdateCommandSteps({ all: true, supportsAll: true }), [
|
|
14
|
+
{ label: "Pi CLI and configured packages", args: ["update", "--all"] },
|
|
15
|
+
], "all updates should prefer --all when the selected Pi executable supports it");
|
|
16
|
+
|
|
17
|
+
const fallbackSteps = piUpdateCommandSteps({ all: true });
|
|
18
|
+
assert.deepEqual(fallbackSteps, [
|
|
19
|
+
{ label: "Pi CLI", args: ["update", "--self"] },
|
|
20
|
+
{ label: "configured Pi packages", args: ["update", "--extensions"] },
|
|
21
|
+
], "all updates should split self and extension updates when --all is unavailable");
|
|
22
|
+
|
|
23
|
+
assert.equal(piUpdateHelpSupportsAll("Usage: pi update [--self|--extensions|--all]"), true);
|
|
24
|
+
assert.equal(piUpdateHelpSupportsAll(" --all Update pi and installed packages"), true);
|
|
25
|
+
assert.equal(piUpdateHelpSupportsAll("Usage: pi update [--self] [--extensions]"), false);
|
|
26
|
+
assert.equal(piUpdateHelpSupportsAll(" --allow-project-files"), false, "similar option names must not count as --all");
|
|
27
|
+
|
|
28
|
+
assert.equal(piUpdateCommandText(), "pi update --self");
|
|
29
|
+
assert.equal(piUpdateCommandText({ all: true, supportsAll: true }), "pi update --all");
|
|
30
|
+
assert.equal(piUpdateCommandText({ all: true }), "pi update --self && pi update --extensions");
|
|
31
|
+
|
|
32
|
+
const [server, app, readme] = await Promise.all([
|
|
33
|
+
readFile(join(packageRoot, "bin", "pi-webui.mjs"), "utf8"),
|
|
34
|
+
readFile(join(packageRoot, "public", "app.js"), "utf8"),
|
|
35
|
+
readFile(join(packageRoot, "README.md"), "utf8"),
|
|
36
|
+
]);
|
|
37
|
+
assert.match(server, /async function piUpdateCommandSupportsAll\(command\)[\s\S]*piUpdateHelpSupportsAll/, "server should inspect update help from the selected Pi command");
|
|
38
|
+
assert.match(server, /resolveCommand\(\["update", "--help"\]\)[\s\S]*piUpdateCommandSteps\(\{ all, supportsAll \}\)/, "server should plan commands from the capability result");
|
|
39
|
+
assert.match(server, /const piTasks = await resolvePiUpdateCommands\(\{ all \}\)/, "all-mode task resolution should preserve the selected Pi update plan");
|
|
40
|
+
assert.match(server, /allCommand: piUpdateCommandText\(\{ all: true, supportsAll: true \}\)[\s\S]*allFallbackCommand: piUpdateCommandText\(\{ all: true \}\)/, "update status should expose preferred and fallback command text");
|
|
41
|
+
assert.match(app, /"pi update --all" when supported, otherwise "pi update --self" followed by "pi update --extensions"/, "update confirmation should describe capability selection and fallback");
|
|
42
|
+
assert.match(readme, /first checks the selected Pi executable's `pi update --help`[\s\S]*uses `pi update --all` when advertised[\s\S]*otherwise falls back/, "documentation should explain the checked fallback behavior");
|
|
43
|
+
|
|
44
|
+
console.log("update command planning tests passed");
|