feat: science icons, pinned default workspace and one trailing row slot

- add 28 hand-drawn "materials & lab" glyphs (lab operations, materials,
  characterization, devices) to the group icon set and expose them as their own
  sections in the appearance picker; identical 16x16 line style, bilingual
  labels, old ids untouched
- make the appearance dialog scroll inside the host modal so the footer and the
  pin button never collide with the icon grid
- give every row kind one right-aligned trailing slot: the member count or the
  session time sits flush with the row's right edge and yields to the "+" / "..."
  buttons on hover or keyboard focus without any reflow; all rows now order them
  "+" then "..."
- move the host default workspace out of the tree into a pinned bottom bar with
  the full workspace row capabilities, deduplicated from groups, top level and
  search results
- add tools/verify-row-layout.mjs: vitest cannot start in this checkout, so the
  layout invariants are asserted over the stylesheet and the row markup
This commit is contained in:
qyh15 2026-10-28 20:08:18 +08:00
parent 2fb87d1904
commit fe455421c5
21 changed files with 3572 additions and 912 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

@ -12,6 +12,39 @@ export declare const BRANCH_ROW_ATTRIBUTE = "data-wg-branch-row";
export declare const BRANCH_ACTIVE_ATTRIBUTE = "data-wg-branch-active";
/** Row kind marker: a group boundary kinks the stem. */
export declare const BRANCH_GROUP_ATTRIBUTE = "data-wg-branch-group";
/**
* The bloom at the branch's endpoint.
*
* Anchoring is done entirely by these transforms, in this order:
*
* 1. `translate(cx cy)` — put the origin on the stem's tip (the endpoint of
* the grown stroke).
* 2. `scale(FLOWER_SCALE)` — shrink the 1024-unit artwork about that origin.
* 3. `translate(-512 -512)` — bring the glyph's own centre (512, 512) onto the
* origin, so the flower is centred on the tip.
*
* The spin is applied by `wgFlowerArt` in CSS as a `rotate()` composed AFTER
* that recentring (`translate(-512 -512) rotate(...)`), so the bloom turns about
* its own centre and the recentring never drifts as it rotates.
*
* Note what is deliberately NOT used here: a percentage `translate(-50%, -50%)`
* or `transform-box: fill-box` + percentage `transform-origin`. Measured on the
* live page, the percentage form resolved against the SVG VIEWPORT rather than
* the path's box, translating by (-24, -409.5) instead of (-373, -409.6) and
* parking the bloom well right of the stem. Explicit user units remove the
* question: 512 is the measured centre, not an inferred one.
*
* The flower rests while the session is idle and turns while it works: one
* animation, paused rather than removed, so a state flip resumes the turn
* instead of snapping the petals back to 0deg.
*
* @param props - endpoint coordinates and whether the session is working.
* @returns the bloom group.
*/
/** In-flow session marker: its position follows the row, including disclosure animations. */
export declare function SessionFlower({ spinning }: {
spinning: boolean;
}): import("react").JSX.Element;
/**
* Render the branch for the rows currently inside `scope`.
* @param props - the element to measure, and whether the open session is working.

53
lib/types/client/group-icon-labels.d.ts vendored Normal file
View File

@ -0,0 +1,53 @@
import type { GroupIconId } from '../core/types.ts';
/** Bilingual accessible names also make native browser tooltips recognizable in either locale. */
export declare const GROUP_ICON_LABELS: Record<GroupIconId, string>;
/** All presets satisfy the existing host's 1–4 Unicode-code-point custom-glyph rule. */
export declare const GROUP_EMOJI_ICONS: readonly [{
readonly icon: "🚀";
readonly label: "启动 / Launch";
}, {
readonly icon: "📚";
readonly label: "学习 / Learning";
}, {
readonly icon: "🔬";
readonly label: "科研 / Research";
}, {
readonly icon: "🧪";
readonly label: "实验 / Experiment";
}, {
readonly icon: "🎨";
readonly label: "创作 / Art";
}, {
readonly icon: "🎯";
readonly label: "目标 / Target";
}, {
readonly icon: "💡";
readonly label: "想法 / Idea";
}, {
readonly icon: "🛠️";
readonly label: "工具 / Tools";
}, {
readonly icon: "🌱";
readonly label: "成长 / Growth";
}, {
readonly icon: "🏠";
readonly label: "生活 / Home";
}, {
readonly icon: "💼";
readonly label: "工作 / Work";
}, {
readonly icon: "🎮";
readonly label: "游戏 / Games";
}, {
readonly icon: "🎵";
readonly label: "音乐 / Music";
}, {
readonly icon: "❤️";
readonly label: "收藏 / Favorites";
}, {
readonly icon: "⭐";
readonly label: "星标 / Star";
}, {
readonly icon: "🔥";
readonly label: "热门 / Hot";
}];

View File

@ -0,0 +1,79 @@
/**
* Self-drawn monochrome artwork for the "Materials & Lab" icon family.
*
* The Host primitive package only ships product/generic glyphs, so the 28
* research icons are drawn here in the exact same visual language as the Host
* ones: a 16x16 viewBox, `currentColor` stroke, 1.3 stroke width (Host
* `ICON_MEDIUM_STROKE`), round caps/joins and no fill. Keeping the artwork as
* primitive data (instead of one opaque `<path>` per icon) lets the icon test
* assert every coordinate stays inside the viewBox and that each id has
* artwork — a hand-tuned path string could silently drift out of frame.
*/
import type { ReactElement } from 'react';
/** One drawable primitive of a 16x16 icon; coordinates are in viewBox units. */
export type SciencePrimitive = {
readonly kind: 'line';
readonly x1: number;
readonly y1: number;
readonly x2: number;
readonly y2: number;
} | {
readonly kind: 'rect';
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
readonly radius?: number;
} | {
readonly kind: 'circle';
readonly cx: number;
readonly cy: number;
readonly radius: number;
readonly filled?: boolean;
} | {
readonly kind: 'ellipse';
readonly cx: number;
readonly cy: number;
readonly rx: number;
readonly ry: number;
/** Rotation around the icon centre (8,8), in degrees. */
readonly rotate?: number;
} | {
readonly kind: 'path';
readonly d: string;
};
/** Ids appended to the shared registry; order is the picker's section order. */
export declare const SCIENCE_ICON_IDS: readonly ["test-tube", "flask", "pipette", "dropper", "stirrer", "hotplate", "centrifuge", "balance", "atom", "molecule", "lattice", "layered", "framework", "thin-film", "fiber", "hydrogel", "microscope", "xrd", "spectrum", "tensile", "electrode", "iv-curve", "illumination", "temperature", "humidity", "actuator", "flex-sensor", "battery"];
/** Union of the research icon ids (a subset of the shared `GroupIconId`). */
export type ScienceIconId = (typeof SCIENCE_ICON_IDS)[number];
/** The picker's section split of the research family. */
export declare const SCIENCE_ICON_SECTIONS: readonly [{
readonly key: "lab";
readonly ids: readonly ["test-tube", "flask", "pipette", "dropper", "stirrer", "hotplate", "centrifuge", "balance"];
}, {
readonly key: "materials";
readonly ids: readonly ["atom", "molecule", "lattice", "layered", "framework", "thin-film", "fiber", "hydrogel"];
}, {
readonly key: "characterization";
readonly ids: readonly ["microscope", "xrd", "spectrum", "tensile", "electrode", "iv-curve"];
}, {
readonly key: "devices";
readonly ids: readonly ["illumination", "temperature", "humidity", "actuator", "flex-sensor", "battery"];
}];
/** Primitive artwork per research icon. */
export declare const SCIENCE_ICON_ART: Record<ScienceIconId, readonly SciencePrimitive[]>;
/** Research icon id → picker section key. */
export declare const SCIENCE_ICON_SECTION_OF: Record<ScienceIconId, (typeof SCIENCE_ICON_SECTIONS)[number]['key']>;
/**
* Render one research icon in the Host glyph's visual language: 16x16,
* `currentColor` stroke, 1.3px, round joins, decorative for screen readers (the
* row/picker button already carries the bilingual name).
* @param props.icon - research icon id.
* @param props.size - rendered square size in CSS pixels (default 16, like Host glyphs).
*/
export declare function ScienceGlyph({ icon, size }: {
icon: ScienceIconId;
size?: number;
}): ReactElement;
/** Research icon id → rendered node, merged into the row icon registry. */
export declare function scienceIconNodes(): Record<ScienceIconId, ReactElement>;

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

