pi-web-ui 0.109.0 → 0.111.0

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.
Files changed (96) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +21 -1
  3. package/README.zh-CN.md +21 -1
  4. package/README.zh-TW.md +201 -677
  5. package/bin/frp-manager.mjs +85 -7
  6. package/dist/server/agent-formatters.js +10 -6
  7. package/dist/server/agent-service-daemon.js +29 -11
  8. package/dist/server/agent-service.js +160 -54
  9. package/dist/server/attachments.js +140 -37
  10. package/dist/server/canvas/canvas-agent-tool.js +587 -0
  11. package/dist/server/canvas/canvas-cards.js +144 -0
  12. package/dist/server/canvas/canvas-dispatch.js +155 -0
  13. package/dist/server/canvas/canvas-orchestrator.js +1027 -0
  14. package/dist/server/canvas/canvas-store.js +260 -0
  15. package/dist/server/client-id-utils.js +2 -2
  16. package/dist/server/client-state.js +24 -0
  17. package/dist/server/context-budget.js +6 -3
  18. package/dist/server/dispatch-domain-handlers.js +2 -0
  19. package/dist/server/dispatch-plugin-handlers.js +1 -0
  20. package/dist/server/dsh/dsh-agent-service.js +115 -9
  21. package/dist/server/dsh/dsh-client.js +10 -1
  22. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  23. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  24. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  25. package/dist/server/durable/durable-agent-service.js +3 -0
  26. package/dist/server/durable/durable-driver.js +1 -1
  27. package/dist/server/durable/durable-tools.js +4 -1
  28. package/dist/server/file-transfer-routes.js +8 -2
  29. package/dist/server/files-service.js +33 -6
  30. package/dist/server/goal-service.js +12 -3
  31. package/dist/server/index.js +175 -13
  32. package/dist/server/locales.js +33 -0
  33. package/dist/server/marker-service.js +10 -14
  34. package/dist/server/markers/builtins/action.js +5 -6
  35. package/dist/server/markers/builtins/notify.js +2 -2
  36. package/dist/server/markers/builtins/rename.js +2 -2
  37. package/dist/server/markers/marker.js +45 -4
  38. package/dist/server/markers/registry.js +36 -1
  39. package/dist/server/message-window.js +193 -0
  40. package/dist/server/model-admin.js +0 -4
  41. package/dist/server/office-parse.js +394 -7
  42. package/dist/server/plugin-api-catalog.js +6 -0
  43. package/dist/server/plugin-catalog-sync.js +10 -2
  44. package/dist/server/plugin-catalog.js +63 -10
  45. package/dist/server/plugins.js +144 -26
  46. package/dist/server/preset-fields.js +35 -1
  47. package/dist/server/preset-share.js +5 -3
  48. package/dist/server/process-utils.js +58 -24
  49. package/dist/server/prompt-assembler.js +7 -1
  50. package/dist/server/prompt-composer.js +66 -36
  51. package/dist/server/protocol-version.js +1 -1
  52. package/dist/server/remote-ssh-service.js +16 -4
  53. package/dist/server/settings-service.js +24 -3
  54. package/dist/server/slash-commands.js +16 -4
  55. package/dist/server/text-sniff.js +10 -7
  56. package/dist/server/themes.js +36 -1
  57. package/dist/server/tool-manager.js +30 -0
  58. package/dist/server/univer-service.js +448 -0
  59. package/dist/server/universal/drivers/claude-code.js +19 -2
  60. package/dist/server/universal/drivers/dsh-driver.js +1 -1
  61. package/dist/server/universal/universal-attachments.js +5 -0
  62. package/dist/server/universal/universal-service.js +5 -0
  63. package/dist/server/universal/universal-session.js +38 -15
  64. package/dist/server/update-check.js +90 -5
  65. package/dist/server/workspace-snapshot.js +33 -2
  66. package/dist/server/worktree-service.js +1 -1
  67. package/docs/dsh-engine.md +497 -0
  68. package/package.json +11 -5
  69. package/plugin-sdk/index.d.ts +37 -0
  70. package/plugin-sdk/index.mjs +19 -0
  71. package/plugins/catalog.json +44 -2
  72. package/themes/aetheris.css +263 -118
  73. package/themes/bases/flow-base.css +1363 -0
  74. package/themes/bases/obsidian-base.css +895 -0
  75. package/themes/bases/zhujian-base.css +687 -0
  76. package/themes/bases/zhupi-base.css +659 -0
  77. package/themes/flow-light.css +2 -925
  78. package/themes/flow.css +1 -936
  79. package/themes/md-preview.css +113 -0
  80. package/themes/wallpaper-flow.css +251 -1029
  81. package/themes/wallpaper-obsidian.css +1 -673
  82. package/themes/zhujian-dark.css +1 -605
  83. package/themes/zhujian.css +1 -654
  84. package/themes/zhupi-dark.css +1 -576
  85. package/themes/zhupi.css +1 -626
  86. package/web/dist/assets/{TerminalPanel-BD3a9o-a.js → TerminalPanel-BiUNySMA.js} +2 -2
  87. package/web/dist/assets/index-B0ajS__T.js +697 -0
  88. package/web/dist/assets/index-BHik5WGG.css +1 -0
  89. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  90. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  91. package/web/dist/index.html +4 -4
  92. package/web/dist/sw.js +1 -1
  93. package/web/dist/assets/es-DIDZppIF.js +0 -2
  94. package/web/dist/assets/index-AccytlpP.css +0 -1
  95. package/web/dist/assets/index-B3dar1BK.js +0 -690
  96. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -10,7 +10,10 @@ import { loadDurableModule } from "./durable-loader.js";
