feat: add cloud folders for remote workspaces

This commit is contained in:
qyh15 2026-10-31 17:26:54 +08:00
parent 47227d33c2
commit f47bd65310
18 changed files with 3290 additions and 475 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -2966,6 +2966,7 @@ function samePath(a, b) {
/** File name of the folder sidecar (also the stable error-text prefix). */
const FOLDERS_FILE_NAME = "workspace-groups.folders.json";
const FOLDER_PATH_LIMIT = 1024;
const REMOTE_PATH_LIMIT = 1024;
/** `C:\…` or `C:/…` — a drive-rooted Windows path. */
const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u;
/** `\\server\share` — a Windows UNC path. */
@ -3030,6 +3031,112 @@ async function hasRemoteMarkerHint(path) {
function invalid(detail) {
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`);
}
/** Trim one optional free-form string field, dropping it when unusable. */
function optionalText(value, limit, fail) {
if (value === void 0) return void 0;
if (typeof value !== "string") {
fail("member text fields must be strings");
return;
}
const text = value.trim();
if (text === "" || text.length > limit || text.includes("\0")) return void 0;
return text;
}
/**
* Parse one workspace-backed ("member") folder.
*
* A member names a real DSH workspace whose own sidebar row is hidden while this
* entry lists it; the fields kept here are exactly what the browser needs to
* start a Session in that workspace and to label the row.
* @param value - raw member from the document.
* @param workspaceId - owning workspace id (used in messages and as a guard).
* @param folders - plain folder paths already accepted for this workspace.
* @param members - member folders already accepted for this workspace.
* @param fail - strict-mode reporter (throws) / tolerant no-op.
* @returns the normalized member, or undefined when unusable.
*/
function parseMember(value, workspaceId, folders, members, fail) {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
fail("member folders must be objects");
return;
}
const source = value;
const rawPath = source.path;
if (typeof rawPath !== "string") {
fail("member folder path must be a string");
return;
}
const path = rawPath.trim();
if (path === "" || path.length > 1024 || path.includes("\0")) {
fail(`member folder path must be 1-${FOLDER_PATH_LIMIT} characters without NUL`);
return;
}
if (!isAbsoluteFolderPath(path)) {
fail(`member folder path "${path}" must be absolute`);
return;
}
if (folders.some((folder) => samePath(folder, path)) || members.some((member) => samePath(member.path, path))) {
fail(`duplicate folder path "${path}"`);
return;
}
const rawId = source.workspaceId;
if (typeof rawId !== "string") {
fail("member workspaceId must be a string");
return;
}
const memberWorkspaceId = rawId.trim();
if (memberWorkspaceId === "" || memberWorkspaceId.length > 200 || memberWorkspaceId.includes("\0")) {
fail(`member workspaceId must be 1-200 characters without NUL`);
return;
}
if (memberWorkspaceId === workspaceId) {
fail("a workspace cannot be a member folder of itself");
return;
}
const kind = source.kind;
if (kind !== "local" && kind !== "remote") {
fail("member kind must be \"local\" or \"remote\"");
return;
}
const title = optionalText(source.title, FOLDER_PATH_LIMIT, fail);
const keepTitle = title === void 0 ? {} : { title };
if (kind === "local") return {
path,
workspaceId: memberWorkspaceId,
kind,
...keepTitle
};
const rawRemote = source.remotePath;
if (typeof rawRemote !== "string") {
fail("a remote member folder needs its remotePath");
return;
}
const remotePath = rawRemote.trim();
if (remotePath === "" || remotePath.length > 1024 || remotePath.includes("\0")) {
fail(`member remotePath must be 1-${REMOTE_PATH_LIMIT} characters without NUL`);
return;
}
const rawProfile = source.profileId;
if (typeof rawProfile !== "string") {
fail("a remote member folder needs its profileId");
return;
}
const profileId = rawProfile.trim();
if (profileId === "" || profileId.length > 200) {
fail(`member profileId must be 1-200 characters`);
return;
}
const recordId = optionalText(source.recordId, 200, fail);
return {
path,
workspaceId: memberWorkspaceId,
kind,
remotePath,
profileId,
...recordId === void 0 ? {} : { recordId },
...keepTitle
};
}
/**
* Parse one workspace entry.
* @param value - raw entry from the document.
@ -3088,19 +3195,32 @@ function parseFolderEntry(value, workspaceId, strict) {
}
folders.push(path);
}
const members = [];
if (source.members !== void 0) {
if (!Array.isArray(source.members)) fail("members must be a list");
else {
if (strict && source.members.length > 16) invalid(`workspace "${workspaceId}": at most 16 member folders`);
for (const candidate of source.members) {
const member = parseMember(candidate, workspaceId, folders, members, fail);
if (member !== void 0) members.push(member);
if (members.length >= 16) break;
}
}
}
let root;
if (source.root !== void 0) {
if (typeof source.root !== "string") fail("root must be a string");
else {
const candidate = source.root.trim();
const member = folders.find((folder) => samePath(folder, candidate));
const member = [...folders, ...members.map((entry) => entry.path)].find((folder) => samePath(folder, candidate));
if (member === void 0) fail(`root "${candidate}" must name one of folders`);
else root = member;
}
}
if (folders.length === 0 && root === void 0) return void 0;
if (folders.length === 0 && members.length === 0 && root === void 0) return void 0;
return {
folders,
...members.length === 0 ? {} : { members },
...root === void 0 ? {} : { root }
};
}

29
lib/types/client/FoldersDialog.d.ts vendored Normal file
View File

@ -0,0 +1,29 @@
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
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 }: {
workspace: WorkspaceView;
entry: WorkspaceFolderEntry | undefined;
t: GroupsBrowserProps['t'];
busy: boolean;
canOpen: boolean;
/** Remote (mirror-backed) workspace: extra folders can also be typed subpaths. */
remote: boolean;
/** Remote root of a cloud owner, so a browsed subdirectory joins as a subfolder. */
ownerRemotePath: string | null;
/** SSH connections, `null` while loading or when the remote-ssh plugin is absent. */
profiles: readonly RemoteProfileSummary[] | null;
profilesError: string | null;
/** Live workspace ids, so a member whose workspace is gone can say so. */
knownWorkspaceIds: readonly string[];
onClose: () => void;
/** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => void;
/** Register one cloud folder: returns true once it is stored. */
onAddRemote: (profileId: string, remotePath: string) => Promise<boolean>;
onAddSubpath: (relative: string) => Promise<boolean>;
onSetRoot: (path: string) => void;
onRemove: (path: string) => void;
onOpenFolder: (path: string) => void;
}): import("react").JSX.Element;

View File

@ -2,7 +2,78 @@ export interface RemoteFolderWorkspace {
mirrorPath: string;
remotePath: string;
profileId: string;
/** Native DSH workspace registered for the mirror root ('' when unregistered). */
workspaceId: string;
/** remote-ssh's own record id ('' when it cannot be resolved). */
recordId: string;
}
/** One SSH connection the remote plugin offers, as the picker needs it. */
export interface RemoteProfileSummary {
id: string;
name: string;
host: string;
user: string;
/** Directory the connection opens on (`~` when the plugin leaves it empty). */
remoteRoot: string;
}
/** One row of a remote directory listing. */
export interface RemoteDirEntry {
name: string;
type: 'directory' | 'file';
size: number;
}
/** A remote directory and its children, as the cloud folder picker needs them. */
export interface RemoteDirListing {
/** Path as requested (`~`, a relative name or an absolute path). */
requested: string;
/** Absolute path the remote shell resolved it to (`requested` when unknown). */
resolved: string;
entries: readonly RemoteDirEntry[];
}
/** Parent of a directory path, or null where going up stops (`~`, `/`, root). */
export declare function remoteDirParent(path: string): string | null;
/** Join a child directory name onto a remote directory path. */
export declare function remoteDirJoin(base: string, name: string): string;
/**
* List one remote directory through the SSH plugin's own pooled session, so
* password auth, ProxyJump and host-key handling stay where they already work.
* @param profileId - SSH connection to browse.
* @param path - directory to list; empty means the connection's remote root.
* @param fetchImpl - fetch implementation (tests inject one).
*/
export declare function listRemoteDirectory(profileId: string, path: string, fetchImpl?: typeof fetch): Promise<RemoteDirListing>;
/** A newly registered remote (mirror-backed) folder workspace. */
export interface CreatedRemoteFolder {
/** Absolute LOCAL mirror path — the member workspace's canonical directory. */
path: string;
/** Native DSH workspace id that now backs the folder row. */
workspaceId: string;
/** remote-ssh's own record id (used to delete the record again). */
recordId: string;
remotePath: string;
profileId: string;
title: string;
/** True when an existing record for the same profile + remote path was taken over. */
reused: boolean;
}
/**
* The SSH connections available for a cloud folder, or null when the
* `@zhangfengshun/dsh-remote-ssh` plugin does not answer at all.
* @param fetchImpl - fetch implementation (tests inject one).
*/
export declare function listRemoteProfiles(fetchImpl?: typeof fetch): Promise<RemoteProfileSummary[] | null>;
/**
* Register one cloud folder: the SSH plugin creates the local mirror, writes the
* connection marker and registers a real DSH workspace for it — exactly what its
* own "new remote workspace" flow does. The returned native workspace id backs
* the folder row, and the workspace's own sidebar row is hidden once the entry
* lists it (see `absorbedWorkspaceIds`).
* @param profileId - SSH connection to use.
* @param remotePath - remote directory (`~`, `~/proj`, `/srv/proj`).
* @param title - optional display title; the plugin derives one from the path.
* @param fetchImpl - fetch implementation (tests inject one).
*/
export declare function createRemoteFolder(profileId: string, remotePath: string, title?: string, fetchImpl?: typeof fetch): Promise<CreatedRemoteFolder>;
/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */
export declare function remoteFolderWorkspace(path: string, remoteBase: string | null, fetchImpl?: typeof fetch): Promise<RemoteFolderWorkspace | null>;
/** Single-segment names match DSH createDirectory(path, name). */

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

View File

@ -111,12 +111,30 @@ export declare const UNCATEGORIZED_KEY = "\u672A\u5206\u7C7B";
export declare function isDockedCategoryKey(key: string): boolean;
/** Directory display label: basename of the path (both separators accepted). */
export declare function workspaceLabel(cwd: string | undefined): string;
/** A workspace-backed ("member") folder resolved against the workspace list. */
export interface MemberWorkspaces {
/** Member workspace id → owning workspace id (the rows to hide). */
absorbed: ReadonlyMap<string, string>;
/** Owning workspace id → member workspaces in stored folder order. */
byOwner: ReadonlyMap<string, readonly WorkspaceView[]>;
}
/**
* Resolve the workspace-backed folders of every project.
*
* A member folder is a real DSH workspace whose OWN row must disappear: its
* sessions are rendered under its owner's folder row instead, so one project can
* carry local and cloud (SSH-mirrored) folders at once. Members the Host no
* longer knows are dropped from the index — the folder row survives (its path is
* still stored) but shows no sessions.
* @param workspaces - real workspaces in Host order.
* @param folders - per-workspace extra folders + members + root.
*/
export declare function memberWorkspaces(workspaces: readonly WorkspaceView[], folders?: FoldersDocument): MemberWorkspaces;
/**
* Display label of one folder: the last path segment. A drive root (`C:\`) or
* the POSIX root has no segment, so the whole path is the honest label.
* @param path - absolute folder path.
*/
export declare function folderLabel(path: string): string;
*/ export declare function folderLabel(path: string): string;
/** Stable identity of one folder row (same path may live under two workspaces). */
export declare function folderKey(workspaceId: WorkspaceId, path: string): string;
/**
@ -180,7 +198,7 @@ export interface SearchMatchSet {
export declare function deriveSearchMatches(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, query: string, archivedSessionIds: readonly SessionId[], content: {
items: readonly SessionSearchResultItem[];
hasMore: boolean;
}, limit: number): SearchMatchSet;
}, limit: number, folders?: FoldersDocument): SearchMatchSet;
/** Search tree: group folders plus top-level (ungrouped) matched workspaces. */
export interface SearchTree {
/** Group folders containing matched sessions, in display order. */

View File

@ -16,9 +16,45 @@
* Everything here is pure and platform-agnostic: it imports no React, no DOM
* and no cordis so plain Node (the verifier, the host route) can load it.
*/
/** Kind of a member folder: a plain local directory, or an SSH-mirrored one. */
export type FolderMemberKind = 'local' | 'remote';
/**
* A folder row that is backed by its OWN DSH workspace ("member").
*
* Plain extra folders ( {@link WorkspaceFolderEntry.folders} ) live inside the
* owner's canonical directory tree and their sessions run with the OWNER's
* workspace id. A member has a directory the owner cannot reach that way — a
* remote (mirror-backed) folder, or a local directory added to a remote project
* — so the platform registers a real workspace for it and the row delegates
* session creation to that workspace id. The member's own workspace row is
* hidden from the sidebar while some entry lists it (see
* {@link absorbedWorkspaceIds}), so the project reads as one project with both
* kinds of folders.
*/
export interface FolderMember {
/** Absolute LOCAL path of the member workspace (its canonical directory). */
readonly path: string;
/** Native DSH workspace id backing this folder row. */
readonly workspaceId: string;
readonly kind: FolderMemberKind;
/** Remote root, when `kind` is 'remote' (`~`, `~/proj`, `/srv/proj`). */
readonly remotePath?: string;
/** SSH connection profile id, when `kind` is 'remote'. */
readonly profileId?: string;
/** remote-ssh's own record id, when `kind` is 'remote'. */
readonly recordId?: string;
/** Display title the platform gave the member workspace. */
readonly title?: string;
}
/** Folders attached to one workspace: EXTRA folders only (the base is implicit). */
export interface WorkspaceFolderEntry {
/**
* Plain local extra folders: directories the owner workspace can address
* directly, so their sessions keep the owner's workspace id.
*/
readonly folders: readonly string[];
/** Workspace-backed extra folders (remote mirrors, or local on a remote owner). */
readonly members?: readonly FolderMember[];
readonly root?: string;
}
/** The whole `workspace-groups.folders.json` document. */
@ -49,6 +85,34 @@ export declare function entryFor(doc: FoldersDocument, workspaceId: string): Wor
* @param entry - saved folder entry, if any.
*/
export declare function effectiveFolders(workspacePath: string, entry: WorkspaceFolderEntry | undefined): readonly string[];
/**
* The member record behind one folder path, when that folder is workspace-backed.
* @param entry - saved folder entry, if any.
* @param path - folder path as stored.
*/
export declare function memberOf(entry: WorkspaceFolderEntry | undefined, path: string): FolderMember | undefined;
/**
* Every member folder of one owner workspace, in stored order.
* @param doc - folders document.
* @param ownerWorkspaceId - workspace the members hang off.
*/
export declare function membersOf(doc: FoldersDocument, ownerWorkspaceId: string): readonly FolderMember[];
/**
* Member workspace id → owning workspace id.
*
* These are the workspaces whose own row disappears from the sidebar: their
* sessions render under the owning project's folder row instead. A workspace
* that is itself an owner (it carries an entry) is never absorbed — absorbing
* it would hide a project together with the folders nested below it.
* @param doc - folders document.
*/
export declare function absorbedWorkspaceIds(doc: FoldersDocument): ReadonlyMap<string, string>;
/**
* True when the entry carries neither a plain folder nor a member, i.e. it can
* be dropped from the sidecar instead of being written empty.
* @param entry - folder entry.
*/
export declare function isEmptyEntry(entry: WorkspaceFolderEntry | undefined): boolean;
/**
* The folder new sessions start in by default.
* @param workspacePath - canonical directory of the workspace.
@ -74,9 +138,17 @@ export declare function folderOfCwd(cwd: string | undefined, workspacePath: stri
*/
export declare function addFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry;
/**
* Drop an extra folder. A root that pointed at it is cleared, so the workspace
* falls back to its own directory instead of referencing a folder it no longer
* has.
* Append a workspace-backed folder. Idempotent under `samePath`: a later call
* for the same path replaces the stored member (so a re-registered workspace id
* wins) instead of stacking a duplicate row.
* @param entry - current entry, or undefined for a workspace with no extras.
* @param member - member record to store.
*/
export declare function addMember(entry: WorkspaceFolderEntry | undefined, member: FolderMember): WorkspaceFolderEntry;
/**
* Drop an extra folder, plain or workspace-backed. A root that pointed at it is
* cleared, so the workspace falls back to its own directory instead of
* referencing a folder it no longer has.
* @param entry - current entry, or undefined.
* @param path - folder path to drop.
*/

View File

@ -3,8 +3,10 @@ import { type FoldersDocument } from './core/folders.ts';
export declare const FOLDERS_FILE_NAME = "workspace-groups.folders.json";
/** Hard limits enforced at the write boundary. */
export declare const FOLDERS_PER_WORKSPACE_LIMIT = 32;
export declare const MEMBERS_PER_WORKSPACE_LIMIT = 16;
export declare const WORKSPACE_ID_LIMIT = 200;
export declare const FOLDER_PATH_LIMIT = 1024;
export declare const REMOTE_PATH_LIMIT = 1024;
/** Default overlay location: `$DSH_HOME/workspace-groups.folders.json`. */
export declare function defaultFoldersPath(): string;
/**

View File

@ -0,0 +1,447 @@
/**
* The folder dialog of one workspace row: the base folder first, then every
* extra folder in stored order. A row is chosen as the root (the folder new
* sessions default to); open/remove act per row, and the base folder is never
* removable because the workspace's canonical directory cannot be dropped.
*
* Folders come in two kinds, and the add area switches between them:
* · local — a directory picked on this machine (`pickDirectory`);
* · cloud — a directory on an SSH host, browsed through the SSH plugin's own
* pooled session, then registered as a mirror-backed workspace.
*
* Cloud browsing lives here rather than behind a second modal: the dialog body
* swaps to the remote tree, so no stacked overlays are needed and the current
* location stays readable at the top.
*/
import { useEffect, useState } from 'react'
import {
Button,
IconFolderOpenOutlineRegular,
IconTrashOutlineRegular,
Modal,
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
import { effectiveFolders, memberOf, rootOf, samePath, type WorkspaceFolderEntry } from '../core/folders.ts'
import type { GroupsBrowserProps } from './contract.ts'
import { folderLabel } from './tree.ts'
import {
listRemoteDirectory,
remoteDirJoin,
remoteDirParent,
type RemoteDirEntry,
type RemoteProfileSummary,
} from './folder-directory.ts'
/** Which kind of folder the add area currently offers. */
type AddMode = 'local' | 'cloud'
/** Relative path of `picked` inside `root`: '' for the root itself, null outside. */
function subfolderOf(root: string | null, picked: string): string | null {
if (root === null) return null
const base = root.trim().replace(/\/+$/u, '')
if (base === '') return null
if (picked === base) return ''
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 }: {
workspace: WorkspaceView
entry: WorkspaceFolderEntry | undefined
t: GroupsBrowserProps['t']
busy: boolean
canOpen: boolean
/** Remote (mirror-backed) workspace: extra folders can also be typed subpaths. */
remote: boolean
/** Remote root of a cloud owner, so a browsed subdirectory joins as a subfolder. */
ownerRemotePath: string | null
/** SSH connections, `null` while loading or when the remote-ssh plugin is absent. */
profiles: readonly RemoteProfileSummary[] | null
profilesError: string | null
/** Live workspace ids, so a member whose workspace is gone can say so. */
knownWorkspaceIds: readonly string[]
onClose: () => void
/** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => void
/** Register one cloud folder: returns true once it is stored. */
onAddRemote: (profileId: string, remotePath: string) => Promise<boolean>
onAddSubpath: (relative: string) => Promise<boolean>
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 [addMode, setAddMode] = useState<AddMode>('local')
const [profileId, setProfileId] = useState('')
const [remotePath, setRemotePath] = useState('')
const [browsing, setBrowsing] = useState(false)
const [notice, setNotice] = useState<string | null>(null)
const profileChoices = profiles ?? []
const knownIds = new Set(knownWorkspaceIds)
const selectedProfile = profileChoices.some(profile => profile.id === profileId)
? profileId
: (profileChoices[0]?.id ?? '')
const currentProfile = profileChoices.find(profile => profile.id === selectedProfile)
/** One field, two shapes: a bare name creates a subdirectory inside THIS
* project's remote root, anything with a separator registers a new cloud
* workspace. Keeping them in one field removed a whole extra row from a
* ~330px wide dialog. */
const typed = remotePath.trim()
const asSubfolder = remote && typed !== '' && !/[/\\~]/u.test(typed)
const submitAdd = (): void => {
if (typed === '' || busy) return
if (asSubfolder) {
void onAddSubpath(typed).then(success => { if (success) setRemotePath('') })
return
}
if (selectedProfile === '') return
void onAddRemote(selectedProfile, typed).then((success) => {
if (!success) return
setRemotePath('')
setBrowsing(false)
})
}
if (browsing && currentProfile !== undefined) {
return (
<RemoteFolderPicker
profile={currentProfile}
startPath={remotePath.trim() === '' ? (ownerRemotePath ?? currentProfile.remoteRoot) : remotePath.trim()}
t={t}
busy={busy}
onPick={(picked) => {
const relative = subfolderOf(ownerRemotePath, picked)
if (relative === '' && ownerRemotePath !== null) {
// Already this project's base folder: nothing to add, say so.
setNotice(t('folder.alreadyRoot'))
setBrowsing(false)
return
}
if (relative !== null) {
// Inside the owner's remote root: one folder of this mirror, no second copy.
void onAddSubpath(relative).then((success) => {
if (success) {
setNotice(null)
setBrowsing(false)
}
})
return
}
setRemotePath(picked)
setBrowsing(false)
}}
onCancel={() => { setBrowsing(false) }}
/>
)
}
const cloudAvailable = profiles !== null
const extraFolders = folders.length > 1
// A cloud project's directory is a generated mirror id, so the header names the
// place a human recognises: the remote root, when we managed to read it.
const ownerPath = remote ? (ownerRemotePath ?? workspace.path) : workspace.path
return (
<Modal
open
onClose={onClose}
closeLabel={t('close')}
title={t('folder.title')}
footer={(
<Button variant="primary" onClick={onClose}>{t('folder.done')}</Button>
)}
>
<div className="wgFolderBody">
<header className="wgFolderHead">
<span className="wgFolderHeadName" title={workspace.title}>{workspace.title}</span>
<code className="wgFolderHeadPath" title={ownerPath}>{ownerPath}</code>
</header>
<section className="wgFolderSection">
<div className="wgFolderSectionTitle">{t('folder.sectionList')}</div>
<div className="wgFolderList" role="list" aria-label={t('folder.listAria')}>
{folders.map((path, index) => {
const isBase = index === 0
const isRoot = samePath(path, root)
const member = memberOf(entry, path)
// A cloud member's directory is a generated mirror id, so the dialog
// names it by its remote path/title, exactly like the sidebar row does.
// The base folder is named by the workspace title for the same reason.
const label = isBase
? workspace.title
: member?.kind === 'remote'
? (member.title ?? folderLabel(member.remotePath ?? path))
: folderLabel(path)
const displayPath = member === undefined
? (isBase ? ownerPath : path)
: (member.remotePath ?? member.path)
// A member whose own workspace disappeared (deleted outside this
// overlay, or an SSH record the plugin dropped) keeps its row so the
// user can still remove it, but says that it cannot run sessions.
const memberGone = member !== undefined && !knownIds.has(member.workspaceId)
return (
<div key={path} className="wgFolderListRow" role="listitem" data-active={isRoot}>
<label className="wgFolderRootPick" title={t('folder.rootBadge')}>
<input
type="radio"
className="wgFolderRadio"
name="wg-folder-root"
checked={isRoot}
aria-label={`${t('folder.rootBadge')} ${label}`}
onChange={() => { onSetRoot(path) }}
/>
</label>
<span className="wgFolderEntry">
<span className="wgFolderListLabel" title={path}>{label}</span>
<code className="wgFolderListPath" title={displayPath}>{displayPath}</code>
</span>
<span className="wgFolderListTags">
{isBase && <span className="wgFolderListTag" data-tone="base">{t('folder.base')}</span>}
{isRoot && <span className="wgFolderListTag" data-tone="root">{t('folder.rootBadge')}</span>}
{member !== undefined && (
<span className="wgFolderListTag" data-tone={member.kind === 'remote' ? 'cloud' : 'local'}>
{member.kind === 'remote' ? t('folder.cloudTag') : t('folder.localTag')}
</span>
)}
{memberGone && (
<span className="wgFolderListTag" data-tone="danger" role="alert">{t('folder.memberMissing')}</span>
)}
</span>
<span className="wgFolderListActions">
{canOpen && (
<button
type="button"
className="wgIconButton"
aria-label={`${t('workspace.openInFolder')} ${label}`}
onClick={() => { onOpenFolder(path) }}
>
<IconFolderOpenOutlineRegular size={16} />
</button>
)}
{!isBase && (
<button
type="button"
className="wgIconButton"
aria-label={`${t('folder.remove')} ${label}`}
onClick={() => { onRemove(path) }}
>
<IconTrashOutlineRegular />
</button>
)}
</span>
</div>
)
})}
</div>
{!extraFolders && <p className="wgFolderEmpty">{t('folder.emptyHint')}</p>}
</section>
<section className="wgFolderAdd">
<div className="wgFolderSectionTitle">{t('folder.sectionAdd')}</div>
<div className="wgFolderSegmented" role="tablist" aria-label={t('folder.addAria')}>
<button
type="button"
role="tab"
className="wgFolderTab"
aria-selected={addMode === 'local'}
onClick={() => { setAddMode('local'); setNotice(null) }}
>
{t('folder.tabLocal')}
</button>
{cloudAvailable && (
<button
type="button"
role="tab"
className="wgFolderTab"
aria-selected={addMode === 'cloud'}
onClick={() => { setAddMode('cloud'); setNotice(null) }}
>
{t('folder.tabCloud')}
</button>
)}
</div>
{notice !== null && <p className="wgFolderNote" role="status">{notice}</p>}
{addMode === 'local'
? (
<div className="wgFolderLocalPane">
{/* Full width, own line: the action used to share a row with the
consequence text and the label wrapped onto two lines. */}
<button type="button" className="wgFolderPick" disabled={busy} onClick={onAddFolder}>
<span className="wgFolderPickPlus" aria-hidden>+</span>
<span>{t('folder.pickLocal')}</span>
</button>
<p className="wgFolderHint">{remote ? t('folder.localIntoRemote') : t('folder.localNote')}</p>
</div>
)
: (
<>
{/* One control per line: the dialog body is only ~330px wide, so a
profile select, a path field and a labelled button cannot share
a row without squeezing one of them. Browsing therefore docks
into the path field as an icon instead of its own button. */}
<div className="wgFolderStack">
{profileChoices.length === 0
? <p className="wgFolderNote">{t('folder.noProfiles')}</p>
: (
<select
className="wgFolderSubpathInput wgFolderSelect"
value={selectedProfile}
aria-label={t('folder.profileLabel')}
disabled={busy}
onChange={event => setProfileId(event.target.value)}
>
{profileChoices.map(profile => (
<option key={profile.id} value={profile.id}>
{profile.host === '' ? profile.name : `${profile.name} (${profile.user}@${profile.host})`}
</option>
))}
</select>
)}
<div className="wgFolderField">
<input
type="text"
className="wgFolderSubpathInput wgFolderFieldInput"
value={remotePath}
placeholder={t(remote ? 'folder.remotePathOrName' : 'folder.remotePathPlaceholder')}
aria-label={t(remote ? 'folder.remotePathOrName' : 'folder.remotePathLabel')}
disabled={busy}
onChange={event => setRemotePath(event.target.value)}
onKeyDown={(event) => {
if (event.key !== 'Enter') return
event.preventDefault()
submitAdd()
}}
/>
<button
type="button"
className="wgFolderFieldAction"
title={t('folder.browse')}
aria-label={t('folder.browse')}
disabled={busy || currentProfile === undefined}
onClick={() => { setBrowsing(true) }}
>
<IconFolderOpenOutlineRegular size={15} />
</button>
</div>
<div className="wgFolderActions">
<Button
variant="primary"
disabled={busy || typed === '' || (!asSubfolder && selectedProfile === '')}
onClick={submitAdd}
>
{t(asSubfolder ? 'folder.createAndAdd' : 'folder.addRemote')}
</Button>
</div>
</div>
<p className="wgFolderHint">{t(remote ? 'folder.cloudNoteBoth' : 'folder.cloudNote')}</p>
</>
)}
{profilesError !== null && (
<p className="wgFolderNote" role="alert">{t('folder.profilesError')}: {profilesError}</p>
)}
</section>
</div>
</Modal>
)
}
/**
* Browse one SSH host and pick a directory. Entries come from the SSH plugin's
* `listDir`, so the local machine never runs a copy of the remote tree and the
* connection's own auth (key, password, ProxyJump) is reused unchanged.
*/
function RemoteFolderPicker({ profile, startPath, t, busy, onPick, onCancel }: {
profile: RemoteProfileSummary
startPath: string
t: GroupsBrowserProps['t']
busy: boolean
onPick: (path: string) => void
onCancel: () => void
}) {
const [path, setPath] = useState(startPath)
const [resolved, setResolved] = useState(startPath)
const [entries, setEntries] = useState<readonly RemoteDirEntry[]>([])
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
const [reloadKey, setReloadKey] = useState(0)
useEffect(() => {
let live = true
setLoading(true)
setError(null)
void listRemoteDirectory(profile.id, path).then(
(listing) => {
if (!live) return
setEntries(listing.entries)
setResolved(listing.resolved)
setLoading(false)
// The shell resolved `~` or a relative name: browse the real place next
// so "up" and the children join behave like an absolute path.
if (listing.resolved !== path) setPath(listing.resolved)
},
(reason: unknown) => {
if (!live) return
setError(reason instanceof Error ? reason.message : String(reason))
setLoading(false)
},
)
return () => { live = false }
}, [profile.id, path, reloadKey])
const parent = remoteDirParent(resolved)
const directories = entries.filter(entry => entry.type === 'directory')
const choose = (): void => { onPick(resolved) }
return (
<Modal
open
onClose={onCancel}
closeLabel={t('close')}
title={`${t('folder.browseTitle')} · ${profile.name}`}
footer={(
<>
<Button variant="outline" onClick={onCancel}>{t('cancel')}</Button>
<Button variant="primary" disabled={busy || loading || error !== null} onClick={choose}>
{t('folder.chooseHere')}
</Button>
</>
)}
>
<div className="wgRemoteBar">
<code className="wgRemotePath" title={resolved}>{resolved}</code>
<span className="wgRemoteActions">
<Button variant="outline" disabled={parent === null || loading} onClick={() => { if (parent !== null) setPath(parent) }}>
{t('folder.up')}
</Button>
<Button variant="outline" disabled={loading} onClick={() => { setPath(profile.remoteRoot) }}>
{t('folder.home')}
</Button>
<Button variant="outline" disabled={loading} onClick={() => { setReloadKey(key => key + 1) }}>
{t('folder.refresh')}
</Button>
</span>
</div>
<div className="wgRemoteList" role="list" aria-label={t('folder.browseListAria')}>
{loading && <p className="wgFolderNote">{t('folder.loading')}</p>}
{!loading && error !== null && (
<p className="wgFolderNote" role="alert">{t('folder.browseFailed')}: {error}</p>
)}
{!loading && error === null && directories.length === 0 && (
<p className="wgFolderNote">{t('folder.emptyDir')}</p>
)}
{!loading && error === null && directories.map(entry => (
<button
key={entry.name}
type="button"
role="listitem"
className="wgRemoteRow"
onClick={() => { setPath(remoteDirJoin(resolved, entry.name)) }}
>
<IconFolderOpenOutlineRegular size={16} />
<span className="wgRemoteName">{entry.name}</span>
</button>
))}
</div>
<p className="wgFolderNote">{t('folder.browseNote')}</p>
</Modal>
)
}

View File

@ -1,8 +1,7 @@
/**
* The workspace-groups browsing region filling the sidebar shell's
* `sidebar.workspaces` hole: section header (title + right-aligned search +
* new-group + add workspace), the three-level tree (category — workspace —
* session), group management dialogs, and the workspace/session dialogs. Wide
* new-group + add workspace), the three-level tree (category —workspace — * session), group management dialogs, and the workspace/session dialogs. Wide
* state renders the full browser; rail state renders the two region icons
* (search / add workspace) as 36px controls on the shell's shared rail entry
* path, each requesting expansion through the owner share.
@ -21,7 +20,6 @@ import {
IconFolderOpenOutlineRegular,
IconProjectAddOutlineRegular,
IconSearchOutlineRegular,
IconTrashOutlineRegular,
IconWarningOutlineRegular,
Modal,
Toast,
@ -52,15 +50,16 @@ import {
type ManualGroups,
} from '../core/types.ts'
import type { GroupsBrowserProps } from './contract.ts'
import { deriveDefaultWorkspace, deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, folderKey, folderLabel, isDockedCategoryKey, UNCATEGORIZED_KEY, type CategoryNode, type SearchMatchSet, type SearchTree, type WorkspaceGroupNode } from './tree.ts'
import { deriveDefaultWorkspace, deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, folderKey, isDockedCategoryKey, memberWorkspaces, UNCATEGORIZED_KEY, type CategoryNode, type SearchMatchSet, type SearchTree, 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 { GROUP_EMOJI_ICONS, GROUP_ICON_LABELS } from './group-icon-labels.ts'
import { SCIENCE_ICON_IDS, SCIENCE_ICON_SECTIONS } from './group-icons-science.tsx'
import { EMPTY_FOLDERS_DOCUMENT, addFolder, effectiveFolders, entryFor, isUnderBase, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'
import { EMPTY_FOLDERS_DOCUMENT, addFolder, addMember, effectiveFolders, entryFor, isEmptyEntry, isUnderBase, memberOf, removeFolder, rootOf, samePath, setRoot, type FolderMember, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'
import { loadFolders, saveFolders } from './folders-persist.ts'
import { createWorkspaceDirectory, remoteFolderWorkspace } from './folder-directory.ts'
import { createRemoteFolder, createWorkspaceDirectory, listRemoteProfiles, remoteFolderWorkspace, type RemoteFolderWorkspace, type RemoteProfileSummary } from './folder-directory.ts'
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
import { FoldersDialog } from './FoldersDialog.tsx'
import { QuickPanel } from './QuickPanel.tsx'
import { SessionTabs } from './SessionTabs.tsx'
import css from './styles.css?inline'
@ -106,7 +105,7 @@ function categoryRowCount(category: CategoryNode): number {
return category.workspaces.reduce((total, workspace) => total + 1 + (workspace.expanded ? workspace.sessions.length : 0), 0)
}
/** Palette id — i18n key for the colour picker (keeps literal key types intact). */
/** Palette id —i18n key for the colour picker (keeps literal key types intact). */
const COLOR_LABEL_KEYS: Record<GroupColor, WorkspaceGroupsKey> = {
red: 'color.red',
orange: 'color.orange',
@ -123,7 +122,7 @@ const COLOR_LABEL_KEYS: Record<GroupColor, WorkspaceGroupsKey> = {
/** Research icon ids, matched against the shared registry for the picker split. */
const SCIENCE_ICON_ID_SET: ReadonlySet<string> = new Set(SCIENCE_ICON_IDS)
/** Picker section key → i18n key (keeps literal key types intact). */
/** Picker section key —i18n key (keeps literal key types intact). */
const SCIENCE_SECTION_LABEL_KEYS: Record<'lab' | 'materials' | 'characterization' | 'devices', WorkspaceGroupsKey> = {
lab: 'group.icon.section.lab',
materials: 'group.icon.section.materials',
@ -346,7 +345,7 @@ export function GroupsBrowser({
// 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.
// mirror —anything else would exist on this machine only.
const [foldersRemoteBase, setFoldersRemoteBase] = useState<string | null>(null)
useEffect(() => {
let cancelled = false
@ -369,9 +368,20 @@ export function GroupsBrowser({
// 0.1.6: the selected Session is the one retained through `mainView`, not a
// `list.current` field (the list snapshot carries catalog facts only).
const current = currentSessionId(list)
const currentWorkspaceKey = current === undefined
? undefined
: (workspaces.find(w => w.sessionIds.includes(current as SessionId))?.workspaceId as string | undefined)
// A member folder is backed by its own DSH workspace, whose sidebar row this
// plugin hides: its sessions belong to the project that SHOWS the folder, so
// "current" must resolve back to that owner for expansion and highlighting.
const members = useMemo(() => memberWorkspaces(workspaces, foldersDoc), [workspaces, foldersDoc])
const visibleWorkspaces = useMemo(
() => workspaces.filter(w => !members.absorbed.has(w.workspaceId as string)),
[workspaces, members],
)
const currentWorkspaceKey = useMemo(() => {
if (current === undefined) return undefined
const owner = workspaces.find(w => w.sessionIds.includes(current as SessionId))?.workspaceId as string | undefined
if (owner === undefined) return undefined
return members.absorbed.get(owner) ?? owner
}, [current, workspaces, members])
// Auto-expand the category + workspace containing the current session, but
// ONLY when the user has never touched that key (`Object.hasOwn`): a
@ -399,7 +409,7 @@ export function GroupsBrowser({
}, [actions, config, manual, workspacePhase, workspaces])
// Session tabs: the strip lives in the conversation column, but its lifecycle
// belongs here — the browser already derives the open session for its own tree,
// belongs here —the browser already derives the open session for its own tree,
// so one effect covers every way a session can be opened (sidebar row,
// workspace New Session, quick panel, conversation-header crumbs).
//
@ -506,8 +516,8 @@ export function GroupsBrowser({
const searchMatches = useMemo<SearchMatchSet | undefined>(
() => (normalizedQuery === ''
? undefined
: deriveSearchMatches(list, workspaces, config, normalizedQuery, archivedSessionIds, activeRemoteSearch, searchResultLimit)),
[list, workspaces, config, normalizedQuery, archivedSessionIds, activeRemoteSearch, searchResultLimit],
: deriveSearchMatches(list, workspaces, config, normalizedQuery, archivedSessionIds, activeRemoteSearch, searchResultLimit, foldersDoc)),
[list, workspaces, config, normalizedQuery, archivedSessionIds, activeRemoteSearch, searchResultLimit, foldersDoc],
)
const searchTree = useMemo<SearchTree | undefined>(
() => (searchMatches === undefined
@ -545,7 +555,7 @@ export function GroupsBrowser({
return map
}, [groups])
// While dragging a project, an empty top-level area must still show a landing
// line — otherwise a project can never be dragged OUT of a group when every
// line —otherwise a project can never be dragged OUT of a group when every
// project is currently grouped.
const topLevelDropActive = dragging === 'workspace' && topLevel.length === 0
// The top-level area is the move-out landing spot: rows reorder with an
@ -707,7 +717,7 @@ export function GroupsBrowser({
// "Open in folder": the host half of the official open-in-app plugin resolves
// which applications it can launch; the project row then just posts the
// project directory to that host's launch route. One availability read per
// mount — a host without the capability (or a refused read) leaves
// mount —a host without the capability (or a refused read) leaves
// `folderApp` undefined, which drops the menu entry rather than failing.
const [folderApp, setFolderApp] = useState<string | undefined>(undefined)
const [folderError, setFolderError] = useState<{ id: number; text: string } | null>(null)
@ -745,11 +755,11 @@ export function GroupsBrowser({
})
}
/** Write one workspace's entry; zero extra folders removes the key entirely. */
/** Write one workspace's entry; an entry with nothing attached removes the key. */
const writeFolderEntry = (workspaceId: WorkspaceId, entry: WorkspaceFolderEntry): void => {
const next: Record<string, WorkspaceFolderEntry> = { ...foldersDoc.workspaces }
const key = workspaceId as string
if (entry.folders.length === 0) delete next[key]
if (isEmptyEntry(entry)) delete next[key]
else next[key] = entry
persistFolders({ version: 1, workspaces: next })
}
@ -763,32 +773,112 @@ export function GroupsBrowser({
foldersRemoteBase !== null && isUnderBase(workspace.path, foldersRemoteBase)
)
// The dialog browses the cloud folder's own remote root so a picked subdirectory
// becomes a folder of THIS project instead of a second mirror of the same tree.
const [foldersOwnerRemote, setFoldersOwnerRemote] = useState<string | null>(null)
const foldersOwnerRequest = useRef('')
/** Open the folder dialog and learn the owner's remote root (cloud owners only). */
const openFoldersFor = (workspaceId: string): void => {
foldersOwnerRequest.current = workspaceId
setFoldersTarget(workspaceId as WorkspaceId)
setFoldersOwnerRemote(null)
const workspace = workspaces.find(row => (row.workspaceId as string) === workspaceId)
if (workspace === undefined || !isRemoteWorkspace(workspace) || foldersRemoteBase === null) return
void remoteFolderWorkspace(workspace.path, foldersRemoteBase).then(
(record) => {
if (foldersOwnerRequest.current !== workspaceId) return
setFoldersOwnerRemote(record === null ? null : record.remotePath)
},
() => { if (foldersOwnerRequest.current === workspaceId) setFoldersOwnerRemote(null) },
)
}
/** The overlay record for a picked path that the SSH plugin already mirrors. */
const remoteMember = (target: RemoteFolderWorkspace): FolderMember => ({
path: target.mirrorPath,
workspaceId: target.workspaceId,
kind: 'remote',
remotePath: target.remotePath,
profileId: target.profileId,
...(target.recordId === '' ? {} : { recordId: target.recordId }),
})
// SSH connections for the dialog's cloud section: read when the dialog opens,
// `null` when the remote-ssh plugin is absent (no cloud folders then), and an
// empty list when it is present but has no connection configured yet.
const [remoteProfiles, setRemoteProfiles] = useState<readonly RemoteProfileSummary[] | null>(null)
const [remoteProfilesError, setRemoteProfilesError] = useState<string | null>(null)
useEffect(() => {
if (foldersTarget === null) return
let cancelled = false
setRemoteProfilesError(null)
void listRemoteProfiles().then((profiles) => {
if (!cancelled) setRemoteProfiles(profiles)
}).catch((reason: unknown) => {
if (cancelled) return
setRemoteProfiles(null)
setRemoteProfilesError(reason instanceof Error ? reason.message : String(reason))
})
return () => { cancelled = true }
}, [foldersTarget])
/**
* Resolve the member workspace that owns one folder living OUTSIDE this
* project's own tree. DSH roots every session's file tools at its workspace,
* so an outside folder is only readable by the agent once it is a workspace of
* its own. A registered workspace already sitting on that exact path is reused
* instead of forked; one that owns folders of its own is refused, because
* nesting a folder tree inside another would hide the inner folders' sessions.
*/
const memberWorkspaceFor = async (workspaceId: WorkspaceId, path: string): Promise<FolderMember> => {
const existing = workspaces.find(w => samePath(w.path, path) && w.workspaceId !== workspaceId)
if (existing !== undefined) {
if (!isEmptyEntry(entryFor(foldersDoc, existing.workspaceId as string))) {
throw new Error(t('folder.memberNested'))
}
return { path, workspaceId: existing.workspaceId as string, kind: 'local' }
}
const created = await createWorkspace({ path })
return { path, workspaceId: created.workspaceId as string, kind: 'local' }
}
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.
setFoldersBusy(true)
try {
if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))
if (await remoteFolderWorkspace(workspace.path, foldersRemoteBase)) {
notifyFolder(t('folder.remoteNeedsSubpath'))
return
}
const path = await pickDirectory()
if (path === null) return // cancelled
if (await remoteFolderWorkspace(path, foldersRemoteBase)) {
notifyFolder(t('folder.remoteNeedsSubpath'))
return
}
const entry = entryFor(foldersDoc, workspaceId as string)
if (effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))) {
notifyFolder(t('folder.duplicate'))
return
}
// The picked directory may BE a cloud folder (a registered SSH mirror): it
// then joins the project as a cloud member, whichever side the project
// itself lives on. A mirror subdirectory has no workspace of its own, so
// that one still needs the subpath field instead.
const target = await remoteFolderWorkspace(path, foldersRemoteBase)
if (target !== null) {
if (samePath(target.mirrorPath, path) && target.workspaceId !== ''
&& target.workspaceId !== (workspaceId as string)) {
writeFolderEntry(workspaceId, addMember(entry, remoteMember(target)))
return
}
notifyFolder(t('folder.remoteNeedsSubpath'))
return
}
// A folder outside this project's own tree becomes a member: its own
// workspace is what makes it reachable for the agent, and a session started
// there then runs natively with no cross-workspace cwd. Folders along the
// tree stay plain — one cheap cwd gesture, grouped under this project.
if (!isUnderBase(path, workspace.path)) {
writeFolderEntry(workspaceId, addMember(entry, await memberWorkspaceFor(workspaceId, path)))
return
}
writeFolderEntry(workspaceId, addFolder(entry, path))
} catch (reason) {
const detail = reason instanceof Error ? reason.message : String(reason)
@ -798,6 +888,50 @@ export function GroupsBrowser({
}
}
/**
* "New cloud folder" in the folder dialog: the SSH plugin creates the mirror,
* registers a real workspace for it and returns both ids, so the folder joins
* this project as a member and its own sidebar row stays hidden.
*/
const addRemoteFolderTo = async (
workspaceId: WorkspaceId, profileId: string, remotePath: string,
): Promise<boolean> => {
if (foldersBusy) return false
const owner = workspaces.find(w => w.workspaceId === workspaceId)
if (owner === undefined) return false
setFoldersBusy(true)
try {
const created = await createRemoteFolder(profileId, remotePath)
if (created.workspaceId === (workspaceId as string)) throw new Error(t('folder.duplicate'))
const entry = entryFor(foldersDoc, workspaceId as string)
if (effectiveFolders(owner.path, entry).some(folder => samePath(folder, created.path))) {
throw new Error(t('folder.duplicate'))
}
const member: FolderMember = {
path: created.path,
workspaceId: created.workspaceId,
kind: 'remote',
remotePath: created.remotePath,
profileId: created.profileId,
title: created.title,
...(created.recordId === '' ? {} : { recordId: created.recordId }),
}
const next: FoldersDocument = {
version: 1,
workspaces: { ...foldersDoc.workspaces, [workspaceId]: addMember(entry, member) },
}
// Like the subpath field: report success only once the overlay is durable.
await saveFolders(next)
setFoldersDoc(next)
return true
} catch (reason) {
notifyFolder(`${t('folder.addError')}: ${reason instanceof Error ? reason.message : String(reason)}`)
return false
} finally {
setFoldersBusy(false)
}
}
/** The same gesture routes through native local or SSH-owned mkdir APIs. */
const addSubpathTo = async (workspaceId: WorkspaceId, name: string): Promise<boolean> => {
if (foldersBusy) return false
@ -836,11 +970,14 @@ export function GroupsBrowser({
}
/**
* "New session here": an extra folder's own directory becomes the Session cwd.
* The base folder keeps the platform's own gesture instead, because that one
* reuses the blank session it already opened; creating a fresh Session on
* every click would pile up empty sessions. One creation in flight at a time;
* a rejection surfaces the failure and creates nothing else.
* "New session here": a member folder has its OWN workspace, so the session is
* created there with no cwd override at all —that is what makes a cloud
* folder and a local folder behave identically under one project row. A plain
* extra folder keeps the cwd gesture. The base folder keeps the platform's own
* gesture instead, because that one reuses the blank session it already opened;
* creating a fresh Session on every click would pile up empty sessions. One
* creation in flight at a time; a rejection surfaces the failure and creates
* nothing else.
*/
const startSessionInFolder = (workspaceId: WorkspaceId, path: string, isBase: boolean): void => {
if (isBase) {
@ -852,7 +989,28 @@ export function GroupsBrowser({
void (async () => {
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
if (!workspace) throw new Error('Workspace not found')
const member = memberOf(entryFor(foldersDoc, workspaceId as string), path)
if (member !== undefined) {
// The member's own workspace is what runs the session; if the user deleted
// it outside this overlay, say so instead of failing inside the platform.
if (!workspaces.some(w => w.workspaceId === member.workspaceId)) {
throw new Error(t('folder.memberMissing'))
}
await createSessionIn(member.workspaceId as WorkspaceId)
return
}
if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))
// Legacy overlay: a folder recorded before out-of-tree folders became
// members has no workspace of its own, and a cwd override cannot escape
// this project's root — so the agent would open the folder and see nothing.
// Register the member now and run the session inside it.
if (!isUnderBase(path, workspace.path)) {
const entry = entryFor(foldersDoc, workspaceId as string)
const attached = await memberWorkspaceFor(workspaceId, path)
writeFolderEntry(workspaceId, addMember(entry, attached))
await createSessionIn(attached.workspaceId as WorkspaceId)
return
}
const remote = await remoteFolderWorkspace(workspace.path, foldersRemoteBase)
const targetRemote = await remoteFolderWorkspace(path, foldersRemoteBase)
if (remote || targetRemote) throw new Error(t('folder.remoteSessionUnsupported'))
@ -865,7 +1023,7 @@ export function GroupsBrowser({
})
}
/** A project row's plus button — starts in that workspace's root folder. */
/** A project row's plus button —starts in that workspace's root folder. */
const startSessionAtRoot = (workspaceId?: WorkspaceId): void => {
const workspace = workspaceId === undefined ? undefined : workspaces.find(w => w.workspaceId === workspaceId)
if (workspace === undefined) {
@ -1192,7 +1350,7 @@ export function GroupsBrowser({
/**
* Drop on a row. The insertion point is re-derived from the drop event's
* position (top half = before, bottom half = after), so it always matches
* the indicator the user last saw — even when dragover and drop arrive in
* the indicator the user last saw —even when dragover and drop arrive in
* the same tick.
*/
const onDropRow = (categoryKey: string, row: DropRowRef) => (event: DragEvent): void => {
@ -1269,8 +1427,7 @@ export function GroupsBrowser({
/**
* Drag over the TOP-LEVEL AREA's blank space (not on a row ???rows stop
* propagation). An insertion line shows the landing spot: empty top level —
* a standalone line under the last group; non-empty — a line below the last
* propagation). An insertion line shows the landing spot: empty top level — * a standalone line under the last group; non-empty —a line below the last
* top-level row (end of the list).
*/
const onDragOverTopLevelArea = (event: DragEvent): void => {
@ -1293,7 +1450,7 @@ export function GroupsBrowser({
}
}
// While dragging a project, only PROJECT rows fold — every expanded
// While dragging a project, only PROJECT rows fold —every expanded
// workspace collapses (inside groups AND top-level); group rows keep their
// expansion so the user still sees where groups are. dragend restores the
// snapshot taken here.
@ -1349,7 +1506,7 @@ export function GroupsBrowser({
// Bottom-bar content. Idle: the default workspace with its real subtree.
// Searching: the pruned branch (matched sessions only), or the bare row when
// nothing matched — the results area never repeats this workspace.
// nothing matched —the results area never repeats this workspace.
const defaultBarNode = defaultWorkspace === undefined
? undefined
: normalizedQuery === ''
@ -1362,8 +1519,7 @@ export function GroupsBrowser({
/**
* One category section with every tree callback bound. Extracted so the docked
* bucket is literally the same row/children component as a tree category —
* drag, menu, rename, appearance, folder management all behave identically.
* bucket is literally the same row/children component as a tree category — * drag, menu, rename, appearance, folder management all behave identically.
*/
const categorySectionNode = (category: CategoryNode): JSX.Element => (
<CategorySection
@ -1387,7 +1543,7 @@ export function GroupsBrowser({
onFolderSetRoot={setFolderRoot}
onFolderRemove={removeFolderFrom}
onOpenFolderPath={openFolderPath}
onManageFolders={(workspaceId) => { setFoldersTarget(workspaceId) }}
onManageFolders={openFoldersFor}
creatingFolderKey={creatingSessionIn}
onRenameRequest={(workspaceId, title) => {
setRenameTarget({ workspaceId, currentTitle: title })
@ -1423,8 +1579,7 @@ export function GroupsBrowser({
onOpenInFolder={openInFolder}
canMoveOut={(workspaceId) => {
// The menu "Move out of group" is offered for any project that
// currently sits inside a group (rule-classified or manual) —
// not just overridden ones. Top-level projects
// currently sits inside a group (rule-classified or manual) — // not just overridden ones. Top-level projects
// (resolveCategory === undefined) don't need it.
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
return workspace !== undefined
@ -1592,7 +1747,7 @@ export function GroupsBrowser({
onFolderSetRoot={setFolderRoot}
onFolderRemove={removeFolderFrom}
onOpenFolderPath={openFolderPath}
onManageFolders={(workspaceId) => { setFoldersTarget(workspaceId) }}
onManageFolders={openFoldersFor}
creatingFolderKey={creatingSessionIn}
onRenameRequest={(workspaceId, title) => {
setRenameTarget({ workspaceId, currentTitle: title })
@ -1620,7 +1775,7 @@ export function GroupsBrowser({
children (same component, same drag/menu behaviour), capped in height
with its own scroll so a big bucket cannot swallow the tree;
- the Host default workspace keeps the whole workspace-row behaviour
(toggle, new session, rename, delete, ⋯ menu, folder management) and
(toggle, new session, rename, delete, —menu, folder management) and
its sessions still highlight as usual. */}
{wide && (dockCategory !== undefined || defaultBarNode !== undefined) && (
<div className="wgDock">
@ -1649,7 +1804,7 @@ export function GroupsBrowser({
{...(openInFolder !== undefined
? { onOpenInFolder: () => { openInFolder(defaultBarNode.workspaceId) } }
: {})}
onManageFolders={() => { setFoldersTarget(defaultBarNode.workspaceId) }}
onManageFolders={() => { openFoldersFor(defaultBarNode.workspaceId as string) }}
/>
<div className="wgDockSessions">
<WorkspaceSubtree
@ -1827,7 +1982,7 @@ export function GroupsBrowser({
onKeyDown={(e) => { if (e.key === 'Enter') commitAppearanceIcon() }}
onBlur={(event) => {
/* A swatch / preset click moves focus out of the field in the
same gesture and writes its own patch — committing the stale
same gesture and writes its own patch —committing the stale
draft here would race it and could overwrite the preset. */
const next = event.relatedTarget
if (next instanceof Element && next.closest('.wgSwatch, .wgIconCell') !== null) return
@ -1863,12 +2018,17 @@ export function GroupsBrowser({
busy={foldersBusy}
canOpen={openFolderPath !== undefined}
remote={isRemoteWorkspace(workspace)}
onClose={() => { setFoldersTarget(null) }}
onAdd={() => { void addFolderTo(foldersTarget) }}
ownerRemotePath={foldersOwnerRemote}
profiles={remoteProfiles}
profilesError={remoteProfilesError}
knownWorkspaceIds={workspaces.map(w => w.workspaceId as string)}
onAddFolder={() => { void addFolderTo(foldersTarget) }}
onAddRemote={(profileId, remotePath) => addRemoteFolderTo(foldersTarget, profileId, remotePath)}
onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)}
onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }}
onRemove={(path) => { removeFolderFrom(foldersTarget, path) }}
onOpenFolder={(path) => { openFolderPath?.(path) }}
onClose={() => { foldersOwnerRequest.current = ''; setFoldersTarget(null) }}
/>
)
})()}
@ -1981,7 +2141,7 @@ export function GroupsBrowser({
<QuickPanel
onClose={() => { setQuickOpen(false) }}
list={list}
workspaces={workspaces}
workspaces={visibleWorkspaces}
archivedSessionIds={archivedSessionIds}
categoryByWorkspace={categoryByWorkspace}
current={current}
@ -2407,7 +2567,7 @@ function SearchSubtree({ workspace, current, now, open, t }: {
/**
* Search results, presentational only: the owner derives the tree and the
* match set (so the pinned default-workspace bar can share that derivation).
* This view never repeats the default workspace — tree.ts leaves it out of the
* This view never repeats the default workspace —tree.ts leaves it out of the
* categories / top-level projections and hands it back as `tree.defaultWorkspace`.
*/
function SearchBody({ tree, matches, status, current, now, open, t }: {
@ -2470,115 +2630,3 @@ function SearchBody({ tree, matches, status, current, now, open, t }: {
</div>
)
}
/**
* Folder list dialog for one workspace: the base folder first, then every extra
* folder in stored order. The radio column chooses the root (the folder new
* 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, 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) => Promise<boolean>
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
if (busy) return
void onAddSubpath(subpath).then(success => { if (success) setSubpath('') })
}
return (
<Modal
open
onClose={onClose}
closeLabel={t('close')}
title={t('folder.title')}
footer={(
<Button variant="primary" onClick={onClose}>{t('folder.done')}</Button>
)}
>
<div className="wgFolderList" role="list" aria-label={t('folder.listAria')}>
{folders.map((path, index) => {
const isBase = index === 0
const isRoot = samePath(path, root)
const label = folderLabel(path)
return (
<div key={path} className="wgFolderListRow" role="listitem">
<input
type="radio"
className="wgFolderRadio"
name="wg-folder-root"
checked={isRoot}
aria-label={`${t('folder.rootBadge')} ${label}`}
onChange={() => { onSetRoot(path) }}
/>
<span className="wgFolderListLabel" title={path}>{label}</span>
{isBase && <span className="wgFolderListTag">{t('folder.base')}</span>}
{isRoot && <span className="wgFolderListTag">{t('folder.rootBadge')}</span>}
<span className="wgFolderListActions">
{canOpen && (
<button
type="button"
className="wgIconButton"
aria-label={`${t('workspace.openInFolder')} ${label}`}
onClick={() => { onOpenFolder(path) }}
>
<IconFolderOpenOutlineRegular size={16} />
</button>
)}
{!isBase && (
<button
type="button"
className="wgIconButton"
aria-label={`${t('folder.remove')} ${label}`}
onClick={() => { onRemove(path) }}
>
<IconTrashOutlineRegular />
</button>
)}
</span>
</div>
)
})}
</div>
<div className="wgFolderListFooter">
<>
<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>
</>
{!remote && <Button variant="outline" disabled={busy} onClick={onAdd}>{t('folder.add')}</Button>}
</div>
</Modal>
)
}

View File

@ -8,6 +8,10 @@ export interface RemoteFolderWorkspace {
mirrorPath: string
remotePath: string
profileId: string
/** Native DSH workspace registered for the mirror root ('' when unregistered). */
workspaceId: string
/** remote-ssh's own record id ('' when it cannot be resolved). */
recordId: string
}
type JsonObject = Record<string, unknown>
@ -48,6 +52,193 @@ async function refuseMarkedLocalPath(path: string, fetchImpl: typeof fetch): Pro
if (body.remoteHint) throw new Error('SSH marker detected but no active registered remote workspace; refusing local operation')
}
/** One SSH connection the remote plugin offers, as the picker needs it. */
export interface RemoteProfileSummary {
id: string
name: string
host: string
user: string
/** Directory the connection opens on (`~` when the plugin leaves it empty). */
remoteRoot: string
}
/** One row of a remote directory listing. */
export interface RemoteDirEntry {
name: string
type: 'directory' | 'file'
size: number
}
/** A remote directory and its children, as the cloud folder picker needs them. */
export interface RemoteDirListing {
/** Path as requested (`~`, a relative name or an absolute path). */
requested: string
/** Absolute path the remote shell resolved it to (`requested` when unknown). */
resolved: string
entries: readonly RemoteDirEntry[]
}
/** Single-quote one POSIX shell word; `~` expands only when it stays unquoted. */
function shellWord(path: string): string {
return `'${path.replace(/'/gu, `'\\''`)}'`
}
/** Quote a remote path for `sh`, keeping a leading `~` expandable. */
function shellPath(path: string): string {
if (path === '~') return '~'
if (path.startsWith('~/')) return `~/${shellWord(path.slice(2))}`
return shellWord(path)
}
/** Parent of a directory path, or null where going up stops (`~`, `/`, root). */
export function remoteDirParent(path: string): string | null {
const trimmed = path.trim().replace(/\/+$/u, '')
if (trimmed === '' || trimmed === '~' || trimmed === '.') return null
const cut = trimmed.lastIndexOf('/')
if (cut < 0) return null
if (cut === 0) return '/'
return trimmed.slice(0, cut)
}
/** Join a child directory name onto a remote directory path. */
export function remoteDirJoin(base: string, name: string): string {
if (base === '') return name
return base.endsWith('/') ? `${base}${name}` : `${base}/${name}`
}
/**
* List one remote directory through the SSH plugin's own pooled session, so
* password auth, ProxyJump and host-key handling stay where they already work.
* @param profileId - SSH connection to browse.
* @param path - directory to list; empty means the connection's remote root.
* @param fetchImpl - fetch implementation (tests inject one).
*/
export async function listRemoteDirectory(
profileId: string, path: string, fetchImpl: typeof fetch = fetch,
): Promise<RemoteDirListing> {
const requested = path.trim() === '' ? '~' : path.trim()
const value = await rpc('listDir', { profileId, path: requested }, fetchImpl)
if (value === null) throw new Error('The SSH plugin is unavailable; cannot browse that connection')
const rows = Array.isArray(value.entries) ? value.entries : []
const entries: RemoteDirEntry[] = []
for (const raw of rows) {
const row = object(raw)
if (row === undefined || typeof row.name !== 'string' || row.name === '') continue
entries.push({
name: row.name,
type: row.type === 'directory' ? 'directory' : 'file',
size: typeof row.size === 'number' && Number.isFinite(row.size) ? row.size : 0,
})
}
return { requested, resolved: await resolveRemoteDirectory(profileId, requested, fetchImpl) ?? requested, entries }
}
/** Absolute form of a remote path, or null when the remote shell cannot resolve it. */
async function resolveRemoteDirectory(
profileId: string, path: string, fetchImpl: typeof fetch,
): Promise<string | null> {
try {
const value = await rpc('remoteExec', { profileId, command: `cd ${shellPath(path)} && pwd -P` }, fetchImpl)
const stdout = typeof value?.stdout === 'string' ? value.stdout.trim() : ''
const line = stdout.split('\n').filter(text => text.trim() !== '').pop()
return line === undefined ? null : line.trim()
} catch {
// Listing succeeded but the path cannot be named (a shell without cd): keep browsing.
return null
}
}
/** A newly registered remote (mirror-backed) folder workspace. */
export interface CreatedRemoteFolder {
/** Absolute LOCAL mirror path — the member workspace's canonical directory. */
path: string
/** Native DSH workspace id that now backs the folder row. */
workspaceId: string
/** remote-ssh's own record id (used to delete the record again). */
recordId: string
remotePath: string
profileId: string
title: string
/** True when an existing record for the same profile + remote path was taken over. */
reused: boolean
}
/**
* The SSH connections available for a cloud folder, or null when the
* `@zhangfengshun/dsh-remote-ssh` plugin does not answer at all.
* @param fetchImpl - fetch implementation (tests inject one).
*/
export async function listRemoteProfiles(
fetchImpl: typeof fetch = fetch,
): Promise<RemoteProfileSummary[] | null> {
let value: JsonObject | null
try {
value = await rpc('listProfiles', {}, fetchImpl)
} catch (reason) {
// A missing plugin answers HTTP 404 with no JSON envelope at all.
if (reason instanceof Error && reason.message.includes('HTTP 404')) return null
throw reason
}
if (value === null) return null
const rows = Array.isArray(value.profiles) ? value.profiles : []
const profiles: RemoteProfileSummary[] = []
for (const raw of rows) {
const row = object(raw)
if (row === undefined || typeof row.id !== 'string' || row.id === '') continue
profiles.push({
id: row.id,
name: typeof row.name === 'string' && row.name !== '' ? row.name : row.id,
host: typeof row.host === 'string' ? row.host : '',
user: typeof row.user === 'string' ? row.user : '',
remoteRoot: typeof row.remoteRoot === 'string' && row.remoteRoot !== '' ? row.remoteRoot : '~',
})
}
return profiles
}
/**
* Register one cloud folder: the SSH plugin creates the local mirror, writes the
* connection marker and registers a real DSH workspace for it — exactly what its
* own "new remote workspace" flow does. The returned native workspace id backs
* the folder row, and the workspace's own sidebar row is hidden once the entry
* lists it (see `absorbedWorkspaceIds`).
* @param profileId - SSH connection to use.
* @param remotePath - remote directory (`~`, `~/proj`, `/srv/proj`).
* @param title - optional display title; the plugin derives one from the path.
* @param fetchImpl - fetch implementation (tests inject one).
*/
export async function createRemoteFolder(
profileId: string,
remotePath: string,
title?: string,
fetchImpl: typeof fetch = fetch,
): Promise<CreatedRemoteFolder> {
const trimmedPath = remotePath.trim()
if (profileId.trim() === '' || trimmedPath === '') throw new Error('Pick a connection and enter a remote path')
const value = await rpc('createRemoteWorkspace', {
profileId,
remotePath: trimmedPath,
...(title === undefined || title.trim() === '' ? {} : { title: title.trim() }),
}, fetchImpl)
if (value === null) throw new Error('The SSH plugin is unavailable; cannot add a cloud folder')
const record = object(value.workspace) ?? {}
const workspaceId = typeof value.workspaceId === 'string' ? value.workspaceId : ''
const mirrorPath = typeof value.mirrorPath === 'string' ? value.mirrorPath : ''
const recordId = typeof record.id === 'string' ? record.id : ''
if (workspaceId === '' || mirrorPath === '') {
throw new Error('The SSH plugin did not register a workspace for this folder')
}
return {
path: mirrorPath,
workspaceId,
recordId,
remotePath: typeof record.remotePath === 'string' ? record.remotePath : trimmedPath,
profileId: typeof record.profileId === 'string' ? record.profileId : profileId,
title: typeof record.title === 'string' && record.title !== '' ? record.title : trimmedPath,
reused: value.reused === true,
}
}
/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */
export async function remoteFolderWorkspace(
path: string, remoteBase: string | null, fetchImpl: typeof fetch = fetch,
@ -68,7 +259,13 @@ export async function remoteFolderWorkspace(
throw new Error('Invalid SSH workspace entry')
}
if (samePath(path, row.mirrorPath) || isUnderBase(path, row.mirrorPath)) {
matches.push({ mirrorPath: row.mirrorPath, remotePath: row.remotePath, profileId: row.profileId })
matches.push({
mirrorPath: row.mirrorPath,
remotePath: row.remotePath,
profileId: row.profileId,
workspaceId: typeof row.shellWorkspaceId === 'string' ? row.shellWorkspaceId : '',
recordId: typeof row.id === 'string' ? row.id : '',
})
}
}
if (matches.length > 1) throw new Error('Overlapping SSH workspaces are not supported safely')

