feat(farm): gather a project's folders into one workspace

A session can only reach its own workspace directory, so folders spread over
several places could not be read and written by one session. The new farm
route builds one real directory whose entries are links to the user's folders
(junction on Windows, directory symlink elsewhere) and registers it as a
workspace.

Nothing is copied or moved. Removal unlinks entries only and aborts as soon as
it meets a real directory, so a farm can never take a user's folder with it.
This commit is contained in:
qyh15 2026-11-07 18:08:27 +08:00
parent bc6a427dfe
commit dcc47fc0b6
14 changed files with 984 additions and 7 deletions

View File

@ -1,5 +1,19 @@
# 更新日志
## 未发布 — 一个工作区收拢多个文件夹(2026-11-07)
会话的文件范围就是它所在的工作区目录,所以分散在不同位置的文件夹无法被同一个会话同时读写。
新增「合并成一个总文件夹」:在 `$DSH_HOME/workspace-groups/farms/<名称>/` 建一个真实目录,
用链接(Windows junction / POSIX 目录符号链接)把该项目的每个文件夹放进去,再注册成一个工作区。
不复制、不移动、不改动原文件夹。
- 新增宿主路由 `POST /workspace-groups/farm` 与 `DELETE /workspace-groups/farm?path=`。宿主只接受绝对路径,
不存在的目录直接拒绝,已存在的农场拒绝复用(避免静默合并到别人建的目录)。
- 删除只解链接:遇到真实目录立刻中止,绝不递归删除,避免顺链接删掉用户的真实文件夹。
- 侧栏「管理文件夹」对话框在该工作区有 2 个及以上文件夹时显示该操作;成功后提示新工作区路径。
- 新增 `tests/farm.test.ts`(11 项):写入穿透链接落到真实文件夹、同名文件夹去重命名、相对/缺失目录拒绝、
重复农场拒绝、删除后原文件夹内容不变、农场根外路径拒绝、农场内真实目录拒绝删除。
## 未发布 — 文件夹管理安全性与一致性修复(2026-11-07)
针对「工作区内的文件夹管理」扫描发现的 10 类问题做的一次集中修复。本次只改本插件,

View File