10
10
  /**
11
11
  * 为指定工作区配置 Durable Registry 和工具链。
12
12
  */
13
- export async function setupDurableRegistry(cwd, options) {
13
+ export async function setupDurableRegistry(cwd,
14
+ // 预留位(尚未消费):`allowDangerous` / `onToolOutput` 现在没有任何实现,
15
+ // 保留参数形状,后续接线时不必改调用方。
16
+ _options) {
14
17
  const durableModule = await loadDurableModule().catch(() => null);
15
18
  if (!durableModule || typeof durableModule.createRegistry !== "function") {
16
19
  throw new Error("Pi Durable 依赖未安装。请运行 npm i -g @earendil-works/pi-durable 启用该引擎。");
@@ -31,8 +31,14 @@ export function registerFileTransferRoutes(app, getCwd, temporaryRoot = tmpdir()
31
31
  const parsed = parseRemoteWorkspaceUri(cwd);
32
32
  if (!parsed)
33
33
  throw new Error("Invalid remote workspace");
34
- const trimmed = raw.trim();
35
- if (!trimmed) {
34
+ let trimmed = raw.trim();
35
+ if (isRemoteWorkspaceUri(trimmed)) {
36
+ const parsedRaw = parseRemoteWorkspaceUri(trimmed);
37
+ if (parsedRaw) {
38
+ trimmed = parsedRaw.remotePath;
39
+ }
40
+ }
41
+ if (!trimmed || trimmed === ".") {
36
42
  if (!allowRoot)
37
43
  throw new Error("Invalid path");
38
44
  return parsed.remotePath;
@@ -12,7 +12,7 @@ import { pick } from "./i18n.js";
12
12
  import { previewKind, looksLikeText, decodeText, hexDump, countLines } from "./text-sniff.js";
13
13
  import { extractOfficeText, isOfficeFile, OFFICE_MAX_FILE_BYTES } from "./office-parse.js";
14
14
  import { gitDirOf, isNotRepoError, scmStatus, scmHistory, scmFileDiff, scmCommitDetail } from "./scm.js";
15
- import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, resolveRemoteWorkspacePath, shellQuotePosix, } from "./remote-ssh-service.js";
15
+ import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, resolveRemoteWorkspacePath, } from "./remote-ssh-service.js";
16
16
  export const IS_WIN32 = process.platform === "win32";
17
17
  /** 机器根虚拟路径:工作区「上一级」到达此处,列出所有盘符(Windows)/ "/"(posix)。
18
18
  * 这是 wire 字面量,前端 web/src/components/{RightPanel,FooterBar}.tsx 里同值使用。 */
@@ -381,6 +381,16 @@ export class FilesService {
381
381
  }
382
382
  // ---- 工作区相对视图(原有行为) ----
383
383
  const target = raw ? resolve(root, raw) : root;
384
+ // 若工作区根目录自身尚不存在,自动自愈创建,避免首帧报错
385
+ if (raw === "") {
386
+ try {
387
+ const fsp = await import("node:fs/promises");
388
+ await fsp.mkdir(target, { recursive: true });
389
+ }
390
+ catch {
391
+ /* ignore if exists */
392
+ }
393
+ }
384
394
  const rawRel = relative(root, target);
385
395
  if (rawRel.startsWith("..") || rawRel.includes(`${sep}..`)) {
386
396
  this.host.emit({
@@ -821,6 +831,7 @@ export class FilesService {
821
831
  kind: "text",
822
832
  lines: countLines(Buffer.from(office.text)),
823
833
  size: stat.size,
834
+ slides: office.slides,
824
835
  });
825
836
  return;
826
837
  }
@@ -1177,8 +1188,17 @@ export class FilesService {
1177
1188
  /** destDir(wire,空串 = 工作区根)→ 原生绝对目录;不存在/非目录 → null(调用方报错)。 */
1178
1189
  async resolveOpDir(dir) {
1179
1190
  const fsp = await import("node:fs/promises");
1180
- if (!dir.trim())
1181
- return { abs: resolve(this.host.getCwd()), wire: "" };
1191
+ if (!dir.trim()) {
1192
+ const rootAbs = resolve(this.host.getCwd());
1193
+ // 工作区根目录在首次运行可能尚未落地,自愈创建以确保后续操作成功
1194
+ try {
1195
+ await fsp.mkdir(rootAbs, { recursive: true });
1196
+ }
1197
+ catch {
1198
+ /* ignore if exists */
1199
+ }
1200
+ return { abs: rootAbs, wire: "" };
1201
+ }
1182
1202
  const t = this.resolveOpTarget(dir);
1183
1203
  if (!t)
1184
1204
  return null;
@@ -1214,7 +1234,7 @@ export class FilesService {
1214
1234
  return;
1215
1235
  }
1216
1236
  if (kind === "dir")
1217
- await fsp.mkdir(abs);
1237
+ await fsp.mkdir(abs, { recursive: true });
1218
1238
  else
1219
1239
  await fsp.writeFile(abs, "");
1220
1240
  this.host.emit({
@@ -1614,10 +1634,16 @@ export class FilesService {
1614
1634
  const parsed = parseRemoteWorkspaceUri(rawCwd);
1615
1635
  if (!parsed)
1616
1636
  return null;
1617
- const trimmed = (p || "").trim();
1637
+ let trimmed = (p || "").trim();
1618
1638
  if (trimmed === MACHINE_ROOT || trimmed === MACHINE_ROOT + "/")
1619
1639
  return null;
1620
- if (!trimmed) {
1640
+ if (isRemoteWorkspaceUri(trimmed)) {
1641
+ const parsedUri = parseRemoteWorkspaceUri(trimmed);
1642
+ if (parsedUri) {
1643
+ trimmed = parsedUri.remotePath;
1644
+ }
1645
+ }
1646
+ if (!trimmed || trimmed === ".") {
1621
1647
  if (!allowRoot)
1622
1648
  return null;
1623
1649
  return { abs: parsed.remotePath, rel: "", parentRel: "", absolute: false };
@@ -1820,6 +1846,7 @@ export class FilesService {
1820
1846
  kind: "text",
1821
1847
  lines: countLines(Buffer.from(office.text)),
1822
1848
  size: st.size,
1849
+ slides: office.slides,
1823
1850
  });
1824
1851
  return;
1825
1852
  }
@@ -745,6 +745,7 @@ export class GoalService {
745
745
  let refinedGoal = "";
746
746
  let parsedSteps = [];
747
747
  let goalEphemeralDir;
748
+ let srvSession;
748
749
  try {
749
750
  const wmSpec = opts?.wizardModel ? parseModelSpec(opts.wizardModel) : null; // "provider/id" 解析(唯一事实源)
750
751
  const services = await createAgentSessionServices({
@@ -907,6 +908,7 @@ export class GoalService {
907
908
  tools: ["goal_ask", "read", "ls", "find", "grep"],
908
909
  ...(model ? { model } : {}),
909
910
  });
911
+ srvSession = srv.session;
910
912
  const wizard = srv.session;
911
913
  this.wizardSession = wizard;
912
914
  await wizard.bindExtensions({ mode: "rpc", uiContext: this.host.webUi });
@@ -977,7 +979,6 @@ export class GoalService {
977
979
  const parsed = parseWizardOutput(rawAssistantText);
978
980
  refinedGoal = parsed.goal;
979
981
  parsedSteps = parsed.steps;
980
- await srv.session.dispose();
981
982
  }
982
983
  catch (err) {
983
984
  this.host.emit({
@@ -998,6 +999,13 @@ export class GoalService {
998
999
  wgoal.wizard.status = "";
999
1000
  wgoal.wizard.statusEn = "";
1000
1001
  this.wizardSession = null;
1002
+ this.wizardAbort = null;
1003
+ if (srvSession) {
1004
+ try {
1005
+ await srvSession.dispose();
1006
+ }
1007
+ catch { }
1008
+ }
1001
1009
  if (goalEphemeralDir) {
1002
1010
  try {
1003
1011
  rmSync(goalEphemeralDir, { recursive: true, force: true });
@@ -1018,7 +1026,6 @@ export class GoalService {
1018
1026
  textEn: `Goal survey cancelled${ac.signal.reason ? `: ${String(ac.signal.reason?.message ?? ac.signal.reason)}` : ""}` +
1019
1027
  `. The initial goal draft is preserved in the conversation "${wizardConversationTitle}" — copy it and start over.`,
1020
1028
  });
1021
- this.wizardAbort = null;
1022
1029
  return;
1023
1030
  }
1024
1031
  if (!refinedGoal.trim()) {
@@ -1066,7 +1073,6 @@ export class GoalService {
1066
1073
  autoStart: false,
1067
1074
  });
1068
1075
  this.wizardCancelled = false;
1069
- this.wizardAbort = null;
1070
1076
  this.host.emit({
1071
1077
  type: "notice",
1072
1078
  level: "info",
@@ -1507,6 +1513,9 @@ export class GoalService {
1507
1513
  }
1508
1514
  /** 会话过户时清理目标审查态并唤醒等待者(issue #457)。 */
1509
1515
  notifyTakeover(conv) {
1516
+ conv.goalGeneration = (conv.goalGeneration ?? 0) + 1;
1517
+ conv.goal.reviewing = false;
1518
+ this.resetLoopCounters(conv);
1510
1519
  this.delegatedPending.delete(conv.id);
1511
1520
  conv.awaitingVerdict = undefined;
1512
1521
  void this.flushDeferredPrompts(conv);
@@ -19,8 +19,8 @@
19
19
  // MUST be imported before the SDK is loaded so on-disk patches apply cleanly.
20
20
  import "./patch-remote-catalog.js";
21
21
  import "./patch-turn-end-boundary.js";
22
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
23
- import { stat } from "node:fs/promises";
22
+ import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
23
+ import { readFile, stat } from "node:fs/promises";
24
24
  import { createServer, request as proxyRequest } from "node:http";
25
25
  import { createConnection } from "node:net";
26
26
  import { basename, delimiter, join, resolve, sep } from "node:path";
@@ -39,17 +39,19 @@ import { httpHostAllowed } from "./host-guard.js";
39
39
  import { registerFileTransferRoutes } from "./file-transfer-routes.js";
40
40
  import { initAttachmentStore, readAttachment } from "./attachment-store.js";
41
41
  import { isAudioFile, previewKind } from "./text-sniff.js";
42
+ import { isOfficeFile, OFFICE_MAX_FILE_BYTES, unzipFiles } from "./office-parse.js";
42
43
  import { startControlServer } from "./control-socket.js";
43
44
  import { scheduleUploadCleanup } from "./uploads.js";
44
45
  import { ensureWindowsBash, windowsBashDir } from "./ensure-bash.js";
45
- import { listThemes, resolveThemeFile } from "./themes.js";
46
+ import { listThemes, readThemeCss, resolveThemeFile } from "./themes.js";
46
47
  import { isManaged, managedRefusal } from "./managed.js";
47
48
  import { launchOrigin, toServiceInfo } from "./launch-origin.js";
48
49
  import { parseTabs, tabsRefusal } from "./tabs.js";
49
50
  import { recordUnknownWsType } from "./ws-unknown-types.js";
51
+ import { MessageWindowTap, readMessageWindowConfig } from "./message-window.js";
50
52
  import { validateClientId } from "./ws-client-id.js";
51
53
  import { PendingCommandQueue } from "./ws-pending-queue.js";
52
- import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, unloadServerStrings, } from "./locales.js";
54
+ import { installPack, isKnownPack, listPacks, loadServerStrings, readPackFile, removePack, resolveSystemDefaultLocale, unloadServerStrings, } from "./locales.js";
53
55
  import { PluginManager, resolvePluginClientFile, } from "./plugins.js";
54
56
  import { confirmPluginInstall, PluginInstaller } from "./plugin-installer.js";
55
57
  import { syncPluginCatalog } from "./plugin-catalog-sync.js";
@@ -64,6 +66,9 @@ import { getAppVersion, getPkgRoot } from "./pkg-info.js";
64
66
  import { handleFileMessage, handleScmMessage, handleBgServerMessage, handlePresetAndDshMessage, handleModelAndProviderMessage, handleTerminalMessage, handleSessionLifecycleMessage, handlePlanAndGoalMessage, handleScheduleMessage, handleSettingsMessage, handleInteractiveResponseMessage, handleRemoteSshMessage, } from "./dispatch-domain-handlers.js";
65
67
  import { RemoteSshService, isRemoteWorkspaceUri, serveRemoteWorkspaceFile, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
66
68
  import { handlePluginMessage } from "./dispatch-plugin-handlers.js";
69
+ import { CanvasOrchestrator } from "./canvas/canvas-orchestrator.js";
70
+ import { setCanvasBroadcaster, setCanvasRuntime } from "./canvas/canvas-agent-tool.js";
71
+ import { handleCanvasMessage } from "./canvas/canvas-dispatch.js";
67
72
  /** Strip npm-injected env (`npm start` exports `npm_config_*` / `npm_package_*` /
68
73
  * `npm_lifecycle_*` into every child). Anything this server spawns — shells,
69
74
  * `pi update` — would otherwise inherit `npm_config_allow_scripts`, which npm
@@ -524,6 +529,72 @@ app.get("/api/file", async (req, res) => {
524
529
  res.status(404).end("not found");
525
530
  }
526
531
  });
532
+ /**
533
+ * PPTX 等 Office 内部媒体流式下发路由。
534
+ * /api/office-media?path=<workspace-rel-path>&media=<image-name>&clientId=…
535
+ */
536
+ app.get("/api/office-media", async (req, res) => {
537
+ try {
538
+ const rawPath = typeof req.query.path === "string" ? req.query.path : "";
539
+ const media = typeof req.query.media === "string" ? req.query.media : "";
540
+ if (!rawPath || !media) {
541
+ res.status(400).end("missing path or media");
542
+ return;
543
+ }
544
+ if (!/^image\d+\.(png|jpe?g|webp|gif|svg|bmp)$/i.test(media)) {
545
+ res.status(400).end("invalid media name");
546
+ return;
547
+ }
548
+ const cid = typeof req.query.clientId === "string" ? req.query.clientId : "";
549
+ const cs = cid ? service.get(cid) : undefined;
550
+ const root = cs?.cwd ?? CWD;
551
+ const absWire = isAbsoluteWirePath(rawPath);
552
+ let abs;
553
+ if (absWire) {
554
+ abs = wireToAbs(rawPath);
555
+ }
556
+ else {
557
+ const wp = workspacePath(root, rawPath);
558
+ if (!wp) {
559
+ res.status(400).end("path outside workspace");
560
+ return;
561
+ }
562
+ abs = wp.abs;
563
+ }
564
+ if (!isOfficeFile(abs)) {
565
+ res.status(400).end("not an office file");
566
+ return;
567
+ }
568
+ const st = await stat(abs);
569
+ if (!st.isFile() || st.size > OFFICE_MAX_FILE_BYTES) {
570
+ res.status(400).end("file not found or too large");
571
+ return;
572
+ }
573
+ const data = await readFile(abs);
574
+ const zipFiles = unzipFiles(data, [`ppt/media/${media}`]);
575
+ const imgBuf = zipFiles.get(`ppt/media/${media}`);
576
+ if (!imgBuf) {
577
+ res.status(404).end("media not found");
578
+ return;
579
+ }
580
+ const ext = media.split(".").pop()?.toLowerCase() ?? "";
581
+ const mimeMap = {
582
+ png: "image/png",
583
+ jpg: "image/jpeg",
584
+ jpeg: "image/jpeg",
585
+ webp: "image/webp",
586
+ gif: "image/gif",
587
+ svg: "image/svg+xml",
588
+ bmp: "image/bmp",
589
+ };
590
+ res.setHeader("Content-Type", mimeMap[ext] || "application/octet-stream");
591
+ res.setHeader("Cache-Control", "public, max-age=86400, immutable");
592
+ res.send(imgBuf);
593
+ }
594
+ catch {
595
+ res.status(404).end("not found");
596
+ }
597
+ });
527
598
  /**
528
599
  * Directory-mapped preview: serves a workspace file at a URL that mirrors its
529
600
  * directory location, so an HTML preview's RELATIVE subresources
@@ -624,14 +695,14 @@ app.get("/api/themes", (_req, res) => {
624
695
  // 语言包:核心只随包发布中英,其余按需下载到 <dataDir>/locales/<code>.json。
625
696
  // 手工放进去的同名 JSON 也会被识别(离线安装)。PI_WEB_TOKEN 鉴权自动覆盖。
626
697
  /**
627
- * PI_WEB_LOCALE — the language a first visit falls back to.
698
+ * PI_WEB_LOCALE / system locale — the language a first visit falls back to.
628
699
  *
629
700
  * It is a fallback, not an override: an explicit choice, and then the
630
701
  * browser's own languages, come first (web/src/pick-locale.ts). It rides on
631
702
  * /api/locales because the client already asks for that at boot, so naming a
632
703
  * default costs no extra request.
633
704
  */
634
- const DEFAULT_LOCALE = (process.env.PI_WEB_LOCALE ?? "").trim().toLowerCase() || null;
705
+ const DEFAULT_LOCALE = resolveSystemDefaultLocale();
635
706
  app.get("/api/locales", (_req, res) => {
636
707
  res.json({ packs: listPacks(DATA_DIR), defaultLocale: DEFAULT_LOCALE });
637
708
  });
@@ -678,7 +749,23 @@ app.delete("/api/locales/:code", (req, res) => {
678
749
  unloadServerStrings(code);
679
750
  res.json({ ok: true });
680
751
  });
752
+ // Serve theme base stylesheets directly if requested (e.g. /themes/bases/flow-base.css).
753
+ app.get("/themes/bases/:name.css", (req, res) => {
754
+ if (!/^[A-Za-z0-9_-]+$/.test(req.params.name)) {
755
+ res.status(404).end("base not found");
756
+ return;
757
+ }
758
+ const baseFile = join(BUILTIN_THEMES_DIR, "bases", `${req.params.name}.css`);
759
+ if (!existsSync(baseFile) || !statSync(baseFile).isFile()) {
760
+ res.status(404).end("base not found");
761
+ return;
762
+ }
763
+ res.setHeader("Content-Type", "text/css; charset=utf-8");
764
+ res.setHeader("Cache-Control", "no-cache");
765
+ res.sendFile(baseFile);
766
+ });
681
767
  // Serve a theme's full CSS file so the frontend can swap the whole stylesheet.
768
+ // Supports server-side @import inlining for shared theme bases (e.g. bases/flow-base.css).
682
769
  // Registered before the SPA catch-all below (otherwise it'd return index.html).
683
770
  app.get("/themes/:id.css", (req, res) => {
684
771
  const file = resolveThemeFile(BUILTIN_THEMES_DIR, USER_THEMES_DIR, req.params.id);
@@ -688,10 +775,8 @@ app.get("/themes/:id.css", (req, res) => {
688
775
  }
689
776
  res.setHeader("Content-Type", "text/css; charset=utf-8");
690
777
  res.setHeader("Cache-Control", "no-cache");
691
- // dotfiles: allow — issue #223:Express 5 的 send 默认 dotfiles=ignore,主题文件位于
692
- // 隐藏目录下(如 ~/.pi-web/themes、npm 全局目录 ~/.local/…)时会被判 404。路径已由
693
- // resolveThemeFile 校验(id 白名单 + 仅已知目录 + isFile),放行安全。
694
- res.sendFile(file, { dotfiles: "allow" });
778
+ const css = readThemeCss(file);
779
+ res.send(css);
695
780
  });
696
781
  // Plugin client bundles: <dataDir>/plugins/<id>/client/* served at
697
782
  // /plugins/<id>/client/* so the frontend can import() plugin views. Only the
@@ -1270,6 +1355,10 @@ const service = {
1270
1355
  for (const s of activeEngines())
1271
1356
  s.applyPluginCommandCatalog();
1272
1357
  },
1358
+ applyPluginMarkers() {
1359
+ for (const s of activeEngines())
1360
+ s.applyPluginMarkers?.();
1361
+ },
1273
1362
  refreshBackgroundServers() {
1274
1363
  for (const s of activeEngines())
1275
1364
  s.refreshBackgroundServers();
@@ -1450,6 +1539,41 @@ async function confirmPluginInstallHelper(items) {
1450
1539
  // 远程 SSH 连接管理、环境探针与目录浏览服务
1451
1540
  const remoteSshService = new RemoteSshService(DATA_DIR);
1452
1541
  setGlobalRemoteSshService(remoteSshService);
1542
+ // 多引擎多模型多目录画布协作调度器 (Canvas Studio)
1543
+ const canvasOrchestrator = new CanvasOrchestrator(CWD, DATA_DIR, (eng) => ensureEngine(eng));
1544
+ setCanvasRuntime(canvasOrchestrator);
1545
+ // AI 工具改图广播:与 orchestrator 同一个 WS 广播,开着的画布实时刷新(免刷新)。
1546
+ const broadcastCanvas = (msg) => {
1547
+ const payload = JSON.stringify(msg);
1548
+ for (const client of wss.clients) {
1549
+ if (client.readyState !== WebSocket.OPEN)
1550
+ continue;
1551
+ if (client.bufferedAmount > BROADCAST_BACKPRESSURE_MAX_BYTES)
1552
+ continue;
1553
+ try {
1554
+ client.send(payload);
1555
+ }
1556
+ catch {
1557
+ /* 客户端断开连接忽略 */
1558
+ }
1559
+ }
1560
+ };
1561
+ setCanvasBroadcaster((msg) => broadcastCanvas(msg));
1562
+ canvasOrchestrator.setBroadcaster((msg) => {
1563
+ const payload = JSON.stringify(msg);
1564
+ for (const client of wss.clients) {
1565
+ if (client.readyState !== WebSocket.OPEN)
1566
+ continue;
1567
+ if (client.bufferedAmount > BROADCAST_BACKPRESSURE_MAX_BYTES)
1568
+ continue;
1569
+ try {
1570
+ client.send(payload);
1571
+ }
1572
+ catch {
1573
+ /* 客户端断开连接忽略 */
1574
+ }
1575
+ }
1576
+ });
1453
1577
  // 内置定时任务(issue #184):全局 <dataDir>/scheduler-tasks.json,TTL 与
1454
1578
  // client-state 同级;Agent 工具建的任务优先唤醒发起对话(issue #193:
1455
1579
  // wakeConversation steer 投递,不切用户当前对话),原对话不在先回落同项目
@@ -1673,6 +1797,8 @@ pluginMgr.onAgentToolsChanged = () => {
1673
1797
  };
1674
1798
  // 插件扩展点:插件斜杠命令(registerCommand)→ 命令选择器目录 + prompt 拦截执行。
1675
1799
  pluginMgr.onCommandsChanged = () => service.applyPluginCommandCatalog();
1800
+ // 插件扩展点:插件内联标记(registerMarker)→ 刷新客户端 markers 与设置状态。
1801
+ pluginMgr.onMarkersChanged = () => service.applyPluginMarkers?.();
1676
1802
  // 插件扩展点:插件常驻后台任务(registerBackgroundTask)→ 并入「后台任务」面板。
1677
1803
  pluginMgr.onBgTasksChanged = () => service.refreshBackgroundServers();
1678
1804
  // ---------------------------------------------------------------------------
@@ -1883,6 +2009,8 @@ wss.on("connection", (ws) => {
1883
2009
  * ready 先行后,ready 只代表传输通,插件命令目录/首快照都还没好,直接分发
1884
2010
  * 会撞「未知命令」/ rev 链断裂。 */
1885
2011
  let attachDone = false;
2012
+ /** attach 代际(#699):hello/switch 每次发起 attach 前 +1,慢 attach 落定时代际过期则只 detach 清理,绝不 flush/replay。 */
2013
+ let attachGen = 0;
1886
2014
  /** 背压丢快照后的延迟重发定时器(去重:一次只排一个)。 */
1887
2015
  let snapshotRetryTimer = null;
1888
2016
  // 协议层错误(非法帧/未 masked 帧等):不注册 handler 会作为 uncaught
@@ -1896,7 +2024,9 @@ wss.on("connection", (ws) => {
1896
2024
  /* already closing */
1897
2025
  }
1898
2026
  });
1899
- const send = (msg) => {
2027
+ /** 引擎→浏览器的**唯一发送漏斗**:历史消息窗口化(按需加载)在它前面一层,
2028
+ * 见下方 `send`。四个引擎(pi / DSH / claude / durable)都走这条漏斗,引擎侧零改动。 */
2029
+ const sendRaw = (msg) => {
1900
2030
  if (closed || ws.readyState !== WebSocket.OPEN)
1901
2031
  return;
1902
2032
  // 发送背压(issue #11):socket 消费不过来时(前端慢/网络差),堆里会堆积
@@ -1931,6 +2061,11 @@ wss.on("connection", (ws) => {
1931
2061
  lastSnapshotBytes = wire.length * 2;
1932
2062
  ws.send(wire);
1933
2063
  };
2064
+ /** 本连接的历史窗口状态(每标签页一份,见 server/message-window.ts)。
2065
+ * `send` 必须包在 `sendRaw` **外面**:窗口先裁消息,再算背压字节数——否则
2066
+ * 背压阈值还在按未裁剪的 10MB 量级估。 */
2067
+ const windowTap = new MessageWindowTap(sendRaw, readMessageWindowConfig(process.env));
2068
+ const send = (msg) => windowTap.accept(msg);
1934
2069
  // Plugins broadcast to every open socket; unregister on close below.
1935
2070
  // Plugins broadcast to every open socket; unregister on close below. The
1936
2071
  // cid getter lets plugins target THIS socket via host.sendTo(clientId).
@@ -2004,6 +2139,7 @@ wss.on("connection", (ws) => {
2004
2139
  }
2005
2140
  const cid = clientId;
2006
2141
  const nextSvc = ensureEngine(targetEngine);
2142
+ const switchGen = ++attachGen;
2007
2143
  nextSvc
2008
2144
  .attach(cid, send)
2009
2145
  .then((newCs) => {
@@ -2011,6 +2147,11 @@ wss.on("connection", (ws) => {
2011
2147
  nextSvc.detach(cid, send);
2012
2148
  return;
2013
2149
  }
2150
+ if (switchGen !== attachGen) {
2151
+ // 期间又有新的 switch/hello attach:本会话已是孤儿,只清理不接管(#699)
2152
+ nextSvc.detach(cid, send);
2153
+ return;
2154
+ }
2014
2155
  nextSvc.applyPluginCommandCatalog();
2015
2156
  newCs.flushSnapshot(true);
2016
2157
  newCs.pushSettings();
@@ -2050,9 +2191,14 @@ wss.on("connection", (ws) => {
2050
2191
  .catch((err) => {
2051
2192
  // 切换失败时事务回滚:原样切回 prevEngine,避免状态悬挂
2052
2193
  setClientEngine(cid, prevEngine);
2194
+ const rollbackGen = ++attachGen;
2053
2195
  ensureEngine(prevEngine)
2054
2196
  .attach(cid, send)
2055
2197
  .then((rollbackCs) => {
2198
+ if (closed || rollbackGen !== attachGen) {
2199
+ ensureEngine(prevEngine).detach(cid, send);
2200
+ return;
2201
+ }
2056
2202
  rollbackCs.flushSnapshot(true);
2057
2203
  attachDone = true;
2058
2204
  for (const m of pending.drain())
@@ -2174,6 +2320,12 @@ wss.on("connection", (ws) => {
2174
2320
  pending.push(msg);
2175
2321
  return;
2176
2322
  }
2323
+ // 历史窗口按需加载:连接级窗口化直接服务(四个引擎通吃,不依赖引擎实现)。
2324
+ // 放在引擎分发之前:它不是引擎能力,窗口化关闭时静默无回执(前端保持现状)。
2325
+ if (msg.type === "load_earlier_messages") {
2326
+ windowTap.loadEarlier(msg.count, msg.all, msg.conversationId);
2327
+ return;
2328
+ }
2177
2329
  // Managed instances do not install software on themselves, and tabs this
2178
2330
  // instance does not offer stay closed. Both refusals live here, on the
2179
2331
  // server, because hiding them in the client would still leave the message
@@ -2206,6 +2358,8 @@ wss.on("connection", (ws) => {
2206
2358
  return;
2207
2359
  if (handleSettingsMessage(msg, cs))
2208
2360
  return;
2361
+ if (handleCanvasMessage(msg, DATA_DIR, canvasOrchestrator, send, { runBase: cs.cwd }))
2362
+ return;
2209
2363
  if (handleInteractiveResponseMessage(msg, cs, service, clientId, send))
2210
2364
  return;
2211
2365
  if (handlePluginMessage(msg, {
@@ -2460,12 +2614,19 @@ wss.on("connection", (ws) => {
2460
2614
  textEn: "Session init is taking a while (possibly scanning the workspace) — hang on…",
2461
2615
  });
2462
2616
  }, ATTACH_SLOW_NOTICE_MS);
2463
- service
2617
+ const helloSvc = ensureEngine(resolveClientEngine(cid));
2618
+ const helloGen = ++attachGen;
2619
+ helloSvc
2464
2620
  .attach(cid, send)
2465
2621
  .then((cs) => {
2466
2622
  clearTimeout(slowTimer);
2467
2623
  if (closed) {
2468
- service.detach(cid, send);
2624
+ helloSvc.detach(cid, send);
2625
+ return;
2626
+ }
2627
+ if (helloGen !== attachGen) {
2628
+ // hello 慢 attach 落定前用户已 switch_engine:旧引擎会话成孤儿,只清理(#699)
2629
+ helloSvc.detach(cid, send);
2469
2630
  return;
2470
2631
  }
2471
2632
  // Plugin catalog: re-scan + activate new dirs on every attach so
@@ -2660,6 +2821,7 @@ const autoInstall = /^(1|true|yes)$/i.test(process.env.PI_WEB_PLUGIN_CATALOG_INS
2660
2821
  if (!bootCatalogDisabled) {
2661
2822
  void syncPluginCatalog(BOOT_CATALOG_URL, { install: autoInstall }, {
2662
2823
  customCatalogPath: pluginMgr.customCatalogPath,
2824
+ communityCatalogPath: pluginMgr.communityCatalogPath,
2663
2825
  pluginsDir: join(DATA_DIR, "plugins"),
2664
2826
  installer: pluginInstaller,
2665
2827
  // 默认仅同步市场列表;重载插件会重复触发其激活广播。
@@ -212,3 +212,36 @@ export async function installPack(dataDir, code, opts = {}) {
212
212
  }
213
213
  throw new Error(lastError || `download failed for ${code}`);
214
214
  }
215
+ /**
216
+ * Resolve the system default fallback locale.
217
+ *
218
+ * Checks PI_WEB_LOCALE first, then inspects standard POSIX environment variables
219
+ * (LC_ALL, LC_MESSAGES, LANG, LANGUAGE). Normalizes tags (e.g. "en_US.UTF-8" -> "en").
220
+ */
221
+ export function resolveSystemDefaultLocale(env = process.env) {
222
+ const explicit = (env.PI_WEB_LOCALE ?? "").trim();
223
+ if (explicit)
224
+ return explicit.toLowerCase();
225
+ const candidates = [env.LC_ALL, env.LC_MESSAGES, env.LANG, env.LANGUAGE];
226
+ for (const raw of candidates) {
227
+ const val = (raw ?? "").trim();
228
+ if (!val || val === "C" || val === "POSIX")
229
+ continue;
230
+ // e.g. "en_US.UTF-8", "zh_CN.gbk", "zh_TW.UTF-8", "en-US", "de"
231
+ const cleaned = val.split(".")[0].split("@")[0].replace(/_/g, "-");
232
+ const lower = cleaned.toLowerCase();
233
+ if (lower === "zh-tw" || lower === "zh-hant" || lower === "zh-mo") {
234
+ return "zh-TW";
235
+ }
236
+ if (lower === "zh-hk") {
237
+ return "zh-HK";
238
+ }
239
+ if (lower === "zh" || lower.startsWith("zh-")) {
240
+ return "zh";
241
+ }
242
+ const primary = lower.split("-")[0];
243
+ if (primary)
244
+ return primary;
245
+ }
246
+ return null;
247
+ }
@@ -43,21 +43,15 @@ export class MarkerService {
43
43
  if (!this.settings.markersEnabled)
44
44
  return "";
45
45
  const disabled = new Set(this.settings.disabledMarkers);
46
- const lines = collectGuidance(disabled, this.lang());
46
+ // AI guidance is strictly in concise English matching tool prompt guidelines.
47
+ const lines = collectGuidance(disabled, "en");
47
48
  if (lines.length === 0)
48
49
  return "";
49
- // The dynamic lines ride the `{lines}` slot so translator packs can
50
- // place them (a static table value could never inline them).
51
50
  const linesText = lines.join("\n");
52
- return pick(this.lang(), "\n\n────────── 内联标记工具(重要)──────────\n" +
53
- "状态类操作(操作建议、对话重命名、通知)请直接写在回答正文里,采用内联标记语法,而不要调用对应工具。\n" +
54
- "插件会替你执行并把标记从展示文本中移除,不会中断你的回答。\n\n" +
51
+ return ("\n\n────────── Inline Markers ──────────\n" +
52
+ "Use inline markers in reply text for status actions (never call tools for them). Markers are executed and stripped before display.\n\n" +
55
53
  linesText +
56
- "\n──────────\n", "\n\n────────── Inline marker tools (important) ──────────\n" +
57
- "Write status operations (action suggestions, conversation renaming, notifications) directly in your reply text using inline marker syntax — do not call a tool for them.\n" +
58
- "The plugin executes them and strips the markers from the displayed text without interrupting your reply.\n\n" +
59
- linesText +
60
- "\n──────────\n", "markers.service.guidance.frame", { lines: linesText });
54
+ "\n──────────\n");
61
55
  }
62
56
  setEnabled(enabled) {
63
57
  this.settings.markersEnabled = !!enabled;
@@ -163,7 +157,7 @@ export class MarkerService {
163
157
  st = this.getState(conversationId, canonicalNs, initActionState);
164
158
  else {
165
159
  const marker = getMarker(canonicalNs);
166
- st = marker?.init ? marker.init() : {};
160
+ st = this.getState(conversationId, canonicalNs, () => (marker?.init ? marker.init() : {}));
167
161
  }
168
162
  states.set(canonicalNs, st);
169
163
  return st;
@@ -237,7 +231,7 @@ export class MarkerService {
237
231
  overlayLines(conversationId) {
238
232
  const lines = [];
239
233
  for (const m of allMarkers()) {
240
- if (m.name === "suggest")
234
+ if (m.isAlias || m.name === "suggest")
241
235
  continue;
242
236
  if (this.settings.disabledMarkers.includes(m.name))
243
237
  continue;
@@ -293,13 +287,15 @@ export class MarkerService {
293
287
  const seen = new Set();
294
288
  const out = [];
295
289
  for (const m of allMarkers()) {
296
- if (m.name === "suggest")
290
+ if (m.isAlias || m.name === "suggest")
297
291
  continue;
298
292
  if (seen.has(m.name))
299
293
  continue;
300
294
  seen.add(m.name);
301
295
  out.push({
302
296
  name: m.name,
297
+ label: m.label,
298
+ pluginId: m.pluginId,
303
299
  enabled: this.isMarkerEnabled(m.name),
304
300
  guidance: m.getGuidance?.(this.lang()) ?? m.guidance,
305
301
  });
@@ -17,14 +17,10 @@ export function initActionState() {
17
17
  return { actions: [], nextId: 1 };
18
18
  }
19
19
  const ACTION_GUIDANCE_ZH = [
20
- "- 建议后续操作:[[action:suggest:<文字>]](当期待用户操作时,如是否继续、后续步骤选择;在对话最底部生成按钮,用户点击即发送该文字)",
21
- "- 可指定不同按钮显示与发送内容:[[action:suggest:<按钮显示>,prompt=<实际发送文本>]]",
22
- "- 清空候选操作:[[action:clear:all]]",
20
+ "- 建议操作按钮:[[action:suggest:<按钮文字>]](一个标记对应一个按钮;多个选项请输出多个独立标记:[[action:suggest:选项A]] [[action:suggest:选项B]],切勿合并)。区分发送内容:[[action:suggest:<显示>,prompt=<发送>]]。清空:[[action:clear:all]]。",
23
21
  ];
24
22
  const ACTION_GUIDANCE_EN = [
25
- "- Suggest next actions: [[action:suggest:<text>]] (when expecting user input, e.g. whether to continue, what to do next; creates buttons at the bottom of the conversation, clicked to send text immediately)",
26
- "- Optional separate prompt: [[action:suggest:<label>,prompt=<text to send>]]",
27
- "- Clear suggestions: [[action:clear:all]]",
23
+ "- Suggest action buttons: [[action:suggest:<label>]] (one marker per button; for multiple choices output separate markers: [[action:suggest:A]] [[action:suggest:B]], NEVER join options in one marker). Separate prompt: [[action:suggest:<label>,prompt=<text>]]. Clear: [[action:clear:all]].",
28
24
  ];
29
25
  /** 语言感知的 action guidance:en 用英译、zh 用中文,默认英文。 */
30
26
  export function getActionGuidance(lang = "en") {
@@ -105,4 +101,7 @@ export const actionMarker = {
105
101
  export const suggestMarker = {
106
102
  ...actionMarker,
107
103
  name: "suggest",
104
+ isAlias: true,
105
+ guidance: [],
106
+ getGuidance: () => [],
108
107
  };