@firstpick/pi-package-webui 0.6.9 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/pi-webui.mjs CHANGED
@@ -4,7 +4,7 @@ import { createHash, randomInt, randomUUID, timingSafeEqual } from "node:crypto"
4
4
  import { createReadStream, readFileSync, realpathSync, statSync } from "node:fs";
5
5
  import { createServer } from "node:http";
6
6
  import { createRequire } from "node:module";
7
- import { access, copyFile, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
7
+ import { access, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
8
8
  import { homedir, networkInterfaces, platform, tmpdir } from "node:os";
9
9
  import path from "node:path";
10
10
  import { StringDecoder } from "node:string_decoder";
@@ -154,6 +154,9 @@ const ATTACHMENT_UPLOAD_MAX_FILE_BYTES = 64 * 1024 * 1024;
154
154
  const ATTACHMENT_UPLOAD_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
155
155
  const INLINE_IMAGE_MAX_BYTES = 8 * 1024 * 1024;
156
156
  const INLINE_IMAGE_TOTAL_MAX_BYTES = 16 * 1024 * 1024;
157
+ // Keep enough headroom for base64-encoded inline images plus their RPC envelope.
158
+ // Pi RPC output is JSONL, so this caps one physical line rather than a response.
159
+ const PI_RPC_JSONL_LINE_MAX_BYTES = 32 * 1024 * 1024;
157
160
  const RPC_IMAGE_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
158
161
  const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
159
162
  const SETTINGS_TRANSPORT_CHOICES = ["sse", "websocket", "websocket-cached", "auto"];
@@ -310,6 +313,7 @@ const OPTIONAL_FEATURE_PACKAGES = new Map([
310
313
  ["gitWorkflow", "@firstpick/pi-prompts-git-pr"],
311
314
  ["releaseNpm", "@firstpick/pi-extension-release-npm"],
312
315
  ["releaseAur", "@firstpick/pi-extension-release-aur"],
316
+ ["aurReview", "@firstpick/pi-extension-aur-review"],
313
317
  ["workflows", "@firstpick/pi-extension-workflows"],
314
318
  ["safetyGuard", "@firstpick/pi-extension-safety-guard"],
315
319
  ["tuiSkillsCommand", "@firstpick/pi-extension-setup-skills"],
@@ -634,6 +638,47 @@ async function installedPiReleaseNotes() {
634
638
  return piReleaseNotesCache;
635
639
  }
636
640
 
641
+ const stderrMirrorFailureListeners = new Set();
642
+ const stderrMirrorErrorHandlers = new WeakSet();
643
+
644
+ function ensureStderrMirrorErrorHandler(stream) {
645
+ if (stderrMirrorErrorHandlers.has(stream)) return;
646
+ stderrMirrorErrorHandlers.add(stream);
647
+ stream.on("error", (error) => {
648
+ // Do not log from this handler: stderr is the failing sink and recursive
649
+ // diagnostics can otherwise terminate the process. Active writers report
650
+ // the failure through their normal Web UI event path instead.
651
+ for (const reportFailure of [...stderrMirrorFailureListeners]) reportFailure(error);
652
+ });
653
+ }
654
+
655
+ function mirrorPiStderr(text, onFailure) {
656
+ const stream = process.stderr;
657
+ let reported = false;
658
+ const reportFailure = (error) => {
659
+ if (reported) return;
660
+ reported = true;
661
+ stderrMirrorFailureListeners.delete(reportFailure);
662
+ onFailure(error);
663
+ };
664
+
665
+ if (!stream?.writable || stream.destroyed || stream.writableEnded) {
666
+ reportFailure(new Error("Web UI stderr sink is not writable"));
667
+ return;
668
+ }
669
+
670
+ ensureStderrMirrorErrorHandler(stream);
671
+ stderrMirrorFailureListeners.add(reportFailure);
672
+ try {
673
+ stream.write(text, (error) => {
674
+ stderrMirrorFailureListeners.delete(reportFailure);
675
+ if (error) reportFailure(error);
676
+ });
677
+ } catch (error) {
678
+ reportFailure(error);
679
+ }
680
+ }
681
+
637
682
  class PiRpcProcess {
638
683
  constructor({ command, args, displayCommand, cwd, env = process.env }) {
639
684
  this.command = command;
@@ -645,6 +690,16 @@ class PiRpcProcess {
645
690
  this.pending = new Map();
646
691
  this.listeners = new Set();
647
692
  this.startedAt = new Date().toISOString();
693
+ this.stderrMirrorFailureReported = false;
694
+ }
695
+
696
+ reportStderrMirrorFailure(error) {
697
+ if (this.stderrMirrorFailureReported) return;
698
+ this.stderrMirrorFailureReported = true;
699
+ this.emit({
700
+ type: "pi_stderr_sink_error",
701
+ error: `Pi RPC stderr could not be mirrored to the Web UI server log: ${sanitizeError(error)}`,
702
+ });
648
703
  }
649
704
 
650
705
  start() {
@@ -669,8 +724,10 @@ class PiRpcProcess {
669
724
  this.attachJsonlReader(this.child.stdout, (line) => this.handleStdoutLine(line));
670
725
  this.attachTextReader(this.child.stderr, (text) => {
671
726
  if (text.length > 0) {
672
- process.stderr.write(text);
727
+ // Publish before attempting the optional terminal mirror so a closed
728
+ // stderr sink cannot hide Pi diagnostics from browser clients.
673
729
  this.emit({ type: "pi_stderr", text });
730
+ mirrorPiStderr(text, (error) => this.reportStderrMirrorFailure(error));
674
731
  }
675
732
  });
676
733
 
@@ -699,24 +756,56 @@ class PiRpcProcess {
699
756
  attachJsonlReader(stream, onLine) {
700
757
  const decoder = new StringDecoder("utf8");
701
758
  let buffer = "";
759
+ let bufferBytes = 0;
760
+ let discardingOversizedLine = false;
761
+
762
+ const emitOversizedLine = () => this.emit({
763
+ type: "pi_stdout_line_too_large",
764
+ error: `Discarded a Pi RPC JSONL line larger than ${PI_RPC_JSONL_LINE_MAX_BYTES} bytes`,
765
+ maxBytes: PI_RPC_JSONL_LINE_MAX_BYTES,
766
+ });
767
+ const consume = (chunk) => {
768
+ let input = chunk;
769
+ while (input.length > 0) {
770
+ if (discardingOversizedLine) {
771
+ const newlineIndex = input.indexOf("\n");
772
+ if (newlineIndex === -1) return;
773
+ discardingOversizedLine = false;
774
+ input = input.slice(newlineIndex + 1);
775
+ continue;
776
+ }
702
777
 
703
- stream.on("data", (chunk) => {
704
- buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
705
- while (true) {
706
- const newlineIndex = buffer.indexOf("\n");
707
- if (newlineIndex === -1) break;
708
- let line = buffer.slice(0, newlineIndex);
709
- buffer = buffer.slice(newlineIndex + 1);
778
+ const newlineIndex = input.indexOf("\n");
779
+ const segment = newlineIndex === -1 ? input : input.slice(0, newlineIndex);
780
+ const segmentBytes = Buffer.byteLength(segment);
781
+ if (bufferBytes + segmentBytes > PI_RPC_JSONL_LINE_MAX_BYTES) {
782
+ buffer = "";
783
+ bufferBytes = 0;
784
+ emitOversizedLine();
785
+ if (newlineIndex === -1) {
786
+ discardingOversizedLine = true;
787
+ return;
788
+ }
789
+ input = input.slice(newlineIndex + 1);
790
+ continue;
791
+ }
792
+
793
+ buffer += segment;
794
+ bufferBytes += segmentBytes;
795
+ if (newlineIndex === -1) return;
796
+ let line = buffer;
797
+ buffer = "";
798
+ bufferBytes = 0;
710
799
  if (line.endsWith("\r")) line = line.slice(0, -1);
711
800
  onLine(line);
801
+ input = input.slice(newlineIndex + 1);
712
802
  }
713
- });
803
+ };
714
804
 
805
+ stream.on("data", (chunk) => consume(typeof chunk === "string" ? chunk : decoder.write(chunk)));
715
806
  stream.on("end", () => {
716
- buffer += decoder.end();
717
- if (buffer.length > 0) {
718
- onLine(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
719
- }
807
+ consume(decoder.end());
808
+ if (!discardingOversizedLine && buffer.length > 0) onLine(buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer);
720
809
  });
721
810
  }
722
811
 
@@ -2009,6 +2098,9 @@ async function restoreGitWorkflowGenerationProfile(tab) {
2009
2098
 
2010
2099
  async function startGitWorkflowGeneration(tab, body = {}) {
2011
2100
  if (tab.gitWorkflowGenerationRestore) throw makeHttpError(409, "A guided Git generation request is already active in this tab");
2101
+ // Browser state is untrusted. When it claims an approved content token,
2102
+ // verify the exact current index again at this server action boundary.
2103
+ await assertExpectedStagedContentHash(tab, body);
2012
2104
  const preferences = await readGitWorkflowPreferences();
2013
2105
  if (!isGitWorkflowSetupComplete(preferences)) throw makeHttpError(409, "Run /git-workflow-setup or open Guided Git Setup before generating Git text");
2014
2106
 
@@ -4391,6 +4483,15 @@ let activeGitWorkflowProcess = null;
4391
4483
  const GIT_CHANGES_COMMAND_TIMEOUT_MS = 5000;
4392
4484
  const GIT_CHANGES_DIFF_MAX_OUTPUT = 500_000;
4393
4485
  const GIT_PULL_TIMEOUT_MS = 15 * 60 * 1000;
4486
+ // Must remain byte-for-byte aligned with pi-extension-aur-review/src/git.ts.
4487
+ const STAGED_CONTENT_HASH_DOMAIN = "firstpick/aur-review/staged-content/v1\0";
4488
+ const STAGED_CONTENT_HASH_TIMEOUT_MS = 10_000;
4489
+ const STAGED_CONTENT_HASH_OUTPUT_LIMIT = 4 * 1024 * 1024;
4490
+ const STAGED_CONTENT_HASH_ARGS = [
4491
+ "-c", "core.quotepath=false",
4492
+ "-c", "diff.external=",
4493
+ "diff", "--cached", "--binary", "--full-index", "--no-ext-diff", "--no-textconv", "--no-renames", "--",
4494
+ ];
4394
4495
  const GIT_STATUS_KIND_RANK = Object.freeze({ changed: 0, untracked: 1, modified: 2, staged: 3, conflicted: 4 });
4395
4496
 
4396
4497
  async function getGitRoot(cwd) {
@@ -4417,6 +4518,103 @@ async function runGitReadCommand(root, args, options = {}) {
4417
4518
  return (await runGitReadCommandDetailed(root, args, options)).output;
4418
4519
  }
4419
4520
 
4521
+ /**
4522
+ * Read binary cached-diff bytes without decoding them. This is intentionally
4523
+ * separate from runCommand(), whose string buffering is appropriate for UI
4524
+ * output but would corrupt the staged-content approval token.
4525
+ */
4526
+ function runGitStagedContentHashCommand(root) {
4527
+ return new Promise((resolve, reject) => {
4528
+ const child = spawn("git", STAGED_CONTENT_HASH_ARGS, {
4529
+ cwd: root,
4530
+ stdio: ["ignore", "pipe", "pipe"],
4531
+ windowsHide: true,
4532
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1", LC_ALL: "C" },
4533
+ });
4534
+ const stdout = [];
4535
+ const stderr = [];
4536
+ let stdoutBytes = 0;
4537
+ let stderrBytes = 0;
4538
+ let settled = false;
4539
+ const finish = (error, result) => {
4540
+ if (settled) return;
4541
+ settled = true;
4542
+ clearTimeout(timeout);
4543
+ if (error) reject(error);
4544
+ else resolve(result);
4545
+ };
4546
+ const stop = (message) => {
4547
+ try { child.kill("SIGKILL"); } catch { /* process already exited */ }
4548
+ finish(makeUserFacingError(message));
4549
+ };
4550
+ const timeout = setTimeout(() => stop(`git diff --cached timed out after ${STAGED_CONTENT_HASH_TIMEOUT_MS / 1000} seconds`), STAGED_CONTENT_HASH_TIMEOUT_MS);
4551
+ child.stdout.on("data", (chunk) => {
4552
+ const bytes = Buffer.from(chunk);
4553
+ stdoutBytes += bytes.length;
4554
+ if (stdoutBytes > STAGED_CONTENT_HASH_OUTPUT_LIMIT) {
4555
+ stop(`git diff --cached output exceeded the ${STAGED_CONTENT_HASH_OUTPUT_LIMIT / 1024 / 1024} MiB staged-content safety limit`);
4556
+ return;
4557
+ }
4558
+ stdout.push(bytes);
4559
+ });
4560
+ child.stderr.on("data", (chunk) => {
4561
+ const bytes = Buffer.from(chunk);
4562
+ stderrBytes += bytes.length;
4563
+ if (stderrBytes <= 64 * 1024) stderr.push(bytes);
4564
+ });
4565
+ child.on("error", (error) => finish(makeUserFacingError(formatCommandSpawnError("git", error))));
4566
+ child.on("close", (exitCode) => {
4567
+ if (exitCode !== 0) {
4568
+ const detail = Buffer.concat(stderr).toString("utf8").trim().slice(0, 1200);
4569
+ finish(makeUserFacingError(detail ? `git diff --cached failed: ${detail}` : `git diff --cached failed with exit code ${exitCode ?? "unknown"}`));
4570
+ return;
4571
+ }
4572
+ finish(null, Buffer.concat(stdout));
4573
+ });
4574
+ });
4575
+ }
4576
+
4577
+ function stagedContentHashFromDiff(stagedDiff) {
4578
+ return createHash("sha256").update(STAGED_CONTENT_HASH_DOMAIN).update(stagedDiff).digest("hex");
4579
+ }
4580
+
4581
+ async function readStagedContentHash(root) {
4582
+ // `git diff --cached` correctly compares the index to the empty tree when
4583
+ // HEAD is unborn, so no HEAD lookup is needed (or allowed) here.
4584
+ const stagedDiff = await runGitStagedContentHashCommand(root);
4585
+ return {
4586
+ stagedDiff,
4587
+ hasStagedChanges: stagedDiff.length > 0,
4588
+ stagedContentHash: stagedDiff.length > 0 ? stagedContentHashFromDiff(stagedDiff) : null,
4589
+ };
4590
+ }
4591
+
4592
+ /** Read-only same-tab digest of the exact staged content git can commit. */
4593
+ async function stagedContentHashForTab(tab) {
4594
+ const root = await getGitRoot(tab.cwd);
4595
+ const staged = await readStagedContentHash(root);
4596
+ return { root, hasStagedChanges: staged.hasStagedChanges, stagedContentHash: staged.stagedContentHash };
4597
+ }
4598
+
4599
+ function expectedStagedContentHashFromBody(body = {}) {
4600
+ const expected = body?.expectedStagedContentHash;
4601
+ if (expected === undefined) return ""; // Legacy Guided Git flow: no review was required.
4602
+ if (typeof expected !== "string" || !/^[a-f0-9]{64}$/i.test(expected)) {
4603
+ throw makeHttpError(400, "expectedStagedContentHash must be a SHA-256 hex digest");
4604
+ }
4605
+ return expected;
4606
+ }
4607
+
4608
+ async function assertExpectedStagedContentHash(tab, body = {}) {
4609
+ const expected = expectedStagedContentHashFromBody(body);
4610
+ if (!expected) return "";
4611
+ const current = await stagedContentHashForTab(tab);
4612
+ if (!current.hasStagedChanges || current.stagedContentHash !== expected) {
4613
+ throw makeHttpError(409, "Staged content changed after manual approval. Return to Stage and request a new manual review before continuing.");
4614
+ }
4615
+ return expected;
4616
+ }
4617
+
4420
4618
  function gitBranchFromPorcelainStatus(statusText) {
4421
4619
  for (const line of String(statusText || "").split(/\r?\n/)) {
4422
4620
  if (!line.startsWith("# branch.head ")) continue;
@@ -5952,18 +6150,17 @@ async function readGitWorkflowMessageFilesForTransfer(root, messageCwd = root) {
5952
6150
  return files;
5953
6151
  }
5954
6152
 
5955
- async function snapshotGitWorkflowBranchState(root, cwd = root) {
6153
+ async function snapshotGitWorkflowBranchState(root, cwd = root, expectedStagedContentHash = "") {
5956
6154
  const messageCwd = gitWorkflowMessageCwd(root, cwd);
5957
- const diffResult = await runGitWorkflowCommand(["diff", "--cached", "--binary", "--full-index"], {
5958
- cwd: root,
5959
- label: "git diff --cached --binary --full-index",
5960
- timeoutMs: 60 * 1000,
5961
- });
5962
- if (diffResult.exitCode !== 0 || diffResult.timedOut || diffResult.cancelled || diffResult.error) {
5963
- throw new Error((diffResult.stderr || diffResult.stdout || diffResult.error || "Unable to read staged changes for the PR worktree").trim());
6155
+ // Preserve raw patch bytes: string decoding would corrupt binary staged
6156
+ // changes before `git apply --index` can copy them to the PR worktree.
6157
+ const staged = await readStagedContentHash(root);
6158
+ if (expectedStagedContentHash && (!staged.hasStagedChanges || staged.stagedContentHash !== expectedStagedContentHash)) {
6159
+ throw makeHttpError(409, "Staged content changed after manual approval. Return to Stage and request a new manual review before creating a PR worktree.");
5964
6160
  }
5965
6161
  return {
5966
- stagedPatch: diffResult.stdout || "",
6162
+ stagedPatch: staged.stagedDiff,
6163
+ stagedContentHash: staged.stagedContentHash,
5967
6164
  messageFiles: await readGitWorkflowMessageFilesForTransfer(root, messageCwd),
5968
6165
  };
5969
6166
  }
@@ -5971,10 +6168,10 @@ async function snapshotGitWorkflowBranchState(root, cwd = root) {
5971
6168
  async function applyGitWorkflowBranchStateToWorktree(snapshot, worktreePath) {
5972
6169
  const copiedMessageFiles = [];
5973
6170
  let appliedStagedPatch = false;
5974
- const patchText = String(snapshot?.stagedPatch || "");
5975
- if (patchText.trim()) {
6171
+ const patchBytes = Buffer.isBuffer(snapshot?.stagedPatch) ? snapshot.stagedPatch : Buffer.alloc(0);
6172
+ if (patchBytes.length > 0) {
5976
6173
  const patchPath = path.join(tmpdir(), `pi-webui-staged-worktree-${process.pid}-${Date.now()}-${randomUUID()}.patch`);
5977
- await writeFile(patchPath, patchText, "utf8");
6174
+ await writeFile(patchPath, patchBytes);
5978
6175
  try {
5979
6176
  const applyResult = await runGitWorkflowCommand(["apply", "--index", "--whitespace=nowarn", patchPath], {
5980
6177
  cwd: worktreePath,
@@ -6020,7 +6217,8 @@ async function createGitWorkflowBranchWorktree(tab, body = {}) {
6020
6217
  const root = await getGitRoot(tab.cwd);
6021
6218
  const branch = cleanGitBranchName(body.branch || body.branchName);
6022
6219
  await validateGitBranchName(root, branch);
6023
- const snapshot = await snapshotGitWorkflowBranchState(root, tab.cwd);
6220
+ const expectedStagedContentHash = expectedStagedContentHashFromBody(body);
6221
+ const snapshot = await snapshotGitWorkflowBranchState(root, tab.cwd, expectedStagedContentHash);
6024
6222
  let createdResult = null;
6025
6223
  try {
6026
6224
  createdResult = await createGitWorktree(tab.cwd, { ...body, branchName: branch });
@@ -6225,6 +6423,7 @@ function gitWorkflowCommandPayload(result) {
6225
6423
  // guard are enforced at the router before dispatch — never dispatch on path
6226
6424
  // alone, or cross-origin GETs (image/script tags) could drive git mutations.
6227
6425
  const GIT_WORKFLOW_READONLY_PATHS = new Set([
6426
+ "/api/git-workflow/staged-content",
6228
6427
  "/api/git-workflow/message",
6229
6428
  "/api/git-workflow/default-commit-message",
6230
6429
  "/api/git-workflow/branch-name",
@@ -6252,6 +6451,9 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
6252
6451
  const cwd = tab?.cwd || tabOrCwd || options.cwd;
6253
6452
  try {
6254
6453
  switch (pathname) {
6454
+ case "/api/git-workflow/staged-content":
6455
+ if (!tab) throw new Error("Staged-content lookup requires a Web UI tab");
6456
+ return { ok: true, data: await stagedContentHashForTab(tab) };
6255
6457
  case "/api/git-workflow/message":
6256
6458
  return { ok: true, data: await readGitWorkflowMessages(cwd) };
6257
6459
  case "/api/git-workflow/default-commit-message":
@@ -6303,6 +6505,9 @@ async function handleGitWorkflowRequest(pathname, body = {}, tabOrCwd = options.
6303
6505
  case "/api/git-workflow/commit": {
6304
6506
  const variant = String(body.variant || "").trim();
6305
6507
  if (!["short", "long", "input"].includes(variant)) throw new Error("variant must be 'short', 'long', or 'input'");
6508
+ // Recheck here as well as in the browser. A staged index can change
6509
+ // between the browser's read-only check and this mutating request.
6510
+ await assertExpectedStagedContentHash(tab || { cwd }, body);
6306
6511
  if (variant === "input") {
6307
6512
  const root = await getGitRoot(cwd);
6308
6513
  const message = cleanGitCommitMessageInput(body.message);
@@ -6455,7 +6660,7 @@ async function readBundledThemes() {
6455
6660
  function normalizeStaticPath(urlPath) {
6456
6661
  if (urlPath === "/") return "index.html";
6457
6662
  const name = urlPath.startsWith("/") ? urlPath.slice(1) : urlPath;
6458
- if (!["index.html", "app.js", "voice-conversation.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
6663
+ if (!["index.html", "app.js", "voice-conversation.mjs", "aur-review-payload.mjs", "guided-git-command-state.mjs", "guided-git-review-state.mjs", "styles.css", "favicon.svg", "apple-touch-icon.png", "icon-192.png", "icon-512.png", "catppuccin-mocha-background.png", "matrix-background.webp", "manifest.webmanifest", "service-worker.js"].includes(name)) return undefined;
6459
6664
  return name;
6460
6665
  }
6461
6666
 
@@ -6892,9 +7097,11 @@ async function workspacePackageRootForName(packageName) {
6892
7097
  return null;
6893
7098
  }
6894
7099
  for (const entry of entries) {
7100
+ // Workspace package directories use the pi-* convention. Confirm every
7101
+ // eligible sibling by its manifest name, never the folder prefix alone.
6895
7102
  if (!entry.isDirectory() || !entry.name.startsWith("pi-")) continue;
6896
7103
  const candidate = path.join(root, entry.name);
6897
- if ((await packageNameForResourcePath(path.join(candidate, "index.ts"))) === packageName) return candidate;
7104
+ if ((await packageNameForResourcePath(path.join(candidate, "package.json"))) === packageName) return candidate;
6898
7105
  }
6899
7106
  return null;
6900
7107
  }
@@ -7495,7 +7702,7 @@ async function flushCompactionQueue(tab, event = {}) {
7495
7702
  let startedPrompt = false;
7496
7703
  while (remaining.length) {
7497
7704
  const item = remaining[0];
7498
- const command = startedPrompt ? queuedStreamingCommand(item) : queuedPromptCommand(item);
7705
+ const command = startedPrompt ? queuedRetryCommand(item) : queuedPromptCommand(item);
7499
7706
  if (!startedPrompt) {
7500
7707
  const pendingThinkingResponse = await applyPendingThinkingBeforePrompt(tab);
7501
7708
  if (pendingThinkingResponse?.success === false) throw new Error(pendingThinkingResponse.error || "failed to apply queued thinking level");
@@ -7833,7 +8040,7 @@ function attachRpcToTab(tab, rpc) {
7833
8040
  scopedEvent = { ...scopedEvent, tabActivity: tabActivitySnapshot(tab), pendingExtensionUiRequestCount: pendingExtensionUiRequests(tab).length };
7834
8041
  recordEvent(scopedEvent);
7835
8042
  for (const client of tab.sseClients) sendSse(client, scopedEvent);
7836
- if (event?.type === "compaction_end" && event.aborted !== true) void flushCompactionQueue(tab, event);
8043
+ if (event?.type === "compaction_end") void flushCompactionQueue(tab, event);
7837
8044
  if (event?.type === "agent_settled") void restoreGitWorkflowGenerationProfile(tab);
7838
8045
  });
7839
8046
  }
@@ -7962,6 +8169,79 @@ function webuiSubagentsData() {
7962
8169
  };
7963
8170
  }
7964
8171
 
8172
+ function normalizeWebuiSubagentTranscriptValue(value, maxLength = WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH) {
8173
+ return String(value ?? "").replace(/\r/g, "").slice(0, maxLength);
8174
+ }
8175
+
8176
+ function normalizeWebuiSubagentTranscriptLines(value) {
8177
+ return String(value ?? "").replace(/\r/g, "").split("\n").map((line) => line.slice(0, WEBUI_SUBAGENT_OUTPUT_LINE_LENGTH));
8178
+ }
8179
+
8180
+ function normalizeWebuiSubagentTranscript(value) {
8181
+ const messages = [];
8182
+ let remainingParts = WEBUI_SUBAGENT_OUTPUT_LINE_LIMIT;
8183
+ const rawMessages = Array.isArray(value) ? value : [];
8184
+ for (let messageIndex = rawMessages.length - 1; messageIndex >= 0 && remainingParts > 0; messageIndex -= 1) {
8185
+ const rawMessage = rawMessages[messageIndex];
8186
+ const role = rawMessage?.role;
8187
+ if (role !== "assistant" && role !== "toolResult") continue;
8188
+ const rawContent = Array.isArray(rawMessage.content) ? rawMessage.content : [{ type: "text", text: rawMessage.content }];
8189
+ const content = [];
8190
+ for (let partIndex = rawContent.length - 1; partIndex >= 0 && remainingParts > 0; partIndex -= 1) {
8191
+ const rawPart = rawContent[partIndex];
8192
+ if (role === "assistant" && rawPart?.type === "toolCall") {
8193
+ const name = normalizeWebuiSubagentText(rawPart.name || rawPart.toolName || rawPart.toolCall?.name, 120) || "tool";
8194
+ let argumentsText = "{}";
8195
+ try {
8196
+ const argumentsValue = rawPart.arguments ?? rawPart.args ?? rawPart.input ?? rawPart.toolCall?.arguments ?? {};
8197
+ argumentsText = normalizeWebuiSubagentTranscriptValue(typeof argumentsValue === "string" ? argumentsValue.replace(/\n/g, "\\n") : JSON.stringify(argumentsValue));
8198
+ } catch {
8199
+ // Keep the bounded placeholder when the helper received a cyclic value.
8200
+ }
8201
+ content.unshift({
8202
+ type: "toolCall",
8203
+ name,
8204
+ arguments: argumentsText,
8205
+ ...(normalizeWebuiSubagentText(rawPart.id || rawPart.toolCallId || rawPart.tool_call_id, 240) ? { id: normalizeWebuiSubagentText(rawPart.id || rawPart.toolCallId || rawPart.tool_call_id, 240) } : {}),
8206
+ });
8207
+ remainingParts -= 1;
8208
+ continue;
8209
+ }
8210
+ const type = role === "assistant" && rawPart?.type === "thinking" ? "thinking" : "text";
8211
+ if (rawPart?.type !== "text" && typeof rawPart !== "string" && type !== "thinking") continue;
8212
+ const rawText = typeof rawPart === "string"
8213
+ ? rawPart
8214
+ : type === "thinking" ? rawPart.thinking ?? rawPart.text ?? rawPart.content : rawPart.text ?? rawPart.content;
8215
+ if (typeof rawText !== "string") continue;
8216
+ const property = type === "thinking" ? "thinking" : "text";
8217
+ const lines = normalizeWebuiSubagentTranscriptLines(rawText);
8218
+ for (let lineIndex = lines.length - 1; lineIndex >= 0 && remainingParts > 0; lineIndex -= 1) {
8219
+ const line = lines[lineIndex];
8220
+ if (line.trim().toLowerCase() === "(no output)") continue;
8221
+ const previous = content[0];
8222
+ if (previous?.type === type) previous[property] = `${line}\n${previous[property]}`;
8223
+ else content.unshift({ type, [property]: line });
8224
+ remainingParts -= 1;
8225
+ }
8226
+ }
8227
+ if (!content.length) continue;
8228
+ const timestamp = Number.isFinite(rawMessage.timestamp)
8229
+ ? rawMessage.timestamp
8230
+ : normalizeWebuiSubagentText(rawMessage.timestamp, 128) || undefined;
8231
+ messages.unshift({
8232
+ role,
8233
+ ...(timestamp ? { timestamp } : {}),
8234
+ ...(role === "toolResult" ? {
8235
+ ...(normalizeWebuiSubagentText(rawMessage.toolCallId || rawMessage.tool_call_id, 240) ? { toolCallId: normalizeWebuiSubagentText(rawMessage.toolCallId || rawMessage.tool_call_id, 240) } : {}),
8236
+ ...(normalizeWebuiSubagentText(rawMessage.toolName || rawMessage.name, 120) ? { toolName: normalizeWebuiSubagentText(rawMessage.toolName || rawMessage.name, 120) } : {}),
8237
+ ...(rawMessage.isError === true ? { isError: true } : {}),
8238
+ } : {}),
8239
+ content,
8240
+ });
8241
+ }
8242
+ return messages;
8243
+ }
8244
+
7965
8245
  function normalizeWebuiSubagentOutput(value, selection) {
7966
8246
  if (!value || typeof value !== "object" || value.version !== 1) throw makeHttpError(502, "Invalid subagent output response from Web UI helper");
7967
8247
  const rawAgent = value.agent && typeof value.agent === "object" ? value.agent : {};
@@ -7973,6 +8253,7 @@ function normalizeWebuiSubagentOutput(value, selection) {
7973
8253
  args: normalizeWebuiSubagentText(entry?.args, 500),
7974
8254
  endMs: Number.isFinite(entry?.endMs) ? entry.endMs : undefined,
7975
8255
  })).filter((entry) => entry.tool);
8256
+ const transcript = normalizeWebuiSubagentTranscript(rawAgent.transcript);
7976
8257
  return {
7977
8258
  version: 1,
7978
8259
  runId: normalizeWebuiSubagentText(value.runId, 160) || selection.run.id,
@@ -7995,6 +8276,7 @@ function normalizeWebuiSubagentOutput(value, selection) {
7995
8276
  tokens: Number.isFinite(rawAgent.tokens) ? rawAgent.tokens : undefined,
7996
8277
  recentTools,
7997
8278
  recentOutput,
8279
+ transcript,
7998
8280
  error: normalizeWebuiSubagentText(rawAgent.error, 1000) || undefined,
7999
8281
  },
8000
8282
  };
@@ -9896,6 +10178,88 @@ async function getFileContentData(tab, requestedPath = "") {
9896
10178
  };
9897
10179
  }
9898
10180
 
10181
+ function aurReviewReportPathSegments(value = "") {
10182
+ const requested = String(value || "").trim();
10183
+ if (!requested || requested.length > 1024 || requested.includes("\0")) throw makeHttpError(400, "Report path must be a non-empty repo-root-relative path");
10184
+ if (path.isAbsolute(requested) || path.win32.isAbsolute(requested) || requested.includes("\\")) {
10185
+ throw makeHttpError(400, "Report path must be a repo-root-relative path");
10186
+ }
10187
+ const segments = requested.split("/");
10188
+ if (segments.some((segment) => !segment || segment === "." || segment === "..")) {
10189
+ throw makeHttpError(400, "Report path cannot contain traversal segments");
10190
+ }
10191
+ return segments;
10192
+ }
10193
+
10194
+ async function canonicalGitRootForTab(tab) {
10195
+ const root = await getGitRoot(tab.cwd);
10196
+ try {
10197
+ return await realpath(root);
10198
+ } catch {
10199
+ throw makeHttpError(404, "Git repository root is no longer accessible");
10200
+ }
10201
+ }
10202
+
10203
+ async function readBoundedAurReviewReport(targetPath) {
10204
+ const handle = await open(targetPath, "r");
10205
+ try {
10206
+ const info = await handle.stat();
10207
+ if (!info.isFile()) throw makeHttpError(400, "Report path is not a regular file");
10208
+ if (info.size > FILE_VIEWER_MAX_BYTES) throw makeHttpError(413, `Report is too large to open in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
10209
+ const chunks = [];
10210
+ let total = 0;
10211
+ while (true) {
10212
+ const remaining = FILE_VIEWER_MAX_BYTES + 1 - total;
10213
+ if (remaining <= 0) throw makeHttpError(413, `Report is too large to open in WebUI (limit ${formatBytes(FILE_VIEWER_MAX_BYTES)})`);
10214
+ const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, remaining));
10215
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, total);
10216
+ if (bytesRead === 0) break;
10217
+ chunks.push(chunk.subarray(0, bytesRead));
10218
+ total += bytesRead;
10219
+ }
10220
+ return { buffer: Buffer.concat(chunks, total), info };
10221
+ } finally {
10222
+ await handle.close().catch(() => {});
10223
+ }
10224
+ }
10225
+
10226
+ /** Read-only AUR-review report access rooted at the tab's canonical Git root. */
10227
+ async function getAurReviewReportContentData(tab, { path: requestedPath = "", repoRoot = "" } = {}) {
10228
+ if (typeof repoRoot !== "string" || !repoRoot || repoRoot.includes("\0")) {
10229
+ throw makeHttpError(400, "repoRoot is required for an AUR review report");
10230
+ }
10231
+ const root = await canonicalGitRootForTab(tab);
10232
+ if (repoRoot !== root) throw makeHttpError(403, "Report repoRoot does not match this tab's canonical Git root");
10233
+ const segments = aurReviewReportPathSegments(requestedPath);
10234
+ let targetPath = root;
10235
+ let info;
10236
+ for (const [index, segment] of segments.entries()) {
10237
+ targetPath = path.join(targetPath, segment);
10238
+ try {
10239
+ info = await lstat(targetPath);
10240
+ } catch (error) {
10241
+ throw makeHttpError(error?.code === "ENOENT" ? 404 : 400, `Report path not found: ${segments.join("/")}`);
10242
+ }
10243
+ if (info.isSymbolicLink()) throw makeHttpError(403, "Report path cannot contain symlinks");
10244
+ if (index < segments.length - 1 && !info.isDirectory()) throw makeHttpError(400, "Report path contains a non-directory component");
10245
+ }
10246
+ if (!info?.isFile()) throw makeHttpError(400, "Report path is not a regular file");
10247
+ const realTarget = await realpath(targetPath).catch(() => "");
10248
+ if (!realTarget || !pathInside(root, realTarget)) throw makeHttpError(403, "Resolved report path escapes the canonical Git root");
10249
+ const opened = await readBoundedAurReviewReport(targetPath);
10250
+ assertTextFileBuffer(opened.buffer);
10251
+ return {
10252
+ root,
10253
+ path: segments.join("/"),
10254
+ name: path.basename(targetPath),
10255
+ content: opened.buffer.toString("utf8"),
10256
+ size: opened.buffer.length,
10257
+ mtimeMs: opened.info.mtimeMs,
10258
+ extension: path.extname(targetPath).toLowerCase(),
10259
+ language: fileViewerLanguage(targetPath),
10260
+ };
10261
+ }
10262
+
9899
10263
  async function saveFileContentData(tab, body = {}) {
9900
10264
  if (typeof body.content !== "string") throw makeHttpError(400, "File content must be a string");
9901
10265
  if (body.content.includes("\0")) throw makeHttpError(400, "File content cannot contain null bytes");
@@ -11678,6 +12042,18 @@ const server = createServer(async (req, res) => {
11678
12042
  return;
11679
12043
  }
11680
12044
 
12045
+ if (url.pathname === "/api/aur-review/report-content" && req.method === "GET") {
12046
+ const tab = getRequestedTab(req, url);
12047
+ sendJson(res, 200, {
12048
+ ok: true,
12049
+ data: await getAurReviewReportContentData(tab, {
12050
+ path: url.searchParams.get("path") || "",
12051
+ repoRoot: url.searchParams.get("repoRoot") || "",
12052
+ }),
12053
+ });
12054
+ return;
12055
+ }
12056
+
11681
12057
  if (url.pathname === "/api/files/content" && req.method === "GET") {
11682
12058
  const tab = getRequestedTab(req, url);
11683
12059
  sendJson(res, 200, { ok: true, data: await getFileContentData(tab, url.searchParams.get("path") || "") });