pi-web-ui 0.113.0 → 0.113.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/CHANGELOG.md CHANGED
@@ -10,6 +10,32 @@
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ 暂无未发布内容。
14
+
15
+ ## [0.113.1] — 2026-10-29
16
+
17
+ ### Added
18
+
19
+ - **CLI 服务控制与配置管理页面入口**:`pi-web-ui server start/restart/install/status` 自动解析并打印本机访问地址、局域网(LAN)IP、生效的鉴权 Token 以及 `/setup` 管理入口(#783);服务控制套接字(control socket)新增 `authToken` 实时凭据查询。
20
+ - **文件预览与 Markdown 深度联动**:正文中的工作区文件链接点击直达内置文件预览弹窗,支持一键在浏览器打开并保持左键安全拦截;文件预览弹窗工具栏新增直接下载文件按钮(`FiDownload`)。
21
+ - **工具调用实时输出替换模式(#782)**:解决累积快照流(如 `bash` 等长输出工具)下客户端反复拼接导致的带宽放大与卡顿;支持 `mode: "replace"` 以及前端自愈识别。
22
+
23
+ ### Changed
24
+
25
+ - **系统对话框与扩展 UI 对齐**:`WebUIContext` 与协议支持结构化代码/命令预览(`structuredCode`),系统提示禁用数学公式渲染以防 Shell 环境变量被误判为公式;优化三段式弹窗布局,长正文滚动不挤压底部操作栏。
26
+ - **工具检查器增强**:针对 `grep` / `tool_search` 模式提取与标题匹配显示,支持正则/关键词高亮标签。
27
+ - **官方插件体系**:`voice-input` 升级至 v0.4.5,优化远程未配置/本地未就绪时的主动引导与引擎切换,适配 Transformers 语音转写入参。
28
+
29
+ ### Fixed
30
+
31
+ - **全屏与移动端文件预览排版**:优化移动端/平板设备下的抽屉间距与安全区贴边,固定关闭按钮防止窄屏被挤出视窗。
32
+ - **全局文件搜索与路径嗅探**:支持带波浪号(`~`)主目录路径与绝对路径的精确探测;修复长输出卡顿与控制台多余告警。
33
+
34
+ <!-- auto-i18n:start -->
35
+ ### i18n
36
+
37
+ - 本版无文案增量(相对 v0.113.0,已核查)。
38
+
13
39
  ## [0.113.0] — 2026-10-28
14
40
 
15
41
  ### Added
package/README.md CHANGED
@@ -78,13 +78,7 @@ pi-web-ui is a full-featured web interface and desktop workspace for the pi codi
78
78
 
79
79
  ### 🎬 Demo Video
80
80
 
81
- <p align="center">
82
- <a href="https://raw.githubusercontent.com/xing-shuyin/pi-web-ui/main/assets/demo-video.mp4">
83
- <img src="https://raw.githubusercontent.com/xing-shuyin/pi-web-ui/main/assets/demo-video-poster.png" alt="pi-web-ui demo video (click to play)" width="100%" style="max-width: 900px; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.35);" />
84
- </a>
85
- <br>
86
- <em>🎬 Click the preview above to play the full demo video directly in your browser (or right-click to save)</em>
87
- </p>
81
+ https://github.com/user-attachments/assets/ddb911ca-eb94-4adf-9455-2f15a64e835e
88
82
 
89
83
  ### 📸 Feature Highlights
90
84
 
package/README.zh-CN.md CHANGED
@@ -72,13 +72,7 @@ pi-web-ui 是基于 pi 智能体 SDK(`@earendil-works/pi-coding-agent`)与 D
72
72
 
73
73
  ### 🎬 演示视频
74
74
 
75
- <p align="center">
76
- <a href="https://raw.githubusercontent.com/xing-shuyin/pi-web-ui/main/assets/demo-video.mp4">
77
- <img src="https://raw.githubusercontent.com/xing-shuyin/pi-web-ui/main/assets/demo-video-poster.png" alt="pi-web-ui 操作演示视频(点击播放)" width="100%" style="max-width: 900px; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.35);" />
78
- </a>
79
- <br>
80
- <em>🎬 点击上方预览图直接在浏览器中播放完整操作演示视频(或右键另存为下载)</em>
81
- </p>
75
+ https://github.com/user-attachments/assets/ddb911ca-eb94-4adf-9455-2f15a64e835e
82
76
 
83
77
  ### 📸 功能截屏
84
78
 
package/README.zh-TW.md CHANGED
@@ -72,13 +72,7 @@ pi-web-ui 是基於 pi 代理 SDK(`@earendil-works/pi-coding-agent`)與 Deep
72
72
 
73
73
  ### 🎬 演示影片
74
74
 
75
- <p align="center">
76
- <a href="https://raw.githubusercontent.com/xing-shuyin/pi-web-ui/main/assets/demo-video.mp4">
77
- <img src="https://raw.githubusercontent.com/xing-shuyin/pi-web-ui/main/assets/demo-video-poster.png" alt="pi-web-ui 操作演示影片(點選播放)" width="100%" style="max-width: 900px; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.35);" />
78
- </a>
79
- <br>
80
- <em>🎬 點選上方預覽圖直接在瀏覽器中播放完整操作演示影片(或右鍵另存為下載)</em>
81
- </p>
75
+ https://github.com/user-attachments/assets/ddb911ca-eb94-4adf-9455-2f15a64e835e
82
76
 
83
77
  ### 📸 功能截圖
84
78
 
package/bin/pi-web-ui.mjs CHANGED
@@ -50,7 +50,7 @@ import {
50
50
  rmSync,
51
51
  writeFileSync,
52
52
  } from "node:fs";
53
- import { homedir, tmpdir, userInfo } from "node:os";
53
+ import { homedir, networkInterfaces, tmpdir, userInfo } from "node:os";
54
54
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
55
55
  import { pathToFileURL } from "node:url";
56
56
  import { fileURLToPath } from "node:url";
@@ -1338,10 +1338,10 @@ function installLaunchd(opts) {
1338
1338
  mkdirSync(dirname(plist), { recursive: true });
1339
1339
  writeFileSync(plist, content);
1340
1340
  run("launchctl", ["bootstrap", `gui/${uid()}`, plist]);
1341
+ if (opts.print) return;
1341
1342
  console.log(ZH ? `✅ 已安装并启动 launchd 服务 ${label}` : `✅ launchd service installed and started ${label}`);
1342
1343
  console.log(ZH ? ` 端口 : ${port}` : ` Port : ${port}`);
1343
1344
  console.log(ZH ? ` 目录 : ${cwd}` : ` Directory : ${cwd}`);
1344
- console.log(ZH ? ` 访问 : http://localhost:${port}` : ` URL : http://localhost:${port}`);
1345
1345
  console.log(
1346
1346
  ZH ? ` 日志 : /tmp/pi-web-ui.log /tmp/pi-web-ui.err` : ` Log : /tmp/pi-web-ui.log /tmp/pi-web-ui.err`,
1347
1347
  );
@@ -1399,7 +1399,6 @@ function installSystemd(opts) {
1399
1399
  );
1400
1400
  console.log(ZH ? ` 端口 : ${port}` : ` Port : ${port}`);
1401
1401
  console.log(ZH ? ` 目录 : ${cwd}` : ` Directory : ${cwd}`);
1402
- console.log(ZH ? ` 访问 : http://localhost:${port}` : ` URL : http://localhost:${port}`);
1403
1402
  console.log(ZH ? ` 日志 : journalctl -u ${name}.service -f` : ` Log : journalctl -u ${name}.service -f`);
1404
1403
  console.log(
1405
1404
  ZH
@@ -1495,7 +1494,6 @@ function installWindows(opts) {
1495
1494
  console.log(ZH ? ` 窗口 : wscript 隐藏启动,无黑窗` : ` Window : wscript hidden launch, no console`);
1496
1495
  console.log(ZH ? ` 端口 : ${port}` : ` Port : ${port}`);
1497
1496
  console.log(ZH ? ` 目录 : ${cwd}` : ` Directory : ${cwd}`);
1498
- console.log(ZH ? ` 访问 : http://localhost:${port}` : ` URL : http://localhost:${port}`);
1499
1497
  console.log(ZH ? ` 日志 : ${winLogPath(name)}` : ` Log : ${winLogPath(name)}`);
1500
1498
  console.log(
1501
1499
  ZH
@@ -1585,6 +1583,88 @@ function controlCommand(opts, cmd) {
1585
1583
  });
1586
1584
  }
1587
1585
 
1586
+ function isLocalLoopback(addr) {
1587
+ if (!addr) return false;
1588
+ const s = addr.trim().toLowerCase();
1589
+ return (
1590
+ s === "localhost" ||
1591
+ s.endsWith(".localhost") ||
1592
+ s === "127.0.0.1" ||
1593
+ s.startsWith("127.") ||
1594
+ s === "::1" ||
1595
+ s.startsWith("::ffff:127.")
1596
+ );
1597
+ }
1598
+
1599
+ function getLocalLanIpv4s() {
1600
+ const ips = [];
1601
+ try {
1602
+ const ifaces = networkInterfaces();
1603
+ for (const list of Object.values(ifaces)) {
1604
+ if (!list) continue;
1605
+ for (const iface of list) {
1606
+ if (iface && iface.family === "IPv4" && !iface.internal) {
1607
+ ips.push(iface.address);
1608
+ }
1609
+ }
1610
+ }
1611
+ } catch {
1612
+ // best-effort
1613
+ }
1614
+ return ips;
1615
+ }
1616
+
1617
+ /** 格式化打印服务的访问链接(包含本机、局域网 IP 与 Token / Setup 入口) */
1618
+ function printServiceUrls(port, host, token = "") {
1619
+ const tokenSuffix = token ? `?token=${token}` : "";
1620
+ const isLoopback = !host || isLocalLoopback(host);
1621
+ console.log(
1622
+ ZH
1623
+ ? ` 本机访问 : http://127.0.0.1:${port}/${tokenSuffix}`
1624
+ : ` Local URL : http://127.0.0.1:${port}/${tokenSuffix}`,
1625
+ );
1626
+
1627
+ if (!isLoopback) {
1628
+ const lanIps = getLocalLanIpv4s();
1629
+ if (lanIps.length > 0) {
1630
+ for (const ip of lanIps) {
1631
+ console.log(
1632
+ ZH
1633
+ ? ` 局域网 : http://${ip}:${port}/${tokenSuffix}`
1634
+ : ` LAN URL : http://${ip}:${port}/${tokenSuffix}`,
1635
+ );
1636
+ }
1637
+ } else if (host !== "0.0.0.0") {
1638
+ console.log(
1639
+ ZH
1640
+ ? ` 访问地址 : http://${host}:${port}/${tokenSuffix}`
1641
+ : ` Host URL : http://${host}:${port}/${tokenSuffix}`,
1642
+ );
1643
+ }
1644
+ }
1645
+ if (token) {
1646
+ console.log(ZH ? ` 访问密钥 : ${token}` : ` Token : ${token}`);
1647
+ }
1648
+ console.log(
1649
+ ZH
1650
+ ? ` 配置管理 : http://127.0.0.1:${port}/setup (仅本机)`
1651
+ : ` Setup : http://127.0.0.1:${port}/setup (local only)`,
1652
+ );
1653
+ }
1654
+
1655
+ /** 轮询等待后台服务就绪并打印包含实时 token 的访问信息 */
1656
+ async function printRunningServiceAccess(opts, host, fallbackToken = "") {
1657
+ const t0 = Date.now();
1658
+ let st = null;
1659
+ while (Date.now() - t0 < 3500) {
1660
+ st = await controlCommand(opts, "status");
1661
+ if (st && st.ok) break;
1662
+ await new Promise((r) => setTimeout(r, 200));
1663
+ }
1664
+ const token = (st && typeof st.authToken === "string" ? st.authToken : fallbackToken).trim();
1665
+ printServiceUrls(effectivePort(opts), host, token);
1666
+ }
1667
+
1588
1668
  /** Append the live server status (via the control socket) to `server status`. */
1589
1669
  async function printLiveStatus(opts) {
1590
1670
  const st = await controlCommand(opts, "status");
@@ -1597,6 +1677,10 @@ async function printLiveStatus(opts) {
1597
1677
  return;
1598
1678
  }
1599
1679
  console.log(ZH ? " --- 实时状态 (control socket) ---" : " --- live status (control socket) ---");
1680
+ if (st.authToken) {
1681
+ const host = process.env.PI_WEB_HOST || "";
1682
+ printServiceUrls(effectivePort(opts), host, st.authToken);
1683
+ }
1600
1684
  console.log(ZH ? ` 版本 : ${st.version} · PID ${st.pid}` : ` Version : ${st.version} · PID ${st.pid}`);
1601
1685
  console.log(ZH ? ` 目录 : ${st.cwd}` : ` Directory : ${st.cwd}`);
1602
1686
  // 启动来源(server/launch-origin.ts):有 supervisor = 这个进程退出后会被自动
@@ -3845,6 +3929,10 @@ async function serverCmd(argv) {
3845
3929
  ZH ? `不支持的系统服务平台: ${process.platform}` : `Unsupported system service platform: ${process.platform}`,
3846
3930
  );
3847
3931
  }
3932
+ if (!opts.print) {
3933
+ const fallbackToken = process.env.PI_WEB_TOKEN || "";
3934
+ await printRunningServiceAccess(opts, opts.host ?? process.env.PI_WEB_HOST, fallbackToken);
3935
+ }
3848
3936
  break;
3849
3937
  }
3850
3938
  case "uninstall": {
@@ -3862,8 +3950,13 @@ async function serverCmd(argv) {
3862
3950
  break;
3863
3951
  }
3864
3952
  case "start":
3953
+ case "restart": {
3954
+ controlService(action, opts);
3955
+ const fallbackToken = process.env.PI_WEB_TOKEN || "";
3956
+ await printRunningServiceAccess(opts, opts.host ?? process.env.PI_WEB_HOST, fallbackToken);
3957
+ break;
3958
+ }
3865
3959
  case "stop":
3866
- case "restart":
3867
3960
  controlService(action, opts);
3868
3961
  break;
3869
3962
  case "status":
@@ -0,0 +1,5 @@
1
+ 已在 commit 9e04e099 中彻底修复并闭环:
2
+
3
+ 1. **Markdown 链接与图片拦截转写**:在 `web/src/components/Markdown.tsx` 中拦截相对路径(如 `output/summary.md`)和绝对路径,自动转换为受鉴权保护的工作区直链(HTML 文件走 `/api/preview` 沙箱隔离预览,其他文件走 `/api/file` 原生打开/流式播放);
4
+ 2. **服务端直开权限完善**:更新 `server/index.ts` 放行合法工作区文本/数据文件(配合 `nosniff` 与沙箱),不再返回 400 阻断;
5
+ 3. **适配远程访问**:`present_files` 探测到远程访问时,自动将本地窗口唤醒按钮替换为新标签页打开。
@@ -4116,13 +4116,19 @@ export class ClientSession {
4116
4116
  case "tool_execution_update": {
4117
4117
  const text = extractPartialText(event.partialResult);
4118
4118
  if (text) {
4119
+ // issue #782: SDK onUpdate(partialResult) sends a cumulative snapshot (e.g. bash).
4120
+ // To avoid O(n^2) bandwidth inflation for long outputs while retaining realtime view,
4121
+ // slice the latest tail (64KB cap). Send with mode="replace" so the client replaces
4122
+ // rather than accumulating prev + delta.
4123
+ const safeText = text.length > 64 * 1024 ? text.slice(text.length - 64 * 1024) : text;
4119
4124
  this.emit({
4120
4125
  type: "tool_delta",
4121
4126
  conversationId: conv.id,
4122
4127
  seq: ++conv.deltaSeq,
4123
4128
  toolCallId: event.toolCallId,
4124
4129
  toolName: event.toolName,
4125
- delta: text,
4130
+ delta: safeText,
4131
+ mode: "replace",
4126
4132
  });
4127
4133
  }
4128
4134
  break;
@@ -49,7 +49,7 @@ export function controlPath(dataDir, port) {
49
49
  }
50
50
  /** Start the control socket; returns a stop function. */
51
51
  export function startControlServer(opts) {
52
- const { service, dataDir, port } = opts;
52
+ const { service, dataDir, port, authToken } = opts;
53
53
  const path = controlPath(dataDir, port);
54
54
  let server;
55
55
  // 只有本实例真正 bind 成功才允许 stop 时删 socket 文件:探测发现活实例而
@@ -127,7 +127,11 @@ export function startControlServer(opts) {
127
127
  let resp;
128
128
  switch (req.cmd) {
129
129
  case "status":
130
- resp = { ok: true, ...service.serviceStatus() };
130
+ resp = {
131
+ ok: true,
132
+ ...service.serviceStatus(),
133
+ ...(authToken ? { authToken: authToken() } : {}),
134
+ };
131
135
  break;
132
136
  case "quiesce":
133
137
  service.quiesce();
@@ -439,8 +439,8 @@ export class FilesService {
439
439
  }
440
440
  const { join } = await import("node:path");
441
441
  const fsp = await import("node:fs/promises");
442
- const q = query.trim().toLowerCase();
443
- if (!q) {
442
+ const rawQuery = query.trim();
443
+ if (!rawQuery) {
444
444
  this.host.emit({ type: "search_files_result", reqId, ok: true, results: [] });
445
445
  return;
446
446
  }
@@ -453,6 +453,49 @@ export class FilesService {
453
453
  const results = [];
454
454
  let visited = 0;
455
455
  let truncated = false;
456
+ // 1) 优先精确探测输入是否为已存在的绝对路径或相对路径
457
+ const normQuery = rawQuery.replace(/\\/g, "/");
458
+ const q = normQuery.toLowerCase();
459
+ try {
460
+ if (isAbsoluteWirePath(normQuery) ||
461
+ (normQuery.startsWith("~") && (normQuery === "~" || normQuery.startsWith("~/")))) {
462
+ const { homedir } = await import("node:os");
463
+ const home = homedir();
464
+ const targetAbs = normQuery.startsWith("~")
465
+ ? normQuery === "~"
466
+ ? home
467
+ : join(home, normQuery.slice(2))
468
+ : wireToAbs(normQuery);
469
+ const st = await fsp.stat(targetAbs).catch(() => null);
470
+ if (st) {
471
+ const wp = workspacePath(root, targetAbs);
472
+ const wirePath = wp ? wp.rel : targetAbs.split(sep).join("/");
473
+ const baseName = targetAbs.split(/[\\/]/).pop() || wirePath;
474
+ results.push({
475
+ path: wirePath,
476
+ name: baseName,
477
+ type: st.isDirectory() ? "dir" : "file",
478
+ });
479
+ }
480
+ }
481
+ else {
482
+ const directWp = workspacePath(root, normQuery);
483
+ if (directWp) {
484
+ const st = await fsp.stat(directWp.abs).catch(() => null);
485
+ if (st) {
486
+ const baseName = directWp.abs.split(/[\\/]/).pop() || directWp.rel;
487
+ results.push({
488
+ path: directWp.rel,
489
+ name: baseName,
490
+ type: st.isDirectory() ? "dir" : "file",
491
+ });
492
+ }
493
+ }
494
+ }
495
+ }
496
+ catch {
497
+ /* ignore probe failure */
498
+ }
456
499
  const budgetLeft = () => results.length < MAX_RESULTS && visited < MAX_VISITED && Date.now() - start < MAX_MS;
457
500
  // Breadth-first-ish iterative stack; depth cap is a symlink-cycle guard.
458
501
  const walk = async (abs, rel, depth) => {
@@ -487,7 +530,9 @@ export class FilesService {
487
530
  isDir = false; // broken link — treat as file
488
531
  }
489
532
  }
490
- if (d.name.toLowerCase().includes(q)) {
533
+ const childRelLower = childRel.toLowerCase();
534
+ const nameLower = d.name.toLowerCase();
535
+ if ((nameLower.includes(q) || childRelLower.includes(q)) && !results.some((r) => r.path === childRel)) {
491
536
  results.push({
492
537
  path: childRel,
493
538
  name: d.name,
@@ -1760,8 +1805,8 @@ export class FilesService {
1760
1805
  }
1761
1806
  }
1762
1807
  async searchRemoteFiles(rawCwd, query, reqId) {
1763
- const q = query.trim().toLowerCase();
1764
- if (!q) {
1808
+ const rawQuery = query.trim();
1809
+ if (!rawQuery) {
1765
1810
  this.host.emit({ type: "search_files_result", reqId, ok: true, results: [] });
1766
1811
  return;
1767
1812
  }
@@ -1771,17 +1816,36 @@ export class FilesService {
1771
1816
  return;
1772
1817
  }
1773
1818
  try {
1819
+ const normQuery = rawQuery.replace(/\\/g, "/");
1820
+ const q = normQuery.toLowerCase();
1821
+ const results = [];
1822
+ let truncated = false;
1823
+ // 优先精确检查直接目标
1824
+ const target = this.resolveRemoteTarget(rawCwd, normQuery);
1825
+ if (target) {
1826
+ try {
1827
+ const st = await sshSvc.sftpStat(rawCwd, target.abs);
1828
+ const name = posix.basename(target.abs) || target.rel;
1829
+ results.push({
1830
+ path: target.rel,
1831
+ name,
1832
+ type: st.isDirectory ? "dir" : "file",
1833
+ });
1834
+ }
1835
+ catch {
1836
+ /* ignore stat error */
1837
+ }
1838
+ }
1774
1839
  const cmd = `find . -maxdepth 8 \\( -name node_modules -o -name .git -o -name .pi-web \\) -prune -o -print 2>/dev/null | head -n 5000`;
1775
1840
  const res = await sshSvc.execInWorkspace(rawCwd, cmd, { timeoutMs: 8000 });
1776
1841
  const lines = res.stdout.split(/\r?\n/);
1777
- const results = [];
1778
- let truncated = false;
1779
1842
  for (const line of lines) {
1780
1843
  const clean = line.trim().replace(/^\.\//, "");
1781
1844
  if (!clean || clean === ".")
1782
1845
  continue;
1783
1846
  const name = posix.basename(clean);
1784
- if (name.toLowerCase().includes(q)) {
1847
+ if ((name.toLowerCase().includes(q) || clean.toLowerCase().includes(q)) &&
1848
+ !results.some((r) => r.path === clean)) {
1785
1849
  results.push({
1786
1850
  path: clean,
1787
1851
  name,
@@ -38,7 +38,6 @@ import { WS_MAX_PAYLOAD_BYTES, isAbsoluteWirePath, wireToAbs } from "./files-ser
38
38
  import { httpHostAllowed, isLoopbackHost, hostWithoutPort } from "./host-guard.js";
39
39
  import { registerFileTransferRoutes } from "./file-transfer-routes.js";
40
40
  import { initAttachmentStore, readAttachment } from "./attachment-store.js";
41
- import { isAudioFile, previewKind } from "./text-sniff.js";
42
41
  import { isOfficeFile, OFFICE_MAX_FILE_BYTES, unzipFiles } from "./office-parse.js";
43
42
  import { startControlServer } from "./control-socket.js";
44
43
  import { scheduleUploadCleanup } from "./uploads.js";
@@ -670,7 +669,7 @@ app.get("/api/file", async (req, res) => {
670
669
  const cs = cid ? service.get(cid) : undefined;
671
670
  const root = cs?.cwd ?? CWD;
672
671
  if (isRemoteWorkspaceUri(root)) {
673
- await serveRemoteWorkspaceFile(req, res, root, raw, { isDownload: req.query.download === "1", allowAllTypes: false }, remoteSshService);
672
+ await serveRemoteWorkspaceFile(req, res, root, raw, { isDownload: req.query.download === "1", allowAllTypes: true }, remoteSshService);
674
673
  return;
675
674
  }
676
675
  const absWire = isAbsoluteWirePath(raw);
@@ -687,18 +686,12 @@ app.get("/api/file", async (req, res) => {
687
686
  abs = wp.abs;
688
687
  }
689
688
  const name = basename(abs);
690
- const kind = previewKind(name);
691
689
  const isDownload = req.query.download === "1";
692
690
  // HTML files preview through a sandboxed <iframe> in the file modal
693
691
  // (FilePreview.tsx). They are text as far as previewKind goes, so
694
692
  // allowlist them explicitly here.
695
693
  const lower = name.toLowerCase();
696
694
  const isHtmlPreview = lower.endsWith(".html") || lower.endsWith(".htm") || lower.endsWith(".xhtml");
697
- const isAudioPreview = isAudioFile(name);
698
- if (!isDownload && kind !== "image" && kind !== "video" && !isHtmlPreview && !isAudioPreview) {
699
- res.status(400).end("not a previewable media file");
700
- return;
701
- }
702
695
  const st = await stat(abs);
703
696
  if (!st.isFile()) {
704
697
  res.status(400).end("not a file");
@@ -3157,7 +3150,12 @@ if (!bootCatalogDisabled) {
3157
3150
  }
3158
3151
  // Local control socket (status / quiesce / unquiesce) — same data dir the
3159
3152
  // CLI uses, so `pi-web-ui server status|quiesce|unquiesce` just works.
3160
- const stopControl = startControlServer({ service, dataDir: DATA_DIR, port: PORT });
3153
+ const stopControl = startControlServer({
3154
+ service,
3155
+ dataDir: DATA_DIR,
3156
+ port: PORT,
3157
+ authToken: () => AUTH_TOKEN,
3158
+ });
3161
3159
  /**
3162
3160
  * Graceful shutdown budget (issue #172): disposeAll() can hang forever on a
3163
3161
  * stuck session runtime / PTY / pending handle, and the process would then
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * 从 agent-service.ts 抽出,行为保持不变。
9
9
  */
10
- import { initTheme, Theme } from "@earendil-works/pi-coding-agent";
10
+ import { initTheme, Theme, } from "@earendil-works/pi-coding-agent";
11
11
  import { VirtualTuiBridge } from "./virtual-tui.js";
12
12
  // Ensure global theme is initialized so extensions calling getSettingsListTheme(),
13
13
  // getMarkdownTheme(), or touching global `theme` proxy don't throw.
@@ -223,17 +223,17 @@ export class WebUIContext {
223
223
  // -- dialogs (select/confirm/input bridged to the browser) ---------------
224
224
  dialogSeq = 0;
225
225
  pendingDialogs = new Map();
226
- select = (title, options) => this.openDialog("select", title, [options]);
227
- confirm = (title, message) => this.openDialog("confirm", title, [message]);
228
- input = (title, placeholder) => this.openDialog("input", title, [placeholder ?? ""]);
229
- openDialog(kind, title, args) {
226
+ select = (title, options, opts) => this.openDialog("select", title, [options], opts?.code);
227
+ confirm = (title, message, opts) => this.openDialog("confirm", title, [message], opts?.code);
228
+ input = (title, placeholder, opts) => this.openDialog("input", title, [placeholder ?? ""], opts?.code);
229
+ openDialog(kind, title, args, code) {
230
230
  // headless:没人能应答,立刻按「取消」结束(与 cancelPendingDialogs 同值)。
231
231
  if (this.headless)
232
232
  return Promise.resolve(null);
233
233
  return new Promise((resolve) => {
234
234
  const id = ++this.dialogSeq;
235
235
  this.pendingDialogs.set(id, resolve);
236
- this.emit({ type: "dialog", id, kind, title, args });
236
+ this.emit({ type: "dialog", id, kind, title, args, ...(code ? { code } : {}) });
237
237
  });
238
238
  }
239
239
  /** Resolve a pending dialog with the user's choice (called from the client). */
@@ -0,0 +1,9 @@
1
+ # 测试文件:验证远程直接访问与新标签页打开能力
2
+
3
+ 这是一份由测试生成的文档:
4
+ - **测试时间**:2025-05-18
5
+ - **服务状态**:已支持纯 Web 原生化文件直连
6
+ - **测试项目**:
7
+ 1. 普通 Markdown 文件链接
8
+ 2. HTML 报告测试
9
+ 3. present_files 工具卡片在远程与本地下的按钮适配
@@ -0,0 +1,11 @@
1
+ # 验证预览弹窗与下载功能
2
+
3
+ 这是一份测试产物,用于验证在对话中点击链接直接打开内置预览弹窗,并从弹窗顶栏下载文件:
4
+
5
+ - **测试项目**:
6
+ 1. 对话正文普通链接直接唤起预览弹窗
7
+ 2. 弹窗顶栏新增的「下载文件」按钮
8
+ 3. 复制内容与全屏等其他工具栏交互
9
+
10
+ 文件生成时间:2025-05-18
11
+ 环境:pi-web-ui 远程/本地自适应环境
@@ -0,0 +1,20 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title>远程 HTML 报告测试</title>
6
+ <style>
7
+ body { font-family: sans-serif; padding: 2rem; background: #0f172a; color: #f8fafc; }
8
+ .card { background: #1e293b; padding: 1.5rem; border-radius: 8px; border: 1px solid #334155; }
9
+ h1 { color: #38bdf8; }
10
+ button { background: #38bdf8; color: #0f172a; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; font-weight: bold; }
11
+ </style>
12
+ </head>
13
+ <body>
14
+ <div class="card">
15
+ <h1>🎉 远程 HTML 报告沙箱正常运行!</h1>
16
+ <p>这是一个能够完全在沙箱中交互并独立打开的 HTML 页面。</p>
17
+ <button onclick="alert('JS 在沙箱中正常触发!')">点击测试 JavaScript 交互</button>
18
+ </div>
19
+ </body>
20
+ </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-web-ui",
3
- "version": "0.113.0",
3
+ "version": "0.113.1",
4
4
  "description": "Just open your browser to get all your work done — browser cockpit for AI coding agents (chat, code, files, terminal, Git in one tab)",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -589,13 +589,27 @@ export interface MockHostControls {
589
589
 
590
590
  /** 浏览器桥兼容(client 侧逻辑单测也能用同一个 mock):无注入回退语义。 */
591
591
  export interface MockHostDialogs {
592
- select(opts: { title?: string; options?: unknown; [key: string]: unknown }): Promise<{
592
+ select(opts: {
593
+ title?: string;
594
+ options?: unknown;
595
+ code?: { content: string; language?: string; hasRisk?: boolean };
596
+ [key: string]: unknown;
597
+ }): Promise<{
593
598
  ok: boolean;
594
599
  selected?: string[];
595
600
  error?: string;
596
601
  }>;
597
- confirm(opts: { title?: string; text?: string; [key: string]: unknown }): Promise<boolean>;
598
- input(opts: { title?: string; [key: string]: unknown }): Promise<{ ok: boolean; value?: string }>;
602
+ confirm(opts: {
603
+ title?: string;
604
+ text?: string;
605
+ code?: { content: string; language?: string; hasRisk?: boolean };
606
+ [key: string]: unknown;
607
+ }): Promise<boolean>;
608
+ input(opts: {
609
+ title?: string;
610
+ code?: { content: string; language?: string; hasRisk?: boolean };
611
+ [key: string]: unknown;
612
+ }): Promise<{ ok: boolean; value?: string }>;
599
613
  }
600
614
 
601
615
  /** createMockHost 返回的 mock host(PluginHost 全量 + harness 字段 + 桥兼容)。 */
@@ -1,3 +1,3 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{i as t,t as n}from"./react-CR5VJ85Q.js";import{n as r,t as i}from"./xterm-Cf5xxe4g.js";import{a,c as o,d as s,f as c,g as l,h as u,i as d,l as f,m as p,o as m,p as h,r as g,s as _,t as v,u as y}from"./index-A8YXwnpZ.js";var b=e(t(),1);function x(e,t){return Math.abs(t)>10&&Math.abs(t)>Math.abs(e)*1.2}function S(e,t){return e-t}var C=n();function w(e){let t=null;return{clean:e.replace(/\r?\n?\[pi-term-exit:(-?\d+)\]\r?\n?/g,(e,n)=>(t=Number(n),`\r
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{i as t,t as n}from"./react-CR5VJ85Q.js";import{n as r,t as i}from"./xterm-Cf5xxe4g.js";import{a,c as o,d as s,f as c,g as l,h as u,i as d,l as f,m as p,o as m,p as h,r as g,s as _,t as v,u as y}from"./index-ByiO9f-N.js";var b=e(t(),1);function x(e,t){return Math.abs(t)>10&&Math.abs(t)>Math.abs(e)*1.2}function S(e,t){return e-t}var C=n();function w(e){let t=null;return{clean:e.replace(/\r?\n?\[pi-term-exit:(-?\d+)\]\r?\n?/g,(e,n)=>(t=Number(n),`\r
2
2
  `)).replace(/\r?\n?\x1b\[90m\[(?:进程已退出,退出码 |Process exited with code )-?\d+\]\x1b\[0m\r?\n?/g,`\r
3
3
  `),exitCode:t}}function T({conversationId:e,terminalId:t,command:n,cwd:o,title:s,agentBash:c,active:l,running:u,exitCode:f,register:p}){let h=(0,b.useRef)(null),_=(0,b.useRef)(null),{locale:v}=m(),y=(0,b.useRef)(v);y.current=v;let T=n?JSON.stringify(n):``,E=(0,b.useRef)(u===!1);(0,b.useEffect)(()=>{let u=h.current;if(!u)return;let f=new r({theme:a(),fontFamily:`"SF Mono", "JetBrains Mono", ui-monospace, Menlo, Consolas, monospace`,fontSize:13,cursorBlink:!0,scrollback:8e3}),m=new i;f.loadAddon(m),f.open(u),_.current={term:f,fit:m},l&&f.focus();let v=()=>{f.options.theme=a()};window.addEventListener(d,v),f.attachCustomKeyEventHandler(e=>{if(e.type!==`keydown`)return!0;let t=e.key?.toLowerCase();if((e.ctrlKey||e.metaKey)&&t===`v`)return!1;if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&t===`c`&&f.hasSelection()){let e=f.textarea;return e&&(e.value=f.getSelection(),e.select()),!1}return!0});let b=p(e,t,{write:e=>f.write(w(e).clean),dispose:()=>f.dispose()}),C=()=>{try{m.fit(),g({type:`terminal_resize`,terminalId:t,conversationId:e,cols:f.cols,rows:f.rows})}catch{}},T=requestAnimationFrame(()=>{try{m.fit()}catch{}E.current||g(n?{type:`run_command`,terminalId:t,conversationId:e,command:n,cols:f.cols,rows:f.rows}:{type:`terminal_create`,terminalId:t,title:s,locale:y.current,agentBash:c,conversationId:e,cwd:o,cols:f.cols,rows:f.rows})}),D=f.onData(n=>{g({type:`terminal_input`,terminalId:t,conversationId:e,data:n})}),O=f.element,k=null,A=0,j=0,M=0,N=!1,P=e=>{if(e.touches.length!==1){k=null,N=!1;return}let t=e.touches[0];k=t.identifier,A=t.clientX,j=t.clientY,M=t.clientY,N=!1},F=e=>{if(k===null||e.touches.length!==1)return;let t=e.touches[0];if(t.identifier!==k)return;if(!N){if(!x(t.clientX-A,t.clientY-j))return;N=!0}e.preventDefault();let n=S(M,t.clientY);M=t.clientY,n!==0&&typeof WheelEvent<`u`&&(u.querySelector(`.xterm-viewport`)??O)?.dispatchEvent(new WheelEvent(`wheel`,{bubbles:!0,cancelable:!0,deltaY:n,deltaMode:0,clientX:t.clientX,clientY:t.clientY}))},I=e=>{if(k!==null){if(e.touches.length>0){k=null,N=!1;return}k=null,N=!1}};O?.addEventListener(`touchstart`,P,{passive:!0}),O?.addEventListener(`touchmove`,F,{passive:!1}),O?.addEventListener(`touchend`,I),O?.addEventListener(`touchcancel`,I);let L=null;return typeof ResizeObserver<`u`&&(L=new ResizeObserver(()=>{u.offsetWidth>0&&u.offsetHeight>0&&C()}),L.observe(u)),()=>{cancelAnimationFrame(T),D.dispose(),O?.removeEventListener(`touchstart`,P),O?.removeEventListener(`touchmove`,F),O?.removeEventListener(`touchend`,I),O?.removeEventListener(`touchcancel`,I),window.removeEventListener(d,v),L?.disconnect(),b(),f.dispose(),_.current=null}},[e,t,T,p]),(0,b.useEffect)(()=>{if(!l)return;let n=requestAnimationFrame(()=>{let n=_.current;if(n){try{n.fit.fit(),g({type:`terminal_resize`,terminalId:t,conversationId:e,cols:n.term.cols,rows:n.term.rows})}catch{}n.term.focus()}});return()=>cancelAnimationFrame(n)},[l]);let{t:D}=m(),O=(0,b.useRef)(void 0);return(0,b.useEffect)(()=>{if(u===O.current||(O.current=u,u!==!1))return;let e=_.current;e&&e.term.write(`\r\n\x1b[90m${D(`exitBanner`,{code:f??``})}\x1b[0m\r\n`)},[u,t,f]),(0,C.jsx)(`div`,{ref:h,className:`term-xterm ${l?``:`hidden`}`})}var E={name:``,command:``,cwd:"${pwd}"};function D({chat:e,terminal:t,uiTerminalToolbar:n,onUiAction:r}){let i=_(),[a,d]=(0,b.useState)(null),[m,x]=(0,b.useState)(!1),[S,w]=(0,b.useState)(!1),[D,O]=(0,b.useState)(null),[k,A]=(0,b.useState)(E),[j,M]=(0,b.useState)(null),N=(0,b.useRef)(null),[P,F]=(0,b.useState)(!0),[I,L]=(0,b.useState)(null),[R,z]=(0,b.useState)(``);(0,b.useEffect)(()=>{e.terminals.length===0?d(null):e.terminals.some(e=>e.id===a)||d(e.terminals[e.terminals.length-1].id)},[e.terminals,a]),(0,b.useEffect)(()=>{e.terminalActiveId&&(d(e.terminalActiveId),x(!1))},[e.terminalActiveId]),(0,b.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]);let B=e.terminals.filter(e=>!e.agentBash),V=e.terminals.filter(e=>e.agentBash),H=n=>{if(!e.ready)return;let r=o(),i=e.activeConversationId||e.state?.conversationId||``;t.create({...n,id:r,conversationId:i,cols:n.cols??80,rows:n.rows??24,running:!0,exitCode:null}),d(r),x(!1)},U=()=>H({title:i(`terminalTitle`,{n:B.length+1}),cwd:e.state?.cwd??``}),W=n=>{let r=n.name||n.command,i=e.terminals.find(e=>e.title===r);if(i){t.restart(i.id),d(i.id),g({type:`run_command`,terminalId:i.id,conversationId:i.conversationId,command:n,cols:80,rows:24});return}H({title:r,cwd:e.state?.cwd??``,command:n})},G=n=>{let r=e.terminals.find(e=>e.id===n);if(r&&g({type:`terminal_kill`,terminalId:n,conversationId:r.conversationId}),t.close(n),a===n){let t=e.terminals.filter(e=>e.id!==n);d(t.length>0?t[t.length-1].id:null)}},K=e=>(0,C.jsxs)(`div`,{className:`term-tab ${e.id===a?`active`:``}`,children:[(0,C.jsxs)(`button`,{type:`button`,className:`term-tab-main`,title:`${e.cwd}${e.command?`\n> ${e.command.command}`:``}`,onClick:()=>{I||(d(e.id),x(!1))},children:[(0,C.jsx)(`span`,{className:`term-tab-dot ${e.running?`run`:`exit`}`}),(0,C.jsxs)(`span`,{className:`term-tab-title`,children:[I===e.id?(0,C.jsx)(`input`,{autoFocus:!0,className:`term-tab-rename-input`,value:R,placeholder:e.title,onClick:e=>e.stopPropagation(),onChange:e=>z(e.target.value),onKeyDown:t=>{if(t.stopPropagation(),t.key===`Enter`&&!t.nativeEvent.isComposing){let t=R.trim();t&&g({type:`rename_terminal`,terminalId:e.id,conversationId:e.conversationId,title:t}),L(null)}else t.key===`Escape`&&L(null)},onBlur:()=>L(null)}):e.title,!e.running&&(0,C.jsx)(`span`,{className:`term-tab-exit`,children:i(`exited`,{code:e.exitCode===null?``:` ${e.exitCode}`})})]})]}),(0,C.jsx)(`button`,{type:`button`,className:`term-tab-close term-tab-rename`,title:i(`renameTerminal`),onClick:t=>{t.stopPropagation(),z(e.title),L(e.id)},children:(0,C.jsx)(f,{})}),(0,C.jsx)(`button`,{type:`button`,className:`term-tab-close`,title:i(`closeTerminal`),onClick:()=>G(e.id),children:(0,C.jsx)(l,{})})]},e.id),q=()=>{w(!0),O(null),A(E)},ee=t=>{let n=e.commands[t];n&&(w(!1),O(t),A({name:n.name,command:n.command,cwd:n.cwd??``}))},J=()=>{w(!1),O(null)},Y=()=>{let t=k.name.trim(),n=k.command.trim();if(!t||!n)return;let r={name:t,command:n,cwd:k.cwd.trim()||void 0},i=S?[...e.commands,r]:D===null?e.commands:e.commands.map((e,t)=>t===D?r:e);g({type:`save_commands`,commands:i}),J()},te=t=>{if(j===t){let n=e.commands.filter((e,n)=>n!==t);g({type:`save_commands`,commands:n}),M(null),N.current&&clearTimeout(N.current)}else M(t),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>M(null),2500)},ne=S||D!==null,X=n===void 0?[`host:term-cmd-refresh`,`host:term-cmd-new`,`host:term-tab-new`].map(e=>({id:e,source:`host`})):n.filter(e=>!e.hidden),Z=(e,t)=>{let n=new Set(e);return X.filter(e=>n.has(e.id)||t&&e.source!==`host`)},Q=(e,t)=>{let n=X.find(t=>t.id===e);return n?.labelExplicit?n.label:t},$={"host:term-cmd-refresh":(0,C.jsx)(`button`,{type:`button`,className:`panel-refresh`,title:Q(`host:term-cmd-refresh`,i(`rerun`)),onClick:()=>g({type:`list_commands`}),children:(0,C.jsx)(h,{})}),"host:term-cmd-new":(0,C.jsx)(`button`,{type:`button`,className:`panel-new`,title:Q(`host:term-cmd-new`,i(`newCommand`)),onClick:q,children:(0,C.jsx)(c,{})}),"host:term-tab-new":(0,C.jsx)(`button`,{type:`button`,className:`panel-new`,title:Q(`host:term-tab-new`,i(`newTerminal`)),onClick:U,children:(0,C.jsx)(c,{})})};return(0,C.jsxs)(`div`,{className:`terminal-view`,children:[(0,C.jsxs)(`aside`,{className:`term-side term-commands ${m?`open`:``}`,children:[(0,C.jsxs)(`div`,{className:`panel-header`,children:[(0,C.jsx)(`span`,{className:`panel-title`,children:i(`commands`)}),(0,C.jsx)(`div`,{className:`panel-header-actions`,children:v(Z([`host:term-cmd-refresh`,`host:term-cmd-new`],!1),$,r)})]}),(0,C.jsx)(`div`,{className:`panel-body`,children:ne?(0,C.jsxs)(`div`,{className:`cmd-form`,children:[(0,C.jsx)(`label`,{htmlFor:`cmd-name`,children:i(`name`)}),(0,C.jsx)(`input`,{id:`cmd-name`,className:`cmd-input`,value:k.name,placeholder:i(`exampleName`),autoFocus:!0,onChange:e=>A({...k,name:e.target.value})}),(0,C.jsx)(`label`,{htmlFor:`cmd-command`,children:i(`command`)}),(0,C.jsx)(`input`,{id:`cmd-command`,className:`cmd-input`,value:k.command,placeholder:i(`exampleCommand`),onChange:e=>A({...k,command:e.target.value}),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&Y()}}),(0,C.jsxs)(`label`,{htmlFor:`cmd-cwd`,children:[i(`directory`),` `,(0,C.jsx)(`span`,{className:`cmd-hint`,children:i(`cwdHint`)})]}),(0,C.jsx)(`input`,{id:`cmd-cwd`,className:`cmd-input`,value:k.cwd,placeholder:"${pwd}",onChange:e=>A({...k,cwd:e.target.value}),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&Y()}}),(0,C.jsxs)(`div`,{className:`cmd-form-actions`,children:[(0,C.jsx)(`button`,{type:`button`,className:`btn`,onClick:J,children:i(`cancel`)}),(0,C.jsx)(`button`,{type:`button`,className:`btn primary`,disabled:!k.name.trim()||!k.command.trim(),onClick:Y,children:i(`save`)})]})]}):(0,C.jsxs)(C.Fragment,{children:[e.commands.length===0&&(0,C.jsx)(`div`,{className:`panel-empty`,children:i(`noCommands`)}),e.commands.map((e,t)=>(0,C.jsxs)(`div`,{className:`cmd-item`,children:[(0,C.jsx)(`button`,{type:`button`,className:`cmd-run`,title:i(`clickToRun`),onClick:()=>W(e),children:(0,C.jsx)(s,{})}),(0,C.jsxs)(`button`,{type:`button`,className:`cmd-main`,title:i(`clickToRun`),onClick:()=>W(e),children:[(0,C.jsx)(`span`,{className:`cmd-name`,children:e.name}),(0,C.jsx)(`span`,{className:`cmd-command`,children:e.command}),e.cwd&&(0,C.jsx)(`span`,{className:`cmd-cwd`,children:e.cwd})]}),(0,C.jsx)(`button`,{type:`button`,className:`cmd-act`,title:i(`edit`),onClick:()=>ee(t),children:(0,C.jsx)(f,{})}),(0,C.jsx)(`button`,{type:`button`,className:`cmd-act del ${j===t?`confirm`:``}`,title:i(`delete`),onClick:()=>te(t),children:j===t?i(`confirmQ`):(0,C.jsx)(u,{})})]},t))]})}),(0,C.jsxs)(`div`,{className:`term-tabs-block`,children:[(0,C.jsxs)(`div`,{className:`panel-header`,children:[(0,C.jsx)(`span`,{className:`panel-title`,children:i(`terminal`)}),v(Z([`host:term-tab-new`],!0),$,r)]}),(0,C.jsxs)(`div`,{className:`panel-body`,children:[e.terminals.length===0&&(0,C.jsx)(`div`,{className:`panel-empty`,children:i(`noTerminal`)}),B.map(K),V.length>0&&(0,C.jsxs)(`div`,{className:`term-folder`,children:[(0,C.jsxs)(`button`,{type:`button`,className:`term-folder-header ${P?`open`:``}`,title:i(`aiBashGroup`),onClick:()=>F(e=>!e),children:[(0,C.jsx)(`span`,{className:`term-folder-caret`,children:P?`▾`:`▸`}),(0,C.jsx)(`span`,{className:`term-folder-title`,children:i(`aiBashGroup`)}),(0,C.jsx)(`span`,{className:`term-folder-count`,children:V.length})]}),P&&(0,C.jsx)(`div`,{className:`term-folder-body`,children:V.map(K)})]})]})]})]}),(0,C.jsxs)(`div`,{className:`term-main`,children:[m&&(0,C.jsx)(`div`,{className:`drawer-backdrop`,onClick:()=>x(!1)}),(0,C.jsx)(`button`,{type:`button`,className:`term-side-toggle`,title:i(`commands`),onClick:()=>x(e=>!e),children:(0,C.jsx)(y,{})}),e.terminals.length===0?(0,C.jsxs)(`div`,{className:`term-empty`,children:[(0,C.jsx)(p,{className:`term-empty-icon`}),(0,C.jsx)(`div`,{className:`term-empty-title`,children:i(`builtinTerminal`)}),(0,C.jsx)(`div`,{className:`term-empty-sub`,children:i(`termEmptySub`)})]}):e.terminals.map(e=>(0,C.jsx)(T,{conversationId:e.conversationId,terminalId:e.id,command:e.command,cwd:e.cwd,title:e.title,agentBash:e.agentBash,active:e.id===a,running:e.running,exitCode:e.exitCode,register:t.register},e.id))]})]})}export{D as TerminalPanel};