feat(farm): mount multiple folders in one workspace; revert visual merge

This commit is contained in:
newbie 2026-11-12 22:20:28 +08:00
parent 5ec9ea5efe
commit 99a8c811a4
18 changed files with 979 additions and 65 deletions

View File

@ -1,5 +1,15 @@
# 更新日志
## 1.2.0 — 2026-11-12
### 新增
- **Farm 合并工作区**:把同一项目的多个文件夹(含远程镜像与本地目录)在 `$DSH_HOME/workspace-groups/farms/<名称>/` 下用 junction/目录符号链接并排挂起,再注册为一个新工作区。一个会话即可同时读取和改写这些文件夹,不复制、不移动原目录。
- 删除 farm 只 unlink 链接,遇到真实目录立即中止,绝不递归删除用户文件夹。
### 修复
- 侧栏底部 `未归类` / `默认工作区` 在宿主 `[data-sidebar-scrollport]` 中占用剩余高度,真正固定在侧栏底部。
- 撤销 1.1.1 的“同名 member 仅视觉合并”:那只是把两个 workspace 的会话画在一起,不能解决一个项目同时读写多个根目录。
## 1.1.0 — 2026-11-12
### 修复

View File

@ -1479,22 +1479,14 @@ window.__ModuleLoader__.load({
const labels = memberFolderLabels(entry);
const title = workspaceTitle.trim();
if (title !== "") labels.set(workspacePath, title);
const nameOf = (value) => value.replace(/[((][^))]*[))]/gu, "").trim();
const baseName = nameOf(title);
new Set((entry?.members ?? []).map((member) => member.path));
const mergedMembers = /* @__PURE__ */ new Set();
if (baseName !== "") {
for (const member of entry?.members ?? []) if (nameOf(labels.get(member.path) ?? folderLabel(member.path)) === baseName) mergedMembers.add(member.path);
}
const isMergedMember = (path) => [...mergedMembers].some((member) => samePath(member, path));
const extras = effectiveFolders(workspacePath, entry).slice(1).filter((path) => !isMergedMember(path));
const extras = effectiveFolders(workspacePath, entry).slice(1);
if (extras.length === 0) return { sessions };
const root = rootOf(workspacePath, entry);
const base = [];
const byFolder = /* @__PURE__ */ new Map();
for (const node of sessions) {
const owner = folderOfCwd(list.byId[node.id]?.cwd, workspacePath, entry);
if (samePath(owner, workspacePath) || isMergedMember(owner)) {
if (samePath(owner, workspacePath)) {
base.push(node);
continue;
}
@ -4365,7 +4357,7 @@ window.__ModuleLoader__.load({
if (picked === base) return "";
return picked.startsWith(`${base}/`) ? picked.slice(base.length + 1) : null;
}
function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }) {
function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, 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");
@ -4600,6 +4592,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,
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: [
@ -4862,6 +4878,70 @@ window.__ModuleLoader__.load({
]
});
}
// 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;
}
// src/client/quick.ts
/** A session row eligible for quick switching: running, top-level, real. */
function quickEligible(summary) {
@ -6799,6 +6879,31 @@ window.__ModuleLoader__.load({
writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId), 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((item) => item.workspaceId === workspaceId);
if (workspace === void 0) return;
const folders = effectiveFolders(workspace.path, entryFor(foldersDoc, 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);
}
};
/**
* Remove one folder from a project. With `deleteRecord` set — only the
* folder dialog offers it, behind an explicit confirm — a remote member's
* backing record is deleted through the SSH plugin as well (record, native
@ -7926,6 +8031,9 @@ window.__ModuleLoader__.load({
t,
busy: foldersBusy,
canOpen: openFolderPath !== void 0,
onBuildFarm: () => {
buildFarmFor(foldersTarget);
},
remote: isRemoteWorkspace(workspace),
ownerRemotePath: foldersOwnerRemote,
profiles: remoteProfiles,
@ -8545,6 +8653,11 @@ window.__ModuleLoader__.load({
"folder.sectionList": "项目文件夹",
"folder.sectionAdd": "添加文件夹",
"folder.emptyHint": "还没有额外文件夹。下面挂一个目录,它的会话会独立运行,模型也能直接读到里面的文件。",
"folder.mergeTitle": "合并成一个总文件夹",
"folder.mergeAction": "生成总文件夹并添加为工作区",
"folder.mergeHint": "在旁边建一个目录,用链接把这些文件夹放进去,再注册成工作区。不复制、不移动原文件夹;之后在这个工作区里的会话可以同时读写它们。",
"folder.mergeDone": "已生成总文件夹:",
"folder.mergeFailed": "生成总文件夹失败",
"folder.base": "基础文件夹",
"folder.setRoot": "设为根目录",
"folder.rootBadge": "根目录",
@ -8735,6 +8848,11 @@ window.__ModuleLoader__.load({
"folder.sectionList": "Project folders",
"folder.sectionAdd": "Add a folder",
"folder.emptyHint": "No extra folders yet. A folder added below runs its sessions on its own, so the agent can read the files inside it directly.",
"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.base": "Base folder",
"folder.setRoot": "Set as root",
"folder.rootBadge": "Root",

File diff suppressed because one or more lines are too long

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";
// node_modules/.pnpm/js-yaml@4.3.2/node_modules/js-yaml/dist/js-yaml.mjs
function getDefaultExportFromCjs(x) {
@ -3345,6 +3345,155 @@ async function writeFoldersDocument(path, document) {
throw error;
}
}
// 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);
}
// src/index.ts
/** Plugin identity for cordis.yml rows. */
const name = "workspace-groups-local";
@ -3660,5 +3809,65 @@ function apply(ctx) {
res.end(body);
}
}), "@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_MANUAL_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");
}
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, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView;
entry: WorkspaceFolderEntry | undefined;
t: GroupsBrowserProps['t'];
@ -18,6 +18,11 @@ export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remo
/** Live workspace ids, so a member whose workspace is gone can say so. */
knownWorkspaceIds: readonly string[];
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.conflict' | 'folder.removeError' | 'folder.removeRemotePrompt' | 'folder.removeRemoteDelete' | 'folder.removeRemoteOnly' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'folder.cloudSection' | 'folder.profileLabel' | 'folder.remotePathLabel' | 'folder.remotePathPlaceholder' | 'folder.remotePathOrName' | 'folder.createAndAdd' | 'folder.cloudNoteBoth' | 'folder.addRemote' | 'folder.noProfiles' | 'folder.profilesError' | 'folder.cloudTag' | 'folder.localTag' | 'folder.memberMissing' | 'folder.memberNested' | 'folder.alreadyRoot' | 'folder.addAria' | 'folder.tabLocal' | 'folder.tabCloud' | 'folder.pickLocal' | 'folder.localNote' | 'folder.localIntoRemote' | 'folder.cloudNote' | 'folder.browse' | 'folder.browseTitle' | 'folder.browseListAria' | 'folder.browseNote' | 'folder.browseFailed' | 'folder.chooseHere' | 'folder.up' | 'folder.home' | 'folder.refresh' | 'folder.loading' | 'folder.loadingState' | 'folder.loadError' | 'folder.refreshError' | 'folder.retry' | 'folder.retryDraft' | 'folder.discardDraft' | 'folder.conflictDetail' | 'folder.emptyDir' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'group.icon.section.common' | 'group.icon.section.lab' | 'group.icon.section.materials' | 'group.icon.section.characterization' | 'group.icon.section.devices' | 'group.icon.section.emoji' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'section.defaultWorkspace' | 'manual.saveError' | 'manual.conflict' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
export type 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.mergeTitle' | 'folder.mergeAction' | 'folder.mergeHint' | 'folder.mergeDone' | 'folder.mergeFailed' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.conflict' | 'folder.removeError' | 'folder.removeRemotePrompt' | 'folder.removeRemoteDelete' | 'folder.removeRemoteOnly' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'folder.cloudSection' | 'folder.profileLabel' | 'folder.remotePathLabel' | 'folder.remotePathPlaceholder' | 'folder.remotePathOrName' | 'folder.createAndAdd' | 'folder.cloudNoteBoth' | 'folder.addRemote' | 'folder.noProfiles' | 'folder.profilesError' | 'folder.cloudTag' | 'folder.localTag' | 'folder.memberMissing' | 'folder.memberNested' | 'folder.alreadyRoot' | 'folder.addAria' | 'folder.tabLocal' | 'folder.tabCloud' | 'folder.pickLocal' | 'folder.localNote' | 'folder.localIntoRemote' | 'folder.cloudNote' | 'folder.browse' | 'folder.browseTitle' | 'folder.browseListAria' | 'folder.browseNote' | 'folder.browseFailed' | 'folder.chooseHere' | 'folder.up' | 'folder.home' | 'folder.refresh' | 'folder.loading' | 'folder.loadingState' | 'folder.loadError' | 'folder.refreshError' | 'folder.retry' | 'folder.retryDraft' | 'folder.discardDraft' | 'folder.conflictDetail' | 'folder.emptyDir' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'group.icon.section.common' | 'group.icon.section.lab' | 'group.icon.section.materials' | 'group.icon.section.characterization' | 'group.icon.section.devices' | 'group.icon.section.emoji' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'section.defaultWorkspace' | 'manual.saveError' | 'manual.conflict' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
/** Simplified Chinese dictionary. */
export declare const zh: WorkspaceGroupsDict;

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

@ -1,6 +1,6 @@
{
"name": "workspace-groups-remote",
"version": "1.1.1",
"version": "1.2.0",
"description": "Merged DSH bundle: the workspace-groups sidebar manager (category -> project -> session grouped tree, session tab strip) plus dsh-remote-ssh (VSCode Remote-SSH-like remote development: remote workspaces, file access, integrated terminal) in one installable package.",
"keywords": [
"dsh",

View File

@ -44,7 +44,7 @@ function subfolderOf(root: string | null, picked: string): string | null {
return picked.startsWith(`${base}/`) ? picked.slice(base.length + 1) : null
}
export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView
entry: WorkspaceFolderEntry | undefined
t: GroupsBrowserProps['t']
@ -60,6 +60,11 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
/** Live workspace ids, so a member whose workspace is gone can say so. */
knownWorkspaceIds: readonly string[]
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. */
@ -274,6 +279,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} 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 } from './folders-persis
import { createRemoteFolder, createWorkspaceDirectory, deleteRemoteWorkspaceRecord, 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'
@ -1147,6 +1148,34 @@ export function GroupsBrowser({
writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId as string), 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(item => item.workspaceId === workspaceId)
if (workspace === undefined) return
const folders = effectiveFolders(workspace.path, entryFor(foldersDoc, workspaceId as string))
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)
}
}
/**
* Remove one folder from a project. With `deleteRecord` set — only the
* folder dialog offers it, behind an explicit confirm — a remote member's
@ -2255,6 +2284,7 @@ export function GroupsBrowser({
t={t}
busy={foldersBusy}
canOpen={openFolderPath !== undefined}
onBuildFarm={() => { void buildFarmFor(foldersTarget) }}
remote={isRemoteWorkspace(workspace)}
ownerRemotePath={foldersOwnerRemote}
profiles={remoteProfiles}

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

@ -41,6 +41,11 @@ export type WorkspaceGroupsKey =
| 'folder.sectionList'
| 'folder.sectionAdd'
| 'folder.emptyHint'
| 'folder.mergeTitle'
| 'folder.mergeAction'
| 'folder.mergeHint'
| 'folder.mergeDone'
| 'folder.mergeFailed'
| 'folder.base'
| 'folder.setRoot'
| 'folder.rootBadge'
@ -233,6 +238,11 @@ export const zh: WorkspaceGroupsDict = {
'folder.sectionList': '项目文件夹',
'folder.sectionAdd': '添加文件夹',
'folder.emptyHint': '还没有额外文件夹。下面挂一个目录,它的会话会独立运行,模型也能直接读到里面的文件。',
'folder.mergeTitle': '合并成一个总文件夹',
'folder.mergeAction': '生成总文件夹并添加为工作区',
'folder.mergeHint': '在旁边建一个目录,用链接把这些文件夹放进去,再注册成工作区。不复制、不移动原文件夹;之后在这个工作区里的会话可以同时读写它们。',
'folder.mergeDone': '已生成总文件夹:',
'folder.mergeFailed': '生成总文件夹失败',
'folder.base': '基础文件夹',
'folder.setRoot': '设为根目录',
'folder.rootBadge': '根目录',
@ -424,6 +434,11 @@ export const en: WorkspaceGroupsDict = {
'folder.sectionList': 'Project folders',
'folder.sectionAdd': 'Add a folder',
'folder.emptyHint': 'No extra folders yet. A folder added below runs its sessions on its own, so the agent can read the files inside it directly.',
'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.base': 'Base folder',
'folder.setRoot': 'Set as root',
'folder.rootBadge': 'Root',

View File

@ -376,27 +376,14 @@ function applyFolders(
// remains the directory identity for file access; only the LABEL changes.
const title = workspaceTitle.trim()
if (title !== '') labels.set(workspacePath, title)
// A member whose name is the same project (allowing a qualifier such as
// "(云端)") is the same folder from the user's point of view. Fold its
// sessions into the base row instead of painting a second folder row.
const nameOf = (value: string): string => value.replace(/[((][^))]*[))]/gu, '').trim()
const baseName = nameOf(title)
const memberPaths = new Set((entry?.members ?? []).map(member => member.path))
const mergedMembers = new Set<string>()
if (baseName !== '') {
for (const member of entry?.members ?? []) {
if (nameOf(labels.get(member.path) ?? folderLabel(member.path)) === baseName) mergedMembers.add(member.path)
}
}
const isMergedMember = (path: string): boolean => [...mergedMembers].some(member => samePath(member, path))
const extras = effectiveFolders(workspacePath, entry).slice(1).filter(path => !isMergedMember(path))
const extras = effectiveFolders(workspacePath, entry).slice(1)
if (extras.length === 0) return { sessions }
const root = rootOf(workspacePath, entry)
const base: SessionNode[] = []
const byFolder = new Map<string, SessionNode[]>()
for (const node of sessions) {
const owner = folderOfCwd(list.byId[node.id]?.cwd, workspacePath, entry)
if (samePath(owner, workspacePath) || isMergedMember(owner)) {
if (samePath(owner, workspacePath)) {
base.push(node)
continue
}

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

@ -53,6 +53,7 @@ import {
validateRemoteHintPath,
writeFoldersDocument,
} from './host-folders.ts'
import { buildFarm, removeFarm } from './host-farm.ts'
/** Plugin identity for cordis.yml rows. */
export const name = 'workspace-groups-local'
@ -381,4 +382,70 @@ export function apply(ctx: GroupsContext): void {
res.end(body)
},
}), '@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_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 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')
})
})

