pi-web-ui 0.101.0 → 0.102.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.
package/CHANGELOG.md CHANGED
@@ -10,7 +10,21 @@
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
- 暂无未发布内容。
13
+ ## [0.102.0] — 2026-10-10
14
+
15
+ ### Added
16
+
17
+ - **问卷卡片与交互式选项组件(QuestionnaireCard)** —— 在对话消息流中支持内联交互式问卷卡片,清晰呈现多分支选项、推荐选项徽标与单选/多选表单;支持键盘数字快捷键快速选定;支持附带原因拒绝或提交自定义说明;支持问卷草稿持久化与会话切换恢复(`question-draft`)。
18
+ - **CodeMode 代码运行模式与 Token 预算配置** —— 设置面板支持针对 CodeMode 工具进行模式切换(常规模式 `on` / 严格纯代码模式 `only`)以及内联提示词 Token 预算调节(`codemodeInlineBudget`),参数完整纳入预设共享与白名单体系。
19
+ - **插件升级自动保护凭据与持久化存储** —— CLI 在插件升级或强制重装时自动暂存并无损还原 `config.json`、`secrets.bin` 与 `storage.json`,防止插件升级导致凭据与私有状态丢失;新增内置插件版本变更守卫单测,保证插件代码更新时版本号严格递增。
20
+ - **桌面端会话深度链接与打包流程增强(#583 #584 #587)** —— 桌面端支持会话深度链接拉起;优化打包健康探测与 Token 鉴权流程;支持提示词模板填入时二次确认覆盖或追加(#586);CI 集成 SignPath Windows 安装包测试签名。
21
+ - **SFTP 插件深度增强与引擎优化** —— 扩充默认 SSH 私钥探测路径与连接稳定性;优化客户端文件操作列表与动作响应机制。
22
+
23
+ <!-- auto-i18n:start -->
24
+ ### i18n
25
+
26
+ - 前端新增 key(28):`modelQuestionRejectWithNote`、`modelQuestionRejectWithNoteTip`、`recommended`、`keyShortcutTip`、`questionCardWaiting`、`questionCardCancelled`、`questionCardRejectReason`、`questionCardUserCustom`、`questionCardNoSelection`、`tpl.confirmFillTitle`、`tpl.confirmFillDesc`、`tpl.confirmFillAppend`、`tpl.confirmFillOverwrite`、`pluginOfficialMarket`、`pluginOfficialMarketHint`、`pluginOfficialLink`、`pluginOfficialLinkHint`、`copyConversationLink`、`copyMessageLink`、`codemodeModeLabel`、`codemodeModeHint`、`codemodeModeOn`、`codemodeModeOnly`、`codemodeInlineBudgetLabel`、`codemodeInlineBudgetHint`、`codemodeNestedApprovalBadge`、`codemodeNestedApprovalDesc`、`codemodeSavedImages`
27
+ <!-- auto-i18n:end -->
14
28
 
15
29
  ## [0.101.0] — 2026-10-10
16
30
 
package/bin/pi-web-ui.mjs CHANGED
@@ -2355,8 +2355,8 @@ async function installOnePlugin({ rawSpec, name, force, build, noBuild, dataDir,
2355
2355
  );
2356
2356
  const target = join(pluginsDir, id);
2357
2357
  let backupTs = null;
2358
- let prevConfig = null;
2359
- const CONFIG_NAME = "config.json";
2358
+ const PRESERVED_FILES = ["config.json", "secrets.bin", "storage.json"];
2359
+ const preservedData = new Map();
2360
2360
  if (existsSync(target)) {
2361
2361
  if (!force)
2362
2362
  throw new Error(
@@ -2367,11 +2367,13 @@ async function installOnePlugin({ rawSpec, name, force, build, noBuild, dataDir,
2367
2367
  // 更新前备份旧版本(<dataDir>/plugin-backups/<id>-<ts>/,保留最近 3 份),
2368
2368
  // 失败时自动回滚。备份与安装同 filter:不带 .git/node_modules。
2369
2369
  backupTs = ensurePluginBackup(dataDir, id, { source: rawSpec });
2370
- // 插件凭据/配置不因升级丢失:先取出旧 config.json,拷完新文件后原样放回
2371
- try {
2372
- prevConfig = readFileSync(join(target, CONFIG_NAME), "utf8");
2373
- } catch {
2374
- /* 无配置文件 */
2370
+ // 插件凭据/加密机密/私有存储不因升级丢失:先取出旧 config.json / secrets.bin / storage.json,拷完新文件后原样放回
2371
+ for (const fname of PRESERVED_FILES) {
2372
+ try {
2373
+ preservedData.set(fname, readFileSync(join(target, fname)));
2374
+ } catch {
2375
+ /* 无该文件 */
2376
+ }
2375
2377
  }
2376
2378
  rmSync(target, { recursive: true, force: true });
2377
2379
  }
@@ -2393,8 +2395,10 @@ async function installOnePlugin({ rawSpec, name, force, build, noBuild, dataDir,
2393
2395
  : `Plugin update failed: ${err?.message ?? err}\n (no backup available, re-run install --force)`,
2394
2396
  );
2395
2397
  }
2396
- if (prevConfig !== null && !existsSync(join(target, CONFIG_NAME))) {
2397
- writeFileSync(join(target, CONFIG_NAME), prevConfig);
2398
+ for (const [fname, buf] of preservedData) {
2399
+ if (!existsSync(join(target, fname))) {
2400
+ writeFileSync(join(target, fname), buf);
2401
+ }
2398
2402
  }
2399
2403
  // 记录安装来源:设置面板「更新」按钮据此重跑同一条安装命令(--force 覆盖)。
2400
2404
  try {
@@ -1004,12 +1004,12 @@ export class AgentService {
1004
1004
  * 跨页作答(question_answer 带 owner):把本页提交的答案送到持有方会话。
1005
1005
  * 问卷已不在(对方刚回答/取消)则明确告知,答案不吞不丢两不沾 —— 没送出就是没送出。
1006
1006
  */
1007
- async answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled) {
1007
+ async answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled, cancelReason) {
1008
1008
  const target = this.clients.get(targetId);
1009
1009
  if (!target)
1010
1010
  return;
1011
1011
  const source = this.clients.get(ownerId);
1012
- const ok = source ? source.resolveQuestion(id, answers, cancelled) : false;
1012
+ const ok = source ? source.resolveQuestion(id, answers, cancelled, cancelReason) : false;
1013
1013
  if (!ok) {
1014
1014
  target.sendNotice({
1015
1015
  type: "notice",
@@ -19,7 +19,7 @@ import { spawn } from "node:child_process";
19
19
  import { createHash, randomUUID } from "node:crypto";
20
20
  import { createRequire } from "node:module";
21
21
  import * as fsPromises from "node:fs/promises";
22
- import { appendFileSync, existsSync, readFileSync, rmSync, statSync, mkdirSync, watch, writeFileSync } from "node:fs";
22
+ import { appendFileSync, existsSync, readFileSync, readdirSync, rmSync, statSync, mkdirSync, watch, writeFileSync, } from "node:fs";
23
23
  import { homedir } from "node:os";
24
24
  import { basename, delimiter, dirname, join, resolve, sep } from "node:path";
25
25
  import { fileURLToPath } from "node:url";
@@ -499,6 +499,7 @@ export class ClientSession {
499
499
  this.applyRetryOverrides();
500
500
  // 软上限覆盖同样重放(子代理跟随主对话的压缩阈值,issue #229)。
501
501
  this.applyCompactionOverrides();
502
+ this.applyCodemodeOverrides();
502
503
  // 扩展绑定(rpc 模式);用 headless 的 Web UI context:
503
504
  // 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
504
505
  try {
@@ -1564,12 +1565,14 @@ export class ClientSession {
1564
1565
  // (含重试次数覆盖)——依次重放:重试覆盖 → 软上限覆盖 → 终端门控。
1565
1566
  this.applyRetryOverrides();
1566
1567
  this.applyCompactionOverrides();
1568
+ this.applyCodemodeOverrides();
1567
1569
  // reload() 会把 custom 工具重新加回活跃集——重放当前会话归属预设门控。
1568
1570
  this.applyToolGating(this.session, this.conv?.agentPreset);
1569
1571
  await this.pushSlashCommands();
1570
1572
  },
1571
1573
  applyRetryOverrides: () => this.applyRetryOverrides(),
1572
1574
  applyCompactionOverrides: () => this.applyCompactionOverrides(),
1575
+ applyCodemodeOverrides: () => this.applyCodemodeOverrides(),
1573
1576
  applyToolGating: () => {
1574
1577
  for (const conv of this.convs.values()) {
1575
1578
  this.applyToolGating(conv.session, conv.agentPreset);
@@ -2000,7 +2003,7 @@ export class ClientSession {
2000
2003
  // 覆盖,则用 composer 把 {{token}} 展开为各来源文本(工具列表/项目上下文/技能
2001
2004
  // 等都取自本次 run 的 systemPromptOptions,永远最新)。
2002
2005
  extensionFactories: [
2003
- createCodemodeExtension({ mode: "on" }),
2006
+ createCodemodeExtension(),
2004
2007
  createToolSearchExtension(),
2005
2008
  {
2006
2009
  name: "pi-webui-persona",
@@ -2366,6 +2369,7 @@ export class ClientSession {
2366
2369
  queueFollowUp: [],
2367
2370
  toolStartTimes: new Map(),
2368
2371
  toolPendingArgs: new Map(),
2372
+ activeToolCalls: new Map(),
2369
2373
  toolWatchdogs: new Map(),
2370
2374
  workspaceSnapshots: [],
2371
2375
  };
@@ -2649,6 +2653,7 @@ export class ClientSession {
2649
2653
  this.applyRetryOverrides();
2650
2654
  // 软上限覆盖同路重放(新 runtime 的 SettingsManager 是干净的,issue #229)。
2651
2655
  this.applyCompactionOverrides();
2656
+ this.applyCodemodeOverrides();
2652
2657
  this.scheduleSnapshot();
2653
2658
  this.webUi.refresh();
2654
2659
  this.startWidgetsTimer();
@@ -3161,6 +3166,7 @@ export class ClientSession {
3161
3166
  // Record the moment the tool actually starts so tool_status can
3162
3167
  // report real execution time (vs. time spent waiting on the model).
3163
3168
  conv.toolStartTimes.set(event.toolCallId, Date.now());
3169
+ conv.activeToolCalls.set(event.toolCallId, event.toolName);
3164
3170
  // Snapshot listeners before a bash run — the post-run diff catches
3165
3171
  // servers the agent started in the background.
3166
3172
  if (event.toolName === "bash") {
@@ -3201,6 +3207,7 @@ export class ClientSession {
3201
3207
  case "tool_execution_end": {
3202
3208
  const startedAt = conv.toolStartTimes.get(event.toolCallId);
3203
3209
  conv.toolStartTimes.delete(event.toolCallId);
3210
+ conv.activeToolCalls.delete(event.toolCallId);
3204
3211
  this.clearToolWatchdog(conv, event.toolCallId);
3205
3212
  const pendingArgs = conv.toolPendingArgs.get(event.toolCallId);
3206
3213
  conv.toolPendingArgs.delete(event.toolCallId);
@@ -4076,12 +4083,17 @@ export class ClientSession {
4076
4083
  * 成功 resolve 后同步推 question_retracted + conversations:本页 live 对话框
4077
4084
  * 靠前者收起(跨页作答时源页就靠它),别处的「?」角标靠后者即时消失。
4078
4085
  * 返回是否真的恢复了一个挂起提问(跨页作答的送达回执用)。 */
4079
- resolveQuestion(id, answers, cancelled) {
4086
+ resolveQuestion(id, answers, cancelled, cancelReason) {
4080
4087
  const pending = this.pendingQuestions.get(id);
4081
4088
  if (!pending)
4082
4089
  return false;
4083
4090
  this.pendingQuestions.delete(id);
4084
- pending.resolve(cancelled ? null : answers);
4091
+ if (cancelled) {
4092
+ pending.resolve(cancelReason?.trim() ? { cancelled: true, reason: cancelReason.trim() } : null);
4093
+ }
4094
+ else {
4095
+ pending.resolve(answers);
4096
+ }
4085
4097
  this.emit({ type: "question_retracted", id });
4086
4098
  // 同上:角标消失也要即时推送(否则要等到 run 结束别处才知道问完了)。
4087
4099
  this.emitConversations();
@@ -4118,8 +4130,8 @@ export class ClientSession {
4118
4130
  }
4119
4131
  /** 标准引擎的 question_answer 路由入口(index.ts 经 cs.answerQuestion?. 转发)。
4120
4132
  * DSH 引擎的 AgentService 也实现了同名方法,此处为 ClientSession 的转发。 */
4121
- answerQuestion(id, answers, cancelled) {
4122
- this.resolveQuestion(id, answers, cancelled);
4133
+ answerQuestion(id, answers, cancelled, cancelReason) {
4134
+ this.resolveQuestion(id, answers, cancelled, cancelReason);
4123
4135
  return Promise.resolve();
4124
4136
  }
4125
4137
  /** 取某对话的等答复问卷原文(跨页作答的 peek 用;只读,不改变状态)。 */
@@ -4180,6 +4192,15 @@ export class ClientSession {
4180
4192
  return;
4181
4193
  }
4182
4194
  const conversationTitle = conv?.title;
4195
+ let parentTool;
4196
+ if (conv?.activeToolCalls) {
4197
+ for (const [id, name] of conv.activeToolCalls.entries()) {
4198
+ if (name === "codemode" && id !== toolCallId) {
4199
+ parentTool = "codemode";
4200
+ break;
4201
+ }
4202
+ }
4203
+ }
4183
4204
  const entry = {
4184
4205
  id,
4185
4206
  toolCallId,
@@ -4189,6 +4210,7 @@ export class ClientSession {
4189
4210
  reasonEn,
4190
4211
  ...(category ? { category } : {}),
4191
4212
  ...(hits && hits.length > 0 ? { hits } : {}),
4213
+ ...(parentTool ? { parentTool } : {}),
4192
4214
  conversationId,
4193
4215
  conversationTitle,
4194
4216
  resolve,
@@ -4205,6 +4227,7 @@ export class ClientSession {
4205
4227
  reasonEn,
4206
4228
  ...(category ? { category } : {}),
4207
4229
  ...(hits && hits.length > 0 ? { hits } : {}),
4230
+ ...(parentTool ? { parentTool } : {}),
4208
4231
  ...(conversationId !== undefined ? { conversationId } : {}),
4209
4232
  ...(conversationTitle ? { conversationTitle } : {}),
4210
4233
  });
@@ -5165,6 +5188,7 @@ export class ClientSession {
5165
5188
  // /reload 同样重读磁盘 settings.json——重放重试覆盖 + 软上限覆盖 + 终端门控。
5166
5189
  this.applyRetryOverrides();
5167
5190
  this.applyCompactionOverrides();
5191
+ this.applyCodemodeOverrides();
5168
5192
  this.applyToolGating(this.session, this.conv?.agentPreset);
5169
5193
  },
5170
5194
  pluginCommands: () => this.pluginCommandsProvider?.() ?? [],
@@ -5554,6 +5578,21 @@ export class ClientSession {
5554
5578
  compaction: { reserveTokens: reserve ?? DEFAULT_COMPACTION_RESERVE_TOKENS },
5555
5579
  });
5556
5580
  }
5581
+ /** 把 codemode 运行模式与内联预算即时注入各存活会话的 SDK SettingsManager。 */
5582
+ applyCodemodeOverrides() {
5583
+ const mode = this.settingsSvc.current.codemodeMode ?? "on";
5584
+ const inlineBudget = this.settingsSvc.current.codemodeInlineBudget ?? 3000;
5585
+ for (const c of this.convs.values()) {
5586
+ try {
5587
+ c.session.settingsManager.applyOverrides({
5588
+ codemode: { mode, inlineBudget },
5589
+ });
5590
+ }
5591
+ catch {
5592
+ // 会话未就绪或已释放 → 其 runtime 创建时统一注入。
5593
+ }
5594
+ }
5595
+ }
5557
5596
  /** 会话模型变化时重放该会话的软上限覆盖。SDK 恢复历史会话的模型
5558
5597
  * (findInitialModel)与 /model 命令都不经过 pi-web-ui 的 setModel
5559
5598
  * 路径,注入过的 reserve 会停留在旧模型窗口的换算值上——例如默认
@@ -8661,8 +8700,12 @@ export class ClientSession {
8661
8700
  // 落盘会话才有文件(inMemory 子代理缺省):右键复制路径 / AI 按 path 读历史时用。
8662
8701
  ...(() => {
8663
8702
  try {
8703
+ const sid = conv.session.sessionId;
8664
8704
  const f = conv.session.sessionFile;
8665
- return f ? { sessionFile: f } : {};
8705
+ return {
8706
+ ...(sid ? { sessionId: sid } : {}),
8707
+ ...(f ? { sessionFile: f } : {}),
8708
+ };
8666
8709
  }
8667
8710
  catch {
8668
8711
  return {};
@@ -8980,6 +9023,7 @@ export class ClientSession {
8980
9023
  const isPinned = this.stateStore?.isSessionPinned(this.cwd, s.path);
8981
9024
  sessions.set(s.path, {
8982
9025
  path: s.path,
9026
+ ...(s.id ? { sessionId: s.id } : {}),
8983
9027
  name: s.name,
8984
9028
  firstMessage: s.firstMessage,
8985
9029
  messageCount: s.messageCount,
@@ -9792,7 +9836,55 @@ export class ClientSession {
9792
9836
  });
9793
9837
  }
9794
9838
  }
9795
- /** Open a persisted session as the active conversation (from listSessions).
9839
+ /** 按 sessionId 解析磁盘上的转录文件路径(issue #587:供 `#s=<sessionId>` 深链直接打开尚未加载进列表的历史会话)。 */
9840
+ async resolveSessionPathById(sessionId) {
9841
+ const want = sessionId.trim();
9842
+ if (!want)
9843
+ return null;
9844
+ const infos = await this.loadSessionInfos();
9845
+ for (const info of infos) {
9846
+ if (info.id === want)
9847
+ return info.path;
9848
+ const base = basename(info.path);
9849
+ if (base === `${want}.jsonl` || base.endsWith(`_${want}.jsonl`))
9850
+ return info.path;
9851
+ }
9852
+ // 跨项目目录兜底扫描(<agentDir>/sessions 及 PI_CODING_AGENT_SESSION_DIR)
9853
+ const roots = [join(this.agentDir, "sessions")];
9854
+ const extra = piSessionsRoot();
9855
+ if (extra)
9856
+ roots.push(extra);
9857
+ for (const root of roots) {
9858
+ if (!existsSync(root))
9859
+ continue;
9860
+ try {
9861
+ const entries = readdirSync(root, { withFileTypes: true });
9862
+ for (const e of entries) {
9863
+ if (e.isFile() && (e.name === `${want}.jsonl` || e.name.endsWith(`_${want}.jsonl`))) {
9864
+ return join(root, e.name);
9865
+ }
9866
+ if (e.isDirectory()) {
9867
+ const subDir = join(root, e.name);
9868
+ try {
9869
+ for (const f of readdirSync(subDir)) {
9870
+ if (f === `${want}.jsonl` || f.endsWith(`_${want}.jsonl`)) {
9871
+ return join(subDir, f);
9872
+ }
9873
+ }
9874
+ }
9875
+ catch {
9876
+ /* ignore unreadable subdir */
9877
+ }
9878
+ }
9879
+ }
9880
+ }
9881
+ catch {
9882
+ /* ignore unreadable root */
9883
+ }
9884
+ }
9885
+ return null;
9886
+ }
9887
+ /** Open a persisted session as the active conversation (from listSessions or `#s=<sessionId>` deep link).
9796
9888
  *
9797
9889
  * A persisted-session click must follow the same ownership rule as
9798
9890
  * new_chat/switch_conversation: every open conversation keeps its own
@@ -9800,12 +9892,40 @@ export class ClientSession {
9800
9892
  * current runtime, which would otherwise stop a response merely because the
9801
9893
  * user opened history while it was streaming.
9802
9894
  */
9803
- async switchSession(path) {
9895
+ async switchSession(path, sessionId) {
9804
9896
  if (this.quiesceBlocked())
9805
9897
  return;
9806
9898
  let openedRuntime = null;
9807
9899
  let openedTerminals = null;
9808
9900
  try {
9901
+ const wantSid = sessionId?.trim() ?? "";
9902
+ if (!path.trim() && wantSid) {
9903
+ for (const conv of this.convs.values()) {
9904
+ let sid = "";
9905
+ try {
9906
+ sid = conv.session.sessionId;
9907
+ }
9908
+ catch {
9909
+ /* ignore */
9910
+ }
9911
+ if (sid === wantSid || conv.id === wantSid) {
9912
+ await this.switchConversation(conv.id);
9913
+ return;
9914
+ }
9915
+ }
9916
+ const resolved = await this.resolveSessionPathById(wantSid);
9917
+ if (!resolved) {
9918
+ this.emit({
9919
+ type: "notice",
9920
+ level: "warning",
9921
+ text: `未找到会话:${wantSid}`,
9922
+ textEn: `Session not found: ${wantSid}`,
9923
+ });
9924
+ this.flushSnapshot();
9925
+ return;
9926
+ }
9927
+ path = resolved;
9928
+ }
9809
9929
  const targetPath = resolve(path);
9810
9930
  if (!isInsideSessionsDir(this.agentDir, targetPath)) {
9811
9931
  this.emit({
@@ -10434,6 +10554,7 @@ export class ClientSession {
10434
10554
  const isPinned = this.stateStore?.isSessionPinned(this.cwd, s.path);
10435
10555
  const base = {
10436
10556
  path: s.path,
10557
+ ...(s.id ? { sessionId: s.id } : {}),
10437
10558
  name: s.name,
10438
10559
  firstMessage: s.firstMessage,
10439
10560
  messageCount: s.messageCount,
@@ -21,6 +21,9 @@ ownerId) {
21
21
  preview: Type.Optional(Type.String({
22
22
  description: "Optional preview (markdown/HTML/code)",
23
23
  })),
24
+ recommended: Type.Optional(Type.Boolean({
25
+ description: "Highlight as recommended option",
26
+ })),
24
27
  });
25
28
  const QuestionSchema = Type.Object({
26
29
  id: Type.String({ description: "Unique identifier (snake_case)" }),
@@ -68,12 +71,19 @@ ownerId) {
68
71
  if (qs.length > 3) {
69
72
  throw new Error("ask_user_question allows at most 3 questions per call to prevent question fatigue (单次提问最多不得超过 3 个问题)");
70
73
  }
71
- const answers = await clientSession.askUser(qs, {
74
+ const res = await clientSession.askUser(qs, {
72
75
  aborted: signal?.aborted,
73
76
  }, ownerId);
74
- if (answers === null) {
77
+ if (res === null) {
75
78
  throw new Error("User cancelled the question.\n用户取消了提问。");
76
79
  }
80
+ if (!Array.isArray(res) && res.cancelled) {
81
+ const cancelReason = res.reason?.trim();
82
+ const note = cancelReason ? `\nUser note / 附言: ${cancelReason}` : "";
83
+ const noteZh = cancelReason ? `\n附言:${cancelReason}` : "";
84
+ throw new Error(`User cancelled the question.${note}\n用户取消了提问。${noteZh}`);
85
+ }
86
+ const answers = res;
77
87
  // 工具结果:把每道题的回答拼成简洁文本给模型,同时留 details 供 UI 展示。
78
88
  const lines = answers.map((a) => {
79
89
  const q = qs.find((q) => q.id === a.id);
@@ -256,6 +256,17 @@ export const DEFAULT_TOOL_LAZY_LOADING = (() => {
256
256
  const v = (process.env.PI_WEB_TOOL_LAZY_LOADING ?? "").trim().toLowerCase();
257
257
  return !(v === "0" || v === "false" || v === "off" || v === "no");
258
258
  })();
259
+ export const DEFAULT_CODEMODE_MODE = "on";
260
+ export const DEFAULT_CODEMODE_INLINE_BUDGET = 3000;
261
+ export function normalizeCodemodeMode(v) {
262
+ return v === "only" ? "only" : "on";
263
+ }
264
+ export function normalizeCodemodeInlineBudget(v) {
265
+ if (typeof v === "number" && Number.isFinite(v) && v > 0) {
266
+ return Math.floor(v);
267
+ }
268
+ return DEFAULT_CODEMODE_INLINE_BUDGET;
269
+ }
259
270
  /** 预设 → 设置面板列表用的 UI 形状(协议要求字段完整:旧/部分预设用默认值补齐)。 */
260
271
  export function settingsPresetToUi(p) {
261
272
  return {
@@ -791,6 +802,8 @@ export class ClientStateStore {
791
802
  readDirEnabled: stored?.readDirEnabled ?? true,
792
803
  bgAutoCleanupMin: normalizeBgCleanupMinutes(stored?.bgAutoCleanupMin),
793
804
  toolLazyLoading: stored?.toolLazyLoading ?? DEFAULT_TOOL_LAZY_LOADING,
805
+ codemodeMode: normalizeCodemodeMode(stored?.codemodeMode),
806
+ codemodeInlineBudget: normalizeCodemodeInlineBudget(stored?.codemodeInlineBudget),
794
807
  toolApprovalEnabled: stored?.toolApprovalEnabled ?? true,
795
808
  editSoftEnabled: stored?.disabledAgentTools !== undefined
796
809
  ? deriveLegacy(legacyToDisabled(stored)).editSoftEnabled
@@ -856,6 +869,8 @@ export class ClientStateStore {
856
869
  readDirEnabled: settings.readDirEnabled ?? cur.readDirEnabled ?? true,
857
870
  bgAutoCleanupMin: normalizeBgCleanupMinutes(settings.bgAutoCleanupMin ?? cur.bgAutoCleanupMin),
858
871
  toolLazyLoading: settings.toolLazyLoading ?? cur.toolLazyLoading ?? DEFAULT_TOOL_LAZY_LOADING,
872
+ codemodeMode: normalizeCodemodeMode(settings.codemodeMode ?? cur.codemodeMode ?? DEFAULT_CODEMODE_MODE),
873
+ codemodeInlineBudget: normalizeCodemodeInlineBudget(settings.codemodeInlineBudget ?? cur.codemodeInlineBudget ?? DEFAULT_CODEMODE_INLINE_BUDGET),
859
874
  toolApprovalEnabled: settings.toolApprovalEnabled ?? cur.toolApprovalEnabled ?? true,
860
875
  editSoftEnabled: settings.editSoftEnabled ?? cur.editSoftEnabled ?? false,
861
876
  questionnaireEnabled: settings.questionnaireEnabled ?? cur.questionnaireEnabled ?? true,
@@ -354,7 +354,7 @@ export function handleSessionLifecycleMessage(msg, cs) {
354
354
  void cs.dismissFinishedSubagents(msg.parentId);
355
355
  return true;
356
356
  case "switch_session":
357
- void cs.switchSession(msg.path);
357
+ void cs.switchSession(msg.path, msg.sessionId);
358
358
  return true;
359
359
  case "switch_conversation":
360
360
  void cs.switchConversation(msg.id);
@@ -595,7 +595,7 @@ export function handleInteractiveResponseMessage(msg, cs, service, clientId, sen
595
595
  if (msg.owner) {
596
596
  // 跨页作答:答案转交持有方会话(本页不持有该问卷)。
597
597
  if (typeof service.answerElsewhereQuestion === "function" && clientId) {
598
- void service.answerElsewhereQuestion(clientId, msg.owner, msg.id, msg.answers, msg.cancelled);
598
+ void service.answerElsewhereQuestion(clientId, msg.owner, msg.id, msg.answers, msg.cancelled, msg.cancelReason);
599
599
  }
600
600
  else {
601
601
  send({
@@ -607,7 +607,7 @@ export function handleInteractiveResponseMessage(msg, cs, service, clientId, sen
607
607
  }
608
608
  }
609
609
  else {
610
- void cs.answerQuestion?.(msg.id, msg.answers, msg.cancelled);
610
+ void cs.answerQuestion?.(msg.id, msg.answers, msg.cancelled, msg.cancelReason);
611
611
  }
612
612
  return true;
613
613
  case "tool_approval_response":
@@ -1393,6 +1393,7 @@ export class DshClientSession {
1393
1393
  continue;
1394
1394
  list.push({
1395
1395
  id: conv.id,
1396
+ sessionId: conv.sessionId,
1396
1397
  title: conv.title,
1397
1398
  cwd: conv.cwd,
1398
1399
  messageCount: conv.messages.length,
@@ -2093,6 +2094,7 @@ export class DshClientSession {
2093
2094
  const { events } = readSessionLog(file);
2094
2095
  summaries.push({
2095
2096
  path: file,
2097
+ sessionId,
2096
2098
  name: sessionId,
2097
2099
  firstMessage: firstUserText(events, this.getLang()),
2098
2100
  messageCount: events.filter((e) => e.type === "user/message" || e.type === "assistant/message" || e.type === "tool/result").length,
@@ -2232,17 +2234,30 @@ export class DshClientSession {
2232
2234
  });
2233
2235
  }
2234
2236
  /** 切换会话:读 JSONL 回放 → 新建 conversation(同一 sessionId 续聊)。 */
2235
- async switchSession(path) {
2237
+ async switchSession(path, wantSessionId) {
2236
2238
  try {
2237
- const abs = resolve(path);
2238
- const sessionId = basename(dirname(abs));
2239
+ const explicitSid = wantSessionId?.trim() ?? "";
2240
+ const sessionId = explicitSid || basename(dirname(resolve(path)));
2239
2241
  // 同一 sessionId 已在运行 → 直接切过去。
2240
2242
  for (const conv of this.convs.values()) {
2241
- if (conv.sessionId === sessionId) {
2243
+ if (conv.sessionId === sessionId || conv.id === sessionId) {
2242
2244
  await this.switchConversation(conv.id);
2243
2245
  return;
2244
2246
  }
2245
2247
  }
2248
+ if (!path.trim() && explicitSid) {
2249
+ const candidateFile = join(this.sessionRoot, explicitSid, "session.jsonl");
2250
+ if (!existsSync(candidateFile)) {
2251
+ this.emit({
2252
+ type: "notice",
2253
+ level: "warning",
2254
+ text: `未找到会话:${explicitSid}`,
2255
+ textEn: `Session not found: ${explicitSid}`,
2256
+ });
2257
+ this.flushSnapshot(true);
2258
+ return;
2259
+ }
2260
+ }
2246
2261
  // issue #145:同 pi 引擎 —— 别处正在跑同一 sessionId 时不建第二个持有者。
2247
2262
  const owner = this.findSessionOwnerById?.(sessionId);
2248
2263
  if (owner && owner.isStreaming) {
@@ -2656,6 +2671,8 @@ export class DshClientSession {
2656
2671
  bgAutoCleanupMin: Number(this.settings.bgAutoCleanupMin ?? 0),
2657
2672
  // DSH 无 pi 工具注册面,不适用延迟加载;保协议完整。
2658
2673
  toolLazyLoading: true,
2674
+ codemodeMode: "on",
2675
+ codemodeInlineBudget: 3000,
2659
2676
  editSoftEnabled: this.settings.editSoftEnabled,
2660
2677
  // DSH 无独立重试配置(pi 引擎才暴露),保持默认。
2661
2678
  retryMaxAttempts: DEFAULT_RETRY_MAX_ATTEMPTS,
@@ -923,7 +923,11 @@ class DshGoalJsonRpcServer extends HarnessSdkJsonRpcServer {
923
923
  }
924
924
  this.questionBridge.pending = null;
925
925
  if (params?.cancelled) {
926
- pending.reject(new Error("用户取消了提问"));
926
+ const reason =
927
+ typeof params?.cancelReason === "string" && params.cancelReason.trim()
928
+ ? `(附言:${params.cancelReason.trim()})`
929
+ : "";
930
+ pending.reject(new Error(`用户取消了提问${reason}`));
927
931
  } else {
928
932
  const answers = Array.isArray(params?.answers) ? params.answers : [];
929
933
  pending.resolve({ answers });
@@ -182,7 +182,12 @@ export class PluginInstaller {
182
182
  // 上 kill(-pid) 指向不存在的组而静默失败,作业杀不掉、锁一直占着
183
183
  // (CI 的 busy 单测在 Linux 上 5 秒超时,Windows 走 taskkill 不受影响)。
184
184
  detached: process.platform !== "win32",
185
- env: { ...process.env, PI_WEB_DATA_DIR: this.deps.dataDir, NO_COLOR: "1" },
185
+ env: {
186
+ ...process.env,
187
+ ...(process.versions.electron ? { ELECTRON_RUN_AS_NODE: "1" } : {}),
188
+ PI_WEB_DATA_DIR: this.deps.dataDir,
189
+ NO_COLOR: "1",
190
+ },
186
191
  stdio: ["ignore", "pipe", "pipe"],
187
192
  });
188
193
  this.child = child;
@@ -2308,6 +2308,7 @@ export class PluginManager {
2308
2308
  name: typeof m.name === "string" && m.name ? m.name : name,
2309
2309
  version: typeof m.version === "string" ? m.version : undefined,
2310
2310
  description: typeof m.description === "string" ? m.description : undefined,
2311
+ homepage: typeof m.homepage === "string" && m.homepage.trim() ? m.homepage.trim() : undefined,
2311
2312
  icon: typeof m.icon === "string" && m.icon.trim() ? m.icon.trim() : undefined,
2312
2313
  iconSvg: normalizeIconSvg(m.iconSvg),
2313
2314
  hasClient: existsSync(join(dir, "client", "entry.mjs")),
@@ -39,6 +39,8 @@ export const PRESET_FIELD_GROUPS = {
39
39
  "disabledPluginTools",
40
40
  "toolPromptOverrides",
41
41
  "toolLazyLoading",
42
+ "codemodeMode",
43
+ "codemodeInlineBudget",
42
44
  "readDirEnabled",
43
45
  "toolApprovalEnabled",
44
46
  "toolWatchdogTimeoutMs",
@@ -183,6 +185,18 @@ export const PRESET_FIELD_META = {
183
185
  hintZh: "仅常驻核心工具,其余工具通过 load_tools 按需动态引入(节省上下文)",
184
186
  hintEn: "Keep only core tools active; load others on demand (saves context)",
185
187
  },
188
+ codemodeMode: {
189
+ labelZh: "codemode 运行模式",
190
+ labelEn: "Codemode Execution Mode",
191
+ hintZh: "常规模式(on)或纯代码模式(only,仅通过沙箱脚本调用工具)",
192
+ hintEn: "Regular mode (on) or strict code mode (only, all tool calls run via sandbox script)",
193
+ },
194
+ codemodeInlineBudget: {
195
+ labelZh: "codemode 工具声明预算",
196
+ labelEn: "Codemode Inline Budget",
197
+ hintZh: "直接嵌入在 codemode 系统提示词中的工具声明 Token 预算(默认 3000)",
198
+ hintEn: "Token budget for tool declarations directly embedded in the codemode prompt (default: 3000)",
199
+ },
186
200
  readDirEnabled: {
187
201
  labelZh: "read 工具列目录",
188
202
  labelEn: "Directory Listing in read",
@@ -589,6 +603,17 @@ export function formatPresetFieldValue(field, value, lang = "zh") {
589
603
  };
590
604
  }
591
605
  // 8. 模式类字段
606
+ if (field === "codemodeMode") {
607
+ return {
608
+ summary: value === "only"
609
+ ? isZh
610
+ ? "纯代码模式 (only,仅通过沙箱脚本调用工具)"
611
+ : "Strict code mode (only, sandbox scripts only)"
612
+ : isZh
613
+ ? "常规模式 (on,常规可用,支持脚本批处理)"
614
+ : "Standard mode (on, direct & scripts)",
615
+ };
616
+ }
592
617
  if (field === "promptMode" ||
593
618
  field === "visionBridgePromptMode" ||
594
619
  field === "scmCommitMsgPromptMode" ||
@@ -662,6 +687,9 @@ export function formatPresetFieldValue(field, value, lang = "zh") {
662
687
  }
663
688
  // 11. 数字配置
664
689
  if (typeof value === "number") {
690
+ if (field === "codemodeInlineBudget") {
691
+ return { summary: `${value} tokens` };
692
+ }
665
693
  if (field === "softCapTokens") {
666
694
  return { summary: value > 0 ? `${value} tokens` : isZh ? "跟随默认 (16384 tokens)" : "Default (16384 tokens)" };
667
695
  }
@@ -241,6 +241,8 @@ const PRESET_FIELD_KINDS = {
241
241
  disabledPluginTools: "list",
242
242
  toolPromptOverrides: "toolPromptOverrides",
243
243
  toolLazyLoading: "bool",
244
+ codemodeMode: "codemodeMode",
245
+ codemodeInlineBudget: "number",
244
246
  readDirEnabled: "bool",
245
247
  bgAutoCleanupMin: "number",
246
248
  toolApprovalEnabled: "bool",
@@ -373,6 +375,12 @@ export function sanitizePresetSettings(input, opts) {
373
375
  else
374
376
  rejected.push(key);
375
377
  break;
378
+ case "codemodeMode":
379
+ if (raw === "on" || raw === "only")
380
+ settings[key] = raw;
381
+ else
382
+ rejected.push(key);
383
+ break;
376
384
  case "number":
377
385
  if (typeof raw === "number" && Number.isFinite(raw) && raw >= 0)
378
386
  settings[key] = Math.floor(raw);
@@ -8,4 +8,4 @@
8
8
  * its own copy in web/src/protocol-version.ts; scripts/check-protocol-sync.mjs
9
9
  * verifies the two never drift.
10
10
  */
11
- export const PROTOCOL_VERSION = 26;
11
+ export const PROTOCOL_VERSION = 27;