fix: 文件夹状态显式化、保存回滚/冲突、远程显示名与路径防重
This commit is contained in:
commit
de4ec03cd0
10
CHANGELOG.md
10
CHANGELOG.md
|
|
@ -1,5 +1,15 @@
|
|||
# 更新日志
|
||||
|
||||
## 1.1.0 — 2026-11-12
|
||||
|
||||
### 修复
|
||||
- 文件夹配置读取区分 loading / ready / error:HTTP 503、非成功状态与解析异常不再伪装成空分组;首次失败只显示错误与重试,已有确认数据时保留并提示刷新失败;自动重试有界退避,网络恢复后重新读取。
|
||||
- 文件夹保存改为串行队列:保存期间保留上一次服务端确认状态,成功后采用宿主回包,失败回滚;409 冲突同时保留服务端版本与未保存草稿,可显式重放,绝不静默覆盖。
|
||||
- 基础目录行使用工作区确认标题(自定义名/远程目录名),不再把本地镜像 basename(如 `w123`)当远程工作区名称;成员行优先远程目录名;路径身份不变。
|
||||
- 右侧文件树根标签改为按完整 `title` 路径精确匹配镜像路径,移除 basename + `padding-left:6px` 的脆弱 DOM 猜测;同名本地目录不会被误改。
|
||||
- 远程路径防重:新输入与历史记录都走同一规范化(`~`/相对路径/绝对路径 + 远端 `pwd -P`);目录身份包含连接 ID;SSH 解析失败时明确报“无法确认是否重复”并拒绝创建,不再 fail-open 制造重复。
|
||||
- 复用已有远程记录时保留用户自定义标题,不被新输入的路径段覆盖。
|
||||
|
||||
## 1.0.0 — 2026-10-28
|
||||
|
||||
首个本地稳定版本,包名 `workspace-groups-local`。基于原项目扩展,保留原 MIT 许可证与版权声明。
|
||||
|
|
|
|||
359
lib/client.js
359
lib/client.js
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1,7 +1,7 @@
|
|||
import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
// node_modules/js-yaml/dist/js-yaml.mjs
|
||||
// node_modules/.pnpm/js-yaml@4.3.2/node_modules/js-yaml/dist/js-yaml.mjs
|
||||
function getDefaultExportFromCjs(x) {
|
||||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1057,17 +1057,20 @@ function expandRemoteHome(path, home) {
|
|||
}
|
||||
|
||||
/**
|
||||
* Resolve a remote path to its canonical absolute form via one SSH round
|
||||
* trip (also learns the remote $HOME). Returns { canonical, home }; on any
|
||||
* failure canonical falls back to the home-expanded light form and the
|
||||
* caller proceeds exactly as upstream would (fail-open).
|
||||
* Resolve a remote path to its canonical absolute identity through one SSH
|
||||
* round trip (also learns the remote $HOME). Returns a discriminated result:
|
||||
* ok:false is NOT "not a duplicate" — the caller must refuse to create
|
||||
* because it cannot prove the path is distinct.
|
||||
*/
|
||||
async function resolveRemoteCanonical(subprocess, p, rawPath) {
|
||||
const light = lightRemotePath(rawPath);
|
||||
if (!light) return { ok: false, error: "remotePath 为空", home: "" };
|
||||
try {
|
||||
const cmd = "printf '__DSH_HOME__%s\n' \"$HOME\"; cd " + shellQuotePath(light) + " 2>/dev/null && pwd -P";
|
||||
const r = await runRemote(subprocess, p, cmd, undefined, 64 * 1024, undefined, 15000);
|
||||
if (!r || !r.ok || !r.stdout) return { canonical: light, home: "" };
|
||||
if (!r || !r.ok) {
|
||||
return { ok: false, error: String((r && (r.error || r.stderr)) || "SSH 解析失败").trim() || "SSH 解析失败", home: "" };
|
||||
}
|
||||
let home = "";
|
||||
let resolved = "";
|
||||
const lines = String(r.stdout).split("\n");
|
||||
|
|
@ -1076,10 +1079,14 @@ async function resolveRemoteCanonical(subprocess, p, rawPath) {
|
|||
if (t.startsWith("__DSH_HOME__")) home = t.slice("__DSH_HOME__".length).trim();
|
||||
else if (t.startsWith("/")) resolved = t;
|
||||
}
|
||||
if (!resolved) return { canonical: expandRemoteHome(light, home), home: home };
|
||||
return { canonical: lightRemotePath(resolved), home: home };
|
||||
if (!resolved) {
|
||||
// cd failed (missing directory / permission / shell error): identity is
|
||||
// unknown, never silently treated as a new directory.
|
||||
return { ok: false, error: "无法解析远端目录(不存在或不可访问):" + light, home: home };
|
||||
}
|
||||
return { ok: true, canonical: lightRemotePath(resolved), home: home };
|
||||
} catch (e) {
|
||||
return { canonical: light, home: "" };
|
||||
return { ok: false, error: String(e && e.message ? e.message : e), home: "" };
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -4929,25 +4936,47 @@ function apply(ctx, config) {
|
|||
// (或宿主重启丢了原生注册的那一条)必须在这里被"接管",而不是再造一条 ——
|
||||
// 否则设置面板里会出现两条一模一样的工作区,删其中一条还会连带删掉另一条的会话行。
|
||||
const prefsNow = settingsFace.read();
|
||||
// [workspace-groups-remote patch] Canonical-path reuse: compare
|
||||
// light-normalized spellings first; on a miss, resolve once over SSH
|
||||
// (fail-open) and compare canonical forms, so ~/x, x/ and the absolute
|
||||
// form of one directory all reuse the existing record instead of
|
||||
// registering a duplicate workspace + mirror. The stored spelling
|
||||
// converges to the matched/canonical form below.
|
||||
let existing = prefsNow.workspaces.find((w) => w && w.profileId === a.profileId && lightRemotePath(w.remotePath) === lightRemotePath(a.remotePath));
|
||||
if (existing) {
|
||||
a.remotePath = lightRemotePath(a.remotePath);
|
||||
} else {
|
||||
const resolvedCanonical = await resolveRemoteCanonical(subprocess, p, a.remotePath);
|
||||
a.remotePath = resolvedCanonical.canonical;
|
||||
existing = prefsNow.workspaces.find((w) => w && w.profileId === a.profileId && expandRemoteHome(lightRemotePath(w.remotePath), resolvedCanonical.home) === resolvedCanonical.canonical);
|
||||
// [workspace-groups-remote patch] Canonical-path reuse: resolve the new
|
||||
// spelling once over SSH and resolve every existing record of the same
|
||||
// connection with the same rule (light form + remote $HOME + pwd -P),
|
||||
// so relative/~, trailing-slash and symlink spellings converge on one
|
||||
// directory identity. A resolution failure is NOT "not a duplicate":
|
||||
// creation is refused with an actionable error instead of silently
|
||||
// registering a second workspace.
|
||||
const targetResolved = await resolveRemoteCanonical(subprocess, p, a.remotePath);
|
||||
if (targetResolved.ok !== true) {
|
||||
return { ok: false, error: "无法确认远端路径是否重复:" + targetResolved.error + ";未创建新工作区" };
|
||||
}
|
||||
const sameProfile = prefsNow.workspaces.filter((w) => w && w.profileId === a.profileId && typeof w.remotePath === "string");
|
||||
let existing = undefined;
|
||||
for (const record of sameProfile) {
|
||||
const light = lightRemotePath(record.remotePath);
|
||||
// Fast path: the spelling expands to exactly the resolved target.
|
||||
if (expandRemoteHome(light, targetResolved.home) === targetResolved.canonical) {
|
||||
existing = record;
|
||||
break;
|
||||
}
|
||||
// Slow path: resolve the old record with the SAME rules. This catches
|
||||
// relative paths, symlinks and historical spellings the old partial
|
||||
// expansion missed. A failure aborts instead of assuming uniqueness.
|
||||
const candidate = await resolveRemoteCanonical(subprocess, p, record.remotePath);
|
||||
if (candidate.ok !== true) {
|
||||
return { ok: false, error: "无法确认是否与已有远程工作区「" + String(record.title || record.id) + "」重复:" + candidate.error + ";未创建新工作区" };
|
||||
}
|
||||
if (candidate.canonical === targetResolved.canonical) {
|
||||
existing = record;
|
||||
break;
|
||||
}
|
||||
}
|
||||
a.remotePath = existing ? String(existing.remotePath) : targetResolved.canonical;
|
||||
const wsId = existing ? existing.id : ("w" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6));
|
||||
// 默认标题取远程路径最后一段目录名(如 ~/proj/DSH_Test → DSH_Test);
|
||||
// 取不到有效段(如 ~/ 或 /)时回退为 连接名:远程路径。
|
||||
// [workspace-groups-remote patch] Reuse keeps the user's existing
|
||||
// title; only a new record (or an explicit a.title) derives one from
|
||||
// the path. Otherwise "reuse" could silently rename a custom workspace.
|
||||
const lastSeg = String(a.remotePath).replace(/\/+$/, "").split("/").pop();
|
||||
const title = a.title || (lastSeg && lastSeg !== "~" ? lastSeg : (p.name + ":" + a.remotePath));
|
||||
const title = a.title || (existing && existing.title) || (lastSeg && lastSeg !== "~" ? lastSeg : (p.name + ":" + a.remotePath));
|
||||
// 本地镜像目录:作为原生工作区注册进 workspaceRegistry,会话 cwd 即指向它。
|
||||
// 根目录走 mirrorBaseDir()(与 fs 处理器的镜像判定同一处,避免两处各写一遍后漂移)。
|
||||
// 复用旧条目时沿用它原来的镜像目录 —— 里面可能有用户没推回去的本地改动。
|
||||
|
|
|
|||
|
|
@ -26,12 +26,26 @@ export interface FoldersSnapshot {
|
|||
readonly remoteBase?: string;
|
||||
}
|
||||
/**
|
||||
* Fetch the stored folder overlay.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @returns the overlay plus the reported mirror base; the empty document on any
|
||||
* failure.
|
||||
* One folder-overlay read result. A failed read must never masquerade as the
|
||||
* empty document: the browser uses `ok` to keep the last confirmed rows and
|
||||
* show a retryable error instead of rendering every member as a duplicate.
|
||||
*/
|
||||
export declare function loadFolders(fetchImpl?: typeof fetch): Promise<FoldersSnapshot>;
|
||||
export interface FoldersLoadResult extends FoldersSnapshot {
|
||||
readonly ok: boolean;
|
||||
/** Human-readable failure reason; absent on success. */
|
||||
readonly error?: string;
|
||||
}
|
||||
/**
|
||||
* Fetch the stored folder overlay.
|
||||
*
|
||||
* A non-2xx response, a malformed body or a transport error is returned as
|
||||
* `ok:false` with the reason. The empty document is still present for callers
|
||||
* that only need a safe value, but `ok` is the authority: the browser must not
|
||||
* treat a failed read as "no folders".
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @param signal - optional cancellation for a superseded read/retry.
|
||||
*/
|
||||
export declare function loadFolders(fetchImpl?: typeof fetch, signal?: AbortSignal): Promise<FoldersLoadResult>;
|
||||
/**
|
||||
* Read a whole folder document off the wire (GET response, PUT echo or the
|
||||
* 409 conflict body), or null when it is not a version-1 document.
|
||||
|
|
@ -45,7 +59,9 @@ export declare function parseWireDocument(source: Record<string, unknown>): Fold
|
|||
*/
|
||||
export declare class FoldersConflictError extends Error {
|
||||
readonly current: FoldersDocument;
|
||||
constructor(current: FoldersDocument);
|
||||
/** The unsaved document the failed PUT attempted to write. */
|
||||
readonly attempted: FoldersDocument;
|
||||
constructor(current: FoldersDocument, attempted?: FoldersDocument);
|
||||
}
|
||||
/**
|
||||
* Store the whole folder overlay.
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
*/
|
||||
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
|
||||
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.sectionList' | 'folder.sectionAdd' | 'folder.emptyHint' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.conflict' | 'folder.removeError' | 'folder.removeRemotePrompt' | 'folder.removeRemoteDelete' | 'folder.removeRemoteOnly' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'folder.cloudSection' | 'folder.profileLabel' | 'folder.remotePathLabel' | 'folder.remotePathPlaceholder' | 'folder.remotePathOrName' | 'folder.createAndAdd' | 'folder.cloudNoteBoth' | 'folder.addRemote' | 'folder.noProfiles' | 'folder.profilesError' | 'folder.cloudTag' | 'folder.localTag' | 'folder.memberMissing' | 'folder.memberNested' | 'folder.alreadyRoot' | 'folder.addAria' | 'folder.tabLocal' | 'folder.tabCloud' | 'folder.pickLocal' | 'folder.localNote' | 'folder.localIntoRemote' | 'folder.cloudNote' | 'folder.browse' | 'folder.browseTitle' | 'folder.browseListAria' | 'folder.browseNote' | 'folder.browseFailed' | 'folder.chooseHere' | 'folder.up' | 'folder.home' | 'folder.refresh' | 'folder.loading' | 'folder.emptyDir' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'group.icon.section.common' | 'group.icon.section.lab' | 'group.icon.section.materials' | 'group.icon.section.characterization' | 'group.icon.section.devices' | 'group.icon.section.emoji' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'section.defaultWorkspace' | 'manual.saveError' | 'manual.conflict' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
|
||||
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.sectionList' | 'folder.sectionAdd' | 'folder.emptyHint' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.conflict' | 'folder.removeError' | 'folder.removeRemotePrompt' | 'folder.removeRemoteDelete' | 'folder.removeRemoteOnly' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'folder.cloudSection' | 'folder.profileLabel' | 'folder.remotePathLabel' | 'folder.remotePathPlaceholder' | 'folder.remotePathOrName' | 'folder.createAndAdd' | 'folder.cloudNoteBoth' | 'folder.addRemote' | 'folder.noProfiles' | 'folder.profilesError' | 'folder.cloudTag' | 'folder.localTag' | 'folder.memberMissing' | 'folder.memberNested' | 'folder.alreadyRoot' | 'folder.addAria' | 'folder.tabLocal' | 'folder.tabCloud' | 'folder.pickLocal' | 'folder.localNote' | 'folder.localIntoRemote' | 'folder.cloudNote' | 'folder.browse' | 'folder.browseTitle' | 'folder.browseListAria' | 'folder.browseNote' | 'folder.browseFailed' | 'folder.chooseHere' | 'folder.up' | 'folder.home' | 'folder.refresh' | 'folder.loading' | 'folder.loadingState' | 'folder.loadError' | 'folder.refreshError' | 'folder.retry' | 'folder.retryDraft' | 'folder.discardDraft' | 'folder.conflictDetail' | 'folder.emptyDir' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'group.icon.section.common' | 'group.icon.section.lab' | 'group.icon.section.materials' | 'group.icon.section.characterization' | 'group.icon.section.devices' | 'group.icon.section.emoji' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'section.defaultWorkspace' | 'manual.saveError' | 'manual.conflict' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
|
||||
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
|
||||
/** Simplified Chinese dictionary. */
|
||||
export declare const zh: WorkspaceGroupsDict;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "workspace-groups-remote",
|
||||
"version": "1.0.3",
|
||||
"version": "1.1.0",
|
||||
"description": "Merged DSH bundle: the workspace-groups sidebar manager (category -> project -> session grouped tree, session tab strip) plus dsh-remote-ssh (VSCode Remote-SSH-like remote development: remote workspaces, file access, integrated terminal) in one installable package.",
|
||||
"keywords": [
|
||||
"dsh",
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -35,6 +35,166 @@ if (body.endsWith(TAIL + '\n')) body = body.slice(0, -(TAIL.length + 1))
|
|||
else if (body.endsWith(TAIL)) body = body.slice(0, -TAIL.length)
|
||||
else throw new Error('remote-ssh client: tail anchor mismatch')
|
||||
|
||||
// [workspace-groups-remote patch] Replace the upstream root-label heuristic
|
||||
// (basename + inline padding-left:6px) with an exact full-path identity match.
|
||||
// better-sidebar's RootRow carries the complete directory in `title`; only an
|
||||
// element whose title equals a remote workspace's mirrorPath is rewritten, so
|
||||
// a same-named local directory can never be relabelled by mistake. If a future
|
||||
// shell drops that attribute nothing is changed (safe degradation).
|
||||
const ROOT_LABEL_OLD = ` // ---- 文件树根标签:显示远程目录名,而不是本地镜像目录 ID(issue #9)----
|
||||
// better-sidebar「文件」页签的树根标签取自会话 cwd(= 本地镜像路径)的 basename,
|
||||
// 于是显示成镜像目录 ID(如 wmirror3)。这条链路不经过任何 fs.* 路由,
|
||||
// 而 Host 侧 session.cwd 虽然已返回 root 字段,客户端只消费 cwd
|
||||
// (client-registry 的 api.sessionCwd(...).then(r => setFetchedCwd(r.cwd)),
|
||||
// 另有 useSessionCwd 直接读客户端会话列表的 cwd),因此只能在渲染层替换文本。
|
||||
// 定位不依赖构建期哈希类名:根行是树里唯一带内联 padding-left:6px 的行,
|
||||
// 仅当该行内的纯文本节点 === 某远程工作区的镜像 basename 时才替换(幂等、可自愈)。
|
||||
var watchedRootLabels = []; // 已替换的标签元素:1s 幂等复检,抵消 React 重渲染
|
||||
function refreshRootLabels(workspaces) {
|
||||
var next = {};
|
||||
for (var i = 0; i < (workspaces || []).length; i++) {
|
||||
var w = workspaces[i] || {};
|
||||
var mirror = String(w.mirrorPath || "").replace(/[\\\\/]+$/, "");
|
||||
var remote = String(w.remotePath || "").replace(/[\\\\/]+$/, "");
|
||||
if (!mirror || !remote) continue;
|
||||
var mb = mirror.split(/[\\\\/]/).pop();
|
||||
var rb = remote.split(/[\\\\/]/).pop();
|
||||
if (mb && rb && mb !== rb) next[mb] = { label: rb, remotePath: remote };
|
||||
}
|
||||
rootLabels = next;
|
||||
}
|
||||
/** 根行判据:自身或 ≤3 层祖先带内联 padding-left:6px(better-sidebar 根行样式)。 */
|
||||
function isRootRow(el) {
|
||||
var node = el;
|
||||
for (var hop = 0; hop < 3 && node; hop++) {
|
||||
var style = node.getAttribute ? node.getAttribute("style") : null;
|
||||
if (style && /padding-left:\\s*6px/i.test(String(style))) return true;
|
||||
node = node.parentElement;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/** 单个标签替换:纯文本 + 命中镜像 basename + 位于根行 → 换成远程目录名。 */
|
||||
function fixRootLabel(el) {
|
||||
var text = (el.textContent || "").trim();
|
||||
if (!text) return false;
|
||||
var hit = rootLabels[text];
|
||||
if (hit === undefined) {
|
||||
// 文本已是远程目录名(上一轮替换过)→ 幂等成功;否则与本插件无关
|
||||
return el.getAttribute && el.getAttribute("data-rssh-root-label") === "1";
|
||||
}
|
||||
if (el.childElementCount > 0) return false; // 只改纯文本节点
|
||||
if (!isRootRow(el)) return false; // 非根行(例如同名子条目)不动
|
||||
el.textContent = hit.label;
|
||||
if (el.setAttribute) {
|
||||
el.setAttribute("data-rssh-root-label", "1");
|
||||
el.setAttribute("title", hit.remotePath); // 悬停可见完整远程路径
|
||||
}
|
||||
watchRootLabel(el);
|
||||
return true;
|
||||
}
|
||||
function watchRootLabel(el) {
|
||||
for (var i = 0; i < watchedRootLabels.length; i++) { if (watchedRootLabels[i] === el) return; }
|
||||
watchedRootLabels.push(el);
|
||||
}
|
||||
function recheckRootLabels() {
|
||||
for (var i = watchedRootLabels.length - 1; i >= 0; i--) {
|
||||
var el = watchedRootLabels[i];
|
||||
if (!el || !el.isConnected) { watchedRootLabels.splice(i, 1); continue; }
|
||||
fixRootLabel(el);
|
||||
}
|
||||
}
|
||||
function applyRootLabelsIn(root) {
|
||||
if (!root || !root.querySelectorAll) return;
|
||||
try {
|
||||
var nodes = root.querySelectorAll("span,div");
|
||||
for (var i = 0; i < nodes.length; i++) fixRootLabel(nodes[i]);
|
||||
if (root.nodeType === 1) fixRootLabel(root);
|
||||
} catch (e) {}
|
||||
}`
|
||||
|
||||
const ROOT_LABEL_NEW = ` // ---- 文件树根标签:按完整镜像路径精确认行(issue #9)----
|
||||
// better-sidebar 的根行 title 是完整目录路径(RootRow title={path})。
|
||||
// 只在该 title 精确等于某个远程工作区的 mirrorPath 时才改写名称:不再
|
||||
// 按 basename 或内联 padding-left 猜测目录身份,因此同名本地目录不会
|
||||
// 被误改;属性缺席时保持原样(安全降级)。
|
||||
var watchedRootLabels = []; // 已替换的标签元素:1s 幂等复检,抵消 React 重渲染
|
||||
var rootLabels = {};
|
||||
function normRemotePath(value) {
|
||||
return String(value == null ? "" : value).replace(/[\\\\/]+$/, "");
|
||||
}
|
||||
function refreshRootLabels(workspaces) {
|
||||
var next = {};
|
||||
for (var i = 0; i < (workspaces || []).length; i++) {
|
||||
var w = workspaces[i] || {};
|
||||
var mirror = normRemotePath(w.mirrorPath);
|
||||
var remote = normRemotePath(w.remotePath);
|
||||
if (!mirror || !remote) continue;
|
||||
var title = normTitle(w.title);
|
||||
var label = title || remote.split(/[\\\\/]/).pop();
|
||||
if (label) next[mirror] = { label: label, remotePath: remote, mirrorPath: mirror };
|
||||
}
|
||||
rootLabels = next;
|
||||
}
|
||||
/** The root row's own full path, from the explicit attributes only. */
|
||||
function rootPathOf(el) {
|
||||
var explicit = el && el.getAttribute ? el.getAttribute("data-rssh-root-mirror") : null;
|
||||
if (explicit) return normRemotePath(explicit);
|
||||
var title = el && el.getAttribute ? el.getAttribute("title") : null;
|
||||
return title ? normRemotePath(title) : "";
|
||||
}
|
||||
/** Direct leaf <span> that prints the folder name (no nested markup). */
|
||||
function rootLabelSpanOf(el) {
|
||||
var children = el && el.children ? el.children : [];
|
||||
for (var i = 0; i < children.length; i++) {
|
||||
if (String(children[i].tagName || "").toLowerCase() === "span" && children[i].childElementCount === 0) return children[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/** Exact full-path hit → replace only the leaf name span. */
|
||||
function fixRootLabel(el) {
|
||||
if (!el || !el.getAttribute) return false;
|
||||
var path = rootPathOf(el);
|
||||
if (!path) return false;
|
||||
var hit = rootLabels[path];
|
||||
if (hit === undefined) return false;
|
||||
var span = rootLabelSpanOf(el);
|
||||
if (!span) return false;
|
||||
var base = path.split(/[\\\\/]/).pop();
|
||||
var text = normTitle(span.textContent);
|
||||
if (text !== base && el.getAttribute("data-rssh-root-label") !== "1") return false;
|
||||
span.textContent = hit.label;
|
||||
el.setAttribute("data-rssh-root-label", "1");
|
||||
el.setAttribute("data-rssh-root-mirror", hit.mirrorPath);
|
||||
el.setAttribute("title", hit.remotePath); // 悬停可见完整远程路径
|
||||
watchRootLabel(el);
|
||||
return true;
|
||||
}
|
||||
function watchRootLabel(el) {
|
||||
for (var i = 0; i < watchedRootLabels.length; i++) { if (watchedRootLabels[i] === el) return; }
|
||||
watchedRootLabels.push(el);
|
||||
}
|
||||
function recheckRootLabels() {
|
||||
for (var i = watchedRootLabels.length - 1; i >= 0; i--) {
|
||||
var el = watchedRootLabels[i];
|
||||
if (!el || !el.isConnected) { watchedRootLabels.splice(i, 1); continue; }
|
||||
fixRootLabel(el);
|
||||
}
|
||||
}
|
||||
function applyRootLabelsIn(root) {
|
||||
if (!root || !root.querySelectorAll) return;
|
||||
try {
|
||||
// Only elements carrying the full path title are candidates; no
|
||||
// text/basename or inline-style scan.
|
||||
var nodes = root.querySelectorAll("[title]");
|
||||
for (var i = 0; i < nodes.length; i++) fixRootLabel(nodes[i]);
|
||||
if (root.nodeType === 1) fixRootLabel(root);
|
||||
} catch (e) {}
|
||||
}`
|
||||
|
||||
const occurrences = body.split(ROOT_LABEL_OLD).length - 1
|
||||
if (occurrences !== 1) throw new Error('remote-ssh client: root-label block anchor found ' + occurrences + ' times')
|
||||
body = body.replace(ROOT_LABEL_OLD, ROOT_LABEL_NEW)
|
||||
|
||||
const out = header
|
||||
+ '// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---\n'
|
||||
+ '// Upstream registers this factory under its own package id; the merged\n'
|
||||
|
|
|
|||
|
|
@ -69,17 +69,20 @@ function expandRemoteHome(path, home) {
|
|||
}
|
||||
|
||||
/**
|
||||
* Resolve a remote path to its canonical absolute form via one SSH round
|
||||
* trip (also learns the remote $HOME). Returns { canonical, home }; on any
|
||||
* failure canonical falls back to the home-expanded light form and the
|
||||
* caller proceeds exactly as upstream would (fail-open).
|
||||
* Resolve a remote path to its canonical absolute identity through one SSH
|
||||
* round trip (also learns the remote $HOME). Returns a discriminated result:
|
||||
* ok:false is NOT "not a duplicate" — the caller must refuse to create
|
||||
* because it cannot prove the path is distinct.
|
||||
*/
|
||||
async function resolveRemoteCanonical(subprocess, p, rawPath) {
|
||||
const light = lightRemotePath(rawPath);
|
||||
if (!light) return { ok: false, error: "remotePath 为空", home: "" };
|
||||
try {
|
||||
const cmd = "printf '__DSH_HOME__%s\\n' \\"$HOME\\"; cd " + shellQuotePath(light) + " 2>/dev/null && pwd -P";
|
||||
const r = await runRemote(subprocess, p, cmd, undefined, 64 * 1024, undefined, 15000);
|
||||
if (!r || !r.ok || !r.stdout) return { canonical: light, home: "" };
|
||||
if (!r || !r.ok) {
|
||||
return { ok: false, error: String((r && (r.error || r.stderr)) || "SSH 解析失败").trim() || "SSH 解析失败", home: "" };
|
||||
}
|
||||
let home = "";
|
||||
let resolved = "";
|
||||
const lines = String(r.stdout).split("\\n");
|
||||
|
|
@ -88,10 +91,14 @@ async function resolveRemoteCanonical(subprocess, p, rawPath) {
|
|||
if (t.startsWith("__DSH_HOME__")) home = t.slice("__DSH_HOME__".length).trim();
|
||||
else if (t.startsWith("/")) resolved = t;
|
||||
}
|
||||
if (!resolved) return { canonical: expandRemoteHome(light, home), home: home };
|
||||
return { canonical: lightRemotePath(resolved), home: home };
|
||||
if (!resolved) {
|
||||
// cd failed (missing directory / permission / shell error): identity is
|
||||
// unknown, never silently treated as a new directory.
|
||||
return { ok: false, error: "无法解析远端目录(不存在或不可访问):" + light, home: home };
|
||||
}
|
||||
return { ok: true, canonical: lightRemotePath(resolved), home: home };
|
||||
} catch (e) {
|
||||
return { canonical: light, home: "" };
|
||||
return { ok: false, error: String(e && e.message ? e.message : e), home: "" };
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -143,20 +150,39 @@ if (typeof runRemote !== 'function' || typeof shellQuotePath !== 'function') {
|
|||
|
||||
const FIND_ANCHOR = ' const existing = prefsNow.workspaces.find((w) => w && w.profileId === a.profileId && String(w.remotePath) === String(a.remotePath));'
|
||||
|
||||
const FIND_REPLACEMENT = ` // [workspace-groups-remote patch] Canonical-path reuse: compare
|
||||
// light-normalized spellings first; on a miss, resolve once over SSH
|
||||
// (fail-open) and compare canonical forms, so ~/x, x/ and the absolute
|
||||
// form of one directory all reuse the existing record instead of
|
||||
// registering a duplicate workspace + mirror. The stored spelling
|
||||
// converges to the matched/canonical form below.
|
||||
let existing = prefsNow.workspaces.find((w) => w && w.profileId === a.profileId && lightRemotePath(w.remotePath) === lightRemotePath(a.remotePath));
|
||||
if (existing) {
|
||||
a.remotePath = lightRemotePath(a.remotePath);
|
||||
} else {
|
||||
const resolvedCanonical = await resolveRemoteCanonical(subprocess, p, a.remotePath);
|
||||
a.remotePath = resolvedCanonical.canonical;
|
||||
existing = prefsNow.workspaces.find((w) => w && w.profileId === a.profileId && expandRemoteHome(lightRemotePath(w.remotePath), resolvedCanonical.home) === resolvedCanonical.canonical);
|
||||
}`
|
||||
const FIND_REPLACEMENT = ` // [workspace-groups-remote patch] Canonical-path reuse: resolve the new
|
||||
// spelling once over SSH and resolve every existing record of the same
|
||||
// connection with the same rule (light form + remote $HOME + pwd -P),
|
||||
// so relative/~, trailing-slash and symlink spellings converge on one
|
||||
// directory identity. A resolution failure is NOT "not a duplicate":
|
||||
// creation is refused with an actionable error instead of silently
|
||||
// registering a second workspace.
|
||||
const targetResolved = await resolveRemoteCanonical(subprocess, p, a.remotePath);
|
||||
if (targetResolved.ok !== true) {
|
||||
return { ok: false, error: "无法确认远端路径是否重复:" + targetResolved.error + ";未创建新工作区" };
|
||||
}
|
||||
const sameProfile = prefsNow.workspaces.filter((w) => w && w.profileId === a.profileId && typeof w.remotePath === "string");
|
||||
let existing = undefined;
|
||||
for (const record of sameProfile) {
|
||||
const light = lightRemotePath(record.remotePath);
|
||||
// Fast path: the spelling expands to exactly the resolved target.
|
||||
if (expandRemoteHome(light, targetResolved.home) === targetResolved.canonical) {
|
||||
existing = record;
|
||||
break;
|
||||
}
|
||||
// Slow path: resolve the old record with the SAME rules. This catches
|
||||
// relative paths, symlinks and historical spellings the old partial
|
||||
// expansion missed. A failure aborts instead of assuming uniqueness.
|
||||
const candidate = await resolveRemoteCanonical(subprocess, p, record.remotePath);
|
||||
if (candidate.ok !== true) {
|
||||
return { ok: false, error: "无法确认是否与已有远程工作区「" + String(record.title || record.id) + "」重复:" + candidate.error + ";未创建新工作区" };
|
||||
}
|
||||
if (candidate.canonical === targetResolved.canonical) {
|
||||
existing = record;
|
||||
break;
|
||||
}
|
||||
}
|
||||
a.remotePath = existing ? String(existing.remotePath) : targetResolved.canonical;`
|
||||
|
||||
// Each entry: [label, anchor, replacement]. Anchors are exact byte strings
|
||||
// from the vendored file; every one must occur exactly once.
|
||||
|
|
@ -324,6 +350,13 @@ const TRANSFORMS = [
|
|||
" // name can no longer break out. (~ still expands remotely.)",
|
||||
" const b64 = (s) => Buffer.from(String(s), 'utf8').toString('base64');",
|
||||
" const expanded = remotePath === '~' ? '$HOME' : (remotePath.indexOf('~/') === 0 ? '$HOME/$(printf %s \\\\'' + b64(remotePath.slice(2)) + '\\\\' | base64 -d)' : '$(printf %s \\\\'' + b64(remotePath) + '\\\\' | base64 -d)');",`],
|
||||
['patch 12: reusing a record keeps its existing title',
|
||||
' const lastSeg = String(a.remotePath).replace(/\\/+$/, "").split("/").pop();\n const title = a.title || (lastSeg && lastSeg !== "~" ? lastSeg : (p.name + ":" + a.remotePath));',
|
||||
` // [workspace-groups-remote patch] Reuse keeps the user's existing
|
||||
// title; only a new record (or an explicit a.title) derives one from
|
||||
// the path. Otherwise "reuse" could silently rename a custom workspace.
|
||||
const lastSeg = String(a.remotePath).replace(/\\/+$/, "").split("/").pop();
|
||||
const title = a.title || (existing && existing.title) || (lastSeg && lastSeg !== "~" ? lastSeg : (p.name + ":" + a.remotePath));`],
|
||||
]
|
||||
|
||||
function countOccurrences(text, needle) {
|
||||
|
|
@ -351,11 +384,11 @@ function applyPatch(source) {
|
|||
// Post-conditions: the vulnerable code forms must be gone, the fixed
|
||||
// forms present. (A historical comment mentioning StrictHostKeyChecking=no
|
||||
// remains in the source; only the executable code form is asserted here.)
|
||||
const gone = ['head.concat(opts, [target])', '["sshpass", "-p"', "'StrictHostKeyChecking=no', '-o', 'ExitOnForwardFailure=no'"]
|
||||
const gone = ['head.concat(opts, [target])', '["sshpass", "-p"', "'StrictHostKeyChecking=no', '-o', 'ExitOnForwardFailure=no'", 'lightRemotePath(w.remotePath) === lightRemotePath(a.remotePath)']
|
||||
for (const bad of gone) {
|
||||
if (out.includes(bad)) throw new Error('patch-remote-ssh: vulnerable form still present after patching: ' + bad)
|
||||
}
|
||||
const present = ['resolveRemoteCanonical', 'head.concat(opts, ["--", target])', '"sshpass", "-e"', 'StrictHostKeyChecking=accept-new', 'inMirrorRoot', 'base64 -d', 'foldedParts', '写回护栏无法确认,本次不推送', 'upstream internals changed (runRemote / shellQuotePath not found)', 'findEscapingLink', 'renameSync(tmpFile, file)', "%s %Y %N", 'startsWith(prev + ".")', 'foldCase', 'dirname(dir) === join(homedir()']
|
||||
const present = ['resolveRemoteCanonical', 'targetResolved.ok', '无法确认远端路径是否重复', 'existing && existing.title', 'head.concat(opts, ["--", target])', '"sshpass", "-e"', 'StrictHostKeyChecking=accept-new', 'inMirrorRoot', 'base64 -d', 'foldedParts', '写回护栏无法确认,本次不推送', 'upstream internals changed (runRemote / shellQuotePath not found)', 'findEscapingLink', 'renameSync(tmpFile, file)', "%s %Y %N", 'startsWith(prev + ".")', 'foldCase', 'dirname(dir) === join(homedir()']
|
||||
for (const good of present) {
|
||||
if (!out.includes(good)) throw new Error('patch-remote-ssh: expected patched form missing: ' + good)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -85,6 +85,7 @@ const lightRemotePath = new Function(grabFunction('lightRemotePath') + '\nreturn
|
|||
const expandRemoteHome = new Function(grabFunction('expandRemoteHome') + '\nreturn expandRemoteHome;')()
|
||||
|
||||
const HOME = '/home/u'
|
||||
const SYMLINKS = { '/home/u/link': '/srv/real' }
|
||||
let sshCalls = 0
|
||||
let sshFails = false
|
||||
function fakeRunRemote(subprocess, p, cmd) {
|
||||
|
|
@ -95,7 +96,8 @@ function fakeRunRemote(subprocess, p, cmd) {
|
|||
let target = m ? m[1].trim() : ''
|
||||
if (target.startsWith('~/')) target = target.slice(2).replace(/^'(.*)'$/, '$1')
|
||||
else target = target.replace(/^'(.*)'$/, '$1')
|
||||
const resolved = (target.startsWith('/') ? target : HOME + '/' + target).replace(/\/+$/, '')
|
||||
const absolute = (target.startsWith('/') ? target : HOME + '/' + target).replace(/\/+$/, '')
|
||||
const resolved = SYMLINKS[absolute] || absolute
|
||||
return Promise.resolve({ ok: true, stdout: '__DSH_HOME__' + HOME + '\n' + resolved + '\n' })
|
||||
}
|
||||
const resolveRemoteCanonical = new Function('shellQuotePath', 'runRemote', 'lightRemotePath', 'expandRemoteHome',
|
||||
|
|
@ -113,10 +115,10 @@ check(expandRemoteHome('~/proj', '') === '~/proj', 'expand: no home, untouched')
|
|||
console.log('resolveRemoteCanonical')
|
||||
{
|
||||
const r = await resolveRemoteCanonical({}, {}, '~/proj/')
|
||||
check(r.canonical === '/home/u/proj' && r.home === HOME, 'resolves ~/proj/ to the absolute canonical path')
|
||||
check(r.ok === true && r.canonical === '/home/u/proj' && r.home === HOME, 'resolves ~/proj/ to the absolute canonical path')
|
||||
sshFails = true
|
||||
const f = await resolveRemoteCanonical({}, {}, '~/proj')
|
||||
check(f.canonical === '~/proj' && f.home === '', 'SSH failure is fail-open (light form, no home)')
|
||||
check(f.ok === false && /stubbed failure/.test(f.error), 'SSH failure is fail-closed (no canonical fallback)')
|
||||
sshFails = false
|
||||
}
|
||||
|
||||
|
|
@ -183,19 +185,38 @@ console.log('createRemoteWorkspace (patched)')
|
|||
const r = await handler({ profileId: 'prof-1', remotePath: '/home/u/proj/' })
|
||||
check(r.ok === true && r.reused === true && state.workspaces.length === 1, 'E: trailing-slash variant reuses')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([{ ...seedRecord, remotePath: 'proj' }])
|
||||
const handler = makeHandler(face)
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '~/proj/' })
|
||||
check(r.ok === true && r.reused === true && state.workspaces.length === 1, 'H: relative record spelling resolves to the same directory')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([{ ...seedRecord, remotePath: '/home/u/link' }])
|
||||
const handler = makeHandler(face)
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '/srv/real' })
|
||||
check(r.ok === true && r.reused === true && state.workspaces.length === 1, 'I: symlink and pwd -P form count as one directory')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([{ ...seedRecord, profileId: 'prof-2' }])
|
||||
const handler = makeHandler(face)
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '/home/u/proj' })
|
||||
check(r.ok === true && r.reused === false && state.workspaces.length === 2, 'J: same path on another connection is not merged')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([seedRecord])
|
||||
const handler = makeHandler(face)
|
||||
sshFails = true
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '/home/u/proj' })
|
||||
sshFails = false
|
||||
check(r.ok === true && state.workspaces.length === 2, 'D: with SSH down the create still succeeds (fail-open, upstream behavior)')
|
||||
check(r.ok === false && /无法确认远端路径是否重复/.test(String(r.error)), 'D: SSH down refuses creation instead of silently duplicating')
|
||||
check(state.workspaces.length === 1, 'D: no second record is written when identity cannot be confirmed')
|
||||
}
|
||||
|
||||
|
||||
// --- sshArgv hardening (patch 2) -------------------------------------------
|
||||
const sshArgv = new Function('sshExecutablePath', 'expandSshPath', 'ensureWindowsAskpass',
|
||||
grabFunction('sshArgv') + '\nreturn sshArgv;')(() => 'ssh', (x) => x, () => { throw new Error('win32 only') })
|
||||
grabFunction('sshArgv') + '\nreturn sshArgv;')(() => 'ssh', (x) => x, () => ({ ascii: true, file: 'C:/tmp/askpass.cmd' }))
|
||||
|
||||
console.log('sshArgv (patched)')
|
||||
{
|
||||
|
|
@ -210,9 +231,14 @@ console.log('sshArgv (patched)')
|
|||
}
|
||||
{
|
||||
const { argv, env } = sshArgv({ user: 'u', host: 'h', port: 22, authMethod: 'password', password: 's3cret-value' }, undefined, false)
|
||||
check(argv[0] === 'sshpass' && argv[1] === '-e', 'G: POSIX password auth uses sshpass -e')
|
||||
if (process.platform === 'win32') {
|
||||
check(!argv.includes('sshpass'), 'G: Windows password auth does not use sshpass')
|
||||
check(env !== undefined && env.SSH_ASKPASS === 'C:/tmp/askpass.cmd' && env.RSSH_ASKPASS_PW === 's3cret-value', 'G: Windows password travels via SSH_ASKPASS env')
|
||||
} else {
|
||||
check(argv[0] === 'sshpass' && argv[1] === '-e', 'G: POSIX password auth uses sshpass -e')
|
||||
check(env !== undefined && env.SSHPASS === 's3cret-value', 'G: password travels via the SSHPASS env var')
|
||||
}
|
||||
check(!argv.some(a => String(a).includes('s3cret-value')), 'G: password is not in argv')
|
||||
check(env !== undefined && env.SSHPASS === 's3cret-value', 'G: password travels via the SSHPASS env var')
|
||||
}
|
||||
|
||||
// --- terminal wrapper (patch 3) ----------------------------------------------
|
||||
|
|
@ -226,6 +252,9 @@ function extractWrapperSource() {
|
|||
return new Function('return (' + arrayText + ')')().join('\n')
|
||||
}
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
console.log('terminal wrapper (patched): skipped on win32 (POSIX /bin/sh fixtures)')
|
||||
} else {
|
||||
console.log('terminal wrapper (patched)')
|
||||
{
|
||||
const sandbox = mkdtempSync(join(tmpdir(), 'wg-remote-wrapper-'))
|
||||
|
|
@ -278,6 +307,7 @@ console.log('terminal wrapper (patched)')
|
|||
const out = spawnSync('bash', ['-c', remoteCmd2], { env: { ...baseEnv, SHELL: join(binDir, 'fakeshell') }, encoding: 'utf8' })
|
||||
check(out.stdout.trim().endsWith(weird), 'W4: weird-but-legit path lands in the right directory')
|
||||
}
|
||||
}
|
||||
|
||||
console.log('localToRemote dot-segment folding')
|
||||
{
|
||||
|
|
@ -329,10 +359,19 @@ console.log('freshness: nanosecond stamps + legacy tolerance + escaping links')
|
|||
try {
|
||||
mkdirSync(join(tree, 'sub'), { recursive: true })
|
||||
writeFileSync(join(tree, 'sub', 'f.txt'), 'x')
|
||||
symlinkSync(join(tree, 'sub', 'f.txt'), join(tree, 'inner-link'))
|
||||
check(findEscapingLink(tree) === null, 'F6: an in-tree symlink is fine')
|
||||
symlinkSync('/etc', join(tree, 'sub', 'escape-link'))
|
||||
check(String(findEscapingLink(tree)).endsWith('escape-link'), 'F7: a symlink escaping the tree is found')
|
||||
let linksAvailable = true
|
||||
try {
|
||||
symlinkSync(join(tree, 'sub', 'f.txt'), join(tree, 'inner-link'))
|
||||
} catch (error) {
|
||||
if (error?.code !== 'EPERM') throw error
|
||||
linksAvailable = false
|
||||
console.log(' skip F6/F7: symlink creation not permitted in this environment')
|
||||
}
|
||||
if (linksAvailable) {
|
||||
check(findEscapingLink(tree) === null, 'F6: an in-tree symlink is fine')
|
||||
symlinkSync('/etc', join(tree, 'sub', 'escape-link'))
|
||||
check(String(findEscapingLink(tree)).endsWith('escape-link'), 'F7: a symlink escaping the tree is found')
|
||||
}
|
||||
} finally {
|
||||
rmSync(tree, { recursive: true, force: true })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
// 4. cordis.patch.yml carries the single insert row plus remote-ssh's two
|
||||
// shell overrides (better-sidebar / terminal-controller).
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import vm from 'node:vm'
|
||||
import { checkVendorManifest } from './vendor-manifest.mjs'
|
||||
|
|
@ -18,7 +18,7 @@ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
|
|||
let failures = 0
|
||||
const check = (label, ok) => { console.log(`${ok ? '✓' : '✗ FAIL'} ${label}`); if (!ok) failures++ }
|
||||
|
||||
const host = await import(join(root, 'lib/index.js'))
|
||||
const host = await import(pathToFileURL(join(root, 'lib/index.js')).href)
|
||||
check('host name is the package name', host.name === pkg.name)
|
||||
check('host exports the remote-ssh Config at top level (owns the settings entry)', !!host.Config)
|
||||
check('host inject is the union', JSON.stringify(host.inject) === JSON.stringify(['webServer', 'subprocess', 'tools', 'workspaceRegistry']))
|
||||
|
|
@ -42,7 +42,7 @@ check('client contains the remote-ssh half', client.includes('remssh'))
|
|||
|
||||
const remoteHost = readFileSync(join(root, 'lib/remote-ssh/index.js'), 'utf8')
|
||||
const vendorHost = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/index.js'), 'utf8')
|
||||
check('remote-ssh host artifact carries the canonical-path patch', remoteHost.includes('resolveRemoteCanonical') && remoteHost.includes('lightRemotePath(w.remotePath) === lightRemotePath(a.remotePath)'))
|
||||
check('remote-ssh host artifact carries the canonical-path patch', remoteHost.includes('resolveRemoteCanonical') && remoteHost.includes('targetResolved.ok') && remoteHost.includes('无法确认远端路径是否重复'))
|
||||
check('vendored upstream host stays pristine', !vendorHost.includes('resolveRemoteCanonical'))
|
||||
check('remote-ssh host artifact carries the ssh hardening patches', remoteHost.includes('head.concat(opts, ["--", target])') && remoteHost.includes('"sshpass", "-e"') && remoteHost.includes('inMirrorRoot'))
|
||||
check('remote-ssh host artifact has no vulnerable code forms', !remoteHost.includes('["sshpass", "-p"') && !remoteHost.includes("'StrictHostKeyChecking=no', '-o', 'ExitOnForwardFailure=no'"))
|
||||
|
|
|
|||
|
|
@ -358,10 +358,18 @@ export function GroupsBrowser({
|
|||
// ---- Per-workspace folders (multi-root) -------------------------------------
|
||||
//
|
||||
// A second host sidecar (`/workspace-groups/folders`) lists each workspace's
|
||||
// extra folders plus the optional root folder. It is read once per mount and
|
||||
// written back whole, like the manual overlay above; a failed write is a
|
||||
// toast rather than a banner because every edit here is a one-off row action.
|
||||
// extra folders plus the optional root folder. Reads carry an explicit
|
||||
// loading/ready/error phase: an HTTP failure must never be rendered as "no
|
||||
// folders", because that makes every member reappear as a duplicate row.
|
||||
const [foldersDoc, setFoldersDoc] = useState<FoldersDocument>(EMPTY_FOLDERS_DOCUMENT)
|
||||
const [foldersPhase, setFoldersPhase] = useState<'loading' | 'ready' | 'error'>('loading')
|
||||
const [foldersError, setFoldersError] = useState<string | null>(null)
|
||||
const [foldersRetryToken, setFoldersRetryToken] = useState(0)
|
||||
const [foldersConflict, setFoldersConflict] = useState<{ current: FoldersDocument; draft: FoldersDocument } | null>(null)
|
||||
const foldersConfirmedRef = useRef<FoldersDocument>(EMPTY_FOLDERS_DOCUMENT)
|
||||
const foldersHasDataRef = useRef(false)
|
||||
const foldersPendingRef = useRef<FoldersDocument | null>(null)
|
||||
const foldersSavingRef = useRef(false)
|
||||
// Folder collapse is component state, not store state: it is a transient view
|
||||
// of the row list, like the quick panel, so it is deliberately NOT persisted
|
||||
// with the category/workspace expansion keys. Folders start expanded, so
|
||||
|
|
@ -378,13 +386,53 @@ export function GroupsBrowser({
|
|||
const [foldersRemoteBase, setFoldersRemoteBase] = useState<string | null>(null)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void loadFolders().then((snapshot) => {
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
let retries = 0
|
||||
const attempt = async (): Promise<void> => {
|
||||
const snapshot = await loadFolders(fetch, controller.signal)
|
||||
if (cancelled) return
|
||||
setFoldersDoc(snapshot.document)
|
||||
setFoldersRemoteBase(snapshot.remoteBase ?? null)
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [])
|
||||
if (snapshot.error === 'aborted') return
|
||||
if (snapshot.ok) {
|
||||
foldersConfirmedRef.current = snapshot.document
|
||||
foldersHasDataRef.current = true
|
||||
setFoldersDoc(snapshot.document)
|
||||
setFoldersRemoteBase(snapshot.remoteBase ?? null)
|
||||
setFoldersPhase('ready')
|
||||
setFoldersError(null)
|
||||
return
|
||||
}
|
||||
const reason = snapshot.error ?? 'unknown error'
|
||||
if (foldersHasDataRef.current) {
|
||||
// Keep the last confirmed rows and mark the refresh as failed; never
|
||||
// replace them with an empty document.
|
||||
setFoldersPhase('ready')
|
||||
setFoldersError(reason)
|
||||
} else {
|
||||
setFoldersPhase('error')
|
||||
setFoldersError(reason)
|
||||
}
|
||||
// Bounded exponential backoff (1s, 2s, 4s, 8s, 15s). The timer is
|
||||
// cancelled on unmount; an online event or the Retry button resets it.
|
||||
if (retries < 5) {
|
||||
const delay = Math.min(15_000, 1_000 * 2 ** retries)
|
||||
retries += 1
|
||||
timer = setTimeout(() => { void attempt() }, delay)
|
||||
}
|
||||
}
|
||||
void attempt()
|
||||
const onOnline = (): void => {
|
||||
retries = 0
|
||||
void attempt()
|
||||
}
|
||||
window.addEventListener('online', onOnline)
|
||||
return () => {
|
||||
cancelled = true
|
||||
controller.abort()
|
||||
if (timer !== null) clearTimeout(timer)
|
||||
window.removeEventListener('online', onOnline)
|
||||
}
|
||||
}, [foldersRetryToken])
|
||||
|
||||
const workspaces = useWorkspaces(state => state.items)
|
||||
const workspacePhase = useWorkspaces(state => state.phase)
|
||||
|
|
@ -775,22 +823,68 @@ export function GroupsBrowser({
|
|||
setFolderError({ id: Date.now(), text })
|
||||
}
|
||||
|
||||
const persistFolders = (next: FoldersDocument): void => {
|
||||
setFoldersDoc(next)
|
||||
saveFolders(next).then((stored) => {
|
||||
setFoldersDoc(stored)
|
||||
}).catch((reason: unknown) => {
|
||||
if (reason instanceof FoldersConflictError) {
|
||||
// Another window wrote first: adopt the host's current document so
|
||||
// the tree shows what is actually stored, and say the edit did not
|
||||
// land instead of leaving a phantom row behind.
|
||||
setFoldersDoc(reason.current)
|
||||
notifyFolder(t('folder.conflict'))
|
||||
return
|
||||
/**
|
||||
* Serialize folder saves. A save always sends the LAST confirmed revision and
|
||||
* the latest pending document; a newer edit made while a request is in flight
|
||||
* is coalesced and sent only after the previous result settles. This keeps an
|
||||
* older response from ever overwriting a newer state.
|
||||
*/
|
||||
const drainFolders = async (): Promise<void> => {
|
||||
if (foldersSavingRef.current) return
|
||||
foldersSavingRef.current = true
|
||||
try {
|
||||
while (foldersPendingRef.current !== null) {
|
||||
const draft = foldersPendingRef.current
|
||||
foldersPendingRef.current = null
|
||||
const payload: FoldersDocument = {
|
||||
...draft,
|
||||
revision: foldersConfirmedRef.current.revision ?? 0,
|
||||
}
|
||||
try {
|
||||
const stored = await saveFolders(payload)
|
||||
foldersConfirmedRef.current = stored
|
||||
setFoldersError(null)
|
||||
if (foldersPendingRef.current === null) setFoldersDoc(stored)
|
||||
} catch (reason) {
|
||||
if (reason instanceof FoldersConflictError) {
|
||||
// Keep the server state visible AND remember the user's unsaved
|
||||
// draft; never silently overwrite the draft or claim success.
|
||||
foldersConfirmedRef.current = reason.current
|
||||
setFoldersDoc(reason.current)
|
||||
setFoldersConflict({ current: reason.current, draft: reason.attempted ?? draft })
|
||||
notifyFolder(t('folder.conflict'))
|
||||
} else {
|
||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||
setFoldersDoc(foldersConfirmedRef.current)
|
||||
notifyFolder(`${t('folder.saveError')}: ${detail}`)
|
||||
}
|
||||
// A failed base makes every queued follow-up stale; stop here and let
|
||||
// the user retry the draft explicitly.
|
||||
foldersPendingRef.current = null
|
||||
break
|
||||
}
|
||||
}
|
||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||
notifyFolder(`${t('folder.saveError')}: ${detail}`)
|
||||
})
|
||||
} finally {
|
||||
foldersSavingRef.current = false
|
||||
if (foldersPendingRef.current !== null) void drainFolders()
|
||||
}
|
||||
}
|
||||
|
||||
const persistFolders = (next: FoldersDocument): void => {
|
||||
if (foldersPhase !== 'ready') {
|
||||
notifyFolder(t('folder.notReady'))
|
||||
return
|
||||
}
|
||||
foldersPendingRef.current = next
|
||||
setFoldersDoc(next)
|
||||
void drainFolders()
|
||||
}
|
||||
|
||||
const retryFolderConflict = (): void => {
|
||||
if (foldersConflict === null) return
|
||||
const draft = foldersConflict.draft
|
||||
setFoldersConflict(null)
|
||||
persistFolders({ ...draft, revision: foldersConflict.current.revision ?? 0 })
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -1802,13 +1896,47 @@ export function GroupsBrowser({
|
|||
)}
|
||||
|
||||
<div className="wgTreeBody">
|
||||
{foldersPhase === 'loading' && (
|
||||
<div className="wgSearchStatus" role="status">{t('folder.loadingState')}</div>
|
||||
)}
|
||||
{foldersPhase === 'error' && (
|
||||
<div className="wgSearchStatus wgManualError" role="alert">
|
||||
{t('folder.loadError')}:{foldersError}
|
||||
{' '}
|
||||
<button type="button" className="wgSmallAction" onClick={() => { setFoldersRetryToken(value => value + 1) }}>
|
||||
{t('folder.retry')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{foldersPhase === 'ready' && foldersError !== null && (
|
||||
<div className="wgSearchStatus" role="status">
|
||||
{t('folder.refreshError')}:{foldersError}
|
||||
{' '}
|
||||
<button type="button" className="wgSmallAction" onClick={() => { setFoldersRetryToken(value => value + 1) }}>
|
||||
{t('folder.retry')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{foldersConflict !== null && (
|
||||
<div className="wgSearchStatus wgManualError" role="alert">
|
||||
<div>{t('folder.conflictDetail')}</div>
|
||||
<div style={{ marginTop: '4px', fontSize: '10.5px' }}>
|
||||
server revision {foldersConflict.current.revision ?? 0} · draft revision {foldersConflict.draft.revision ?? 0}
|
||||
</div>
|
||||
<div style={{ marginTop: '4px' }}>
|
||||
<button type="button" className="wgSmallAction" onClick={retryFolderConflict}>{t('folder.retryDraft')}</button>
|
||||
{' '}
|
||||
<button type="button" className="wgSmallAction" onClick={() => { setFoldersConflict(null) }}>{t('folder.discardDraft')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{configError !== null && (
|
||||
<div className="wgSearchStatus" role="status">{t('configUnavailable')}</div>
|
||||
)}
|
||||
{manualError !== null && (
|
||||
<div className="wgSearchStatus wgManualError" role="alert">{t('manual.saveError')}: {manualError}</div>
|
||||
)}
|
||||
{wide && normalizedQuery !== '' && searchTreeForBody !== undefined && searchMatches !== undefined ? (
|
||||
{foldersPhase !== 'ready' ? null : wide && normalizedQuery !== '' && searchTreeForBody !== undefined && searchMatches !== undefined ? (
|
||||
<SearchBody
|
||||
tree={searchTreeForBody}
|
||||
matches={searchMatches}
|
||||
|
|
|
|||
|
|
@ -33,6 +33,17 @@ export interface FoldersSnapshot {
|
|||
readonly remoteBase?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* One folder-overlay read result. A failed read must never masquerade as the
|
||||
* empty document: the browser uses `ok` to keep the last confirmed rows and
|
||||
* show a retryable error instead of rendering every member as a duplicate.
|
||||
*/
|
||||
export interface FoldersLoadResult extends FoldersSnapshot {
|
||||
readonly ok: boolean
|
||||
/** Human-readable failure reason; absent on success. */
|
||||
readonly error?: string
|
||||
}
|
||||
|
||||
/** One non-empty string field, or undefined when it is absent or blank. */
|
||||
function wireText(value: unknown): string | undefined {
|
||||
if (typeof value !== 'string') return undefined
|
||||
|
|
@ -107,29 +118,51 @@ function parseWireEntry(value: unknown): WorkspaceFolderEntry | null {
|
|||
|
||||
/**
|
||||
* Fetch the stored folder overlay.
|
||||
*
|
||||
* A non-2xx response, a malformed body or a transport error is returned as
|
||||
* `ok:false` with the reason. The empty document is still present for callers
|
||||
* that only need a safe value, but `ok` is the authority: the browser must not
|
||||
* treat a failed read as "no folders".
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @returns the overlay plus the reported mirror base; the empty document on any
|
||||
* failure.
|
||||
* @param signal - optional cancellation for a superseded read/retry.
|
||||
*/
|
||||
export async function loadFolders(fetchImpl: typeof fetch = fetch): Promise<FoldersSnapshot> {
|
||||
export async function loadFolders(
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
signal?: AbortSignal,
|
||||
): Promise<FoldersLoadResult> {
|
||||
try {
|
||||
const response = await fetchImpl(FOLDERS_ROUTE, {
|
||||
method: 'GET',
|
||||
// Folders are user state; a cached response would show stale rows.
|
||||
cache: 'no-store',
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
})
|
||||
if (!response.ok) return { document: EMPTY_FOLDERS_DOCUMENT }
|
||||
if (!response.ok) {
|
||||
return { ok: false, document: EMPTY_FOLDERS_DOCUMENT, error: `HTTP ${response.status}` }
|
||||
}
|
||||
const body: unknown = await response.json()
|
||||
if (typeof body !== 'object' || body === null) return { document: EMPTY_FOLDERS_DOCUMENT }
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return { ok: false, document: EMPTY_FOLDERS_DOCUMENT, error: '响应不是 JSON 对象' }
|
||||
}
|
||||
const source = body as Record<string, unknown>
|
||||
const remoteBase = typeof source.remoteBase === 'string' && source.remoteBase.trim() !== ''
|
||||
? source.remoteBase.trim()
|
||||
: undefined
|
||||
const base = remoteBase === undefined ? {} : { remoteBase }
|
||||
const document = parseWireDocument(source)
|
||||
return { document: document ?? EMPTY_FOLDERS_DOCUMENT, ...base }
|
||||
} catch {
|
||||
return { document: EMPTY_FOLDERS_DOCUMENT }
|
||||
if (document === null) {
|
||||
return { ok: false, document: EMPTY_FOLDERS_DOCUMENT, ...base, error: '文件夹文档格式无效' }
|
||||
}
|
||||
return { ok: true, document, ...base }
|
||||
} catch (error) {
|
||||
if (signal?.aborted === true) {
|
||||
return { ok: false, document: EMPTY_FOLDERS_DOCUMENT, error: 'aborted' }
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
document: EMPTY_FOLDERS_DOCUMENT,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -162,10 +195,13 @@ export function parseWireDocument(source: Record<string, unknown>): FoldersDocum
|
|||
*/
|
||||
export class FoldersConflictError extends Error {
|
||||
readonly current: FoldersDocument
|
||||
constructor(current: FoldersDocument) {
|
||||
/** The unsaved document the failed PUT attempted to write. */
|
||||
readonly attempted: FoldersDocument
|
||||
constructor(current: FoldersDocument, attempted: FoldersDocument = current) {
|
||||
super('folder overlay changed in another window')
|
||||
this.name = 'FoldersConflictError'
|
||||
this.current = current
|
||||
this.attempted = attempted
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -196,7 +232,7 @@ export async function saveFolders(
|
|||
const current = typeof body === 'object' && body !== null
|
||||
? parseWireDocument(body as Record<string, unknown>)
|
||||
: null
|
||||
throw new FoldersConflictError(current ?? EMPTY_FOLDERS_DOCUMENT)
|
||||
throw new FoldersConflictError(current ?? EMPTY_FOLDERS_DOCUMENT, document)
|
||||
}
|
||||
if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`)
|
||||
// Adopt the host's echo: it is the normalized document (with the bumped
|
||||
|
|
|
|||
|
|
@ -96,6 +96,13 @@ export type WorkspaceGroupsKey =
|
|||
| 'folder.home'
|
||||
| 'folder.refresh'
|
||||
| 'folder.loading'
|
||||
| 'folder.loadingState'
|
||||
| 'folder.loadError'
|
||||
| 'folder.refreshError'
|
||||
| 'folder.retry'
|
||||
| 'folder.retryDraft'
|
||||
| 'folder.discardDraft'
|
||||
| 'folder.conflictDetail'
|
||||
| 'folder.emptyDir'
|
||||
| 'group.create'
|
||||
| 'group.createTitle'
|
||||
|
|
@ -281,6 +288,13 @@ export const zh: WorkspaceGroupsDict = {
|
|||
'folder.home': '主目录',
|
||||
'folder.refresh': '刷新',
|
||||
'folder.loading': '正在读取远端目录…',
|
||||
'folder.loadingState': '正在读取文件夹配置…',
|
||||
'folder.loadError': '文件夹配置读取失败(未显示为空分组)',
|
||||
'folder.refreshError': '文件夹配置刷新失败,继续显示上次确认的配置',
|
||||
'folder.retry': '重试',
|
||||
'folder.retryDraft': '重新应用我的修改',
|
||||
'folder.discardDraft': '保留服务端版本',
|
||||
'folder.conflictDetail': '文件夹已被另一个窗口修改:下面是服务端当前版本;你未保存的修改仍保留在此处,可重新应用。',
|
||||
'folder.emptyDir': '这个目录下没有子目录',
|
||||
'group.create': '新建分组',
|
||||
'group.createTitle': '新建分组',
|
||||
|
|
@ -465,6 +479,13 @@ export const en: WorkspaceGroupsDict = {
|
|||
'folder.home': 'Home',
|
||||
'folder.refresh': 'Refresh',
|
||||
'folder.loading': 'Reading the remote directory…',
|
||||
'folder.loadingState': 'Reading folder configuration…',
|
||||
'folder.loadError': 'Could not read folder configuration (not shown as an empty grouping)',
|
||||
'folder.refreshError': 'Could not refresh folder configuration; showing the last confirmed state',
|
||||
'folder.retry': 'Retry',
|
||||
'folder.retryDraft': 'Reapply my changes',
|
||||
'folder.discardDraft': 'Keep server version',
|
||||
'folder.conflictDetail': 'Folders changed in another window. The server version is shown below; your unsaved changes are kept here and can be reapplied.',
|
||||
'folder.emptyDir': 'No subdirectories here',
|
||||
'group.create': 'New group',
|
||||
'group.createTitle': 'New group',
|
||||
|
|
|
|||
|
|
@ -1714,54 +1714,60 @@ export default (require) => {
|
|||
}
|
||||
} catch (e) {}
|
||||
|
||||
// ---- 文件树根标签:显示远程目录名,而不是本地镜像目录 ID(issue #9)----
|
||||
// better-sidebar「文件」页签的树根标签取自会话 cwd(= 本地镜像路径)的 basename,
|
||||
// 于是显示成镜像目录 ID(如 wmirror3)。这条链路不经过任何 fs.* 路由,
|
||||
// 而 Host 侧 session.cwd 虽然已返回 root 字段,客户端只消费 cwd
|
||||
// (client-registry 的 api.sessionCwd(...).then(r => setFetchedCwd(r.cwd)),
|
||||
// 另有 useSessionCwd 直接读客户端会话列表的 cwd),因此只能在渲染层替换文本。
|
||||
// 定位不依赖构建期哈希类名:根行是树里唯一带内联 padding-left:6px 的行,
|
||||
// 仅当该行内的纯文本节点 === 某远程工作区的镜像 basename 时才替换(幂等、可自愈)。
|
||||
// ---- 文件树根标签:按完整镜像路径精确认行(issue #9)----
|
||||
// better-sidebar 的根行 title 是完整目录路径(RootRow title={path})。
|
||||
// 只在该 title 精确等于某个远程工作区的 mirrorPath 时才改写名称:不再
|
||||
// 按 basename 或内联 padding-left 猜测目录身份,因此同名本地目录不会
|
||||
// 被误改;属性缺席时保持原样(安全降级)。
|
||||
var watchedRootLabels = []; // 已替换的标签元素:1s 幂等复检,抵消 React 重渲染
|
||||
var rootLabels = {};
|
||||
function normRemotePath(value) {
|
||||
return String(value == null ? "" : value).replace(/[\\/]+$/, "");
|
||||
}
|
||||
function refreshRootLabels(workspaces) {
|
||||
var next = {};
|
||||
for (var i = 0; i < (workspaces || []).length; i++) {
|
||||
var w = workspaces[i] || {};
|
||||
var mirror = String(w.mirrorPath || "").replace(/[\\/]+$/, "");
|
||||
var remote = String(w.remotePath || "").replace(/[\\/]+$/, "");
|
||||
var mirror = normRemotePath(w.mirrorPath);
|
||||
var remote = normRemotePath(w.remotePath);
|
||||
if (!mirror || !remote) continue;
|
||||
var mb = mirror.split(/[\\/]/).pop();
|
||||
var rb = remote.split(/[\\/]/).pop();
|
||||
if (mb && rb && mb !== rb) next[mb] = { label: rb, remotePath: remote };
|
||||
var title = normTitle(w.title);
|
||||
var label = title || remote.split(/[\\/]/).pop();
|
||||
if (label) next[mirror] = { label: label, remotePath: remote, mirrorPath: mirror };
|
||||
}
|
||||
rootLabels = next;
|
||||
}
|
||||
/** 根行判据:自身或 ≤3 层祖先带内联 padding-left:6px(better-sidebar 根行样式)。 */
|
||||
function isRootRow(el) {
|
||||
var node = el;
|
||||
for (var hop = 0; hop < 3 && node; hop++) {
|
||||
var style = node.getAttribute ? node.getAttribute("style") : null;
|
||||
if (style && /padding-left:\s*6px/i.test(String(style))) return true;
|
||||
node = node.parentElement;
|
||||
}
|
||||
return false;
|
||||
/** The root row's own full path, from the explicit attributes only. */
|
||||
function rootPathOf(el) {
|
||||
var explicit = el && el.getAttribute ? el.getAttribute("data-rssh-root-mirror") : null;
|
||||
if (explicit) return normRemotePath(explicit);
|
||||
var title = el && el.getAttribute ? el.getAttribute("title") : null;
|
||||
return title ? normRemotePath(title) : "";
|
||||
}
|
||||
/** 单个标签替换:纯文本 + 命中镜像 basename + 位于根行 → 换成远程目录名。 */
|
||||
/** Direct leaf <span> that prints the folder name (no nested markup). */
|
||||
function rootLabelSpanOf(el) {
|
||||
var children = el && el.children ? el.children : [];
|
||||
for (var i = 0; i < children.length; i++) {
|
||||
if (String(children[i].tagName || "").toLowerCase() === "span" && children[i].childElementCount === 0) return children[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/** Exact full-path hit → replace only the leaf name span. */
|
||||
function fixRootLabel(el) {
|
||||
var text = (el.textContent || "").trim();
|
||||
if (!text) return false;
|
||||
var hit = rootLabels[text];
|
||||
if (hit === undefined) {
|
||||
// 文本已是远程目录名(上一轮替换过)→ 幂等成功;否则与本插件无关
|
||||
return el.getAttribute && el.getAttribute("data-rssh-root-label") === "1";
|
||||
}
|
||||
if (el.childElementCount > 0) return false; // 只改纯文本节点
|
||||
if (!isRootRow(el)) return false; // 非根行(例如同名子条目)不动
|
||||
el.textContent = hit.label;
|
||||
if (el.setAttribute) {
|
||||
el.setAttribute("data-rssh-root-label", "1");
|
||||
el.setAttribute("title", hit.remotePath); // 悬停可见完整远程路径
|
||||
}
|
||||
if (!el || !el.getAttribute) return false;
|
||||
var path = rootPathOf(el);
|
||||
if (!path) return false;
|
||||
var hit = rootLabels[path];
|
||||
if (hit === undefined) return false;
|
||||
var span = rootLabelSpanOf(el);
|
||||
if (!span) return false;
|
||||
var base = path.split(/[\\/]/).pop();
|
||||
var text = normTitle(span.textContent);
|
||||
if (text !== base && el.getAttribute("data-rssh-root-label") !== "1") return false;
|
||||
span.textContent = hit.label;
|
||||
el.setAttribute("data-rssh-root-label", "1");
|
||||
el.setAttribute("data-rssh-root-mirror", hit.mirrorPath);
|
||||
el.setAttribute("title", hit.remotePath); // 悬停可见完整远程路径
|
||||
watchRootLabel(el);
|
||||
return true;
|
||||
}
|
||||
|
|
@ -1779,7 +1785,9 @@ export default (require) => {
|
|||
function applyRootLabelsIn(root) {
|
||||
if (!root || !root.querySelectorAll) return;
|
||||
try {
|
||||
var nodes = root.querySelectorAll("span,div");
|
||||
// Only elements carrying the full path title are candidates; no
|
||||
// text/basename or inline-style scan.
|
||||
var nodes = root.querySelectorAll("[title]");
|
||||
for (var i = 0; i < nodes.length; i++) fixRootLabel(nodes[i]);
|
||||
if (root.nodeType === 1) fixRootLabel(root);
|
||||
} catch (e) {}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,8 @@
|
|||
flex-direction:column;
|
||||
flex:1;
|
||||
width:100%;
|
||||
height:100%;
|
||||
max-height:100%;
|
||||
min-width:0;
|
||||
min-height:0;
|
||||
display:flex;
|
||||
|
|
@ -705,6 +707,22 @@
|
|||
word-break:break-word;
|
||||
}
|
||||
|
||||
.wgSmallAction {
|
||||
border:1px solid var(--dsw-border-1,#7f7f7f55);
|
||||
border-radius:4px;
|
||||
background:transparent;
|
||||
color:inherit;
|
||||
font:inherit;
|
||||
font-size:10.5px;
|
||||
line-height:1;
|
||||
padding:3px 6px;
|
||||
cursor:pointer;
|
||||
}
|
||||
|
||||
.wgSmallAction:hover {
|
||||
border-color:var(--dsw-accent,#4c8dff);
|
||||
}
|
||||
|
||||
.wgRail {
|
||||
flex-direction:column;
|
||||
align-items:center;
|
||||
|
|
|
|||
|
|
@ -364,12 +364,18 @@ function memberFolderLabels(entry: WorkspaceFolderEntry | undefined): Map<string
|
|||
function applyFolders(
|
||||
workspaceId: WorkspaceId,
|
||||
workspacePath: string,
|
||||
workspaceTitle: string,
|
||||
sessions: readonly SessionNode[],
|
||||
list: SessionListState,
|
||||
entry: WorkspaceFolderEntry | undefined,
|
||||
collapsedFolders: ReadonlySet<string> | undefined,
|
||||
): { sessions: readonly SessionNode[]; folders?: readonly FolderNode[] } {
|
||||
const labels = memberFolderLabels(entry)
|
||||
// The base row shows the project's confirmed display title (custom name or
|
||||
// remote directory name) instead of the local mirror basename. The path
|
||||
// remains the directory identity for file access; only the LABEL changes.
|
||||
const title = workspaceTitle.trim()
|
||||
if (title !== '') labels.set(workspacePath, title)
|
||||
const extras = effectiveFolders(workspacePath, entry).slice(1)
|
||||
if (extras.length === 0) return { sessions }
|
||||
const root = rootOf(workspacePath, entry)
|
||||
|
|
@ -492,6 +498,7 @@ export function deriveGroups(
|
|||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
workspace.title,
|
||||
sessions,
|
||||
list,
|
||||
entryFor(folders, workspace.workspaceId as string),
|
||||
|
|
@ -568,6 +575,7 @@ export function deriveTopLevel(
|
|||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
workspace.title,
|
||||
sessions,
|
||||
list,
|
||||
entryFor(folders, workspaceId),
|
||||
|
|
@ -627,6 +635,7 @@ export function deriveDefaultWorkspace(
|
|||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
workspace.title,
|
||||
sessions,
|
||||
list,
|
||||
entryFor(folders, workspace.workspaceId as string),
|
||||
|
|
@ -819,6 +828,7 @@ export function deriveSearchGroups(
|
|||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
workspace.title,
|
||||
nodes,
|
||||
list,
|
||||
entryFor(folders, workspace.workspaceId as string),
|
||||
|
|
|
|||
|
|
@ -22,10 +22,21 @@ function stubFetch(status: number, body: unknown, capture?: (url: string, init?:
|
|||
describe('loadFolders revision', () => {
|
||||
it('carries the stored revision, defaulting an absent one to 0', async () => {
|
||||
const withRevision = await loadFolders(stubFetch(200, { version: 1, revision: 7, workspaces: {} }))
|
||||
expect(withRevision.ok).toBe(true)
|
||||
expect(withRevision.document.revision).toBe(7)
|
||||
const without = await loadFolders(stubFetch(200, { version: 1, workspaces: {} }))
|
||||
expect(without.ok).toBe(true)
|
||||
expect(without.document.revision).toBe(0)
|
||||
})
|
||||
|
||||
it('does not turn HTTP 503 or malformed JSON into a successful empty document', async () => {
|
||||
const unavailable = await loadFolders(stubFetch(503, {}))
|
||||
expect(unavailable.ok).toBe(false)
|
||||
expect(unavailable.error).toContain('503')
|
||||
const malformed = await loadFolders(stubFetch(200, { version: 2, workspaces: {} }))
|
||||
expect(malformed.ok).toBe(false)
|
||||
expect(malformed.error).toContain('格式无效')
|
||||
})
|
||||
})
|
||||
|
||||
describe('saveFolders', () => {
|
||||
|
|
@ -36,9 +47,11 @@ describe('saveFolders', () => {
|
|||
})
|
||||
it('rejects with FoldersConflictError carrying the current document on 409', async () => {
|
||||
const current = { version: 1, revision: 5, workspaces: {} }
|
||||
const failure = await saveFolders({ version: 1, revision: 2, workspaces: {} }, stubFetch(409, current)).catch((e: unknown) => e)
|
||||
const attempted = { version: 1, revision: 2, workspaces: { a: { folders: ['/x'] } } }
|
||||
const failure = await saveFolders(attempted, stubFetch(409, current)).catch((e: unknown) => e)
|
||||
expect(failure).toBeInstanceOf(FoldersConflictError)
|
||||
expect((failure as FoldersConflictError).current).toEqual(current)
|
||||
expect((failure as FoldersConflictError).attempted).toEqual(attempted)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -429,7 +429,9 @@ describe('folders revision guard (route)', () => {
|
|||
} as unknown as ServerResponse)
|
||||
return { status, text }
|
||||
}
|
||||
const first = { version: 1, revision: 0, workspaces: { a: { folders: ['/x'] } } }
|
||||
const rootA = process.platform === 'win32' ? 'C:\\x' : '/x'
|
||||
const rootB = process.platform === 'win32' ? 'C:\\y' : '/y'
|
||||
const first = { version: 1, revision: 0, workspaces: { a: { folders: [rootA] } } }
|
||||
const accepted = await request('PUT', JSON.stringify(first))
|
||||
expect(accepted.status).toBe(200)
|
||||
expect(JSON.parse(accepted.text!)).toEqual({ ...first, revision: 1 })
|
||||
|
|
@ -438,7 +440,7 @@ describe('folders revision guard (route)', () => {
|
|||
expect(stale.status).toBe(409)
|
||||
expect(JSON.parse(stale.text!)).toEqual({ ...first, revision: 1 })
|
||||
// Building on the current revision works and bumps again.
|
||||
const second = { version: 1, revision: 1, workspaces: { a: { folders: ['/x', '/y'] } } }
|
||||
const second = { version: 1, revision: 1, workspaces: { a: { folders: [rootA, rootB] } } }
|
||||
const accepted2 = await request('PUT', JSON.stringify(second))
|
||||
expect(accepted2.status).toBe(200)
|
||||
expect(JSON.parse(accepted2.text!).revision).toBe(2)
|
||||
|
|
@ -468,26 +470,31 @@ describe('folders revision (validation + tolerant read)', () => {
|
|||
|
||||
describe('write-boundary hardening (dot segments, __proto__, UNC hints)', () => {
|
||||
it('validateFoldersDocument rejects dot segments in folder and member paths', () => {
|
||||
const badFolder = process.platform === 'win32' ? 'C:\\x\\..\\y' : '/x/../y'
|
||||
const badMember = process.platform === 'win32' ? 'C:\\x\\.\\y' : '/x/./y'
|
||||
expect(() => hostFolders.validateFoldersDocument({
|
||||
version: 1, workspaces: { a: { folders: ['/x/../y'] } },
|
||||
version: 1, workspaces: { a: { folders: [badFolder] } },
|
||||
})).toThrow(/"\.\." segments/)
|
||||
expect(() => hostFolders.validateFoldersDocument({
|
||||
version: 1, workspaces: { a: { folders: [], members: [{ path: '/x/./y', workspaceId: 'b', kind: 'local' }] } },
|
||||
version: 1, workspaces: { a: { folders: [], members: [{ path: badMember, workspaceId: 'b', kind: 'local' }] } },
|
||||
})).toThrow(/"\.\." segments/)
|
||||
})
|
||||
it('validateFoldersDocument rejects a __proto__ workspace id; the tolerant read skips it', () => {
|
||||
expect(() => hostFolders.validateFoldersDocument({
|
||||
version: 1, workspaces: { ['__proto__']: { folders: ['/x'] } },
|
||||
})).toThrow(/workspace ids/)
|
||||
const parsed = hostFolders.parseFoldersDocument({
|
||||
version: 1, workspaces: { ['__proto__']: { folders: ['/x'] }, ok: { folders: ['/y'] } },
|
||||
})
|
||||
const doc: Record<string, unknown> = Object.create(null)
|
||||
doc.version = 1
|
||||
const workspaces: Record<string, unknown> = Object.create(null)
|
||||
workspaces['__proto__'] = { folders: [process.platform === 'win32' ? 'C:\\x' : '/x'] }
|
||||
workspaces.ok = { folders: [process.platform === 'win32' ? 'C:\\y' : '/y'] }
|
||||
doc.workspaces = workspaces
|
||||
expect(() => hostFolders.validateFoldersDocument(doc)).toThrow(/workspace ids/)
|
||||
const parsed = hostFolders.parseFoldersDocument(doc)
|
||||
expect(Object.keys(parsed.workspaces)).toEqual(['ok'])
|
||||
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
|
||||
})
|
||||
it('validateRemoteHintPath rejects UNC paths', () => {
|
||||
expect(() => hostFolders.validateRemoteHintPath('\\\\server\\share\\dir')).toThrow(/UNC/)
|
||||
expect(hostFolders.validateRemoteHintPath('/home/u/proj')).toBe('/home/u/proj')
|
||||
expect(() => hostFolders.validateRemoteHintPath(String.raw`\\server\share\dir`)).toThrow(/UNC/)
|
||||
expect(hostFolders.validateRemoteHintPath(process.platform === 'win32' ? 'C:\\home\\u\\proj' : '/home/u/proj'))
|
||||
.toBe(process.platform === 'win32' ? 'C:\\home\\u\\proj' : '/home/u/proj')
|
||||
})
|
||||
it('addMember keeps a root that names the member path', () => {
|
||||
const entry = addMember(
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-sess
|
|||
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import { deriveGroups, deriveSearchGroups, deriveTopLevel } from '../src/client/tree.ts'
|
||||
import type { GroupsConfig, ManualGroups } from '../src/core/types.ts'
|
||||
import type { FoldersDocument } from '../src/core/folders.ts'
|
||||
|
||||
const CONFIG: GroupsConfig = {
|
||||
categories: [
|
||||
|
|
@ -179,6 +180,39 @@ describe('category appearance on the tree nodes', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('folder rows use confirmed display names', () => {
|
||||
it('base row shows the project title, not the local mirror basename', () => {
|
||||
const ws = workspace('ws-remote', 'C:/mirror/w123', '远程项目', ['s1'])
|
||||
const folders: FoldersDocument = {
|
||||
version: 1,
|
||||
revision: 1,
|
||||
workspaces: {
|
||||
'ws-remote': {
|
||||
folders: ['C:/mirror/w123/extra'],
|
||||
members: [{
|
||||
path: 'C:/mirror/w123/extra',
|
||||
workspaceId: 'ws-extra',
|
||||
kind: 'remote',
|
||||
remotePath: '/srv/proj/extra',
|
||||
profileId: 'prof-1',
|
||||
title: 'extra-remote',
|
||||
}],
|
||||
},
|
||||
},
|
||||
}
|
||||
const view = { expandedCategories: [], expandedWorkspaces: ['ws-remote'] }
|
||||
const top = deriveTopLevel(listState([ws], 's1'), [ws], [], CONFIG, view, { categories: [], assignments: {} }, new Map(), folders)
|
||||
const node = top.find(item => item.workspaceId === 'ws-remote')
|
||||
expect(node).toBeDefined()
|
||||
const base = node?.folders?.find(folder => folder.isBase)
|
||||
const member = node?.folders?.find(folder => !folder.isBase)
|
||||
expect(base?.label).toBe('远程项目')
|
||||
expect(member?.label).toBe('extra-remote')
|
||||
// The underlying path identity is untouched.
|
||||
expect(base?.path).toBe('C:/mirror/w123')
|
||||
})
|
||||
})
|
||||
|
||||
describe('deriveTopLevel', () => {
|
||||
const ws = [
|
||||
workspace('ws-a', '/Users/zcol/Project/SomePlugin', 'DSH插件Demo'),
|
||||
|
|
|
|||
|
|
@ -58,6 +58,9 @@ const block = (selector) => {
|
|||
const start = match.index + match[0].length - match[1].length
|
||||
return css.slice(start, css.indexOf('}', start))
|
||||
}
|
||||
assert.match(block('.wgRoot'), /height:100%/, 'the root consumes the sidebar slot height')
|
||||
assert.match(block('.wgRoot'), /max-height:100%/, 'the root cannot grow past its slot')
|
||||
assert.match(block('.wgRoot'), /overflow:hidden/, 'the root clips instead of scrolling the whole sidebar')
|
||||
assert.match(block('.wgDock'), /border-top:1px solid/, 'the dock draws the divider against the tree')
|
||||
assert.match(block('.wgDock'), /max-height:min\(62vh,560px\)/, 'the dock is capped so the tree always keeps room')
|
||||
assert.match(block('.wgDock'), /overflow:hidden/, 'the dock clips its own overflow instead of painting over the tree')
|
||||
|
|
|
|||
Loading…
Reference in New Issue