@ -4362,7 +4362,7 @@ window.__ModuleLoader__.load({
* swaps to the remote tree, so no stacked overlays are needed and the current
* location stays readable at the top.
*/
function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, blockedReason, warnings, onReload, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }) {
function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, blockedReason, warnings, onReload, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }) {
const folders = effectiveFolders(workspace.path, entry);
const root = rootOf(workspace.path, entry);
const [addMode, setAddMode] = (0, react.useState)("local");
@ -4572,6 +4572,30 @@ window.__ModuleLoader__.load({
})
]
}),
extraFolders && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
className: "wgFolderMerge",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "wgFolderSectionTitle",
children: t("folder.mergeTitle")
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
type: "button",
className: "wgFolderPick",
disabled: busy || editBlocked,
onClick: onBuildFarm,
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
className: "wgFolderPickPlus",
"aria-hidden": true,
children: "⇄"
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: t("folder.mergeAction") })]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
className: "wgFolderHint",
children: t("folder.mergeHint")
})
]
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("section", {
className: "wgFolderAdd",
children: [
@ -4864,6 +4888,71 @@ window.__ModuleLoader__.load({
});
}
//#endregion
//#region src/client/folders-farm.ts
/**
* Client side of the farm route.
*
* A farm is one real directory holding a link per project folder, so a session
* can read and write all of them at once. The host owns the filesystem work;
* this module only speaks the two requests, and never assumes success: every
* failure comes back as an Error with the host's own message.
*/
const FARM_ROUTE = "/workspace-groups/farm";
const FARM_TIMEOUT_MS = 2e4;
function hostMessage(body, fallback) {
if (typeof body === "object" && body !== null) {
const message = body.error;
if (typeof message === "string" && message !== "") return message;
}
return fallback;
}
async function failure(response, action) {
let body;
try {
body = await response.json();
} catch {
body = null;
}
return new Error(hostMessage(body, `${action}: HTTP ${response.status}`));
}
function parseFarm(body) {
if (typeof body !== "object" || body === null) return null;
const source = body;
if (typeof source.path !== "string" || source.path === "") return null;
if (!Array.isArray(source.links)) return null;
const links = [];
for (const entry of source.links) {
if (typeof entry !== "object" || entry === null) return null;
const link = entry;
if (typeof link.name !== "string" || link.name === "") return null;
if (typeof link.target !== "string" || link.target === "") return null;
links.push({
name: link.name,
target: link.target
});
}
return {
path: source.path,
links
};
}
/** Build a farm for `folders`; the host refuses to reuse an existing one. */
async function buildFarm(name, folders, fetchImpl = fetch) {
const response = await fetchImpl(FARM_ROUTE, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
folders
}),
signal: AbortSignal.timeout(FARM_TIMEOUT_MS)
});
if (!response.ok) throw await failure(response, "POST /workspace-groups/farm");
const parsed = parseFarm(await response.json());
if (parsed === null) throw new Error("POST /workspace-groups/farm: malformed response");
return parsed;
}
//#endregion
//#region src/client/quick.ts
/** A session row eligible for quick switching: running, top-level, real. */
function quickEligible(summary) {
@ -6731,6 +6820,31 @@ window.__ModuleLoader__.load({
const setFolderRoot = (workspaceId, path) => {
editFolderEntry(workspaceId, (current) => setRoot(current, path));
};
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so one session reaches all of them. The folders themselves are
* never copied, moved or deleted; the farm holds links only.
*/
const buildFarmFor = async (workspaceId) => {
if (foldersBusy) return;
const workspace = workspaces.find((w) => w.workspaceId === workspaceId);
if (workspace === void 0) return;
const folders = effectiveFolders(workspace.path, entryFor(foldersDocRef.current, workspaceId));
if (folders.length < 2) {
notifyFolder(t("folder.emptyHint"));
return;
}
setFoldersBusy(true);
try {
const farm = await buildFarm(workspace.title, folders);
await createWorkspace({ path: farm.path });
notifyFolder(`${t("folder.mergeDone")} ${farm.path}`);
} catch (reason) {
notifyFolder(`${t("folder.mergeFailed")}: ${reason instanceof Error ? reason.message : String(reason)}`);
} finally {
setFoldersBusy(false);
}
};
const removeFolderFrom = (workspaceId, path) => {
editFolderEntry(workspaceId, (current) => removeFolder(current, path));
};
@ -7769,6 +7883,9 @@ window.__ModuleLoader__.load({
blockedReason: foldersLoadError !== null ? `${t("folder.loadError")}: ${foldersLoadError}` : foldersSchemaWarning,
warnings: [...foldersRemoteBaseWarning === null ? [] : [foldersRemoteBaseWarning]],
onReload: reloadFolders,
onBuildFarm: () => {
buildFarmFor(foldersTarget);
},
onAddFolder: () => {
addFolderTo(foldersTarget);
},
@ -8403,6 +8520,11 @@ window.__ModuleLoader__.load({
"folder.addKindSubfolder": "本项目子目录",
"folder.addKindWorkspace": "独立云端工作区",
"folder.cloudNoteSubfolder": "会在项目云端根目录下新建该目录并挂进来;不会注册第二个镜像工作区",
"folder.mergeTitle": "合并成一个总文件夹",
"folder.mergeAction": "生成总文件夹并添加为工作区",
"folder.mergeHint": "在旁边建一个目录,用链接把这些文件夹放进去,再注册成工作区。不复制、不移动原文件夹;之后在这个工作区里的会话可以同时读写它们。",
"folder.mergeDone": "已生成总文件夹:",
"folder.mergeFailed": "生成总文件夹失败",
"folder.notReady": "目录安全信息尚未加载,请重启 DSH 并刷新页面后重试",
"folder.remoteSessionUnsupported": "当前 SSH 插件不完整支持子目录会话,请从远程工作区根目录打开会话。不会退回本地终端。",
"folder.remoteHint": "输入一个文件夹名:本地使用 DSH 目录接口;远程使用 SSH 创建目录接口(远端同名目录已存在时复用)。SSH 不可用时不会在镜像里创建本地目录。",
@ -8588,6 +8710,11 @@ window.__ModuleLoader__.load({
"folder.addKindSubfolder": "Subfolder of this project",
"folder.addKindWorkspace": "Standalone cloud workspace",
"folder.cloudNoteSubfolder": "Creates that directory under this project’s remote root and attaches it; no second mirror workspace is registered",
"folder.mergeTitle": "Merge into one folder",
"folder.mergeAction": "Create the merged folder as a workspace",
"folder.mergeHint": "Builds one directory that links these folders side by side and registers it as a workspace. Nothing is copied or moved; sessions in that workspace can read and write all of them.",
"folder.mergeDone": "Merged folder created: ",
"folder.mergeFailed": "Could not build the merged folder",
"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.",

View File

@ -1,5 +1,5 @@
import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { lstat, mkdir, open, readFile, readdir, realpath, rename, rmdir, stat, symlink, unlink } from "node:fs/promises";
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
import { homedir } from "node:os";
import { createHash } from "node:crypto";
//#region node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs
@ -3538,6 +3538,156 @@ async function replaceFoldersDocument(path, expectedRevision, document) {
return run;
}
//#endregion
//#region src/host-farm.ts
/**
* A farm gathers several project folders into one real directory, so a single
* session can read and write all of them.
*
* A session's file scope is its workspace directory, so "one project, several
* folders" needs one directory that contains all of them. The farm is that
* directory: every entry is a link (a junction on Windows, a directory symlink
* elsewhere) to a folder the user already owns. Nothing is copied or moved, and
* the user's folders keep their own life.
*
* Deletion is the dangerous half. A recursive delete that followed a link would
* erase the user's real folder, so {@link removeFarm} only ever unlinks entries
* that are links, and refuses as soon as it meets a real directory.
*/
/** Characters Windows refuses in a name, plus control characters. */
const RESERVED_CHARS = /[\u005C\u002F:*?"<>|\u0000-\u001f]/gu;
/** Device names Windows refuses as a whole entry name. */
const RESERVED_NAMES = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/iu;
const MAX_NAME_LENGTH = 64;
const WINDOWS = process.platform === "win32";
function dshHome() {
const configured = process.env.DSH_HOME;
return configured === void 0 || configured.trim() === "" ? join(homedir(), ".dsh") : configured;
}
/** Root that holds every farm: `$DSH_HOME/workspace-groups/farms`. */
function defaultFarmRoot() {
return resolve(dshHome(), "workspace-groups", "farms");
}
/** One directory-safe name for a farm, derived from a workspace title. */
function farmDirectoryName(title) {
const cleaned = title.replace(RESERVED_CHARS, " ").replace(/\s+/gu, " ").trim().replace(/[. ]+$/u, "").slice(0, MAX_NAME_LENGTH).trim().replace(/[. ]+$/u, "");
if (cleaned === "") return "farm";
return RESERVED_NAMES.test(cleaned) ? `_${cleaned}` : cleaned;
}
function linkNameFor(target, taken) {
const raw = basename(target).replace(RESERVED_CHARS, " ").replace(/\s+/gu, " ").trim() || "folder";
const base = RESERVED_NAMES.test(raw) ? `_${raw}` : raw;
let name = base;
let suffix = 2;
while (taken.has(name.toLowerCase())) {
name = `${base} (${suffix})`;
suffix += 1;
}
taken.add(name.toLowerCase());
return name;
}
/**
* Delete one farm entry, and only one.
*
* A junction reports as a symbolic link to `lstat` but is a reparse point that
* `unlink` refuses; a directory symlink on POSIX removes fine with `unlink`. A
* real directory is never touched.
*/
async function unlinkEntry(path) {
const info = await lstat(path);
if (info.isDirectory() && !info.isSymbolicLink()) throw new Error(`farm: refusing to delete a real directory: ${path}`);
try {
await unlink(path);
} catch {
await rmdir(path);
}
}
async function discard(path) {
let entries;
try {
entries = await readdir(path);
} catch {
return;
}
for (const entry of entries) try {
await unlinkEntry(join(path, entry));
} catch {}
try {
await rmdir(path);
} catch {}
}
/** Resolve and validate one folder the user asked to gather. */
async function resolveFolder(raw) {
if (typeof raw !== "string" || raw.trim() === "") throw new Error("farm: empty folder path");
if (!isAbsolute(raw)) throw new Error(`farm: folder must be an absolute path: ${raw}`);
let real;
try {
real = await realpath(raw);
} catch {
throw new Error(`farm: folder does not exist: ${raw}`);
}
if (!(await stat(real)).isDirectory()) throw new Error(`farm: not a directory: ${raw}`);
return real;
}
/**
* Build a farm for `folders` under `defaultFarmRoot()`.
*
* Refuses to reuse an existing farm directory: a silent merge into a directory
* that already holds links would hide which entries this call owns.
*/
async function buildFarm(input) {
const seen = /* @__PURE__ */ new Set();
const targets = [];
for (const raw of input.folders) {
const target = await resolveFolder(raw);
const key = WINDOWS ? target.toLowerCase() : target;
if (seen.has(key)) continue;
seen.add(key);
targets.push(target);
}
if (targets.length < 2) throw new Error("farm: needs at least two distinct folders");
const root = defaultFarmRoot();
const path = join(root, farmDirectoryName(String(input.name)));
await mkdir(root, { recursive: true });
try {
await mkdir(path);
} catch (error) {
if (error.code === "EEXIST") throw new Error(`farm: already exists, remove it first: ${path}`);
throw new Error(`farm: cannot create ${path}: ${error instanceof Error ? error.message : String(error)}`);
}
const taken = /* @__PURE__ */ new Set();
const links = [];
try {
for (const target of targets) {
const name = linkNameFor(target, taken);
await symlink(target, join(path, name), WINDOWS ? "junction" : "dir");
links.push({
name,
target
});
}
} catch (error) {
await discard(path);
throw new Error(`farm: cannot link into ${path}: ${error instanceof Error ? error.message : String(error)}`);
}
return {
path,
links
};
}
/**
* Remove a farm this module built. Only entries under `defaultFarmRoot()` are
* accepted, and only links are unlinked: a real directory aborts the removal.
*/
async function removeFarm(farmPath) {
const root = defaultFarmRoot();
const target = resolve(farmPath);
const inside = relative(root, target);
if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) throw new Error(`farm: not a farm directory: ${farmPath}`);
const entries = await readdir(target);
for (const entry of entries) await unlinkEntry(join(target, entry));
await rmdir(target);
}
//#endregion
//#region src/index.ts
/** Plugin identity for cordis.yml rows. */
const name = "workspace-groups-local";
@ -3858,6 +4008,66 @@ function apply(ctx) {
}, diagnostic)), result.revision);
}
}), "@dsh-xhl/workspace-groups: /workspace-groups/folders route");
ctx.effect(() => ctx.webServer.register({
kind: "exact",
path: "/workspace-groups/farm",
handler: async (req, res) => {
if (req.method === "POST") {
let raw;
try {
raw = JSON.parse(await readBody(req, MAX_FOLDERS_BODY_BYTES));
} catch (error) {
writeError(res, error instanceof HttpError ? error.status : 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const body = raw;
if (body === null || typeof body !== "object" || !Array.isArray(body.folders)) {
writeError(res, 400, "workspace-groups: farm needs { name, folders: string[] }");
return;
}
let result;
try {
result = await buildFarm({
name: typeof body.name === "string" ? body.name : "farm",
folders: body.folders
});
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const payload = JSON.stringify(result);
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"Content-Length": Buffer.byteLength(payload)
});
res.end(payload);
return;
}
if (req.method === "DELETE") {
const target = new URL(req.url ?? "/", "http://localhost").searchParams.get("path");
if (target === null || target.trim() === "") {
writeError(res, 400, "workspace-groups: farm needs ?path=");
return;
}
try {
await removeFarm(target);
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const payload = JSON.stringify({ ok: true });
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"Content-Length": Buffer.byteLength(payload)
});
res.end(payload);
return;
}
writeError(res, 405, "method not allowed");
}
}), "@dsh-xhl/workspace-groups: /workspace-groups/farm route");
}
//#endregion
export { apply, inject, name };

View File

@ -2,7 +2,7 @@ import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/cl
import { type WorkspaceFolderEntry } from '../core/folders.ts';
import type { GroupsBrowserProps } from './contract.ts';
import { type RemoteProfileSummary } from './folder-directory.ts';
export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, blockedReason, warnings, onReload, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, blockedReason, warnings, onReload, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView;
entry: WorkspaceFolderEntry | undefined;
t: GroupsBrowserProps['t'];
@ -23,6 +23,11 @@ export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remo
warnings: readonly string[];
onReload: () => void;
onClose: () => void;
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so a single session can read and write all of them.
*/
onBuildFarm: () => void;
/** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => void;
/** Register one cloud folder: returns true once it is stored. */

24
lib/types/client/folders-farm.d.ts vendored Normal file
View File

@ -0,0 +1,24 @@
/**
* Client side of the farm route.
*
* A farm is one real directory holding a link per project folder, so a session
* can read and write all of them at once. The host owns the filesystem work;
* this module only speaks the two requests, and never assumes success: every
* failure comes back as an Error with the host's own message.
*/
export declare const FARM_ROUTE = "/workspace-groups/farm";
export interface FarmLink {
/** Entry name inside the farm directory. */
readonly name: string;
/** Absolute real path of the folder it points at. */
readonly target: string;
}
export interface FarmResult {
/** Absolute path of the farm directory. */
readonly path: string;
readonly links: readonly FarmLink[];
}
/** Build a farm for `folders`; the host refuses to reuse an existing one. */
export declare function buildFarm(name: string, folders: readonly string[], fetchImpl?: typeof fetch): Promise<FarmResult>;
/** Remove a farm; only its links are unlinked, never a real folder. */
export declare function removeFarm(farmPath: string, fetchImpl?: typeof fetch): Promise<void>;

View File

@ -4,7 +4,7 @@
*/
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.sectionList' | 'folder.sectionAdd' | 'folder.emptyHint' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.loadError' | 'folder.conflict' | 'folder.retry' | 'folder.reload' | 'folder.addKind' | 'folder.addKindSubfolder' | 'folder.addKindWorkspace' | 'folder.cloudNoteSubfolder' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'folder.cloudSection' | 'folder.profileLabel' | 'folder.remotePathLabel' | 'folder.remotePathPlaceholder' | 'folder.remotePathOrName' | 'folder.createAndAdd' | 'folder.cloudNoteBoth' | 'folder.addRemote' | 'folder.noProfiles' | 'folder.profilesError' | 'folder.cloudTag' | 'folder.localTag' | 'folder.memberMissing' | 'folder.memberNested' | 'folder.alreadyRoot' | 'folder.addAria' | 'folder.tabLocal' | 'folder.tabCloud' | 'folder.pickLocal' | 'folder.localNote' | 'folder.localIntoRemote' | 'folder.cloudNote' | 'folder.browse' | 'folder.browseTitle' | 'folder.browseListAria' | 'folder.browseNote' | 'folder.browseFailed' | 'folder.chooseHere' | 'folder.up' | 'folder.home' | 'folder.refresh' | 'folder.loading' | 'folder.emptyDir' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'group.icon.section.common' | 'group.icon.section.lab' | 'group.icon.section.materials' | 'group.icon.section.characterization' | 'group.icon.section.devices' | 'group.icon.section.emoji' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'section.defaultWorkspace' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.sectionList' | 'folder.sectionAdd' | 'folder.emptyHint' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.loadError' | 'folder.conflict' | 'folder.retry' | 'folder.reload' | 'folder.addKind' | 'folder.addKindSubfolder' | 'folder.addKindWorkspace' | 'folder.cloudNoteSubfolder' | 'folder.mergeTitle' | 'folder.mergeAction' | 'folder.mergeHint' | 'folder.mergeDone' | 'folder.mergeFailed' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'folder.cloudSection' | 'folder.profileLabel' | 'folder.remotePathLabel' | 'folder.remotePathPlaceholder' | 'folder.remotePathOrName' | 'folder.createAndAdd' | 'folder.cloudNoteBoth' | 'folder.addRemote' | 'folder.noProfiles' | 'folder.profilesError' | 'folder.cloudTag' | 'folder.localTag' | 'folder.memberMissing' | 'folder.memberNested' | 'folder.alreadyRoot' | 'folder.addAria' | 'folder.tabLocal' | 'folder.tabCloud' | 'folder.pickLocal' | 'folder.localNote' | 'folder.localIntoRemote' | 'folder.cloudNote' | 'folder.browse' | 'folder.browseTitle' | 'folder.browseListAria' | 'folder.browseNote' | 'folder.browseFailed' | 'folder.chooseHere' | 'folder.up' | 'folder.home' | 'folder.refresh' | 'folder.loading' | 'folder.emptyDir' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'group.icon.section.common' | 'group.icon.section.lab' | 'group.icon.section.materials' | 'group.icon.section.characterization' | 'group.icon.section.devices' | 'group.icon.section.emoji' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'section.defaultWorkspace' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
/** Simplified Chinese dictionary. */
export declare const zh: WorkspaceGroupsDict;

30
lib/types/host-farm.d.ts vendored Normal file
View File

@ -0,0 +1,30 @@
export interface FarmLink {
/** Entry name inside the farm directory. */
readonly name: string;
/** Absolute real path of the folder it points at. */
readonly target: string;
}
export interface FarmResult {
/** Absolute path of the farm directory. */
readonly path: string;
readonly links: readonly FarmLink[];
}
/** Root that holds every farm: `$DSH_HOME/workspace-groups/farms`. */
export declare function defaultFarmRoot(): string;
/** One directory-safe name for a farm, derived from a workspace title. */
export declare function farmDirectoryName(title: string): string;
/**
* Build a farm for `folders` under `defaultFarmRoot()`.
*
* Refuses to reuse an existing farm directory: a silent merge into a directory
* that already holds links would hide which entries this call owns.
*/
export declare function buildFarm(input: {
name: string;
folders: readonly unknown[];
}): Promise<FarmResult>;
/**
* Remove a farm this module built. Only entries under `defaultFarmRoot()` are
* accepted, and only links are unlinked: a real directory aborts the removal.
*/
export declare function removeFarm(farmPath: string): Promise<void>;

View File

@ -38,7 +38,7 @@ type AddMode = 'local' | 'cloud'
/** What a typed value in the cloud field means. Explicit, never inferred. */
type AddKind = 'subfolder' | 'workspace'
export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, blockedReason, warnings, onReload, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, blockedReason, warnings, onReload, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView
entry: WorkspaceFolderEntry | undefined
t: GroupsBrowserProps['t']
@ -59,6 +59,11 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
warnings: readonly string[]
onReload: () => void
onClose: () => void
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so a single session can read and write all of them.
*/
onBuildFarm: () => void
/** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => void
/** Register one cloud folder: returns true once it is stored. */
@ -249,6 +254,20 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
{!extraFolders && <p className="wgFolderEmpty">{t('folder.emptyHint')}</p>}
</section>
{extraFolders && (
<section className="wgFolderMerge">
<div className="wgFolderSectionTitle">{t('folder.mergeTitle')}</div>
{/* A session's file scope is its workspace directory, so folders in
different places are unreachable from one session. A farm puts
them side by side as links; nothing is copied or moved. */}
<button type="button" className="wgFolderPick" disabled={busy || editBlocked} onClick={onBuildFarm}>
<span className="wgFolderPickPlus" aria-hidden>⇄</span>
<span>{t('folder.mergeAction')}</span>
</button>
<p className="wgFolderHint">{t('folder.mergeHint')}</p>
</section>
)}
<section className="wgFolderAdd">
<div className="wgFolderSectionTitle">{t('folder.sectionAdd')}</div>
<div className="wgFolderSegmented" role="tablist" aria-label={t('folder.addAria')}>

View File

@ -60,6 +60,7 @@ import { FoldersConflictError, loadFolders, saveFolders, type FoldersSnapshot }
import { createRemoteFolder, createWorkspaceDirectory, listRemoteDirectory, listRemoteProfiles, remoteFolderWorkspace, type RemoteFolderWorkspace, type RemoteProfileSummary } from './folder-directory.ts'
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
import { FoldersDialog } from './FoldersDialog.tsx'
import { buildFarm } from './folders-farm.ts'
import { QuickPanel } from './QuickPanel.tsx'
import { SessionTabs } from './SessionTabs.tsx'
import css from './styles.css?inline'
@ -1099,6 +1100,34 @@ export function GroupsBrowser({
void editFolderEntry(workspaceId, (current) => setRoot(current, path))
}
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so one session reaches all of them. The folders themselves are
* never copied, moved or deleted; the farm holds links only.
*/
const buildFarmFor = async (workspaceId: WorkspaceId): Promise<void> => {
if (foldersBusy) return
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
if (workspace === undefined) return
const folders = effectiveFolders(workspace.path, entryFor(foldersDocRef.current, workspaceId))
if (folders.length < 2) {
notifyFolder(t('folder.emptyHint'))
return
}
setFoldersBusy(true)
try {
const farm = await buildFarm(workspace.title, folders)
// Registering the farm is a separate step: a created directory without a
// workspace is harmless, and the error still names what already exists.
await createWorkspace({ path: farm.path })
notifyFolder(`${t('folder.mergeDone')} ${farm.path}`)
} catch (reason) {
notifyFolder(`${t('folder.mergeFailed')}: ${reason instanceof Error ? reason.message : String(reason)}`)
} finally {
setFoldersBusy(false)
}
}
const removeFolderFrom = (workspaceId: WorkspaceId, path: string): void => {
void editFolderEntry(workspaceId, (current) => removeFolder(current, path))
}
@ -2168,6 +2197,7 @@ export function GroupsBrowser({
...(foldersRemoteBaseWarning === null ? [] : [foldersRemoteBaseWarning]),
]}
onReload={reloadFolders}
onBuildFarm={() => { void buildFarmFor(foldersTarget) }}
onAddFolder={() => { void addFolderTo(foldersTarget) }}
onAddRemote={(profileId, remotePath) => addRemoteFolderTo(foldersTarget, profileId, remotePath)}
onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)}

