release: workspace-groups-local 1.0.0
This commit is contained in:
parent
fe3b9b0503
commit
2fb87d1904
|
|
@ -0,0 +1,25 @@
|
||||||
|
# 更新日志
|
||||||
|
|
||||||
|
## 1.0.0 — 2026-10-28
|
||||||
|
|
||||||
|
首个本地稳定版本,包名 `workspace-groups-local`。基于原项目扩展,保留原 MIT 许可证与版权声明。
|
||||||
|
|
||||||
|
### 功能
|
||||||
|
- 工作区分组:颜色、图标、置顶、折叠动画、拖拽归组与排序。
|
||||||
|
- 分组行新增工作区入口,创建后自动归组并展开。
|
||||||
|
- 会话标签:固定、拖拽排序、中键关闭、右键菜单、双击重命名。
|
||||||
|
- 多文件夹与默认根目录配置。
|
||||||
|
- 移除侧栏花朵的连线,保留花朵标记。
|
||||||
|
|
||||||
|
### SSH 兼容与修复
|
||||||
|
- 顶部与分组新增工作区入口复用已注册的自包含目录选择窗口,包括 remote-ssh 的本地/远程窗口。
|
||||||
|
- 未注册选择窗口时,回退 DSH 原生本地目录选择器;不强制依赖 SSH 插件。
|
||||||
|
- 统一创建文件夹入口:本地使用 DSH API,远程使用 SSH 插件接口;远程失败禁止回退本地写入。
|
||||||
|
- 停止复制子目录 SSH 标记,旧标记不自动删除。
|
||||||
|
- 对需要额外渲染器上下文的第三方选择窗口明确报错,不静默丢弃其上下文。
|
||||||
|
|
||||||
|
### 验证与限制
|
||||||
|
- 类型检查、构建及纯逻辑/模拟接口回归测试通过。
|
||||||
|
- 用户已确认本次界面改动可用;未完成卸载 SSH 插件的独立环境测试及所有真实服务器组合测试。
|
||||||
|
- remote-ssh 2.4.40 的远程子目录会话路由不一致:暂时阻止从这些子目录新建会话,可在注册的远程工作区根启动。
|
||||||
|
- 本次仅本地 Git 提交与版本标记;未发布 npm、GitHub Release 或插件市场。公开发布前需设置自己的仓库元数据并完成安装验证。
|
||||||
|
|
@ -179,7 +179,11 @@ $installed = "C:\Users\qyh15\.dsh\profiles\desktop\node_modules\@dsh-xhl\workspa
|
||||||
额外文件夹只能是镜像内子目录(用 `joinSubpath` 拼、`isUnderBase` 判定,**绝不要让
|
额外文件夹只能是镜像内子目录(用 `joinSubpath` 拼、`isUnderBase` 判定,**绝不要让
|
||||||
用户用原生选择器挑任意本地目录**);`cwd` 分区逻辑照常可用,因为会话本身也在本地跑。
|
用户用原生选择器挑任意本地目录**);`cwd` 分区逻辑照常可用,因为会话本身也在本地跑。
|
||||||
真正"服务器上另一个根目录"应当由 SSH 插件单独建成工作区,再用分组归到一起。
|
真正"服务器上另一个根目录"应当由 SSH 插件单独建成工作区,再用分组归到一起。
|
||||||
另外 `POST /workspace-groups/folders` 会在**镜像内新增的子目录**里补一份
|
`POST /workspace-groups/folders` 已停用(410):禁止复制子 marker,避免绕过父写回规则。
|
||||||
`.remote-ssh.json`(`remotePath` 拼到对应远端子目录):SSH 插件的 shell wrapper 与
|
统一创建入口在 `src/client/folder-directory.ts`:listWorkspaces 判归属,本地使用 DSH
|
||||||
部分 fs 桥只在**会话 cwd 本身**找这个标记、不向上遍历,缺了它子目录会话会退化成
|
createDirectory,远端用专属 mkdir API(递归幂等),不走可能降级本地的 sidebar fs.mkdir。
|
||||||
本地终端。该文件被同步流程永久排除,不会落到服务器。
|
缺 SSH 的已知镜像、网络/鉴权失败、坏目录清单和重叠根一律报错。远程子目录会话暂阻断,
|
||||||
|
因 remote-ssh 2.4.40 模型工具仍只匹配注册根 cwd。历史 marker 不自动清理。
|
||||||
|
验证:`node tools/verify-folder-directory.mjs`(模拟 API)和
|
||||||
|
`node --experimental-transform-types tools/verify-folders.mjs`(含 marker POST 拒绝回归)。
|
||||||
|
不要把静态检查/模拟通过当成实机 SSH 联调通过。
|
||||||
|
|
|
||||||
29
README.md
29
README.md
|
|
@ -94,17 +94,24 @@
|
||||||
clicking it twice reuses the blank session instead of stacking empty ones
|
clicking it twice reuses the blank session instead of stacking empty ones
|
||||||
- Folders start expanded, so attaching one never hides sessions that were already visible;
|
- Folders start expanded, so attaching one never hides sessions that were already visible;
|
||||||
collapse state is per-view and intentionally not persisted
|
collapse state is per-view and intentionally not persisted
|
||||||
- **Remote (SSH) projects are mirror-backed**: `@zhangfengshun/dsh-remote-ssh` registers a
|
- **Unified Create folder**: enter one child name in either workspace type. Local workspaces
|
||||||
remote workspace as an ordinary workspace whose directory is a LOCAL mirror
|
call DSH `uiWorkspace.createDirectory`; registered SSH mirrors call the SSH-owned
|
||||||
(`<home>/.dsh/remote-workspaces/<workspaceId>`) of the remote root. For those projects the
|
`/remote-ssh/api/mkdir` with the profile and mapped remote path. SSH is optional for local use.
|
||||||
dialog swaps the folder picker for a **relative-path field**, so an extra folder is always a
|
Remote mkdir is recursive/idempotent (existing remote directories are reused), unlike the
|
||||||
subdirectory of that mirror — i.e. a directory that also exists on the server. Picking an
|
native local operation. Failures do not fall back to creating local mirror directories.
|
||||||
unrelated local directory is refused, because a session there would never sync: a separate
|
- SSH recognition uses `listWorkspaces`, including non-default mirror locations. A missing
|
||||||
remote root should be its own workspace (add it with the SSH plugin), grouped next to this one
|
plugin or unregistered default mirror fails closed; malformed catalogs and overlapping roots
|
||||||
- Such an extra folder gets a **`.remote-ssh.json` stamped into it** (same connection record,
|
are rejected. The existing local folder picker remains available for attaching local folders.
|
||||||
`remotePath` pointing at the matching remote subdirectory). The SSH plugin reads that record at
|
- **SSH subdirectory sessions are not fully supported by remote-ssh 2.4.40**. Creation is
|
||||||
the session cwd only, never walking up, so without it a session in the subdirectory would fall
|
blocked with an explanation; open a session at the registered remote workspace root instead.
|
||||||
back to a LOCAL terminal. The file is always excluded from sync, so it never reaches the server
|
A separate remote root should be registered through the SSH plugin. Folder creation itself
|
||||||
|
does not create or change any SSH registration.
|
||||||
|
- **No child `.remote-ssh.json` is written**. The old marker POST returns 410. Child markers do
|
||||||
|
not establish model-tool context and can bypass parent write-back exclusions. Previously
|
||||||
|
created markers are NOT automatically deleted; review them before using old subdirectory
|
||||||
|
sessions. Root SSH markers remain owned by the SSH plugin.
|
||||||
|
- Verification uses mocked APIs plus host route fixtures; live SSH/terminal/UI behavior still
|
||||||
|
requires an integration test before publishing.
|
||||||
|
|
||||||
### Search & operations
|
### Search & operations
|
||||||
- **Tree-shaped search**: results keep the three-level structure (category → project → matched
|
- **Tree-shaped search**: results keep the three-level structure (category → project → matched
|
||||||
|
|
|
||||||
20
README_ZH.md
20
README_ZH.md
|
|
@ -77,14 +77,18 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
|
||||||
沿用平台自己的“新建会话”手势,连点两次会复用已打开的空白会话,而不是堆一堆空会话
|
沿用平台自己的“新建会话”手势,连点两次会复用已打开的空白会话,而不是堆一堆空会话
|
||||||
- 文件夹默认展开,挂上新文件夹不会把本来能看到的会话藏起来;折叠状态只是当前视图状态,
|
- 文件夹默认展开,挂上新文件夹不会把本来能看到的会话藏起来;折叠状态只是当前视图状态,
|
||||||
故意不持久化
|
故意不持久化
|
||||||
- **远程(SSH)项目是镜像式工作区**:`@zhangfengshun/dsh-remote-ssh` 把远程工作区登记成
|
- **统一“创建文件夹”**:输入一个子目录名,本地调用 DSH 原生 `uiWorkspace.createDirectory`;
|
||||||
普通工作区,目录是远端根在**本地的镜像**(`<home>/.dsh/remote-workspaces/<工作区id>`)。
|
已注册的远程镜像调用 SSH 专属 `/remote-ssh/api/mkdir`,传连接 ID 和映射后的远端路径。
|
||||||
这类项目里弹窗会把“挑文件夹”换成**相对路径输入框**,额外文件夹只能是该镜像内的子目录
|
本地功能不依赖 SSH 插件。远端接口为 `mkdir -p`,同名目录存在时复用;本地沿用原生行为。
|
||||||
——也就是服务器上同样存在的目录;挑一个无关的本地目录会被拒绝,因为那种会话永远不会同步。
|
SSH 不可用或请求失败时绝不降级为镜像里的本地创建。普通本地目录仍可用“添加文件夹”选取。
|
||||||
服务器上另一个不相干的根目录,应该用 SSH 插件单独建成一个工作区,再用分组放到一起
|
- 通过 SSH 的 `listWorkspaces` 识别已注册镜像,支持非默认镜像位置;重叠注册根、坏响应、
|
||||||
- 远程项目的额外文件夹会**自动补一个 `.remote-ssh.json`**(连接信息,`remotePath` 指向
|
未注册的默认镜像路径会报错。此功能不另建 SSH 工作区,也不改动它的连接配置。
|
||||||
对应远端子目录)。原因:SSH 插件只在“当前工作目录”读这个标记、不向上找,缺了它这些
|
- **remote-ssh 2.4.40 不完整支持子目录会话**:新建此类会话暂时阻断并提示从注册的远程工作区根
|
||||||
子目录里的会话会退化成**本地终端**。该文件永远被同步排除,不会推到服务器上
|
打开。创建远端文件夹本身不受此限制;另一个远端根请通过 SSH 插件注册。
|
||||||
|
- **不再复制 `.remote-ssh.json` 到子目录**,旧 POST 接口返回 410。复制标记不能修复模型工具
|
||||||
|
上下文,还可能绕过父工作区写回限制。历史子目录标记不会自动删除,应审查后再使用旧会话;
|
||||||
|
工作区根标记仍由 SSH 插件管理。此前“子标记永远不会同步”的说明不成立,已撤回。
|
||||||
|
- 自动验证使用模拟 API 和临时目录;真实 SSH、终端和界面尚需发布前联调。
|
||||||
|
|
||||||
### 搜索与操作
|
### 搜索与操作
|
||||||
- **树形搜索**:命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮 +
|
- **树形搜索**:命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮 +
|
||||||
|
|
|
||||||
375
lib/client.js
375
lib/client.js
|
|
@ -1,5 +1,5 @@
|
||||||
window.__ModuleLoader__.load({
|
window.__ModuleLoader__.load({
|
||||||
id: "@dsh-xhl/workspace-groups",
|
id: "workspace-groups-local",
|
||||||
factory: (require) => {
|
factory: (require) => {
|
||||||
var module = { exports: {} };
|
var module = { exports: {} };
|
||||||
var exports = module.exports;
|
var exports = module.exports;
|
||||||
|
|
@ -1624,7 +1624,7 @@ window.__ModuleLoader__.load({
|
||||||
* groups via overlay renames/hides), draggable source for group reorder and
|
* groups via overlay renames/hides), draggable source for group reorder and
|
||||||
* drop target for both workspace moves and group reorders.
|
* drop target for both workspace moves and group reorders.
|
||||||
*/
|
*/
|
||||||
function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }) {
|
function CategoryRow({ node, t, onToggle, onAddWorkspace, addingWorkspace = false, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }) {
|
||||||
const [menuOpen, setMenuOpen] = (0, react.useState)(false);
|
const [menuOpen, setMenuOpen] = (0, react.useState)(false);
|
||||||
const count = node.workspaces.length;
|
const count = node.workspaces.length;
|
||||||
const manageable = onRename !== void 0 && onDelete !== void 0;
|
const manageable = onRename !== void 0 && onDelete !== void 0;
|
||||||
|
|
@ -1697,6 +1697,22 @@ window.__ModuleLoader__.load({
|
||||||
"aria-hidden": true,
|
"aria-hidden": true,
|
||||||
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPinFillMedium, {})
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPinFillMedium, {})
|
||||||
}),
|
}),
|
||||||
|
onAddWorkspace !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
||||||
|
className: "wgRowActions",
|
||||||
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
|
||||||
|
type: "button",
|
||||||
|
className: "wgIconButton",
|
||||||
|
draggable: false,
|
||||||
|
disabled: addingWorkspace,
|
||||||
|
title: t("workspace.add"),
|
||||||
|
"aria-label": `${t("workspace.add")} · ${node.label}`,
|
||||||
|
onClick: (event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
onAddWorkspace();
|
||||||
|
},
|
||||||
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPlusOutlineRegular, {})
|
||||||
|
})
|
||||||
|
}),
|
||||||
manageable && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
manageable && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
|
||||||
className: "wgRowActions",
|
className: "wgRowActions",
|
||||||
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu, {
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu, {
|
||||||
|
|
@ -2199,38 +2215,103 @@ window.__ModuleLoader__.load({
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`);
|
if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`);
|
||||||
}
|
}
|
||||||
/**
|
//#endregion
|
||||||
* Ask the host to stamp the remote-ssh connection record into an extra folder of
|
//#region src/client/folder-directory.ts
|
||||||
* a MIRROR workspace.
|
/** One directory operation for local DSH and optional remote-ssh workspaces.
|
||||||
*
|
* Never send remote writes through the sidebar route: without its SSH interceptor
|
||||||
* remote-ssh decides "remote backed" by reading `.remote-ssh.json` at the
|
* that route can create a LOCAL directory instead. Use the SSH-owned API instead.
|
||||||
* session cwd and never walks up, so a folder below the mirror root would
|
|
||||||
* otherwise get a local terminal. Best-effort: the folder itself is already
|
|
||||||
* persisted by the time this runs, and a local workspace answers `marked:false`
|
|
||||||
* (nothing to stamp) rather than failing.
|
|
||||||
* @param workspacePath - the workspace's canonical directory (mirror root).
|
|
||||||
* @param folderPath - the extra folder just added.
|
|
||||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
|
||||||
* @returns true when a record was written.
|
|
||||||
*/
|
*/
|
||||||
async function ensureRemoteFolderMarker(workspacePath, folderPath, fetchImpl = fetch) {
|
function object(value) {
|
||||||
try {
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
||||||
const response = await fetchImpl(FOLDERS_ROUTE, {
|
}
|
||||||
method: "POST",
|
function message(value) {
|
||||||
headers: { "Content-Type": "application/json" },
|
const error = value?.error;
|
||||||
body: JSON.stringify({
|
return typeof error === "string" ? error : typeof object(error)?.message === "string" ? String(object(error)?.message) : typeof value?.stderr === "string" && value.stderr !== "" ? value.stderr : "Remote SSH request failed";
|
||||||
workspacePath,
|
}
|
||||||
folderPath
|
async function rpc(method, body, fetchImpl) {
|
||||||
}),
|
const response = await fetchImpl(`/remote-ssh/api/${method}`, {
|
||||||
cache: "no-store"
|
method: "POST",
|
||||||
});
|
headers: {
|
||||||
if (!response.ok) return false;
|
"Content-Type": "application/json",
|
||||||
const body = await response.json();
|
"X-Requested-With": "XMLHttpRequest"
|
||||||
if (typeof body !== "object" || body === null) return false;
|
},
|
||||||
return body.marked === true;
|
body: JSON.stringify(body),
|
||||||
} catch {
|
cache: "no-store",
|
||||||
return false;
|
signal: AbortSignal.timeout(3e4)
|
||||||
|
});
|
||||||
|
if (response.status === 404 && method === "listWorkspaces") return null;
|
||||||
|
if (!response.ok) throw new Error(`Remote SSH ${method}: HTTP ${response.status}`);
|
||||||
|
const envelope = object(await response.json());
|
||||||
|
const value = object(envelope?.value);
|
||||||
|
if (envelope?.ok !== true || value?.ok !== true) throw new Error(message(value ?? envelope));
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
/** A marker is only a refusal hint, never authority to execute remote commands. */
|
||||||
|
async function refuseMarkedLocalPath(path, fetchImpl) {
|
||||||
|
const response = await fetchImpl(`/workspace-groups/remote-hint?path=${encodeURIComponent(path)}`, {
|
||||||
|
cache: "no-store",
|
||||||
|
signal: AbortSignal.timeout(1e4)
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error(`Cannot verify local directory: HTTP ${response.status}`);
|
||||||
|
const body = object(await response.json());
|
||||||
|
if (typeof body?.remoteHint !== "boolean") throw new Error("Invalid directory safety response");
|
||||||
|
if (body.remoteHint) throw new Error("SSH marker detected but no active registered remote workspace; refusing local operation");
|
||||||
|
}
|
||||||
|
/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */
|
||||||
|
async function remoteFolderWorkspace(path, remoteBase, fetchImpl = fetch) {
|
||||||
|
const value = await rpc("listWorkspaces", {}, fetchImpl);
|
||||||
|
const knownMirror = remoteBase !== null && isUnderBase(path, remoteBase);
|
||||||
|
if (value === null) {
|
||||||
|
if (knownMirror) throw new Error("SSH plugin is unavailable; refusing a local operation in a remote mirror");
|
||||||
|
await refuseMarkedLocalPath(path, fetchImpl);
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
if (!Array.isArray(value.workspaces)) throw new Error("Invalid SSH workspace catalog");
|
||||||
|
const matches = [];
|
||||||
|
for (const raw of value.workspaces) {
|
||||||
|
const row = object(raw);
|
||||||
|
if (!row || typeof row.mirrorPath !== "string" || typeof row.remotePath !== "string" || typeof row.profileId !== "string" || !row.mirrorPath || !row.remotePath || !row.profileId) throw new Error("Invalid SSH workspace entry");
|
||||||
|
if (samePath(path, row.mirrorPath) || isUnderBase(path, row.mirrorPath)) matches.push({
|
||||||
|
mirrorPath: row.mirrorPath,
|
||||||
|
remotePath: row.remotePath,
|
||||||
|
profileId: row.profileId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (matches.length > 1) throw new Error("Overlapping SSH workspaces are not supported safely");
|
||||||
|
if (matches.length === 1) return matches[0];
|
||||||
|
if (knownMirror) throw new Error("Remote mirror is not registered with the SSH plugin");
|
||||||
|
await refuseMarkedLocalPath(path, fetchImpl);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
/** Single-segment names match DSH createDirectory(path, name). */
|
||||||
|
function validateFolderName(raw) {
|
||||||
|
const name = raw.trim();
|
||||||
|
if (!name || name === "." || name === ".." || /[\\/\u0000-\u001f]/u.test(name)) throw new Error("Enter a single folder name, not an absolute path or nested path");
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
async function createWorkspaceDirectory(parent, rawName, remoteBase, createLocal, fetchImpl = fetch) {
|
||||||
|
const name = validateFolderName(rawName);
|
||||||
|
const path = joinSubpath(parent, name);
|
||||||
|
if (path === null) throw new Error("Invalid folder name");
|
||||||
|
const remote = await remoteFolderWorkspace(parent, remoteBase, fetchImpl);
|
||||||
|
if (!remote) return {
|
||||||
|
path: await createLocal(parent, name),
|
||||||
|
remote: false
|
||||||
|
};
|
||||||
|
if (/[\u0000-\u001f`$"\\]/u.test(name)) throw new Error("Unsupported remote folder name");
|
||||||
|
const normalizedParent = parent.trim().replace(/\\/gu, "/").replace(/\/+$/u, "");
|
||||||
|
const normalizedRoot = remote.mirrorPath.trim().replace(/\\/gu, "/").replace(/\/+$/u, "");
|
||||||
|
const suffix = normalizedParent.slice(normalizedRoot.length).replace(/^\/+/, "");
|
||||||
|
if (suffix.split("/").some((part) => part === ".." || part === ".")) throw new Error("Invalid mirror path");
|
||||||
|
const remotePath = `${remote.remotePath.replace(/\/+$/u, "")}/${suffix ? `${suffix}/` : ""}${name}`;
|
||||||
|
await rpc("mkdir", {
|
||||||
|
profileId: remote.profileId,
|
||||||
|
path: remotePath
|
||||||
|
}, fetchImpl);
|
||||||
|
return {
|
||||||
|
path,
|
||||||
|
remote: true
|
||||||
|
};
|
||||||
}
|
}
|
||||||
//#endregion
|
//#endregion
|
||||||
//#region src/client/open-folder.ts
|
//#region src/client/open-folder.ts
|
||||||
|
|
@ -3738,7 +3819,7 @@ window.__ModuleLoader__.load({
|
||||||
* @param props - composed slot props (shell owner share + store + injected actions).
|
* @param props - composed slot props (shell owner share + store + injected actions).
|
||||||
* @returns the region element tree.
|
* @returns the region element tree.
|
||||||
*/
|
*/
|
||||||
function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, createSessionIn, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t }) {
|
function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, createSessionIn, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, getDirectoryFlow, createDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t }) {
|
||||||
(0, react.useEffect)(() => {
|
(0, react.useEffect)(() => {
|
||||||
const style = document.createElement("style");
|
const style = document.createElement("style");
|
||||||
style.setAttribute("data-plugin", "dsh-workspace-groups");
|
style.setAttribute("data-plugin", "dsh-workspace-groups");
|
||||||
|
|
@ -3781,6 +3862,7 @@ window.__ModuleLoader__.load({
|
||||||
const [collapsedFolderKeys, setCollapsedFolderKeys] = (0, react.useState)([]);
|
const [collapsedFolderKeys, setCollapsedFolderKeys] = (0, react.useState)([]);
|
||||||
const [foldersTarget, setFoldersTarget] = (0, react.useState)(null);
|
const [foldersTarget, setFoldersTarget] = (0, react.useState)(null);
|
||||||
const [foldersBusy, setFoldersBusy] = (0, react.useState)(false);
|
const [foldersBusy, setFoldersBusy] = (0, react.useState)(false);
|
||||||
|
const createdFolderPendingSave = (0, react.useRef)(null);
|
||||||
const [creatingSessionIn, setCreatingSessionIn] = (0, react.useState)(null);
|
const [creatingSessionIn, setCreatingSessionIn] = (0, react.useState)(null);
|
||||||
const [foldersRemoteBase, setFoldersRemoteBase] = (0, react.useState)(null);
|
const [foldersRemoteBase, setFoldersRemoteBase] = (0, react.useState)(null);
|
||||||
(0, react.useEffect)(() => {
|
(0, react.useEffect)(() => {
|
||||||
|
|
@ -3953,18 +4035,82 @@ window.__ModuleLoader__.load({
|
||||||
kind: "topLevel",
|
kind: "topLevel",
|
||||||
key: UNCATEGORIZED_KEY
|
key: UNCATEGORIZED_KEY
|
||||||
};
|
};
|
||||||
|
const [directoryFlowOpen, setDirectoryFlowOpen] = (0, react.useState)(false);
|
||||||
|
const [directoryFlow, setDirectoryFlow] = (0, react.useState)(null);
|
||||||
|
const DirectoryFlow = directoryFlow?.component;
|
||||||
|
const directoryRequest = (0, react.useRef)(null);
|
||||||
|
const finishDirectoryFlow = (path, error) => {
|
||||||
|
const pending = directoryRequest.current;
|
||||||
|
directoryRequest.current = null;
|
||||||
|
setDirectoryFlowOpen(false);
|
||||||
|
if (error !== void 0) pending?.reject(new Error(error));
|
||||||
|
else pending?.resolve(path);
|
||||||
|
};
|
||||||
|
(0, react.useEffect)(() => () => {
|
||||||
|
directoryRequest.current?.resolve(null);
|
||||||
|
directoryRequest.current = null;
|
||||||
|
}, []);
|
||||||
|
const pickWorkspaceDirectory = () => {
|
||||||
|
const flow = getDirectoryFlow();
|
||||||
|
if (!flow) return pickDirectory();
|
||||||
|
if (directoryRequest.current) return Promise.resolve(null);
|
||||||
|
setDirectoryFlow(flow);
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
directoryRequest.current = {
|
||||||
|
resolve,
|
||||||
|
reject
|
||||||
|
};
|
||||||
|
setDirectoryFlowOpen(true);
|
||||||
|
});
|
||||||
|
};
|
||||||
const [adding, setAdding] = (0, react.useState)(false);
|
const [adding, setAdding] = (0, react.useState)(false);
|
||||||
const [addError, setAddError] = (0, react.useState)(null);
|
const [addError, setAddError] = (0, react.useState)(null);
|
||||||
const [addErrorOpen, setAddErrorOpen] = (0, react.useState)(false);
|
const [addErrorOpen, setAddErrorOpen] = (0, react.useState)(false);
|
||||||
const addWorkspace = async () => {
|
const addCategoryRef = (0, react.useRef)(void 0);
|
||||||
if (adding) return;
|
const currentGrouping = (0, react.useRef)({
|
||||||
|
manual,
|
||||||
|
groups,
|
||||||
|
manualSaving
|
||||||
|
});
|
||||||
|
currentGrouping.current = {
|
||||||
|
manual,
|
||||||
|
groups,
|
||||||
|
manualSaving
|
||||||
|
};
|
||||||
|
const addWorkspace = async (categoryKey) => {
|
||||||
|
if (adding || manualSaving) return;
|
||||||
|
addCategoryRef.current = categoryKey;
|
||||||
setAdding(true);
|
setAdding(true);
|
||||||
setAddError(null);
|
setAddError(null);
|
||||||
setAddErrorOpen(false);
|
setAddErrorOpen(false);
|
||||||
try {
|
try {
|
||||||
const path = await pickDirectory();
|
const path = await pickWorkspaceDirectory();
|
||||||
if (path === null) return;
|
if (path === null) return;
|
||||||
startSession((await createWorkspace({ path })).workspaceId);
|
const workspace = await createWorkspace({ path });
|
||||||
|
if (categoryKey !== void 0) {
|
||||||
|
const latest = currentGrouping.current;
|
||||||
|
if (latest.manualSaving || !latest.groups.some((group) => group.key === categoryKey)) throw new Error("The group changed while adding the workspace. Please retry from the target group.");
|
||||||
|
const workspaceId = workspace.workspaceId;
|
||||||
|
const workspaceOrder = Object.fromEntries(Object.entries(latest.manual.workspaceOrder).map(([key, ids]) => [key, ids.filter((id) => id !== workspaceId)]));
|
||||||
|
workspaceOrder[categoryKey] = [...workspaceOrder[categoryKey] ?? [], workspaceId];
|
||||||
|
const next = {
|
||||||
|
...latest.manual,
|
||||||
|
assignments: {
|
||||||
|
...latest.manual.assignments,
|
||||||
|
[workspaceId]: categoryKey
|
||||||
|
},
|
||||||
|
workspaceOrder
|
||||||
|
};
|
||||||
|
setManualSaving(true);
|
||||||
|
try {
|
||||||
|
await saveManualOverlay(next);
|
||||||
|
setManual(next);
|
||||||
|
actions.setCategoryExpanded(categoryKey, true);
|
||||||
|
} finally {
|
||||||
|
setManualSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
startSession(workspace.workspaceId);
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
const message = reason instanceof Error ? reason.message : String(reason);
|
const message = reason instanceof Error ? reason.message : String(reason);
|
||||||
setAddError(message);
|
setAddError(message);
|
||||||
|
|
@ -4097,14 +4243,19 @@ window.__ModuleLoader__.load({
|
||||||
if (foldersBusy) return;
|
if (foldersBusy) return;
|
||||||
const workspace = workspaces.find((w) => w.workspaceId === workspaceId);
|
const workspace = workspaces.find((w) => w.workspaceId === workspaceId);
|
||||||
if (workspace === void 0) return;
|
if (workspace === void 0) return;
|
||||||
if (isRemoteWorkspace(workspace)) {
|
|
||||||
notifyFolder(t("folder.remoteNeedsSubpath"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setFoldersBusy(true);
|
setFoldersBusy(true);
|
||||||
try {
|
try {
|
||||||
|
if (foldersRemoteBase === null) throw new Error(t("folder.notReady"));
|
||||||
|
if (await remoteFolderWorkspace(workspace.path, foldersRemoteBase)) {
|
||||||
|
notifyFolder(t("folder.remoteNeedsSubpath"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
const path = await pickDirectory();
|
const path = await pickDirectory();
|
||||||
if (path === null) return;
|
if (path === null) return;
|
||||||
|
if (await remoteFolderWorkspace(path, foldersRemoteBase)) {
|
||||||
|
notifyFolder(t("folder.remoteNeedsSubpath"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
const entry = entryFor(foldersDoc, workspaceId);
|
const entry = entryFor(foldersDoc, workspaceId);
|
||||||
if (effectiveFolders(workspace.path, entry).some((folder) => samePath(folder, path))) {
|
if (effectiveFolders(workspace.path, entry).some((folder) => samePath(folder, path))) {
|
||||||
notifyFolder(t("folder.duplicate"));
|
notifyFolder(t("folder.duplicate"));
|
||||||
|
|
@ -4118,28 +4269,39 @@ window.__ModuleLoader__.load({
|
||||||
setFoldersBusy(false);
|
setFoldersBusy(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
/**
|
/** The same gesture routes through native local or SSH-owned mkdir APIs. */
|
||||||
* Add a folder to a REMOTE workspace by typing a path relative to its mirror.
|
const addSubpathTo = async (workspaceId, name) => {
|
||||||
* The mirror is a copy of the remote root, so `<mirror>/sub` and remote `sub`
|
if (foldersBusy) return false;
|
||||||
* are the same directory — that is the only way an extra folder can mean
|
|
||||||
* something on both sides.
|
|
||||||
*/
|
|
||||||
const addSubpathTo = (workspaceId, relative) => {
|
|
||||||
if (foldersBusy) return;
|
|
||||||
const workspace = workspaces.find((w) => w.workspaceId === workspaceId);
|
const workspace = workspaces.find((w) => w.workspaceId === workspaceId);
|
||||||
if (workspace === void 0) return;
|
if (workspace === void 0) return false;
|
||||||
const path = joinSubpath(workspace.path, relative);
|
setFoldersBusy(true);
|
||||||
if (path === null) {
|
try {
|
||||||
notifyFolder(t("folder.subpathInvalid"));
|
if (foldersRemoteBase === null) throw new Error(t("folder.notReady"));
|
||||||
return;
|
const pending = createdFolderPendingSave.current;
|
||||||
|
const created = pending?.workspaceId === workspaceId && pending.name === name ? pending : await createWorkspaceDirectory(workspace.path, name, foldersRemoteBase, createDirectory);
|
||||||
|
createdFolderPendingSave.current = {
|
||||||
|
workspaceId,
|
||||||
|
name,
|
||||||
|
path: created.path
|
||||||
|
};
|
||||||
|
const entry = addFolder(entryFor(foldersDoc, workspaceId), created.path);
|
||||||
|
const next = {
|
||||||
|
version: 1,
|
||||||
|
workspaces: {
|
||||||
|
...foldersDoc.workspaces,
|
||||||
|
[workspaceId]: entry
|
||||||
|
}
|
||||||
|
};
|
||||||
|
await saveFolders(next);
|
||||||
|
setFoldersDoc(next);
|
||||||
|
createdFolderPendingSave.current = null;
|
||||||
|
return true;
|
||||||
|
} catch (reason) {
|
||||||
|
notifyFolder(`${t("folder.addError")}: ${reason instanceof Error ? reason.message : String(reason)}`);
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
setFoldersBusy(false);
|
||||||
}
|
}
|
||||||
const entry = entryFor(foldersDoc, workspaceId);
|
|
||||||
if (effectiveFolders(workspace.path, entry).some((folder) => samePath(folder, path))) {
|
|
||||||
notifyFolder(t("folder.duplicate"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
writeFolderEntry(workspaceId, addFolder(entry, path));
|
|
||||||
ensureRemoteFolderMarker(workspace.path, path);
|
|
||||||
};
|
};
|
||||||
const setFolderRoot = (workspaceId, path) => {
|
const setFolderRoot = (workspaceId, path) => {
|
||||||
writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId), path));
|
writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId), path));
|
||||||
|
|
@ -4161,7 +4323,15 @@ window.__ModuleLoader__.load({
|
||||||
}
|
}
|
||||||
if (creatingSessionIn !== null) return;
|
if (creatingSessionIn !== null) return;
|
||||||
setCreatingSessionIn(folderKey(workspaceId, path));
|
setCreatingSessionIn(folderKey(workspaceId, path));
|
||||||
createSessionIn(workspaceId, path).catch((reason) => {
|
(async () => {
|
||||||
|
const workspace = workspaces.find((w) => w.workspaceId === workspaceId);
|
||||||
|
if (!workspace) throw new Error("Workspace not found");
|
||||||
|
if (foldersRemoteBase === null) throw new Error(t("folder.notReady"));
|
||||||
|
const remote = await remoteFolderWorkspace(workspace.path, foldersRemoteBase);
|
||||||
|
const targetRemote = await remoteFolderWorkspace(path, foldersRemoteBase);
|
||||||
|
if (remote || targetRemote) throw new Error(t("folder.remoteSessionUnsupported"));
|
||||||
|
await createSessionIn(workspaceId, path);
|
||||||
|
})().catch((reason) => {
|
||||||
const detail = reason instanceof Error ? reason.message : String(reason);
|
const detail = reason instanceof Error ? reason.message : String(reason);
|
||||||
notifyFolder(`${t("folder.sessionError")}: ${detail}`);
|
notifyFolder(`${t("folder.sessionError")}: ${detail}`);
|
||||||
}).finally(() => {
|
}).finally(() => {
|
||||||
|
|
@ -4624,7 +4794,9 @@ window.__ModuleLoader__.load({
|
||||||
className: "wgIconButton",
|
className: "wgIconButton",
|
||||||
"aria-label": t("workspace.add"),
|
"aria-label": t("workspace.add"),
|
||||||
disabled: adding,
|
disabled: adding,
|
||||||
onClick: addWorkspace,
|
onClick: () => {
|
||||||
|
addWorkspace();
|
||||||
|
},
|
||||||
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconProjectAddOutlineRegular, { size: wide ? 16 : 18 })
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconProjectAddOutlineRegular, { size: wide ? 16 : 18 })
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -4739,6 +4911,10 @@ window.__ModuleLoader__.load({
|
||||||
onSessionRename,
|
onSessionRename,
|
||||||
onSessionArchive,
|
onSessionArchive,
|
||||||
onFork: forkSession,
|
onFork: forkSession,
|
||||||
|
onAddWorkspace: () => {
|
||||||
|
addWorkspace(category.key);
|
||||||
|
},
|
||||||
|
addingWorkspace: adding || manualSaving,
|
||||||
onGroupRename: () => {
|
onGroupRename: () => {
|
||||||
setGroupDraft(category.key);
|
setGroupDraft(category.key);
|
||||||
setGroupError(null);
|
setGroupError(null);
|
||||||
|
|
@ -5036,9 +5212,7 @@ window.__ModuleLoader__.load({
|
||||||
onAdd: () => {
|
onAdd: () => {
|
||||||
addFolderTo(foldersTarget);
|
addFolderTo(foldersTarget);
|
||||||
},
|
},
|
||||||
onAddSubpath: (relative) => {
|
onAddSubpath: (relative) => addSubpathTo(foldersTarget, relative),
|
||||||
addSubpathTo(foldersTarget, relative);
|
|
||||||
},
|
|
||||||
onSetRoot: (path) => {
|
onSetRoot: (path) => {
|
||||||
setFolderRoot(foldersTarget, path);
|
setFolderRoot(foldersTarget, path);
|
||||||
},
|
},
|
||||||
|
|
@ -5150,6 +5324,20 @@ window.__ModuleLoader__.load({
|
||||||
children: sessionRenameError
|
children: sessionRenameError
|
||||||
})]
|
})]
|
||||||
}),
|
}),
|
||||||
|
directoryFlowOpen && DirectoryFlow && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DirectoryFlow, {
|
||||||
|
...directoryFlow?.injected,
|
||||||
|
open: true,
|
||||||
|
busy: false,
|
||||||
|
onPicked: (path) => {
|
||||||
|
finishDirectoryFlow(path);
|
||||||
|
},
|
||||||
|
onCancel: () => {
|
||||||
|
finishDirectoryFlow(null);
|
||||||
|
},
|
||||||
|
onError: (message) => {
|
||||||
|
finishDirectoryFlow(null, message);
|
||||||
|
}
|
||||||
|
}),
|
||||||
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Modal, {
|
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Modal, {
|
||||||
open: addErrorOpen,
|
open: addErrorOpen,
|
||||||
onClose: () => {
|
onClose: () => {
|
||||||
|
|
@ -5165,7 +5353,9 @@ window.__ModuleLoader__.load({
|
||||||
children: t("close")
|
children: t("close")
|
||||||
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
|
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
|
||||||
variant: "primary",
|
variant: "primary",
|
||||||
onClick: addWorkspace,
|
onClick: () => {
|
||||||
|
addWorkspace(addCategoryRef.current);
|
||||||
|
},
|
||||||
children: t("retry")
|
children: t("retry")
|
||||||
})] }),
|
})] }),
|
||||||
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
||||||
|
|
@ -5275,7 +5465,7 @@ window.__ModuleLoader__.load({
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
/** One category section: header row + expanded workspace folders. */
|
/** One category section: header row + expanded workspace folders. */
|
||||||
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }) {
|
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onAddWorkspace, addingWorkspace, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }) {
|
||||||
const categoryLine = dragIndicator?.mode === "line" && dragIndicator.row.kind === "category" && dragIndicator.row.key === category.key ? dragIndicator.before ? "before" : "after" : void 0;
|
const categoryLine = dragIndicator?.mode === "line" && dragIndicator.row.kind === "category" && dragIndicator.row.key === category.key ? dragIndicator.before ? "before" : "after" : void 0;
|
||||||
const categoryInto = dragIndicator?.mode === "into" && dragIndicator.categoryKey === category.key;
|
const categoryInto = dragIndicator?.mode === "into" && dragIndicator.categoryKey === category.key;
|
||||||
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
||||||
|
|
@ -5284,6 +5474,8 @@ window.__ModuleLoader__.load({
|
||||||
node: category,
|
node: category,
|
||||||
t,
|
t,
|
||||||
onToggle: onToggleCategory,
|
onToggle: onToggleCategory,
|
||||||
|
onAddWorkspace,
|
||||||
|
addingWorkspace,
|
||||||
onRename: onGroupRename,
|
onRename: onGroupRename,
|
||||||
onDelete: onGroupDelete,
|
onDelete: onGroupDelete,
|
||||||
onTogglePin: onGroupTogglePin,
|
onTogglePin: onGroupTogglePin,
|
||||||
|
|
@ -5610,8 +5802,10 @@ window.__ModuleLoader__.load({
|
||||||
const [subpath, setSubpath] = (0, react.useState)("");
|
const [subpath, setSubpath] = (0, react.useState)("");
|
||||||
const submitSubpath = () => {
|
const submitSubpath = () => {
|
||||||
if (subpath.trim() === "") return;
|
if (subpath.trim() === "") return;
|
||||||
onAddSubpath(subpath);
|
if (busy) return;
|
||||||
setSubpath("");
|
onAddSubpath(subpath).then((success) => {
|
||||||
|
if (success) setSubpath("");
|
||||||
|
});
|
||||||
};
|
};
|
||||||
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, {
|
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, {
|
||||||
open: true,
|
open: true,
|
||||||
|
|
@ -5681,9 +5875,9 @@ window.__ModuleLoader__.load({
|
||||||
]
|
]
|
||||||
}, path);
|
}, path);
|
||||||
})
|
})
|
||||||
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
|
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
||||||
className: "wgFolderListFooter",
|
className: "wgFolderListFooter",
|
||||||
children: remote ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
|
||||||
className: "wgFolderHint",
|
className: "wgFolderHint",
|
||||||
children: t("folder.remoteHint")
|
children: t("folder.remoteHint")
|
||||||
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
|
||||||
|
|
@ -5707,16 +5901,27 @@ window.__ModuleLoader__.load({
|
||||||
onClick: submitSubpath,
|
onClick: submitSubpath,
|
||||||
children: t("folder.addSubpath")
|
children: t("folder.addSubpath")
|
||||||
})]
|
})]
|
||||||
})] }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
|
})] }), !remote && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
|
||||||
variant: "outline",
|
variant: "outline",
|
||||||
disabled: busy,
|
disabled: busy,
|
||||||
onClick: onAdd,
|
onClick: onAdd,
|
||||||
children: t("folder.add")
|
children: t("folder.add")
|
||||||
})
|
})]
|
||||||
})]
|
})]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
//#endregion
|
//#endregion
|
||||||
|
//#region src/client/directory-flow.ts
|
||||||
|
/** Adapt the elected self-contained picker, without stealing its original slot. */
|
||||||
|
function directoryFlowFromEntry(entry) {
|
||||||
|
if (!entry) return null;
|
||||||
|
if (entry.store || entry.locale || entry.children || typeof entry.component !== "function") throw new Error("This directory picker requires an unsupported renderer context.");
|
||||||
|
return {
|
||||||
|
component: entry.component,
|
||||||
|
injected: entry.inject?.() ?? {}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
//#endregion
|
||||||
//#region src/client/locales.ts
|
//#region src/client/locales.ts
|
||||||
/** Simplified Chinese dictionary. */
|
/** Simplified Chinese dictionary. */
|
||||||
const zh = {
|
const zh = {
|
||||||
|
|
@ -5761,11 +5966,13 @@ window.__ModuleLoader__.load({
|
||||||
"folder.addError": "添加文件夹失败",
|
"folder.addError": "添加文件夹失败",
|
||||||
"folder.sessionError": "新建会话失败",
|
"folder.sessionError": "新建会话失败",
|
||||||
"folder.saveError": "文件夹保存失败",
|
"folder.saveError": "文件夹保存失败",
|
||||||
"folder.remoteHint": "远程(SSH)工作区:本地目录是服务器根目录的镜像,所以这里只能添加镜像内的子目录,填相对路径即可(也会同步到服务器同名目录)",
|
"folder.notReady": "目录安全信息尚未加载,请重启 DSH 并刷新页面后重试",
|
||||||
|
"folder.remoteSessionUnsupported": "当前 SSH 插件不完整支持子目录会话,请从远程工作区根目录打开会话。不会退回本地终端。",
|
||||||
|
"folder.remoteHint": "输入一个文件夹名:本地使用 DSH 目录接口;远程使用 SSH 创建目录接口(远端同名目录已存在时复用)。SSH 不可用时不会在镜像里创建本地目录。",
|
||||||
"folder.remoteNeedsSubpath": "远程工作区请用子目录方式添加文件夹",
|
"folder.remoteNeedsSubpath": "远程工作区请用子目录方式添加文件夹",
|
||||||
"folder.subpathLabel": "相对路径",
|
"folder.subpathLabel": "文件夹名称",
|
||||||
"folder.subpathPlaceholder": "例如 data 或 src/generated",
|
"folder.subpathPlaceholder": "例如 data",
|
||||||
"folder.addSubpath": "添加子目录",
|
"folder.addSubpath": "创建文件夹",
|
||||||
"folder.subpathInvalid": "路径无效:请填工作区内的相对路径,不能用绝对路径或 ..",
|
"folder.subpathInvalid": "路径无效:请填工作区内的相对路径,不能用绝对路径或 ..",
|
||||||
"group.create": "新建分组",
|
"group.create": "新建分组",
|
||||||
"group.createTitle": "新建分组",
|
"group.createTitle": "新建分组",
|
||||||
|
|
@ -5893,11 +6100,13 @@ window.__ModuleLoader__.load({
|
||||||
"folder.addError": "Could not add the folder",
|
"folder.addError": "Could not add the folder",
|
||||||
"folder.sessionError": "Could not start a session",
|
"folder.sessionError": "Could not start a session",
|
||||||
"folder.saveError": "Could not save folders",
|
"folder.saveError": "Could not save folders",
|
||||||
"folder.remoteHint": "Remote (SSH) workspace: the local directory mirrors the server root, so only subdirectories of that mirror can be added here — type a path relative to the workspace root",
|
"folder.notReady": "Directory safety information is not loaded. Restart DSH and refresh the page before retrying.",
|
||||||
|
"folder.remoteSessionUnsupported": "This SSH plugin does not fully support subdirectory sessions. Start from the remote workspace root instead; no local terminal fallback is allowed.",
|
||||||
|
"folder.remoteHint": "Enter one folder name. Local workspaces use DSH; remote workspaces use SSH mkdir (existing remote directories are reused). Missing SSH never falls back to a local mirror write.",
|
||||||
"folder.remoteNeedsSubpath": "Remote workspaces take a subdirectory, not a picked folder",
|
"folder.remoteNeedsSubpath": "Remote workspaces take a subdirectory, not a picked folder",
|
||||||
"folder.subpathLabel": "Relative path",
|
"folder.subpathLabel": "Folder name",
|
||||||
"folder.subpathPlaceholder": "e.g. data or src/generated",
|
"folder.subpathPlaceholder": "e.g. data",
|
||||||
"folder.addSubpath": "Add subdirectory",
|
"folder.addSubpath": "Create folder",
|
||||||
"folder.subpathInvalid": "Invalid path: use a relative path inside the workspace (no absolute paths, no ..)",
|
"folder.subpathInvalid": "Invalid path: use a relative path inside the workspace (no absolute paths, no ..)",
|
||||||
"group.create": "New group",
|
"group.create": "New group",
|
||||||
"group.createTitle": "New group",
|
"group.createTitle": "New group",
|
||||||
|
|
@ -6076,6 +6285,8 @@ window.__ModuleLoader__.load({
|
||||||
await ctx.uiWorkspace.archiveSession(sessionId);
|
await ctx.uiWorkspace.archiveSession(sessionId);
|
||||||
},
|
},
|
||||||
pickDirectory: () => ctx.uiWorkspace.pickDirectory(),
|
pickDirectory: () => ctx.uiWorkspace.pickDirectory(),
|
||||||
|
getDirectoryFlow: () => directoryFlowFromEntry(ctx.slots.entriesOfSlot("sidebar.workspaces.directoryFlow")[0]),
|
||||||
|
createDirectory: (path, name) => ctx.uiWorkspace.createDirectory(path, name),
|
||||||
searchSessions,
|
searchSessions,
|
||||||
searchResultLimit: ctx.sessions.searchResultLimit,
|
searchResultLimit: ctx.sessions.searchResultLimit,
|
||||||
hooks: { directoryFlow: {
|
hooks: { directoryFlow: {
|
||||||
|
|
|
||||||
File diff suppressed because one or more lines are too long
178
lib/index.js
178
lib/index.js
|
|
@ -1,5 +1,5 @@
|
||||||
import { mkdir, open, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises";
|
||||||
import { dirname, relative, resolve, sep } from "node:path";
|
import { dirname, resolve } from "node:path";
|
||||||
import { homedir } from "node:os";
|
import { homedir } from "node:os";
|
||||||
//#region node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs
|
//#region node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs
|
||||||
function getDefaultExportFromCjs(x) {
|
function getDefaultExportFromCjs(x) {
|
||||||
|
|
@ -3001,6 +3001,31 @@ function defaultRemoteMirrorBase() {
|
||||||
function isAbsoluteFolderPath(path) {
|
function isAbsoluteFolderPath(path) {
|
||||||
return process.platform === "win32" ? WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path) : POSIX_ABSOLUTE.test(path);
|
return process.platform === "win32" ? WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path) : POSIX_ABSOLUTE.test(path);
|
||||||
}
|
}
|
||||||
|
/** Validate a local path for the read-only remote hint endpoint. */
|
||||||
|
function validateRemoteHintPath(path) {
|
||||||
|
if (typeof path !== "string" || path.length === 0 || path.length > 1024 || path.includes("\0") || !isAbsoluteFolderPath(path)) throw new Error("remote hint path must be an absolute host path without NUL, at most 1024 characters");
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Presence-only safety hint, never a trusted SSH connection or registration.
|
||||||
|
* lstat also treats dangling symlinks as hints without reading their targets.
|
||||||
|
* Only ENOENT is ignored: permissions and all other inspection failures must
|
||||||
|
* prevent callers from silently falling back to local operations.
|
||||||
|
*/
|
||||||
|
async function hasRemoteMarkerHint(path) {
|
||||||
|
let directory = resolve(validateRemoteHintPath(path));
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
await lstat(resolve(directory, ".remote-ssh.json"));
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== "ENOENT") throw error;
|
||||||
|
}
|
||||||
|
const parent = dirname(directory);
|
||||||
|
if (parent === directory) return false;
|
||||||
|
directory = parent;
|
||||||
|
}
|
||||||
|
}
|
||||||
/** Reject helper carrying the stable file-scoped message prefix. */
|
/** Reject helper carrying the stable file-scoped message prefix. */
|
||||||
function invalid(detail) {
|
function invalid(detail) {
|
||||||
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`);
|
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`);
|
||||||
|
|
@ -3170,95 +3195,6 @@ async function writeFoldersDocument(path, document) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/** Connection record of the remote-ssh plugin at a mirror root. */
|
|
||||||
const REMOTE_MARKER_FILE_NAME = ".remote-ssh.json";
|
|
||||||
/**
|
|
||||||
* Read the remote-ssh connection record of a directory.
|
|
||||||
* @param dir - directory that may hold the record (a mirror root, usually).
|
|
||||||
* @returns the record, or null when the directory is not remote-backed.
|
|
||||||
*/
|
|
||||||
async function readRemoteMarker(dir) {
|
|
||||||
let text;
|
|
||||||
try {
|
|
||||||
text = await readFile(resolve(dir, REMOTE_MARKER_FILE_NAME), "utf8");
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
let parsed;
|
|
||||||
try {
|
|
||||||
parsed = JSON.parse(text);
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
|
|
||||||
const row = parsed;
|
|
||||||
if (typeof row.host !== "string" || row.host === "") return null;
|
|
||||||
if (typeof row.user !== "string" || row.user === "") return null;
|
|
||||||
const port = typeof row.port === "number" && Number.isInteger(row.port) && row.port > 0 ? row.port : 22;
|
|
||||||
const remotePath = typeof row.remotePath === "string" ? row.remotePath.trim() : "";
|
|
||||||
if (remotePath === "") return null;
|
|
||||||
return {
|
|
||||||
...typeof row.profileId === "string" && row.profileId !== "" ? { profileId: row.profileId } : {},
|
|
||||||
host: row.host,
|
|
||||||
port,
|
|
||||||
user: row.user,
|
|
||||||
...typeof row.keyPath === "string" ? { keyPath: row.keyPath } : {},
|
|
||||||
...typeof row.proxyJump === "string" && row.proxyJump !== "" ? { proxyJump: row.proxyJump } : {},
|
|
||||||
remotePath
|
|
||||||
};
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Join a remote path with a mirror-relative subpath.
|
|
||||||
*
|
|
||||||
* The remote path is POSIX (the server's), so this never uses `node:path`:
|
|
||||||
* a Windows host would otherwise hand `/home/me/proj\data` to the remote shell.
|
|
||||||
* @param remotePath - the workspace's remote root (`~`, `~/proj`, `/srv/proj`).
|
|
||||||
* @param relativePath - subpath inside the mirror, either separator style.
|
|
||||||
* @returns the remote counterpart, or null for an empty or escaping subpath.
|
|
||||||
*/
|
|
||||||
function remoteSubpath(remotePath, relativePath) {
|
|
||||||
const rel = relativePath.trim().replace(/\\/gu, "/").replace(/^\/+|\/+$/gu, "");
|
|
||||||
if (rel === "") return null;
|
|
||||||
if (rel.split("/").some((segment) => segment === ".." || segment === ".")) return null;
|
|
||||||
const base = remotePath === "~" ? "~" : remotePath.replace(/\/+$/u, "");
|
|
||||||
return base === "" ? rel : `${base}/${rel}`;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Stamp the remote-ssh connection record into a subdirectory of a mirror, so
|
|
||||||
* that sessions started there keep a remote terminal (see the block comment).
|
|
||||||
*
|
|
||||||
* A workspace that is not remote-backed is left untouched: no record at the
|
|
||||||
* workspace root means the plugin has nothing to reproduce.
|
|
||||||
* @param workspacePath - the workspace's canonical directory (the mirror root).
|
|
||||||
* @param folderPath - subdirectory added as an extra folder.
|
|
||||||
* @returns `{ marked: false }` for a local workspace, otherwise the remote path
|
|
||||||
* written into the subdirectory record.
|
|
||||||
*/
|
|
||||||
async function ensureRemoteMarker(workspacePath, folderPath) {
|
|
||||||
const base = resolve(workspacePath);
|
|
||||||
const folder = resolve(folderPath);
|
|
||||||
const rel = relative(base, folder);
|
|
||||||
if (rel === "" || rel.startsWith("..")) throw invalid("folder is not inside the workspace directory");
|
|
||||||
const marker = await readRemoteMarker(base);
|
|
||||||
if (marker === null) return { marked: false };
|
|
||||||
const remotePath = remoteSubpath(marker.remotePath, rel.split(sep).join("/"));
|
|
||||||
if (remotePath === null) throw invalid("remote subpath is unusable");
|
|
||||||
const record = {
|
|
||||||
...marker.profileId === void 0 ? {} : { profileId: marker.profileId },
|
|
||||||
host: marker.host,
|
|
||||||
port: marker.port,
|
|
||||||
user: marker.user,
|
|
||||||
...marker.keyPath === void 0 ? {} : { keyPath: marker.keyPath },
|
|
||||||
...marker.proxyJump === void 0 ? {} : { proxyJump: marker.proxyJump },
|
|
||||||
remotePath
|
|
||||||
};
|
|
||||||
await mkdir(folder, { recursive: true });
|
|
||||||
await writeFile(resolve(folder, REMOTE_MARKER_FILE_NAME), JSON.stringify(record, null, 2), "utf8");
|
|
||||||
return {
|
|
||||||
marked: true,
|
|
||||||
remotePath
|
|
||||||
};
|
|
||||||
}
|
|
||||||
//#endregion
|
//#endregion
|
||||||
//#region src/index.ts
|
//#region src/index.ts
|
||||||
/** Plugin identity for cordis.yml rows. */
|
/** Plugin identity for cordis.yml rows. */
|
||||||
|
|
@ -3448,6 +3384,37 @@ function apply(ctx) {
|
||||||
res.end(body);
|
res.end(body);
|
||||||
}
|
}
|
||||||
}), "@dsh-xhl/workspace-groups: /workspace-groups/manual route");
|
}), "@dsh-xhl/workspace-groups: /workspace-groups/manual route");
|
||||||
|
ctx.effect(() => ctx.webServer.register({
|
||||||
|
kind: "exact",
|
||||||
|
path: "/workspace-groups/remote-hint",
|
||||||
|
handler: async (req, res) => {
|
||||||
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||||
|
writeError(res, 405, "method not allowed");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let path;
|
||||||
|
try {
|
||||||
|
path = validateRemoteHintPath(new URL(req.url ?? "", "http://localhost").searchParams.get("path"));
|
||||||
|
} catch {
|
||||||
|
writeError(res, 400, "workspace-groups: invalid remote hint path");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let remoteHint;
|
||||||
|
try {
|
||||||
|
remoteHint = await hasRemoteMarkerHint(path);
|
||||||
|
} catch {
|
||||||
|
writeError(res, 500, "workspace-groups: failed to inspect remote hint; local fallback is unsafe");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const body = JSON.stringify({ remoteHint });
|
||||||
|
res.writeHead(200, {
|
||||||
|
"Content-Type": "application/json; charset=utf-8",
|
||||||
|
"Cache-Control": "no-store",
|
||||||
|
"Content-Length": Buffer.byteLength(body)
|
||||||
|
});
|
||||||
|
res.end(req.method === "HEAD" ? void 0 : body);
|
||||||
|
}
|
||||||
|
}), "@dsh-xhl/workspace-groups: /workspace-groups/remote-hint route");
|
||||||
ctx.effect(() => ctx.webServer.register({
|
ctx.effect(() => ctx.webServer.register({
|
||||||
kind: "exact",
|
kind: "exact",
|
||||||
path: "/workspace-groups/folders",
|
path: "/workspace-groups/folders",
|
||||||
|
|
@ -3467,34 +3434,7 @@ function apply(ctx) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (req.method === "POST") {
|
if (req.method === "POST") {
|
||||||
let raw;
|
writeError(res, 410, "workspace-groups: remote marker creation is deprecated; use the registered remote workspace root");
|
||||||
try {
|
|
||||||
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES));
|
|
||||||
} catch (error) {
|
|
||||||
writeError(res, error instanceof HttpError ? error.status : 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const payload = typeof raw === "object" && raw !== null ? raw : {};
|
|
||||||
const workspacePath = typeof payload.workspacePath === "string" ? payload.workspacePath.trim() : "";
|
|
||||||
const folderPath = typeof payload.folderPath === "string" ? payload.folderPath.trim() : "";
|
|
||||||
if (workspacePath === "" || folderPath === "") {
|
|
||||||
writeError(res, 400, "workspace-groups: workspacePath and folderPath are required");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let result;
|
|
||||||
try {
|
|
||||||
result = await ensureRemoteMarker(workspacePath, folderPath);
|
|
||||||
} catch (error) {
|
|
||||||
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const marked = JSON.stringify(result);
|
|
||||||
res.writeHead(200, {
|
|
||||||
"Content-Type": "application/json; charset=utf-8",
|
|
||||||
"Cache-Control": "no-store",
|
|
||||||
"Content-Length": Buffer.byteLength(marked)
|
|
||||||
});
|
|
||||||
res.end(marked);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (req.method !== "PUT") {
|
if (req.method !== "PUT") {
|
||||||
|
|
|
||||||
|
|
@ -30,4 +30,4 @@ export type DragIndicator = {
|
||||||
* @param props - composed slot props (shell owner share + store + injected actions).
|
* @param props - composed slot props (shell owner share + store + injected actions).
|
||||||
* @returns the region element tree.
|
* @returns the region element tree.
|
||||||
*/
|
*/
|
||||||
export declare function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, createSessionIn, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t, }: GroupsBrowserProps): import("react").JSX.Element;
|
export declare function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, createSessionIn, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, getDirectoryFlow, createDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t, }: GroupsBrowserProps): import("react").JSX.Element;
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,8 @@
|
||||||
* self-contained via `pickDirectory` — and no locale-keyed naming collision.
|
* self-contained via `pickDirectory` — and no locale-keyed naming collision.
|
||||||
*/
|
*/
|
||||||
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots';
|
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots';
|
||||||
|
import type { ComponentType } from 'react';
|
||||||
|
import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client';
|
||||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||||
import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client';
|
import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||||
import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client';
|
import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client';
|
||||||
|
|
@ -64,6 +66,13 @@ export type GroupsBrowserInjected = {
|
||||||
}) => Promise<WorkspaceView>;
|
}) => Promise<WorkspaceView>;
|
||||||
/** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */
|
/** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */
|
||||||
pickDirectory: () => Promise<string | null>;
|
pickDirectory: () => Promise<string | null>;
|
||||||
|
/** Snapshot a self-contained standard picker without redeclaring its owned slot. */
|
||||||
|
getDirectoryFlow: () => {
|
||||||
|
component: ComponentType<DirectoryFlowOwnerProps>;
|
||||||
|
injected: Record<string, unknown>;
|
||||||
|
} | null;
|
||||||
|
/** DSH native local directory creation (SSH routing is owned by our adapter). */
|
||||||
|
createDirectory: (path: string, name: string) => Promise<string>;
|
||||||
/**
|
/**
|
||||||
* Surface the session-tab strip for a session that is in play (called with the
|
* Surface the session-tab strip for a session that is in play (called with the
|
||||||
* session the browser itself just opened, and again whenever its status
|
* session the browser itself just opened, and again whenever its status
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots';
|
||||||
|
import type { GroupsBrowserInjected } from './contract.ts';
|
||||||
|
/** Adapt the elected self-contained picker, without stealing its original slot. */
|
||||||
|
export declare function directoryFlowFromEntry(entry: StoredEntry | undefined): ReturnType<GroupsBrowserInjected['getDirectoryFlow']>;
|
||||||
|
|
@ -0,0 +1,13 @@
|
||||||
|
export interface RemoteFolderWorkspace {
|
||||||
|
mirrorPath: string;
|
||||||
|
remotePath: string;
|
||||||
|
profileId: string;
|
||||||
|
}
|
||||||
|
/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */
|
||||||
|
export declare function remoteFolderWorkspace(path: string, remoteBase: string | null, fetchImpl?: typeof fetch): Promise<RemoteFolderWorkspace | null>;
|
||||||
|
/** Single-segment names match DSH createDirectory(path, name). */
|
||||||
|
export declare function validateFolderName(raw: string): string;
|
||||||
|
export declare function createWorkspaceDirectory(parent: string, rawName: string, remoteBase: string | null, createLocal: (path: string, name: string) => Promise<string>, fetchImpl?: typeof fetch): Promise<{
|
||||||
|
path: string;
|
||||||
|
remote: boolean;
|
||||||
|
}>;
|
||||||
|
|
@ -42,18 +42,3 @@ export declare function loadFolders(fetchImpl?: typeof fetch): Promise<FoldersSn
|
||||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||||
*/
|
*/
|
||||||
export declare function saveFolders(document: FoldersDocument, fetchImpl?: typeof fetch): Promise<void>;
|
export declare function saveFolders(document: FoldersDocument, fetchImpl?: typeof fetch): Promise<void>;
|
||||||
/**
|
|
||||||
* Ask the host to stamp the remote-ssh connection record into an extra folder of
|
|
||||||
* a MIRROR workspace.
|
|
||||||
*
|
|
||||||
* remote-ssh decides "remote backed" by reading `.remote-ssh.json` at the
|
|
||||||
* session cwd and never walks up, so a folder below the mirror root would
|
|
||||||
* otherwise get a local terminal. Best-effort: the folder itself is already
|
|
||||||
* persisted by the time this runs, and a local workspace answers `marked:false`
|
|
||||||
* (nothing to stamp) rather than failing.
|
|
||||||
* @param workspacePath - the workspace's canonical directory (mirror root).
|
|
||||||
* @param folderPath - the extra folder just added.
|
|
||||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
|
||||||
* @returns true when a record was written.
|
|
||||||
*/
|
|
||||||
export declare function ensureRemoteFolderMarker(workspacePath: string, folderPath: string, fetchImpl?: typeof fetch): Promise<boolean>;
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
*/
|
*/
|
||||||
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
|
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
|
||||||
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
|
/** 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.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | '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' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'manual.saveError' | '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.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | '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' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'manual.saveError' | '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'>;
|
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
|
||||||
/** Simplified Chinese dictionary. */
|
/** Simplified Chinese dictionary. */
|
||||||
export declare const zh: WorkspaceGroupsDict;
|
export declare const zh: WorkspaceGroupsDict;
|
||||||
|
|
|
||||||
|
|
@ -50,10 +50,13 @@ export declare function CategoryGlyph({ icon, fallback }: {
|
||||||
* groups via overlay renames/hides), draggable source for group reorder and
|
* groups via overlay renames/hides), draggable source for group reorder and
|
||||||
* drop target for both workspace moves and group reorders.
|
* drop target for both workspace moves and group reorders.
|
||||||
*/
|
*/
|
||||||
export declare function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin, onEditAppearance, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {
|
export declare function CategoryRow({ node, t, onToggle, onAddWorkspace, addingWorkspace, onRename, onDelete, onTogglePin, onEditAppearance, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {
|
||||||
node: CategoryNode;
|
node: CategoryNode;
|
||||||
t: T;
|
t: T;
|
||||||
onToggle: () => void;
|
onToggle: () => void;
|
||||||
|
/** Create and assign a workspace directly to this category. */
|
||||||
|
onAddWorkspace?: () => void;
|
||||||
|
addingWorkspace?: boolean;
|
||||||
/** Rename/delete actions; the hover menu renders only when both provided. */
|
/** Rename/delete actions; the hover menu renders only when both provided. */
|
||||||
onRename?: () => void;
|
onRename?: () => void;
|
||||||
onDelete?: () => void;
|
onDelete?: () => void;
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,15 @@ export declare function defaultRemoteMirrorBase(): string;
|
||||||
* @param path - candidate path.
|
* @param path - candidate path.
|
||||||
*/
|
*/
|
||||||
export declare function isAbsoluteFolderPath(path: string): boolean;
|
export declare function isAbsoluteFolderPath(path: string): boolean;
|
||||||
|
/** Validate a local path for the read-only remote hint endpoint. */
|
||||||
|
export declare function validateRemoteHintPath(path: unknown): string;
|
||||||
|
/**
|
||||||
|
* Presence-only safety hint, never a trusted SSH connection or registration.
|
||||||
|
* lstat also treats dangling symlinks as hints without reading their targets.
|
||||||
|
* Only ENOENT is ignored: permissions and all other inspection failures must
|
||||||
|
* prevent callers from silently falling back to local operations.
|
||||||
|
*/
|
||||||
|
export declare function hasRemoteMarkerHint(path: string): Promise<boolean>;
|
||||||
/**
|
/**
|
||||||
* Tolerant reader: shape-normalizes whatever was on disk and drops unusable
|
* Tolerant reader: shape-normalizes whatever was on disk and drops unusable
|
||||||
* workspaces, folders and roots instead of throwing. A missing, non-mapping or
|
* workspaces, folders and roots instead of throwing. A missing, non-mapping or
|
||||||
|
|
@ -58,24 +67,6 @@ export declare function readFoldersDocument(path: string): Promise<FoldersDocume
|
||||||
* @param document - validated document to persist.
|
* @param document - validated document to persist.
|
||||||
*/
|
*/
|
||||||
export declare function writeFoldersDocument(path: string, document: FoldersDocument): Promise<void>;
|
export declare function writeFoldersDocument(path: string, document: FoldersDocument): Promise<void>;
|
||||||
/** Connection record of the remote-ssh plugin at a mirror root. */
|
|
||||||
export declare const REMOTE_MARKER_FILE_NAME = ".remote-ssh.json";
|
|
||||||
/** The subset of that record this plugin needs to reproduce it. */
|
|
||||||
export interface RemoteMarker {
|
|
||||||
readonly profileId?: string;
|
|
||||||
readonly host: string;
|
|
||||||
readonly port: number;
|
|
||||||
readonly user: string;
|
|
||||||
readonly keyPath?: string;
|
|
||||||
readonly proxyJump?: string;
|
|
||||||
readonly remotePath: string;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* Read the remote-ssh connection record of a directory.
|
|
||||||
* @param dir - directory that may hold the record (a mirror root, usually).
|
|
||||||
* @returns the record, or null when the directory is not remote-backed.
|
|
||||||
*/
|
|
||||||
export declare function readRemoteMarker(dir: string): Promise<RemoteMarker | null>;
|
|
||||||
/**
|
/**
|
||||||
* Join a remote path with a mirror-relative subpath.
|
* Join a remote path with a mirror-relative subpath.
|
||||||
*
|
*
|
||||||
|
|
@ -86,18 +77,3 @@ export declare function readRemoteMarker(dir: string): Promise<RemoteMarker | nu
|
||||||
* @returns the remote counterpart, or null for an empty or escaping subpath.
|
* @returns the remote counterpart, or null for an empty or escaping subpath.
|
||||||
*/
|
*/
|
||||||
export declare function remoteSubpath(remotePath: string, relativePath: string): string | null;
|
export declare function remoteSubpath(remotePath: string, relativePath: string): string | null;
|
||||||
/**
|
|
||||||
* Stamp the remote-ssh connection record into a subdirectory of a mirror, so
|
|
||||||
* that sessions started there keep a remote terminal (see the block comment).
|
|
||||||
*
|
|
||||||
* A workspace that is not remote-backed is left untouched: no record at the
|
|
||||||
* workspace root means the plugin has nothing to reproduce.
|
|
||||||
* @param workspacePath - the workspace's canonical directory (the mirror root).
|
|
||||||
* @param folderPath - subdirectory added as an extra folder.
|
|
||||||
* @returns `{ marked: false }` for a local workspace, otherwise the remote path
|
|
||||||
* written into the subdirectory record.
|
|
||||||
*/
|
|
||||||
export declare function ensureRemoteMarker(workspacePath: string, folderPath: string): Promise<{
|
|
||||||
marked: boolean;
|
|
||||||
remotePath?: string;
|
|
||||||
}>;
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "workspace-groups-local",
|
"name": "workspace-groups-local",
|
||||||
"version": "0.6.2",
|
"version": "1.0.0",
|
||||||
"description": "Complete workspace grouping manager for the DSH web sidebar: category -> project -> session three-level tree with optional per-project folders (multi-root), manual group create/rename/delete, drag-and-drop grouping and ordering with insertion indicator, rule-based auto-classification, tree search, group colour/icon/pin, plus the session tab strip seated in the conversation column head. Sidecar YAML + runtime overlays, zero core-storage intrusion.",
|
"description": "Complete workspace grouping manager for the DSH web sidebar: category -> project -> session three-level tree with optional per-project folders (multi-root), manual group create/rename/delete, drag-and-drop grouping and ordering with insertion indicator, rule-based auto-classification, tree search, group colour/icon/pin, plus the session tab strip seated in the conversation column head. Sidecar YAML + runtime overlays, zero core-storage intrusion.",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"dsh",
|
"dsh",
|
||||||
|
|
|
||||||
|
|
@ -55,8 +55,9 @@ import type { GroupsBrowserProps } from './contract.ts'
|
||||||
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, folderKey, folderLabel, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'
|
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, folderKey, folderLabel, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'
|
||||||
import { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, FolderRow, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx'
|
import { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, FolderRow, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx'
|
||||||
import type { WorkspaceGroupsKey } from './locales.ts'
|
import type { WorkspaceGroupsKey } from './locales.ts'
|
||||||
import { EMPTY_FOLDERS_DOCUMENT, addFolder, effectiveFolders, entryFor, isUnderBase, joinSubpath, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'
|
import { EMPTY_FOLDERS_DOCUMENT, addFolder, effectiveFolders, entryFor, isUnderBase, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'
|
||||||
import { ensureRemoteFolderMarker, loadFolders, saveFolders } from './folders-persist.ts'
|
import { loadFolders, saveFolders } from './folders-persist.ts'
|
||||||
|
import { createWorkspaceDirectory, remoteFolderWorkspace } from './folder-directory.ts'
|
||||||
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
|
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
|
||||||
import { QuickPanel } from './QuickPanel.tsx'
|
import { QuickPanel } from './QuickPanel.tsx'
|
||||||
import { SessionTabs } from './SessionTabs.tsx'
|
import { SessionTabs } from './SessionTabs.tsx'
|
||||||
|
|
@ -219,6 +220,8 @@ export function GroupsBrowser({
|
||||||
insertSessionBefore,
|
insertSessionBefore,
|
||||||
createWorkspace,
|
createWorkspace,
|
||||||
pickDirectory,
|
pickDirectory,
|
||||||
|
getDirectoryFlow,
|
||||||
|
createDirectory,
|
||||||
searchSessions,
|
searchSessions,
|
||||||
searchResultLimit,
|
searchResultLimit,
|
||||||
openTab,
|
openTab,
|
||||||
|
|
@ -283,6 +286,7 @@ export function GroupsBrowser({
|
||||||
const [collapsedFolderKeys, setCollapsedFolderKeys] = useState<readonly string[]>([])
|
const [collapsedFolderKeys, setCollapsedFolderKeys] = useState<readonly string[]>([])
|
||||||
const [foldersTarget, setFoldersTarget] = useState<WorkspaceId | null>(null)
|
const [foldersTarget, setFoldersTarget] = useState<WorkspaceId | null>(null)
|
||||||
const [foldersBusy, setFoldersBusy] = useState(false)
|
const [foldersBusy, setFoldersBusy] = useState(false)
|
||||||
|
const createdFolderPendingSave = useRef<{ workspaceId: WorkspaceId; name: string; path: string } | null>(null)
|
||||||
const [creatingSessionIn, setCreatingSessionIn] = useState<string | null>(null)
|
const [creatingSessionIn, setCreatingSessionIn] = useState<string | null>(null)
|
||||||
// Local mirror root of the remote-ssh plugin, as reported by the host. A
|
// Local mirror root of the remote-ssh plugin, as reported by the host. A
|
||||||
// project whose directory lives below it is a REMOTE workspace: its folder is
|
// project whose directory lives below it is a REMOTE workspace: its folder is
|
||||||
|
|
@ -458,19 +462,71 @@ export function GroupsBrowser({
|
||||||
// appends to the end of the list. No whole-area highlight box.
|
// appends to the end of the list. No whole-area highlight box.
|
||||||
const topLevelRef: DropRowRef = { kind: 'topLevel', key: UNCATEGORIZED_KEY }
|
const topLevelRef: DropRowRef = { kind: 'topLevel', key: UNCATEGORIZED_KEY }
|
||||||
|
|
||||||
// Add workspace flow: self-contained (no directory-flow hole dependency).
|
// Use the elected standard flow, including remote-ssh's local/remote picker.
|
||||||
|
const [directoryFlowOpen, setDirectoryFlowOpen] = useState(false)
|
||||||
|
const [directoryFlow, setDirectoryFlow] = useState<ReturnType<GroupsBrowserProps['getDirectoryFlow']>>(null)
|
||||||
|
const DirectoryFlow = directoryFlow?.component
|
||||||
|
const directoryRequest = useRef<{
|
||||||
|
resolve: (path: string | null) => void
|
||||||
|
reject: (error: Error) => void
|
||||||
|
} | null>(null)
|
||||||
|
const finishDirectoryFlow = (path: string | null, error?: string): void => {
|
||||||
|
const pending = directoryRequest.current
|
||||||
|
directoryRequest.current = null
|
||||||
|
setDirectoryFlowOpen(false)
|
||||||
|
if (error !== undefined) pending?.reject(new Error(error))
|
||||||
|
else pending?.resolve(path)
|
||||||
|
}
|
||||||
|
useEffect(() => () => {
|
||||||
|
directoryRequest.current?.resolve(null)
|
||||||
|
directoryRequest.current = null
|
||||||
|
}, [])
|
||||||
|
const pickWorkspaceDirectory = (): Promise<string | null> => {
|
||||||
|
const flow = getDirectoryFlow()
|
||||||
|
if (!flow) return pickDirectory()
|
||||||
|
if (directoryRequest.current) return Promise.resolve(null)
|
||||||
|
setDirectoryFlow(flow)
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
directoryRequest.current = { resolve, reject }
|
||||||
|
setDirectoryFlowOpen(true)
|
||||||
|
})
|
||||||
|
}
|
||||||
const [adding, setAdding] = useState(false)
|
const [adding, setAdding] = useState(false)
|
||||||
const [addError, setAddError] = useState<string | null>(null)
|
const [addError, setAddError] = useState<string | null>(null)
|
||||||
const [addErrorOpen, setAddErrorOpen] = useState(false)
|
const [addErrorOpen, setAddErrorOpen] = useState(false)
|
||||||
const addWorkspace = async (): Promise<void> => {
|
const addCategoryRef = useRef<string | undefined>(undefined)
|
||||||
if (adding) return
|
const currentGrouping = useRef({ manual, groups, manualSaving })
|
||||||
|
currentGrouping.current = { manual, groups, manualSaving }
|
||||||
|
const addWorkspace = async (categoryKey?: string): Promise<void> => {
|
||||||
|
if (adding || manualSaving) return
|
||||||
|
addCategoryRef.current = categoryKey
|
||||||
setAdding(true)
|
setAdding(true)
|
||||||
setAddError(null)
|
setAddError(null)
|
||||||
setAddErrorOpen(false)
|
setAddErrorOpen(false)
|
||||||
try {
|
try {
|
||||||
const path = await pickDirectory()
|
const path = await pickWorkspaceDirectory()
|
||||||
if (path === null) return // cancelled
|
if (path === null) return // cancelled
|
||||||
const workspace = await createWorkspace({ path })
|
const workspace = await createWorkspace({ path })
|
||||||
|
if (categoryKey !== undefined) {
|
||||||
|
// Use the returned ID: the workspace observable may not have caught up yet.
|
||||||
|
const latest = currentGrouping.current
|
||||||
|
if (latest.manualSaving || !latest.groups.some(group => group.key === categoryKey)) {
|
||||||
|
throw new Error('The group changed while adding the workspace. Please retry from the target group.')
|
||||||
|
}
|
||||||
|
const workspaceId = workspace.workspaceId as string
|
||||||
|
const workspaceOrder = Object.fromEntries(Object.entries(latest.manual.workspaceOrder)
|
||||||
|
.map(([key, ids]) => [key, ids.filter(id => id !== workspaceId)]))
|
||||||
|
workspaceOrder[categoryKey] = [...(workspaceOrder[categoryKey] ?? []), workspaceId]
|
||||||
|
const next = { ...latest.manual, assignments: { ...latest.manual.assignments, [workspaceId]: categoryKey }, workspaceOrder }
|
||||||
|
setManualSaving(true)
|
||||||
|
try {
|
||||||
|
await saveManualOverlay(next)
|
||||||
|
setManual(next)
|
||||||
|
actions.setCategoryExpanded(categoryKey, true)
|
||||||
|
} finally {
|
||||||
|
setManualSaving(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
startSession(workspace.workspaceId)
|
startSession(workspace.workspaceId)
|
||||||
} catch (reason) {
|
} catch (reason) {
|
||||||
const message = reason instanceof Error ? reason.message : String(reason)
|
const message = reason instanceof Error ? reason.message : String(reason)
|
||||||
|
|
@ -624,14 +680,19 @@ export function GroupsBrowser({
|
||||||
// native picker would happily return an unrelated local directory that has
|
// native picker would happily return an unrelated local directory that has
|
||||||
// no remote counterpart, so that path is closed off here and the dialog
|
// no remote counterpart, so that path is closed off here and the dialog
|
||||||
// takes a subpath instead.
|
// takes a subpath instead.
|
||||||
if (isRemoteWorkspace(workspace)) {
|
|
||||||
notifyFolder(t('folder.remoteNeedsSubpath'))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setFoldersBusy(true)
|
setFoldersBusy(true)
|
||||||
try {
|
try {
|
||||||
|
if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))
|
||||||
|
if (await remoteFolderWorkspace(workspace.path, foldersRemoteBase)) {
|
||||||
|
notifyFolder(t('folder.remoteNeedsSubpath'))
|
||||||
|
return
|
||||||
|
}
|
||||||
const path = await pickDirectory()
|
const path = await pickDirectory()
|
||||||
if (path === null) return // cancelled
|
if (path === null) return // cancelled
|
||||||
|
if (await remoteFolderWorkspace(path, foldersRemoteBase)) {
|
||||||
|
notifyFolder(t('folder.remoteNeedsSubpath'))
|
||||||
|
return
|
||||||
|
}
|
||||||
const entry = entryFor(foldersDoc, workspaceId as string)
|
const entry = entryFor(foldersDoc, workspaceId as string)
|
||||||
if (effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))) {
|
if (effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))) {
|
||||||
notifyFolder(t('folder.duplicate'))
|
notifyFolder(t('folder.duplicate'))
|
||||||
|
|
@ -646,31 +707,33 @@ export function GroupsBrowser({
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** The same gesture routes through native local or SSH-owned mkdir APIs. */
|
||||||
* Add a folder to a REMOTE workspace by typing a path relative to its mirror.
|
const addSubpathTo = async (workspaceId: WorkspaceId, name: string): Promise<boolean> => {
|
||||||
* The mirror is a copy of the remote root, so `<mirror>/sub` and remote `sub`
|
if (foldersBusy) return false
|
||||||
* are the same directory — that is the only way an extra folder can mean
|
|
||||||
* something on both sides.
|
|
||||||
*/
|
|
||||||
const addSubpathTo = (workspaceId: WorkspaceId, relative: string): void => {
|
|
||||||
if (foldersBusy) return
|
|
||||||
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
|
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
|
||||||
if (workspace === undefined) return
|
if (workspace === undefined) return false
|
||||||
const path = joinSubpath(workspace.path, relative)
|
setFoldersBusy(true)
|
||||||
if (path === null) {
|
try {
|
||||||
notifyFolder(t('folder.subpathInvalid'))
|
if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))
|
||||||
return
|
const pending = createdFolderPendingSave.current
|
||||||
|
const created = pending?.workspaceId === workspaceId && pending.name === name
|
||||||
|
? pending
|
||||||
|
: await createWorkspaceDirectory(workspace.path, name, foldersRemoteBase, createDirectory)
|
||||||
|
createdFolderPendingSave.current = { workspaceId, name, path: created.path }
|
||||||
|
const entry = addFolder(entryFor(foldersDoc, workspaceId as string), created.path)
|
||||||
|
const next: FoldersDocument = { version: 1, workspaces: { ...foldersDoc.workspaces, [workspaceId]: entry } }
|
||||||
|
// Do not report success or clear the input until both operations succeed.
|
||||||
|
// A failed overlay save does NOT delete the newly created user directory.
|
||||||
|
await saveFolders(next)
|
||||||
|
setFoldersDoc(next)
|
||||||
|
createdFolderPendingSave.current = null
|
||||||
|
return true
|
||||||
|
} catch (reason) {
|
||||||
|
notifyFolder(`${t('folder.addError')}: ${reason instanceof Error ? reason.message : String(reason)}`)
|
||||||
|
return false
|
||||||
|
} finally {
|
||||||
|
setFoldersBusy(false)
|
||||||
}
|
}
|
||||||
const entry = entryFor(foldersDoc, workspaceId as string)
|
|
||||||
if (effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))) {
|
|
||||||
notifyFolder(t('folder.duplicate'))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeFolderEntry(workspaceId, addFolder(entry, path))
|
|
||||||
// Mirror subdirectory: also stamp the remote-ssh record, otherwise the new
|
|
||||||
// folder's sessions would lose the remote terminal (remote-ssh reads the
|
|
||||||
// record at the cwd only). Fire and forget — the folder row already works.
|
|
||||||
void ensureRemoteFolderMarker(workspace.path, path)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const setFolderRoot = (workspaceId: WorkspaceId, path: string): void => {
|
const setFolderRoot = (workspaceId: WorkspaceId, path: string): void => {
|
||||||
|
|
@ -695,7 +758,15 @@ export function GroupsBrowser({
|
||||||
}
|
}
|
||||||
if (creatingSessionIn !== null) return
|
if (creatingSessionIn !== null) return
|
||||||
setCreatingSessionIn(folderKey(workspaceId, path))
|
setCreatingSessionIn(folderKey(workspaceId, path))
|
||||||
createSessionIn(workspaceId, path).catch((reason: unknown) => {
|
void (async () => {
|
||||||
|
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
|
||||||
|
if (!workspace) throw new Error('Workspace not found')
|
||||||
|
if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))
|
||||||
|
const remote = await remoteFolderWorkspace(workspace.path, foldersRemoteBase)
|
||||||
|
const targetRemote = await remoteFolderWorkspace(path, foldersRemoteBase)
|
||||||
|
if (remote || targetRemote) throw new Error(t('folder.remoteSessionUnsupported'))
|
||||||
|
await createSessionIn(workspaceId, path)
|
||||||
|
})().catch((reason: unknown) => {
|
||||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||||
notifyFolder(`${t('folder.sessionError')}: ${detail}`)
|
notifyFolder(`${t('folder.sessionError')}: ${detail}`)
|
||||||
}).finally(() => {
|
}).finally(() => {
|
||||||
|
|
@ -1245,7 +1316,7 @@ export function GroupsBrowser({
|
||||||
className="wgIconButton"
|
className="wgIconButton"
|
||||||
aria-label={t('workspace.add')}
|
aria-label={t('workspace.add')}
|
||||||
disabled={adding}
|
disabled={adding}
|
||||||
onClick={addWorkspace}
|
onClick={() => { void addWorkspace() }}
|
||||||
>
|
>
|
||||||
<IconProjectAddOutlineRegular size={wide ? 16 : 18} />
|
<IconProjectAddOutlineRegular size={wide ? 16 : 18} />
|
||||||
</button>
|
</button>
|
||||||
|
|
@ -1338,6 +1409,8 @@ export function GroupsBrowser({
|
||||||
onSessionRename={onSessionRename}
|
onSessionRename={onSessionRename}
|
||||||
onSessionArchive={onSessionArchive}
|
onSessionArchive={onSessionArchive}
|
||||||
onFork={forkSession}
|
onFork={forkSession}
|
||||||
|
onAddWorkspace={() => { void addWorkspace(category.key) }}
|
||||||
|
addingWorkspace={adding || manualSaving}
|
||||||
onGroupRename={() => {
|
onGroupRename={() => {
|
||||||
setGroupDraft(category.key)
|
setGroupDraft(category.key)
|
||||||
setGroupError(null)
|
setGroupError(null)
|
||||||
|
|
@ -1578,7 +1651,7 @@ export function GroupsBrowser({
|
||||||
remote={isRemoteWorkspace(workspace)}
|
remote={isRemoteWorkspace(workspace)}
|
||||||
onClose={() => { setFoldersTarget(null) }}
|
onClose={() => { setFoldersTarget(null) }}
|
||||||
onAdd={() => { void addFolderTo(foldersTarget) }}
|
onAdd={() => { void addFolderTo(foldersTarget) }}
|
||||||
onAddSubpath={(relative) => { addSubpathTo(foldersTarget, relative) }}
|
onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)}
|
||||||
onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }}
|
onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }}
|
||||||
onRemove={(path) => { removeFolderFrom(foldersTarget, path) }}
|
onRemove={(path) => { removeFolderFrom(foldersTarget, path) }}
|
||||||
onOpenFolder={(path) => { openFolderPath?.(path) }}
|
onOpenFolder={(path) => { openFolderPath?.(path) }}
|
||||||
|
|
@ -1652,6 +1725,17 @@ export function GroupsBrowser({
|
||||||
</Modal>
|
</Modal>
|
||||||
|
|
||||||
{/* Add workspace error dialog */}
|
{/* Add workspace error dialog */}
|
||||||
|
{directoryFlowOpen && DirectoryFlow && (
|
||||||
|
<DirectoryFlow
|
||||||
|
{...directoryFlow?.injected}
|
||||||
|
open
|
||||||
|
busy={false}
|
||||||
|
onPicked={path => { finishDirectoryFlow(path) }}
|
||||||
|
onCancel={() => { finishDirectoryFlow(null) }}
|
||||||
|
onError={message => { finishDirectoryFlow(null, message) }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
<Modal
|
<Modal
|
||||||
open={addErrorOpen}
|
open={addErrorOpen}
|
||||||
onClose={() => { setAddErrorOpen(false) }}
|
onClose={() => { setAddErrorOpen(false) }}
|
||||||
|
|
@ -1660,7 +1744,7 @@ export function GroupsBrowser({
|
||||||
footer={(
|
footer={(
|
||||||
<>
|
<>
|
||||||
<Button variant="outline" onClick={() => { setAddErrorOpen(false) }}>{t('close')}</Button>
|
<Button variant="outline" onClick={() => { setAddErrorOpen(false) }}>{t('close')}</Button>
|
||||||
<Button variant="primary" onClick={addWorkspace}>{t('retry')}</Button>
|
<Button variant="primary" onClick={() => { void addWorkspace(addCategoryRef.current) }}>{t('retry')}</Button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
|
|
@ -1806,7 +1890,7 @@ function WorkspaceSubtree({ workspace, current, now, t, animate, onOpen, onSessi
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One category section: header row + expanded workspace folders. */
|
/** One category section: header row + expanded workspace folders. */
|
||||||
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }: {
|
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onAddWorkspace, addingWorkspace, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }: {
|
||||||
category: CategoryNode
|
category: CategoryNode
|
||||||
current: SessionId | undefined
|
current: SessionId | undefined
|
||||||
now: number
|
now: number
|
||||||
|
|
@ -1829,6 +1913,8 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
|
||||||
onSessionRename: (sessionId: SessionId, currentTitle: string) => void
|
onSessionRename: (sessionId: SessionId, currentTitle: string) => void
|
||||||
onSessionArchive: (sessionId: SessionId) => void
|
onSessionArchive: (sessionId: SessionId) => void
|
||||||
onFork: (sessionId: SessionId) => void
|
onFork: (sessionId: SessionId) => void
|
||||||
|
onAddWorkspace: () => void
|
||||||
|
addingWorkspace: boolean
|
||||||
onGroupRename: () => void
|
onGroupRename: () => void
|
||||||
onGroupDelete: () => void
|
onGroupDelete: () => void
|
||||||
/** Pin/unpin this group from its row menu. */
|
/** Pin/unpin this group from its row menu. */
|
||||||
|
|
@ -1859,6 +1945,8 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
|
||||||
node={category}
|
node={category}
|
||||||
t={t}
|
t={t}
|
||||||
onToggle={onToggleCategory}
|
onToggle={onToggleCategory}
|
||||||
|
onAddWorkspace={onAddWorkspace}
|
||||||
|
addingWorkspace={addingWorkspace}
|
||||||
onRename={onGroupRename}
|
onRename={onGroupRename}
|
||||||
onDelete={onGroupDelete}
|
onDelete={onGroupDelete}
|
||||||
onTogglePin={onGroupTogglePin}
|
onTogglePin={onGroupTogglePin}
|
||||||
|
|
@ -2195,7 +2283,7 @@ function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, onClose, on
|
||||||
remote: boolean
|
remote: boolean
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
onAdd: () => void
|
onAdd: () => void
|
||||||
onAddSubpath: (relative: string) => void
|
onAddSubpath: (relative: string) => Promise<boolean>
|
||||||
onSetRoot: (path: string) => void
|
onSetRoot: (path: string) => void
|
||||||
onRemove: (path: string) => void
|
onRemove: (path: string) => void
|
||||||
onOpenFolder: (path: string) => void
|
onOpenFolder: (path: string) => void
|
||||||
|
|
@ -2205,8 +2293,8 @@ function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, onClose, on
|
||||||
const [subpath, setSubpath] = useState('')
|
const [subpath, setSubpath] = useState('')
|
||||||
const submitSubpath = (): void => {
|
const submitSubpath = (): void => {
|
||||||
if (subpath.trim() === '') return
|
if (subpath.trim() === '') return
|
||||||
onAddSubpath(subpath)
|
if (busy) return
|
||||||
setSubpath('')
|
void onAddSubpath(subpath).then(success => { if (success) setSubpath('') })
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
|
|
@ -2263,9 +2351,7 @@ function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, onClose, on
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
<div className="wgFolderListFooter">
|
<div className="wgFolderListFooter">
|
||||||
{remote
|
<>
|
||||||
? (
|
|
||||||
<>
|
|
||||||
<p className="wgFolderHint">{t('folder.remoteHint')}</p>
|
<p className="wgFolderHint">{t('folder.remoteHint')}</p>
|
||||||
<div className="wgFolderSubpath">
|
<div className="wgFolderSubpath">
|
||||||
<input
|
<input
|
||||||
|
|
@ -2286,9 +2372,8 @@ function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, onClose, on
|
||||||
{t('folder.addSubpath')}
|
{t('folder.addSubpath')}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)
|
{!remote && <Button variant="outline" disabled={busy} onClick={onAdd}>{t('folder.add')}</Button>}
|
||||||
: <Button variant="outline" disabled={busy} onClick={onAdd}>{t('folder.add')}</Button>}
|
|
||||||
</div>
|
</div>
|
||||||
</Modal>
|
</Modal>
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,8 @@ import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore,
|
||||||
// slot this registrant shadows) and its runtime props. Erased from both the JS
|
// slot this registrant shadows) and its runtime props. Erased from both the JS
|
||||||
// bundle and the emitted .d.ts, so it must stay a bare `import type {}`.
|
// bundle and the emitted .d.ts, so it must stay a bare `import type {}`.
|
||||||
import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client';
|
import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client';
|
||||||
|
import type { ComponentType } from 'react';
|
||||||
|
import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client';
|
||||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||||
import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client';
|
import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||||
import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client';
|
import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client';
|
||||||
|
|
@ -69,6 +71,13 @@ export type GroupsBrowserInjected = {
|
||||||
}) => Promise<WorkspaceView>;
|
}) => Promise<WorkspaceView>;
|
||||||
/** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */
|
/** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */
|
||||||
pickDirectory: () => Promise<string | null>;
|
pickDirectory: () => Promise<string | null>;
|
||||||
|
/** Snapshot a self-contained standard picker without redeclaring its owned slot. */
|
||||||
|
getDirectoryFlow: () => {
|
||||||
|
component: ComponentType<DirectoryFlowOwnerProps>;
|
||||||
|
injected: Record<string, unknown>;
|
||||||
|
} | null;
|
||||||
|
/** DSH native local directory creation (SSH routing is owned by our adapter). */
|
||||||
|
createDirectory: (path: string, name: string) => Promise<string>;
|
||||||
/**
|
/**
|
||||||
* Surface the session-tab strip for a session that is in play (called with the
|
* Surface the session-tab strip for a session that is in play (called with the
|
||||||
* session the browser itself just opened, and again whenever its status
|
* session the browser itself just opened, and again whenever its status
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,16 @@
|
||||||
|
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'
|
||||||
|
import type { GroupsBrowserInjected } from './contract.ts'
|
||||||
|
|
||||||
|
/** Adapt the elected self-contained picker, without stealing its original slot. */
|
||||||
|
export function directoryFlowFromEntry(entry: StoredEntry | undefined): ReturnType<GroupsBrowserInjected['getDirectoryFlow']> {
|
||||||
|
if (!entry) return null
|
||||||
|
// Stateful/translated/nested seats need the full original renderer context.
|
||||||
|
// Never silently drop them or fall back to a local picker for a remote request.
|
||||||
|
if (entry.store || entry.locale || entry.children || typeof entry.component !== 'function') {
|
||||||
|
throw new Error('This directory picker requires an unsupported renderer context.')
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
component: entry.component as NonNullable<ReturnType<GroupsBrowserInjected['getDirectoryFlow']>>['component'],
|
||||||
|
injected: entry.inject?.() ?? {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,109 @@
|
||||||
|
/** One directory operation for local DSH and optional remote-ssh workspaces.
|
||||||
|
* Never send remote writes through the sidebar route: without its SSH interceptor
|
||||||
|
* that route can create a LOCAL directory instead. Use the SSH-owned API instead.
|
||||||
|
*/
|
||||||
|
import { isUnderBase, joinSubpath, samePath } from '../core/folders.ts'
|
||||||
|
|
||||||
|
export interface RemoteFolderWorkspace {
|
||||||
|
mirrorPath: string
|
||||||
|
remotePath: string
|
||||||
|
profileId: string
|
||||||
|
}
|
||||||
|
|
||||||
|
type JsonObject = Record<string, unknown>
|
||||||
|
function object(value: unknown): JsonObject | undefined {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||||
|
? value as JsonObject : undefined
|
||||||
|
}
|
||||||
|
function message(value: JsonObject | undefined): string {
|
||||||
|
const error = value?.error
|
||||||
|
return typeof error === 'string' ? error
|
||||||
|
: typeof object(error)?.message === 'string' ? String(object(error)?.message)
|
||||||
|
: typeof value?.stderr === 'string' && value.stderr !== '' ? value.stderr
|
||||||
|
: 'Remote SSH request failed'
|
||||||
|
}
|
||||||
|
|
||||||
|
async function rpc(method: string, body: JsonObject, fetchImpl: typeof fetch): Promise<JsonObject | null> {
|
||||||
|
const response = await fetchImpl(`/remote-ssh/api/${method}`, {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
|
||||||
|
body: JSON.stringify(body), cache: 'no-store', signal: AbortSignal.timeout(30000),
|
||||||
|
})
|
||||||
|
// Only catalog absence denotes an optional plugin not installed/running.
|
||||||
|
if (response.status === 404 && method === 'listWorkspaces') return null
|
||||||
|
if (!response.ok) throw new Error(`Remote SSH ${method}: HTTP ${response.status}`)
|
||||||
|
const envelope = object(await response.json())
|
||||||
|
const value = object(envelope?.value)
|
||||||
|
if (envelope?.ok !== true || value?.ok !== true) throw new Error(message(value ?? envelope))
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A marker is only a refusal hint, never authority to execute remote commands. */
|
||||||
|
async function refuseMarkedLocalPath(path: string, fetchImpl: typeof fetch): Promise<void> {
|
||||||
|
const response = await fetchImpl(`/workspace-groups/remote-hint?path=${encodeURIComponent(path)}`, {
|
||||||
|
cache: 'no-store', signal: AbortSignal.timeout(10000),
|
||||||
|
})
|
||||||
|
if (!response.ok) throw new Error(`Cannot verify local directory: HTTP ${response.status}`)
|
||||||
|
const body = object(await response.json())
|
||||||
|
if (typeof body?.remoteHint !== 'boolean') throw new Error('Invalid directory safety response')
|
||||||
|
if (body.remoteHint) throw new Error('SSH marker detected but no active registered remote workspace; refusing local operation')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */
|
||||||
|
export async function remoteFolderWorkspace(
|
||||||
|
path: string, remoteBase: string | null, fetchImpl: typeof fetch = fetch,
|
||||||
|
): Promise<RemoteFolderWorkspace | null> {
|
||||||
|
const value = await rpc('listWorkspaces', {}, fetchImpl)
|
||||||
|
const knownMirror = remoteBase !== null && isUnderBase(path, remoteBase)
|
||||||
|
if (value === null) {
|
||||||
|
if (knownMirror) throw new Error('SSH plugin is unavailable; refusing a local operation in a remote mirror')
|
||||||
|
await refuseMarkedLocalPath(path, fetchImpl)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
if (!Array.isArray(value.workspaces)) throw new Error('Invalid SSH workspace catalog')
|
||||||
|
const matches: RemoteFolderWorkspace[] = []
|
||||||
|
for (const raw of value.workspaces) {
|
||||||
|
const row = object(raw)
|
||||||
|
if (!row || typeof row.mirrorPath !== 'string' || typeof row.remotePath !== 'string'
|
||||||
|
|| typeof row.profileId !== 'string' || !row.mirrorPath || !row.remotePath || !row.profileId) {
|
||||||
|
throw new Error('Invalid SSH workspace entry')
|
||||||
|
}
|
||||||
|
if (samePath(path, row.mirrorPath) || isUnderBase(path, row.mirrorPath)) {
|
||||||
|
matches.push({ mirrorPath: row.mirrorPath, remotePath: row.remotePath, profileId: row.profileId })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (matches.length > 1) throw new Error('Overlapping SSH workspaces are not supported safely')
|
||||||
|
if (matches.length === 1) return matches[0]!
|
||||||
|
if (knownMirror) throw new Error('Remote mirror is not registered with the SSH plugin')
|
||||||
|
await refuseMarkedLocalPath(path, fetchImpl)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Single-segment names match DSH createDirectory(path, name). */
|
||||||
|
export function validateFolderName(raw: string): string {
|
||||||
|
const name = raw.trim()
|
||||||
|
if (!name || name === '.' || name === '..' || /[\\/\u0000-\u001f]/u.test(name)) {
|
||||||
|
throw new Error('Enter a single folder name, not an absolute path or nested path')
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createWorkspaceDirectory(
|
||||||
|
parent: string, rawName: string, remoteBase: string | null,
|
||||||
|
createLocal: (path: string, name: string) => Promise<string>, fetchImpl: typeof fetch = fetch,
|
||||||
|
): Promise<{ path: string; remote: boolean }> {
|
||||||
|
const name = validateFolderName(rawName)
|
||||||
|
const path = joinSubpath(parent, name)
|
||||||
|
if (path === null) throw new Error('Invalid folder name')
|
||||||
|
const remote = await remoteFolderWorkspace(parent, remoteBase, fetchImpl)
|
||||||
|
if (!remote) return { path: await createLocal(parent, name), remote: false }
|
||||||
|
// Names with shell expansions are rejected defensively for older SSH wrappers.
|
||||||
|
if (/[\u0000-\u001f`$"\\]/u.test(name)) throw new Error('Unsupported remote folder name')
|
||||||
|
const normalizedParent = parent.trim().replace(/\\/gu, '/').replace(/\/+$/u, '')
|
||||||
|
const normalizedRoot = remote.mirrorPath.trim().replace(/\\/gu, '/').replace(/\/+$/u, '')
|
||||||
|
const suffix = normalizedParent.slice(normalizedRoot.length).replace(/^\/+/, '')
|
||||||
|
if (suffix.split('/').some(part => part === '..' || part === '.')) throw new Error('Invalid mirror path')
|
||||||
|
const root = remote.remotePath.replace(/\/+$/u, '')
|
||||||
|
const remotePath = `${root}/${suffix ? `${suffix}/` : ''}${name}`
|
||||||
|
await rpc('mkdir', { profileId: remote.profileId, path: remotePath }, fetchImpl)
|
||||||
|
return { path, remote: true }
|
||||||
|
}
|
||||||
|
|
@ -111,38 +111,3 @@ export async function saveFolders(
|
||||||
})
|
})
|
||||||
if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`)
|
if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Ask the host to stamp the remote-ssh connection record into an extra folder of
|
|
||||||
* a MIRROR workspace.
|
|
||||||
*
|
|
||||||
* remote-ssh decides "remote backed" by reading `.remote-ssh.json` at the
|
|
||||||
* session cwd and never walks up, so a folder below the mirror root would
|
|
||||||
* otherwise get a local terminal. Best-effort: the folder itself is already
|
|
||||||
* persisted by the time this runs, and a local workspace answers `marked:false`
|
|
||||||
* (nothing to stamp) rather than failing.
|
|
||||||
* @param workspacePath - the workspace's canonical directory (mirror root).
|
|
||||||
* @param folderPath - the extra folder just added.
|
|
||||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
|
||||||
* @returns true when a record was written.
|
|
||||||
*/
|
|
||||||
export async function ensureRemoteFolderMarker(
|
|
||||||
workspacePath: string,
|
|
||||||
folderPath: string,
|
|
||||||
fetchImpl: typeof fetch = fetch,
|
|
||||||
): Promise<boolean> {
|
|
||||||
try {
|
|
||||||
const response = await fetchImpl(FOLDERS_ROUTE, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ workspacePath, folderPath }),
|
|
||||||
cache: 'no-store',
|
|
||||||
})
|
|
||||||
if (!response.ok) return false
|
|
||||||
const body: unknown = await response.json()
|
|
||||||
if (typeof body !== 'object' || body === null) return false
|
|
||||||
return (body as { marked?: unknown }).marked === true
|
|
||||||
} catch {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -58,6 +58,7 @@ import { loadTabs, saveTabs } from './tab-persist.ts'
|
||||||
import { createStoreHook } from './store-hook.ts'
|
import { createStoreHook } from './store-hook.ts'
|
||||||
import { shouldOpenTab, type TabOpenMode } from './tabs.ts'
|
import { shouldOpenTab, type TabOpenMode } from './tabs.ts'
|
||||||
import { GroupsBrowser } from './GroupsBrowser.tsx'
|
import { GroupsBrowser } from './GroupsBrowser.tsx'
|
||||||
|
import { directoryFlowFromEntry } from './directory-flow.ts'
|
||||||
import { en, zh, type WorkspaceGroupsKey } from './locales.ts'
|
import { en, zh, type WorkspaceGroupsKey } from './locales.ts'
|
||||||
|
|
||||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||||
|
|
@ -193,6 +194,10 @@ export function apply(ctx: Context): void {
|
||||||
// resolves).
|
// resolves).
|
||||||
},
|
},
|
||||||
pickDirectory: () => ctx.uiWorkspace.pickDirectory(),
|
pickDirectory: () => ctx.uiWorkspace.pickDirectory(),
|
||||||
|
// Our shadow entry cannot own/render the official browser's child slot.
|
||||||
|
// Reuse the elected self-contained picker and its actual injected services.
|
||||||
|
getDirectoryFlow: () => directoryFlowFromEntry(ctx.slots.entriesOfSlot('sidebar.workspaces.directoryFlow')[0]),
|
||||||
|
createDirectory: (path, name) => ctx.uiWorkspace.createDirectory(path, name),
|
||||||
searchSessions,
|
searchSessions,
|
||||||
searchResultLimit: ctx.sessions.searchResultLimit,
|
searchResultLimit: ctx.sessions.searchResultLimit,
|
||||||
// Directory-flow hole occupancy. The official ui-workspace browser gates
|
// Directory-flow hole occupancy. The official ui-workspace browser gates
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,8 @@ export type WorkspaceGroupsKey =
|
||||||
| 'folder.addError'
|
| 'folder.addError'
|
||||||
| 'folder.sessionError'
|
| 'folder.sessionError'
|
||||||
| 'folder.saveError'
|
| 'folder.saveError'
|
||||||
|
| 'folder.notReady'
|
||||||
|
| 'folder.remoteSessionUnsupported'
|
||||||
| 'folder.remoteHint'
|
| 'folder.remoteHint'
|
||||||
| 'folder.remoteNeedsSubpath'
|
| 'folder.remoteNeedsSubpath'
|
||||||
| 'folder.subpathLabel'
|
| 'folder.subpathLabel'
|
||||||
|
|
@ -181,11 +183,13 @@ export const zh: WorkspaceGroupsDict = {
|
||||||
'folder.addError': '添加文件夹失败',
|
'folder.addError': '添加文件夹失败',
|
||||||
'folder.sessionError': '新建会话失败',
|
'folder.sessionError': '新建会话失败',
|
||||||
'folder.saveError': '文件夹保存失败',
|
'folder.saveError': '文件夹保存失败',
|
||||||
'folder.remoteHint': '远程(SSH)工作区:本地目录是服务器根目录的镜像,所以这里只能添加镜像内的子目录,填相对路径即可(也会同步到服务器同名目录)',
|
'folder.notReady': '目录安全信息尚未加载,请重启 DSH 并刷新页面后重试',
|
||||||
|
'folder.remoteSessionUnsupported': '当前 SSH 插件不完整支持子目录会话,请从远程工作区根目录打开会话。不会退回本地终端。',
|
||||||
|
'folder.remoteHint': '输入一个文件夹名:本地使用 DSH 目录接口;远程使用 SSH 创建目录接口(远端同名目录已存在时复用)。SSH 不可用时不会在镜像里创建本地目录。',
|
||||||
'folder.remoteNeedsSubpath': '远程工作区请用子目录方式添加文件夹',
|
'folder.remoteNeedsSubpath': '远程工作区请用子目录方式添加文件夹',
|
||||||
'folder.subpathLabel': '相对路径',
|
'folder.subpathLabel': '文件夹名称',
|
||||||
'folder.subpathPlaceholder': '例如 data 或 src/generated',
|
'folder.subpathPlaceholder': '例如 data',
|
||||||
'folder.addSubpath': '添加子目录',
|
'folder.addSubpath': '创建文件夹',
|
||||||
'folder.subpathInvalid': '路径无效:请填工作区内的相对路径,不能用绝对路径或 ..',
|
'folder.subpathInvalid': '路径无效:请填工作区内的相对路径,不能用绝对路径或 ..',
|
||||||
'group.create': '新建分组',
|
'group.create': '新建分组',
|
||||||
'group.createTitle': '新建分组',
|
'group.createTitle': '新建分组',
|
||||||
|
|
@ -314,11 +318,13 @@ export const en: WorkspaceGroupsDict = {
|
||||||
'folder.addError': 'Could not add the folder',
|
'folder.addError': 'Could not add the folder',
|
||||||
'folder.sessionError': 'Could not start a session',
|
'folder.sessionError': 'Could not start a session',
|
||||||
'folder.saveError': 'Could not save folders',
|
'folder.saveError': 'Could not save folders',
|
||||||
'folder.remoteHint': 'Remote (SSH) workspace: the local directory mirrors the server root, so only subdirectories of that mirror can be added here — type a path relative to the workspace root',
|
'folder.notReady': 'Directory safety information is not loaded. Restart DSH and refresh the page before retrying.',
|
||||||
|
'folder.remoteSessionUnsupported': 'This SSH plugin does not fully support subdirectory sessions. Start from the remote workspace root instead; no local terminal fallback is allowed.',
|
||||||
|
'folder.remoteHint': 'Enter one folder name. Local workspaces use DSH; remote workspaces use SSH mkdir (existing remote directories are reused). Missing SSH never falls back to a local mirror write.',
|
||||||
'folder.remoteNeedsSubpath': 'Remote workspaces take a subdirectory, not a picked folder',
|
'folder.remoteNeedsSubpath': 'Remote workspaces take a subdirectory, not a picked folder',
|
||||||
'folder.subpathLabel': 'Relative path',
|
'folder.subpathLabel': 'Folder name',
|
||||||
'folder.subpathPlaceholder': 'e.g. data or src/generated',
|
'folder.subpathPlaceholder': 'e.g. data',
|
||||||
'folder.addSubpath': 'Add subdirectory',
|
'folder.addSubpath': 'Create folder',
|
||||||
'folder.subpathInvalid': 'Invalid path: use a relative path inside the workspace (no absolute paths, no ..)',
|
'folder.subpathInvalid': 'Invalid path: use a relative path inside the workspace (no absolute paths, no ..)',
|
||||||
'group.create': 'New group',
|
'group.create': 'New group',
|
||||||
'group.createTitle': 'New group',
|
'group.createTitle': 'New group',
|
||||||
|
|
|
||||||
|
|
@ -167,10 +167,13 @@ export function CategoryGlyph({ icon, fallback = null }: { icon: string | undefi
|
||||||
* groups via overlay renames/hides), draggable source for group reorder and
|
* groups via overlay renames/hides), draggable source for group reorder and
|
||||||
* drop target for both workspace moves and group reorders.
|
* drop target for both workspace moves and group reorders.
|
||||||
*/
|
*/
|
||||||
export function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {
|
export function CategoryRow({ node, t, onToggle, onAddWorkspace, addingWorkspace = false, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {
|
||||||
node: CategoryNode
|
node: CategoryNode
|
||||||
t: T
|
t: T
|
||||||
onToggle: () => void
|
onToggle: () => void
|
||||||
|
/** Create and assign a workspace directly to this category. */
|
||||||
|
onAddWorkspace?: () => void
|
||||||
|
addingWorkspace?: boolean
|
||||||
/** Rename/delete actions; the hover menu renders only when both provided. */
|
/** Rename/delete actions; the hover menu renders only when both provided. */
|
||||||
onRename?: () => void
|
onRename?: () => void
|
||||||
onDelete?: () => void
|
onDelete?: () => void
|
||||||
|
|
@ -237,6 +240,16 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin
|
||||||
<IconPinFillMedium />
|
<IconPinFillMedium />
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
|
{onAddWorkspace !== undefined && (
|
||||||
|
<span className="wgRowActions">
|
||||||
|
<button type="button" className="wgIconButton" draggable={false}
|
||||||
|
disabled={addingWorkspace}
|
||||||
|
title={t('workspace.add')} aria-label={`${t('workspace.add')} · ${node.label}`}
|
||||||
|
onClick={event => { event.stopPropagation(); onAddWorkspace() }}>
|
||||||
|
<IconPlusOutlineRegular />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
{manageable && (
|
{manageable && (
|
||||||
<span className="wgRowActions">
|
<span className="wgRowActions">
|
||||||
<Menu
|
<Menu
|
||||||
|
|
|
||||||
|
|
@ -12,8 +12,8 @@
|
||||||
* same reason the manual overlay does: a stale or malformed sidecar must never
|
* same reason the manual overlay does: a stale or malformed sidecar must never
|
||||||
* freeze the tree.
|
* freeze the tree.
|
||||||
*/
|
*/
|
||||||
import { mkdir, open, readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
import { lstat, mkdir, open, readFile, rename, unlink } from 'node:fs/promises'
|
||||||
import { dirname, relative, resolve, sep } from 'node:path'
|
import { dirname, resolve } from 'node:path'
|
||||||
import { homedir } from 'node:os'
|
import { homedir } from 'node:os'
|
||||||
import {
|
import {
|
||||||
EMPTY_FOLDERS_DOCUMENT,
|
EMPTY_FOLDERS_DOCUMENT,
|
||||||
|
|
@ -75,6 +75,36 @@ export function isAbsoluteFolderPath(path: string): boolean {
|
||||||
: POSIX_ABSOLUTE.test(path)
|
: POSIX_ABSOLUTE.test(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Validate a local path for the read-only remote hint endpoint. */
|
||||||
|
export function validateRemoteHintPath(path: unknown): string {
|
||||||
|
if (typeof path !== 'string' || path.length === 0 || path.length > FOLDER_PATH_LIMIT
|
||||||
|
|| path.includes('\u0000') || !isAbsoluteFolderPath(path)) {
|
||||||
|
throw new Error('remote hint path must be an absolute host path without NUL, at most 1024 characters')
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Presence-only safety hint, never a trusted SSH connection or registration.
|
||||||
|
* lstat also treats dangling symlinks as hints without reading their targets.
|
||||||
|
* Only ENOENT is ignored: permissions and all other inspection failures must
|
||||||
|
* prevent callers from silently falling back to local operations.
|
||||||
|
*/
|
||||||
|
export async function hasRemoteMarkerHint(path: string): Promise<boolean> {
|
||||||
|
let directory = resolve(validateRemoteHintPath(path))
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
await lstat(resolve(directory, '.remote-ssh.json'))
|
||||||
|
return true
|
||||||
|
} catch (error) {
|
||||||
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
|
||||||
|
}
|
||||||
|
const parent = dirname(directory)
|
||||||
|
if (parent === directory) return false
|
||||||
|
directory = parent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Reject helper carrying the stable file-scoped message prefix. */
|
/** Reject helper carrying the stable file-scoped message prefix. */
|
||||||
function invalid(detail: string): never {
|
function invalid(detail: string): never {
|
||||||
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`)
|
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`)
|
||||||
|
|
@ -256,71 +286,10 @@ export async function writeFoldersDocument(path: string, document: FoldersDocume
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// Do not copy remote-ssh records into subdirectories. Remote-ssh 2.4.40
|
||||||
// remote-ssh markers
|
// resolves model-tool context only at registered roots; child records do not
|
||||||
//
|
// register a workspace and can bypass the parent's writeBack guard.
|
||||||
// `@zhangfengshun/dsh-remote-ssh` decides "this directory belongs to a remote
|
// Existing records belong to the user / remote-ssh and are left untouched.
|
||||||
// workspace" by looking for a `.remote-ssh.json` connection record at the
|
|
||||||
// directory itself (the shell wrapper and several fs bridges read exactly one
|
|
||||||
// path, they do NOT walk up). Its mirror root carries one; a plain subdirectory
|
|
||||||
// of the mirror does not, so a session whose cwd is such a subdirectory falls
|
|
||||||
// back to a LOCAL terminal even though every file under it is remote-backed.
|
|
||||||
//
|
|
||||||
// Stamping the record into the subdirectory fixes that: the record holds the
|
|
||||||
// same connection with `remotePath` adjusted to the matching remote folder, and
|
|
||||||
// remote-ssh always excludes `.remote-ssh.json` from sync, so it never travels
|
|
||||||
// to the server.
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/** Connection record of the remote-ssh plugin at a mirror root. */
|
|
||||||
export const REMOTE_MARKER_FILE_NAME = '.remote-ssh.json'
|
|
||||||
|
|
||||||
/** The subset of that record this plugin needs to reproduce it. */
|
|
||||||
export interface RemoteMarker {
|
|
||||||
readonly profileId?: string
|
|
||||||
readonly host: string
|
|
||||||
readonly port: number
|
|
||||||
readonly user: string
|
|
||||||
readonly keyPath?: string
|
|
||||||
readonly proxyJump?: string
|
|
||||||
readonly remotePath: string
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Read the remote-ssh connection record of a directory.
|
|
||||||
* @param dir - directory that may hold the record (a mirror root, usually).
|
|
||||||
* @returns the record, or null when the directory is not remote-backed.
|
|
||||||
*/
|
|
||||||
export async function readRemoteMarker(dir: string): Promise<RemoteMarker | null> {
|
|
||||||
let text: string
|
|
||||||
try {
|
|
||||||
text = await readFile(resolve(dir, REMOTE_MARKER_FILE_NAME), 'utf8')
|
|
||||||
} catch {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
let parsed: unknown
|
|
||||||
try {
|
|
||||||
parsed = JSON.parse(text)
|
|
||||||
} catch {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null
|
|
||||||
const row = parsed as Record<string, unknown>
|
|
||||||
if (typeof row.host !== 'string' || row.host === '') return null
|
|
||||||
if (typeof row.user !== 'string' || row.user === '') return null
|
|
||||||
const port = typeof row.port === 'number' && Number.isInteger(row.port) && row.port > 0 ? row.port : 22
|
|
||||||
const remotePath = typeof row.remotePath === 'string' ? row.remotePath.trim() : ''
|
|
||||||
if (remotePath === '') return null
|
|
||||||
return {
|
|
||||||
...(typeof row.profileId === 'string' && row.profileId !== '' ? { profileId: row.profileId } : {}),
|
|
||||||
host: row.host,
|
|
||||||
port,
|
|
||||||
user: row.user,
|
|
||||||
...(typeof row.keyPath === 'string' ? { keyPath: row.keyPath } : {}),
|
|
||||||
...(typeof row.proxyJump === 'string' && row.proxyJump !== '' ? { proxyJump: row.proxyJump } : {}),
|
|
||||||
remotePath,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Join a remote path with a mirror-relative subpath.
|
* Join a remote path with a mirror-relative subpath.
|
||||||
|
|
@ -338,42 +307,3 @@ export function remoteSubpath(remotePath: string, relativePath: string): string
|
||||||
const base = remotePath === '~' ? '~' : remotePath.replace(/\/+$/u, '')
|
const base = remotePath === '~' ? '~' : remotePath.replace(/\/+$/u, '')
|
||||||
return base === '' ? rel : `${base}/${rel}`
|
return base === '' ? rel : `${base}/${rel}`
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Stamp the remote-ssh connection record into a subdirectory of a mirror, so
|
|
||||||
* that sessions started there keep a remote terminal (see the block comment).
|
|
||||||
*
|
|
||||||
* A workspace that is not remote-backed is left untouched: no record at the
|
|
||||||
* workspace root means the plugin has nothing to reproduce.
|
|
||||||
* @param workspacePath - the workspace's canonical directory (the mirror root).
|
|
||||||
* @param folderPath - subdirectory added as an extra folder.
|
|
||||||
* @returns `{ marked: false }` for a local workspace, otherwise the remote path
|
|
||||||
* written into the subdirectory record.
|
|
||||||
*/
|
|
||||||
export async function ensureRemoteMarker(
|
|
||||||
workspacePath: string,
|
|
||||||
folderPath: string,
|
|
||||||
): Promise<{ marked: boolean; remotePath?: string }> {
|
|
||||||
const base = resolve(workspacePath)
|
|
||||||
const folder = resolve(folderPath)
|
|
||||||
const rel = relative(base, folder)
|
|
||||||
if (rel === '' || rel.startsWith('..')) {
|
|
||||||
throw invalid('folder is not inside the workspace directory')
|
|
||||||
}
|
|
||||||
const marker = await readRemoteMarker(base)
|
|
||||||
if (marker === null) return { marked: false }
|
|
||||||
const remotePath = remoteSubpath(marker.remotePath, rel.split(sep).join('/'))
|
|
||||||
if (remotePath === null) throw invalid('remote subpath is unusable')
|
|
||||||
const record: RemoteMarker = {
|
|
||||||
...(marker.profileId === undefined ? {} : { profileId: marker.profileId }),
|
|
||||||
host: marker.host,
|
|
||||||
port: marker.port,
|
|
||||||
user: marker.user,
|
|
||||||
...(marker.keyPath === undefined ? {} : { keyPath: marker.keyPath }),
|
|
||||||
...(marker.proxyJump === undefined ? {} : { proxyJump: marker.proxyJump }),
|
|
||||||
remotePath,
|
|
||||||
}
|
|
||||||
await mkdir(folder, { recursive: true })
|
|
||||||
await writeFile(resolve(folder, REMOTE_MARKER_FILE_NAME), JSON.stringify(record, null, 2), 'utf8')
|
|
||||||
return { marked: true, remotePath }
|
|
||||||
}
|
|
||||||
|
|
|
||||||
81
src/index.ts
81
src/index.ts
|
|
@ -17,9 +17,11 @@
|
||||||
* - `PUT /workspace-groups/folders` — replace the folder overlay whole.
|
* - `PUT /workspace-groups/folders` — replace the folder overlay whole.
|
||||||
* Strictly validated (absolute paths, no duplicates, root membership) and
|
* Strictly validated (absolute paths, no duplicates, root membership) and
|
||||||
* written atomically; the saved document is echoed back.
|
* written atomically; the saved document is echoed back.
|
||||||
* - `POST /workspace-groups/folders` — stamp the remote-ssh connection record
|
* - `POST /workspace-groups/folders` — deprecated; returns 410 without reading
|
||||||
* into an extra folder of a mirror workspace, so sessions started there keep
|
* the payload or touching remote-ssh records.
|
||||||
* a remote terminal (see the mirror block comment in host-folders.ts).
|
*
|
||||||
|
* - `GET /workspace-groups/remote-hint?path=...` — presence-only marker hint
|
||||||
|
* at the requested absolute path or ancestors; never returns marker content.
|
||||||
*
|
*
|
||||||
* Core workspace.json / session storage is never touched.
|
* Core workspace.json / session storage is never touched.
|
||||||
*/
|
*/
|
||||||
|
|
@ -45,9 +47,10 @@ import {
|
||||||
import {
|
import {
|
||||||
defaultFoldersPath,
|
defaultFoldersPath,
|
||||||
defaultRemoteMirrorBase,
|
defaultRemoteMirrorBase,
|
||||||
ensureRemoteMarker,
|
hasRemoteMarkerHint,
|
||||||
readFoldersDocument,
|
readFoldersDocument,
|
||||||
validateFoldersDocument,
|
validateFoldersDocument,
|
||||||
|
validateRemoteHintPath,
|
||||||
writeFoldersDocument,
|
writeFoldersDocument,
|
||||||
} from './host-folders.ts'
|
} from './host-folders.ts'
|
||||||
|
|
||||||
|
|
@ -248,6 +251,39 @@ export function apply(ctx: GroupsContext): void {
|
||||||
},
|
},
|
||||||
}), '@dsh-xhl/workspace-groups: /workspace-groups/manual route')
|
}), '@dsh-xhl/workspace-groups: /workspace-groups/manual route')
|
||||||
|
|
||||||
|
ctx.effect(() => ctx.webServer.register({
|
||||||
|
kind: 'exact',
|
||||||
|
path: '/workspace-groups/remote-hint',
|
||||||
|
handler: async (req, res) => {
|
||||||
|
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||||
|
writeError(res, 405, 'method not allowed')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let path: string
|
||||||
|
try {
|
||||||
|
const url = new URL(req.url ?? '', 'http://localhost')
|
||||||
|
path = validateRemoteHintPath(url.searchParams.get('path'))
|
||||||
|
} catch {
|
||||||
|
writeError(res, 400, 'workspace-groups: invalid remote hint path')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
let remoteHint: boolean
|
||||||
|
try {
|
||||||
|
remoteHint = await hasRemoteMarkerHint(path)
|
||||||
|
} catch {
|
||||||
|
writeError(res, 500, 'workspace-groups: failed to inspect remote hint; local fallback is unsafe')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const body = JSON.stringify({ remoteHint })
|
||||||
|
res.writeHead(200, {
|
||||||
|
'Content-Type': 'application/json; charset=utf-8',
|
||||||
|
'Cache-Control': 'no-store',
|
||||||
|
'Content-Length': Buffer.byteLength(body),
|
||||||
|
})
|
||||||
|
res.end(req.method === 'HEAD' ? undefined : body)
|
||||||
|
},
|
||||||
|
}), '@dsh-xhl/workspace-groups: /workspace-groups/remote-hint route')
|
||||||
|
|
||||||
ctx.effect(() => ctx.webServer.register({
|
ctx.effect(() => ctx.webServer.register({
|
||||||
kind: 'exact',
|
kind: 'exact',
|
||||||
path: '/workspace-groups/folders',
|
path: '/workspace-groups/folders',
|
||||||
|
|
@ -268,40 +304,9 @@ export function apply(ctx: GroupsContext): void {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (req.method === 'POST') {
|
if (req.method === 'POST') {
|
||||||
// `{ workspacePath, folderPath }` → stamp the remote-ssh connection
|
// Child markers neither register model-tool context nor preserve the
|
||||||
// record into an extra folder of a MIRROR workspace. The client sends
|
// parent's writeBack guard. Never read, write or remove any marker.
|
||||||
// this right after adding such a folder: remote-ssh reads the record at
|
writeError(res, 410, 'workspace-groups: remote marker creation is deprecated; use the registered remote workspace root')
|
||||||
// the session cwd (it never walks up), so without it a session started
|
|
||||||
// in `<mirror>/sub` would silently get a local terminal.
|
|
||||||
let raw: unknown
|
|
||||||
try {
|
|
||||||
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES))
|
|
||||||
} catch (error) {
|
|
||||||
const status = error instanceof HttpError ? error.status : 400
|
|
||||||
writeError(res, status, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const payload = typeof raw === 'object' && raw !== null ? raw as Record<string, unknown> : {}
|
|
||||||
const workspacePath = typeof payload.workspacePath === 'string' ? payload.workspacePath.trim() : ''
|
|
||||||
const folderPath = typeof payload.folderPath === 'string' ? payload.folderPath.trim() : ''
|
|
||||||
if (workspacePath === '' || folderPath === '') {
|
|
||||||
writeError(res, 400, 'workspace-groups: workspacePath and folderPath are required')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
let result: { marked: boolean; remotePath?: string }
|
|
||||||
try {
|
|
||||||
result = await ensureRemoteMarker(workspacePath, folderPath)
|
|
||||||
} catch (error) {
|
|
||||||
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const marked = JSON.stringify(result)
|
|
||||||
res.writeHead(200, {
|
|
||||||
'Content-Type': 'application/json; charset=utf-8',
|
|
||||||
'Cache-Control': 'no-store',
|
|
||||||
'Content-Length': Buffer.byteLength(marked),
|
|
||||||
})
|
|
||||||
res.end(marked)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (req.method !== 'PUT') {
|
if (req.method !== 'PUT') {
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,12 @@
|
||||||
* write validation and tolerant read, including the atomic file round-trip.
|
* write validation and tolerant read, including the atomic file round-trip.
|
||||||
*/
|
*/
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
|
||||||
|
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||||
|
import { Readable } from 'node:stream'
|
||||||
|
import { apply } from '../src/index.ts'
|
||||||
|
import type { GroupsContext, GroupsWebRoute } from '../src/context-types.ts'
|
||||||
|
import * as hostFolders from '../src/host-folders.ts'
|
||||||
import { join } from 'node:path'
|
import { join } from 'node:path'
|
||||||
import { tmpdir } from 'node:os'
|
import { tmpdir } from 'node:os'
|
||||||
import {
|
import {
|
||||||
|
|
@ -29,6 +34,104 @@ import {
|
||||||
const BASE = 'C:\\work\\project'
|
const BASE = 'C:\\work\\project'
|
||||||
const EXTRA = 'C:\\work\\extra'
|
const EXTRA = 'C:\\work\\extra'
|
||||||
|
|
||||||
|
describe('deprecated remote marker route', () => {
|
||||||
|
it('exports no marker writer or connection record reader', () => {
|
||||||
|
expect(hostFolders).not.toHaveProperty('ensureRemoteMarker')
|
||||||
|
expect(hostFolders).not.toHaveProperty('readRemoteMarker')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('returns 410 without creating or changing markers, while GET/PUT still work', async () => {
|
||||||
|
const home = await mkdtemp(join(tmpdir(), 'wg-deprecated-marker-'))
|
||||||
|
const previousHome = process.env.DSH_HOME
|
||||||
|
process.env.DSH_HOME = home
|
||||||
|
try {
|
||||||
|
const routes: GroupsWebRoute[] = []
|
||||||
|
apply({
|
||||||
|
effect: (callback: () => unknown) => callback(),
|
||||||
|
webServer: { register: (route: GroupsWebRoute) => { routes.push(route); return () => {} } },
|
||||||
|
} as unknown as GroupsContext)
|
||||||
|
const route = routes.find(item => item.path === '/workspace-groups/folders')!
|
||||||
|
expect(route).toBeDefined()
|
||||||
|
const request = async (method: string, body?: string) => {
|
||||||
|
const req = Readable.from(body === undefined ? [] : [body]) as IncomingMessage
|
||||||
|
req.method = method
|
||||||
|
let status = 0
|
||||||
|
let text: string | undefined
|
||||||
|
await route.handler(req, {
|
||||||
|
writeHead: (code: number) => { status = code },
|
||||||
|
end: (value?: string) => { text = value },
|
||||||
|
} as unknown as ServerResponse)
|
||||||
|
return { status, text }
|
||||||
|
}
|
||||||
|
const mirror = join(home, 'mirror')
|
||||||
|
const existing = join(mirror, 'existing')
|
||||||
|
await mkdir(existing, { recursive: true })
|
||||||
|
const rootMarker = '{"host":"example.invalid","user":"test","port":22,"remotePath":"/srv/test","writeBack":false}'
|
||||||
|
const childMarker = '{"keep":"existing user marker"}\n'
|
||||||
|
await writeFile(join(mirror, '.remote-ssh.json'), rootMarker, 'utf8')
|
||||||
|
await writeFile(join(existing, '.remote-ssh.json'), childMarker, 'utf8')
|
||||||
|
for (const body of [
|
||||||
|
JSON.stringify({ workspacePath: mirror, folderPath: join(mirror, 'new', 'nested') }),
|
||||||
|
JSON.stringify({ workspacePath: mirror, folderPath: existing }),
|
||||||
|
'{invalid json',
|
||||||
|
undefined,
|
||||||
|
]) {
|
||||||
|
const response = await request('POST', body)
|
||||||
|
expect(response.status).toBe(410)
|
||||||
|
expect(response.text).toContain('deprecated')
|
||||||
|
}
|
||||||
|
expect(await readdir(mirror)).toEqual(['.remote-ssh.json', 'existing'])
|
||||||
|
expect(await readFile(join(mirror, '.remote-ssh.json'), 'utf8')).toBe(rootMarker)
|
||||||
|
expect(await readFile(join(existing, '.remote-ssh.json'), 'utf8')).toBe(childMarker)
|
||||||
|
expect(await readdir(home)).toEqual(['mirror'])
|
||||||
|
const document = { version: 1, workspaces: { test: { folders: [existing] } } }
|
||||||
|
expect((await request('PUT', JSON.stringify(document))).status).toBe(200)
|
||||||
|
const response = await request('GET')
|
||||||
|
expect(response.status).toBe(200)
|
||||||
|
expect(JSON.parse(response.text!)).toEqual({ ...document, remoteBase: hostFolders.defaultRemoteMirrorBase() })
|
||||||
|
|
||||||
|
const hintRoute = routes.find(item => item.path === '/workspace-groups/remote-hint')!
|
||||||
|
expect(hintRoute).toBeDefined()
|
||||||
|
const hintRequest = async (method: string, path?: string) => {
|
||||||
|
let status = 0
|
||||||
|
let text: string | undefined
|
||||||
|
await hintRoute.handler({
|
||||||
|
method,
|
||||||
|
url: '/workspace-groups/remote-hint' + (path === undefined ? '' : '?path=' + encodeURIComponent(path)),
|
||||||
|
} as IncomingMessage, {
|
||||||
|
writeHead: (code: number) => { status = code },
|
||||||
|
end: (value?: string) => { text = value },
|
||||||
|
} as unknown as ServerResponse)
|
||||||
|
return { status, text }
|
||||||
|
}
|
||||||
|
expect(await hintRequest('GET', join(mirror, 'not-created', 'nested'))).toEqual({ status: 200, text: '{"remoteHint":true}' })
|
||||||
|
expect(await hintRequest('GET', existing)).toEqual({ status: 200, text: '{"remoteHint":true}' })
|
||||||
|
expect(await hintRequest('GET', home)).toEqual({ status: 200, text: '{"remoteHint":false}' })
|
||||||
|
expect(await hintRequest('HEAD', existing)).toEqual({ status: 200, text: undefined })
|
||||||
|
expect((await hintRequest('POST', existing)).status).toBe(405)
|
||||||
|
for (const path of [undefined, '', 'relative', home + '\u0000', home + 'x'.repeat(1025)]) {
|
||||||
|
expect((await hintRequest('GET', path)).status).toBe(400)
|
||||||
|
}
|
||||||
|
expect(await readFile(join(mirror, '.remote-ssh.json'), 'utf8')).toBe(rootMarker)
|
||||||
|
expect(await readFile(join(existing, '.remote-ssh.json'), 'utf8')).toBe(childMarker)
|
||||||
|
} finally {
|
||||||
|
if (previousHome === undefined) delete process.env.DSH_HOME
|
||||||
|
else process.env.DSH_HOME = previousHome
|
||||||
|
await rm(home, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('remoteSubpath (pure path logic)', () => {
|
||||||
|
it('joins remote roots with POSIX separators and rejects traversal', () => {
|
||||||
|
expect(hostFolders.remoteSubpath('~', 'data')).toBe('~/data')
|
||||||
|
expect(hostFolders.remoteSubpath('/srv/project/', 'a\\b')).toBe('/srv/project/a/b')
|
||||||
|
expect(hostFolders.remoteSubpath('/srv/project', '../escape')).toBeNull()
|
||||||
|
expect(hostFolders.remoteSubpath('/srv/project', 'a/../b')).toBeNull()
|
||||||
|
expect(hostFolders.remoteSubpath('/srv/project', ' ')).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
describe('samePath', () => {
|
describe('samePath', () => {
|
||||||
it('is case-insensitive for Windows-style paths', () => {
|
it('is case-insensitive for Windows-style paths', () => {
|
||||||
expect(samePath('C:\\Work\\Project', 'c:\\work\\project')).toBe(true)
|
expect(samePath('C:\\Work\\Project', 'c:\\work\\project')).toBe(true)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,17 @@
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { directoryFlowFromEntry } from '../src/client/directory-flow.ts'
|
||||||
|
assert.equal(directoryFlowFromEntry(undefined), null)
|
||||||
|
const component = () => null
|
||||||
|
const workspaces = { create() {} }
|
||||||
|
let called = 0
|
||||||
|
const entry = { component, options: {}, inject: () => { called++; return { workspaces } } }
|
||||||
|
const flow = directoryFlowFromEntry(entry)
|
||||||
|
assert.equal(flow.component, component)
|
||||||
|
assert.equal(flow.injected.workspaces, workspaces)
|
||||||
|
assert.equal(called, 1)
|
||||||
|
assert.deepEqual(directoryFlowFromEntry({ component, options: {} }).injected, {})
|
||||||
|
for (const extra of [{ locale: 'picker' }, { store: {} }, { children: {} }, { component: null }]) {
|
||||||
|
assert.throws(() => directoryFlowFromEntry({ ...entry, ...extra }), /unsupported renderer context/)
|
||||||
|
}
|
||||||
|
assert.throws(() => directoryFlowFromEntry({ ...entry, inject: () => { throw new Error('service unavailable') } }), /service unavailable/)
|
||||||
|
console.log('directory flow adapter: all assertions passed')
|
||||||
|
|
@ -0,0 +1,78 @@
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { createWorkspaceDirectory, remoteFolderWorkspace, validateFolderName } from '../src/client/folder-directory.ts'
|
||||||
|
|
||||||
|
const mirror = 'C:\\Users\\test\\.dsh\\remote-workspaces\\one'
|
||||||
|
const base = 'C:\\Users\\test\\.dsh\\remote-workspaces'
|
||||||
|
const ws = { mirrorPath: mirror, profileId: 'test-profile', remotePath: '~/project' }
|
||||||
|
const response = value => new Response(JSON.stringify({ ok: true, value }), { status: 200 })
|
||||||
|
const catalog = workspaces => response({ ok: true, workspaces })
|
||||||
|
let localCalls = 0
|
||||||
|
const local = async (path, name) => { localCalls++; return `${path}/${name}` }
|
||||||
|
const hint = remoteHint => new Response(JSON.stringify({ remoteHint }))
|
||||||
|
const missing = async url => url.startsWith('/workspace-groups/remote-hint?') ? hint(false) : new Response('', { status: 404 })
|
||||||
|
assert.deepEqual(await createWorkspaceDirectory('/tmp/project', 'data', base, local, missing), { path: '/tmp/project/data', remote: false })
|
||||||
|
assert.equal(localCalls, 1)
|
||||||
|
await assert.rejects(createWorkspaceDirectory(mirror, 'data', base, local, missing), /unavailable/)
|
||||||
|
assert.equal(localCalls, 1)
|
||||||
|
|
||||||
|
const calls = []
|
||||||
|
const ssh = async (url, init) => {
|
||||||
|
calls.push({ url, body: JSON.parse(init.body), headers: init.headers })
|
||||||
|
return url.endsWith('listWorkspaces') ? catalog([ws]) : response({ ok: true, exitCode: 0 })
|
||||||
|
}
|
||||||
|
const created = await createWorkspaceDirectory(mirror, '数据', base, local, ssh)
|
||||||
|
assert.equal(created.remote, true)
|
||||||
|
assert.equal(created.path, `${mirror}\\数据`)
|
||||||
|
assert.deepEqual(calls[1].body, { profileId: 'test-profile', path: '~/project/数据' })
|
||||||
|
assert.equal(calls[1].url, '/remote-ssh/api/mkdir')
|
||||||
|
assert.equal(calls[1].headers['X-Requested-With'], 'XMLHttpRequest')
|
||||||
|
assert.equal(localCalls, 1)
|
||||||
|
calls.length = 0
|
||||||
|
await createWorkspaceDirectory(`${mirror}\\src`, 'data', base, local, ssh)
|
||||||
|
assert.equal(calls[1].body.path, '~/project/src/data')
|
||||||
|
calls.length = 0
|
||||||
|
await createWorkspaceDirectory(mirror.toUpperCase().replaceAll('\\', '/') + '/src', 'space name', base, local, ssh)
|
||||||
|
assert.equal(calls[1].body.path, '~/project/src/space name')
|
||||||
|
let rootRequest
|
||||||
|
await createWorkspaceDirectory(mirror, 'data', base, local, async (url, init) => {
|
||||||
|
if (url.endsWith('listWorkspaces')) return catalog([{ ...ws, remotePath: '/' }])
|
||||||
|
rootRequest = JSON.parse(init.body)
|
||||||
|
return response({ ok: true })
|
||||||
|
})
|
||||||
|
assert.equal(rootRequest.path, '/data')
|
||||||
|
// Non-default mirror location is recognized from the registered catalog.
|
||||||
|
assert.ok(await remoteFolderWorkspace('D:/custom', base, async () => catalog([{ ...ws, mirrorPath: 'D:\\custom' }])))
|
||||||
|
assert.equal(await remoteFolderWorkspace(`${mirror}-other`, null, async url => url.startsWith('/workspace-groups/remote-hint?') ? hint(false) : catalog([ws])), null)
|
||||||
|
// Custom mirrors and even the initial null mirror-base state are guarded by a read-only marker hint.
|
||||||
|
for (const remoteBase of [null, base]) {
|
||||||
|
await assert.rejects(createWorkspaceDirectory('D:/custom', 'data', remoteBase, local,
|
||||||
|
async url => url.startsWith('/workspace-groups/remote-hint?') ? hint(true) : new Response('', { status: 404 })), /marker detected/)
|
||||||
|
}
|
||||||
|
await assert.rejects(createWorkspaceDirectory('/tmp/project', 'data', base, local,
|
||||||
|
async url => url.startsWith('/workspace-groups/remote-hint?') ? new Response('', { status: 500 }) : new Response('', { status: 404 })), /Cannot verify/)
|
||||||
|
await assert.rejects(createWorkspaceDirectory('/tmp/project', 'data', base, local,
|
||||||
|
async url => url.startsWith('/workspace-groups/remote-hint?') ? new Response('{}') : catalog([])), /Invalid directory/)
|
||||||
|
await assert.rejects(remoteFolderWorkspace(mirror, base, async () => new Response(JSON.stringify({ ok: false, error: { message: 'denied' } }))), /denied/)
|
||||||
|
await assert.rejects(remoteFolderWorkspace(mirror, base, async () => catalog([])), /not registered/)
|
||||||
|
await assert.rejects(remoteFolderWorkspace(`${mirror}\\src`, base, async () => catalog([ws, { ...ws, mirrorPath: `${mirror}\\src` }])), /Overlapping/)
|
||||||
|
for (const value of [{ ok: true }, { ok: true, workspaces: [null] }, { ok: false, error: 'denied' }]) {
|
||||||
|
await assert.rejects(remoteFolderWorkspace('/tmp/project', base, async () => response(value)))
|
||||||
|
}
|
||||||
|
for (const status of [403, 500]) {
|
||||||
|
await assert.rejects(createWorkspaceDirectory('/tmp/project', 'data', base, local, async () => new Response('', { status })))
|
||||||
|
}
|
||||||
|
await assert.rejects(createWorkspaceDirectory('/tmp/project', 'data', base, local, async () => { throw new Error('network') }), /network/)
|
||||||
|
await assert.rejects(createWorkspaceDirectory('/tmp/project', 'data', base, local, async () => new Response('not json')))
|
||||||
|
for (const status of [404, 403, 500]) {
|
||||||
|
await assert.rejects(createWorkspaceDirectory(mirror, 'data', base, local, async url => url.endsWith('listWorkspaces') ? catalog([ws]) : new Response('', { status })))
|
||||||
|
}
|
||||||
|
await assert.rejects(createWorkspaceDirectory(mirror, 'data', base, local, async url => url.endsWith('listWorkspaces') ? catalog([ws]) : response({ ok: false, stderr: 'permission denied' })), /permission denied/)
|
||||||
|
assert.equal(localCalls, 1, 'Failures must never fall back to local mkdir')
|
||||||
|
for (const name of ['', '.', '..', '/absolute', 'C:\\drive', 'nested/path', 'nested\\path', '\u0000']) {
|
||||||
|
assert.throws(() => validateFolderName(name))
|
||||||
|
}
|
||||||
|
for (const name of ['$(whoami)', '`date`', 'a"b']) {
|
||||||
|
await assert.rejects(createWorkspaceDirectory(mirror, name, base, local, ssh))
|
||||||
|
}
|
||||||
|
assert.equal(validateFolderName(' 中文 '), '中文')
|
||||||
|
console.log('folder-directory: all assertions passed (mocked APIs, no SSH connection)')
|
||||||
|
|
@ -2,15 +2,19 @@
|
||||||
* Standalone verifier for the per-workspace folder layer.
|
* Standalone verifier for the per-workspace folder layer.
|
||||||
*
|
*
|
||||||
* vitest cannot spawn in this sandbox (EPERM), so this script runs the same
|
* vitest cannot spawn in this sandbox (EPERM), so this script runs the same
|
||||||
* critical assertions under plain Node 24 type-stripping:
|
* critical assertions under Node 24 with TypeScript transformation:
|
||||||
* node tools/verify-folders.mjs
|
* node --experimental-transform-types tools/verify-folders.mjs
|
||||||
*
|
*
|
||||||
* It imports the pure module (`src/core/folders.ts`) and the host overlay
|
* It exercises the pure root/cwd rules, the host overlay's strict-write /
|
||||||
* (`src/host-folders.ts`, Node built-ins only), exercises the root/cwd rules and
|
* tolerant-read boundary, and the registered folder route in a fake context.
|
||||||
* the strict-write / tolerant-read boundary, then prints exactly one line.
|
* All filesystem fixtures use temporary directories, never real profiles.
|
||||||
*/
|
*/
|
||||||
import assert from 'node:assert/strict'
|
import assert from 'node:assert/strict'
|
||||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
|
||||||
|
import fsPromises from 'node:fs/promises'
|
||||||
|
import { syncBuiltinESMExports } from 'node:module'
|
||||||
|
import { Readable } from 'node:stream'
|
||||||
|
import { apply } from '../src/index.ts'
|
||||||
import { join } from 'node:path'
|
import { join } from 'node:path'
|
||||||
import { tmpdir } from 'node:os'
|
import { tmpdir } from 'node:os'
|
||||||
|
|
||||||
|
|
@ -29,15 +33,15 @@ const {
|
||||||
samePath,
|
samePath,
|
||||||
setRoot,
|
setRoot,
|
||||||
} = await import(coreUrl.href)
|
} = await import(coreUrl.href)
|
||||||
|
const host = await import(hostUrl.href)
|
||||||
const {
|
const {
|
||||||
ensureRemoteMarker,
|
defaultRemoteMirrorBase,
|
||||||
parseFoldersDocument,
|
parseFoldersDocument,
|
||||||
readFoldersDocument,
|
readFoldersDocument,
|
||||||
readRemoteMarker,
|
|
||||||
remoteSubpath,
|
remoteSubpath,
|
||||||
validateFoldersDocument,
|
validateFoldersDocument,
|
||||||
writeFoldersDocument,
|
writeFoldersDocument,
|
||||||
} = await import(hostUrl.href)
|
} = host
|
||||||
|
|
||||||
const BASE = 'C:\\work\\project'
|
const BASE = 'C:\\work\\project'
|
||||||
const EXTRA = 'C:\\work\\extra'
|
const EXTRA = 'C:\\work\\extra'
|
||||||
|
|
@ -175,10 +179,7 @@ equal(joinSubpath(MIRROR_WS, './ok'), `${MIRROR_WS}\\ok`, 'a leading dot segment
|
||||||
equal(folderOfCwd(`${MIRROR_WS}\\data\\file`, MIRROR_WS, entry), `${MIRROR_WS}\\data`, 'sessions under the mirror subpath belong to it')
|
equal(folderOfCwd(`${MIRROR_WS}\\data\\file`, MIRROR_WS, entry), `${MIRROR_WS}\\data`, 'sessions under the mirror subpath belong to it')
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- remote-ssh markers ------------------------------------------------------
|
// --- pure remote path logic (no marker I/O) ----------------------------------
|
||||||
// remote-ssh reads `.remote-ssh.json` at the session cwd only (never walking
|
|
||||||
// up), so an extra folder inside a mirror needs its own record or its sessions
|
|
||||||
// silently lose the remote terminal.
|
|
||||||
equal(remoteSubpath('~/projects/cloud-memory', 'data'), '~/projects/cloud-memory/data', 'a ~ root joins with a slash')
|
equal(remoteSubpath('~/projects/cloud-memory', 'data'), '~/projects/cloud-memory/data', 'a ~ root joins with a slash')
|
||||||
equal(remoteSubpath('~', 'data'), '~/data', 'a bare ~ keeps its home meaning')
|
equal(remoteSubpath('~', 'data'), '~/data', 'a bare ~ keeps its home meaning')
|
||||||
equal(remoteSubpath('/srv/proj/', 'a/b'), '/srv/proj/a/b', 'an absolute remote root joins with a POSIX slash')
|
equal(remoteSubpath('/srv/proj/', 'a/b'), '/srv/proj/a/b', 'an absolute remote root joins with a POSIX slash')
|
||||||
|
|
@ -187,45 +188,100 @@ equal(remoteSubpath('/srv/proj', '..'), null, 'a parent traversal never reaches
|
||||||
equal(remoteSubpath('/srv/proj', 'a/../b'), null, 'an embedded traversal never reaches the remote shell')
|
equal(remoteSubpath('/srv/proj', 'a/../b'), null, 'an embedded traversal never reaches the remote shell')
|
||||||
equal(remoteSubpath('/srv/proj', ' '), null, 'a blank subpath is refused')
|
equal(remoteSubpath('/srv/proj', ' '), null, 'a blank subpath is refused')
|
||||||
|
|
||||||
|
// --- deprecated route: isolated fake context, no server or real profile -------
|
||||||
|
check(!('ensureRemoteMarker' in host), 'no exported marker writer remains')
|
||||||
|
check(!('readRemoteMarker' in host), 'no remote connection record reader remains')
|
||||||
{
|
{
|
||||||
const mirror = await mkdtemp(join(tmpdir(), 'wg-mirror-verify-'))
|
const home = await mkdtemp(join(tmpdir(), 'wg-deprecated-marker-'))
|
||||||
|
const previousHome = process.env.DSH_HOME
|
||||||
|
process.env.DSH_HOME = home
|
||||||
try {
|
try {
|
||||||
equal(await readRemoteMarker(mirror), null, 'a directory without a record is not remote-backed')
|
const routes = []
|
||||||
const local = await mkdtemp(join(tmpdir(), 'wg-local-verify-'))
|
apply({
|
||||||
try {
|
effect: callback => callback(),
|
||||||
equal(
|
webServer: { register: route => { routes.push(route); return () => {} } },
|
||||||
await ensureRemoteMarker(local, join(local, 'sub')),
|
})
|
||||||
{ marked: false },
|
const route = routes.find(item => item.path === '/workspace-groups/folders')
|
||||||
'a local workspace is left untouched',
|
check(route !== undefined, 'folders route remains registered')
|
||||||
)
|
const request = async (method, body) => {
|
||||||
const marker = {
|
const req = Readable.from(body === undefined ? [] : [body])
|
||||||
profileId: 'p-1', host: 'qyhhh.top', port: 22, user: 'ubuntu',
|
req.method = method
|
||||||
keyPath: 'C:\\Users\\me\\.ssh\\id_ed25519', remotePath: '~/projects/cloud-memory',
|
let status
|
||||||
}
|
let text
|
||||||
await writeFile(join(mirror, '.remote-ssh.json'), JSON.stringify(marker, null, 2), 'utf8')
|
await route.handler(req, {
|
||||||
equal(await readRemoteMarker(mirror), marker, 'the record round-trips')
|
writeHead: code => { status = code },
|
||||||
|
end: value => { text = value },
|
||||||
|
})
|
||||||
|
return { status, text }
|
||||||
|
}
|
||||||
|
const mirror = join(home, 'mirror')
|
||||||
|
const existing = join(mirror, 'existing')
|
||||||
|
await mkdir(existing, { recursive: true })
|
||||||
|
const rootMarker = '{"host":"example.invalid","user":"test","port":22,"remotePath":"/srv/test","writeBack":false}'
|
||||||
|
const childMarker = '{"keep":"existing user marker"}\n'
|
||||||
|
await writeFile(join(mirror, '.remote-ssh.json'), rootMarker, 'utf8')
|
||||||
|
await writeFile(join(existing, '.remote-ssh.json'), childMarker, 'utf8')
|
||||||
|
for (const body of [
|
||||||
|
JSON.stringify({ workspacePath: mirror, folderPath: join(mirror, 'new', 'nested') }),
|
||||||
|
JSON.stringify({ workspacePath: mirror, folderPath: existing }),
|
||||||
|
'{invalid json',
|
||||||
|
undefined,
|
||||||
|
]) {
|
||||||
|
const response = await request('POST', body)
|
||||||
|
equal(response.status, 410, 'legacy POST is unconditionally gone')
|
||||||
|
check(response.text.includes('deprecated'), 'legacy POST explains deprecation')
|
||||||
|
}
|
||||||
|
equal(await readdir(mirror), ['.remote-ssh.json', 'existing'], 'POST creates no child directories or markers')
|
||||||
|
equal(await readFile(join(mirror, '.remote-ssh.json'), 'utf8'), rootMarker, 'root marker and writeBack guard stay unchanged')
|
||||||
|
equal(await readFile(join(existing, '.remote-ssh.json'), 'utf8'), childMarker, 'existing child marker is neither overwritten nor deleted')
|
||||||
|
equal(await readdir(home), ['mirror'], 'POST writes no overlay either')
|
||||||
|
const document = { version: 1, workspaces: { test: { folders: [existing] } } }
|
||||||
|
equal((await request('PUT', JSON.stringify(document))).status, 200, 'normal folder PUT remains available')
|
||||||
|
const response = await request('GET')
|
||||||
|
equal(response.status, 200, 'normal folder GET remains available')
|
||||||
|
equal(JSON.parse(response.text), { ...document, remoteBase: defaultRemoteMirrorBase() }, 'GET preserves saved folders and remote mirror base')
|
||||||
|
|
||||||
const sub = join(mirror, 'data', 'raw')
|
const hintRoute = routes.find(item => item.path === '/workspace-groups/remote-hint')
|
||||||
equal(
|
check(hintRoute !== undefined, 'remote hint route is registered')
|
||||||
await ensureRemoteMarker(mirror, sub),
|
const hintRequest = async (method, path) => {
|
||||||
{ marked: true, remotePath: '~/projects/cloud-memory/data/raw' },
|
let status
|
||||||
'a nested extra folder gets the remote counterpart of its own path',
|
let text
|
||||||
)
|
await hintRoute.handler({
|
||||||
equal(
|
method,
|
||||||
await readRemoteMarker(sub),
|
url: '/workspace-groups/remote-hint' + (path === undefined ? '' : '?path=' + encodeURIComponent(path)),
|
||||||
{ ...marker, remotePath: '~/projects/cloud-memory/data/raw' },
|
}, {
|
||||||
'the stamped record keeps the connection and only rewrites remotePath',
|
writeHead: code => { status = code },
|
||||||
)
|
end: value => { text = value },
|
||||||
await assert.rejects(
|
})
|
||||||
() => ensureRemoteMarker(mirror, join(mirror, '..', 'outside')),
|
return { status, text }
|
||||||
/folder is not inside the workspace directory/u,
|
}
|
||||||
'a folder outside the mirror is refused, never stamped',
|
equal(await hintRequest('GET', join(mirror, 'not-created', 'nested')), { status: 200, text: '{"remoteHint":true}' }, 'ancestor marker detects a non-default mirror even for missing descendants')
|
||||||
)
|
equal(await hintRequest('GET', existing), { status: 200, text: '{"remoteHint":true}' }, 'marker content need not parse as connection data')
|
||||||
|
equal(await hintRequest('GET', home), { status: 200, text: '{"remoteHint":false}' }, 'no marker reports false')
|
||||||
|
equal(await hintRequest('HEAD', existing), { status: 200, text: undefined }, 'HEAD has no response body')
|
||||||
|
equal((await hintRequest('POST', existing)).status, 405, 'hint endpoint is read-only')
|
||||||
|
for (const path of [undefined, '', 'relative', home + '\u0000', home + 'x'.repeat(1025)]) {
|
||||||
|
equal((await hintRequest('GET', path)).status, 400, 'invalid hint paths are rejected')
|
||||||
|
}
|
||||||
|
equal(await readFile(join(mirror, '.remote-ssh.json'), 'utf8'), rootMarker, 'hint leaves root marker unchanged')
|
||||||
|
equal(await readFile(join(existing, '.remote-ssh.json'), 'utf8'), childMarker, 'hint never rewrites malformed marker content')
|
||||||
|
const originalLstat = fsPromises.lstat
|
||||||
|
try {
|
||||||
|
for (const code of ['EACCES', 'EIO', 'ENOTDIR']) {
|
||||||
|
fsPromises.lstat = async () => { throw Object.assign(new Error('private path must not leak'), { code }) }
|
||||||
|
syncBuiltinESMExports()
|
||||||
|
const failed = await hintRequest('GET', existing)
|
||||||
|
equal(failed.status, 500, 'inspection errors fail closed, never return false')
|
||||||
|
check(!failed.text.includes('private path'), 'inspection errors do not expose marker details')
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
await rm(local, { recursive: true, force: true })
|
fsPromises.lstat = originalLstat
|
||||||
|
syncBuiltinESMExports()
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
await rm(mirror, { recursive: true, force: true })
|
if (previousHome === undefined) delete process.env.DSH_HOME
|
||||||
|
else process.env.DSH_HOME = previousHome
|
||||||
|
await rm(home, { recursive: true, force: true })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,13 +18,26 @@
|
||||||
*
|
*
|
||||||
* Types ship from lib/types (tsc -p tsconfig.build.json), not from tsdown.
|
* Types ship from lib/types (tsc -p tsconfig.build.json), not from tsdown.
|
||||||
*/
|
*/
|
||||||
|
import { existsSync, readFileSync } from 'node:fs'
|
||||||
import { readFile } from 'node:fs/promises'
|
import { readFile } from 'node:fs/promises'
|
||||||
import { dirname, resolve as resolvePath, isAbsolute } from 'node:path'
|
import { dirname, resolve as resolvePath, isAbsolute } from 'node:path'
|
||||||
import { existsSync } from 'node:fs'
|
import { fileURLToPath } from 'node:url'
|
||||||
import { builtinModules } from 'node:module'
|
import { builtinModules } from 'node:module'
|
||||||
import type { UserConfig } from 'tsdown'
|
import type { UserConfig } from 'tsdown'
|
||||||
import { transform } from 'lightningcss'
|
import { transform } from 'lightningcss'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The client bundle banner MUST register under the package name: client-modules
|
||||||
|
* keys its graph rows by package name, so a banner id that differs makes the
|
||||||
|
* row look unregistered (the row is then re-fetched, hits `register()` a second
|
||||||
|
* time and throws "duplicate factory registration", failing the whole boot).
|
||||||
|
* Read the name instead of hardcoding it — the package has been renamed once
|
||||||
|
* already (`@dsh-xhl/workspace-groups` -> `workspace-groups-local`).
|
||||||
|
*/
|
||||||
|
const PACKAGE_NAME: string = (
|
||||||
|
JSON.parse(readFileSync(fileURLToPath(new URL('./package.json', import.meta.url)), 'utf8')) as { name: string }
|
||||||
|
).name
|
||||||
|
|
||||||
/** Node builtins must never survive into the browser module-loader factory. */
|
/** Node builtins must never survive into the browser module-loader factory. */
|
||||||
const NODE_BUILTINS = new Set([
|
const NODE_BUILTINS = new Set([
|
||||||
...builtinModules,
|
...builtinModules,
|
||||||
|
|
@ -147,7 +160,7 @@ function clientConfig(): UserConfig {
|
||||||
],
|
],
|
||||||
outputOptions: {
|
outputOptions: {
|
||||||
entryFileNames: 'client.js',
|
entryFileNames: 'client.js',
|
||||||
banner: `window.__ModuleLoader__.load({ id: "@dsh-xhl/workspace-groups", factory: (require) => {`,
|
banner: `window.__ModuleLoader__.load({ id: ${JSON.stringify(PACKAGE_NAME)}, factory: (require) => {`,
|
||||||
footer: 'return module.exports; } });',
|
footer: 'return module.exports; } });',
|
||||||
intro: 'var module = { exports: {} }; var exports = module.exports;',
|
intro: 'var module = { exports: {} }; var exports = module.exports;',
|
||||||
},
|
},
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue