fix(folders): remote-ssh projects only take mirror subdirectories

@zhangfengshun/dsh-remote-ssh registers a remote workspace as an ordinary workspace whose directory is a local mirror of the remote root. The folder picker would have accepted any local directory for such a project, and sessions started there would never sync. The host now reports the mirror base alongside the overlay, the dialog swaps the picker for a relative-path field for mirror-backed projects, and joinSubpath refuses absolute input and .. escapes so a typo cannot leave the mirror.
This commit is contained in:
qyh15 2026-10-28 15:21:04 +08:00
parent 9ac682c06e
commit d166d4a872
19 changed files with 534 additions and 63 deletions

View File

@ -37,7 +37,7 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30
| `src/index.ts` | 插件入口。`inject = ['webServer']`,注册 4 组路由:`GET /workspace-groups/config`、`GET|PUT /workspace-groups/tabs`、`PUT /workspace-groups/manual`、`GET|PUT /workspace-groups/folders` |
| `src/host-config.ts` | 读用户 YAML 分类规则(默认 `~/.dsh/workspace-groups.yaml`),校验后以 JSON 下发 |
| `src/host-manual.ts` | 运行期分组覆盖(手动分组 + 单工作区归类覆盖),落 `$DSH_HOME/workspace-groups.manual.json` |
| `src/host-folders.ts` | 每个工作区的额外文件夹 + 根目录,落 `$DSH_HOME/workspace-groups.folders.json`(写时严格、读时宽容) |
| `src/host-folders.ts` | 每个工作区的额外文件夹 + 根目录,落 `$DSH_HOME/workspace-groups.folders.json`(写时严格、读时宽容)。另提供 `defaultRemoteMirrorBase()`:`~/.dsh/remote-workspaces`,即 `@zhangfengshun/dsh-remote-ssh` 的本地镜像根,GET 时随文档下发 |
| `src/host-tabs.ts` | 会话标签条的宿主侧持久化。放在宿主是因为**浏览器存储按 origin 隔离,而 origin 含端口**,`dsh web`/测试/桌面壳端口各不相同 |
| `src/context-types.ts` | 本插件消费的 cordis 服务结构类型(第三方插件拿不到 monorepo 内的 `declare module` 合并) |
@ -47,7 +47,7 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30
| --- | --- |
| `src/core/types.ts` | 规则配置类型,零运行时依赖 |
| `src/core/matcher.ts` | 归类与排序的纯函数:工作区归哪个分类、分类/工作区怎么排。宿主校验与客户端建树共用,语义不会漂移 |
| `src/core/folders.ts` | 多文件夹的纯函数:有效文件夹列表、根目录解析、cwd 归属(最具体优先)。宿主校验与客户端建树共用 |
| `src/core/folders.ts` | 多文件夹的纯函数:有效文件夹列表、根目录解析、cwd 归属(最具体优先)、镜像判定与相对子路径拼装(`isUnderBase` / `joinSubpath`)。宿主校验与客户端建树共用 |
浏览器半边(`src/client/`,输出 CJS 闭包工厂):
@ -173,3 +173,9 @@ $installed = "C:\Users\qyh15\.dsh\profiles\desktop\node_modules\@dsh-xhl\workspa
新字段在 `restore*` 里必须原样带过去(`pinned`/`title` 漏带就等于重启丢配置)。
- **package 版本号语义混乱**:仓库 HEAD 里是 `0.1.0`,但提交里写 `feat(v0.7)`;
重建树统一对齐到安装版的 `0.4.2`。发布前自己定一版号。
- **远程(`@zhangfengshun/dsh-remote-ssh`)工作区是镜像,不是真实远端目录**:它用
`workspaceRegistry.create(mirrorDir)` 把远端根登记成普通工作区,`mirrorDir` 就是
`~/.dsh/remote-workspaces/<workspaceId>`。所以对付这类项目时:
额外文件夹只能是镜像内子目录(用 `joinSubpath` 拼、`isUnderBase` 判定,**绝不要让
用户用原生选择器挑任意本地目录**);`cwd` 分区逻辑照常可用,因为会话本身也在本地跑。
真正"服务器上另一个根目录"应当由 SSH 插件单独建成工作区,再用分组归到一起。

View File

@ -94,6 +94,13 @@
clicking it twice reuses the blank session instead of stacking empty ones
- Folders start expanded, so attaching one never hides sessions that were already visible;
collapse state is per-view and intentionally not persisted
- **Remote (SSH) projects are mirror-backed**: `@zhangfengshun/dsh-remote-ssh` registers a
remote workspace as an ordinary workspace whose directory is a LOCAL mirror
(`<home>/.dsh/remote-workspaces/<workspaceId>`) of the remote root. For those projects the
dialog swaps the folder picker for a **relative-path field**, so an extra folder is always a
subdirectory of that mirror — i.e. a directory that also exists on the server. Picking an
unrelated local directory is refused, because a session there would never sync: a separate
remote root should be its own workspace (add it with the SSH plugin), grouped next to this one
### Search & operations
- **Tree-shaped search**: results keep the three-level structure (category → project → matched

View File

@ -77,6 +77,11 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
沿用平台自己的“新建会话”手势,连点两次会复用已打开的空白会话,而不是堆一堆空会话
- 文件夹默认展开,挂上新文件夹不会把本来能看到的会话藏起来;折叠状态只是当前视图状态,
故意不持久化
- **远程(SSH)项目是镜像式工作区**:`@zhangfengshun/dsh-remote-ssh` 把远程工作区登记成
普通工作区,目录是远端根在**本地的镜像**(`<home>/.dsh/remote-workspaces/<工作区id>`)。
这类项目里弹窗会把“挑文件夹”换成**相对路径输入框**,额外文件夹只能是该镜像内的子目录
——也就是服务器上同样存在的目录;挑一个无关的本地目录会被拒绝,因为那种会话永远不会同步。
服务器上另一个不相干的根目录,应该用 SSH 插件单独建成一个工作区,再用分组放到一起
### 搜索与操作
- **树形搜索**:命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮 +

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -2912,6 +2912,21 @@ function isWindowsStyle(path) {
return WINDOWS_DRIVE$1.test(path) || WINDOWS_UNC$1.test(path);
}
/**
* One path with trailing separators removed, spelling preserved (no case
* folding) — the form to STORE. A drive/UNC/root prefix keeps its separator.
* @param path - raw path.
*/
function withoutTrailingSeparator(path) {
if (isWindowsStyle(path)) {
let value = path.replaceAll("/", "\\");
while (value.length > 3 && value.endsWith("\\")) value = value.slice(0, -1);
return value;
}
let value = path;
while (value.length > 1 && value.endsWith("/")) value = value.slice(0, -1);
return value;
}
/**
* Comparison form of one path: trimmed, separator-normalized and, for Windows
* spellings, lower-cased (drive letters and file names are case-insensitive
* there). Trailing separators are dropped except for a drive/UNC/root prefix.
@ -2920,14 +2935,8 @@ function isWindowsStyle(path) {
*/
function canonicalPath(path) {
const trimmed = path.trim();
if (isWindowsStyle(trimmed)) {
let value = trimmed.replaceAll("/", "\\").toLowerCase();
while (value.length > 3 && value.endsWith("\\")) value = value.slice(0, -1);
return value;
}
let value = trimmed;
while (value.length > 1 && value.endsWith("/")) value = value.slice(0, -1);
return value;
const value = withoutTrailingSeparator(trimmed);
return isWindowsStyle(trimmed) ? value.toLowerCase() : value;
}
/**
* Path equality: case-insensitive for Windows-style paths, tolerant of
@ -2969,6 +2978,22 @@ function defaultFoldersPath() {
return resolve(home, FOLDERS_FILE_NAME);
}
/**
* Local mirror root of `@zhangfengshun/dsh-remote-ssh`.
*
* That plugin registers every remote workspace as an ordinary DSH workspace
* whose canonical directory is a LOCAL mirror (`<homedir>/.dsh/remote-workspaces/
* <workspaceId>`) and keeps the real remote path in its own records. Telling the
* browser this base lets it treat such workspaces differently: their extra
* folders must be subdirectories of the mirror, because only those also exist on
* the remote side.
*
* The path is hardcoded there (not read from `DSH_HOME`), so it is hardcoded
* here too — a mismatch would silently disable the distinction.
*/
function defaultRemoteMirrorBase() {
return resolve(homedir(), ".dsh", "remote-workspaces");
}
/**
* True when `path` is absolute in the host platform's spelling: a drive
* letter or UNC prefix on Windows, a leading slash elsewhere.
* @param path - candidate path.
@ -3340,7 +3365,10 @@ function apply(ctx) {
handler: async (req, res) => {
if (req.method === "GET" || req.method === "HEAD") {
const document = await readFoldersDocument(foldersPath);
const body = JSON.stringify(document);
const body = JSON.stringify({
...document,
remoteBase: defaultRemoteMirrorBase()
});
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",

View File

@ -15,12 +15,23 @@
import { type FoldersDocument } from '../core/folders.ts';
/** Host route holding the folder overlay. */
export declare const FOLDERS_ROUTE = "/workspace-groups/folders";
/** One successful read: the overlay plus the mirror base the host reported. */
export interface FoldersSnapshot {
readonly document: FoldersDocument;
/**
* Local mirror root of the remote-ssh plugin, when the host named one.
* Workspaces whose directory lives below it are remote mirrors, so their extra
* folders must be subdirectories of that same mirror.
*/
readonly remoteBase?: string;
}
/**
* Fetch the stored folder overlay.
* @param fetchImpl - fetch implementation (injectable for tests).
* @returns the document; the empty document on any failure.
* @returns the overlay plus the reported mirror base; the empty document on any
* failure.
*/
export declare function loadFolders(fetchImpl?: typeof fetch): Promise<FoldersDocument>;
export declare function loadFolders(fetchImpl?: typeof fetch): Promise<FoldersSnapshot>;
/**
* Store the whole folder overlay.
*

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.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
/** Simplified Chinese dictionary. */
export declare const zh: WorkspaceGroupsDict;

View File

@ -89,3 +89,24 @@ export declare function removeFolder(entry: WorkspaceFolderEntry | undefined, pa
* @param path - folder to make the root.
*/
export declare function setRoot(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry;
/**
* True when `path` is `base` itself or lives somewhere below it, with the same
* separator and case rules as {@link samePath}.
* @param path - candidate path.
* @param base - containing directory.
*/
export declare function isUnderBase(path: string, base: string): boolean;
/**
* Resolve a user-typed SUBPATH against a base directory.
*
* This is what remote (mirror-backed) workspaces need: their canonical
* directory is a local mirror of a remote root, so an extra folder must be a
* directory INSIDE the mirror — that is the only spelling that also exists on
* the remote side. Absolute input and `..` escapes are rejected outright so a
* typo cannot smuggle in an unrelated local directory.
* @param base - the workspace's canonical directory.
* @param relative - typed subpath, either separator style.
* @returns the joined path, or null when the input is empty, absolute, or
* escapes the base.
*/
export declare function joinSubpath(base: string, relative: string): string | null;

View File

@ -7,6 +7,20 @@ export declare const WORKSPACE_ID_LIMIT = 200;
export declare const FOLDER_PATH_LIMIT = 1024;
/** Default overlay location: `$DSH_HOME/workspace-groups.folders.json`. */
export declare function defaultFoldersPath(): string;
/**
* Local mirror root of `@zhangfengshun/dsh-remote-ssh`.
*
* That plugin registers every remote workspace as an ordinary DSH workspace
* whose canonical directory is a LOCAL mirror (`<homedir>/.dsh/remote-workspaces/
* <workspaceId>`) and keeps the real remote path in its own records. Telling the
* browser this base lets it treat such workspaces differently: their extra
* folders must be subdirectories of the mirror, because only those also exist on
* the remote side.
*
* The path is hardcoded there (not read from `DSH_HOME`), so it is hardcoded
* here too — a mismatch would silently disable the distinction.
*/
export declare function defaultRemoteMirrorBase(): string;
/**
* True when `path` is absolute in the host platform's spelling: a drive
* letter or UNC prefix on Windows, a leading slash elsewhere.

View File

@ -1,6 +1,6 @@
{
"name": "@dsh-xhl/workspace-groups",
"version": "0.6.0",
"version": "0.6.1",
"description": "Complete workspace grouping manager for the DSH web sidebar: 分类 → 项目 → 会话 three-level tree with optional per-project folders (multi-root), manual group create/rename/delete, drag-and-drop grouping & ordering with insertion indicator, rule-based auto-classification, tree search, group colour/icon/pin, plus the session tab strip seated in the conversation column head. Sidecar YAML + runtime overlays, zero core-storage intrusion.",
"keywords": [
"dsh",

View File

@ -55,7 +55,7 @@ import type { GroupsBrowserProps } from './contract.ts'
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, folderKey, folderLabel, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'
import { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, FolderRow, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx'
import type { WorkspaceGroupsKey } from './locales.ts'
import { EMPTY_FOLDERS_DOCUMENT, addFolder, effectiveFolders, entryFor, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'
import { EMPTY_FOLDERS_DOCUMENT, addFolder, effectiveFolders, entryFor, isUnderBase, joinSubpath, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'
import { loadFolders, saveFolders } from './folders-persist.ts'
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
import { QuickPanel } from './QuickPanel.tsx'
@ -284,11 +284,17 @@ export function GroupsBrowser({
const [foldersTarget, setFoldersTarget] = useState<WorkspaceId | null>(null)
const [foldersBusy, setFoldersBusy] = useState(false)
const [creatingSessionIn, setCreatingSessionIn] = useState<string | null>(null)
// Local mirror root of the remote-ssh plugin, as reported by the host. A
// project whose directory lives below it is a REMOTE workspace: its folder is
// a mirror of one remote root, so extra folders must be subdirectories of that
// mirror — anything else would exist on this machine only.
const [foldersRemoteBase, setFoldersRemoteBase] = useState<string | null>(null)
useEffect(() => {
let cancelled = false
void loadFolders().then((document) => {
void loadFolders().then((snapshot) => {
if (cancelled) return
setFoldersDoc(document)
setFoldersDoc(snapshot.document)
setFoldersRemoteBase(snapshot.remoteBase ?? null)
})
return () => { cancelled = true }
}, [])
@ -606,10 +612,22 @@ export function GroupsBrowser({
setCollapsedFolderKeys(keys => (keys.includes(key) ? keys.filter(k => k !== key) : [...keys, key]))
}
const isRemoteWorkspace = (workspace: WorkspaceView): boolean => (
foldersRemoteBase !== null && isUnderBase(workspace.path, foldersRemoteBase)
)
const addFolderTo = async (workspaceId: WorkspaceId): Promise<void> => {
if (foldersBusy) return
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
if (workspace === undefined) return
// A remote workspace's directory is a local MIRROR of one remote root; the
// native picker would happily return an unrelated local directory that has
// no remote counterpart, so that path is closed off here and the dialog
// takes a subpath instead.
if (isRemoteWorkspace(workspace)) {
notifyFolder(t('folder.remoteNeedsSubpath'))
return
}
setFoldersBusy(true)
try {
const path = await pickDirectory()
@ -628,6 +646,29 @@ export function GroupsBrowser({
}
}
/**
* Add a folder to a REMOTE workspace by typing a path relative to its mirror.
* The mirror is a copy of the remote root, so `<mirror>/sub` and remote `sub`
* are the same directory — that is the only way an extra folder can mean
* something on both sides.
*/
const addSubpathTo = (workspaceId: WorkspaceId, relative: string): void => {
if (foldersBusy) return
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
if (workspace === undefined) return
const path = joinSubpath(workspace.path, relative)
if (path === null) {
notifyFolder(t('folder.subpathInvalid'))
return
}
const entry = entryFor(foldersDoc, workspaceId as string)
if (effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))) {
notifyFolder(t('folder.duplicate'))
return
}
writeFolderEntry(workspaceId, addFolder(entry, path))
}
const setFolderRoot = (workspaceId: WorkspaceId, path: string): void => {
writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId as string), path))
}
@ -1530,8 +1571,10 @@ export function GroupsBrowser({
t={t}
busy={foldersBusy}
canOpen={openFolderPath !== undefined}
remote={isRemoteWorkspace(workspace)}
onClose={() => { setFoldersTarget(null) }}
onAdd={() => { void addFolderTo(foldersTarget) }}
onAddSubpath={(relative) => { addSubpathTo(foldersTarget, relative) }}
onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }}
onRemove={(path) => { removeFolderFrom(foldersTarget, path) }}
onOpenFolder={(path) => { openFolderPath?.(path) }}
@ -2138,20 +2181,29 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu
* sessions default to); open/remove act per row, and removing the base folder is
* never offered because the workspace's canonical directory cannot be dropped.
*/
function FoldersDialog({ workspace, entry, t, busy, canOpen, onClose, onAdd, onSetRoot, onRemove, onOpenFolder }: {
function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, onClose, onAdd, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView
entry: WorkspaceFolderEntry | undefined
t: GroupsBrowserProps['t']
busy: boolean
canOpen: boolean
/** Remote (mirror-backed) workspace: extra folders are typed subpaths, not picked. */
remote: boolean
onClose: () => void
onAdd: () => void
onAddSubpath: (relative: string) => void
onSetRoot: (path: string) => void
onRemove: (path: string) => void
onOpenFolder: (path: string) => void
}) {
const folders = effectiveFolders(workspace.path, entry)
const root = rootOf(workspace.path, entry)
const [subpath, setSubpath] = useState('')
const submitSubpath = (): void => {
if (subpath.trim() === '') return
onAddSubpath(subpath)
setSubpath('')
}
return (
<Modal
open
@ -2207,7 +2259,32 @@ function FoldersDialog({ workspace, entry, t, busy, canOpen, onClose, onAdd, onS
})}
</div>
<div className="wgFolderListFooter">
<Button variant="outline" disabled={busy} onClick={onAdd}>{t('folder.add')}</Button>
{remote
? (
<>
<p className="wgFolderHint">{t('folder.remoteHint')}</p>
<div className="wgFolderSubpath">
<input
type="text"
className="wgFolderSubpathInput"
value={subpath}
placeholder={t('folder.subpathPlaceholder')}
aria-label={t('folder.subpathLabel')}
disabled={busy}
onChange={event => setSubpath(event.target.value)}
onKeyDown={(event) => {
if (event.key !== 'Enter') return
event.preventDefault()
submitSubpath()
}}
/>
<Button variant="outline" disabled={busy || subpath.trim() === ''} onClick={submitSubpath}>
{t('folder.addSubpath')}
</Button>
</div>
</>
)
: <Button variant="outline" disabled={busy} onClick={onAdd}>{t('folder.add')}</Button>}
</div>
</Modal>
)

