pi-web-ui 0.107.0 → 0.108.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.
@@ -11,7 +11,7 @@
11
11
  * 经 ModelAdminHost 与 ClientSession 解耦(同 settings/goal/slash 服务模式)。
12
12
  * UI 文案直接中文(服务端 notice 约定)。apiKey/headers 绝不下发浏览器。
13
13
  */
14
- import { existsSync, mkdirSync, readFileSync, renameSync } from "node:fs";
14
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
15
15
  import { dirname, join } from "node:path";
16
16
  import { writeJsonAtomicSync } from "./atomic-file.js";
17
17
  import { enrichBatch } from "./model-enrich.js";
@@ -70,6 +70,17 @@ export function graduateOverlayModels(providers, official) {
70
70
  function atomicWriteJson(path, data) {
71
71
  writeJsonAtomicSync(path, data);
72
72
  }
73
+ /** 原子写凭据 JSON 并修权限 0600(port from fork 50e723f,保留上游原子写语义)。
74
+ * chmod 覆盖已存在文件(mode 选项只对新建有效)。Windows 下尽力而为。 */
75
+ function atomicWriteCredentialJson(path, data) {
76
+ writeJsonAtomicSync(path, data);
77
+ try {
78
+ chmodSync(path, CREDENTIAL_FILE_MODE);
79
+ }
80
+ catch {
81
+ /* best-effort (win) */
82
+ }
83
+ }
73
84
  /** Strip // and /* *\/ comments without touching string literals (URLs contain //). */
74
85
  function stripJsonComments(src) {
75
86
  let out = "";
@@ -247,12 +258,40 @@ function parseGoogleModel(m) {
247
258
  ...(numMeta(r.outputTokenLimit) ? { maxTokens: numMeta(r.outputTokenLimit) } : {}),
248
259
  };
249
260
  }
261
+ /** Credential files hold raw provider API keys — always mode 0600.
262
+ * models.json can hold per-provider apiKey/headers, so it gets the same treatment. */
263
+ export const CREDENTIAL_FILE_MODE = 0o600;
264
+ /** Write a credential file (provider-keys.json / auth.json / models.json) with mode 0600.
265
+ * The `mode` option covers creation; the chmod covers pre-existing files
266
+ * (mode is ignored when the file already exists). Best-effort on Windows. */
267
+ export function writeCredentialFile(path, data) {
268
+ mkdirSync(dirname(path), { recursive: true });
269
+ writeFileSync(path, data, { mode: CREDENTIAL_FILE_MODE });
270
+ try {
271
+ chmodSync(path, CREDENTIAL_FILE_MODE);
272
+ }
273
+ catch {
274
+ /* best-effort (win) */
275
+ }
276
+ }
277
+ /** Startup repair: chmod existing credential files to 0600 (best-effort). */
278
+ export function ensureCredentialFilePermissions(agentDir) {
279
+ for (const name of ["provider-keys.json", "auth.json", "models.json"]) {
280
+ try {
281
+ chmodSync(join(agentDir, name), CREDENTIAL_FILE_MODE);
282
+ }
283
+ catch {
284
+ /* missing / win — ignore */
285
+ }
286
+ }
287
+ }
250
288
  export class ModelAdminService {
251
289
  host;
252
290
  oauthFlows;
253
291
  activeEnrichAbort = new Map();
254
292
  constructor(host) {
255
293
  this.host = host;
294
+ ensureCredentialFilePermissions(host.agentDir);
256
295
  this.oauthFlows = new ProviderOAuthFlowManager({
257
296
  modelRuntime: host.modelRuntime ??
258
297
  (() => {
@@ -379,8 +418,15 @@ export class ModelAdminService {
379
418
  return out;
380
419
  }
381
420
  writeProviderKeys(data) {
382
- // 原子写(tmp+rename):崩溃不留半截 JSON。
383
- writeJsonAtomicSync(this.providerKeysPath(), data);
421
+ atomicWriteCredentialJson(this.providerKeysPath(), data);
422
+ // Keep the sibling credential file at 0600 too (e.g. adding an
423
+ // inactive key rewrites provider-keys.json but not auth.json).
424
+ try {
425
+ chmodSync(join(this.host.agentDir, "auth.json"), CREDENTIAL_FILE_MODE);
426
+ }
427
+ catch {
428
+ /* missing / win — ignore */
429
+ }
384
430
  }
385
431
  /** 解析失败的配置文件改名留存为 <name>.corrupt-<timestamp>。改名失败(占用/
386
432
  * 跨盘等)也不抛——留存是尽力而为,绝不能阻塞主流程。 */
@@ -498,7 +544,6 @@ export class ModelAdminService {
498
544
  /** Persist the ACTIVE key's apiKey into auth.json + runtime override + refresh. */
499
545
  async applyActiveKey(pid, apiKey) {
500
546
  const authPath = join(this.host.agentDir, "auth.json");
501
- mkdirSync(this.host.agentDir, { recursive: true });
502
547
  let data = {};
503
548
  try {
504
549
  data = JSON.parse(readFileSync(authPath, "utf8"));
@@ -507,7 +552,13 @@ export class ModelAdminService {
507
552
  // no file yet / unparsable — start fresh
508
553
  }
509
554
  data[pid] = { type: "api_key", key: apiKey };
510
- atomicWriteJson(authPath, data);
555
+ atomicWriteCredentialJson(authPath, data);
556
+ try {
557
+ chmodSync(this.providerKeysPath(), CREDENTIAL_FILE_MODE);
558
+ }
559
+ catch {
560
+ /* missing / win — ignore */
561
+ }
511
562
  const mr = this.host.modelRuntime?.();
512
563
  if (mr) {
513
564
  await mr.setRuntimeApiKey(pid, apiKey);
@@ -740,7 +791,7 @@ export class ModelAdminService {
740
791
  // no file yet — nothing to clean
741
792
  }
742
793
  delete auth[pid];
743
- atomicWriteJson(authPath, auth);
794
+ atomicWriteCredentialJson(authPath, auth);
744
795
  const mr = this.host.modelRuntime?.();
745
796
  if (mr) {
746
797
  await mr.removeRuntimeApiKey(pid);
@@ -833,7 +884,7 @@ export class ModelAdminService {
833
884
  return;
834
885
  }
835
886
  delete data[pid];
836
- atomicWriteJson(authPath, data);
887
+ atomicWriteCredentialJson(authPath, data);
837
888
  // Clear every stored key so the provider returns to unconfigured.
838
889
  delete keyData[pid];
839
890
  this.writeProviderKeys(keyData);
@@ -1704,7 +1755,7 @@ export class ModelAdminService {
1704
1755
  if (graduated.length === 0)
1705
1756
  return graduated;
1706
1757
  try {
1707
- atomicWriteJson(this.modelsConfigPath(), { providers });
1758
+ atomicWriteCredentialJson(this.modelsConfigPath(), { providers });
1708
1759
  }
1709
1760
  catch {
1710
1761
  return [];
@@ -1741,7 +1792,7 @@ export class ModelAdminService {
1741
1792
  * config list + the picker. Callers emit their own notice. */
1742
1793
  async writeModelsConfigAndReload(providers, pid) {
1743
1794
  mkdirSync(this.host.agentDir, { recursive: true });
1744
- atomicWriteJson(this.modelsConfigPath(), { providers });
1795
+ atomicWriteCredentialJson(this.modelsConfigPath(), { providers });
1745
1796
  // Allow a models.json entry to reuse the provider credential already
1746
1797
  // stored in auth.json. Seed the shared runtime too, because older pi-ai
1747
1798
  // versions did not always fall back to stored credentials for a
@@ -1898,7 +1949,7 @@ export class ModelAdminService {
1898
1949
  return;
1899
1950
  }
1900
1951
  delete providers[providerId];
1901
- atomicWriteJson(this.modelsConfigPath(), { providers });
1952
+ atomicWriteCredentialJson(this.modelsConfigPath(), { providers });
1902
1953
  await this.host.modelRuntime?.()?.refresh();
1903
1954
  this.host.invalidatePiConfig?.();
1904
1955
  await this.listModelsConfig();
@@ -77,6 +77,7 @@ export const PRESET_FIELD_GROUPS = {
77
77
  "toolsWrap",
78
78
  "toolImagesEnabled",
79
79
  "keepRecentMessages",
80
+ "reversePagination",
80
81
  "showForkedParentSessions",
81
82
  "retainFinishedConversations",
82
83
  "openRecentSessionOnProjectSwitch",
@@ -84,6 +85,7 @@ export const PRESET_FIELD_GROUPS = {
84
85
  "quickPhrases",
85
86
  "quickPhrasesEnabled",
86
87
  "minimalNewChat",
88
+ "preserveDraftAcrossConversations",
87
89
  "devNoCache",
88
90
  "autoReload",
89
91
  ],
@@ -403,6 +405,12 @@ export const PRESET_FIELD_META = {
403
405
  hintZh: "消息列表尾部保持完整渲染的消息条数;更早的折叠为摘要行",
404
406
  hintEn: "Recent messages rendered in full; older ones collapse to summary rows",
405
407
  },
408
+ reversePagination: {
409
+ labelZh: "向上分页加载",
410
+ labelEn: "Load Earlier Messages",
411
+ hintZh: "默认仅挂载最近消息,向上滚动或点击加载更早历史,完全跳过视口占位符获得原生流畅度",
412
+ hintEn: "Only mount recent messages; scroll up or click to load earlier history with zero placeholders",
413
+ },
406
414
  showForkedParentSessions: {
407
415
  labelZh: "显示已分支的父会话",
408
416
  labelEn: "Show Forked Parent Sessions",
@@ -439,6 +447,12 @@ export const PRESET_FIELD_META = {
439
447
  hintZh: "新对话隐藏提示词模板并隐藏快捷短语,呈现现代极简风格",
440
448
  hintEn: "Hide prompt templates and quick phrases on new chat for a clean modern look",
441
449
  },
450
+ preserveDraftAcrossConversations: {
451
+ labelZh: "输入框文字跨对话保留",
452
+ labelEn: "Preserve Composer Text Across Conversations",
453
+ hintZh: "开启:输入文字切换别的会话不清空;关闭:仅保留当前会话文字,切换其他会话时清空或显示该会话已保留文字,切回时恢复当前会话文字",
454
+ hintEn: "Enabled: keep composer text when switching conversations. Disabled: retain text only for the current conversation",
455
+ },
442
456
  devNoCache: {
443
457
  labelZh: "开发者免缓存模式",
444
458
  labelEn: "Developer No-Cache Mode",
@@ -273,12 +273,14 @@ const PRESET_FIELD_KINDS = {
273
273
  toolsWrap: "bool",
274
274
  toolImagesEnabled: "bool",
275
275
  keepRecentMessages: "number",
276
+ reversePagination: "bool",
276
277
  showForkedParentSessions: "bool",
277
278
  retainFinishedConversations: "bool",
278
279
  openRecentSessionOnProjectSwitch: "bool",
279
280
  quickPhrases: "list",
280
281
  quickPhrasesEnabled: "bool",
281
282
  minimalNewChat: "bool",
283
+ preserveDraftAcrossConversations: "bool",
282
284
  devNoCache: "bool",
283
285
  autoReload: "bool",
284
286
  // -- engine ----------------------------------------------------------
@@ -47,12 +47,11 @@ export async function snapshotListeningPorts() {
47
47
  return m;
48
48
  }
49
49
  /**
50
- * Snapshot every process's parent pid → Map<pid, ppid>. Windows: one
51
- * PowerShell CIM pass (avoids spawning PowerShell once per pid); POSIX:
52
- * one `ps -Ao pid=,ppid=` pass. Returns undefined when the whole query
53
- * fails — callers should treat that as "cannot verify, stay conservative".
50
+ * Snapshot every process's parent pid & name → Map<pid, ProcessTreeNode>.
51
+ * Windows: one PowerShell CIM pass; POSIX: one `ps -Ao pid=,ppid=,comm=` pass.
52
+ * Returns undefined when query fails — callers should treat as unverified.
54
53
  */
55
- export async function snapshotProcessParents() {
54
+ export async function snapshotProcessTree() {
56
55
  try {
57
56
  const { execFile } = await import("node:child_process");
58
57
  const m = new Map();
@@ -61,23 +60,35 @@ export async function snapshotProcessParents() {
61
60
  "-NoProfile",
62
61
  "-NonInteractive",
63
62
  "-Command",
64
- 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId):$($_.ParentProcessId)" }',
63
+ 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId):$($_.ParentProcessId):$($_.Name)" }',
65
64
  ], { windowsHide: true, timeout: 10000 }, (err, stdout) => (err ? reject(err) : resolve(stdout))));
66
65
  for (const line of out.split(/\r?\n/)) {
67
- const [pid, ppid] = line.trim().split(":").map(Number);
68
- if (Number.isFinite(pid) && Number.isFinite(ppid))
69
- m.set(pid, ppid);
66
+ const trimmed = line.trim();
67
+ if (!trimmed)
68
+ continue;
69
+ const firstColon = trimmed.indexOf(":");
70
+ const secondColon = trimmed.indexOf(":", firstColon + 1);
71
+ if (firstColon === -1)
72
+ continue;
73
+ const pid = Number(trimmed.slice(0, firstColon));
74
+ const ppid = Number(secondColon === -1 ? trimmed.slice(firstColon + 1) : trimmed.slice(firstColon + 1, secondColon));
75
+ const name = secondColon === -1 ? undefined : trimmed.slice(secondColon + 1).trim() || undefined;
76
+ if (Number.isFinite(pid) && Number.isFinite(ppid)) {
77
+ m.set(pid, { ppid, ...(name ? { name } : {}) });
78
+ }
70
79
  }
71
80
  }
72
81
  else {
73
- const out = await new Promise((resolve, reject) => execFile("ps", ["-Ao", "pid=,ppid="], { timeout: 5000 }, (err, stdout) => err ? reject(err) : resolve(stdout)));
82
+ const out = await new Promise((resolve, reject) => execFile("ps", ["-Ao", "pid=,ppid=,comm="], { timeout: 5000 }, (err, stdout) => err ? reject(err) : resolve(stdout)));
74
83
  for (const line of out.split(/\r?\n/)) {
75
84
  const p = line.trim().split(/\s+/);
76
85
  if (p.length >= 2) {
77
86
  const pid = Number(p[0]);
78
87
  const ppid = Number(p[1]);
79
- if (Number.isFinite(pid) && Number.isFinite(ppid))
80
- m.set(pid, ppid);
88
+ const name = p.slice(2).join(" ").trim() || undefined;
89
+ if (Number.isFinite(pid) && Number.isFinite(ppid)) {
90
+ m.set(pid, { ppid, ...(name ? { name } : {}) });
91
+ }
81
92
  }
82
93
  }
83
94
  }
@@ -87,6 +98,97 @@ export async function snapshotProcessParents() {
87
98
  return undefined;
88
99
  }
89
100
  }
101
+ /**
102
+ * Snapshot every process's parent pid → Map<pid, ppid>.
103
+ * Retained for backward compatibility; powered by snapshotProcessTree.
104
+ */
105
+ export async function snapshotProcessParents() {
106
+ const tree = await snapshotProcessTree();
107
+ if (!tree)
108
+ return undefined;
109
+ const m = new Map();
110
+ for (const [pid, node] of tree) {
111
+ m.set(pid, node.ppid);
112
+ }
113
+ return m;
114
+ }
115
+ /**
116
+ * Batch lookup detailed process info (pid, ppid, name, commandLine, createdMs).
117
+ * Windows: single PowerShell CIM pass with filter; POSIX: `ps -o pid=,ppid=,etimes=,comm=,command=`.
118
+ */
119
+ export async function lookupProcessDetailsBatch(pids) {
120
+ const out = new Map();
121
+ const validPids = [...new Set(pids.filter((p) => Number.isInteger(p) && p > 0))];
122
+ if (validPids.length === 0)
123
+ return out;
124
+ try {
125
+ const { execFile } = await import("node:child_process");
126
+ if (process.platform === "win32") {
127
+ const filter = validPids.map((p) => `ProcessId=${p}`).join(" or ");
128
+ const command = [
129
+ `$filter = '${filter}';`,
130
+ `Get-CimInstance Win32_Process -Filter $filter | ForEach-Object {`,
131
+ ` $ts = if ($_.CreationDate) { [DateTimeOffset]::new($_.CreationDate).ToUnixTimeMilliseconds() } else { 0 };`,
132
+ ` $cmd = if ($_.CommandLine) { $_.CommandLine -replace "\\r?\\n", " " } else { "" };`,
133
+ ` "$($_.ProcessId)\`t$($_.ParentProcessId)\`t$($_.Name)\`t$ts\`t$cmd"`,
134
+ `}`,
135
+ ].join(" ");
136
+ const stdout = await new Promise((resolve, reject) => execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], { windowsHide: true, timeout: 8000 }, (err, res) => (err ? reject(err) : resolve(res))));
137
+ for (const line of stdout.split(/\r?\n/)) {
138
+ const trimmed = line.trim();
139
+ if (!trimmed)
140
+ continue;
141
+ const parts = trimmed.split("\t");
142
+ if (parts.length >= 3) {
143
+ const pid = Number(parts[0]);
144
+ const ppid = Number(parts[1]);
145
+ const name = parts[2] || undefined;
146
+ const ts = Number(parts[3]);
147
+ const cmd = parts.slice(4).join("\t").trim();
148
+ if (Number.isFinite(pid)) {
149
+ out.set(pid, {
150
+ pid,
151
+ ...(Number.isFinite(ppid) ? { ppid } : {}),
152
+ ...(name ? { name } : {}),
153
+ ...(Number.isFinite(ts) && ts > 0 ? { createdMs: ts } : {}),
154
+ ...(cmd ? { commandLine: cmd } : {}),
155
+ });
156
+ }
157
+ }
158
+ }
159
+ return out;
160
+ }
161
+ // POSIX (Linux / macOS)
162
+ const stdout = await new Promise((resolve, reject) => execFile("ps", ["-o", "pid=,ppid=,etimes=,comm=,command=", "-p", validPids.join(",")], { timeout: 5000 }, (err, res) => (err ? reject(err) : resolve(res))));
163
+ const now = Date.now();
164
+ for (const line of stdout.split(/\r?\n/)) {
165
+ const trimmed = line.trim();
166
+ if (!trimmed)
167
+ continue;
168
+ // 格式: pid ppid etimes comm command...
169
+ const match = trimmed.match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)(?:\s+(.*))?$/);
170
+ if (match) {
171
+ const pid = Number(match[1]);
172
+ const ppid = Number(match[2]);
173
+ const etimes = Number(match[3]);
174
+ const name = match[4];
175
+ const commandLine = match[5]?.trim();
176
+ const createdMs = Number.isFinite(etimes) ? now - etimes * 1000 : undefined;
177
+ out.set(pid, {
178
+ pid,
179
+ ppid,
180
+ name,
181
+ ...(commandLine ? { commandLine } : {}),
182
+ ...(createdMs !== undefined ? { createdMs } : {}),
183
+ });
184
+ }
185
+ }
186
+ }
187
+ catch {
188
+ // best effort — lookup failure just returns empty map
189
+ }
190
+ return out;
191
+ }
90
192
  /** Kill a pid and its whole process tree (cross-platform).
91
193
  *
92
194
  * The returned promise is only meaningful on Windows, where taskkill is itself
@@ -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 = 31;
11
+ export const PROTOCOL_VERSION = 32;
@@ -372,6 +372,7 @@ export class SettingsService {
372
372
  quickPhrases: [...this.settings.quickPhrases],
373
373
  quickPhrasesEnabled: this.settings.quickPhrasesEnabled,
374
374
  minimalNewChat: this.settings.minimalNewChat,
375
+ preserveDraftAcrossConversations: this.settings.preserveDraftAcrossConversations ?? false,
375
376
  quickPhrasesSeeded: this.host.stateStore.getQuickPhrasesSeeded(),
376
377
  mcpServers: mcp.servers,
377
378
  mcpGlobalConfigPath: mcp.globalPath,
@@ -662,6 +663,9 @@ export class SettingsService {
662
663
  if (partial.minimalNewChat !== undefined) {
663
664
  this.settings.minimalNewChat = partial.minimalNewChat;
664
665
  }
666
+ if (partial.preserveDraftAcrossConversations !== undefined) {
667
+ this.settings.preserveDraftAcrossConversations = Boolean(partial.preserveDraftAcrossConversations);
668
+ }
665
669
  // 统一工具开关 live 生效(ActiveSet 加减;失败静默,下次创建/reload 重放)。
666
670
  // 必须在 this.push() 前生效,保证 promptSnapshot 收集到的是最新的活跃工具集与完整提示词!
667
671
  if (toolGatingChanged)
@@ -151,6 +151,8 @@ export function previewKind(name) {
151
151
  return "image";
152
152
  if (PREVIEW_VIDEO_EXTS.has(ext))
153
153
  return "video";
154
+ if (PREVIEW_AUDIO_EXTS.has(ext))
155
+ return "audio";
154
156
  if (ext === "" || PREVIEW_TEXT_EXTS.has(ext))
155
157
  return "text";
156
158
  return "none";
@@ -259,6 +259,7 @@ export class UniversalSession {
259
259
  isDisposed: () => this.disposed,
260
260
  pluginTasks: () => [],
261
261
  cleanupMinutes: () => 0,
262
+ workspaceCwd: () => this.cwd,
262
263
  });
263
264
  // 加载现有会话或创建初始会话
264
265
  const existing = this.store.listConversations(this.cwd);
@@ -1845,6 +1846,7 @@ export class UniversalSession {
1845
1846
  quickPhrases: s?.quickPhrases ?? [],
1846
1847
  quickPhrasesEnabled: s?.quickPhrasesEnabled ?? true,
1847
1848
  minimalNewChat: s?.minimalNewChat ?? false,
1849
+ preserveDraftAcrossConversations: s?.preserveDraftAcrossConversations ?? false,
1848
1850
  quickPhrasesSeeded: this.stateStore?.getQuickPhrasesSeeded() ?? true,
1849
1851
  };
1850
1852
  this.send({ type: "settings_state", settings });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-web-ui",
3
- "version": "0.107.0",
3
+ "version": "0.108.0",
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": {
@@ -75,6 +75,7 @@
75
75
  "test:smoke:core": "node tests/run-smoke.mjs --core",
76
76
  "check:protocol": "node scripts/check-protocol-sync.mjs",
77
77
  "i18n:diff": "node scripts/i18n-diff.mjs",
78
+ "i18n:check": "node scripts/i18n-diff.mjs --check-packs",
78
79
  "release:notes": "node scripts/release-notes.mjs",
79
80
  "changelog:i18n": "node scripts/release-notes.mjs --unreleased",
80
81
  "test:freeze": "node tests/freeze-test.mjs",
@@ -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-fH5vhkAE.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-C_2Fl6f6.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:a,title:o,agentBash:s,active:c,running:l,exitCode:u,register:f}){let p=(0,b.useRef)(null),h=(0,b.useRef)(null),{locale:v}=d(),y=(0,b.useRef)(v);y.current=v;let T=n?JSON.stringify(n):``,E=(0,b.useRef)(l===!1);(0,b.useEffect)(()=>{let l=p.current;if(!l)return;let u=new r({theme:_(),fontFamily:`"SF Mono", "JetBrains Mono", ui-monospace, Menlo, Consolas, monospace`,fontSize:13,cursorBlink:!0,scrollback:8e3}),d=new i;u.loadAddon(d),u.open(l),h.current={term:u,fit:d},c&&u.focus();let v=()=>{u.options.theme=_()};window.addEventListener(m,v),u.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`&&u.hasSelection()){let e=u.textarea;return e&&(e.value=u.getSelection(),e.select()),!1}return!0});let b=f(e,t,{write:e=>u.write(w(e).clean),dispose:()=>u.dispose()}),C=()=>{try{d.fit(),g({type:`terminal_resize`,terminalId:t,conversationId:e,cols:u.cols,rows:u.rows})}catch{}},T=requestAnimationFrame(()=>{try{d.fit()}catch{}E.current||g(n?{type:`run_command`,terminalId:t,conversationId:e,command:n,cols:u.cols,rows:u.rows}:{type:`terminal_create`,terminalId:t,title:o,locale:y.current,agentBash:s,conversationId:e,cwd:a,cols:u.cols,rows:u.rows})}),D=u.onData(n=>{g({type:`terminal_input`,terminalId:t,conversationId:e,data:n})}),O=u.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`&&(l.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(()=>{l.offsetWidth>0&&l.offsetHeight>0&&C()}),L.observe(l)),()=>{cancelAnimationFrame(T),D.dispose(),O?.removeEventListener(`touchstart`,P),O?.removeEventListener(`touchmove`,F),O?.removeEventListener(`touchend`,I),O?.removeEventListener(`touchcancel`,I),window.removeEventListener(m,v),L?.disconnect(),b(),u.dispose(),h.current=null}},[e,t,T,f]),(0,b.useEffect)(()=>{if(!c)return;let n=requestAnimationFrame(()=>{let n=h.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)},[c]);let{t:D}=d(),O=(0,b.useRef)(void 0);return(0,b.useEffect)(()=>{if(l===O.current||(O.current=l,l!==!1))return;let e=h.current;e&&e.term.write(`\r\n\x1b[90m${D(`exitBanner`,{code:u??``})}\x1b[0m\r\n`)},[l,t,u]),(0,C.jsx)(`div`,{ref:p,className:`term-xterm ${c?``:`hidden`}`})}var E={name:``,command:``,cwd:"${pwd}"};function D({chat:e,terminal:t,uiTerminalToolbar:n,onUiAction:r}){let i=a(),[d,m]=(0,b.useState)(null),[_,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?m(null):e.terminals.some(e=>e.id===d)||m(e.terminals[e.terminals.length-1].id)},[e.terminals,d]),(0,b.useEffect)(()=>{e.terminalActiveId&&(m(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}),m(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),m(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),d===n){let t=e.terminals.filter(e=>e.id!==n);m(t.length>0?t[t.length-1].id:null)}},K=e=>(0,C.jsxs)(`div`,{className:`term-tab ${e.id===d?`active`:``}`,children:[(0,C.jsxs)(`button`,{type:`button`,className:`term-tab-main`,title:`${e.cwd}${e.command?`\n> ${e.command.command}`:``}`,onClick:()=>{I||(m(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 ${_?`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:[_&&(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===d,running:e.running,exitCode:e.exitCode,register:t.register},`${e.conversationId}:${e.id}`))]})]})}export{D as TerminalPanel};