@firstpick/pi-package-webui 0.6.3 → 0.6.4
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 +449 -13
- package/lib/trust-boundaries.mjs +2 -0
- package/package.json +2 -2
- package/public/app.js +918 -10
- package/public/index.html +66 -2
- package/public/styles.css +450 -2
- package/tests/fixtures/fake-pi.mjs +59 -3
- package/tests/http-endpoints-harness.test.mjs +212 -2
package/bin/pi-webui.mjs
CHANGED
|
@@ -94,6 +94,14 @@ const CLAUDE_USAGE_COMMAND = process.env.PI_WEBUI_CLAUDE_BIN || "claude";
|
|
|
94
94
|
const CLAUDE_USAGE_ARGS = ["--safe-mode", "--no-session-persistence", "-p", "/usage", "--output-format", "json"];
|
|
95
95
|
const BODY_LIMIT_BYTES = 1024 * 1024;
|
|
96
96
|
const SKILL_FILE_BODY_LIMIT_BYTES = 2 * 1024 * 1024;
|
|
97
|
+
const FILE_VIEWER_MAX_BYTES = 2 * 1024 * 1024;
|
|
98
|
+
const FILE_VIEWER_BODY_LIMIT_BYTES = FILE_VIEWER_MAX_BYTES + 64 * 1024;
|
|
99
|
+
const FILE_TREE_MAX_ENTRIES = 1200;
|
|
100
|
+
const FILE_TREE_ENTRY_STAT_CONCURRENCY = 32;
|
|
101
|
+
const FILE_SEARCH_MAX_RESULTS = 200;
|
|
102
|
+
const FILE_SEARCH_MAX_SCANNED = 12_000;
|
|
103
|
+
const FILE_SEARCH_MAX_DEPTH = 8;
|
|
104
|
+
const FILE_SEARCH_EXCLUDED_DIRS = new Set([".git", "node_modules"]);
|
|
97
105
|
const PROMPT_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
|
|
98
106
|
const VOICE_AUDIO_BODY_LIMIT_BYTES = 24 * 1024 * 1024;
|
|
99
107
|
const VOICE_AUDIO_JSON_BODY_LIMIT_BYTES = Math.ceil(VOICE_AUDIO_BODY_LIMIT_BYTES * 1.4) + 1024 * 1024;
|
|
@@ -5184,6 +5192,7 @@ async function serveStatic(req, res, url) {
|
|
|
5184
5192
|
|
|
5185
5193
|
function requestBodyLimitForPath(pathname) {
|
|
5186
5194
|
if (pathname === "/api/attachments") return UPLOAD_BODY_LIMIT_BYTES;
|
|
5195
|
+
if (pathname === "/api/files/content") return FILE_VIEWER_BODY_LIMIT_BYTES;
|
|
5187
5196
|
if (["/api/prompt", "/api/steer", "/api/follow-up"].includes(pathname)) return PROMPT_BODY_LIMIT_BYTES;
|
|
5188
5197
|
return BODY_LIMIT_BYTES;
|
|
5189
5198
|
}
|
|
@@ -8094,6 +8103,292 @@ function resolveTabPath(tab, value) {
|
|
|
8094
8103
|
return path.isAbsolute(text) ? text : path.resolve(tab?.cwd || options.cwd, text);
|
|
8095
8104
|
}
|
|
8096
8105
|
|
|
8106
|
+
async function workspaceRoot(tab) {
|
|
8107
|
+
const root = path.resolve(tab?.cwd || options.cwd);
|
|
8108
|
+
return { root, realRoot: await realpath(root).catch(() => root) };
|
|
8109
|
+
}
|
|
8110
|
+
|
|
8111
|
+
async function resolveWorkspacePath(tab, value = "", { mustExist = true } = {}) {
|
|
8112
|
+
const { root, realRoot } = await workspaceRoot(tab);
|
|
8113
|
+
const text = String(value || "").trim();
|
|
8114
|
+
if (text.includes("\0")) throw makeHttpError(400, "Path cannot contain null bytes");
|
|
8115
|
+
const targetPath = text ? (path.isAbsolute(text) ? path.resolve(text) : path.resolve(root, text)) : root;
|
|
8116
|
+
if (targetPath !== root && !pathInside(root, targetPath)) throw makeHttpError(403, "Path must stay inside the active tab working directory");
|
|
8117
|
+
let info = null;
|
|
8118
|
+
let realTarget = targetPath;
|
|
8119
|
+
try {
|
|
8120
|
+
info = await stat(targetPath);
|
|
8121
|
+
realTarget = await realpath(targetPath).catch(() => targetPath);
|
|
8122
|
+
} catch (error) {
|
|
8123
|
+
if (mustExist) throw makeHttpError(error?.code === "ENOENT" ? 404 : 400, `Path not found: ${displayPath(targetPath)}`);
|
|
8124
|
+
}
|
|
8125
|
+
if (realTarget !== realRoot && !pathInside(realRoot, realTarget)) throw makeHttpError(403, "Resolved path escapes the active tab working directory");
|
|
8126
|
+
const relative = path.relative(root, targetPath).split(path.sep).join("/");
|
|
8127
|
+
return { root, realRoot, targetPath, realTarget, relative, info };
|
|
8128
|
+
}
|
|
8129
|
+
|
|
8130
|
+
function fileViewerLanguage(filePath) {
|
|
8131
|
+
const ext = path.extname(String(filePath || "")).toLowerCase();
|
|
8132
|
+
if (ext === ".md" || ext === ".markdown") return "markdown";
|
|
8133
|
+
return "text";
|
|
8134
|
+
}
|
|
8135
|
+
|
|
8136
|
+
function fileTreeEntryType(dirent, info) {
|
|
8137
|
+
if (info?.isDirectory?.() || dirent?.isDirectory?.()) return "directory";
|
|
8138
|
+
if (info?.isFile?.() || dirent?.isFile?.()) return "file";
|
|
8139
|
+
return dirent?.isSymbolicLink?.() ? "symlink" : "other";
|
|
8140
|
+
}
|
|
8141
|
+
|
|
8142
|
+
async function statFileTreeEntries(dirPath, dirents, root, realRoot) {
|
|
8143
|
+
const ordered = [...dirents].sort((a, b) => {
|
|
8144
|
+
const aRank = a.isDirectory() ? 0 : a.isFile() ? 1 : 2;
|
|
8145
|
+
const bRank = b.isDirectory() ? 0 : b.isFile() ? 1 : 2;
|
|
8146
|
+
return aRank - bRank || a.name.localeCompare(b.name);
|
|
8147
|
+
});
|
|
8148
|
+
const selected = ordered.slice(0, FILE_TREE_MAX_ENTRIES);
|
|
8149
|
+
const entries = [];
|
|
8150
|
+
let cursor = 0;
|
|
8151
|
+
async function worker() {
|
|
8152
|
+
while (cursor < selected.length) {
|
|
8153
|
+
const dirent = selected[cursor++];
|
|
8154
|
+
const targetPath = path.join(dirPath, dirent.name);
|
|
8155
|
+
const relative = path.relative(root, targetPath).split(path.sep).join("/");
|
|
8156
|
+
try {
|
|
8157
|
+
const [info, realTarget] = await Promise.all([stat(targetPath), realpath(targetPath).catch(() => targetPath)]);
|
|
8158
|
+
const outsideRoot = realTarget !== realRoot && !pathInside(realRoot, realTarget);
|
|
8159
|
+
const type = outsideRoot ? "other" : fileTreeEntryType(dirent, info);
|
|
8160
|
+
entries.push({
|
|
8161
|
+
name: dirent.name,
|
|
8162
|
+
path: relative,
|
|
8163
|
+
type,
|
|
8164
|
+
directory: type === "directory",
|
|
8165
|
+
file: type === "file",
|
|
8166
|
+
symlink: dirent.isSymbolicLink(),
|
|
8167
|
+
outsideRoot,
|
|
8168
|
+
size: info.size,
|
|
8169
|
+
mtimeMs: info.mtimeMs,
|
|
8170
|
+
extension: path.extname(dirent.name).toLowerCase(),
|
|
8171
|
+
canOpenInWebui: type === "file",
|
|
8172
|
+
});
|
|
8173
|
+
} catch (error) {
|
|
8174
|
+
entries.push({ name: dirent.name, path: relative, type: "error", directory: false, file: false, error: sanitizeError(error), canOpenInWebui: false });
|
|
8175
|
+
}
|
|
8176
|
+
}
|
|
8177
|
+
}
|
|
8178
|
+
const workers = Array.from({ length: Math.min(FILE_TREE_ENTRY_STAT_CONCURRENCY, selected.length) }, () => worker());
|
|
8179
|
+
await Promise.all(workers);
|
|
8180
|
+
entries.sort((a, b) => {
|
|
8181
|
+
const aRank = a.type === "directory" ? 0 : a.type === "file" ? 1 : 2;
|
|
8182
|
+
const bRank = b.type === "directory" ? 0 : b.type === "file" ? 1 : 2;
|
|
8183
|
+
return aRank - bRank || a.name.localeCompare(b.name);
|
|
8184
|
+
});
|
|
8185
|
+
return { entries, truncated: ordered.length > selected.length, total: ordered.length };
|
|
8186
|
+
}
|
|
8187
|
+
|
|
8188
|
+
async function getFileTreeData(tab, requestedPath = "") {
|
|
8189
|
+
const resolved = await resolveWorkspacePath(tab, requestedPath);
|
|
8190
|
+
if (!resolved.info?.isDirectory()) throw makeHttpError(400, "Path is not a directory");
|
|
8191
|
+
const dirents = await readdir(resolved.targetPath, { withFileTypes: true });
|
|
8192
|
+
const listed = await statFileTreeEntries(resolved.targetPath, dirents, resolved.root, resolved.realRoot);
|
|
8193
|
+
return {
|
|
8194
|
+
root: resolved.root,
|
|
8195
|
+
displayRoot: displayPath(resolved.root),
|
|
8196
|
+
path: resolved.relative,
|
|
8197
|
+
displayPath: displayPath(resolved.targetPath),
|
|
8198
|
+
entries: listed.entries,
|
|
8199
|
+
truncated: listed.truncated,
|
|
8200
|
+
total: listed.total,
|
|
8201
|
+
};
|
|
8202
|
+
}
|
|
8203
|
+
|
|
8204
|
+
function normalizeFileSearchQuery(value = "") {
|
|
8205
|
+
const query = String(value || "").trim().replace(/\s+/g, " ");
|
|
8206
|
+
if (query.includes("\0")) throw makeHttpError(400, "Search query cannot contain null bytes");
|
|
8207
|
+
if (query.length > 160) throw makeHttpError(400, "Search query is too long");
|
|
8208
|
+
return query;
|
|
8209
|
+
}
|
|
8210
|
+
|
|
8211
|
+
function fileSearchMatches(entry, queryLower) {
|
|
8212
|
+
const name = String(entry.name || "").toLowerCase();
|
|
8213
|
+
const filePath = String(entry.path || "").toLowerCase();
|
|
8214
|
+
return name.includes(queryLower) || filePath.includes(queryLower);
|
|
8215
|
+
}
|
|
8216
|
+
|
|
8217
|
+
async function getFileSearchData(tab, rawQuery = "") {
|
|
8218
|
+
const query = normalizeFileSearchQuery(rawQuery);
|
|
8219
|
+
if (!query) {
|
|
8220
|
+
const root = path.resolve(tab?.cwd || options.cwd);
|
|
8221
|
+
return { root, displayRoot: displayPath(root), query, entries: [], truncated: false, total: 0, scanned: 0, maxDepth: FILE_SEARCH_MAX_DEPTH };
|
|
8222
|
+
}
|
|
8223
|
+
const resolved = await resolveWorkspacePath(tab, "");
|
|
8224
|
+
if (!resolved.info?.isDirectory()) throw makeHttpError(400, "Workspace root is not a directory");
|
|
8225
|
+
const queryLower = query.toLowerCase();
|
|
8226
|
+
const entries = [];
|
|
8227
|
+
const queue = [{ dirPath: resolved.root, relative: "", depth: 0 }];
|
|
8228
|
+
const visitedRealDirs = new Set([resolved.realRoot]);
|
|
8229
|
+
let scanned = 0;
|
|
8230
|
+
let truncated = false;
|
|
8231
|
+
|
|
8232
|
+
while (queue.length && scanned < FILE_SEARCH_MAX_SCANNED && entries.length < FILE_SEARCH_MAX_RESULTS) {
|
|
8233
|
+
const current = queue.shift();
|
|
8234
|
+
let dirents = [];
|
|
8235
|
+
try {
|
|
8236
|
+
dirents = await readdir(current.dirPath, { withFileTypes: true });
|
|
8237
|
+
} catch {
|
|
8238
|
+
continue;
|
|
8239
|
+
}
|
|
8240
|
+
dirents.sort((a, b) => {
|
|
8241
|
+
const aRank = a.isDirectory() ? 0 : a.isFile() ? 1 : 2;
|
|
8242
|
+
const bRank = b.isDirectory() ? 0 : b.isFile() ? 1 : 2;
|
|
8243
|
+
return aRank - bRank || a.name.localeCompare(b.name);
|
|
8244
|
+
});
|
|
8245
|
+
|
|
8246
|
+
for (const dirent of dirents) {
|
|
8247
|
+
if (scanned >= FILE_SEARCH_MAX_SCANNED || entries.length >= FILE_SEARCH_MAX_RESULTS) break;
|
|
8248
|
+
scanned += 1;
|
|
8249
|
+
const targetPath = path.join(current.dirPath, dirent.name);
|
|
8250
|
+
const relative = (current.relative ? `${current.relative}/${dirent.name}` : dirent.name).split(path.sep).join("/");
|
|
8251
|
+
const depth = current.depth + 1;
|
|
8252
|
+
try {
|
|
8253
|
+
const [info, realTarget] = await Promise.all([stat(targetPath), realpath(targetPath).catch(() => targetPath)]);
|
|
8254
|
+
const outsideRoot = realTarget !== resolved.realRoot && !pathInside(resolved.realRoot, realTarget);
|
|
8255
|
+
const type = outsideRoot ? "other" : fileTreeEntryType(dirent, info);
|
|
8256
|
+
const entry = {
|
|
8257
|
+
name: dirent.name,
|
|
8258
|
+
path: relative,
|
|
8259
|
+
type,
|
|
8260
|
+
directory: type === "directory",
|
|
8261
|
+
file: type === "file",
|
|
8262
|
+
symlink: dirent.isSymbolicLink(),
|
|
8263
|
+
outsideRoot,
|
|
8264
|
+
size: info.size,
|
|
8265
|
+
mtimeMs: info.mtimeMs,
|
|
8266
|
+
extension: path.extname(dirent.name).toLowerCase(),
|
|
8267
|
+
depth,
|
|
8268
|
+
canOpenInWebui: type === "file",
|
|
8269
|
+
};
|
|
8270
|
+
if (fileSearchMatches(entry, queryLower)) entries.push(entry);
|
|
8271
|
+
if (depth < FILE_SEARCH_MAX_DEPTH && type === "directory" && !FILE_SEARCH_EXCLUDED_DIRS.has(dirent.name) && !visitedRealDirs.has(realTarget)) {
|
|
8272
|
+
visitedRealDirs.add(realTarget);
|
|
8273
|
+
queue.push({ dirPath: targetPath, relative, depth });
|
|
8274
|
+
}
|
|
8275
|
+
} catch (error) {
|
|
8276
|
+
const entry = { name: dirent.name, path: relative, type: "error", directory: false, file: false, depth, error: sanitizeError(error), canOpenInWebui: false };
|
|
8277
|
+
if (fileSearchMatches(entry, queryLower)) entries.push(entry);
|
|
8278
|
+
}
|
|
8279
|
+
}
|
|
8280
|
+
}
|
|
8281
|
+
truncated = queue.length > 0 || scanned >= FILE_SEARCH_MAX_SCANNED || entries.length >= FILE_SEARCH_MAX_RESULTS;
|
|
8282
|
+
return {
|
|
8283
|
+
root: resolved.root,
|
|
8284
|
+
displayRoot: displayPath(resolved.root),
|
|
8285
|
+
query,
|
|
8286
|
+
entries,
|
|
8287
|
+
truncated,
|
|
8288
|
+
total: entries.length,
|
|
8289
|
+
scanned,
|
|
8290
|
+
maxDepth: FILE_SEARCH_MAX_DEPTH,
|
|
8291
|
+
excludedDirs: [...FILE_SEARCH_EXCLUDED_DIRS],
|
|
8292
|
+
};
|
|
8293
|
+
}
|
|
8294
|
+
|
|
8295
|
+
function assertTextFileBuffer(buffer) {
|
|
8296
|
+
if (isLikelyBinaryBuffer(buffer)) throw makeHttpError(415, "File appears to be binary; only text files can be opened in WebUI");
|
|
8297
|
+
}
|
|
8298
|
+
|
|
8299
|
+
async function getFileContentData(tab, requestedPath = "") {
|
|
8300
|
+
const resolved = await resolveWorkspacePath(tab, requestedPath);
|
|
8301
|
+
if (!resolved.info?.isFile()) throw makeHttpError(400, "Path is not a regular file");
|
|
8302
|
+
if (resolved.info.size > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `File is too large to open in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
|
|
8303
|
+
const buffer = await readFile(resolved.targetPath);
|
|
8304
|
+
assertTextFileBuffer(buffer);
|
|
8305
|
+
return {
|
|
8306
|
+
root: resolved.root,
|
|
8307
|
+
path: resolved.relative,
|
|
8308
|
+
name: path.basename(resolved.targetPath),
|
|
8309
|
+
content: buffer.toString("utf8"),
|
|
8310
|
+
size: resolved.info.size,
|
|
8311
|
+
mtimeMs: resolved.info.mtimeMs,
|
|
8312
|
+
extension: path.extname(resolved.targetPath).toLowerCase(),
|
|
8313
|
+
language: fileViewerLanguage(resolved.targetPath),
|
|
8314
|
+
};
|
|
8315
|
+
}
|
|
8316
|
+
|
|
8317
|
+
async function saveFileContentData(tab, body = {}) {
|
|
8318
|
+
if (typeof body.content !== "string") throw makeHttpError(400, "File content must be a string");
|
|
8319
|
+
if (body.content.includes("\0")) throw makeHttpError(400, "File content cannot contain null bytes");
|
|
8320
|
+
if (Buffer.byteLength(body.content, "utf8") > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `File is too large to save in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
|
|
8321
|
+
const resolved = await resolveWorkspacePath(tab, body.path || body.filePath || "");
|
|
8322
|
+
if (!resolved.info?.isFile()) throw makeHttpError(400, "Path is not a regular file");
|
|
8323
|
+
if (resolved.info.size > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `File is too large to save in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
|
|
8324
|
+
assertTextFileBuffer(await readFile(resolved.targetPath));
|
|
8325
|
+
const expectedMtimeMs = Number(body.mtimeMs);
|
|
8326
|
+
if (Number.isFinite(expectedMtimeMs) && Math.abs(resolved.info.mtimeMs - expectedMtimeMs) > 5) {
|
|
8327
|
+
throw makeHttpError(409, "File changed on disk after it was opened. Reopen it before saving.");
|
|
8328
|
+
}
|
|
8329
|
+
const tmpFile = `${resolved.targetPath}.${process.pid}.${Date.now()}.tmp`;
|
|
8330
|
+
try {
|
|
8331
|
+
await writeFile(tmpFile, body.content, { encoding: "utf8", mode: resolved.info.mode & 0o777 });
|
|
8332
|
+
await rename(tmpFile, resolved.targetPath);
|
|
8333
|
+
} catch (error) {
|
|
8334
|
+
await rm(tmpFile, { force: true }).catch(() => {});
|
|
8335
|
+
throw error;
|
|
8336
|
+
}
|
|
8337
|
+
const nextStats = await stat(resolved.targetPath);
|
|
8338
|
+
return {
|
|
8339
|
+
path: resolved.relative,
|
|
8340
|
+
name: path.basename(resolved.targetPath),
|
|
8341
|
+
size: nextStats.size,
|
|
8342
|
+
mtimeMs: nextStats.mtimeMs,
|
|
8343
|
+
extension: path.extname(resolved.targetPath).toLowerCase(),
|
|
8344
|
+
language: fileViewerLanguage(resolved.targetPath),
|
|
8345
|
+
};
|
|
8346
|
+
}
|
|
8347
|
+
|
|
8348
|
+
function defaultEditorCommand(targetPath) {
|
|
8349
|
+
if (platform() === "win32") return { command: "cmd", args: ["/c", "start", "", targetPath] };
|
|
8350
|
+
if (platform() === "darwin") return { command: "open", args: [targetPath] };
|
|
8351
|
+
return { command: process.env.PI_WEBUI_OPEN_COMMAND || "xdg-open", args: [targetPath] };
|
|
8352
|
+
}
|
|
8353
|
+
|
|
8354
|
+
function firstCommandOutputLine(value = "") {
|
|
8355
|
+
return String(value || "").split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "";
|
|
8356
|
+
}
|
|
8357
|
+
|
|
8358
|
+
async function queryXdgMime(args = [], cwd = options.cwd) {
|
|
8359
|
+
const result = await runCommand("xdg-mime", args, { cwd, timeoutMs: 1500, maxOutputLength: 4096 });
|
|
8360
|
+
if (result.exitCode !== 0) return "";
|
|
8361
|
+
return firstCommandOutputLine(result.stdout);
|
|
8362
|
+
}
|
|
8363
|
+
|
|
8364
|
+
async function linuxDefaultEditorCommand(targetPath, { cwd = options.cwd, isFile = true } = {}) {
|
|
8365
|
+
if (process.env.PI_WEBUI_OPEN_COMMAND) return defaultEditorCommand(targetPath);
|
|
8366
|
+
if (!isFile) return defaultEditorCommand(targetPath);
|
|
8367
|
+
const fileMime = await queryXdgMime(["query", "filetype", targetPath], cwd);
|
|
8368
|
+
const fileDefaultDesktop = fileMime ? await queryXdgMime(["query", "default", fileMime], cwd) : "";
|
|
8369
|
+
if (fileDefaultDesktop) return { command: "xdg-open", args: [targetPath], mime: fileMime, desktopFile: fileDefaultDesktop, fallbackToTextEditor: false };
|
|
8370
|
+
const textDefaultDesktop = await queryXdgMime(["query", "default", "text/plain"], cwd);
|
|
8371
|
+
if (textDefaultDesktop) {
|
|
8372
|
+
return { command: "gio", args: ["launch", textDefaultDesktop, targetPath], mime: fileMime, desktopFile: textDefaultDesktop, fallbackToTextEditor: true };
|
|
8373
|
+
}
|
|
8374
|
+
return { ...defaultEditorCommand(targetPath), mime: fileMime, fallbackToTextEditor: false };
|
|
8375
|
+
}
|
|
8376
|
+
|
|
8377
|
+
async function defaultEditorCommandForPath(targetPath, options = {}) {
|
|
8378
|
+
if (platform() === "linux") return linuxDefaultEditorCommand(targetPath, options);
|
|
8379
|
+
return defaultEditorCommand(targetPath);
|
|
8380
|
+
}
|
|
8381
|
+
|
|
8382
|
+
async function openPathInDefaultEditor(tab, requestedPath = "") {
|
|
8383
|
+
if (!String(requestedPath || "").trim()) throw makeHttpError(400, "Path to open is required");
|
|
8384
|
+
const resolved = await resolveWorkspacePath(tab, requestedPath);
|
|
8385
|
+
const { command, args, mime, desktopFile, fallbackToTextEditor } = await defaultEditorCommandForPath(resolved.targetPath, { cwd: resolved.root, isFile: !!resolved.info?.isFile?.() });
|
|
8386
|
+
const child = spawn(command, args, { cwd: resolved.root, stdio: "ignore", detached: true, windowsHide: true });
|
|
8387
|
+
child.on("error", () => {});
|
|
8388
|
+
child.unref?.();
|
|
8389
|
+
return { path: resolved.relative, command: [command, ...args].join(" "), mime, desktopFile, fallbackToTextEditor: !!fallbackToTextEditor };
|
|
8390
|
+
}
|
|
8391
|
+
|
|
8097
8392
|
function configuredSessionDir() {
|
|
8098
8393
|
for (let index = 0; index < options.piArgs.length; index++) {
|
|
8099
8394
|
const arg = options.piArgs[index];
|
|
@@ -8169,7 +8464,7 @@ function extractSessionTextContent(content) {
|
|
|
8169
8464
|
.map((part) => {
|
|
8170
8465
|
if (typeof part === "string") return part;
|
|
8171
8466
|
if (part?.type === "text" && typeof part.text === "string") return part.text;
|
|
8172
|
-
if (part?.type === "toolCall") return `[tool call: ${part.toolName || "tool"}]`;
|
|
8467
|
+
if (part?.type === "toolCall") return `[tool call: ${part.toolName || part.name || "tool"}]`;
|
|
8173
8468
|
if (part?.type === "thinking") return "[thinking]";
|
|
8174
8469
|
if (part?.type === "image") return "[image]";
|
|
8175
8470
|
return "";
|
|
@@ -8178,6 +8473,104 @@ function extractSessionTextContent(content) {
|
|
|
8178
8473
|
.join(" ");
|
|
8179
8474
|
}
|
|
8180
8475
|
|
|
8476
|
+
function generatedSessionEntryId(usedIds) {
|
|
8477
|
+
let id = "";
|
|
8478
|
+
do {
|
|
8479
|
+
id = randomUUID().replace(/-/g, "").slice(0, 8);
|
|
8480
|
+
} while (usedIds.has(id));
|
|
8481
|
+
usedIds.add(id);
|
|
8482
|
+
return id;
|
|
8483
|
+
}
|
|
8484
|
+
|
|
8485
|
+
async function writeForkedSessionFromEntries({ entries, targetLeafId, cwd, parentSession }) {
|
|
8486
|
+
const manager = SessionManager.create(cwd, configuredSessionDir(), { parentSession });
|
|
8487
|
+
const header = manager.getHeader();
|
|
8488
|
+
const sessionFile = manager.getSessionFile();
|
|
8489
|
+
if (!header || !sessionFile) throw new Error("Failed to create forked session metadata");
|
|
8490
|
+
|
|
8491
|
+
const outputEntries = [header];
|
|
8492
|
+
if (targetLeafId) {
|
|
8493
|
+
const byId = new Map(entries.map((entry) => [entry.id, entry]));
|
|
8494
|
+
const pathEntries = [];
|
|
8495
|
+
let current = byId.get(targetLeafId);
|
|
8496
|
+
while (current) {
|
|
8497
|
+
pathEntries.push(current);
|
|
8498
|
+
current = current.parentId ? byId.get(current.parentId) : undefined;
|
|
8499
|
+
}
|
|
8500
|
+
pathEntries.reverse();
|
|
8501
|
+
if (!pathEntries.length) throw makeHttpError(400, `Fork target entry not found in the active session: ${targetLeafId}`);
|
|
8502
|
+
|
|
8503
|
+
const pathWithoutLabels = [];
|
|
8504
|
+
let pathParentId = null;
|
|
8505
|
+
for (const entry of pathEntries) {
|
|
8506
|
+
if (entry.type === "label") continue;
|
|
8507
|
+
pathWithoutLabels.push({ ...entry, parentId: pathParentId });
|
|
8508
|
+
pathParentId = entry.id;
|
|
8509
|
+
}
|
|
8510
|
+
outputEntries.push(...pathWithoutLabels);
|
|
8511
|
+
|
|
8512
|
+
const pathEntryIds = new Set(pathWithoutLabels.map((entry) => entry.id));
|
|
8513
|
+
const labelsByTarget = new Map();
|
|
8514
|
+
const labelTimestampsByTarget = new Map();
|
|
8515
|
+
for (const entry of entries) {
|
|
8516
|
+
if (entry?.type !== "label" || !pathEntryIds.has(entry.targetId)) continue;
|
|
8517
|
+
if (entry.label) {
|
|
8518
|
+
labelsByTarget.set(entry.targetId, entry.label);
|
|
8519
|
+
labelTimestampsByTarget.set(entry.targetId, entry.timestamp);
|
|
8520
|
+
} else {
|
|
8521
|
+
labelsByTarget.delete(entry.targetId);
|
|
8522
|
+
labelTimestampsByTarget.delete(entry.targetId);
|
|
8523
|
+
}
|
|
8524
|
+
}
|
|
8525
|
+
|
|
8526
|
+
let labelParentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
|
|
8527
|
+
const usedIds = new Set([...pathEntryIds, header.id]);
|
|
8528
|
+
for (const [targetId, label] of labelsByTarget) {
|
|
8529
|
+
const labelEntry = {
|
|
8530
|
+
type: "label",
|
|
8531
|
+
id: generatedSessionEntryId(usedIds),
|
|
8532
|
+
parentId: labelParentId,
|
|
8533
|
+
timestamp: labelTimestampsByTarget.get(targetId) || new Date().toISOString(),
|
|
8534
|
+
targetId,
|
|
8535
|
+
label,
|
|
8536
|
+
};
|
|
8537
|
+
outputEntries.push(labelEntry);
|
|
8538
|
+
labelParentId = labelEntry.id;
|
|
8539
|
+
}
|
|
8540
|
+
}
|
|
8541
|
+
|
|
8542
|
+
await writeFile(sessionFile, `${outputEntries.map((entry) => JSON.stringify(entry)).join("\n")}\n`, { flag: "wx" });
|
|
8543
|
+
return sessionFile;
|
|
8544
|
+
}
|
|
8545
|
+
|
|
8546
|
+
async function createForkedSessionFile(tab, entryId) {
|
|
8547
|
+
requirePersistentSessions();
|
|
8548
|
+
const targetEntryId = String(entryId || "").trim();
|
|
8549
|
+
if (!targetEntryId) throw makeHttpError(400, "entryId is required");
|
|
8550
|
+
|
|
8551
|
+
const state = await currentSessionState(tab).catch(() => tab.lastState || {});
|
|
8552
|
+
if (state.isCompacting) throw makeHttpError(409, "Wait for compaction to finish before forking the session.");
|
|
8553
|
+
const parentSession = state.sessionFile || tabRestorableSessionFile(tab);
|
|
8554
|
+
|
|
8555
|
+
const entriesResponse = await safeRpcResponse(tab, { type: "get_entries" }, REQUEST_TIMEOUT_MS);
|
|
8556
|
+
if (entriesResponse.success === false) throw makeHttpError(400, entriesResponse.error || "failed to load session entries");
|
|
8557
|
+
const entries = Array.isArray(entriesResponse.data?.entries) ? entriesResponse.data.entries : [];
|
|
8558
|
+
const selectedEntry = entries.find((entry) => entry?.id === targetEntryId);
|
|
8559
|
+
if (!selectedEntry) throw makeHttpError(400, `Fork target entry not found in the active session: ${targetEntryId}`);
|
|
8560
|
+
if (selectedEntry.type !== "message" || selectedEntry.message?.role !== "user") {
|
|
8561
|
+
throw makeHttpError(400, "Fork point must be a user message");
|
|
8562
|
+
}
|
|
8563
|
+
|
|
8564
|
+
const text = extractSessionTextContent(selectedEntry.message.content).trim();
|
|
8565
|
+
const sessionFile = await writeForkedSessionFromEntries({
|
|
8566
|
+
entries,
|
|
8567
|
+
targetLeafId: selectedEntry.parentId || null,
|
|
8568
|
+
cwd: tab.cwd,
|
|
8569
|
+
parentSession,
|
|
8570
|
+
});
|
|
8571
|
+
return { sessionFile, text, parentSession, targetEntryId };
|
|
8572
|
+
}
|
|
8573
|
+
|
|
8181
8574
|
function sessionTreeEntryLabel(entry) {
|
|
8182
8575
|
if (!entry || typeof entry !== "object") return "entry";
|
|
8183
8576
|
if (entry.type === "message") return entry.message?.role || "message";
|
|
@@ -8249,18 +8642,26 @@ async function requireIdleForSessionAction(tab, actionLabel) {
|
|
|
8249
8642
|
}
|
|
8250
8643
|
|
|
8251
8644
|
async function runForkCommand(tab, entryId) {
|
|
8252
|
-
await
|
|
8253
|
-
const
|
|
8254
|
-
|
|
8255
|
-
|
|
8256
|
-
|
|
8257
|
-
|
|
8258
|
-
|
|
8645
|
+
const fork = await createForkedSessionFile(tab, entryId);
|
|
8646
|
+
const title = uniqueTabTitle(generatedTabTitleFromPrompt(fork.text) || `${tab.title || "Session"} fork`, null);
|
|
8647
|
+
const forkTab = await createTab({
|
|
8648
|
+
title,
|
|
8649
|
+
titleSource: title ? "auto" : undefined,
|
|
8650
|
+
conversationStarted: true,
|
|
8651
|
+
cwd: tab.cwd,
|
|
8652
|
+
sessionFile: fork.sessionFile,
|
|
8653
|
+
gitWorkspace: tab.gitWorkspace,
|
|
8654
|
+
});
|
|
8655
|
+
const forkTabMeta = tabMeta(forkTab);
|
|
8259
8656
|
return rpcSuccess("fork", {
|
|
8260
|
-
message:
|
|
8261
|
-
text:
|
|
8262
|
-
result:
|
|
8263
|
-
|
|
8657
|
+
message: "Forked the current session in a new terminal tab.",
|
|
8658
|
+
text: fork.text || "",
|
|
8659
|
+
result: { cancelled: false, text: fork.text || "", sessionFile: fork.sessionFile, targetEntryId: fork.targetEntryId },
|
|
8660
|
+
sessionFile: fork.sessionFile,
|
|
8661
|
+
parentSession: fork.parentSession,
|
|
8662
|
+
tab: forkTabMeta,
|
|
8663
|
+
tabs: listTabs(),
|
|
8664
|
+
sourceTab: tabMeta(tab),
|
|
8264
8665
|
});
|
|
8265
8666
|
}
|
|
8266
8667
|
|
|
@@ -9455,6 +9856,41 @@ const server = createServer(async (req, res) => {
|
|
|
9455
9856
|
return;
|
|
9456
9857
|
}
|
|
9457
9858
|
|
|
9859
|
+
if (url.pathname === "/api/files" && req.method === "GET") {
|
|
9860
|
+
const tab = getRequestedTab(req, url);
|
|
9861
|
+
sendJson(res, 200, { ok: true, data: await getFileTreeData(tab, url.searchParams.get("path") || "") });
|
|
9862
|
+
return;
|
|
9863
|
+
}
|
|
9864
|
+
|
|
9865
|
+
if (url.pathname === "/api/files/search" && req.method === "GET") {
|
|
9866
|
+
const tab = getRequestedTab(req, url);
|
|
9867
|
+
sendJson(res, 200, { ok: true, data: await getFileSearchData(tab, url.searchParams.get("q") || url.searchParams.get("query") || "") });
|
|
9868
|
+
return;
|
|
9869
|
+
}
|
|
9870
|
+
|
|
9871
|
+
if (url.pathname === "/api/files/content" && req.method === "GET") {
|
|
9872
|
+
const tab = getRequestedTab(req, url);
|
|
9873
|
+
sendJson(res, 200, { ok: true, data: await getFileContentData(tab, url.searchParams.get("path") || "") });
|
|
9874
|
+
return;
|
|
9875
|
+
}
|
|
9876
|
+
|
|
9877
|
+
if (url.pathname === "/api/files/content" && req.method === "POST") {
|
|
9878
|
+
requireLocalhostRoute(req, url.pathname);
|
|
9879
|
+
const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
|
|
9880
|
+
const tab = getRequestedTab(req, url, body);
|
|
9881
|
+
if (isNaturalConversationActive(tab)) throw makeHttpError(409, "file edits are blocked");
|
|
9882
|
+
sendJson(res, 200, { ok: true, data: await saveFileContentData(tab, body) });
|
|
9883
|
+
return;
|
|
9884
|
+
}
|
|
9885
|
+
|
|
9886
|
+
if (url.pathname === "/api/files/open-default" && req.method === "POST") {
|
|
9887
|
+
requireLocalhostRoute(req, url.pathname);
|
|
9888
|
+
const body = await readJsonBody(req);
|
|
9889
|
+
const tab = getRequestedTab(req, url, body);
|
|
9890
|
+
sendJson(res, 200, { ok: true, data: await openPathInDefaultEditor(tab, body.path || body.filePath || "") });
|
|
9891
|
+
return;
|
|
9892
|
+
}
|
|
9893
|
+
|
|
9458
9894
|
if (url.pathname === "/api/attachments" && req.method === "POST") {
|
|
9459
9895
|
const body = await readJsonBody(req, { limitBytes: requestBodyLimitForPath(url.pathname) });
|
|
9460
9896
|
const tab = getRequestedTab(req, url, body);
|
|
@@ -9501,7 +9937,7 @@ const server = createServer(async (req, res) => {
|
|
|
9501
9937
|
const tab = getRequestedTab(req, url, body);
|
|
9502
9938
|
ensureNaturalConversationRouteAllowed(tab, "session fork actions are blocked");
|
|
9503
9939
|
const response = await runForkCommand(tab, body.entryId);
|
|
9504
|
-
sendJson(res, response.success === false ? 400 : 200,
|
|
9940
|
+
sendJson(res, response.success === false ? 400 : 200, response);
|
|
9505
9941
|
return;
|
|
9506
9942
|
}
|
|
9507
9943
|
|
package/lib/trust-boundaries.mjs
CHANGED
|
@@ -18,6 +18,8 @@ export const LOCALHOST_ONLY_POST_ROUTES = new Map([
|
|
|
18
18
|
["/api/shutdown", "Shutdown is only allowed from localhost"],
|
|
19
19
|
["/api/optional-feature-install", "Installing optional Web UI features is only allowed from localhost"],
|
|
20
20
|
["/api/skill-file", "Saving skill files is only allowed from localhost"],
|
|
21
|
+
["/api/files/content", "Saving files from the Web UI is only allowed from localhost"],
|
|
22
|
+
["/api/files/open-default", "Opening files in the default editor is only allowed from localhost"],
|
|
21
23
|
["/api/session-delete", "Deleting sessions is only allowed from localhost"],
|
|
22
24
|
["/api/auth-logout", "Removing stored provider credentials is only allowed from localhost"],
|
|
23
25
|
]);
|
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.4",
|
|
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",
|
|
@@ -61,7 +61,7 @@
|
|
|
61
61
|
"optionalDependencies": {
|
|
62
62
|
"@firstpick/pi-extension-bang-command-autocomplete": "^0.2.1",
|
|
63
63
|
"@firstpick/pi-extension-btw": "^0.1.2",
|
|
64
|
-
"@firstpick/pi-extension-fish-user-bash": "^0.2.
|
|
64
|
+
"@firstpick/pi-extension-fish-user-bash": "^0.2.1",
|
|
65
65
|
"@firstpick/pi-extension-git-footer-status": "^0.3.6",
|
|
66
66
|
"@firstpick/pi-extension-release-aur": "^0.1.7",
|
|
67
67
|
"@firstpick/pi-extension-release-npm": "^0.4.0",
|