View File

@ -0,0 +1,87 @@
/**
* Client side of the farm route.
*
* A farm is one real directory holding a link per project folder, so a session
* can read and write all of them at once. The host owns the filesystem work;
* this module only speaks the two requests, and never assumes success: every
* failure comes back as an Error with the host's own message.
*/
export const FARM_ROUTE = '/workspace-groups/farm'
const FARM_TIMEOUT_MS = 20_000
export interface FarmLink {
/** Entry name inside the farm directory. */
readonly name: string
/** Absolute real path of the folder it points at. */
readonly target: string
}
export interface FarmResult {
/** Absolute path of the farm directory. */
readonly path: string
readonly links: readonly FarmLink[]
}
function hostMessage(body: unknown, fallback: string): string {
if (typeof body === 'object' && body !== null) {
const message = (body as { error?: unknown }).error
if (typeof message === 'string' && message !== '') return message
}
return fallback
}
async function failure(response: Response, action: string): Promise<Error> {
let body: unknown
try {
body = await response.json()
} catch {
body = null
}
return new Error(hostMessage(body, `${action}: HTTP ${response.status}`))
}
function parseFarm(body: unknown): FarmResult | null {
if (typeof body !== 'object' || body === null) return null
const source = body as { path?: unknown; links?: unknown }
if (typeof source.path !== 'string' || source.path === '') return null
if (!Array.isArray(source.links)) return null
const links: FarmLink[] = []
for (const entry of source.links) {
if (typeof entry !== 'object' || entry === null) return null
const link = entry as { name?: unknown; target?: unknown }
if (typeof link.name !== 'string' || link.name === '') return null
if (typeof link.target !== 'string' || link.target === '') return null
links.push({ name: link.name, target: link.target })
}
return { path: source.path, links }
}
/** Build a farm for `folders`; the host refuses to reuse an existing one. */
export async function buildFarm(
name: string,
folders: readonly string[],
fetchImpl: typeof fetch = fetch,
): Promise<FarmResult> {
const response = await fetchImpl(FARM_ROUTE, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, folders }),
signal: AbortSignal.timeout(FARM_TIMEOUT_MS),
})
if (!response.ok) throw await failure(response, 'POST /workspace-groups/farm')
const parsed = parseFarm(await response.json())
if (parsed === null) throw new Error('POST /workspace-groups/farm: malformed response')
return parsed
}
/** Remove a farm; only its links are unlinked, never a real folder. */
export async function removeFarm(
farmPath: string,
fetchImpl: typeof fetch = fetch,
): Promise<void> {
const response = await fetchImpl(`${FARM_ROUTE}?path=${encodeURIComponent(farmPath)}`, {
method: 'DELETE',
signal: AbortSignal.timeout(FARM_TIMEOUT_MS),
})
if (!response.ok) throw await failure(response, 'DELETE /workspace-groups/farm')
}