View File

@ -14,6 +14,7 @@
*/
import {
EMPTY_FOLDERS_DOCUMENT,
type FolderMember,
type FoldersDocument,
type WorkspaceFolderEntry,
} from '../core/folders.ts'
@ -32,23 +33,76 @@ export interface FoldersSnapshot {
readonly remoteBase?: string
}
/** One non-empty string field, or undefined when it is absent or blank. */
function wireText(value: unknown): string | undefined {
if (typeof value !== 'string') return undefined
const trimmed = value.trim()
return trimmed === '' ? undefined : trimmed
}
/**
* Read one member (a folder backed by its own workspace) off the wire.
* @param value - one value of the stored `members` list.
* @returns the member, or null for a malformed one.
*/
function parseWireMember(value: unknown): FolderMember | null {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null
const row = value as Record<string, unknown>
const path = wireText(row.path)
const workspaceId = wireText(row.workspaceId)
// A member without a directory or without its workspace cannot run a session,
// so it is not worth a row.
if (path === undefined || workspaceId === undefined) return null
const remotePath = wireText(row.remotePath)
const profileId = wireText(row.profileId)
const recordId = wireText(row.recordId)
const title = wireText(row.title)
return {
path,
workspaceId,
kind: row.kind === 'remote' ? 'remote' : 'local',
...(remotePath === undefined ? {} : { remotePath }),
...(profileId === undefined ? {} : { profileId }),
...(recordId === undefined ? {} : { recordId }),
...(title === undefined ? {} : { title }),
}
}
/**
* Read one workspace entry off the wire, dropping the entry when it is
* unusable.
*
* `members` must survive this round trip: the client owns the whole document
* (the PUT sends it back verbatim), so an entry parsed without its members is
* not merely a display gap — the next folder edit would rewrite the sidecar and
* erase every member-backed folder for good.
* @param value - one value of the stored `workspaces` mapping.
* @returns the entry, or null for a malformed one.
*/
function parseWireEntry(value: unknown): WorkspaceFolderEntry | null {
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null
const row = value as Record<string, unknown>
if (!Array.isArray(row.folders)) return null
const folders: string[] = []
for (const candidate of row.folders) {
if (typeof candidate !== 'string' || candidate.trim() === '') continue
folders.push(candidate)
if (Array.isArray(row.folders)) {
for (const candidate of row.folders) {
const path = wireText(candidate)
if (path !== undefined) folders.push(path)
}
}
const members: FolderMember[] = []
if (Array.isArray(row.members)) {
for (const candidate of row.members) {
const member = parseWireMember(candidate)
if (member !== null) members.push(member)
}
}
if (folders.length === 0 && members.length === 0) return null
const root = wireText(row.root)
return {
folders,
...(members.length === 0 ? {} : { members }),
...(root === undefined ? {} : { root }),
}
const root = typeof row.root === 'string' && row.root.trim() !== '' ? row.root : undefined
return { folders, ...(root === undefined ? {} : { root }) }
}
/**

View File

@ -5,6 +5,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'
@ -37,6 +38,9 @@ export type WorkspaceGroupsKey =
| 'folder.title'
| 'folder.manage'
| 'folder.listAria'
| 'folder.sectionList'
| 'folder.sectionAdd'
| 'folder.emptyHint'
| 'folder.base'
| 'folder.setRoot'
| 'folder.rootBadge'
@ -55,6 +59,39 @@ export type WorkspaceGroupsKey =
| 'folder.subpathPlaceholder'
| 'folder.addSubpath'
| 'folder.subpathInvalid'
| 'folder.cloudSection'
| 'folder.profileLabel'
| 'folder.remotePathLabel'
| 'folder.remotePathPlaceholder'
| 'folder.remotePathOrName'
| 'folder.createAndAdd'
| 'folder.cloudNoteBoth'
| 'folder.addRemote'
| 'folder.noProfiles'
| 'folder.profilesError'
| 'folder.cloudTag'
| 'folder.localTag'
| 'folder.memberMissing'
| 'folder.memberNested'
| 'folder.alreadyRoot'
| 'folder.addAria'
| 'folder.tabLocal'
| 'folder.tabCloud'
| 'folder.pickLocal'
| 'folder.localNote'
| 'folder.localIntoRemote'
| 'folder.cloudNote'
| 'folder.browse'
| 'folder.browseTitle'
| 'folder.browseListAria'
| 'folder.browseNote'
| 'folder.browseFailed'
| 'folder.chooseHere'
| 'folder.up'
| 'folder.home'
| 'folder.refresh'
| 'folder.loading'
| 'folder.emptyDir'
| 'group.create'
| 'group.createTitle'
| 'group.createPlaceholder'
@ -151,7 +188,7 @@ export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>
export const zh: WorkspaceGroupsDict = {
'section.workspaces': '工作区',
'section.sessions': '会话',
search: '搜索',
'search': '搜索',
'search.placeholder': '搜索会话…',
'search.clear': '清除',
'search.noMatches': '没有匹配的会话',
@ -180,6 +217,9 @@ export const zh: WorkspaceGroupsDict = {
'folder.title': '文件夹',
'folder.manage': '文件夹…',
'folder.listAria': '工作区文件夹',
'folder.sectionList': '项目文件夹',
'folder.sectionAdd': '添加文件夹',
'folder.emptyHint': '还没有额外文件夹。下面挂一个目录,它的会话会独立运行,模型也能直接读到里面的文件。',
'folder.base': '基础文件夹',
'folder.setRoot': '设为根目录',
'folder.rootBadge': '根目录',
@ -198,6 +238,39 @@ export const zh: WorkspaceGroupsDict = {
'folder.subpathPlaceholder': '例如 data',
'folder.addSubpath': '创建文件夹',
'folder.subpathInvalid': '路径无效:请填工作区内的相对路径,不能用绝对路径或 ..',
'folder.cloudSection': '云端文件夹',
'folder.profileLabel': 'SSH 连接',
'folder.remotePathLabel': '远端目录',
'folder.remotePathPlaceholder': '例如 ~/projects/app',
'folder.remotePathOrName': '例如 ~/projects/app,或新目录名',
'folder.createAndAdd': '新建并添加',
'folder.cloudNoteBoth': '填绝对路径:新建一个云端工作区(带本地镜像);只填名字:在项目云端根目录下新建该目录并挂进来',
'folder.addRemote': '添加云端文件夹',
'folder.noProfiles': '没有可用的 SSH 连接:请先在 remote-ssh 插件中配置连接',
'folder.profilesError': '读取 SSH 连接失败',
'folder.cloudTag': '云端',
'folder.localTag': '本地',
'folder.memberMissing': '该文件夹对应的独立工作区已不存在,请移除后重新添加',
'folder.memberNested': '该目录本身已是一个含文件夹的项目,不能作为文件夹加入',
'folder.alreadyRoot': '这就是项目的根目录,不能再作为一个文件夹加入',
'folder.addAria': '添加文件夹的方式',
'folder.tabLocal': '本地目录',
'folder.tabCloud': '云端目录',
'folder.pickLocal': '选择本地目录…',
'folder.localNote': '在本机选一个目录,作为这个项目的文件夹',
'folder.localIntoRemote': '这个项目在云端;本地目录会作为本地文件夹挂到这个项目里',
'folder.cloudNote': '会为该远端目录建立本地镜像,并注册成一个工作区供会话使用',
'folder.browse': '浏览…',
'folder.browseTitle': '选择云端文件夹',
'folder.browseListAria': '远端目录列表',
'folder.browseNote': '只列出目录:点目录进入,用底部按钮选择当前目录。',
'folder.browseFailed': '读取远端目录失败',
'folder.chooseHere': '选择此目录',
'folder.up': '上一级',
'folder.home': '主目录',
'folder.refresh': '刷新',
'folder.loading': '正在读取远端目录…',
'folder.emptyDir': '这个目录下没有子目录',
'group.create': '新建分组',
'group.createTitle': '新建分组',
'group.createPlaceholder': '分组名称',
@ -252,17 +325,17 @@ export const zh: WorkspaceGroupsDict = {
'session.renameConfirm': '重命名',
'session.renameCancel': '取消',
'session.renaming': '重命名中…',
uncategorized: '未分类',
'uncategorized': '未分类',
'empty.none': '暂无内容',
'empty.noWorkspaces': '还没有工作区',
close: '关闭',
cancel: '取消',
confirm: '确定',
retry: '重试',
configUnavailable: '分组配置不可用',
collapse: '折叠',
expandMore: '展开全部',
newSession: '新建会话',
'close': '关闭',
'cancel': '取消',
'confirm': '确定',
'retry': '重试',
'configUnavailable': '分组配置不可用',
'collapse': '折叠',
'expandMore': '展开全部',
'newSession': '新建会话',
'quick.title': '快速切换',
'quick.tab.workspaces': '工作区',
'quick.tab.sessions': '全部会话',
@ -293,7 +366,7 @@ export const zh: WorkspaceGroupsDict = {
export const en: WorkspaceGroupsDict = {
'section.workspaces': 'Workspaces',
'section.sessions': 'Sessions',
search: 'Search',
'search': 'Search',
'search.placeholder': 'Search sessions…',
'search.clear': 'Clear',
'search.noMatches': 'No matching sessions',
@ -322,6 +395,9 @@ export const en: WorkspaceGroupsDict = {
'folder.title': 'Folders',
'folder.manage': 'Folders…',
'folder.listAria': 'Workspace folders',
'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.base': 'Base folder',
'folder.setRoot': 'Set as root',
'folder.rootBadge': 'Root',
@ -340,6 +416,39 @@ export const en: WorkspaceGroupsDict = {
'folder.subpathPlaceholder': 'e.g. data',
'folder.addSubpath': 'Create folder',
'folder.subpathInvalid': 'Invalid path: use a relative path inside the workspace (no absolute paths, no ..)',
'folder.cloudSection': 'Cloud folders',
'folder.profileLabel': 'SSH connection',
'folder.remotePathLabel': 'Remote directory',
'folder.remotePathPlaceholder': 'e.g. ~/projects/app',
'folder.remotePathOrName': 'e.g. ~/projects/app, or a new folder name',
'folder.createAndAdd': 'Create and add',
'folder.cloudNoteBoth': 'A path creates a new cloud workspace with its local mirror; a bare name creates that directory under this project’s remote root and attaches it',
'folder.addRemote': 'Add cloud folder',
'folder.noProfiles': 'No SSH connection available: configure one in the remote-ssh plugin first',
'folder.profilesError': 'Could not read SSH connections',
'folder.cloudTag': 'Cloud',
'folder.localTag': 'Local',
'folder.memberMissing': 'The standalone workspace behind this folder no longer exists. Remove the folder and add it again.',
'folder.memberNested': 'That directory is a project with folders of its own, so it cannot join as a folder.',
'folder.alreadyRoot': 'That is the root of this project, so it cannot join as a folder.',
'folder.addAria': 'Ways to add a folder',
'folder.tabLocal': 'Local directory',
'folder.tabCloud': 'Cloud directory',
'folder.pickLocal': 'Choose a local directory…',
'folder.localNote': 'Pick a directory on this machine to use as a folder of this project',
'folder.localIntoRemote': 'This project lives on the SSH host; a local directory joins it as a local folder',
'folder.cloudNote': 'Mirrors that remote directory locally and registers a workspace for its sessions',
'folder.browse': 'Browse…',
'folder.browseTitle': 'Choose a cloud folder',
'folder.browseListAria': 'Remote directory list',
'folder.browseNote': 'Only directories are listed: enter one, then choose the current directory with the button below.',
'folder.browseFailed': 'Could not read the remote directory',
'folder.chooseHere': 'Choose this directory',
'folder.up': 'Up',
'folder.home': 'Home',
'folder.refresh': 'Refresh',
'folder.loading': 'Reading the remote directory…',
'folder.emptyDir': 'No subdirectories here',
'group.create': 'New group',
'group.createTitle': 'New group',
'group.createPlaceholder': 'Group name',
@ -394,17 +503,17 @@ export const en: WorkspaceGroupsDict = {
'session.renameConfirm': 'Rename',
'session.renameCancel': 'Cancel',
'session.renaming': 'Renaming…',
uncategorized: 'Uncategorized',
'uncategorized': 'Uncategorized',
'empty.none': 'Nothing here',
'empty.noWorkspaces': 'No workspaces yet',
close: 'Close',
cancel: 'Cancel',
confirm: 'Confirm',
retry: 'Retry',
configUnavailable: 'Grouping config unavailable',
collapse: 'Collapse',
expandMore: 'Show all',
newSession: 'New Session',
'close': 'Close',
'cancel': 'Cancel',
'confirm': 'Confirm',
'retry': 'Retry',
'configUnavailable': 'Grouping config unavailable',
'collapse': 'Collapse',
'expandMore': 'Show all',
'newSession': 'New Session',
'quick.title': 'Quick switch',
'quick.tab.workspaces': 'Workspaces',
'quick.tab.sessions': 'All sessions',

View File

@ -730,45 +730,193 @@
border-color:var(--dsw-accent,#4a90d9);
}
/* Folder list dialog: one row per folder (base first), radio picks the root. */
/* Folder dialog: project header, one card per folder, then the add section.
Rows are two-line (name over path) so a generated mirror id never has to be
read as a name, and the add action owns a full-width row so its label cannot
wrap. */
.wgFolderBody {
display:flex;
flex-direction:column;
gap:14px;
}
.wgFolderHead {
display:flex;
flex-direction:column;
gap:2px;
min-width:0;
}
.wgFolderHeadName {
color:var(--dsw-fg-1,inherit);
font-size:13px;
font-weight:600;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
.wgFolderHeadPath {
color:var(--dsw-alias-label-secondary,inherit);
font-family:var(--dsw-font-mono,ui-monospace,SFMono-Regular,monospace);
font-size:11px;
opacity:.65;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
.wgFolderSection {
display:flex;
flex-direction:column;
gap:6px;
min-width:0;
}
.wgFolderSectionTitle {
color:var(--dsw-alias-label-secondary,inherit);
font-size:11px;
font-weight:600;
letter-spacing:.03em;
opacity:.7;
}
.wgFolderList {
display:flex;
flex-direction:column;
gap:4px;
max-height:280px;
overflow:auto;
padding:2px;
margin:0 -2px;
}
.wgFolderListRow {
border-radius:6px;
align-items:center;
gap:6px;
padding:4px 4px 4px 2px;
display:flex;
align-items:center;
gap:8px;
padding:7px 8px;
border:1px solid transparent;
border-radius:8px;
background:#7f7f7f1a;
transition:background .12s ease,border-color .12s ease;
}
.wgFolderListRow:hover {
background:var(--dsw-bg-hover,#7f7f7f2e);
}
.wgFolderListRow[data-active="true"] {
border-color:var(--dsw-alias-border-l2,#7f7f7f40);
background:var(--dsw-bg-hover,#7f7f7f1f);
}
.wgFolderRadio {
.wgFolderRootPick {
display:inline-flex;
align-items:center;
flex:none;
accent-color:var(--dsw-accent,#4a90d9);
cursor:pointer;
}
.wgFolderRadio {
appearance:none;
width:14px;
height:14px;
margin:0;
border:1.5px solid var(--dsw-alias-border-l2,#7f7f7f80);
border-radius:50%;
background:none;
display:grid;
place-content:center;
cursor:pointer;
transition:border-color .12s ease;
}
.wgFolderRadio:hover {
border-color:var(--dsw-accent,#4a90d9);
}
.wgFolderRadio:checked {
border-color:var(--dsw-accent,#4a90d9);
}
.wgFolderRadio:checked::after {
content:"";
width:7px;
height:7px;
border-radius:50%;
background:var(--dsw-accent,#4a90d9);
}
.wgFolderRadio:focus-visible {
outline:2px solid var(--dsw-accent,#4a90d9);
outline-offset:2px;
}
.wgFolderEntry {
display:flex;
flex-direction:column;
gap:1px;
flex:1 1 auto;
min-width:0;
}
.wgFolderListLabel {
color:var(--dsw-fg-1,inherit);
font-size:12.5px;
font-weight:500;
line-height:1.35;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
min-width:0;
color:var(--dsw-fg-1,inherit);
font-size:12px;
flex:1;
}
.wgFolderListPath {
color:var(--dsw-alias-label-secondary,inherit);
font-family:var(--dsw-font-mono,ui-monospace,SFMono-Regular,monospace);
font-size:11px;
line-height:1.35;
opacity:.6;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
.wgFolderListTags {
display:inline-flex;
align-items:center;
gap:4px;
flex:none;
}
.wgFolderListTag {
color:var(--dsw-fg-3,#7f7f7fcc);
flex:none;
font-size:11px;
padding:2px 6px;
border:1px solid var(--dsw-alias-border-l2,#7f7f7f40);
border-radius:999px;
color:var(--dsw-alias-label-secondary,inherit);
font-size:10px;
line-height:1.4;
white-space:nowrap;
}
.wgFolderListTag[data-tone="base"] {
border-style:dashed;
}
.wgFolderListTag[data-tone="root"] {
border-color:transparent;
background:#4a90d92e;
color:var(--dsw-fg-1,inherit);
}
.wgFolderListTag[data-tone="cloud"],
.wgFolderListTag[data-tone="local"] {
opacity:.85;
}
.wgFolderListTag[data-tone="danger"] {
border-color:#d464644d;
color:#e08a8a;
}
.wgFolderListActions {
@ -776,26 +924,264 @@
align-items:center;
gap:2px;
display:inline-flex;
opacity:.5;
transition:opacity .12s ease;
}
.wgFolderListFooter {
margin-top:8px;
.wgFolderListRow:hover .wgFolderListActions,
.wgFolderListRow:focus-within .wgFolderListActions {
opacity:1;
}
/* Remote (mirror-backed) workspaces add a folder by typed subpath, so the
footer grows a hint + input row instead of the picker button. */
.wgFolderHint {
.wgFolderEmpty {
margin:0;
padding:10px 12px;
border:1px dashed var(--dsw-alias-border-l2,#7f7f7f40);
border-radius:8px;
color:var(--dsw-alias-label-secondary,inherit);
margin:0 0 6px;
font-size:12px;
font-size:11.5px;
line-height:1.5;
opacity:.85;
opacity:.75;
}
.wgFolderSubpath {
/* Add area: a segmented switch chooses local directory or cloud directory; the
chosen action then owns its own row so nothing competes for its width. */
.wgFolderAdd {
display:flex;
flex-direction:column;
gap:8px;
padding-top:12px;
border-top:1px solid var(--dsw-alias-border-l2,#7f7f7f33);
}
.wgFolderSegmented {
display:inline-flex;
align-self:flex-start;
gap:2px;
padding:2px;
border-radius:999px;
background:#7f7f7f29;
}
.wgFolderTab {
padding:4px 12px;
border:0;
border-radius:999px;
background:none;
color:var(--dsw-alias-label-secondary,inherit);
font:inherit;
font-size:12px;
cursor:pointer;
white-space:nowrap;
transition:background .12s ease,color .12s ease;
}
.wgFolderTab:hover {
color:var(--dsw-fg-1,inherit);
}
/* The selected pill must read as a raised chip inside the tinted track, so it
never looks like the outlined buttons further down the dialog. */
.wgFolderTab[aria-selected="true"] {
background:#ffffff2b;
box-shadow:inset 0 0 0 1px #ffffff1f;
color:var(--dsw-fg-1,inherit);
font-weight:600;
}
.wgFolderLocalPane {
display:flex;
flex-direction:column;
gap:6px;
}
.wgFolderPick {
display:flex;
align-items:center;
gap:8px;
width:100%;
padding:9px 12px;
border:1px dashed var(--dsw-alias-border-l2,#7f7f7f59);
border-radius:8px;
background:none;
color:var(--dsw-fg-1,inherit);
font:inherit;
font-size:12.5px;
font-weight:500;
text-align:left;
cursor:pointer;
white-space:nowrap;
transition:border-color .12s ease,background .12s ease;
}
.wgFolderPick:hover:not(:disabled) {
border-color:var(--dsw-accent,#4a90d9);
background:#4a90d91a;
}
.wgFolderPick:disabled {
opacity:.5;
cursor:default;
}
.wgFolderPickPlus {
flex:none;
color:var(--dsw-accent,#4a90d9);
font-size:13px;
line-height:1;
}
.wgFolderHint {
margin:0;
color:var(--dsw-alias-label-secondary,inherit);
font-size:11px;
line-height:1.55;
opacity:.7;
}
.wgFolderActions {
display:flex;
gap:6px;
}
/* The add actions own their line: a primary button sharing a row with a field
left it too narrow to render its label on one line. */
.wgFolderActions > button {
width:100%;
justify-content:center;
}
.wgFolderStack {
display:flex;
flex-direction:column;
gap:6px;
}
.wgFolderField {
position:relative;
display:flex;
align-items:center;
}
.wgFolderField .wgFolderFieldInput {
width:100%;
padding-right:30px;
}
/* Browse lives inside the path field: the dialog is too narrow to spend a whole
button on it. */
.wgFolderFieldAction {
position:absolute;
right:4px;
top:50%;
transform:translateY(-50%);
display:inline-flex;
align-items:center;
justify-content:center;
width:22px;
height:22px;
padding:0;
border:0;
border-radius:5px;
background:none;
color:var(--dsw-fg-3,#a6abc4);
cursor:pointer;
}
.wgFolderFieldAction:hover:not(:disabled) {
background:var(--dsw-bg-hover,#ffffff1f);
color:var(--dsw-fg-1,inherit);
}
.wgFolderFieldAction:disabled {
opacity:.4;
cursor:default;
}
.wgFolderAddRow {
display:flex;
align-items:center;
gap:6px;
margin-top:6px;
}
.wgFolderAddRow > button {
flex:none;
white-space:nowrap;
}
.wgFolderNote {
margin:0;
color:var(--dsw-alias-label-secondary,inherit);
font-size:11px;
line-height:1.5;
opacity:.8;
}
/* Remote directory picker: location bar on top, directory list under it. */
.wgRemoteBar {
display:flex;
align-items:center;
gap:6px;
margin-bottom:8px;
}
.wgRemotePath {
flex:1 1 auto;
min-width:0;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
font-family:var(--dsw-font-mono,ui-monospace,monospace);
font-size:12px;
color:var(--dsw-fg-1,inherit);
}
.wgRemoteActions {
flex:none;
display:inline-flex;
gap:4px;
}
.wgRemoteList {
max-height:260px;
overflow:auto;
border:1px solid var(--dsw-alias-border-l2,#7f7f7f33);
border-radius:8px;
padding:4px;
margin:0 0 8px;
}
.wgRemoteRow {
display:flex;
align-items:center;
gap:6px;
width:100%;
padding:5px 6px;
border:0;
border-radius:6px;
background:none;
color:var(--dsw-fg-1,inherit);
font:inherit;
font-size:12px;
text-align:left;
cursor:pointer;
}
.wgRemoteRow:hover {
background:var(--dsw-bg-hover,#7f7f7f1f);
}
.wgRemoteName {
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
.wgFolderSelect {
flex:1 1 auto;
width:100%;
min-width:0;
}
.wgFolderSubpathInput {

View File

@ -19,6 +19,7 @@ import { indexSubagentDescendants, type SubagentDescendantSummary } from './suba
import { isDefaultWorkspace } from '../core/default-workspace.ts'
import { categoryAppearance, effectiveCategories, orderedWorkspaceIds, resolveCategory } from '../core/matcher.ts'
import {
absorbedWorkspaceIds,
EMPTY_FOLDERS_DOCUMENT,
effectiveFolders,
entryFor,
@ -231,12 +232,91 @@ function workspaceSessions(
return nodes
}
/** A workspace-backed ("member") folder resolved against the workspace list. */
export interface MemberWorkspaces {
/** Member workspace id → owning workspace id (the rows to hide). */
absorbed: ReadonlyMap<string, string>
/** Owning workspace id → member workspaces in stored folder order. */
byOwner: ReadonlyMap<string, readonly WorkspaceView[]>
}
/**
* Resolve the workspace-backed folders of every project.
*
* A member folder is a real DSH workspace whose OWN row must disappear: its
* sessions are rendered under its owner's folder row instead, so one project can
* carry local and cloud (SSH-mirrored) folders at once. Members the Host no
* longer knows are dropped from the index — the folder row survives (its path is
* still stored) but shows no sessions.
* @param workspaces - real workspaces in Host order.
* @param folders - per-workspace extra folders + members + root.
*/
export function memberWorkspaces(
workspaces: readonly WorkspaceView[],
folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT,
): MemberWorkspaces {
const byId = new Map<string, WorkspaceView>()
for (const workspace of workspaces) byId.set(workspace.workspaceId as string, workspace)
// Only an owner that still exists may hide a row: if the project itself is gone,
// its members must come back as their own rows instead of staying invisible. A
// chained member (an absorbed project that owns members of its own) is refused
// for the same reason — nesting would swallow the inner sessions.
const stored = absorbedWorkspaceIds(folders)
const absorbed = new Map<string, string>()
for (const [memberId, ownerId] of stored) {
if (!byId.has(ownerId) || stored.has(ownerId)) continue
absorbed.set(memberId, ownerId)
}
const byOwner = new Map<string, WorkspaceView[]>()
for (const [ownerId, entry] of Object.entries(folders.workspaces)) {
for (const member of entry.members ?? []) {
if (absorbed.get(member.workspaceId) !== ownerId) continue
const view = byId.get(member.workspaceId)
if (view === undefined) continue
const bucket = byOwner.get(ownerId)
if (bucket === undefined) byOwner.set(ownerId, [view])
else bucket.push(view)
}
}
return { absorbed, byOwner }
}
/** Visible sessions of a project: its own rows plus every member folder's rows. */
function sessionsWithMembers(
list: SessionListState,
workspace: WorkspaceView,
members: readonly WorkspaceView[],
archived: ReadonlySet<SessionId>,
descendants: ReadonlyMap<SessionId, SubagentDescendantSummary>,
statuses: SessionStatuses,
current: SessionId | undefined,
): SessionNode[] {
if (members.length === 0) {
return workspaceSessions(list, workspace, archived, descendants, statuses, current)
}
const nodes = workspaceSessions(list, workspace, archived, descendants, statuses, current)
for (const member of members) {
nodes.push(...workspaceSessions(list, member, archived, descendants, statuses, current))
}
return nodes
}
/** Whether a session lives in this project or in one of its member folders. */
function projectHoldsSession(
workspace: WorkspaceView,
members: readonly WorkspaceView[],
sessionId: SessionId | undefined,
): boolean {
if (sessionId === undefined) return false
if (workspace.sessionIds.includes(sessionId)) return true
return members.some(member => member.sessionIds.includes(sessionId))
}
/**
* Display label of one folder: the last path segment. A drive root (`C:\`) or
* the POSIX root has no segment, so the whole path is the honest label.
* @param path - absolute folder path.
*/
export function folderLabel(path: string): string {
*/export function folderLabel(path: string): string {
const trimmed = path.replace(/[/\\]+$/u, '')
if (trimmed === '' || /^[A-Za-z]:$/u.test(trimmed)) return path
const base = trimmed.split(/[/\\]/u).pop()
@ -248,6 +328,25 @@ export function folderKey(workspaceId: WorkspaceId, path: string): string {
return `${workspaceId}\u0000${path}`
}
/**
* Display labels for member folders.
*
* A cloud member's directory is a locally generated mirror id (`wabc123`), which
* says nothing to the user: its REMOTE path or title is the honest label. Local
* members keep the last path segment, like every other folder.
* @param folders - per-workspace folders + members.
*/
function memberFolderLabels(entry: WorkspaceFolderEntry | undefined): Map<string, string> {
const labels = new Map<string, string>()
for (const member of entry?.members ?? []) {
const label = member.kind === 'remote'
? (member.title ?? folderLabel(member.remotePath ?? member.path))
: folderLabel(member.path)
if (label !== '') labels.set(member.path, label)
}
return labels
}
/**
* Split a workspace's visible sessions between its base directory and its extra
* folders. Sessions keep the order they already had inside their owner, and a
@ -270,6 +369,7 @@ function applyFolders(
entry: WorkspaceFolderEntry | undefined,
collapsedFolders: ReadonlySet<string> | undefined,
): { sessions: readonly SessionNode[]; folders?: readonly FolderNode[] } {
const labels = memberFolderLabels(entry)
const extras = effectiveFolders(workspacePath, entry).slice(1)
if (extras.length === 0) return { sessions }
const root = rootOf(workspacePath, entry)
@ -289,7 +389,7 @@ function applyFolders(
const owned = isBase ? base : (byFolder.get(path) ?? [])
return {
path,
label: folderLabel(path),
label: labels.get(path) ?? folderLabel(path),
isRoot: samePath(path, root),
expanded: collapsedFolders === undefined || !collapsedFolders.has(folderKey(workspaceId, path)),
isBase,
@ -346,6 +446,7 @@ export function deriveGroups(
const collapsedFolders = new Set(view.collapsedFolders ?? [])
const descendants = indexSubagentDescendants(list.byId)
const current = currentSessionId(list)
const members = memberWorkspaces(workspaces, folders)
// Bucket workspaces by display key. Seed with every effective category so
// manual groups render while empty. Top-level (ungrouped) workspaces are
@ -357,6 +458,8 @@ export function deriveGroups(
for (const workspace of workspaces) {
// The Host default workspace is pinned to its own bottom bar, never grouped.
if (isDefaultWorkspace(workspace)) continue
// Member folders render inside their owner; their own row is not a project.
if (members.absorbed.has(workspace.workspaceId as string)) continue
const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
if (key === undefined) continue // top-level — rendered by deriveTopLevel
if (!byCategory.has(key)) byCategory.set(key, [])
@ -366,7 +469,8 @@ export function deriveGroups(
const manualCategories = new Set(manual.categories)
const currentWorkspaceId = current === undefined
? undefined
: workspaces.find(w => w.sessionIds.includes(current))?.workspaceId
: workspaces.find(w => !members.absorbed.has(w.workspaceId as string)
&& projectHoldsSession(w, members.byOwner.get(w.workspaceId as string) ?? [], current))?.workspaceId
const nodes: CategoryNode[] = []
// Effective categories in display order (categoryOrder applied).
@ -381,7 +485,8 @@ export function deriveGroups(
for (const workspaceId of ordered) {
const workspace = bucket.find(w => w.workspaceId === workspaceId)
if (workspace === undefined) continue
const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)
const ownerMembers = members.byOwner.get(workspace.workspaceId as string) ?? []
const sessions = sessionsWithMembers(list, workspace, ownerMembers, archived, descendants, statuses, current)
const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)
const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId
const partitioned = applyFolders(
@ -440,12 +545,15 @@ export function deriveTopLevel(
const collapsedFolders = new Set(view.collapsedFolders ?? [])
const descendants = indexSubagentDescendants(list.byId)
const current = currentSessionId(list)
const members = memberWorkspaces(workspaces, folders)
const currentWorkspaceId = current === undefined
? undefined
: workspaces.find(w => w.sessionIds.includes(current))?.workspaceId
: workspaces.find(w => !members.absorbed.has(w.workspaceId as string)
&& projectHoldsSession(w, members.byOwner.get(w.workspaceId as string) ?? [], current))?.workspaceId
const topLevelIds = workspaces
.filter(w => !isDefaultWorkspace(w))
.filter(w => !members.absorbed.has(w.workspaceId as string))
.filter(w => resolveCategory(config, manual, w.workspaceId, w.path, w.title) === undefined)
.map(w => w.workspaceId as string)
const ordered = orderedWorkspaceIds(manual, TOP_LEVEL_ORDER_KEY, topLevelIds)
@ -454,7 +562,8 @@ export function deriveTopLevel(
for (const workspaceId of ordered) {
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
if (workspace === undefined) continue
const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)
const ownerMembers = members.byOwner.get(workspaceId) ?? []
const sessions = sessionsWithMembers(list, workspace, ownerMembers, archived, descendants, statuses, current)
const wsExpanded = expandedWorkspaces.has(workspaceId)
const partitioned = applyFolders(
workspace.workspaceId,
@ -511,7 +620,9 @@ export function deriveDefaultWorkspace(
const collapsedFolders = new Set(view.collapsedFolders ?? [])
const descendants = indexSubagentDescendants(list.byId)
const current = currentSessionId(list)
const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)
const members = memberWorkspaces(workspaces, folders)
const ownerMembers = members.byOwner.get(workspace.workspaceId as string) ?? []
const sessions = sessionsWithMembers(list, workspace, ownerMembers, archived, descendants, statuses, current)
const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)
const partitioned = applyFolders(
workspace.workspaceId,
@ -528,7 +639,7 @@ export function deriveDefaultWorkspace(
createdAt: Date.parse(workspace.createdAt),
sessionCount: sessions.length,
expanded: wsExpanded,
containsCurrent: current !== undefined && workspace.sessionIds.includes(current),
containsCurrent: projectHoldsSession(workspace, ownerMembers, current),
sessions: wsExpanded ? partitioned.sessions : [],
...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }),
}
@ -562,17 +673,27 @@ export function deriveSearchMatches(
archivedSessionIds: readonly SessionId[],
content: { items: readonly SessionSearchResultItem[]; hasMore: boolean },
limit: number,
folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT,
): SearchMatchSet {
const q = query.trim().toLowerCase()
if (q === '') return { matchedIds: new Set(), snippetsBySession: new Map(), hasMore: false }
const archived = new Set(archivedSessionIds)
const descendants = indexSubagentDescendants(list.byId)
const current = currentSessionId(list)
const members = memberWorkspaces(workspaces, folders)
// A member folder's sessions search as part of the project that shows them.
const workspaceBySession = new Map<SessionId, WorkspaceView>()
for (const workspace of workspaces) {
if (members.absorbed.has(workspace.workspaceId as string)) continue
const owner = workspace
for (const sessionId of workspace.sessionIds) {
if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, workspace)
if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, owner)
}
for (const member of members.byOwner.get(workspace.workspaceId as string) ?? []) {
for (const sessionId of member.sessionIds) {
if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, owner)
}
}
}
const labelOf = (summary: SessionSummary): string =>
@ -666,6 +787,7 @@ export function deriveSearchGroups(
const archived = new Set(archivedSessionIds)
const descendants = indexSubagentDescendants(list.byId)
const current = currentSessionId(list)
const members = memberWorkspaces(workspaces, folders)
const byCategory = new Map<string, WorkspaceGroupNode[]>()
for (const key of effectiveCategories(config, manual).map(e => e.key)) byCategory.set(key, [])
@ -673,19 +795,24 @@ export function deriveSearchGroups(
const topLevel: WorkspaceGroupNode[] = []
let defaultWorkspace: WorkspaceGroupNode | undefined
for (const workspace of workspaces) {
// A member's own row is folded into its owner's folder row below.
if (members.absorbed.has(workspace.workspaceId as string)) continue
// Only sessions that matched the query and are visible in this folder.
const nodes: SessionNode[] = []
for (const id of workspace.sessionIds) {
const summary = list.byId[id]
if (summary === undefined || !matchedIds.has(id)) continue
if (!sessionVisible(summary, current, archived)) continue
const node = sessionNode(summary, descendants, statuses)
const snippet = snippetsBySession?.get(id)
nodes.push({
...node,
matched: true,
...(snippet === undefined ? {} : { snippet }),
})
const sources = [workspace, ...(members.byOwner.get(workspace.workspaceId as string) ?? [])]
for (const source of sources) {
for (const id of source.sessionIds) {
const summary = list.byId[id]
if (summary === undefined || !matchedIds.has(id)) continue
if (!sessionVisible(summary, current, archived)) continue
const node = sessionNode(summary, descendants, statuses)
const snippet = snippetsBySession?.get(id)
nodes.push({
...node,
matched: true,
...(snippet === undefined ? {} : { snippet }),
})
}
}
if (nodes.length === 0) continue

View File

@ -17,9 +17,47 @@
* and no cordis so plain Node (the verifier, the host route) can load it.
*/
/** Kind of a member folder: a plain local directory, or an SSH-mirrored one. */
export type FolderMemberKind = 'local' | 'remote'
/**
* A folder row that is backed by its OWN DSH workspace ("member").
*
* Plain extra folders ( {@link WorkspaceFolderEntry.folders} ) live inside the
* owner's canonical directory tree and their sessions run with the OWNER's
* workspace id. A member has a directory the owner cannot reach that way — a
* remote (mirror-backed) folder, or a local directory added to a remote project
* — so the platform registers a real workspace for it and the row delegates
* session creation to that workspace id. The member's own workspace row is
* hidden from the sidebar while some entry lists it (see
* {@link absorbedWorkspaceIds}), so the project reads as one project with both
* kinds of folders.
*/
export interface FolderMember {
/** Absolute LOCAL path of the member workspace (its canonical directory). */
readonly path: string
/** Native DSH workspace id backing this folder row. */
readonly workspaceId: string
readonly kind: FolderMemberKind
/** Remote root, when `kind` is 'remote' (`~`, `~/proj`, `/srv/proj`). */
readonly remotePath?: string
/** SSH connection profile id, when `kind` is 'remote'. */
readonly profileId?: string
/** remote-ssh's own record id, when `kind` is 'remote'. */
readonly recordId?: string
/** Display title the platform gave the member workspace. */
readonly title?: string
}
/** Folders attached to one workspace: EXTRA folders only (the base is implicit). */
export interface WorkspaceFolderEntry {
/**
* Plain local extra folders: directories the owner workspace can address
* directly, so their sessions keep the owner's workspace id.
*/
readonly folders: readonly string[]
/** Workspace-backed extra folders (remote mirrors, or local on a remote owner). */
readonly members?: readonly FolderMember[]
readonly root?: string
}
@ -103,7 +141,11 @@ export function effectiveFolders(
entry: WorkspaceFolderEntry | undefined,
): readonly string[] {
const extras: string[] = []
for (const folder of entry?.folders ?? []) {
const candidates: string[] = [
...(entry?.folders ?? []),
...(entry?.members ?? []).map(member => member.path),
]
for (const folder of candidates) {
if (folder.trim() === '') continue
if (samePath(folder, workspacePath)) continue
if (extras.some(existing => samePath(existing, folder))) continue
@ -112,6 +154,55 @@ export function effectiveFolders(
return [workspacePath, ...extras]
}
/**
* The member record behind one folder path, when that folder is workspace-backed.
* @param entry - saved folder entry, if any.
* @param path - folder path as stored.
*/
export function memberOf(entry: WorkspaceFolderEntry | undefined, path: string): FolderMember | undefined {
return (entry?.members ?? []).find(member => samePath(member.path, path))
}
/**
* Every member folder of one owner workspace, in stored order.
* @param doc - folders document.
* @param ownerWorkspaceId - workspace the members hang off.
*/
export function membersOf(doc: FoldersDocument, ownerWorkspaceId: string): readonly FolderMember[] {
return entryFor(doc, ownerWorkspaceId)?.members ?? []
}
/**
* Member workspace id → owning workspace id.
*
* These are the workspaces whose own row disappears from the sidebar: their
* sessions render under the owning project's folder row instead. A workspace
* that is itself an owner (it carries an entry) is never absorbed — absorbing
* it would hide a project together with the folders nested below it.
* @param doc - folders document.
*/
export function absorbedWorkspaceIds(doc: FoldersDocument): ReadonlyMap<string, string> {
const owners = new Set(Object.keys(doc.workspaces))
const absorbed = new Map<string, string>()
for (const [ownerId, entry] of Object.entries(doc.workspaces)) {
for (const member of entry.members ?? []) {
if (member.workspaceId === '' || member.workspaceId === ownerId) continue
if (owners.has(member.workspaceId)) continue
if (!absorbed.has(member.workspaceId)) absorbed.set(member.workspaceId, ownerId)
}
}
return absorbed
}
/**
* True when the entry carries neither a plain folder nor a member, i.e. it can
* be dropped from the sidecar instead of being written empty.
* @param entry - folder entry.
*/
export function isEmptyEntry(entry: WorkspaceFolderEntry | undefined): boolean {
return (entry?.folders.length ?? 0) === 0 && (entry?.members?.length ?? 0) === 0
}
/**
* The folder new sessions start in by default.
* @param workspacePath - canonical directory of the workspace.
@ -165,28 +256,47 @@ export function folderOfCwd(
*/
export function addFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry {
const folders = entry?.folders ?? []
const members = entry?.members ?? []
const root = entry?.root
const trimmed = path.trim()
const keepRoot = root === undefined ? {} : { root }
if (trimmed === '' || folders.some(folder => samePath(folder, trimmed))) {
return { folders: [...folders], ...keepRoot }
const keepMembers = members.length === 0 ? {} : { members: [...members] }
if (trimmed === '' || folders.some(folder => samePath(folder, trimmed))
|| members.some(member => samePath(member.path, trimmed))) {
return { folders: [...folders], ...keepMembers, ...keepRoot }
}
return { folders: [...folders, trimmed], ...keepRoot }
return { folders: [...folders, trimmed], ...keepMembers, ...keepRoot }
}
/**
* Drop an extra folder. A root that pointed at it is cleared, so the workspace
* falls back to its own directory instead of referencing a folder it no longer
* has.
* Append a workspace-backed folder. Idempotent under `samePath`: a later call
* for the same path replaces the stored member (so a re-registered workspace id
* wins) instead of stacking a duplicate row.
* @param entry - current entry, or undefined for a workspace with no extras.
* @param member - member record to store.
*/
export function addMember(entry: WorkspaceFolderEntry | undefined, member: FolderMember): WorkspaceFolderEntry {
const folders = (entry?.folders ?? []).filter(folder => !samePath(folder, member.path))
const members = (entry?.members ?? []).filter(existing => !samePath(existing.path, member.path))
const root = entry?.root
const keepRoot = root === undefined || samePath(root, member.path) ? {} : { root }
return { folders: [...folders], members: [...members, member], ...keepRoot }
}
/**
* Drop an extra folder, plain or workspace-backed. A root that pointed at it is
* cleared, so the workspace falls back to its own directory instead of
* referencing a folder it no longer has.
* @param entry - current entry, or undefined.
* @param path - folder path to drop.
*/
export function removeFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry {
const folders = entry?.folders ?? []
const remaining = folders.filter(folder => !samePath(folder, path))
const folders = (entry?.folders ?? []).filter(folder => !samePath(folder, path))
const members = (entry?.members ?? []).filter(member => !samePath(member.path, path))
const root = entry?.root
const keepRoot = root !== undefined && !samePath(root, path)
return { folders: remaining, ...(keepRoot ? { root } : {}) }
const keepMembers = members.length === 0 ? {} : { members }
return { folders: folders, ...keepMembers, ...(keepRoot ? { root } : {}) }
}
/**
@ -198,9 +308,12 @@ export function removeFolder(entry: WorkspaceFolderEntry | undefined, path: stri
*/
export function setRoot(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry {
const folders = entry?.folders ?? []
const match = folders.find(folder => samePath(folder, path))
if (match === undefined) return { folders: [...folders] }
return { folders: [...folders], root: match }
const members = entry?.members ?? []
const keepMembers = members.length === 0 ? {} : { members: [...members] }
const match = [...folders, ...members.map(member => member.path)]
.find(folder => samePath(folder, path))
if (match === undefined) return { folders: [...folders], ...keepMembers }
return { folders: [...folders], ...keepMembers, root: match }
}
/**

View File

@ -18,6 +18,7 @@ import { homedir } from 'node:os'
import {
EMPTY_FOLDERS_DOCUMENT,
samePath,
type FolderMember,
type FoldersDocument,
type WorkspaceFolderEntry,
} from './core/folders.ts'
@ -27,8 +28,10 @@ export const FOLDERS_FILE_NAME = 'workspace-groups.folders.json'
/** Hard limits enforced at the write boundary. */
export const FOLDERS_PER_WORKSPACE_LIMIT = 32
export const MEMBERS_PER_WORKSPACE_LIMIT = 16
export const WORKSPACE_ID_LIMIT = 200
export const FOLDER_PATH_LIMIT = 1024
export const REMOTE_PATH_LIMIT = 1024
/** `C:\…` or `C:/…` — a drive-rooted Windows path. */
const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u
@ -110,6 +113,117 @@ function invalid(detail: string): never {
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`)
}
/** Trim one optional free-form string field, dropping it when unusable. */
function optionalText(value: unknown, limit: number, fail: (detail: string) => void): string | undefined {
if (value === undefined) return undefined
if (typeof value !== 'string') {
fail('member text fields must be strings')
return undefined
}
const text = value.trim()
if (text === '' || text.length > limit || text.includes('\u0000')) return undefined
return text
}
/**
* Parse one workspace-backed ("member") folder.
*
* A member names a real DSH workspace whose own sidebar row is hidden while this
* entry lists it; the fields kept here are exactly what the browser needs to
* start a Session in that workspace and to label the row.
* @param value - raw member from the document.
* @param workspaceId - owning workspace id (used in messages and as a guard).
* @param folders - plain folder paths already accepted for this workspace.
* @param members - member folders already accepted for this workspace.
* @param fail - strict-mode reporter (throws) / tolerant no-op.
* @returns the normalized member, or undefined when unusable.
*/
function parseMember(
value: unknown,
workspaceId: string,
folders: readonly string[],
members: readonly FolderMember[],
fail: (detail: string) => void,
): FolderMember | undefined {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
fail('member folders must be objects')
return undefined
}
const source = value as Record<string, unknown>
const rawPath = source.path
if (typeof rawPath !== 'string') {
fail('member folder path must be a string')
return undefined
}
const path = rawPath.trim()
if (path === '' || path.length > FOLDER_PATH_LIMIT || path.includes('\u0000')) {
fail(`member folder path must be 1-${FOLDER_PATH_LIMIT} characters without NUL`)
return undefined
}
if (!isAbsoluteFolderPath(path)) {
fail(`member folder path "${path}" must be absolute`)
return undefined
}
if (folders.some(folder => samePath(folder, path)) || members.some(member => samePath(member.path, path))) {
fail(`duplicate folder path "${path}"`)
return undefined
}
const rawId = source.workspaceId
if (typeof rawId !== 'string') {
fail('member workspaceId must be a string')
return undefined
}
const memberWorkspaceId = rawId.trim()
if (memberWorkspaceId === '' || memberWorkspaceId.length > WORKSPACE_ID_LIMIT
|| memberWorkspaceId.includes('\u0000')) {
fail(`member workspaceId must be 1-${WORKSPACE_ID_LIMIT} characters without NUL`)
return undefined
}
if (memberWorkspaceId === workspaceId) {
fail('a workspace cannot be a member folder of itself')
return undefined
}
const kind = source.kind
if (kind !== 'local' && kind !== 'remote') {
fail('member kind must be "local" or "remote"')
return undefined
}
const title = optionalText(source.title, FOLDER_PATH_LIMIT, fail)
const keepTitle = title === undefined ? {} : { title }
if (kind === 'local') return { path, workspaceId: memberWorkspaceId, kind, ...keepTitle }
const rawRemote = source.remotePath
if (typeof rawRemote !== 'string') {
fail('a remote member folder needs its remotePath')
return undefined
}
const remotePath = rawRemote.trim()
if (remotePath === '' || remotePath.length > REMOTE_PATH_LIMIT || remotePath.includes('\u0000')) {
fail(`member remotePath must be 1-${REMOTE_PATH_LIMIT} characters without NUL`)
return undefined
}
const rawProfile = source.profileId
if (typeof rawProfile !== 'string') {
fail('a remote member folder needs its profileId')
return undefined
}
const profileId = rawProfile.trim()
if (profileId === '' || profileId.length > WORKSPACE_ID_LIMIT) {
fail(`member profileId must be 1-${WORKSPACE_ID_LIMIT} characters`)
return undefined
}
const recordId = optionalText(source.recordId, WORKSPACE_ID_LIMIT, fail)
return {
path,
workspaceId: memberWorkspaceId,
kind,
remotePath,
profileId,
...(recordId === undefined ? {} : { recordId }),
...keepTitle,
}
}
/**
* Parse one workspace entry.
* @param value - raw entry from the document.
@ -176,20 +290,37 @@ function parseFolderEntry(
folders.push(path)
}
const members: FolderMember[] = []
if (source.members !== undefined) {
if (!Array.isArray(source.members)) {
fail('members must be a list')
} else {
if (strict && source.members.length > MEMBERS_PER_WORKSPACE_LIMIT) {
invalid(`workspace "${workspaceId}": at most ${MEMBERS_PER_WORKSPACE_LIMIT} member folders`)
}
for (const candidate of source.members) {
const member = parseMember(candidate, workspaceId, folders, members, fail)
if (member !== undefined) members.push(member)
if (members.length >= MEMBERS_PER_WORKSPACE_LIMIT) break
}
}
}
let root: string | undefined
if (source.root !== undefined) {
if (typeof source.root !== 'string') {
fail('root must be a string')
} else {
const candidate = source.root.trim()
const member = folders.find(folder => samePath(folder, candidate))
const member = [...folders, ...members.map(entry => entry.path)]
.find(folder => samePath(folder, candidate))
if (member === undefined) fail(`root "${candidate}" must name one of folders`)
else root = member
}
}
if (folders.length === 0 && root === undefined) return undefined
return { folders, ...(root === undefined ? {} : { root }) }
if (folders.length === 0 && members.length === 0 && root === undefined) return undefined
return { folders, ...(members.length === 0 ? {} : { members }), ...(root === undefined ? {} : { root }) }
}
/**