pi-web-ui 0.101.0 → 0.103.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 (39) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +1 -1
  4. package/bin/pi-web-ui.mjs +13 -9
  5. package/dist/server/agent-service-daemon.js +19 -12
  6. package/dist/server/agent-service.js +255 -58
  7. package/dist/server/ask-user-question-tool.js +12 -2
  8. package/dist/server/bash-tool.js +19 -1
  9. package/dist/server/client-state.js +24 -1
  10. package/dist/server/dispatch-domain-handlers.js +69 -3
  11. package/dist/server/dsh/dsh-agent-service.js +21 -4
  12. package/dist/server/dsh/runtime/goal-rpc.mjs +5 -1
  13. package/dist/server/edit-soft-tool.js +15 -3
  14. package/dist/server/files-service.js +636 -14
  15. package/dist/server/index.js +7 -1
  16. package/dist/server/plugin-installer.js +6 -1
  17. package/dist/server/plugins.js +1 -0
  18. package/dist/server/preset-fields.js +28 -0
  19. package/dist/server/preset-share.js +8 -0
  20. package/dist/server/protocol-version.js +1 -1
  21. package/dist/server/read-tool.js +11 -4
  22. package/dist/server/remote-ssh-service.js +1314 -0
  23. package/dist/server/scm.js +16 -0
  24. package/dist/server/settings-service.js +15 -0
  25. package/dist/server/terminals.js +65 -20
  26. package/dist/server/tool-guards.js +18 -6
  27. package/dist/server/virtual-tui.js +258 -0
  28. package/dist/server/webui-context.js +109 -4
  29. package/package.json +7 -1
  30. package/themes/zhupi-dark.css +3 -14
  31. package/themes/zhupi.css +2 -16
  32. package/web/dist/assets/TerminalPanel-PIx1pMZ0.js +3 -0
  33. package/web/dist/assets/index-CYQdZEbx.css +1 -0
  34. package/web/dist/assets/index-CtaYhpZt.js +680 -0
  35. package/web/dist/index.html +4 -2
  36. package/web/dist/sw.js +1 -1
  37. package/web/dist/assets/TerminalPanel-DD7I5_aC.js +0 -3
  38. package/web/dist/assets/index-CpjA1YdT.css +0 -1
  39. package/web/dist/assets/index-nKn87VuM.js +0 -678
@@ -7,11 +7,12 @@
7
7
  */
8
8
  import { Dirent, existsSync, mkdirSync, readFileSync, statSync, writeFileSync, watch } from "node:fs";
9
9
  import { homedir } from "node:os";
10
- import { resolve, relative, sep, isAbsolute } from "node:path";
10
+ import { resolve, relative, sep, isAbsolute, posix } from "node:path";
11
11
  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
16
  export const IS_WIN32 = process.platform === "win32";
16
17
  /** 机器根虚拟路径:工作区「上一级」到达此处,列出所有盘符(Windows)/ "/"(posix)。
17
18
  * 这是 wire 字面量,前端 web/src/components/{RightPanel,FooterBar}.tsx 里同值使用。 */
@@ -332,8 +333,14 @@ export class FilesService {
332
333
  });
333
334
  }