View File

@ -181,38 +181,6 @@ describe('category appearance on the tree nodes', () => {
})
describe('folder rows use confirmed display names', () => {
it('folds a same-name local member into the base row instead of a second folder', () => {
const owner = workspace('ws-remote', 'C:/mirror/w123', '云端记忆系统(云端)', ['s1'])
const member = workspace('ws-local', 'C:/Users/qyh15/云端记忆系统', '云端记忆系统', ['s2'])
const list = {
ids: ['s1', 's2'],
byId: {
s1: { ...session('s1', 'remote'), cwd: 'C:/mirror/w123' },
s2: { ...session('s2', 'local'), cwd: 'C:/Users/qyh15/云端记忆系统' },
},
current: 's1',
phase: 'ready',
subagentsByParent: {},
} as unknown as SessionListState
const folders: FoldersDocument = {
version: 1,
revision: 1,
workspaces: {
'ws-remote': {
folders: [],
members: [{ path: 'C:/Users/qyh15/云端记忆系统', workspaceId: 'ws-local', kind: 'local' }],
},
},
}
const view = { expandedCategories: [], expandedWorkspaces: ['ws-remote'] }
const top = deriveTopLevel(list, [owner, member], [], CONFIG, view, { categories: [], assignments: {} }, new Map(), folders)
const node = top.find(item => item.workspaceId === 'ws-remote')
expect(node).toBeDefined()
// The member row is gone; both sessions live on the single base row.
expect(node?.folders).toBeUndefined()
expect(node?.sessions.map(item => item.id)).toEqual(['s1', 's2'])
})
it('base row shows the project title, not the local mirror basename', () => {
const ws = workspace('ws-remote', 'C:/mirror/w123', '远程项目', ['s1'])
const folders: FoldersDocument = {