View File

@ -21,6 +21,17 @@ import {
/** Host route holding the folder overlay. */
export const FOLDERS_ROUTE = '/workspace-groups/folders'
/** One successful read: the overlay plus the mirror base the host reported. */
export interface FoldersSnapshot {
readonly document: FoldersDocument
/**
* Local mirror root of the remote-ssh plugin, when the host named one.
* Workspaces whose directory lives below it are remote mirrors, so their extra
* folders must be subdirectories of that same mirror.
*/
readonly remoteBase?: string
}
/**
* Read one workspace entry off the wire, dropping the entry when it is
* unusable.
@ -43,31 +54,36 @@ function parseWireEntry(value: unknown): WorkspaceFolderEntry | null {
/**
* Fetch the stored folder overlay.
* @param fetchImpl - fetch implementation (injectable for tests).
* @returns the document; the empty document on any failure.
* @returns the overlay plus the reported mirror base; the empty document on any
* failure.
*/
export async function loadFolders(fetchImpl: typeof fetch = fetch): Promise<FoldersDocument> {
export async function loadFolders(fetchImpl: typeof fetch = fetch): Promise<FoldersSnapshot> {
try {
const response = await fetchImpl(FOLDERS_ROUTE, {
method: 'GET',
// Folders are user state; a cached response would show stale rows.
cache: 'no-store',
})
if (!response.ok) return EMPTY_FOLDERS_DOCUMENT
if (!response.ok) return { document: EMPTY_FOLDERS_DOCUMENT }
const body: unknown = await response.json()
if (typeof body !== 'object' || body === null) return EMPTY_FOLDERS_DOCUMENT
if (typeof body !== 'object' || body === null) return { document: EMPTY_FOLDERS_DOCUMENT }
const source = body as Record<string, unknown>
if (source.version !== 1) return EMPTY_FOLDERS_DOCUMENT
const remoteBase = typeof source.remoteBase === 'string' && source.remoteBase.trim() !== ''
? source.remoteBase.trim()
: undefined
const base = remoteBase === undefined ? {} : { remoteBase }
if (source.version !== 1) return { document: EMPTY_FOLDERS_DOCUMENT, ...base }
if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {
return { version: 1, workspaces: {} }
return { document: { version: 1, workspaces: {} }, ...base }
}
const workspaces: Record<string, WorkspaceFolderEntry> = {}
for (const [workspaceId, value] of Object.entries(source.workspaces)) {
const entry = parseWireEntry(value)
if (entry !== null) workspaces[workspaceId] = entry
}
return { version: 1, workspaces }
return { document: { version: 1, workspaces }, ...base }
} catch {
return EMPTY_FOLDERS_DOCUMENT
return { document: EMPTY_FOLDERS_DOCUMENT }
}
}

View File

@ -47,6 +47,12 @@ export type WorkspaceGroupsKey =
| 'folder.addError'
| 'folder.sessionError'
| 'folder.saveError'
| 'folder.remoteHint'
| 'folder.remoteNeedsSubpath'
| 'folder.subpathLabel'
| 'folder.subpathPlaceholder'
| 'folder.addSubpath'
| 'folder.subpathInvalid'
| 'group.create'
| 'group.createTitle'
| 'group.createPlaceholder'
@ -175,6 +181,12 @@ export const zh: WorkspaceGroupsDict = {
'folder.addError': '添加文件夹失败',
'folder.sessionError': '新建会话失败',
'folder.saveError': '文件夹保存失败',
'folder.remoteHint': '远程(SSH)工作区:本地目录是服务器根目录的镜像,所以这里只能添加镜像内的子目录,填相对路径即可(也会同步到服务器同名目录)',
'folder.remoteNeedsSubpath': '远程工作区请用子目录方式添加文件夹',
'folder.subpathLabel': '相对路径',
'folder.subpathPlaceholder': '例如 data 或 src/generated',
'folder.addSubpath': '添加子目录',
'folder.subpathInvalid': '路径无效:请填工作区内的相对路径,不能用绝对路径或 ..',
'group.create': '新建分组',
'group.createTitle': '新建分组',
'group.createPlaceholder': '分组名称',
@ -302,6 +314,12 @@ export const en: WorkspaceGroupsDict = {
'folder.addError': 'Could not add the folder',
'folder.sessionError': 'Could not start a session',
'folder.saveError': 'Could not save folders',
'folder.remoteHint': 'Remote (SSH) workspace: the local directory mirrors the server root, so only subdirectories of that mirror can be added here — type a path relative to the workspace root',
'folder.remoteNeedsSubpath': 'Remote workspaces take a subdirectory, not a picked folder',
'folder.subpathLabel': 'Relative path',
'folder.subpathPlaceholder': 'e.g. data or src/generated',
'folder.addSubpath': 'Add subdirectory',
'folder.subpathInvalid': 'Invalid path: use a relative path inside the workspace (no absolute paths, no ..)',
'group.create': 'New group',
'group.createTitle': 'New group',
'group.createPlaceholder': 'Group name',

View File

@ -645,6 +645,39 @@
margin-top:8px;
}
/* Remote (mirror-backed) workspaces add a folder by typed subpath, so the
footer grows a hint + input row instead of the picker button. */
.wgFolderHint {
color:var(--dsw-alias-label-secondary,inherit);
margin:0 0 6px;
font-size:12px;
line-height:1.5;
opacity:.85;
}
.wgFolderSubpath {
display:flex;
align-items:center;
gap:6px;
}
.wgFolderSubpathInput {
flex:1 1 auto;
min-width:0;
padding:4px 8px;
border:1px solid var(--dsw-alias-border-l2,#7f7f7f40);
border-radius:6px;
background:var(--dsw-alias-bg-base,transparent);
color:inherit;
font:inherit;
font-size:13px;
}
.wgFolderSubpathInput:focus {
outline:none;
border-color:var(--dsw-alias-label-primary,currentColor);
}
/* Appearance dialog: colour swatches, icon picker grid, pin toggle. */
.wgAppearanceSection {
display:flex;

View File

@ -43,6 +43,22 @@ function isWindowsStyle(path: string): boolean {
return WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path)
}
/**
* One path with trailing separators removed, spelling preserved (no case
* folding) — the form to STORE. A drive/UNC/root prefix keeps its separator.
* @param path - raw path.
*/
function withoutTrailingSeparator(path: string): string {
if (isWindowsStyle(path)) {
let value = path.replaceAll('/', '\\')
while (value.length > 3 && value.endsWith('\\')) value = value.slice(0, -1)
return value
}
let value = path
while (value.length > 1 && value.endsWith('/')) value = value.slice(0, -1)
return value
}
/**
* Comparison form of one path: trimmed, separator-normalized and, for Windows
* spellings, lower-cased (drive letters and file names are case-insensitive
@ -52,16 +68,8 @@ function isWindowsStyle(path: string): boolean {
*/
function canonicalPath(path: string): string {
const trimmed = path.trim()
if (isWindowsStyle(trimmed)) {
let value = trimmed.replaceAll('/', '\\').toLowerCase()
// `C:\` is three characters and already a root; `\\srv\share\` keeps its
// trailing separator only while a further segment remains.
while (value.length > 3 && value.endsWith('\\')) value = value.slice(0, -1)
return value
}
let value = trimmed
while (value.length > 1 && value.endsWith('/')) value = value.slice(0, -1)
return value
const value = withoutTrailingSeparator(trimmed)
return isWindowsStyle(trimmed) ? value.toLowerCase() : value
}
/**
@ -194,3 +202,45 @@ export function setRoot(entry: WorkspaceFolderEntry | undefined, path: string):
if (match === undefined) return { folders: [...folders] }
return { folders: [...folders], root: match }
}
/**
* True when `path` is `base` itself or lives somewhere below it, with the same
* separator and case rules as {@link samePath}.
* @param path - candidate path.
* @param base - containing directory.
*/
export function isUnderBase(path: string, base: string): boolean {
const root = canonicalPath(base)
const target = canonicalPath(path)
if (root === '' || target === '') return false
if (target === root) return true
const separator = isWindowsStyle(root) ? '\\' : '/'
const prefix = root.endsWith(separator) ? root : `${root}${separator}`
return target.startsWith(prefix)
}
/**
* Resolve a user-typed SUBPATH against a base directory.
*
* This is what remote (mirror-backed) workspaces need: their canonical
* directory is a local mirror of a remote root, so an extra folder must be a
* directory INSIDE the mirror — that is the only spelling that also exists on
* the remote side. Absolute input and `..` escapes are rejected outright so a
* typo cannot smuggle in an unrelated local directory.
* @param base - the workspace's canonical directory.
* @param relative - typed subpath, either separator style.
* @returns the joined path, or null when the input is empty, absolute, or
* escapes the base.
*/
export function joinSubpath(base: string, relative: string): string | null {
const root = base.trim()
const raw = relative.trim()
if (root === '' || raw === '') return null
if (WINDOWS_DRIVE.test(raw) || WINDOWS_UNC.test(raw) || raw.startsWith('/')) return null
const segments = raw.split(/[\\/]+/u).filter(segment => segment !== '' && segment !== '.')
if (segments.length === 0) return null
if (segments.includes('..')) return null
const windows = isWindowsStyle(root)
const separator = windows ? '\\' : '/'
return `${withoutTrailingSeparator(root)}${separator}${segments.join(separator)}`
}

View File

@ -47,6 +47,23 @@ export function defaultFoldersPath(): string {
return resolve(home, FOLDERS_FILE_NAME)
}
/**
* Local mirror root of `@zhangfengshun/dsh-remote-ssh`.
*
* That plugin registers every remote workspace as an ordinary DSH workspace
* whose canonical directory is a LOCAL mirror (`<homedir>/.dsh/remote-workspaces/
* <workspaceId>`) and keeps the real remote path in its own records. Telling the
* browser this base lets it treat such workspaces differently: their extra
* folders must be subdirectories of the mirror, because only those also exist on
* the remote side.
*
* The path is hardcoded there (not read from `DSH_HOME`), so it is hardcoded
* here too — a mismatch would silently disable the distinction.
*/
export function defaultRemoteMirrorBase(): string {
return resolve(homedir(), '.dsh', 'remote-workspaces')
}
/**
* True when `path` is absolute in the host platform's spelling: a drive
* letter or UNC prefix on Windows, a leading slash elsewhere.

View File

@ -41,6 +41,7 @@ import {
} from './host-tabs.ts'
import {
defaultFoldersPath,
defaultRemoteMirrorBase,
readFoldersDocument,
validateFoldersDocument,
writeFoldersDocument,
@ -249,9 +250,11 @@ export function apply(ctx: GroupsContext): void {
handler: async (req, res) => {
if (req.method === 'GET' || req.method === 'HEAD') {
// The reader is tolerant by construction (a missing or torn sidecar is
// the empty document), so it cannot fail a GET.
// the empty document), so it cannot fail a GET. `remoteBase` rides along
// so the browser knows which projects are remote-ssh mirrors and must
// only accept subdirectories of their own mirror as extra folders.
const document = await readFoldersDocument(foldersPath)
const body = JSON.stringify(document)
const body = JSON.stringify({ ...document, remoteBase: defaultRemoteMirrorBase() })
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',

View File

@ -22,6 +22,8 @@ const {
effectiveFolders,
entryFor,
folderOfCwd,
isUnderBase,
joinSubpath,
removeFolder,
rootOf,
samePath,
@ -142,5 +144,33 @@ try {
await rm(dir, { recursive: true, force: true })
}
// --- remote (mirror) workspaces ----------------------------------------------
// A remote-ssh workspace is an ordinary workspace whose directory is a local
// mirror, so extra folders must resolve INSIDE the mirror.
const MIRROR_BASE = 'C:\\Users\\me\\.dsh\\remote-workspaces'
const MIRROR_WS = `${MIRROR_BASE}\\ws-1`
check(isUnderBase(MIRROR_WS, MIRROR_BASE), 'a mirror workspace lives under the mirror base')
check(isUnderBase(`${MIRROR_WS}\\sub`, MIRROR_BASE), 'a mirror subdirectory lives under the mirror base')
check(isUnderBase('C:/Users/ME/.dsh/remote-workspaces/ws-1', MIRROR_BASE), 'mirror detection folds separators and case')
check(!isUnderBase('C:\\work\\project', MIRROR_BASE), 'an ordinary project is not a mirror')
check(!isUnderBase('C:\\Users\\me\\.dsh\\remote-workspaces-other\\ws', MIRROR_BASE), 'a name prefix is not inside the base')
equal(joinSubpath(MIRROR_WS, 'data'), `${MIRROR_WS}\\data`, 'subpath joins under the mirror')
equal(joinSubpath(MIRROR_WS, 'src/generated/'), `${MIRROR_WS}\\src\\generated`, 'subpath normalizes separators and drops a trailing slash')
equal(joinSubpath('/home/me/mirror/ws', 'data/raw'), '/home/me/mirror/ws/data/raw', 'POSIX mirrors join with slashes')
equal(joinSubpath(MIRROR_WS, ' '), null, 'a blank subpath is rejected')
equal(joinSubpath(MIRROR_WS, '..\\escape'), null, 'a parent traversal is rejected')
equal(joinSubpath(MIRROR_WS, 'a/../..'), null, 'an embedded traversal is rejected')
equal(joinSubpath(MIRROR_WS, 'D:\\absolute'), null, 'a Windows absolute path is rejected')
equal(joinSubpath(MIRROR_WS, '/absolute'), null, 'a POSIX absolute path is rejected')
equal(joinSubpath(MIRROR_WS, './ok'), `${MIRROR_WS}\\ok`, 'a leading dot segment is dropped')
// A remote workspace's typed subpath then behaves like any other extra folder.
{
const entry = addFolder(undefined, joinSubpath(MIRROR_WS, 'data'))
equal(effectiveFolders(MIRROR_WS, entry), [MIRROR_WS, `${MIRROR_WS}\\data`], 'a typed mirror subpath becomes an extra folder')
equal(folderOfCwd(`${MIRROR_WS}\\data\\file`, MIRROR_WS, entry), `${MIRROR_WS}\\data`, 'sessions under the mirror subpath belong to it')
}
// Success is a single machine-checkable line: the harness pastes this output.
process.stdout.write('folders: all assertions passed\n')