334
335
  async listFiles(relPath) {
336
+ const rawCwd = this.host.getCwd();
337
+ if (isRemoteWorkspaceUri(rawCwd)) {
338
+ this.unwatchDir();
339
+ await this.listRemoteFiles(rawCwd, relPath);
340
+ return;
341
+ }
335
342
  const { resolve, sep, relative } = await import("node:path");
336
- const root = resolve(this.host.getCwd());
343
+ const root = resolve(rawCwd);
337
344
  let raw = relPath ?? "";
338
345
  // Expand a leading "~/" (path-bar input) to the home directory — same
339
346
  // rules as completePath/makeDir. The result is absolute, so it lands in
@@ -415,6 +422,11 @@ export class FilesService {
415
422
  * stalls (ok:false on unexpected failure).
416
423
  */
417
424
  async searchFiles(query, reqId) {
425
+ const activeCwd = this.host.getActiveCwd();
426
+ if (isRemoteWorkspaceUri(activeCwd)) {
427
+ await this.searchRemoteFiles(activeCwd, query, reqId);
428
+ return;
429
+ }
418
430
  const { join } = await import("node:path");
419
431
  const fsp = await import("node:fs/promises");
420
432
  const q = query.trim().toLowerCase();
@@ -422,7 +434,7 @@ export class FilesService {
422
434
  this.host.emit({ type: "search_files_result", reqId, ok: true, results: [] });
423
435
  return;
424
436
  }
425
- const root = resolve(this.host.getActiveCwd());
437
+ const root = resolve(activeCwd);
426
438
  const ignored = ignoredEntries();
427
439
  const MAX_RESULTS = 50;
428
440
  const MAX_VISITED = 20000;
@@ -499,7 +511,8 @@ export class FilesService {
499
511
  */
500
512
  async scmQuery(kind, reqId, arg) {
501
513
  const cwd = this.host.getActiveCwd();
502
- if (kind === "status")
514
+ const isRemote = isRemoteWorkspaceUri(cwd);
515
+ if (kind === "status" && !isRemote)
503
516
  this.watchGitDir(cwd);
504
517
  try {
505
518
  if (kind === "status") {
@@ -513,12 +526,21 @@ export class FilesService {
513
526
  return;
514
527
  }
515
528
  if (kind === "filediff" && arg?.path) {
516
- // Path stays inside the workspace (defense in depth — paths come
517
- // from our own listing, and execFile passes args verbatim anyway).
518
- const { resolve, relative } = await import("node:path");
519
- const rel = relative(resolve(cwd), resolve(cwd, arg.path));
520
- if (rel.startsWith("..") || rel === "")
521
- throw new Error(pick(this.lang(), "路径超出工作区", "Path is outside the workspace", "files.path.outside.workspace"));
529
+ if (isRemote) {
530
+ const parsed = parseRemoteWorkspaceUri(cwd);
531
+ const resolved = parsed ? resolveRemoteWorkspacePath(parsed.remotePath, arg.path) : null;
532
+ if (!resolved || !resolved.rel) {
533
+ throw new Error(pick(this.lang(), "路径超出工作区", "Path is outside the workspace", "files.path.outside.workspace"));
534
+ }
535
+ }
536
+ else {
537
+ // Path stays inside the workspace (defense in depth — paths come
538
+ // from our own listing, and execFile passes args verbatim anyway).
539
+ const { resolve, relative } = await import("node:path");
540
+ const rel = relative(resolve(cwd), resolve(cwd, arg.path));
541
+ if (rel.startsWith("..") || rel === "")
542
+ throw new Error(pick(this.lang(), "路径超出工作区", "Path is outside the workspace", "files.path.outside.workspace"));
543
+ }
522
544
  const { staged, worktree } = await scmFileDiff(cwd, arg.path, () => this.lang());
523
545
  this.host.emit({
524
546
  type: "scm_data",
@@ -742,9 +764,13 @@ export class FilesService {
742
764
  }
743
765
  /** Read a workspace file for the preview panel (size-capped, binary-safe). */
744
766
  async readFile(relPath) {
767
+ const root = this.host.getCwd();
768
+ if (isRemoteWorkspaceUri(root)) {
769
+ await this.readRemoteFile(root, relPath);
770
+ return;
771
+ }
745
772
  try {
746
773
  const fs = await import("node:fs/promises");
747
- const root = this.host.getCwd();
748
774
  const absWire = isAbsoluteWirePath(relPath);
749
775
  let abs;
750
776
  let rel;
@@ -871,8 +897,12 @@ export class FilesService {
871
897
  }
872
898
  /** Save text from the file preview panel within the active workspace. */
873
899
  async writeFile(relPath, text) {
900
+ const root = this.host.getCwd();
901
+ if (isRemoteWorkspaceUri(root)) {
902
+ await this.writeRemoteFile(root, relPath, text);
903
+ return;
904
+ }
874
905
  try {
875
- const root = this.host.getCwd();
876
906
  const absWire = isAbsoluteWirePath(relPath);
877
907
  let abs;
878
908
  let rel;
@@ -941,9 +971,13 @@ export class FilesService {
941
971
  * for the target dir (the recursive watcher may not cover it on posix).
942
972
  */
943
973
  async uploadFile(relDir, name, data) {
974
+ const root = this.host.getCwd();
975
+ if (isRemoteWorkspaceUri(root)) {
976
+ await this.uploadRemoteFile(root, relDir, name, data);
977
+ return;
978
+ }
944
979
  const emitErr = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
945
980
  try {
946
- const root = this.host.getCwd();
947
981
  const absDir = relDir ? isAbsoluteWirePath(relDir) : false;
948
982
  let wp;
949
983
  if (relDir && !absDir) {
@@ -1029,6 +1063,40 @@ export class FilesService {
1029
1063
  * with a notice; the picker refreshes its listing on its own.
1030
1064
  */
1031
1065
  async makeDir(input) {
1066
+ const rawCwd = this.host.getCwd();
1067
+ if (isRemoteWorkspaceUri(rawCwd) || isRemoteWorkspaceUri(input)) {
1068
+ try {
1069
+ const sshSvc = getGlobalRemoteSshService();
1070
+ if (!sshSvc)
1071
+ throw new Error("Remote SSH service not initialized");
1072
+ const uri = isRemoteWorkspaceUri(input) ? input.trim() : rawCwd;
1073
+ const parsed = parseRemoteWorkspaceUri(uri);
1074
+ if (!parsed)
1075
+ throw new Error("Invalid remote workspace URI");
1076
+ const targetAbs = isRemoteWorkspaceUri(input)
1077
+ ? parsed.remotePath
1078
+ : input.trim().startsWith("/")
1079
+ ? posix.normalize(input.trim())
1080
+ : posix.resolve(parsed.remotePath, input.trim());
1081
+ await sshSvc.sftpMkdirRecursive(uri, targetAbs);
1082
+ this.host.emit({
1083
+ type: "notice",
1084
+ level: "info",
1085
+ text: `已创建远程文件夹:${targetAbs}`,
1086
+ textEn: `Remote folder created: ${targetAbs}`,
1087
+ });
1088
+ return isRemoteWorkspaceUri(input) ? uri : targetAbs;
1089
+ }
1090
+ catch (err) {
1091
+ this.host.emit({
1092
+ type: "notice",
1093
+ level: "error",
1094
+ text: `创建远程文件夹失败:${err.message}`,
1095
+ textEn: `Failed to create remote folder: ${err.message}`,
1096
+ });
1097
+ return null;
1098
+ }
1099
+ }
1032
1100
  try {
1033
1101
  const fs = await import("node:fs/promises");
1034
1102
  const { resolve, sep, isAbsolute } = await import("node:path");
@@ -1121,6 +1189,11 @@ export class FilesService {
1121
1189
  }
1122
1190
  /** 在 dir 下新建空文件或空文件夹。已存在不覆盖(报错);成功后对 dir 推 file_changed。 */
1123
1191
  async createEntry(dir, name, kind) {
1192
+ const rawCwd = this.host.getCwd();
1193
+ if (isRemoteWorkspaceUri(rawCwd)) {
1194
+ await this.createRemoteEntry(rawCwd, dir, name, kind);
1195
+ return;
1196
+ }
1124
1197
  const err = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
1125
1198
  try {
1126
1199
  const fsp = await import("node:fs/promises");
@@ -1158,6 +1231,11 @@ export class FilesService {
1158
1231
  }
1159
1232
  /** 同目录内重命名(newName 只取 basename,不跨目录)。成功后对父目录推 file_changed。 */
1160
1233
  async renameEntry(path, newName) {
1234
+ const rawCwd = this.host.getCwd();
1235
+ if (isRemoteWorkspaceUri(rawCwd)) {
1236
+ await this.renameRemoteEntry(rawCwd, path, newName);
1237
+ return;
1238
+ }
1161
1239
  const err = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
1162
1240
  try {
1163
1241
  const fsp = await import("node:fs/promises");
@@ -1193,6 +1271,11 @@ export class FilesService {
1193
1271
  }
1194
1272
  /** 删除文件或目录(目录递归删)。工作区根/机器根/盘符根拒绝;成功后对父目录推 file_changed。 */
1195
1273
  async deleteEntry(path) {
1274
+ const rawCwd = this.host.getCwd();
1275
+ if (isRemoteWorkspaceUri(rawCwd)) {
1276
+ await this.deleteRemoteEntry(rawCwd, path);
1277
+ return;
1278
+ }
1196
1279
  const err = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
1197
1280
  try {
1198
1281
  const fsp = await import("node:fs/promises");
@@ -1218,6 +1301,11 @@ export class FilesService {
1218
1301
  /** 复制或移动(move=true 即剪切粘贴)。destDir 与源同目录即「创建副本」;
1219
1302
  * 重名自动加 " copy" 后缀;目录搬进自身/子目录拒绝;跨盘移动回落为复制+删源。 */
1220
1303
  async copyEntry(src, destDir, move) {
1304
+ const rawCwd = this.host.getCwd();
1305
+ if (isRemoteWorkspaceUri(rawCwd)) {
1306
+ await this.copyRemoteEntry(rawCwd, src, destDir, move);
1307
+ return;
1308
+ }
1221
1309
  const err = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
1222
1310
  try {
1223
1311
  const fsp = await import("node:fs/promises");
@@ -1408,12 +1496,16 @@ export class FilesService {
1408
1496
  */
1409
1497
  async completePath(input) {
1410
1498
  const empty = () => this.host.emit({ type: "path_completions", completions: [] });
1499
+ const cwd = this.host.getCwd();
1500
+ if (isRemoteWorkspaceUri(input) || (isRemoteWorkspaceUri(cwd) && !isAbsoluteWirePath(input.trim()))) {
1501
+ await this.completeRemotePath(isRemoteWorkspaceUri(input) ? input.trim() : cwd, input.trim());
1502
+ return;
1503
+ }
1411
1504
  try {
1412
1505
  const fs = await import("node:fs/promises");
1413
1506
  const { resolve, sep, isAbsolute } = await import("node:path");
1414
1507
  const { homedir } = await import("node:os");
1415
1508
  const home = homedir();
1416
- const cwd = this.host.getCwd();
1417
1509
  const isWin = IS_WIN32;
1418
1510
  const rawInput = input.trim();
1419
1511
  if (rawInput === "") {
@@ -1515,4 +1607,534 @@ export class FilesService {
1515
1607
  empty();
1516
1608
  }
1517
1609
  }
1610
+ // =========================================================================
1611
+ // 远程 SSH 工作区 (ssh://...) 专属文件操作实现
1612
+ // =========================================================================
1613
+ resolveRemoteTarget(rawCwd, p, allowRoot = false) {
1614
+ const parsed = parseRemoteWorkspaceUri(rawCwd);
1615
+ if (!parsed)
1616
+ return null;
1617
+ const trimmed = (p || "").trim();
1618
+ if (trimmed === MACHINE_ROOT || trimmed === MACHINE_ROOT + "/")
1619
+ return null;
1620
+ if (!trimmed) {
1621
+ if (!allowRoot)
1622
+ return null;
1623
+ return { abs: parsed.remotePath, rel: "", parentRel: "", absolute: false };
1624
+ }
1625
+ if (trimmed.startsWith("/")) {
1626
+ const abs = posix.normalize(trimmed);
1627
+ if (abs === "/" && !allowRoot)
1628
+ return null;
1629
+ const parentRel = abs === "/" ? "" : posix.dirname(abs);
1630
+ return { abs, rel: abs, parentRel, absolute: true };
1631
+ }
1632
+ const w = resolveRemoteWorkspacePath(parsed.remotePath, trimmed);
1633
+ if (!w || (!allowRoot && w.rel === ""))
1634
+ return null;
1635
+ const parentRel = w.rel.includes("/") ? w.rel.slice(0, w.rel.lastIndexOf("/")) : "";
1636
+ return { abs: w.abs, rel: w.rel, parentRel, absolute: false };
1637
+ }
1638
+ async listRemoteFiles(rawCwd, relPath) {
1639
+ const sshSvc = getGlobalRemoteSshService();
1640
+ const parsed = parseRemoteWorkspaceUri(rawCwd);
1641
+ if (!sshSvc || !parsed) {
1642
+ this.emitListError(rawCwd, "Remote SSH service is not available");
1643
+ return;
1644
+ }
1645
+ const raw = (relPath ?? "").trim();
1646
+ if (raw === MACHINE_ROOT || raw === MACHINE_ROOT + "/") {
1647
+ this.host.emit({
1648
+ type: "files",
1649
+ path: MACHINE_ROOT,
1650
+ parent: null,
1651
+ entries: [{ name: "/", path: "/", type: "dir" }],
1652
+ truncated: false,
1653
+ absolute: true,
1654
+ });
1655
+ return;
1656
+ }
1657
+ const isAbs = raw.startsWith("/");
1658
+ let targetAbs;
1659
+ let wirePath;
1660
+ let parentWire;
1661
+ if (isAbs) {
1662
+ targetAbs = posix.normalize(raw);
1663
+ wirePath = targetAbs;
1664
+ parentWire = targetAbs === "/" ? MACHINE_ROOT : posix.dirname(targetAbs) || "/";
1665
+ }
1666
+ else {
1667
+ const w = resolveRemoteWorkspacePath(parsed.remotePath, raw);
1668
+ if (!w) {
1669
+ this.host.emit({
1670
+ type: "notice",
1671
+ level: "warning",
1672
+ text: `路径超出工作区:${relPath ?? ""}`,
1673
+ textEn: `Path is outside the workspace: ${relPath ?? ""}`,
1674
+ });
1675
+ return;
1676
+ }
1677
+ targetAbs = w.abs;
1678
+ wirePath = w.rel;
1679
+ parentWire =
1680
+ w.rel === ""
1681
+ ? parsed.remotePath === "/"
1682
+ ? MACHINE_ROOT
1683
+ : posix.dirname(parsed.remotePath)
1684
+ : w.rel.includes("/")
1685
+ ? w.rel.slice(0, w.rel.lastIndexOf("/"))
1686
+ : "";
1687
+ }
1688
+ try {
1689
+ const rawEntries = await sshSvc.sftpReaddir(rawCwd, targetAbs);
1690
+ const ignored = IGNORED_ENTRIES_WIN;
1691
+ const out = [];
1692
+ for (const d of rawEntries) {
1693
+ if (ignored.has(d.name))
1694
+ continue;
1695
+ const entryPath = wirePath === ""
1696
+ ? d.name
1697
+ : wirePath.endsWith("/")
1698
+ ? `${wirePath.slice(0, -1)}/${d.name}`
1699
+ : `${wirePath}/${d.name}`;
1700
+ const entry = {
1701
+ name: d.name,
1702
+ path: entryPath,
1703
+ type: d.type,
1704
+ };
1705
+ if (d.type === "file")
1706
+ entry.kind = previewKind(d.name);
1707
+ out.push(entry);
1708
+ }
1709
+ out.sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type === "dir" ? -1 : 1));
1710
+ const MAX = 2000;
1711
+ const truncated = out.length > MAX;
1712
+ if (truncated)
1713
+ out.length = MAX;
1714
+ this.host.emit({
1715
+ type: "files",
1716
+ path: wirePath,
1717
+ parent: parentWire,
1718
+ entries: out,
1719
+ truncated,
1720
+ ...(isAbs ? { absolute: true } : {}),
1721
+ });
1722
+ }
1723
+ catch (err) {
1724
+ const e = err;
1725
+ this.host.emit({
1726
+ type: "files",
1727
+ path: wirePath,
1728
+ parent: parentWire,
1729
+ entries: [],
1730
+ truncated: false,
1731
+ ...(isAbs ? { absolute: true } : {}),
1732
+ });
1733
+ this.emitListError(targetAbs, e.message || String(err), e.code);
1734
+ }
1735
+ }
1736
+ async searchRemoteFiles(rawCwd, query, reqId) {
1737
+ const q = query.trim().toLowerCase();
1738
+ if (!q) {
1739
+ this.host.emit({ type: "search_files_result", reqId, ok: true, results: [] });
1740
+ return;
1741
+ }
1742
+ const sshSvc = getGlobalRemoteSshService();
1743
+ if (!sshSvc) {
1744
+ this.host.emit({ type: "search_files_result", reqId, ok: false, results: [] });
1745
+ return;
1746
+ }
1747
+ try {
1748
+ const cmd = `find . -maxdepth 8 \\( -name node_modules -o -name .git -o -name .pi-web \\) -prune -o -print 2>/dev/null | head -n 5000`;
1749
+ const res = await sshSvc.execInWorkspace(rawCwd, cmd, { timeoutMs: 8000 });
1750
+ const lines = res.stdout.split(/\r?\n/);
1751
+ const results = [];
1752
+ let truncated = false;
1753
+ for (const line of lines) {
1754
+ const clean = line.trim().replace(/^\.\//, "");
1755
+ if (!clean || clean === ".")
1756
+ continue;
1757
+ const name = posix.basename(clean);
1758
+ if (name.toLowerCase().includes(q)) {
1759
+ results.push({
1760
+ path: clean,
1761
+ name,
1762
+ type: "file",
1763
+ });
1764
+ if (results.length >= 50) {
1765
+ truncated = true;
1766
+ break;
1767
+ }
1768
+ }
1769
+ }
1770
+ this.host.emit({
1771
+ type: "search_files_result",
1772
+ reqId,
1773
+ ok: true,
1774
+ results,
1775
+ ...(truncated ? { truncated: true } : {}),
1776
+ });
1777
+ }
1778
+ catch {
1779
+ this.host.emit({ type: "search_files_result", reqId, ok: false, results: [] });
1780
+ }
1781
+ }
1782
+ async readRemoteFile(rawCwd, relPath) {
1783
+ try {
1784
+ const sshSvc = getGlobalRemoteSshService();
1785
+ if (!sshSvc)
1786
+ throw new Error("Remote SSH service not initialized");
1787
+ const t = this.resolveRemoteTarget(rawCwd, relPath);
1788
+ if (!t) {
1789
+ this.host.emit({
1790
+ type: "notice",
1791
+ level: "warning",
1792
+ text: `路径超出工作区:${relPath}`,
1793
+ textEn: `Path is outside the workspace: ${relPath}`,
1794
+ });
1795
+ return;
1796
+ }
1797
+ const st = await sshSvc.sftpStat(rawCwd, t.abs);
1798
+ if (!st.isFile) {
1799
+ this.host.emit({
1800
+ type: "notice",
1801
+ level: "warning",
1802
+ text: `不是文件:${relPath}`,
1803
+ textEn: `Not a file: ${relPath}`,
1804
+ });
1805
+ return;
1806
+ }
1807
+ const name = posix.basename(t.abs) || relPath;
1808
+ if (isOfficeFile(name) && st.size <= OFFICE_MAX_FILE_BYTES) {
1809
+ try {
1810
+ const { data } = await sshSvc.sftpReadFile(rawCwd, t.abs, OFFICE_MAX_FILE_BYTES);
1811
+ const office = extractOfficeText(name, data);
1812
+ if (office) {
1813
+ this.host.emit({
1814
+ type: "file_content",
1815
+ path: t.rel,
1816
+ name,
1817
+ text: office.text,
1818
+ truncated: office.truncated || data.length < st.size,
1819
+ binary: false,
1820
+ kind: "text",
1821
+ lines: countLines(Buffer.from(office.text)),
1822
+ size: st.size,
1823
+ });
1824
+ return;
1825
+ }
1826
+ }
1827
+ catch { }
1828
+ }
1829
+ const kind = previewKind(name);
1830
+ const { data, size } = await sshSvc.sftpReadFile(rawCwd, t.abs, MAX_PREVIEW_BYTES);
1831
+ if (looksLikeText(data)) {
1832
+ this.host.emit({
1833
+ type: "file_content",
1834
+ path: t.rel,
1835
+ name,
1836
+ text: decodeText(data),
1837
+ truncated: data.length < size,
1838
+ binary: false,
1839
+ kind: "text",
1840
+ lines: countLines(data),
1841
+ size,
1842
+ });
1843
+ }
1844
+ else {
1845
+ this.host.emit({
1846
+ type: "file_content",
1847
+ path: t.rel,
1848
+ name,
1849
+ text: hexDump(data),
1850
+ truncated: data.length < size,
1851
+ binary: true,
1852
+ kind: kind === "text" ? "text" : "none",
1853
+ lines: 0,
1854
+ size,
1855
+ });
1856
+ }
1857
+ }
1858
+ catch (err) {
1859
+ this.host.emit({
1860
+ type: "notice",
1861
+ level: "error",
1862
+ text: `读取远程文件失败:${err.message}`,
1863
+ textEn: `Failed to read remote file: ${err.message}`,
1864
+ });
1865
+ }
1866
+ }
1867
+ async writeRemoteFile(rawCwd, relPath, text) {
1868
+ try {
1869
+ const sshSvc = getGlobalRemoteSshService();
1870
+ if (!sshSvc)
1871
+ throw new Error("Remote SSH service not initialized");
1872
+ const t = this.resolveRemoteTarget(rawCwd, relPath);
1873
+ if (!t) {
1874
+ this.host.emit({
1875
+ type: "notice",
1876
+ level: "warning",
1877
+ text: `路径超出工作区:${relPath}`,
1878
+ textEn: `Path is outside the workspace: ${relPath}`,
1879
+ });
1880
+ return;
1881
+ }
1882
+ if (Buffer.byteLength(text, "utf8") > 2 * 1024 * 1024) {
1883
+ this.host.emit({
1884
+ type: "notice",
1885
+ level: "warning",
1886
+ text: "文件内容过大,无法保存(上限 2MB)",
1887
+ textEn: "File too large to save (2MB max)",
1888
+ });
1889
+ return;
1890
+ }
1891
+ await sshSvc.sftpWriteFile(rawCwd, t.abs, text);
1892
+ this.host.emit({
1893
+ type: "notice",
1894
+ level: "info",
1895
+ text: `已保存:${t.rel}`,
1896
+ textEn: `Saved: ${t.rel}`,
1897
+ });
1898
+ await this.readRemoteFile(rawCwd, t.rel);
1899
+ }
1900
+ catch (err) {
1901
+ this.host.emit({
1902
+ type: "notice",
1903
+ level: "error",
1904
+ text: `保存远程文件失败:${err.message}`,
1905
+ textEn: `Failed to save remote file: ${err.message}`,
1906
+ });
1907
+ }
1908
+ }
1909
+ async uploadRemoteFile(rawCwd, relDir, name, data) {
1910
+ const emitErr = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
1911
+ try {
1912
+ const sshSvc = getGlobalRemoteSshService();
1913
+ if (!sshSvc)
1914
+ throw new Error("Remote SSH service not initialized");
1915
+ const dirTarget = this.resolveRemoteTarget(rawCwd, relDir, true);
1916
+ if (!dirTarget) {
1917
+ emitErr(`路径超出工作区:${relDir}`, `Path outside workspace: ${relDir}`);
1918
+ return;
1919
+ }
1920
+ const safe = this.sanitizeName(name);
1921
+ if (!safe) {
1922
+ emitErr(`文件名不合法:${name}`, `Invalid file name: ${name}`);
1923
+ return;
1924
+ }
1925
+ if (isUploadDataTooLong(data.length)) {
1926
+ emitErr(`文件过大:${name}`, `File too large: ${name}`);
1927
+ return;
1928
+ }
1929
+ const buf = Buffer.from(data, "base64");
1930
+ if (buf.length === 0 || buf.length > MAX_UPLOAD_BYTES) {
1931
+ emitErr(`文件大小不合法:${name}`, `Invalid file size: ${name}`);
1932
+ return;
1933
+ }
1934
+ const destAbs = posix.join(dirTarget.abs, safe);
1935
+ const exists = await sshSvc.sftpStat(rawCwd, destAbs).catch(() => null);
1936
+ if (exists) {
1937
+ emitErr(`已存在:${safe}`, `Already exists: ${safe}`);
1938
+ return;
1939
+ }
1940
+ await sshSvc.sftpWriteFile(rawCwd, destAbs, buf, { createParents: true });
1941
+ const uploadRel = dirTarget.rel ? `${dirTarget.rel}/${safe}` : safe;
1942
+ this.host.emit({
1943
+ type: "notice",
1944
+ level: "info",
1945
+ text: `已上传:${uploadRel}`,
1946
+ textEn: `Uploaded: ${uploadRel}`,
1947
+ });
1948
+ this.host.emit({
1949
+ type: "file_changed",
1950
+ path: dirTarget.rel,
1951
+ });
1952
+ }
1953
+ catch (err) {
1954
+ emitErr(`上传文件失败:${err.message}`, `Upload failed: ${err.message}`);
1955
+ }
1956
+ }
1957
+ async createRemoteEntry(rawCwd, dir, name, kind) {
1958
+ const err = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
1959
+ try {
1960
+ const sshSvc = getGlobalRemoteSshService();
1961
+ if (!sshSvc)
1962
+ throw new Error("Remote SSH service not initialized");
1963
+ const safe = this.sanitizeName(name);
1964
+ if (!safe) {
1965
+ err("名称不合法:" + name, "Invalid name: " + name);
1966
+ return;
1967
+ }
1968
+ const parent = this.resolveRemoteTarget(rawCwd, dir, true);
1969
+ if (!parent) {
1970
+ err("此处不可新建:" + dir, "Cannot create here: " + dir);
1971
+ return;
1972
+ }
1973
+ const targetAbs = posix.join(parent.abs, safe);
1974
+ const existing = await sshSvc.sftpStat(rawCwd, targetAbs).catch(() => null);
1975
+ if (existing) {
1976
+ err("已存在同名项:" + safe, "Already exists: " + safe);
1977
+ return;
1978
+ }
1979
+ if (kind === "dir") {
1980
+ await sshSvc.sftpMkdirRecursive(rawCwd, targetAbs);
1981
+ }
1982
+ else {
1983
+ await sshSvc.sftpWriteFile(rawCwd, targetAbs, "");
1984
+ }
1985
+ this.host.emit({
1986
+ type: "notice",
1987
+ level: "info",
1988
+ text: (kind === "dir" ? "已新建文件夹:" : "已新建文件:") + safe,
1989
+ textEn: (kind === "dir" ? "Created folder: " : "Created file: ") + safe,
1990
+ });
1991
+ this.host.emit({ type: "file_changed", path: parent.rel });
1992
+ }
1993
+ catch (e) {
1994
+ err("新建失败:" + e.message, "Create failed: " + e.message);
1995
+ }
1996
+ }
1997
+ async renameRemoteEntry(rawCwd, pathStr, newName) {
1998
+ const err = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
1999
+ try {
2000
+ const sshSvc = getGlobalRemoteSshService();
2001
+ if (!sshSvc)
2002
+ throw new Error("Remote SSH service not initialized");
2003
+ const safe = this.sanitizeName(newName);
2004
+ if (!safe) {
2005
+ err("新名称不合法:" + newName, "Invalid name: " + newName);
2006
+ return;
2007
+ }
2008
+ const t = this.resolveRemoteTarget(rawCwd, pathStr);
2009
+ if (!t) {
2010
+ err("此处不可重命名:" + pathStr, "Cannot rename: " + pathStr);
2011
+ return;
2012
+ }
2013
+ const destAbs = posix.join(posix.dirname(t.abs), safe);
2014
+ if (destAbs === t.abs)
2015
+ return;
2016
+ const existing = await sshSvc.sftpStat(rawCwd, destAbs).catch(() => null);
2017
+ if (existing) {
2018
+ err("目标已存在:" + safe, "Already exists: " + safe);
2019
+ return;
2020
+ }
2021
+ await sshSvc.sftpRename(rawCwd, t.abs, destAbs);
2022
+ this.host.emit({
2023
+ type: "notice",
2024
+ level: "info",
2025
+ text: "已重命名为:" + safe,
2026
+ textEn: "Renamed to: " + safe,
2027
+ });
2028
+ this.host.emit({ type: "file_changed", path: t.parentRel });
2029
+ }
2030
+ catch (e) {
2031
+ err("重命名失败:" + e.message, "Rename failed: " + e.message);
2032
+ }
2033
+ }
2034
+ async deleteRemoteEntry(rawCwd, pathStr) {
2035
+ const err = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
2036
+ try {
2037
+ const sshSvc = getGlobalRemoteSshService();
2038
+ if (!sshSvc)
2039
+ throw new Error("Remote SSH service not initialized");
2040
+ const t = this.resolveRemoteTarget(rawCwd, pathStr);
2041
+ if (!t) {
2042
+ err("此处不可删除:" + pathStr, "Cannot delete: " + pathStr);
2043
+ return;
2044
+ }
2045
+ await sshSvc.sftpRemove(rawCwd, t.abs);
2046
+ const base = posix.basename(t.abs);
2047
+ this.host.emit({
2048
+ type: "notice",
2049
+ level: "info",
2050
+ text: "已删除:" + base,
2051
+ textEn: "Deleted: " + base,
2052
+ });
2053
+ this.host.emit({ type: "file_changed", path: t.parentRel });
2054
+ }
2055
+ catch (e) {
2056
+ err("删除失败:" + e.message, "Delete failed: " + e.message);
2057
+ }
2058
+ }
2059
+ async copyRemoteEntry(rawCwd, src, destDir, move) {
2060
+ const err = (text, textEn) => this.host.emit({ type: "notice", level: "error", text, textEn });
2061
+ try {
2062
+ const sshSvc = getGlobalRemoteSshService();
2063
+ if (!sshSvc)
2064
+ throw new Error("Remote SSH service not initialized");
2065
+ const s = this.resolveRemoteTarget(rawCwd, src);
2066
+ const d = this.resolveRemoteTarget(rawCwd, destDir, true);
2067
+ if (!s || !d) {
2068
+ err("无效的路径", "Invalid path");
2069
+ return;
2070
+ }
2071
+ const base = posix.basename(s.abs);
2072
+ let destAbs = posix.join(d.abs, base);
2073
+ if (destAbs === s.abs) {
2074
+ if (move)
2075
+ return;
2076
+ const ext = posix.extname(base);
2077
+ const stem = ext ? base.slice(0, -ext.length) : base;
2078
+ destAbs = posix.join(d.abs, `${stem} copy${ext}`);
2079
+ }
2080
+ await sshSvc.sftpCopy(rawCwd, s.abs, destAbs, move);
2081
+ this.host.emit({
2082
+ type: "notice",
2083
+ level: "info",
2084
+ text: (move ? "已移动:" : "已复制:") + posix.basename(destAbs),
2085
+ textEn: (move ? "Moved: " : "Copied: ") + posix.basename(destAbs),
2086
+ });
2087
+ this.host.emit({ type: "file_changed", path: d.rel });
2088
+ if (move && s.parentRel !== d.rel) {
2089
+ this.host.emit({ type: "file_changed", path: s.parentRel });
2090
+ }
2091
+ }
2092
+ catch (e) {
2093
+ err((move ? "移动失败:" : "复制失败:") + e.message);
2094
+ }
2095
+ }
2096
+ async completeRemotePath(rawCwd, rawInput) {
2097
+ const empty = () => this.host.emit({ type: "path_completions", completions: [] });
2098
+ try {
2099
+ const sshSvc = getGlobalRemoteSshService();
2100
+ const parsed = parseRemoteWorkspaceUri(rawCwd);
2101
+ if (!sshSvc || !parsed) {
2102
+ empty();
2103
+ return;
2104
+ }
2105
+ let targetPath = rawInput;
2106
+ if (isRemoteWorkspaceUri(rawInput)) {
2107
+ const p = parseRemoteWorkspaceUri(rawInput);
2108
+ targetPath = p ? p.remotePath + (rawInput.endsWith("/") ? "/" : "") : "/";
2109
+ }
2110
+ else if (!targetPath.startsWith("/")) {
2111
+ targetPath = posix.resolve(parsed.remotePath, targetPath);
2112
+ }
2113
+ const lastSlash = targetPath.lastIndexOf("/");
2114
+ const dirPart = lastSlash >= 0 ? targetPath.slice(0, lastSlash + 1) || "/" : "/";
2115
+ const prefix = lastSlash >= 0 ? targetPath.slice(lastSlash + 1) : targetPath;
2116
+ const entries = await sshSvc.sftpReaddir(rawCwd, dirPart).catch(() => null);
2117
+ if (!entries) {
2118
+ empty();
2119
+ return;
2120
+ }
2121
+ const completions = entries
2122
+ .filter((d) => d.name.startsWith(prefix))
2123
+ .map((e) => ({
2124
+ name: e.name,
2125
+ type: e.type,
2126
+ path: dirPart === "/" ? `/${e.name}` : `${dirPart.replace(/\/+$/, "")}/${e.name}`,
2127
+ }))
2128
+ .sort((a, b) => {
2129
+ if (a.type !== b.type)
2130
+ return a.type === "dir" ? -1 : 1;
2131
+ return a.name.localeCompare(b.name);
2132
+ })
2133
+ .slice(0, 100);
2134
+ this.host.emit({ type: "path_completions", completions });
2135
+ }
2136
+ catch {
2137
+ empty();
2138
+ }
2139
+ }
1518
2140
  }