View File

@ -59,6 +59,11 @@ export type WorkspaceGroupsKey =
| 'folder.addKindSubfolder'
| 'folder.addKindWorkspace'
| 'folder.cloudNoteSubfolder'
| 'folder.mergeTitle'
| 'folder.mergeAction'
| 'folder.mergeHint'
| 'folder.mergeDone'
| 'folder.mergeFailed'
| 'folder.notReady'
| 'folder.remoteSessionUnsupported'
| 'folder.remoteHint'
@ -246,6 +251,11 @@ export const zh: WorkspaceGroupsDict = {
'folder.addKindSubfolder': '本项目子目录',
'folder.addKindWorkspace': '独立云端工作区',
'folder.cloudNoteSubfolder': '会在项目云端根目录下新建该目录并挂进来;不会注册第二个镜像工作区',
'folder.mergeTitle': '合并成一个总文件夹',
'folder.mergeAction': '生成总文件夹并添加为工作区',
'folder.mergeHint': '在旁边建一个目录,用链接把这些文件夹放进去,再注册成工作区。不复制、不移动原文件夹;之后在这个工作区里的会话可以同时读写它们。',
'folder.mergeDone': '已生成总文件夹:',
'folder.mergeFailed': '生成总文件夹失败',
'folder.notReady': '目录安全信息尚未加载,请重启 DSH 并刷新页面后重试',
'folder.remoteSessionUnsupported': '当前 SSH 插件不完整支持子目录会话,请从远程工作区根目录打开会话。不会退回本地终端。',
'folder.remoteHint': '输入一个文件夹名:本地使用 DSH 目录接口;远程使用 SSH 创建目录接口(远端同名目录已存在时复用)。SSH 不可用时不会在镜像里创建本地目录。',
@ -432,6 +442,11 @@ export const en: WorkspaceGroupsDict = {
'folder.addKindSubfolder': 'Subfolder of this project',
'folder.addKindWorkspace': 'Standalone cloud workspace',
'folder.cloudNoteSubfolder': 'Creates that directory under this project’s remote root and attaches it; no second mirror workspace is registered',
'folder.mergeTitle': 'Merge into one folder',
'folder.mergeAction': 'Create the merged folder as a workspace',
'folder.mergeHint': 'Builds one directory that links these folders side by side and registers it as a workspace. Nothing is copied or moved; sessions in that workspace can read and write all of them.',
'folder.mergeDone': 'Merged folder created: ',
'folder.mergeFailed': 'Could not build the merged folder',
'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.',

194
src/host-farm.ts Normal file
View File

@ -0,0 +1,194 @@
/**
* A farm gathers several project folders into one real directory, so a single
* session can read and write all of them.
*
* A session's file scope is its workspace directory, so "one project, several
* folders" needs one directory that contains all of them. The farm is that
* directory: every entry is a link (a junction on Windows, a directory symlink
* elsewhere) to a folder the user already owns. Nothing is copied or moved, and
* the user's folders keep their own life.
*
* Deletion is the dangerous half. A recursive delete that followed a link would
* erase the user's real folder, so {@link removeFarm} only ever unlinks entries
* that are links, and refuses as soon as it meets a real directory.
*/
import { lstat, mkdir, readdir, realpath, rmdir, stat, symlink, unlink } from 'node:fs/promises'
import { homedir } from 'node:os'
import { basename, isAbsolute, join, relative as relativePath, resolve } from 'node:path'
/** Characters Windows refuses in a name, plus control characters. */
// \u005C is a backslash and \u002F a slash: written this way so this file holds
// no literal backslash at all.
const RESERVED_CHARS = /[\u005C\u002F:*?"<>|\u0000-\u001f]/gu
/** Device names Windows refuses as a whole entry name. */
const RESERVED_NAMES = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/iu
const MAX_NAME_LENGTH = 64
const WINDOWS = process.platform === 'win32'
export interface FarmLink {
/** Entry name inside the farm directory. */
readonly name: string
/** Absolute real path of the folder it points at. */
readonly target: string
}
export interface FarmResult {
/** Absolute path of the farm directory. */
readonly path: string
readonly links: readonly FarmLink[]
}
function dshHome(): string {
const configured = process.env.DSH_HOME
return configured === undefined || configured.trim() === '' ? join(homedir(), '.dsh') : configured
}
/** Root that holds every farm: `$DSH_HOME/workspace-groups/farms`. */
export function defaultFarmRoot(): string {
return resolve(dshHome(), 'workspace-groups', 'farms')
}
/** One directory-safe name for a farm, derived from a workspace title. */
export function farmDirectoryName(title: string): string {
const cleaned = title
.replace(RESERVED_CHARS, ' ')
.replace(/\s+/gu, ' ')
.trim()
.replace(/[. ]+$/u, '')
.slice(0, MAX_NAME_LENGTH)
.trim()
.replace(/[. ]+$/u, '')
if (cleaned === '') return 'farm'
return RESERVED_NAMES.test(cleaned) ? `_${cleaned}` : cleaned
}
function linkNameFor(target: string, taken: Set<string>): string {
const raw = basename(target).replace(RESERVED_CHARS, ' ').replace(/\s+/gu, ' ').trim() || 'folder'
const base = RESERVED_NAMES.test(raw) ? `_${raw}` : raw
let name = base
let suffix = 2
while (taken.has(name.toLowerCase())) {
name = `${base} (${suffix})`
suffix += 1
}
taken.add(name.toLowerCase())
return name
}
/**
* Delete one farm entry, and only one.
*
* A junction reports as a symbolic link to `lstat` but is a reparse point that
* `unlink` refuses; a directory symlink on POSIX removes fine with `unlink`. A
* real directory is never touched.
*/
async function unlinkEntry(path: string): Promise<void> {
const info = await lstat(path)
if (info.isDirectory() && !info.isSymbolicLink()) {
throw new Error(`farm: refusing to delete a real directory: ${path}`)
}
try {
await unlink(path)
} catch {
// Windows junction: unlink is EPERM, rmdir removes the reparse point only.
await rmdir(path)
}
}
async function discard(path: string): Promise<void> {
let entries: string[]
try {
entries = await readdir(path)
} catch {
return
}
for (const entry of entries) {
try {
await unlinkEntry(join(path, entry))
} catch {
// Best effort: a half-built farm is still better than a thrown rollback.
}
}
try {
await rmdir(path)
} catch {
// Leave it: an empty directory is harmless and the next build reports it.
}
}
/** Resolve and validate one folder the user asked to gather. */
async function resolveFolder(raw: unknown): Promise<string> {
if (typeof raw !== 'string' || raw.trim() === '') throw new Error('farm: empty folder path')
if (!isAbsolute(raw)) throw new Error(`farm: folder must be an absolute path: ${raw}`)
let real: string
try {
real = await realpath(raw)
} catch {
throw new Error(`farm: folder does not exist: ${raw}`)
}
const info = await stat(real)
if (!info.isDirectory()) throw new Error(`farm: not a directory: ${raw}`)
return real
}
/**
* Build a farm for `folders` under `defaultFarmRoot()`.
*
* Refuses to reuse an existing farm directory: a silent merge into a directory
* that already holds links would hide which entries this call owns.
*/
export async function buildFarm(input: { name: string; folders: readonly unknown[] }): Promise<FarmResult> {
const seen = new Set<string>()
const targets: string[] = []
for (const raw of input.folders) {
const target = await resolveFolder(raw)
const key = WINDOWS ? target.toLowerCase() : target
if (seen.has(key)) continue
seen.add(key)
targets.push(target)
}
if (targets.length < 2) throw new Error('farm: needs at least two distinct folders')
const root = defaultFarmRoot()
const path = join(root, farmDirectoryName(String(input.name)))
await mkdir(root, { recursive: true })
try {
await mkdir(path)
} catch (error) {
const code = (error as { code?: string }).code
if (code === 'EEXIST') throw new Error(`farm: already exists, remove it first: ${path}`)
throw new Error(`farm: cannot create ${path}: ${error instanceof Error ? error.message : String(error)}`)
}
const taken = new Set<string>()
const links: FarmLink[] = []
try {
for (const target of targets) {
const name = linkNameFor(target, taken)
await symlink(target, join(path, name), WINDOWS ? 'junction' : 'dir')
links.push({ name, target })
}
} catch (error) {
await discard(path)
throw new Error(`farm: cannot link into ${path}: ${error instanceof Error ? error.message : String(error)}`)
}
return { path, links }
}
/**
* Remove a farm this module built. Only entries under `defaultFarmRoot()` are
* accepted, and only links are unlinked: a real directory aborts the removal.
*/
export async function removeFarm(farmPath: string): Promise<void> {
const root = defaultFarmRoot()
const target = resolve(farmPath)
const inside = relativePath(root, target)
if (inside === '' || inside.startsWith('..') || isAbsolute(inside)) {
throw new Error(`farm: not a farm directory: ${farmPath}`)
}
const entries = await readdir(target)
for (const entry of entries) {
await unlinkEntry(join(target, entry))
}
await rmdir(target)
}

View File

@ -25,7 +25,11 @@
* the payload or touching remote-ssh records.
*
* - `GET /workspace-groups/remote-hint?path=...` — presence-only marker hint
* at the requested absolute path or ancestors; never returns marker content.
* at the requested absolute path or ancestors; never returns marker content;
* - `POST /workspace-groups/farm` — gather several folders into one real
* directory of links, so a single session can reach all of them;
* - `DELETE /workspace-groups/farm?path=...` — remove such a farm; only links
* are unlinked, meeting a real directory aborts.
*
* Core workspace.json / session storage is never touched.
*/
@ -59,6 +63,7 @@ import {
type FoldersState,
type RemoteMirrorBaseDiagnostic,
} from './host-folders.ts'
import { buildFarm, removeFarm } from './host-farm.ts'
/** Plugin identity for cordis.yml rows. */
export const name = 'workspace-groups-local'
@ -421,4 +426,70 @@ export function apply(ctx: GroupsContext): void {
sendFolders(res, 200, body, result.revision)
},
}), '@dsh-xhl/workspace-groups: /workspace-groups/folders route')
ctx.effect(() => ctx.webServer.register({
kind: 'exact',
path: '/workspace-groups/farm',
handler: async (req, res) => {
if (req.method === 'POST') {
let raw: unknown
try {
raw = JSON.parse(await readBody(req, MAX_FOLDERS_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 body = raw as { name?: unknown; folders?: unknown } | null
if (body === null || typeof body !== 'object' || !Array.isArray(body.folders)) {
writeError(res, 400, 'workspace-groups: farm needs { name, folders: string[] }')
return
}
let result
try {
// Nothing is copied: every entry is a link to a folder the user owns.
result = await buildFarm({
name: typeof body.name === 'string' ? body.name : 'farm',
folders: body.folders,
})
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
const payload = JSON.stringify(result)
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'Content-Length': Buffer.byteLength(payload),
})
res.end(payload)
return
}
if (req.method === 'DELETE') {
const url = new URL(req.url ?? '/', 'http://localhost')
const target = url.searchParams.get('path')
if (target === null || target.trim() === '') {
writeError(res, 400, 'workspace-groups: farm needs ?path=')
return
}
try {
// Unlinks entries only; a real directory inside aborts the removal
// instead of being deleted with everything under it.
await removeFarm(target)
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
const payload = JSON.stringify({ ok: true })
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'Content-Length': Buffer.byteLength(payload),
})
res.end(payload)
return
}
writeError(res, 405, 'method not allowed')
},
}), '@dsh-xhl/workspace-groups: /workspace-groups/farm route')
}