@ -144,6 +144,24 @@ export declare function deriveGroups(list: SessionListState, workspaces: readonl
* falling back to host registration order.
*/
export declare function deriveTopLevel(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses, folders?: FoldersDocument): WorkspaceGroupNode[];
/**
* The Host's default workspace as a standalone node for the pinned bottom bar.
*
* The default workspace is not part of the grouping tree (it is excluded from
* `deriveGroups`, `deriveTopLevel` and the search results), yet it keeps the
* full workspace-row behaviour: expansion, session count, its sessions and its
* extra folders. This derives exactly that node, reusing the same visibility,
* folder partitioning and current-session marking as the tree.
*
* @param list - sessions list snapshot.
* @param workspaces - real workspaces in stable Host order.
* @param archivedSessionIds - registry-global archive set.
* @param view - local expansion arrays.
* @param statuses - unified UI status by Session.
* @param folders - per-workspace extra folders + root.
* @returns the default workspace node, or undefined when the Host has none.
*/
export declare function deriveDefaultWorkspace(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], view: GroupsTreeView, statuses?: SessionStatuses, folders?: FoldersDocument): WorkspaceGroupNode | undefined;
/** Bounded set of matched sessions plus content snippets (feeds the search tree). */
export interface SearchMatchSet {
/** Session ids that matched (local metadata hits + Host content hits). */
@ -167,6 +185,12 @@ export interface SearchTree {
categories: CategoryNode[];
/** Top-level (ungrouped) workspaces holding matched sessions. */
topLevel: WorkspaceGroupNode[];
/**
* The Host default workspace's matched branch, when it has a hit. It is
* rendered in the pinned bottom bar instead of the results list, so a hit
* never makes the default workspace appear twice.
*/
defaultWorkspace?: WorkspaceGroupNode;
}
/**
* Build a three-level search tree containing ONLY the branches that hold a

32
lib/types/core/default-workspace.d.ts vendored Normal file
View File

@ -0,0 +1,32 @@
/**
* Recognising the Host's own default workspace ("默认工作区").
*
* The workspace snapshot carries no `isDefault` flag, so the only Host-owned
* signal is the one the Host itself uses: the registry title. Its
* `workspaceDisplayTitle()` treats a title equal to `DEFAULT_WORKSPACE_DIRECTORY`
* as "the default workspace" and swaps in a localized label. That constant lives
* in the workspace-controller package, which this plugin must not import at
* runtime (it is a client bundle), so the string is mirrored here.
*
* Two Host signals are combined:
* - the registry title (primary: exactly what the Host substitutes for);
* - the Host's own directory layout (`<Documents>/deepseek-harness/default-workspace`),
* which still identifies the workspace after the user renames it.
* A user-created directory that merely happens to be called "default-workspace"
* somewhere else on disk is NOT treated as the default workspace, and no single
* directory name is used as the sole test.
*/
/** Directory name the Host uses for its default workspace (host mirror). */
export declare const DEFAULT_WORKSPACE_TITLE = "default-workspace";
/** The fields the identification needs from a workspace snapshot. */
export interface DefaultWorkspaceIdentity {
/** Registry title (`WorkspaceView.title`). */
title?: string | undefined;
/** Absolute workspace directory (`WorkspaceView.path`). */
path?: string | undefined;
}
/**
* Whether a workspace snapshot is the Host's default workspace.
* @param workspace - workspace snapshot (title is the primary signal, path the fallback).
*/
export declare function isDefaultWorkspace(workspace: DefaultWorkspaceIdentity): boolean;

View File

@ -26,8 +26,9 @@ export type GroupColor = 'red' | 'orange' | 'amber' | 'green' | 'teal' | 'blue'
/** Whitelist shared by the host write-validation and the client picker. */
export declare const GROUP_COLORS: readonly GroupColor[];
/** Curated icon ids (rendered from @deepseek-ai/dsh-client-ui-primitives). */
export type GroupIconId = 'folder' | 'workspace' | 'code' | 'plugin' | 'skill' | 'data' | 'database' | 'api' | 'plan' | 'goal' | 'light' | 'globe' | 'archive' | 'branch' | 'users' | 'clock' | 'shield' | 'checklist' | 'sparkle' | 'tree';
export declare const GROUP_ICON_IDS: readonly GroupIconId[];
export declare const GROUP_ICON_IDS: readonly ["folder", "workspace", "code", "plugin", "skill", "data", "database", "api", "plan", "goal", "light", "globe", "archive", "branch", "users", "clock", "shield", "checklist", "sparkle", "tree", "chat", "search", "settings", "document", "edit", "think", "agent", "browse", "context", "link", "share", "user", "send", "attachment", "download", "play", "design", "moon", "monitor", "gauge", "queue", "notes", "inspect", "help", "info", "alarm", "compare", "done", "pin", "microphone", "test-tube", "flask", "pipette", "dropper", "stirrer", "hotplate", "centrifuge", "balance", "atom", "molecule", "lattice", "layered", "framework", "thin-film", "fiber", "hydrogel", "microscope", "xrd", "spectrum", "tensile", "electrode", "iv-curve", "illumination", "temperature", "humidity", "actuator", "flex-sensor", "battery"];
/** Derived from the shared registry so host validation and UI cannot drift. */
export type GroupIconId = (typeof GROUP_ICON_IDS)[number];
/**
* Presentation metadata for one group. Every field optional.
*
@ -38,7 +39,7 @@ export declare const GROUP_ICON_IDS: readonly GroupIconId[];
export interface CategoryAppearance {
/** Palette id; the CSS palette lives in styles.css `[data-wg-color]`. */
color?: GroupColor | undefined;
/** `GroupIconId` preset id, or a short glyph (1–4 code units, emoji/latin). */
/** `GroupIconId` preset id, or a short glyph (1–4 Unicode code points, emoji/latin). */
icon?: string | undefined;
/** Pinned groups sort before unpinned ones (within the manual order). */
pinned?: boolean | undefined;

View File

@ -106,6 +106,17 @@ const FLOWER_CENTRE = 512
* @param props - endpoint coordinates and whether the session is working.
* @returns the bloom group.
*/
/** In-flow session marker: its position follows the row, including disclosure animations. */
export function SessionFlower({ spinning }: { spinning: boolean }) {
return (
<svg width={17} height={17} viewBox="0 0 1024 1024"
className={spinning ? 'wgSessionFlower wgFlowerSpinning' : 'wgSessionFlower'}
aria-hidden="true" focusable="false" style={{ flex: 'none', overflow: 'visible' }}>
<path className="wgFlowerArt" d={FLOWER_PATH} fill={FLOWER_PETAL} />
</svg>
)
}
function Flower({ cx, cy, spinning }: { cx: number; cy: number; spinning: boolean }) {
return (
<g

View File

@ -14,7 +14,7 @@
* through `PUT /workspace-groups/manual`; the sidecar YAML is never rewritten
* (rule-group rename/delete ride the overlay `renamed`/`hidden` maps).
*/
import { useEffect, useMemo, useRef, useState, type DragEvent } from 'react'
import { useEffect, useMemo, useRef, useState, type DragEvent, type ReactElement } from 'react'
import {
Button,
IconCloseFillMedium,
@ -52,16 +52,17 @@ import {
type ManualGroups,
} from '../core/types.ts'
import type { GroupsBrowserProps } from './contract.ts'
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, folderKey, folderLabel, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'
import { deriveDefaultWorkspace, deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, folderKey, folderLabel, 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 { loadFolders, saveFolders } from './folders-persist.ts'
import { createWorkspaceDirectory, remoteFolderWorkspace } from './folder-directory.ts'
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
import { QuickPanel } from './QuickPanel.tsx'
import { SessionTabs } from './SessionTabs.tsx'
import { FlowerBranch } from './FlowerBranch.tsx'
import css from './styles.css?inline'
const SEARCH_DEBOUNCE_MS = 250
@ -119,6 +120,38 @@ const COLOR_LABEL_KEYS: Record<GroupColor, WorkspaceGroupsKey> = {
gray: 'color.gray',
}
/** 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). */
const SCIENCE_SECTION_LABEL_KEYS: Record<'lab' | 'materials' | 'characterization' | 'devices', WorkspaceGroupsKey> = {
lab: 'group.icon.section.lab',
materials: 'group.icon.section.materials',
characterization: 'group.icon.section.characterization',
devices: 'group.icon.section.devices',
}
/** The pre-existing glyphs, shown as the picker's "common" section. */
const COMMON_ICON_IDS = GROUP_ICON_IDS.filter(id => !SCIENCE_ICON_ID_SET.has(id))
/**
* The same workspace node without its extra folders and session rows: used
* while searching, so the pinned default-workspace bar never paints unrelated
* sessions next to pruned search results.
*/
function withoutSessions(node: WorkspaceGroupNode): WorkspaceGroupNode {
return {
workspaceId: node.workspaceId,
path: node.path,
label: node.label,
createdAt: node.createdAt,
sessionCount: node.sessionCount,
expanded: node.expanded,
containsCurrent: node.containsCurrent,
sessions: [],
}
}
function sanitizeSearchQuery(value: string): string {
const withoutNul = value.replaceAll('\0', '')
if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul
@ -318,17 +351,6 @@ export function GroupsBrowser({
? undefined
: (workspaces.find(w => w.sessionIds.includes(current as SessionId))?.workspaceId as string | undefined)
// Whether the open session is WORKING right now, which is what makes the
// flower at the branch's endpoint turn. Read from the unified status snapshot
// (the catalog summary alone goes stale), folded together with the session's
// own `running` so a subagent-only turn still counts.
//
// Derived as a boolean on purpose: the overlay re-measures through its own
// MutationObserver, so handing it a live value would re-render the tree on
// every status tick.
const currentRunning = current !== undefined
&& ((statuses.get(current)?.running ?? false) || (list.byId[current]?.running ?? false))
// Auto-expand the category + workspace containing the current session, but
// ONLY when the user has never touched that key (`Object.hasOwn`): a
// present `false` is a deliberate collapse and must stay folded. Without
@ -375,10 +397,6 @@ export function GroupsBrowser({
})
const searchInput = useRef<HTMLInputElement | null>(null)
const searchRoot = useRef<HTMLDivElement | null>(null)
// Box the flower branch measures and paints into. Held as a ref (not state)
// because the overlay re-measures on its own MutationObserver; a state update
// here would re-render the whole tree on every layout tick.
const branchScope = useRef<HTMLDivElement | null>(null)
// Search debounce + abort, same posture as the official browser.
useEffect(() => {
@ -444,6 +462,37 @@ export function GroupsBrowser({
}, manual, statuses, foldersDoc),
[list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces, collapsedFolderKeys, foldersDoc],
)
// The Host's default workspace is not part of the grouping tree: it is pinned
// to its own bar at the bottom of the sidebar (see deriveDefaultWorkspace and
// the exclusions in tree.ts), while keeping the full workspace-row behaviour.
const defaultWorkspace = useMemo(
() => deriveDefaultWorkspace(list, workspaces, archivedSessionIds, {
expandedCategories,
expandedWorkspaces,
collapsedFolders: collapsedFolderKeys,
}, statuses, foldersDoc),
[list, workspaces, archivedSessionIds, statuses, foldersDoc, expandedCategories, expandedWorkspaces, collapsedFolderKeys],
)
// Search derivation lives here (not inside SearchBody) so the pinned
// default-workspace bar can show the very same pruned branch the results use.
const activeRemoteSearch = useMemo<RemoteSearchState>(
() => (remoteSearch.query === normalizedQuery
? remoteSearch
: { query: normalizedQuery, status: 'loading', items: [], hasMore: false }),
[remoteSearch, normalizedQuery],
)
const searchMatches = useMemo<SearchMatchSet | undefined>(
() => (normalizedQuery === ''
? undefined
: deriveSearchMatches(list, workspaces, config, normalizedQuery, archivedSessionIds, activeRemoteSearch, searchResultLimit)),
[list, workspaces, config, normalizedQuery, archivedSessionIds, activeRemoteSearch, searchResultLimit],
)
const searchTree = useMemo<SearchTree | undefined>(
() => (searchMatches === undefined
? undefined
: deriveSearchGroups(list, workspaces, config, searchMatches.matchedIds, archivedSessionIds, manual, searchMatches.snippetsBySession, statuses, foldersDoc)),
[list, workspaces, config, searchMatches, archivedSessionIds, manual, statuses, foldersDoc],
)
// Quick panel (Ctrl+R): category label per grouped workspace id (the tree
// derivation already resolved grouping; top-level workspaces stay absent).
const categoryByWorkspace = useMemo(() => {
@ -1233,8 +1282,38 @@ export function GroupsBrowser({
}
}
// Appearance picker cell: the same glyph button for every icon section
// (common presets, the four research sections, and the emoji row).
const renderIconCell = (id: string, label: string): ReactElement => (
<button
key={id}
type="button"
className="wgIconCell"
aria-pressed={appearanceCurrent.icon === id}
aria-label={label}
title={label}
disabled={manualSaving}
onClick={() => {
setAppearanceDraft({ ...appearanceDraft, icon: id })
setAppearanceError(null)
if (appearanceTarget !== null) void updateCategoryAppearance(appearanceTarget, { icon: id })
}}
>
<CategoryGlyph icon={id} />
</button>
)
const now = Date.now()
// 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.
const defaultBarNode = defaultWorkspace === undefined
? undefined
: normalizedQuery === ''
? defaultWorkspace
: (searchTree?.defaultWorkspace ?? withoutSessions(defaultWorkspace))
return (
<div className={`wgRoot${wide ? '' : ' wgRail'}`}>
{/* The tab strip portals itself into the conversation column's head seat,
@ -1345,21 +1424,14 @@ export function GroupsBrowser({
{manualError !== null && (
<div className="wgSearchStatus wgManualError" role="alert">{t('manual.saveError')}: {manualError}</div>
)}
{wide && normalizedQuery !== '' ? (
{wide && normalizedQuery !== '' && searchTree !== undefined && searchMatches !== undefined ? (
<SearchBody
list={list}
workspaces={workspaces}
config={config}
archivedSessionIds={archivedSessionIds}
statuses={statuses}
query={normalizedQuery}
remote={remoteSearch}
resultLimit={searchResultLimit}
tree={searchTree}
matches={searchMatches}
status={activeRemoteSearch.status}
current={current}
now={now}
open={open}
manual={manual}
folders={foldersDoc}
t={t}
/>
) : (
@ -1367,10 +1439,11 @@ export function GroupsBrowser({
the rows and paints behind them, so it must share their box without
becoming a row itself (which would break role="tree" semantics and
the index-based measurement). */
<div className="wgTreeWrap" ref={branchScope}>
<FlowerBranch scope={branchScope.current} spinning={currentRunning} />
<div className="wgTreeWrap">
<div className="wgList" role="tree" aria-label={t('section.workspaces')}>
{groups.length === 0 && topLevel.length === 0 && !topLevelDropActive && (
{/* The pinned default workspace sits in its own bottom bar, so a tree
holding nothing but that workspace is not "empty". */}
{groups.length === 0 && topLevel.length === 0 && !topLevelDropActive && defaultBarNode === undefined && (
<div className="wgEmpty">{workspacePhase === 'ready' ? t('empty.noWorkspaces') : t('empty.none')}</div>
)}
{groups.map((category) => (
@ -1488,6 +1561,53 @@ export function GroupsBrowser({
)}
</div>
{/* Pinned default workspace: a sibling of the tree's scroll area (not a
row inside it), above a divider, so a long session list can never
push it away or scroll it out. It keeps the whole workspace-row
behaviour — toggle, new session, rename, delete, ⋯ menu, folder
management — and its sessions still highlight as usual. */}
{wide && defaultBarNode !== undefined && (
<div className="wgDefaultWorkspaceBar" role="group" aria-label={t('section.defaultWorkspace')}>
<WorkspaceRow
node={defaultBarNode}
t={t}
flat
onToggle={() => { actions.setWorkspaceExpanded(defaultBarNode.workspaceId as string, !workspaceExpansion[defaultBarNode.workspaceId]) }}
onNewSession={() => { startSessionAtRoot(defaultBarNode.workspaceId) }}
onRename={() => {
setRenameTarget({ workspaceId: defaultBarNode.workspaceId, currentTitle: defaultBarNode.label })
setRenameDraft(defaultBarNode.label)
setRenameError(null)
}}
onDelete={() => {
setDeleteTarget({ workspaceId: defaultBarNode.workspaceId, title: defaultBarNode.label })
setDeleteError(null)
}}
{...(openInFolder !== undefined
? { onOpenInFolder: () => { openInFolder(defaultBarNode.workspaceId) } }
: {})}
onManageFolders={() => { setFoldersTarget(defaultBarNode.workspaceId) }}
/>
<WorkspaceSubtree
workspace={defaultBarNode}
current={current}
now={now}
t={t}
animate={dragging === null}
onOpen={open}
onSessionRename={onSessionRename}
onSessionArchive={onSessionArchive}
onFork={forkSession}
onToggleFolder={toggleFolder}
onFolderNewSession={startSessionInFolder}
onFolderSetRoot={setFolderRoot}
onFolderRemove={removeFolderFrom}
onOpenFolderPath={openFolderPath}
creatingFolderKey={creatingSessionIn}
/>
</div>
)}
{/* Group create / rename dialog */}
<Modal
open={groupDialog !== null}
@ -1534,18 +1654,23 @@ export function GroupsBrowser({
</Modal>
{/* Group appearance dialog: every control writes immediately (optimistic
patch + rollback banner), so the footer is only "done". */}
patch + rollback banner), so the footer is only "done". The body is a
single scroll column (the dialog caps itself at the viewport and keeps
the footer outside the scroller), and the sections are spaced so a
focused field's ring never touches the next control. */}
<Modal
open={appearanceTarget !== null}
onClose={() => { setAppearanceTarget(null) }}
closeLabel={t('group.appearanceDone')}
title={t('group.appearanceTitle')}
className="wgAppearanceDialog"
contentClassName="wgAppearanceContent"
footer={(
<Button variant="primary" onClick={() => { setAppearanceTarget(null) }}>{t('group.appearanceDone')}</Button>
)}
>
{appearanceTarget !== null && (
<>
<div className="wgAppearanceBody">
<div className="wgAppearanceSection">
<div className="wgAppearanceLabel">{t('group.color')}</div>
<div className="wgSwatchRow" role="group" aria-label={t('group.color')}>
@ -1578,49 +1703,71 @@ export function GroupsBrowser({
</div>
<div className="wgAppearanceSection">
<div className="wgAppearanceLabel">{t('group.icon')}</div>
<div className="wgIconGrid" role="group" aria-label={t('group.icon')}>
{GROUP_ICON_IDS.map((id) => {
const active = appearanceCurrent.icon === id
{/* Categorised picker: the pre-existing presets stay together as
the common section, the research family is split into its four
families, the emoji stay in their own row. The sections share
one height-capped scroller so the footer button is never
pushed out of the dialog. */}
<div className="wgIconSections">
<div className="wgIconSection">
<div className="wgIconSectionLabel">{t('group.icon.section.common')}</div>
<div className="wgIconGrid" role="group" aria-label={t('group.icon.section.common')}>
{COMMON_ICON_IDS.map(id => renderIconCell(id, GROUP_ICON_LABELS[id]))}
</div>
</div>
{SCIENCE_ICON_SECTIONS.map(section => {
const label = t(SCIENCE_SECTION_LABEL_KEYS[section.key])
return (
<button
key={id}
type="button"
className="wgIconCell"
aria-pressed={active}
aria-label={id}
title={id}
disabled={manualSaving}
onClick={() => {
setAppearanceDraft({ ...appearanceDraft, icon: id })
setAppearanceError(null)
void updateCategoryAppearance(appearanceTarget, { icon: id })
}}
>
<CategoryGlyph icon={id} />
</button>
<div key={section.key} className="wgIconSection">
<div className="wgIconSectionLabel">{label}</div>
<div className="wgIconGrid" role="group" aria-label={label}>
{section.ids.map(id => renderIconCell(id, GROUP_ICON_LABELS[id]))}
</div>
</div>
)
})}
<div className="wgIconSection">
<div className="wgIconSectionLabel">{t('group.icon.section.emoji')}</div>
<div className="wgIconGrid wgEmojiGrid" role="group" aria-label={t('group.icon.section.emoji')}>
{GROUP_EMOJI_ICONS.map(({ icon, label }) => renderIconCell(icon, label))}
</div>
</div>
</div>
<div className="wgIconCustom">
<button
type="button"
className="wgIconCell wgIconDefault"
aria-pressed={appearanceCurrent.icon === undefined}
disabled={manualSaving}
onClick={() => {
setAppearanceDraft({ ...appearanceDraft, icon: '' })
setAppearanceError(null)
void updateCategoryAppearance(appearanceTarget, { icon: undefined })
}}
>
{t('group.iconDefault')}
</button>
<input
className="wgRenameInput"
value={appearanceDraft.icon ?? ''}
aria-label={t('group.iconCustom')}
placeholder={t('group.iconDefault')}
disabled={manualSaving}
onChange={(e) => {
setAppearanceDraft({ ...appearanceDraft, icon: e.target.value })
setAppearanceError(null)
}}
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
draft here would race it and could overwrite the preset. */
const next = event.relatedTarget
if (next instanceof Element && next.closest('.wgSwatch, .wgIconCell') !== null) return
commitAppearanceIcon()
}}
/>
</div>
<input
className="wgRenameInput"
value={appearanceDraft.icon ?? ''}
aria-label={t('group.iconCustom')}
placeholder={t('group.iconDefault')}
disabled={manualSaving}
onChange={(e) => {
setAppearanceDraft({ ...appearanceDraft, icon: e.target.value })
setAppearanceError(null)
}}
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
draft here would race it and could overwrite the preset. */
const next = event.relatedTarget
if (next instanceof Element && next.closest('.wgSwatch, .wgIconCell') !== null) return
commitAppearanceIcon()
}}
/>
</div>
<div className="wgAppearanceSection">
<Button
@ -1632,7 +1779,7 @@ export function GroupsBrowser({
</Button>
</div>
{appearanceError !== null && <div className="wgAddError" role="alert">{appearanceError}</div>}
</>
</div>
)}
</Modal>
@ -2190,35 +2337,25 @@ function SearchSubtree({ workspace, current, now, open, t }: {
* Only branches that contain a hit are rendered, which keeps a long list short. Reuses the same row components as
* the idle tree, so search keeps the same folder hierarchy the user is used to.
*/
function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, query, remote, resultLimit, current, now, open, manual, folders, t }: {
list: SessionListState
workspaces: readonly WorkspaceView[]
config: GroupsConfig
archivedSessionIds: readonly SessionId[]
statuses: SessionStatusSnapshot
query: string
remote: RemoteSearchState
resultLimit: number
/**
* 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
* categories / top-level projections and hands it back as `tree.defaultWorkspace`.
*/
function SearchBody({ tree, matches, status, current, now, open, t }: {
tree: SearchTree
matches: SearchMatchSet
status: RemoteSearchState['status']
current: SessionId | undefined
now: number
open: (sessionId: SessionId) => void
manual: ManualGroups
folders: FoldersDocument
t: GroupsBrowserProps['t']
}) {
const currentRemote = remote.query === query ? remote : { query, status: 'loading' as const, items: [], hasMore: false }
const matches = useMemo(
() => deriveSearchMatches(list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit),
[list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit],
)
const searchTree = useMemo(
() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession, statuses, folders),
[list, workspaces, config, matches, archivedSessionIds, manual, statuses, folders],
)
const groups = searchTree.categories
const searchTopLevel = searchTree.topLevel
const pending = currentRemote.status === 'loading'
const failed = currentRemote.status === 'error'
const groups = tree.categories
const searchTopLevel = tree.topLevel
const pending = status === 'loading'
const failed = status === 'error'
return (
<div className="wgList" role="tree" aria-label={t('search.results.aria')}>
{groups.map((category) => (

View File

@ -0,0 +1,54 @@
import type { GroupIconId } from '../core/types.ts'
/** Bilingual accessible names also make native browser tooltips recognizable in either locale. */
export const GROUP_ICON_LABELS: Record<GroupIconId, string> = {
folder: '文件夹 / Folder', workspace: '工作区 / Workspace', code: '代码 / Code',
plugin: '插件 / Plugin', skill: '技能 / Skill', data: '数据 / Data',
database: '数据库 / Database', api: '接口 / API', plan: '计划 / Plan',
goal: '目标 / Goal', light: '日光 / Sun', globe: '全球 / Globe',
archive: '归档 / Archive', branch: '分支 / Branch', users: '团队 / Team',
clock: '时间 / Clock', shield: '安全 / Security', checklist: '清单 / Checklist',
sparkle: '灵感 / Sparkle', tree: '层级 / Tree',
chat: '对话 / Chat', search: '搜索 / Search', settings: '设置 / Settings',
document: '文档 / Document', edit: '编辑 / Edit', think: '思考 / Think',
agent: '智能体 / Agent', browse: '浏览 / Browse', context: '上下文 / Context',
link: '链接 / Link', share: '分享 / Share', user: '个人 / Personal',
send: '发送 / Send', attachment: '附件 / Attachment', download: '下载 / Download',
play: '运行 / Run', design: '设计 / Design', moon: '夜间 / Moon',
monitor: '桌面 / Desktop', gauge: '性能 / Performance', queue: '队列 / Queue',
notes: '笔记 / Notes', inspect: '检查 / Inspect', help: '帮助 / Help',
info: '信息 / Information', alarm: '提醒 / Reminder', compare: '对比 / Compare',
done: '完成 / Done', pin: '重点 / Pin', microphone: '语音 / Voice',
// Materials & Lab family
'test-tube': '试管 / Test tube', flask: '烧瓶 / Flask', pipette: '移液枪 / Pipette',
dropper: '滴液 / Dropper', stirrer: '磁力搅拌 / Magnetic stirrer', hotplate: '加热台 / Hot plate',
centrifuge: '离心机 / Centrifuge', balance: '电子天平 / Balance',
atom: '原子 / Atom', molecule: '分子 / Molecule', lattice: '晶格 / Crystal lattice',
layered: '层状材料 / Layered material', framework: '多孔框架 / Porous framework',
'thin-film': '薄膜 / Thin film', fiber: '纤维 / Fiber', hydrogel: '水凝胶 / Hydrogel',
microscope: '显微镜 / Microscope', xrd: 'XRD 衍射峰 / XRD pattern', spectrum: '光谱 / Spectrum',
tensile: '拉伸测试 / Tensile test', electrode: '电极 / Electrode', 'iv-curve': '电学曲线 / I–V curve',
illumination: '光照 / Illumination', temperature: '温度 / Temperature', humidity: '湿度 / Humidity',
actuator: '弯曲驱动器 / Bending actuator', 'flex-sensor': '柔性传感器 / Flexible sensor',
battery: '电池 / Battery',
}
/** All presets satisfy the existing host's 1–4 Unicode-code-point custom-glyph rule. */
export const GROUP_EMOJI_ICONS = [
{ icon: '🚀', label: '启动 / Launch' },
{ icon: '📚', label: '学习 / Learning' },
{ icon: '🔬', label: '科研 / Research' },
{ icon: '🧪', label: '实验 / Experiment' },
{ icon: '🎨', label: '创作 / Art' },
{ icon: '🎯', label: '目标 / Target' },
{ icon: '💡', label: '想法 / Idea' },
{ icon: '🛠️', label: '工具 / Tools' },
{ icon: '🌱', label: '成长 / Growth' },
{ icon: '🏠', label: '生活 / Home' },
{ icon: '💼', label: '工作 / Work' },
{ icon: '🎮', label: '游戏 / Games' },
{ icon: '🎵', label: '音乐 / Music' },
{ icon: '❤️', label: '收藏 / Favorites' },
{ icon: '⭐', label: '星标 / Star' },
{ icon: '🔥', label: '热门 / Hot' },
] as const

View File

@ -0,0 +1,354 @@
/**
* Self-drawn monochrome artwork for the "Materials & Lab" icon family.
*
* The Host primitive package only ships product/generic glyphs, so the 28
* research icons are drawn here in the exact same visual language as the Host
* ones: a 16x16 viewBox, `currentColor` stroke, 1.3 stroke width (Host
* `ICON_MEDIUM_STROKE`), round caps/joins and no fill. Keeping the artwork as
* primitive data (instead of one opaque `<path>` per icon) lets the icon test
* assert every coordinate stays inside the viewBox and that each id has
* artwork — a hand-tuned path string could silently drift out of frame.
*/
import type { ReactElement } from 'react'
/** One drawable primitive of a 16x16 icon; coordinates are in viewBox units. */
export type SciencePrimitive =
| { readonly kind: 'line'; readonly x1: number; readonly y1: number; readonly x2: number; readonly y2: number }
| {
readonly kind: 'rect'
readonly x: number
readonly y: number
readonly width: number
readonly height: number
readonly radius?: number
}
| { readonly kind: 'circle'; readonly cx: number; readonly cy: number; readonly radius: number; readonly filled?: boolean }
| {
readonly kind: 'ellipse'
readonly cx: number
readonly cy: number
readonly rx: number
readonly ry: number
/** Rotation around the icon centre (8,8), in degrees. */
readonly rotate?: number
}
| { readonly kind: 'path'; readonly d: string }
/** Ids appended to the shared registry; order is the picker's section order. */
export const SCIENCE_ICON_IDS = [
// Lab operations
'test-tube', 'flask', 'pipette', 'dropper', 'stirrer', 'hotplate', 'centrifuge', 'balance',
// Material structures
'atom', 'molecule', 'lattice', 'layered', 'framework', 'thin-film', 'fiber', 'hydrogel',
// Characterization
'microscope', 'xrd', 'spectrum', 'tensile', 'electrode', 'iv-curve',
// Functional devices
'illumination', 'temperature', 'humidity', 'actuator', 'flex-sensor', 'battery',
] as const
/** Union of the research icon ids (a subset of the shared `GroupIconId`). */
export type ScienceIconId = (typeof SCIENCE_ICON_IDS)[number]
/** The picker's section split of the research family. */
export const SCIENCE_ICON_SECTIONS = [
{ key: 'lab', ids: ['test-tube', 'flask', 'pipette', 'dropper', 'stirrer', 'hotplate', 'centrifuge', 'balance'] },
{ key: 'materials', ids: ['atom', 'molecule', 'lattice', 'layered', 'framework', 'thin-film', 'fiber', 'hydrogel'] },
{ key: 'characterization', ids: ['microscope', 'xrd', 'spectrum', 'tensile', 'electrode', 'iv-curve'] },
{ key: 'devices', ids: ['illumination', 'temperature', 'humidity', 'actuator', 'flex-sensor', 'battery'] },
] as const satisfies readonly { readonly key: string; readonly ids: readonly ScienceIconId[] }[]
/** Primitive artwork per research icon. */
export const SCIENCE_ICON_ART: Record<ScienceIconId, readonly SciencePrimitive[]> = {
// ---- Lab operations ------------------------------------------------------
'test-tube': [
{ kind: 'path', d: 'M5.2 2.8v7.6a2.8 2.8 0 0 0 5.6 0V2.8' },
{ kind: 'line', x1: 4.5, y1: 2.8, x2: 11.5, y2: 2.8 },
{ kind: 'line', x1: 5.2, y1: 8.4, x2: 10.8, y2: 8.4 },
],
flask: [
{ kind: 'path', d: 'M6.2 2.4v3.4L3 11.6a1.6 1.6 0 0 0 1.4 2.4h7.2a1.6 1.6 0 0 0 1.4-2.4L9.8 5.8V2.4' },
{ kind: 'line', x1: 5.2, y1: 2.4, x2: 10.8, y2: 2.4 },
{ kind: 'line', x1: 5.2, y1: 9.8, x2: 10.8, y2: 9.8 },
],
pipette: [
{ kind: 'line', x1: 8, y1: 1.5, x2: 8, y2: 2.4 },
{ kind: 'rect', x: 6.1, y: 2.5, width: 3.8, height: 6.4, radius: 1.1 },
{ kind: 'line', x1: 6.1, y1: 4.6, x2: 7.2, y2: 4.6 },
{ kind: 'line', x1: 6.1, y1: 6.1, x2: 7.2, y2: 6.1 },
{ kind: 'path', d: 'M7.3 8.9L8 13.2L8.7 8.9' },
],
dropper: [
{ kind: 'rect', x: 5.1, y: 2.1, width: 5.8, height: 4.2, radius: 2.1 },
{ kind: 'line', x1: 6.6, y1: 6.3, x2: 6.6, y2: 10.3 },
{ kind: 'line', x1: 9.4, y1: 6.3, x2: 9.4, y2: 10.3 },
{ kind: 'path', d: 'M6.6 10.3L8 13.4L9.4 10.3' },
{ kind: 'circle', cx: 11.9, cy: 12.2, radius: 0.95, filled: true },
],
stirrer: [
{ kind: 'circle', cx: 8, cy: 6.1, radius: 2.5 },
{ kind: 'path', d: 'M6.4 6.1c1-.9 2.2-.9 3.2 0' },
{ kind: 'rect', x: 2, y: 9.6, width: 12, height: 4.2, radius: 1.2 },
{ kind: 'circle', cx: 11.4, cy: 11.7, radius: 0.85, filled: true },
],
hotplate: [
{ kind: 'path', d: 'M5.4 8.4c1.2-.9 1.2-2.1 0-3' },
{ kind: 'path', d: 'M8 8.4c1.2-.9 1.2-2.1 0-3' },
{ kind: 'path', d: 'M10.6 8.4c1.2-.9 1.2-2.1 0-3' },
{ kind: 'rect', x: 2, y: 9.6, width: 12, height: 4.2, radius: 1.2 },
{ kind: 'circle', cx: 11.4, cy: 11.7, radius: 0.85, filled: true },
],
centrifuge: [
{ kind: 'circle', cx: 8, cy: 5.6, radius: 3.4 },
{ kind: 'line', x1: 8, y1: 5.6, x2: 8, y2: 2.3 },
{ kind: 'line', x1: 8, y1: 5.6, x2: 5.1, y2: 7.3 },
{ kind: 'line', x1: 8, y1: 5.6, x2: 10.9, y2: 7.3 },
{ kind: 'circle', cx: 8, cy: 5.6, radius: 0.9, filled: true },
{ kind: 'line', x1: 8, y1: 9, x2: 8, y2: 9.8 },
{ kind: 'rect', x: 2.6, y: 9.8, width: 10.8, height: 3.4, radius: 1 },
],
balance: [
{ kind: 'path', d: 'M4.1 7.8h7.8' },
{ kind: 'path', d: 'M5 7.8a3 3 0 0 0 6 0' },
{ kind: 'line', x1: 8, y1: 9.3, x2: 8, y2: 10.4 },
{ kind: 'rect', x: 2.2, y: 10.4, width: 11.6, height: 3.2, radius: 1 },
{ kind: 'rect', x: 9.6, y: 11.2, width: 2.6, height: 1.5, radius: 0.3 },
],
// ---- Material structures -------------------------------------------------
atom: [
{ kind: 'ellipse', cx: 8, cy: 8, rx: 6.2, ry: 2.5 },
{ kind: 'ellipse', cx: 8, cy: 8, rx: 6.2, ry: 2.5, rotate: 60 },
{ kind: 'ellipse', cx: 8, cy: 8, rx: 6.2, ry: 2.5, rotate: -60 },
{ kind: 'circle', cx: 8, cy: 8, radius: 1.05, filled: true },
],
molecule: [
{ kind: 'line', x1: 5, y1: 4.2, x2: 11, y2: 4.2 },
{ kind: 'line', x1: 4.5, y1: 5.4, x2: 6.9, y2: 9.7 },
{ kind: 'line', x1: 11.5, y1: 5.4, x2: 9.1, y2: 9.7 },
{ kind: 'circle', cx: 3.6, cy: 4.2, radius: 1.35 },
{ kind: 'circle', cx: 12.4, cy: 4.2, radius: 1.35 },
{ kind: 'circle', cx: 8, cy: 11.6, radius: 1.35 },
],
lattice: [
{ kind: 'line', x1: 3.6, y1: 3.6, x2: 3.6, y2: 12.4 },
{ kind: 'line', x1: 8, y1: 3.6, x2: 8, y2: 12.4 },
{ kind: 'line', x1: 12.4, y1: 3.6, x2: 12.4, y2: 12.4 },
{ kind: 'line', x1: 3.6, y1: 3.6, x2: 12.4, y2: 3.6 },
{ kind: 'line', x1: 3.6, y1: 8, x2: 12.4, y2: 8 },
{ kind: 'line', x1: 3.6, y1: 12.4, x2: 12.4, y2: 12.4 },
{ kind: 'circle', cx: 3.6, cy: 3.6, radius: 0.85, filled: true },
{ kind: 'circle', cx: 8, cy: 3.6, radius: 0.85, filled: true },
{ kind: 'circle', cx: 12.4, cy: 3.6, radius: 0.85, filled: true },
{ kind: 'circle', cx: 3.6, cy: 8, radius: 0.85, filled: true },
{ kind: 'circle', cx: 8, cy: 8, radius: 0.85, filled: true },
{ kind: 'circle', cx: 12.4, cy: 8, radius: 0.85, filled: true },
{ kind: 'circle', cx: 3.6, cy: 12.4, radius: 0.85, filled: true },
{ kind: 'circle', cx: 8, cy: 12.4, radius: 0.85, filled: true },
{ kind: 'circle', cx: 12.4, cy: 12.4, radius: 0.85, filled: true },
],
layered: [
{ kind: 'rect', x: 2.6, y: 3, width: 10.8, height: 2.3, radius: 0.6 },
{ kind: 'rect', x: 3.6, y: 6.85, width: 10.8, height: 2.3, radius: 0.6 },
{ kind: 'rect', x: 2.6, y: 10.7, width: 10.8, height: 2.3, radius: 0.6 },
],
framework: [
{ kind: 'rect', x: 2.6, y: 2.8, width: 10.8, height: 10.4, radius: 0.8 },
{ kind: 'line', x1: 8, y1: 2.8, x2: 8, y2: 13.2 },
{ kind: 'line', x1: 2.6, y1: 8, x2: 13.4, y2: 8 },
{ kind: 'circle', cx: 5.3, cy: 5.3, radius: 0.8, filled: true },
{ kind: 'circle', cx: 10.7, cy: 5.3, radius: 0.8, filled: true },
{ kind: 'circle', cx: 5.3, cy: 10.7, radius: 0.8, filled: true },
{ kind: 'circle', cx: 10.7, cy: 10.7, radius: 0.8, filled: true },
],
'thin-film': [
{ kind: 'path', d: 'M2.6 7.6q1.35-1.6 2.7 0t2.7 0t2.7 0t2.7 0' },
{ kind: 'line', x1: 2.6, y1: 9.4, x2: 13.4, y2: 9.4 },
{ kind: 'rect', x: 2.6, y: 10.6, width: 10.8, height: 2.6, radius: 0.6 },
],
fiber: [
{ kind: 'path', d: 'M5 2.4c1 1.6-1 2.4 0 4s-1 2.4 0 4 0 1.6 0 3.2' },
{ kind: 'path', d: 'M8 2.4c1 1.6-1 2.4 0 4s-1 2.4 0 4 0 1.6 0 3.2' },
{ kind: 'path', d: 'M11 2.4c1 1.6-1 2.4 0 4s-1 2.4 0 4 0 1.6 0 3.2' },
{ kind: 'rect', x: 2.9, y: 7.2, width: 10.2, height: 1.8, radius: 0.9 },
],
hydrogel: [
{ kind: 'rect', x: 2.4, y: 4.4, width: 11.2, height: 8.4, radius: 4.2 },
{ kind: 'path', d: 'M5.4 7.3L8 9.4L10.6 6.9L5.4 7.3' },
{ kind: 'circle', cx: 5.4, cy: 7.3, radius: 0.8, filled: true },
{ kind: 'circle', cx: 8, cy: 9.4, radius: 0.8, filled: true },
{ kind: 'circle', cx: 10.6, cy: 6.9, radius: 0.8, filled: true },
],
// ---- Characterization ----------------------------------------------------
microscope: [
{ kind: 'line', x1: 5.9, y1: 2.1, x2: 8.9, y2: 5.1 },
{ kind: 'circle', cx: 5.4, cy: 1.9, radius: 0.9 },
{ kind: 'circle', cx: 9.5, cy: 7.4, radius: 1.1 },
{ kind: 'path', d: 'M11 6.6c1.5 1.5 1.5 3.8 0 5.3' },
{ kind: 'line', x1: 4.2, y1: 10.4, x2: 11.6, y2: 10.4 },
{ kind: 'line', x1: 9.9, y1: 10.4, x2: 9.9, y2: 13.2 },
{ kind: 'line', x1: 3, y1: 13.2, x2: 12.6, y2: 13.2 },
],
xrd: [
{ kind: 'path', d: 'M2.6 13.2V2.9h11' },
{
kind: 'path',
d: 'M3.4 12.4h1.9l.6-4.6.6 4.6h1.9l.7-2.6.6 2.6h1.9l.9-6.1.7 6.1h1.3',
},
],
spectrum: [
{ kind: 'path', d: 'M6.6 4.4L9.8 10.6H3.4z' },
{ kind: 'line', x1: 1.2, y1: 8.4, x2: 4.4, y2: 8.4 },
{ kind: 'line', x1: 9.2, y1: 9.2, x2: 13.4, y2: 4.8 },
{ kind: 'line', x1: 9.6, y1: 10, x2: 13.7, y2: 6.4 },
{ kind: 'line', x1: 9.8, y1: 10.6, x2: 13.8, y2: 8.6 },
],
tensile: [
{ kind: 'rect', x: 5.8, y: 7.2, width: 4.4, height: 1.6, radius: 0.4 },
{ kind: 'line', x1: 4.4, y1: 5.8, x2: 4.4, y2: 10.2 },
{ kind: 'line', x1: 11.6, y1: 5.8, x2: 11.6, y2: 10.2 },
{ kind: 'path', d: 'M2.4 8h1.7' },
{ kind: 'path', d: 'M3.3 7.2l.8.8-.8.8' },
{ kind: 'path', d: 'M13.6 8h-1.7' },
{ kind: 'path', d: 'M12.7 7.2l-.8.8.8.8' },
{ kind: 'line', x1: 8, y1: 4.9, x2: 8, y2: 3.2 },
{ kind: 'path', d: 'M7.2 4l.8-.8.8.8' },
{ kind: 'line', x1: 8, y1: 11.1, x2: 8, y2: 12.8 },
{ kind: 'path', d: 'M7.2 12l.8.8.8-.8' },
],
electrode: [
{ kind: 'path', d: 'M3.2 8.6v4.4a1.2 1.2 0 0 0 1.2 1.2h7.2a1.2 1.2 0 0 0 1.2-1.2V8.6' },
{ kind: 'line', x1: 3.2, y1: 10.6, x2: 12.8, y2: 10.6 },
{ kind: 'line', x1: 6, y1: 2.4, x2: 6, y2: 10.6 },
{ kind: 'line', x1: 10, y1: 2.4, x2: 10, y2: 10.6 },
{ kind: 'line', x1: 5.2, y1: 2.4, x2: 6.8, y2: 2.4 },
{ kind: 'line', x1: 9.2, y1: 2.4, x2: 10.8, y2: 2.4 },
],
'iv-curve': [
{ kind: 'path', d: 'M2.8 13.2V3.2h10.4' },
{ kind: 'path', d: 'M3.6 12.4c2.6 0 2.7-4.6 5-5.6s3.4-2.6 4.3-3.4' },
{ kind: 'circle', cx: 8.6, cy: 6.8, radius: 0.8, filled: true },
],
// ---- Functional devices --------------------------------------------------
illumination: [
{ kind: 'rect', x: 4.6, y: 1.8, width: 6.8, height: 2.6, radius: 0.7 },
{ kind: 'line', x1: 6.2, y1: 4.9, x2: 4.6, y2: 8.4 },
{ kind: 'line', x1: 8, y1: 4.9, x2: 8, y2: 9 },
{ kind: 'line', x1: 9.8, y1: 4.9, x2: 11.4, y2: 8.4 },
{ kind: 'line', x1: 2.6, y1: 12.6, x2: 13.4, y2: 12.6 },
],
temperature: [
{ kind: 'rect', x: 6.9, y: 2.4, width: 2.2, height: 8.2, radius: 1.1 },
{ kind: 'circle', cx: 8, cy: 12.2, radius: 1.9 },
{ kind: 'line', x1: 8, y1: 6.4, x2: 8, y2: 11.4 },
{ kind: 'line', x1: 9.1, y1: 4.8, x2: 10, y2: 4.8 },
{ kind: 'line', x1: 9.1, y1: 7, x2: 10, y2: 7 },
{ kind: 'line', x1: 9.1, y1: 9.2, x2: 10, y2: 9.2 },
],
humidity: [
{ kind: 'path', d: 'M8 2.1c0 0-4.2 5-4.2 7.9a4.2 4.2 0 0 0 8.4 0C12.2 7.1 8 2.1 8 2.1z' },
{ kind: 'path', d: 'M6 10.2c1.3-1 2.7-1 4 0' },
],
actuator: [
{ kind: 'path', d: 'M2.6 12.6c6 .4 9.2-1.8 10.2-6.4' },
{ kind: 'path', d: 'M2.6 10.6c5.2.3 7.8-1.6 8.6-5.2' },
{ kind: 'line', x1: 2.6, y1: 9.6, x2: 2.6, y2: 14 },
],
'flex-sensor': [
{ kind: 'path', d: 'M2.8 4.2v8.2h3.4V4.2h3.4v8.2h3.4V4.2' },
{ kind: 'circle', cx: 2.8, cy: 3.2, radius: 0.8, filled: true },
{ kind: 'circle', cx: 13, cy: 3.2, radius: 0.8, filled: true },
{ kind: 'circle', cx: 8, cy: 8.2, radius: 1.1 },
],
battery: [
{ kind: 'rect', x: 1.8, y: 5.4, width: 11, height: 5.4, radius: 1 },
{ kind: 'rect', x: 12.8, y: 7.1, width: 1.6, height: 2, radius: 0.4 },
{ kind: 'path', d: 'M8.8 6.3L6.8 8.8h2.2l-1.4 2.5' },
],
}
/** Research icon id → picker section key. */
export const SCIENCE_ICON_SECTION_OF: Record<ScienceIconId, (typeof SCIENCE_ICON_SECTIONS)[number]['key']> = {
'test-tube': 'lab', flask: 'lab', pipette: 'lab', dropper: 'lab',
stirrer: 'lab', hotplate: 'lab', centrifuge: 'lab', balance: 'lab',
atom: 'materials', molecule: 'materials', lattice: 'materials', layered: 'materials',
framework: 'materials', 'thin-film': 'materials', fiber: 'materials', hydrogel: 'materials',
microscope: 'characterization', xrd: 'characterization', spectrum: 'characterization',
tensile: 'characterization', electrode: 'characterization', 'iv-curve': 'characterization',
illumination: 'devices', temperature: 'devices', humidity: 'devices',
actuator: 'devices', 'flex-sensor': 'devices', battery: 'devices',
}
function Primitive({ primitive }: { primitive: SciencePrimitive }): ReactElement {
switch (primitive.kind) {
case 'line':
return <line x1={primitive.x1} y1={primitive.y1} x2={primitive.x2} y2={primitive.y2} />
case 'rect':
return (
<rect
x={primitive.x}
y={primitive.y}
width={primitive.width}
height={primitive.height}
rx={primitive.radius ?? 0}
/>
)
case 'circle':
return (
<circle
cx={primitive.cx}
cy={primitive.cy}
r={primitive.radius}
fill={primitive.filled === true ? 'currentColor' : 'none'}
/>
)
case 'ellipse':
return (
<ellipse
cx={primitive.cx}
cy={primitive.cy}
rx={primitive.rx}
ry={primitive.ry}
{...(primitive.rotate === undefined ? {} : { transform: `rotate(${primitive.rotate} 8 8)` })}
/>
)
case 'path':
return <path d={primitive.d} />
}
}
/**
* Render one research icon in the Host glyph's visual language: 16x16,
* `currentColor` stroke, 1.3px, round joins, decorative for screen readers (the
* row/picker button already carries the bilingual name).
* @param props.icon - research icon id.
* @param props.size - rendered square size in CSS pixels (default 16, like Host glyphs).
*/
export function ScienceGlyph({ icon, size = 16 }: { icon: ScienceIconId; size?: number }): ReactElement {
return (
<svg
width={size}
height={size}
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
stroke="currentColor"
strokeWidth={1.3}
strokeLinecap="round"
strokeLinejoin="round"
>
{SCIENCE_ICON_ART[icon].map((primitive, index) => (
<Primitive key={index} primitive={primitive} />
))}
</svg>
)
}
/** Research icon id → rendered node, merged into the row icon registry. */
export function scienceIconNodes(): Record<ScienceIconId, ReactElement> {
const nodes: Partial<Record<ScienceIconId, ReactElement>> = {}
for (const id of SCIENCE_ICON_IDS) nodes[id] = <ScienceGlyph icon={id} />
return nodes as Record<ScienceIconId, ReactElement>
}

View File

@ -81,6 +81,12 @@ export type WorkspaceGroupsKey =
| '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'
@ -92,6 +98,7 @@ export type WorkspaceGroupsKey =
| 'color.pink'
| 'color.gray'
| 'section.topLevel'
| 'section.defaultWorkspace'
| 'manual.saveError'
| 'session.new'
| 'session.rename'
@ -217,6 +224,12 @@ export const zh: WorkspaceGroupsDict = {
'group.iconDefault': '默认图标',
'group.iconCustom': '自定义字符',
'group.iconInvalid': '图标需为预设图标或 1–4 个字符',
'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': '琥珀',
@ -228,6 +241,7 @@ export const zh: WorkspaceGroupsDict = {
'color.pink': '粉色',
'color.gray': '灰色',
'section.topLevel': '顶层项目',
'section.defaultWorkspace': '默认工作区',
'manual.saveError': '分组变更保存失败',
'session.new': '新建会话',
'session.rename': '重命名会话',
@ -352,6 +366,12 @@ export const en: WorkspaceGroupsDict = {
'group.iconDefault': 'Default icon',
'group.iconCustom': 'Custom character',
'group.iconInvalid': 'Use a preset icon or 1–4 characters',
'group.icon.section.common': 'Common icons',
'group.icon.section.lab': 'Lab operations',
'group.icon.section.materials': 'Material structures',
'group.icon.section.characterization': 'Characterization',
'group.icon.section.devices': 'Functional devices',
'group.icon.section.emoji': 'Emoji',
'color.red': 'Red',
'color.orange': 'Orange',
'color.amber': 'Amber',
@ -363,6 +383,7 @@ export const en: WorkspaceGroupsDict = {
'color.pink': 'Pink',
'color.gray': 'Gray',
'section.topLevel': 'Top-level projects',
'section.defaultWorkspace': 'Default workspace',
'manual.saveError': 'Could not save group changes',
'session.new': 'New Session',
'session.rename': 'Rename session',

View File

@ -10,6 +10,36 @@
*/
import { useEffect, useRef, useState, type AnimationEvent, type DragEvent, type ReactNode } from 'react'
import {
IconNewChatOutlineMedium,
IconSearchOutlineMedium,
IconSettingsOutlineMedium,
IconDeliverDocMedium,
IconEditOutlineMedium,
IconThinkOutlineMedium,
IconAgentPresetOutlineMedium,
IconBrowseOutlineMedium,
IconContextInjectionOutlineMedium,
IconLinkOutlineMedium,
IconShareOutlineMedium,
IconUserOutlineMedium,
IconPaperPlaneOutlineMedium,
IconPaperclipOutlineMedium,
IconDownloadOutlineMedium,
IconPlayOutlineMedium,
IconPersonalizationOutlineMedium,
IconDarkOutlineMedium,
IconFollowsystemOutlineMedium,
IconGaugeOutlineMedium,
IconQueueOutlineMedium,
IconListPenOutlineMedium,
IconInspectOutlineMedium,
IconQuestionOutlineMedium,
IconInfoOutlineMedium,
IconAlarmClockOutlineMedium,
IconCompareSplitOutlineMedium,
IconCheckCircleOutlineMedium,
IconPinOutlineMedium,
IconMicrophoneOutlineMedium,
IconApiOutlineMedium,
IconArchiveOutlineRegular,
IconArchiveOutlineMedium,
@ -51,6 +81,9 @@ import {
} from '@deepseek-ai/dsh-client-ui-primitives'
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
import type { WorkspaceGroupsKey } from './locales.ts'
import { SessionFlower } from './FlowerBranch.tsx'
import { scienceIconNodes, type ScienceIconId } from './group-icons-science.tsx'
import type { GroupIconId } from '../core/types.ts'
import type { CategoryNode, FolderNode, SessionNode, WorkspaceGroupNode } from './tree.ts'
type T = TranslateNS<'workspaceGroups'>
@ -118,7 +151,7 @@ export interface RowDropProps {
* folder glyph used by unprefixed groups. Keyed by plain string so an id from
* a newer host (or a hand-edited JSON file) degrades instead of throwing.
*/
const CATEGORY_ICONS: Record<string, ReactNode> = {
const HOST_CATEGORY_ICONS = {
folder: <IconFolderCloseMedium />,
workspace: <IconWorkspaceTreeOutlineMedium />,
code: <IconCodeOutlineMedium />,
@ -139,6 +172,46 @@ const CATEGORY_ICONS: Record<string, ReactNode> = {
checklist: <IconChecklistOutlineMedium />,
sparkle: <IconSparkleMedium />,
tree: <IconTreeCornerMedium />,
chat: <IconNewChatOutlineMedium />,
search: <IconSearchOutlineMedium />,
settings: <IconSettingsOutlineMedium />,
document: <IconDeliverDocMedium />,
edit: <IconEditOutlineMedium />,
think: <IconThinkOutlineMedium />,
agent: <IconAgentPresetOutlineMedium />,
browse: <IconBrowseOutlineMedium />,
context: <IconContextInjectionOutlineMedium />,
link: <IconLinkOutlineMedium />,
share: <IconShareOutlineMedium />,
user: <IconUserOutlineMedium />,
send: <IconPaperPlaneOutlineMedium />,
attachment: <IconPaperclipOutlineMedium />,
download: <IconDownloadOutlineMedium />,
play: <IconPlayOutlineMedium />,
design: <IconPersonalizationOutlineMedium />,
moon: <IconDarkOutlineMedium />,
monitor: <IconFollowsystemOutlineMedium />,
gauge: <IconGaugeOutlineMedium />,
queue: <IconQueueOutlineMedium />,
notes: <IconListPenOutlineMedium />,
inspect: <IconInspectOutlineMedium />,
help: <IconQuestionOutlineMedium />,
info: <IconInfoOutlineMedium />,
alarm: <IconAlarmClockOutlineMedium />,
compare: <IconCompareSplitOutlineMedium />,
done: <IconCheckCircleOutlineMedium />,
pin: <IconPinOutlineMedium />,
microphone: <IconMicrophoneOutlineMedium />,
} satisfies Record<Exclude<GroupIconId, ScienceIconId>, ReactNode>
/**
* Registered icon id → rendered artwork. The research family is merged in from
* its own module: those glyphs are drawn locally (the Host primitive package
* ships no lab/material icons) but must render through the very same path.
*/
const CATEGORY_ICONS: Record<string, ReactNode> = {
...HOST_CATEGORY_ICONS,
...scienceIconNodes(),
}
/**
@ -148,7 +221,7 @@ const CATEGORY_ICONS: Record<string, ReactNode> = {
*/
function resolveCategoryIcon(icon: string | undefined): ReactNode | null {
if (icon === undefined || icon === '') return null
const preset = CATEGORY_ICONS[icon]
const preset = Object.prototype.hasOwnProperty.call(CATEGORY_ICONS, icon) ? CATEGORY_ICONS[icon] : undefined
if (preset !== undefined) return preset
return Array.from(icon).length <= 4 ? <span className="wgCategoryGlyph">{icon}</span> : null
}
@ -234,51 +307,55 @@ export function CategoryRow({ node, t, onToggle, onAddWorkspace, addingWorkspace
/>
</span>
<span className="wgCategoryLabel">{node.label}</span>
<span className="wgCategoryCount">{count}</span>
{pinned && (
<span className="wgCategoryPin" aria-hidden>
<IconPinFillMedium />
</span>
)}
{onAddWorkspace !== undefined && (
{/* One trailing slot for both states: the count and the hover buttons are
stacked in the same grid cell pinned to the row's right edge, so the
count is right-aligned exactly where the buttons appear and the swap
never moves a box (see .wgRowTrail in styles.css). */}
<span className="wgRowTrail">
<span className="wgCategoryCount">{count}</span>
<span className="wgRowActions">
<button type="button" className="wgIconButton" draggable={false}
disabled={addingWorkspace}
title={t('workspace.add')} aria-label={`${t('workspace.add')} · ${node.label}`}
onClick={event => { event.stopPropagation(); onAddWorkspace() }}>
<IconPlusOutlineRegular />
</button>
{onAddWorkspace !== undefined && (
<button type="button" className="wgIconButton" draggable={false}
disabled={addingWorkspace}
title={t('workspace.add')} aria-label={`${t('workspace.add')} · ${node.label}`}
onClick={event => { event.stopPropagation(); onAddWorkspace() }}>
<IconPlusOutlineRegular />
</button>
)}
{manageable && (
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={menuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'pin') onTogglePin?.()
if (id === 'appearance') onEditAppearance?.()
if (id === 'rename') onRename()
if (id === 'delete') onDelete()
}}
portal
closeOnPointerLeave
anchor={(
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('group.rename')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
>
<IconEllipsisOutlineRegular />
</button>
)}
/>
)}
</span>
)}
{manageable && (
<span className="wgRowActions">
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={menuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'pin') onTogglePin?.()
if (id === 'appearance') onEditAppearance?.()
if (id === 'rename') onRename()
if (id === 'delete') onDelete()
}}
portal
closeOnPointerLeave
anchor={(
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('group.rename')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
>
<IconEllipsisOutlineRegular />
</button>
)}
/>
</span>
)}
</span>
</div>
)
}
@ -357,42 +434,50 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
<IconProjectAddOutlineRegular />
</span>
<span className="wgProjectLabel" title={node.path}>{node.label}</span>
<span className="wgRowActions">
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={menuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'openInFolder') onOpenInFolder?.()
if (id === 'moveOut') onMoveOut?.()
if (id === 'folders') onManageFolders?.()
if (id === 'rename') onRename()
if (id === 'delete') onDelete()
}}
portal
closeOnPointerLeave
anchor={(
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('workspace.rename')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
>
<IconEllipsisOutlineRegular />
</button>
)}
/>
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('session.new')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); onNewSession() }}
>
<IconPlusOutlineRegular />
</button>
{/* Same trailing-slot contract as groups and folders: the count and the
hover buttons share one right-aligned grid cell, so the count sits where
the buttons appear and the swap never moves either box. */}
<span className="wgRowTrail">
<span className="wgProjectCount">{node.sessionCount}</span>
{/* Action order is uniform across every row kind: new-session + first,
menu ⋯ second (see CategoryRow). */}
<span className="wgRowActions">
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('session.new')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); onNewSession() }}
>
<IconPlusOutlineRegular />
</button>
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={menuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'openInFolder') onOpenInFolder?.()
if (id === 'moveOut') onMoveOut?.()
if (id === 'folders') onManageFolders?.()
if (id === 'rename') onRename()
if (id === 'delete') onDelete()
}}
portal
closeOnPointerLeave
anchor={(
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('workspace.rename')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
>
<IconEllipsisOutlineRegular />
</button>
)}
/>
</span>
</span>
</div>
)
@ -460,43 +545,49 @@ export function FolderRow({ node, t, onToggle, onNewSession, onSetRoot, onRemove
{node.isRoot && (
<span className="wgFolderRoot" title={t('folder.rootBadge')} aria-label={t('folder.rootBadge')}>★</span>
)}
<span className="wgFolderCount">{node.sessions.length}</span>
<span className="wgRowActions">
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={menuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'newSession') onNewSession()
if (id === 'openInFolder') onOpenInFolder?.()
if (id === 'setRoot') onSetRoot()
if (id === 'remove') onRemove()
}}
portal
closeOnPointerLeave
anchor={(
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('folder.title')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
>
<IconEllipsisOutlineRegular />
</button>
)}
/>
<button
type="button"
className="wgIconButton"
draggable={false}
disabled={creating}
aria-label={`${t('session.new')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); onNewSession() }}
>
<IconPlusOutlineRegular />
</button>
{/* Count and hover buttons share the same right-aligned cell (as on every
other row): the count is flush with the row's right edge and yields to
the buttons without any reflow. */}
<span className="wgRowTrail">
<span className="wgFolderCount">{node.sessions.length}</span>
{/* Same + then ⋯ order as groups and workspaces. */}
<span className="wgRowActions">
<button
type="button"
className="wgIconButton"
draggable={false}
disabled={creating}
aria-label={`${t('session.new')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); onNewSession() }}
>
<IconPlusOutlineRegular />
</button>
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={menuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'newSession') onNewSession()
if (id === 'openInFolder') onOpenInFolder?.()
if (id === 'setRoot') onSetRoot()
if (id === 'remove') onRemove()
}}
portal
closeOnPointerLeave
anchor={(
<button
type="button"
className="wgIconButton"
draggable={false}
aria-label={`${t('folder.title')} ${node.label}`}
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
>
<IconEllipsisOutlineRegular />
</button>
)}
/>
</span>
</span>
</div>
)
@ -613,13 +704,8 @@ export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork,
}) {
const selected = node.id === currentId
const [menuOpen, setMenuOpen] = useState(false)
// The ACTIVE session hands its status slot to the flower: the branch anchors
// on this cell (`anchorX` targets `.wgStatusSlot`), so the bloom and the dot
// occupy the same 14px square. Drawing both puts the dot's green "ongoing"
// ring (or the loading spinner) on top of the petals, which is what made the
// flower look broken. The flower already carries this row's state — it turns
// exactly while the session runs — so the dot is redundant here anyway.
const showStatus = !selected
// Keep the active flower inside its own status slot, never in a measured
// overlay: scrolling and expanding ancestors must move it with this row.
const menuItems = [
{ id: 'rename', label: t('session.rename'), icon: <IconEditOutlineRegular /> },
{ id: 'fork', label: t('session.fork'), icon: <IconBranchOutlineRegular /> },
@ -635,38 +721,45 @@ export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork,
onClick={() => { onOpen(node.id) }}
>
<span className="wgStatusSlot">
{showStatus && <StateDot state={sessionDotState(node)} />}
{selected
? <SessionFlower spinning={node.running || node.runningSubagentCount > 0} />
: <StateDot state={sessionDotState(node)} />}
</span>
<span className="wgSessionTitle">{node.title}</span>
{!node.blank && <span className="wgSessionTime">{relativeTimeLabel(node.updatedAt, now)}</span>}
{node.snippet !== undefined && (
<span className="wgSessionSnippet" title={node.snippet}>{node.snippet}</span>
)}
{/* Same trailing slot as groups, workspaces and folders: the time is
right-aligned on the row's right edge and yields to the ⋯ button on
hover/focus without moving either box (see .wgRowTrail in styles.css). */}
{!node.blank && (
<span className="wgRowActions">
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={menuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'rename') onRename(node.id, node.title)
if (id === 'fork') onFork(node.id)
if (id === 'archive') onArchive(node.id)
}}
portal
closeOnPointerLeave
anchor={(
<button
type="button"
className="wgIconButton"
aria-label={`${t('session.rename')} ${node.title}`}
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
>
<IconEllipsisOutlineRegular />
</button>
)}
/>
<span className="wgRowTrail">
<span className="wgSessionTime">{relativeTimeLabel(node.updatedAt, now)}</span>
<span className="wgRowActions">
<Menu
open={menuOpen}
onClose={() => { setMenuOpen(false) }}
items={menuItems}
onSelect={(id) => {
setMenuOpen(false)
if (id === 'rename') onRename(node.id, node.title)
if (id === 'fork') onFork(node.id)
if (id === 'archive') onArchive(node.id)
}}
portal
closeOnPointerLeave
anchor={(
<button
type="button"
className="wgIconButton"
aria-label={`${t('session.rename')} ${node.title}`}
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
>
<IconEllipsisOutlineRegular />
</button>
)}
/>
</span>
</span>
)}
</div>

View File

@ -3,6 +3,7 @@
flex-direction:column;
flex:1;
width:100%;
min-width:0;
min-height:0;
display:flex;
overflow:hidden;
@ -80,11 +81,48 @@
.wgTreeBody {
flex:1;
min-width:0;
min-height:0;
padding:0 8px 8px;
overflow-x:hidden;
overflow-y:auto;
}
/* Pinned default workspace: a sibling of the tree's scroll area, never inside
it — a long session list scrolls above this bar and can neither push it away
nor scroll it out. The divider separates the two zones. */
.wgDefaultWorkspaceBar {
flex:none;
min-width:0;
padding:6px 8px 8px;
border-top:1px solid var(--dsw-alias-border-l2,#7f7f7f47);
}
.wgDefaultWorkspaceBar .wgProjectRow {
margin-bottom:2px;
}
/* Every nesting container must be allowed to shrink below its min-content
width. Otherwise a long title expands the grid track and pushes the action
column beyond the visible scrollport, even though the title has ellipsis. */
.wgTreeWrap,.wgList,.wgRows,.wgRowsInner,.wgTreeChildren {
min-width:0;
max-width:100%;
}
.wgCategoryRow,.wgProjectRow,.wgFolderRow,.wgSessionRow {
box-sizing:border-box;
width:100%;
min-width:0;
max-width:100%;
}
/* Indentation belongs only on the left; all trailing action buttons share
the same right inset, independent of title length and nesting depth. */
.wgRowActions:last-child {
margin-left:auto;
}
.wgList {
flex-direction:column;
gap:1px;
@ -203,7 +241,8 @@
overflow:hidden;
}
.wgCategoryCount {
.wgCategoryCount,
.wgProjectCount {
color:var(--dsw-fg-3,#7f7f7fcc);
flex:none;
font-size:11px;
@ -295,6 +334,22 @@
display:inline-flex;
}
/* One trailing slot per row: the member count and the hover buttons are stacked
in the same grid cell, pinned to the row's right edge. The count therefore
sits exactly where the buttons appear (both right-aligned), the cell is always
as wide as the widest of the two, and the swap cannot move either box. */
.wgRowTrail {
display:grid;
flex:none;
margin-left:auto;
align-items:center;
justify-items:end;
}
.wgRowTrail > * {
grid-area:1 / 1;
}
.wgProjectRow:hover .wgRowActions,.wgProjectRow:focus-within .wgRowActions {
opacity:1;
}
@ -353,6 +408,29 @@
font-size:11px;
}
/* Trailing member count / session time and trailing actions are mutually
exclusive: at rest a row states its count (groups, workspaces, folders) or the
session's relative time, and as soon as it is hovered or reached by keyboard
focus the "+" / "⋯" buttons take that trailing slot. Both live in the same
.wgRowTrail cell and keep their boxes (opacity + visibility), so the count and
the time are right-aligned on the row's right edge exactly where the buttons
appear, and the swap never changes the row height nor reflows the label. */
.wgCategoryCount,.wgFolderCount,.wgProjectCount,.wgSessionTime {
transition:opacity .12s ease;
}
.wgCategoryRow:hover .wgCategoryCount,
.wgCategoryRow:focus-within .wgCategoryCount,
.wgFolderRow:hover .wgFolderCount,
.wgFolderRow:focus-within .wgFolderCount,
.wgProjectRow:hover .wgProjectCount,
.wgProjectRow:focus-within .wgProjectCount,
.wgSessionRow:hover .wgSessionTime,
.wgSessionRow:focus-within .wgSessionTime {
opacity:0;
visibility:hidden;
}
/* Sessions hanging off a folder row: one indent step deeper than a plain
session title (74 → 90). */
.wgSessionNested {
@ -410,6 +488,7 @@
hover halos and focus rings are never cut off. */
.wgRows {
display:grid;
grid-template-columns:minmax(0,1fr);
grid-template-rows:1fr;
}
@ -678,7 +757,35 @@
border-color:var(--dsw-alias-label-primary,currentColor);
}
/* Appearance dialog: colour swatches, icon picker grid, pin toggle. */
/* Appearance dialog: colour swatches, categorised icon picker, pin toggle. */
.wgAppearanceBody {
display:flex;
flex-direction:column;
gap:16px;
}
/* Cap against the modal's padded viewport box (the host Modal documents
`max-height:100%` for consumers) and scroll the card body instead of letting
the card grow: the title row stays pinned while it scrolls, and the footer —
the only "done" button — lives outside the scroller, so a taller icon picker
can never push it out of the dialog. */
.wgAppearanceDialog {
max-height:100%;
}
.wgAppearanceContent {
overflow-x:hidden;
overflow-y:auto;
min-height:0;
}
.wgAppearanceContent > :first-child {
position:sticky;
top:0;
z-index:1;
background:var(--dsw-alias-bg-layer-2,transparent);
}
.wgAppearanceSection {
display:flex;
flex-direction:column;
@ -724,12 +831,62 @@
background:var(--dsw-bg-hover,#7f7f7f1f);
}
/* One height-capped scroller for every icon section (common presets, the four
research families, emoji), so the picker grows sideways, not downwards. The
4px padding keeps edge cells' focus rings inside the clip. */
.wgIconSections {
display:flex;
flex-direction:column;
gap:10px;
max-height:216px;
overflow-y:auto;
padding:4px;
scrollbar-gutter:stable;
}
.wgIconSection {
display:flex;
flex-direction:column;
gap:4px;
}
.wgIconSectionLabel {
color:var(--dsw-fg-3,#7f7f7fcc);
font-size:11px;
font-weight:600;
line-height:14px;
}
.wgIconGrid {
gap:4px;
grid-template-columns:repeat(10,1fr);
grid-template-columns:repeat(auto-fill,minmax(28px,1fr));
padding:1px;
display:grid;
}
.wgEmojiGrid .wgIconCell {
font-size:18px;
}
/* Restore-default + custom glyph: a row under the picker, kept clear of the
picker's scroller (its focus ring never overlaps a cell). */
.wgIconCustom {
display:flex;
align-items:center;
gap:8px;
margin-top:2px;
}
.wgIconCustom .wgRenameInput {
flex:1;
min-width:0;
}
.wgIconCell.wgIconDefault {
width:auto;
padding:0 8px;
}
.wgIconCell {
cursor:pointer;
color:var(--dsw-fg-2,inherit);
@ -737,8 +894,8 @@
border-radius:5px;
justify-content:center;
align-items:center;
width:24px;
height:24px;
width:28px;
height:28px;
padding:0;
display:inline-flex;
background:transparent;
@ -750,6 +907,12 @@
.wgIconCell[aria-pressed=true] {
background:var(--dsw-bg-selected,#4a90d92e);
box-shadow:inset 0 0 0 1px var(--dsw-accent,#4a90d9);
}
.wgIconCell:focus-visible {
outline:2px solid var(--dsw-accent,#4a90d9);
outline-offset:1px;
}
.wgIconCell:disabled {

View File

@ -16,6 +16,7 @@ import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-
import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { indexSubagentDescendants, type SubagentDescendantSummary } from './subagent-lineage.ts'
import { isDefaultWorkspace } from '../core/default-workspace.ts'
import { categoryAppearance, effectiveCategories, orderedWorkspaceIds, resolveCategory } from '../core/matcher.ts'
import {
EMPTY_FOLDERS_DOCUMENT,
@ -341,6 +342,8 @@ export function deriveGroups(
byCategory.set(key, [])
}
for (const workspace of workspaces) {
// The Host default workspace is pinned to its own bottom bar, never grouped.
if (isDefaultWorkspace(workspace)) 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, [])
@ -429,6 +432,7 @@ export function deriveTopLevel(
: workspaces.find(w => w.sessionIds.includes(current))?.workspaceId
const topLevelIds = workspaces
.filter(w => !isDefaultWorkspace(w))
.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)
@ -462,6 +466,61 @@ export function deriveTopLevel(
return nodes
}
/**
* The Host's default workspace as a standalone node for the pinned bottom bar.
*
* The default workspace is not part of the grouping tree (it is excluded from
* `deriveGroups`, `deriveTopLevel` and the search results), yet it keeps the
* full workspace-row behaviour: expansion, session count, its sessions and its
* extra folders. This derives exactly that node, reusing the same visibility,
* folder partitioning and current-session marking as the tree.
*
* @param list - sessions list snapshot.
* @param workspaces - real workspaces in stable Host order.
* @param archivedSessionIds - registry-global archive set.
* @param view - local expansion arrays.
* @param statuses - unified UI status by Session.
* @param folders - per-workspace extra folders + root.
* @returns the default workspace node, or undefined when the Host has none.
*/
export function deriveDefaultWorkspace(
list: SessionListState,
workspaces: readonly WorkspaceView[],
archivedSessionIds: readonly SessionId[],
view: GroupsTreeView,
statuses: SessionStatuses = new Map(),
folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT,
): WorkspaceGroupNode | undefined {
const workspace = workspaces.find(w => isDefaultWorkspace(w))
if (workspace === undefined) return undefined
const archived = new Set(archivedSessionIds)
const expandedWorkspaces = new Set(view.expandedWorkspaces)
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 wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)
const partitioned = applyFolders(
workspace.workspaceId,
workspace.path,
sessions,
list,
entryFor(folders, workspace.workspaceId as string),
collapsedFolders,
)
return {
workspaceId: workspace.workspaceId,
path: workspace.path,
label: workspace.title,
createdAt: Date.parse(workspace.createdAt),
sessionCount: sessions.length,
expanded: wsExpanded,
containsCurrent: current !== undefined && workspace.sessionIds.includes(current),
sessions: wsExpanded ? partitioned.sessions : [],
...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }),
}
}
/** Recency comparator: newest first, id as the deterministic tiebreak. */
function byRecency(a: SessionSummary, b: SessionSummary): number {
if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt
@ -550,6 +609,12 @@ export interface SearchTree {
categories: CategoryNode[]
/** Top-level (ungrouped) workspaces holding matched sessions. */
topLevel: WorkspaceGroupNode[]
/**
* The Host default workspace's matched branch, when it has a hit. It is
* rendered in the pinned bottom bar instead of the results list, so a hit
* never makes the default workspace appear twice.
*/
defaultWorkspace?: WorkspaceGroupNode
}
/**
@ -593,6 +658,7 @@ export function deriveSearchGroups(
for (const key of effectiveCategories(config, manual).map(e => e.key)) byCategory.set(key, [])
const topLevel: WorkspaceGroupNode[] = []
let defaultWorkspace: WorkspaceGroupNode | undefined
for (const workspace of workspaces) {
// Only sessions that matched the query and are visible in this folder.
const nodes: SessionNode[] = []
@ -629,6 +695,10 @@ export function deriveSearchGroups(
sessions: partitioned.sessions,
...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }),
}
if (isDefaultWorkspace(workspace)) {
defaultWorkspace = node
continue
}
const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
if (key === undefined) {
topLevel.push(node)
@ -653,5 +723,9 @@ export function deriveSearchGroups(
...(appearance === undefined ? {} : { appearance }),
})
}
return { categories, topLevel }
return {
categories,
topLevel,
...(defaultWorkspace === undefined ? {} : { defaultWorkspace }),
}
}

View File

@ -0,0 +1,46 @@
/**
* Recognising the Host's own default workspace ("默认工作区").
*
* The workspace snapshot carries no `isDefault` flag, so the only Host-owned
* signal is the one the Host itself uses: the registry title. Its
* `workspaceDisplayTitle()` treats a title equal to `DEFAULT_WORKSPACE_DIRECTORY`
* as "the default workspace" and swaps in a localized label. That constant lives
* in the workspace-controller package, which this plugin must not import at
* runtime (it is a client bundle), so the string is mirrored here.
*
* Two Host signals are combined:
* - the registry title (primary: exactly what the Host substitutes for);
* - the Host's own directory layout (`<Documents>/deepseek-harness/default-workspace`),
* which still identifies the workspace after the user renames it.
* A user-created directory that merely happens to be called "default-workspace"
* somewhere else on disk is NOT treated as the default workspace, and no single
* directory name is used as the sole test.
*/
/** Directory name the Host uses for its default workspace (host mirror). */
export const DEFAULT_WORKSPACE_TITLE = 'default-workspace'
/** Parent directory the Host creates inside <Documents> for its state. */
const HOST_STATE_DIRECTORY = 'deepseek-harness'
/** The fields the identification needs from a workspace snapshot. */
export interface DefaultWorkspaceIdentity {
/** Registry title (`WorkspaceView.title`). */
title?: string | undefined
/** Absolute workspace directory (`WorkspaceView.path`). */
path?: string | undefined
}
/**
* Whether a workspace snapshot is the Host's default workspace.
* @param workspace - workspace snapshot (title is the primary signal, path the fallback).
*/
export function isDefaultWorkspace(workspace: DefaultWorkspaceIdentity): boolean {
if (workspace.title?.trim().toLowerCase() === DEFAULT_WORKSPACE_TITLE) return true
const path = (workspace.path ?? '').replace(/[/\\]+$/u, '')
if (path === '') return false
const segments = path.split(/[/\\]+/u)
const base = segments[segments.length - 1]?.toLowerCase()
return base === DEFAULT_WORKSPACE_TITLE
&& segments.some(segment => segment.toLowerCase() === HOST_STATE_DIRECTORY)
}

View File

@ -36,18 +36,30 @@ export const GROUP_COLORS: readonly GroupColor[] = [
]
/** Curated icon ids (rendered from @deepseek-ai/dsh-client-ui-primitives). */
export type GroupIconId =
| 'folder' | 'workspace' | 'code' | 'plugin' | 'skill' | 'data'
| 'database' | 'api' | 'plan' | 'goal' | 'light' | 'globe'
| 'archive' | 'branch' | 'users' | 'clock' | 'shield' | 'checklist'
| 'sparkle' | 'tree'
export const GROUP_ICON_IDS: readonly GroupIconId[] = [
export const GROUP_ICON_IDS = [
'folder', 'workspace', 'code', 'plugin', 'skill', 'data',
'database', 'api', 'plan', 'goal', 'light', 'globe',
'archive', 'branch', 'users', 'clock', 'shield', 'checklist',
'sparkle', 'tree',
]
'chat', 'search', 'settings', 'document', 'edit', 'think',
'agent', 'browse', 'context', 'link', 'share', 'user',
'send', 'attachment', 'download', 'play', 'design', 'moon',
'monitor', 'gauge', 'queue', 'notes', 'inspect', 'help',
'info', 'alarm', 'compare', 'done', 'pin', 'microphone',
// Materials & Lab family (appended: the first 50 ids keep their order because
// saved configs address icons by id, never by position).
// Lab operations
'test-tube', 'flask', 'pipette', 'dropper', 'stirrer', 'hotplate', 'centrifuge', 'balance',
// Material structures
'atom', 'molecule', 'lattice', 'layered', 'framework', 'thin-film', 'fiber', 'hydrogel',
// Characterization
'microscope', 'xrd', 'spectrum', 'tensile', 'electrode', 'iv-curve',
// Functional devices
'illumination', 'temperature', 'humidity', 'actuator', 'flex-sensor', 'battery',
] as const
/** Derived from the shared registry so host validation and UI cannot drift. */
export type GroupIconId = (typeof GROUP_ICON_IDS)[number]
/**
* Presentation metadata for one group. Every field optional.
@ -59,7 +71,7 @@ export const GROUP_ICON_IDS: readonly GroupIconId[] = [
export interface CategoryAppearance {
/** Palette id; the CSS palette lives in styles.css `[data-wg-color]`. */
color?: GroupColor | undefined
/** `GroupIconId` preset id, or a short glyph (1–4 code units, emoji/latin). */
/** `GroupIconId` preset id, or a short glyph (1–4 Unicode code points, emoji/latin). */
icon?: string | undefined
/** Pinned groups sort before unpinned ones (within the manual order). */
pinned?: boolean | undefined

76
tests/group-icons.test.ts Normal file
View File

@ -0,0 +1,76 @@
import { describe, expect, it } from 'vitest'
import { readFileSync } from 'node:fs'
import { GROUP_ICON_IDS } from '../src/core/types.ts'
import { GROUP_EMOJI_ICONS, GROUP_ICON_LABELS } from '../src/client/group-icon-labels.ts'
import { SCIENCE_ICON_ART, SCIENCE_ICON_IDS, SCIENCE_ICON_SECTIONS } from '../src/client/group-icons-science.tsx'
import { parseManualGroups } from '../src/host-manual.ts'
const legacy = ['folder', 'workspace', 'code', 'plugin', 'skill', 'data', 'database', 'api', 'plan', 'goal', 'light', 'globe', 'archive', 'branch', 'users', 'clock', 'shield', 'checklist', 'sparkle', 'tree']
const scienceIds: readonly string[] = SCIENCE_ICON_IDS
describe('group icon catalog', () => {
it('preserves every legacy id and provides the 50 native presets ahead of the research family', () => {
expect(GROUP_ICON_IDS.slice(0, legacy.length)).toEqual(legacy)
expect(GROUP_ICON_IDS).toHaveLength(50 + scienceIds.length)
expect(GROUP_ICON_IDS.slice(0, 50)).not.toContain('test-tube')
expect(GROUP_ICON_IDS.slice(50)).toEqual([...scienceIds])
expect(new Set(GROUP_ICON_IDS).size).toBe(GROUP_ICON_IDS.length)
expect(Object.keys(GROUP_ICON_LABELS).sort()).toEqual([...GROUP_ICON_IDS].sort())
for (const label of Object.values(GROUP_ICON_LABELS)) {
expect(label).toMatch(/[\u4e00-\u9fff]+.*\/.*[A-Za-z]+/u)
}
})
it('gives every research id a unique, fully-allocated, in-bounds artwork', () => {
expect(new Set(scienceIds).size).toBe(scienceIds.length)
const sectioned = SCIENCE_ICON_SECTIONS.flatMap(section => [...section.ids])
expect([...sectioned].sort()).toEqual([...scienceIds].sort())
expect(Object.keys(SCIENCE_ICON_ART).sort()).toEqual([...scienceIds].sort())
for (const id of scienceIds) {
const artwork = SCIENCE_ICON_ART[id as keyof typeof SCIENCE_ICON_ART]
expect(artwork.length, id).toBeGreaterThan(0)
for (const primitive of artwork) {
for (const [key, value] of Object.entries(primitive)) {
/* `rotate` is an angle, not a coordinate: skip it. */
if (key === 'rotate' || typeof value !== 'number') continue
/* Every primitive is authored in the 16x16 box the host icons use. */
expect(Math.abs(value), `${id}: ${key}`).toBeLessThanOrEqual(16)
}
}
}
})
it('maps every native preset to artwork actually exported by the installed host primitives', () => {
const rows = readFileSync(new URL('../src/client/rows.tsx', import.meta.url), 'utf8')
const declarations = readFileSync(new URL('../node_modules/@deepseek-ai/dsh-client-ui-primitives/lib/types/icons/index.d.ts', import.meta.url), 'utf8')
for (const id of GROUP_ICON_IDS.slice(0, 50)) {
const match = rows.match(new RegExp(`\\b${id}: <(Icon\\w+) />`))
expect(match, id).not.toBeNull()
expect(declarations).toContain(`export declare const ${match![1]}:`)
}
})
it('merges the self-drawn research artwork into the same preset map', () => {
const rows = readFileSync(new URL('../src/client/rows.tsx', import.meta.url), 'utf8')
expect(rows).toContain('scienceIconNodes()')
/* The research ids must not be claimed by the host-artwork table: the host
primitives export no lab/science glyph, so they are self-drawn. */
for (const id of scienceIds) {
expect(rows).not.toMatch(new RegExp(`\\b${id}: <Icon\\w+`))
}
})
it.each([...GROUP_ICON_IDS, ...GROUP_EMOJI_ICONS.map(entry => entry.icon), '研', 'AB', '🧑‍💻', 'future-icon'])('round-trips %s through unchanged host validation', (icon) => {
const parsed = parseManualGroups({ categories: ['Icons'], assignments: {}, appearance: { Icons: { icon, color: 'blue', pinned: true } } })
expect(parsed.appearance?.Icons).toEqual({ icon, color: 'blue', pinned: true })
})
it('gives each emoji a unique value and bilingual name', () => {
expect(new Set(GROUP_EMOJI_ICONS.map(entry => entry.icon)).size).toBe(GROUP_EMOJI_ICONS.length)
for (const { icon, label } of GROUP_EMOJI_ICONS) {
expect(Array.from(icon).length).toBeLessThanOrEqual(4)
expect(label).toMatch(/[\u4e00-\u9fff]+.*\/.*[A-Za-z]+/u)
}
})
})

View File

@ -0,0 +1,99 @@
// Static CSS contract checks; browser geometry requires visual verification.
// Vitest cannot start in this checkout (missing @vitest/utils, std-env), so the
// stylesheet's invariants are asserted here instead:
// node --input-type=module tools/verify-row-layout.mjs (NODE_PATH -> lightningcss)
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { transform } from 'lightningcss'
const source = readFileSync(new URL('../src/client/styles.css', import.meta.url), 'utf8')
transform({ filename: 'styles.css', code: Buffer.from(source) })
const rule = selector => {
const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const result = source.match(new RegExp(`${escaped}\\s*\\{([^}]*)\\}`))
assert.ok(result, `missing rule: ${selector}`)
return result[1].replace(/\s/g, '')
}
// A. Rows cannot overflow the rail: the actions slot stays at the row's right
// edge and every nested box is allowed to shrink below its content.
assert.ok(rule('.wgRoot').includes('min-width:0;'))
assert.ok(rule('.wgTreeBody').includes('overflow-x:hidden;'))
assert.ok(rule('.wgRows').includes('grid-template-columns:minmax(0,1fr);'))
assert.ok(rule('.wgTreeWrap,.wgList,.wgRows,.wgRowsInner,.wgTreeChildren').includes('min-width:0;'))
const rows = rule('.wgCategoryRow,.wgProjectRow,.wgFolderRow,.wgSessionRow')
assert.ok(rows.includes('width:100%;') && rows.includes('box-sizing:border-box;'))
assert.ok(rule('.wgSessionTitle').includes('text-overflow:ellipsis;'))
assert.ok(rule('.wgRowActions:last-child').includes('margin-left:auto;'))
// B. The member count and the hover buttons share one right-aligned trailing
// slot: same grid cell, same right edge, both keep their boxes — so the count is
// flush with the row's right edge and the swap never moves or reflows anything.
assert.ok(rule('.wgCategoryCount,\n.wgProjectCount').includes('flex:none;'), 'project count must share the group count style')
const trail = rule('.wgRowTrail')
assert.ok(trail.includes('margin-left:auto;'), 'the trailing slot is pinned to the right edge')
assert.ok(trail.includes('justify-items:end;') && trail.includes('display:grid;'), 'count and buttons must overlap right-aligned')
assert.ok(rule('.wgRowTrail > *').includes('grid-area:1/1;'), 'both states must occupy the same cell')
const swap = rule('.wgCategoryCount,.wgFolderCount,.wgProjectCount,.wgSessionTime')
assert.ok(swap.includes('transition:opacity'), 'count and time fade instead of popping')
const hide = source.match(/\.wgCategoryRow:hover \.wgCategoryCount,[\s\S]*?\{([^}]*)\}/)?.[1]?.replace(/\s/g, '') ?? ''
assert.ok(hide.includes('opacity:0;') && hide.includes('visibility:hidden;'), 'hover/focus must hide every count and the session time')
const swapSelectors = (source.match(/\.wgCategoryRow:hover \.wgCategoryCount,[\s\S]*?\{/)?.[0] ?? '').replace(/\s+/g, ' ')
for (const selector of ['.wgProjectRow:hover .wgProjectCount,', '.wgProjectRow:focus-within .wgProjectCount,', '.wgFolderRow:focus-within .wgFolderCount,']) {
assert.ok(swapSelectors.includes(selector), `count swap missing ${selector}`)
}
for (const selector of ['.wgSessionRow:hover .wgSessionTime,', '.wgSessionRow:focus-within .wgSessionTime {']) {
assert.ok(swapSelectors.includes(selector), `session time swap missing ${selector}`)
}
// C. The appearance dialog scrolls inside the host Modal's padding box, so the
// icon picker can grow without pushing the footer out of reach.
assert.ok(rule('.wgAppearanceBody').includes('gap:16px;'), 'field and pin button need real spacing')
assert.ok(rule('.wgAppearanceDialog').includes('max-height:100%;'))
const content = rule('.wgAppearanceContent')
assert.ok(content.includes('overflow-y:auto;') && content.includes('min-height:0;'))
const sticky = rule('.wgAppearanceContent > :first-child')
assert.ok(sticky.includes('position:sticky;') && sticky.includes('top:0;'), 'dialog header must stay reachable while scrolling')
const sections = rule('.wgIconSections')
assert.ok(sections.includes('max-height:') && sections.includes('overflow-y:auto;'), 'icon picker is bounded, footer stays visible')
assert.ok(!rule('.wgIconGrid').includes('max-height:'), 'the scroll box moved from the grid to the section list')
// D. The pinned default workspace is a sibling of the scrolling tree, so a long
// session list can never scroll it away.
const bar = rule('.wgDefaultWorkspaceBar')
assert.ok(bar.includes('border-top:'), 'the bar is separated from the tree')
assert.ok(bar.includes('flex:none;'), 'the bar must not be squeezed by the tree')
// E. The markup backs the CSS: every row hands its rest-state label (member
// count or session time) AND its buttons to the one trailing slot, so both right
// edges are the same box edge.
const rowsSource = readFileSync(new URL('../src/client/rows.tsx', import.meta.url), 'utf8')
const trailStarts = [...rowsSource.matchAll(/<span className="wgRowTrail">/g)].map(match => match.index ?? -1)
assert.equal(trailStarts.length, 4, 'category, workspace, folder and session rows each get one trailing slot')
const restStateClasses = ['wgCategoryCount', 'wgProjectCount', 'wgFolderCount', 'wgSessionTime']
for (const [index, start] of trailStarts.entries()) {
// Bound the slot to its own row component, so a neighbouring row's buttons can
// never satisfy the assertions below.
const nextRow = rowsSource.indexOf('\nexport function ', start)
const slot = rowsSource.slice(start, nextRow === -1 ? rowsSource.length : nextRow)
const restAt = slot.indexOf(`className="${restStateClasses[index]}"`)
const actionsAt = slot.indexOf('className="wgRowActions"')
assert.ok(restAt > 0, `trailing slot ${index + 1} lost ${restStateClasses[index]}`)
assert.ok(actionsAt > restAt, `trailing slot ${index + 1} must sit after ${restStateClasses[index]}`)
assert.equal(slot.match(/className="wgRowActions"/g)?.length, 1, `trailing slot ${index + 1} must hold exactly one action box`)
const ellipsisAt = slot.indexOf('<IconEllipsisOutlineRegular />')
assert.ok(ellipsisAt > restAt, `trailing slot ${index + 1} must end with the ⋯ button`)
const plusAt = slot.indexOf('<IconPlusOutlineRegular />')
const actionBox = slot.slice(actionsAt)
if (index === 3) {
assert.ok(!actionBox.includes('<IconPlusOutlineRegular'), 'session rows offer only ⋯ in the trailing slot')
} else {
assert.ok(plusAt > 0 && ellipsisAt > plusAt, `trailing slot ${index + 1} must order the actions + then ⋯`)
}
}
const allActionBoxes = [...rowsSource.matchAll(/className="wgRowActions"/g)].map(match => match.index ?? -1)
assert.equal(allActionBoxes.length, 4, 'exactly one action box per row kind, none duplicated')
const sessionRow = rowsSource.slice(rowsSource.indexOf('export function SessionRow'))
assert.ok(sessionRow.includes('className="wgRowTrail"'), 'session rows use the same trailing slot')
assert.ok(!/wg(Category|Project|Folder)Count/.test(sessionRow), 'session rows have no member count')
console.log('Row layout CSS contracts passed (not a browser geometry test).')