151
tests/farm.test.ts Normal file
View File

@ -0,0 +1,151 @@
/**
* A farm is the only supported way to put several folders inside one workspace,
* so these tests pin its two dangerous properties: the folders themselves are
* never written to, and removal never deletes anything but links.
*/
import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { buildFarm, defaultFarmRoot, farmDirectoryName, removeFarm } from '../src/host-farm.ts'
const previousHome = process.env.DSH_HOME
let scratch = ''
beforeEach(async () => {
scratch = await mkdtemp(join(tmpdir(), 'wg-farm-'))
process.env.DSH_HOME = join(scratch, 'dsh-home')
await mkdir(process.env.DSH_HOME, { recursive: true })
})
afterEach(async () => {
// Remove farms first: their entries are links, and a recursive delete that
// walked into one would erase the fixture folders of another test.
try {
for (const name of await readdir(defaultFarmRoot())) {
try {
await removeFarm(join(defaultFarmRoot(), name))
} catch {
// A deliberately planted real directory: the scratch delete below is
// safe because it holds no links any more.
}
}
} catch {
// No farm root: nothing was built.
}
if (previousHome === undefined) delete process.env.DSH_HOME
else process.env.DSH_HOME = previousHome
await rm(scratch, { recursive: true, force: true })
})
async function folder(...segments: string[]): Promise<string> {
const path = join(scratch, ...segments)
await mkdir(path, { recursive: true })
return path
}
describe('farm directory', () => {
it('gathers every folder into one directory of links', async () => {
const alpha = await folder('alpha')
const beta = await folder('beta')
const farm = await buildFarm({ name: 'demo', folders: [alpha, beta] })
expect(farm.path).toBe(join(defaultFarmRoot(), 'demo'))
expect(farm.links.map(link => link.name)).toEqual(['alpha', 'beta'])
expect(farm.links.map(link => link.target)).toEqual([alpha, beta])
// A write through the farm lands in the real folder: that is the whole
// point of the feature, so it is asserted rather than assumed.
await writeFile(join(farm.path, 'alpha', 'note.txt'), 'hello', 'utf8')
expect(await readFile(join(alpha, 'note.txt'), 'utf8')).toBe('hello')
})
it('keeps two folders that share a name apart', async () => {
const one = await folder('x', 'project')
const two = await folder('y', 'project')
const farm = await buildFarm({ name: 'dup', folders: [one, two] })
expect(farm.links.map(link => link.name)).toEqual(['project', 'project (2)'])
expect(farm.links.map(link => link.target)).toEqual([one, two])
})
it('ignores the same folder named twice', async () => {
const alpha = await folder('alpha')
const beta = await folder('beta')
const farm = await buildFarm({ name: 'twice', folders: [alpha, beta, alpha] })
expect(farm.links).toHaveLength(2)
})
})
describe('farm validation', () => {
it('refuses fewer than two distinct folders', async () => {
const alpha = await folder('alpha')
await expect(buildFarm({ name: 'solo', folders: [alpha] })).rejects.toThrow(/at least two/u)
})
it('refuses a relative path', async () => {
await expect(buildFarm({ name: 'rel', folders: ['alpha', 'beta'] }))
.rejects.toThrow(/absolute/u)
})
it('refuses a folder that does not exist', async () => {
const alpha = await folder('alpha')
await expect(buildFarm({ name: 'gone', folders: [alpha, join(scratch, 'missing')] }))
.rejects.toThrow(/does not exist/u)
})
it('refuses to reuse an existing farm', async () => {
const alpha = await folder('alpha')
const beta = await folder('beta')
await buildFarm({ name: 'same', folders: [alpha, beta] })
await expect(buildFarm({ name: 'same', folders: [alpha, beta] }))
.rejects.toThrow(/already exists/u)
})
})
describe('farm removal', () => {
it('unlinks the farm but leaves the folders untouched', async () => {
const alpha = await folder('alpha')
const beta = await folder('beta')
await writeFile(join(alpha, 'marker.txt'), 'keep', 'utf8')
const farm = await buildFarm({ name: 'remove', folders: [alpha, beta] })
await removeFarm(farm.path)
await expect(stat(farm.path)).rejects.toThrow()
expect(await readFile(join(alpha, 'marker.txt'), 'utf8')).toBe('keep')
expect((await stat(beta)).isDirectory()).toBe(true)
})
it('refuses a directory outside the farm root', async () => {
const elsewhere = await folder('elsewhere')
await expect(removeFarm(elsewhere)).rejects.toThrow(/not a farm directory/u)
expect((await stat(elsewhere)).isDirectory()).toBe(true)
})
it('refuses to delete a real directory planted inside a farm', async () => {
const alpha = await folder('alpha')
const beta = await folder('beta')
const farm = await buildFarm({ name: 'guard', folders: [alpha, beta] })
const real = join(farm.path, 'real')
await mkdir(real)
await expect(removeFarm(farm.path)).rejects.toThrow(/real directory/u)
expect((await stat(real)).isDirectory()).toBe(true)
})
})
describe('farm naming', () => {
it('turns a workspace title into one safe directory name', () => {
expect(farmDirectoryName('云端记忆系统(云端)')).toBe('云端记忆系统(云端)')
expect(farmDirectoryName('a/b:c')).toBe('a b c')
expect(farmDirectoryName(' ')).toBe('farm')
expect(farmDirectoryName('CON')).toBe('_CON')
expect(farmDirectoryName('trailing. ')).toBe('trailing')
})
})